Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,21 @@ async function checkReturnedFiles(ready, page, errors, writes) {
}
}
await page.screenshot({path: resolve(output, `${baseline ? "before" : "after"}-files-desktop.png`), animations: "disabled"});
const historyPath = `/api/chat/sessions/${ready.sessionId}`;
const readerRequest = page.context().waitForEvent("request", {predicate: request =>
new URL(request.url()).pathname === historyPath
&& new URL(request.frame().url()).searchParams.get("reportMessageId") === ready.fileMessageId});
const opened = page.context().waitForEvent("page");
await timeline.getByRole("link", {name: "单独阅读完整答复"}).click();
const report = await opened;
report.on("pageerror", error => errors.push(error.message));
await report.getByRole("heading", {name: "结果已核验 / Verified result", exact: true}).waitFor();
const readerQuery = new URL((await readerRequest).url()).searchParams;
if (!baseline) {
assert.equal(readerQuery.get("turn_id"), answer.turn_id, "The saved answer checks its original Turn");
assert.equal(readerQuery.get("report_message_id"), answer.message_id, "The reader requests only the chosen answer");
assert.equal(readerQuery.has("message_limit"), false);
}
assert.equal(await report.locator("a[download]").count(), baseline ? 0 : ready.files.length);
await report.screenshot({path: resolve(output, `${baseline ? "before" : "after"}-files-reader.png`), animations: "disabled"});
if (!baseline) {
Expand All @@ -109,6 +119,91 @@ async function checkReturnedFiles(ready, page, errors, writes) {
const url = ready.origin + answer.attachments[0].data_url;
assert.equal((await page.request.get(url.replace(ready.sessionId, "unrelated-session"))).status(), 404);
assert.equal((await page.request.get(url, {headers: {Origin: "https://unrelated.example"}})).status(), 403);

const legacy = new URL(report.url());
legacy.searchParams.delete("reportTurnId");
const savedAnswerRequest = url => url.pathname === historyPath && url.searchParams.get("report_message_id") === ready.fileMessageId;
const legacyRead = report.waitForResponse(response => new URL(response.url()).pathname === historyPath);
await report.goto(legacy.toString());
await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor();
const legacyResponse = await legacyRead;
assert.ok(savedAnswerRequest(new URL(legacyResponse.url())), "An existing link selects its saved message without loading the transcript");
const legacySnapshot = await legacyResponse.json();
assert.deepEqual(legacySnapshot.messages.filter(row => row.role !== "user").map(row => row.message_id), [ready.fileMessageId]);
const legacyAnswer = legacySnapshot.messages.find(row => row.message_id === ready.fileMessageId);
assert.equal(legacyAnswer.text, answer.text);
assert.deepEqual(legacyAnswer.attachments, answer.attachments);

await report.route(savedAnswerRequest, route => route.fulfill({status: 400, json: {ok: false, error: "invalid history page arguments"}}));
const fallbackRead = report.waitForRequest(request => {
const url = new URL(request.url());
return url.pathname === historyPath && url.search === "";
});
await report.reload();
await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor();
await fallbackRead;

const fallbackTurnRead = report.waitForRequest(request => {
const url = new URL(request.url());
return url.pathname === historyPath && url.searchParams.get("turn_id") === answer.turn_id && url.searchParams.has("message_limit");
});
const withTurn = new URL(legacy);
withTurn.searchParams.set("reportTurnId", answer.turn_id);
await report.goto(withTurn.toString());
await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor();
await fallbackTurnRead;
await report.unroute(savedAnswerRequest);
await report.goto(legacy.toString());
await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor();

// Earlier history readers accept unknown query arguments and return their
// complete v1 snapshot. Both existing and Turn-pinned links still open it.
await report.route(savedAnswerRequest, route => route.fulfill({json: snapshot}));
for (const address of [legacy, withTurn]) {
await report.goto(address.toString());
await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor();
assert.equal(await report.locator("a[download]").count(), ready.files.length);
}
const wrongTurn = new URL(withTurn);
wrongTurn.searchParams.set("reportTurnId", "unrelated-turn");
await report.goto(wrongTurn.toString());
await report.getByText("This answer was not found. It may have been removed, or the link may be incorrect.").waitFor();
assert.equal(await report.locator("a[download]").count(), 0);
await report.unroute(savedAnswerRequest);

for (const invalid of [
{...snapshot, session: {...snapshot.session, session_id: "another-session"}},
{...snapshot, report_message_id: "another-message"},
{...snapshot, message_page: {next_cursor: "another-page"}},
]) {
await report.route(savedAnswerRequest, route => route.fulfill({json: invalid}));
await report.goto(legacy.toString());
await report.getByText("Could not load this answer.").waitFor();
assert.equal(await report.locator("a[download]").count(), 0);
await report.unroute(savedAnswerRequest);
}

const refusedReads = [];
const observeRefusal = request => {
if (new URL(request.url()).pathname === historyPath) refusedReads.push(new URL(request.url()));
};
report.on("request", observeRefusal);
for (const [status, error] of [[403, "Source access was revoked"], [400, "invalid Chat journal record"]]) {
refusedReads.length = 0;
await report.route(savedAnswerRequest, route => route.fulfill({status, json: {ok: false, error}}));
await report.reload();
await report.getByText("Could not load this answer.").waitFor();
assert.equal(await report.locator("a[download]").count(), 0);
assert.equal(refusedReads.length, 1);
assert.ok(savedAnswerRequest(refusedReads[0]), "A refused or invalid source must never trigger a wider history read");
await report.unroute(savedAnswerRequest);
}
report.off("request", observeRefusal);

legacy.searchParams.set("reportTurnId", "unrelated-turn");
await report.goto(legacy.toString());
await report.getByText(/This answer was not found|Could not load this answer/).waitFor();
assert.equal(await report.locator("a[download]").count(), 0);
}
child.stdin.write("inspect\n");
const inspection = await next();
Expand Down
26 changes: 26 additions & 0 deletions apps/presentation/dashboard/src/data/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -972,6 +972,32 @@ export async function fetchChatSession(sessionId: string, signal?: AbortSignal)
return requestJson<ChatSessionSnapshot>(`/api/chat/sessions/${encodeURIComponent(sessionId)}`, { signal });
}

export async function fetchSavedChatAnswer(sessionId: string, messageId: string, signal: AbortSignal, turnId?: string) {
const query = new URLSearchParams({report_message_id: messageId});
if (turnId !== undefined) query.set("turn_id", turnId);
const path = `/api/chat/sessions/${encodeURIComponent(sessionId)}?${query}`;
try {
const snapshot = await requestJson<ChatSessionSnapshot & {report_message_id?: string}>(path, {signal});
// A legacy service can ignore the selector and return its complete v1
// snapshot. A conflicting marker or a partial history remains invalid.
if (Object.hasOwn(snapshot, "report_message_id")) {
if (snapshot.report_message_id !== messageId) throw new Error("The saved answer selection changed during read.");
} else if ("message_page" in snapshot || "history_resume" in snapshot) {
throw new Error("The saved answer history is incomplete.");
}
return snapshot;
} catch (error) {
// Older Chat builds reject unknown history selectors before reading the
// Session. Only that response enables the earlier history read paths.
if (!(error instanceof ChatApiError) || error.payload.http_status !== 400
|| error.message !== "invalid history page arguments") throw error;
signal.throwIfAborted();
return turnId === undefined
? fetchChatSession(sessionId, signal)
: fetchChatSessionHistory(sessionId, signal, turnId);
}
}

export const chatQueueInputRequestSchema = z.discriminatedUnion("action", [
z.object({action: z.literal("edit"), operation_id: z.string().min(1).max(160),
expected_revision: z.number().int().nonnegative(), message: z.string().min(1).max(24000)}).strict(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {useEffect, useMemo, useRef, useState} from "react";

import {fetchChatSession, type ChatSessionSnapshot, type ChatVisibleMessage} from "../../data/chat";
import {fetchSavedChatAnswer, type ChatSessionSnapshot, type ChatVisibleMessage} from "../../data/chat";
import {visibleAgentMessage} from "./answer-text";
import {readWorkspaceLocale} from "./i18n";
import {resolveConversationScope} from "../../../../../../loopx/control_plane/collaboration/conversation_scope";
Expand All @@ -24,7 +24,8 @@ export function AnswerReportPage({sessionId, messageId, statusUrl}: {
messageId: string;
statusUrl: string;
}) {
const scope = JSON.stringify([statusUrl || "/status.json", sessionId, messageId]);
const turnId = new URLSearchParams(window.location.search).get("reportTurnId");
const scope = JSON.stringify([statusUrl || "/status.json", sessionId, messageId, turnId]);
const [loaded, setLoaded] = useState<{scope: string; value: ReportState} | null>(null);
// A late read from the preceding source never appears in the new reader.
const state: ReportState = loaded?.scope === scope ? loaded.value : {kind: "loading"};
Expand All @@ -44,16 +45,18 @@ export function AnswerReportPage({sessionId, messageId, statusUrl}: {
setLoaded({scope, value: {kind: "loading"}});
setCopied(false);
setCopyFailed(false);
void fetchChatSession(sessionId, controller.signal).then((snapshot) => {
const read = fetchSavedChatAnswer(sessionId, messageId, controller.signal, turnId ?? undefined);
void read.then((snapshot) => {
if (!live) return;
if (snapshot.ok !== true || snapshot.schema_version !== "loopx_chat_store_v1"
|| snapshot.session.session_id !== sessionId) throw new Error("The saved Session changed during read.");
const message = snapshot.messages.find((item) => item.message_id === messageId
&& ["agent", "assistant"].includes(item.role));
&& ["agent", "assistant"].includes(item.role)
&& (turnId === null || item.turn_id === turnId));
setLoaded({scope, value: message ? {kind: "ready", snapshot, message} : {kind: "missing", snapshot}});
}).catch(() => { if (live) setLoaded({scope, value: {kind: "error"}}); });
return () => {live = false; controller.abort(); copyAttempt.current += 1; document.title = previousTitle;};
}, [scope, sessionId, messageId, zh, readRevision]);
}, [scope, sessionId, messageId, turnId, zh, readRevision]);

const navigation = answerReportNavigation(
(state.kind === "ready" || state.kind === "missing") ? state.snapshot.session : null, window.location.href, statusUrl, zh,
Expand Down Expand Up @@ -180,6 +183,7 @@ export function answerReportNavigation(
const managed = scope.kind === "owner_goal" && session?.managed_agent_id;
url.searchParams.delete("reportSessionId");
url.searchParams.delete("reportMessageId");
url.searchParams.delete("reportTurnId");
url.searchParams.delete("todo");
url.searchParams.delete("messageSession");
url.searchParams.delete("message");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ import { conversationOrder } from "./conversation-order";
import { ConversationFind, conversationMessageKey } from "./conversation-find";
import type { WorkspaceActionPreview, WorkspaceDrawerSelection, WorkspaceGoal, WorkspaceTimelineItem } from "./personal-workspace-model";

function answerLink(sessionId: string, messageId: string) {
function answerLink(sessionId: string, messageId: string, turnId?: string) {
const url = new URL(window.location.href);
url.searchParams.set("reportSessionId", sessionId);
url.searchParams.set("reportMessageId", messageId);
if (turnId) url.searchParams.set("reportTurnId", turnId);
else url.searchParams.delete("reportTurnId");
url.searchParams.set("view", "conversation");
url.hash = "";
return url.toString();
Expand Down Expand Up @@ -288,7 +290,7 @@ export const ChannelTimeline = memo(function ChannelTimeline({
<ConversationReplyContext context={item.message.replyContext} zh={locale === "zh-CN"}/>
{item.message.role === "assistant" && !item.message.pending && item.message.text.length >= MIN_SEPARATE_ANSWER_LENGTH
&& item.message.sourceSessionId && item.message.sourceMessageId
? <a className="personal-answer-link" href={answerLink(item.message.sourceSessionId, item.message.sourceMessageId)}
? <a className="personal-answer-link" href={answerLink(item.message.sourceSessionId, item.message.sourceMessageId, item.message.sourceTurnId)}
target="_blank" rel="noopener noreferrer">{locale === "zh-CN" ? "单独阅读完整答复" : "Read full answer separately"}</a>
: null}
{item.message.role !== "user" && (item.message.pending || item.message.sourceTurnId || item.message.activity?.length || item.message.steps?.length) ? <MessageActivity message={item.message} onCancelPreparation={onCancelPreparation} onInterruptTurn={onInterruptTurn} onAdjustTurn={onAdjustTurn}/> : null}
Expand Down
Loading
Loading