diff --git a/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs b/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs index 784a95aa7c..67bf327169 100644 --- a/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs +++ b/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs @@ -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) { @@ -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(); diff --git a/apps/presentation/dashboard/src/data/chat.ts b/apps/presentation/dashboard/src/data/chat.ts index ed9ebf8896..c0fdf5234c 100644 --- a/apps/presentation/dashboard/src/data/chat.ts +++ b/apps/presentation/dashboard/src/data/chat.ts @@ -972,6 +972,32 @@ export async function fetchChatSession(sessionId: string, signal?: AbortSignal) return requestJson(`/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(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(), diff --git a/apps/presentation/dashboard/src/features/personal-workspace/answer-report-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/answer-report-page.tsx index 5f38dc2034..167c0a129c 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/answer-report-page.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/answer-report-page.tsx @@ -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"; @@ -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"}; @@ -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, @@ -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"); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx index 43549a1332..2645c89c58 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx @@ -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(); @@ -288,7 +290,7 @@ export const ChannelTimeline = memo(function ChannelTimeline({ {item.message.role === "assistant" && !item.message.pending && item.message.text.length >= MIN_SEPARATE_ANSWER_LENGTH && item.message.sourceSessionId && item.message.sourceMessageId - ? {locale === "zh-CN" ? "单独阅读完整答复" : "Read full answer separately"} : null} {item.message.role !== "user" && (item.message.pending || item.message.sourceTurnId || item.message.activity?.length || item.message.steps?.length) ? : null} diff --git a/loopx/capabilities/manager_context/roundtrip.py b/loopx/capabilities/manager_context/roundtrip.py index 3ce56200f9..8359b41340 100644 --- a/loopx/capabilities/manager_context/roundtrip.py +++ b/loopx/capabilities/manager_context/roundtrip.py @@ -427,24 +427,46 @@ def observe_result(result_path, reply): ] +def _saved_answer_rows(messages, message_id, expected_turn_id): + matches = [row for row in messages if row.get("message_id") == message_id] + if len(matches) > 1: + raise ValueError("saved answer has conflicting message identities") + if not matches or matches[0].get("role") not in {"agent", "assistant"}: + return [], [] + answer = matches[0] + turn_id = answer.get("turn_id") + if expected_turn_id is not None and turn_id != expected_turn_id: + return [], [] + if not turn_id: + return [answer], [answer] + original = [row for row in messages if row.get("turn_id") == turn_id] + question = next((row for row in original if row.get("role") == "user"), None) + return ([question, answer] if question else [answer]), original + + def project_chat_session_snapshot(root, store, session_id, *, registry, - message_limit=None, message_cursor=None, turn_id=None, + message_limit=None, message_cursor=None, turn_id=None, report_message_id=None, resume_from=None, project_history_messages=None, include_turn_error=False): """Project return delivery state into one existing Chat snapshot.""" turn = None - if turn_id is not None: + if turn_id is not None and report_message_id is None: if message_limit is None: raise ValueError("a selected original Turn requires paged history") turn = store.load_turn(session_id, turn_id) if not turn or turn.get("session_id") != session_id or turn.get("turn_id") != turn_id: raise ValueError("original Turn is unavailable from this Session") - strict = message_limit is not None or resume_from is not None + strict = message_limit is not None or resume_from is not None or report_message_id is not None # Read the status first: terminal completion persists its answer before # publishing completed. An older message prefix must not appear final. snapshot = (store.session_snapshot(session_id, strict_messages=True) if strict else store.session_snapshot(session_id)) - if turn is not None: + report_context = None + if report_message_id is not None: + snapshot["messages"], report_context = _saved_answer_rows(snapshot["messages"], report_message_id, turn_id) + snapshot["report_message_id"] = report_message_id + snapshot["active_turn"] = None + elif turn is not None: status = turn["status"] snapshot["selected_turn"] = {"turn_id": turn_id, "status": status, "terminal": status in TERMINAL_TURN_STATES} # Failure records persist the reason with the status, before appending the message. @@ -464,7 +486,7 @@ def project_chat_session_snapshot(root, store, session_id, *, registry, from .chat_history import page_chat_messages page = (page_chat_messages(session_id, snapshot["messages"], limit=message_limit, cursor=message_cursor, turn_id=turn_id) if message_limit is not None else None) - context_messages = snapshot["messages"] + context_messages = snapshot["messages"] if report_context is None else report_context if page is not None: context_messages = context_messages[:page["message_page"]["total"]] snapshot["messages"] = page["messages"] @@ -475,8 +497,14 @@ def project_chat_session_snapshot(root, store, session_id, *, registry, # Use the frozen context to choose the carrier, projecting only this page. # A question and answer can straddle pages without duplicating a commitment # or re-reading every off-page Turn for each page. - snapshot["messages"] = project_collaboration(store, root, session_id, snapshot["messages"], + projected = project_collaboration(store, root, session_id, snapshot["messages"], registry=registry, context_messages=context_messages) + if report_message_id is not None: + # Collaboration may include the original receipt carrier. The saved + # answer only exposes its precise answer and the question it displays. + visible_ids = {row.get("message_id") for row in snapshot["messages"]} + projected = [row for row in projected if row.get("message_id") in visible_ids] + snapshot["messages"] = projected # Provider-owned history joins the selected page at the composition root. # Core capabilities never import an extension projection sink. if page is not None: @@ -487,9 +515,13 @@ def project_chat_session_snapshot(root, store, session_id, *, registry, def parse_chat_history_selection(query): """Validate one HTTP history selection before any recovery observation.""" - if (set(query) - {"message_limit", "message_cursor", "turn_id", "known_history", "task_goal_id", "task_todo_id"} + keys = set(query) + report = "report_message_id" in keys + if (keys - {"message_limit", "message_cursor", "turn_id", "known_history", + "task_goal_id", "task_todo_id", "report_message_id"} or any(len(values) != 1 or not values[0] for values in query.values()) - or ("message_limit" not in query and set(query) & {"message_cursor", "turn_id", "known_history"})): + or (report and keys - {"report_message_id", "turn_id"}) + or (not report and "message_limit" not in keys and keys & {"message_cursor", "turn_id", "known_history"})): raise ValueError("invalid history page arguments") limit = int(query["message_limit"][0]) if "message_limit" in query else None if limit is not None and not 1 <= limit <= 200: @@ -512,7 +544,8 @@ def parse_chat_history_selection(query): raise ValueError("invalid known history proof") parsed_basis = (basis, count, proof) return {"message_limit": limit, "message_cursor": query.get("message_cursor", [None])[0], - "turn_id": query.get("turn_id", [None])[0], "known_history": parsed_basis, "task_scope": task_scope} + "turn_id": query.get("turn_id", [None])[0], "known_history": parsed_basis, "task_scope": task_scope, + "report_message_id": query.get("report_message_id", [None])[0]} def prepare_chat_history_session(store, session_id, selection, *, recover_turn): @@ -520,7 +553,7 @@ def prepare_chat_history_session(store, session_id, selection, *, recover_turn): task_scope = selection["task_scope"] turn_id = selection["turn_id"] if task_scope is None: - if turn_id is None: + if turn_id is None and selection["report_message_id"] is None: recover_turn(session_id) return store.load_session(session_id) or {} @@ -553,6 +586,7 @@ def read_chat_history_selection(root, store, session_id, *, registry, selection, snapshot = project_chat_session_snapshot(root, store, session_id, registry=registry, message_limit=selection["message_limit"], message_cursor=selection["message_cursor"], turn_id=selection["turn_id"], project_history_messages=project_history_messages, + report_message_id=selection["report_message_id"], include_turn_error=selection["task_scope"] is not None) snapshot["messages"] = project_provider(snapshot["messages"]) if selection["message_limit"] == 200 and selection["turn_id"] is None: diff --git a/loopx/chat_server.py b/loopx/chat_server.py index ab9a4425ea..65337c4b63 100644 --- a/loopx/chat_server.py +++ b/loopx/chat_server.py @@ -936,7 +936,8 @@ def _session_snapshot(self, session_id: str) -> None: media = self.server.private_media_history contexts = getattr(self.server.runtime_controller, "project_contexts", None) bindings = getattr(contexts, "conversation_bindings", None) - markers = [] if selection["turn_id"] is not None else media.read(store, bindings, session) + scoped = selection["turn_id"] is not None or selection["report_message_id"] is not None + markers = [] if scoped else media.read(store, bindings, session) payload = read_chat_history_selection( self.server.runtime_controller.coordination_runtime_root, store, session_id, registry=self.server.registry_path, selection=selection, diff --git a/tests/test_manager_context_roundtrip.py b/tests/test_manager_context_roundtrip.py index 2a396f4c1c..60ab6e7d72 100644 --- a/tests/test_manager_context_roundtrip.py +++ b/tests/test_manager_context_roundtrip.py @@ -136,6 +136,34 @@ def test_frozen_private_reply_projects_original_text_without_mutating_model_inpu assert {str(p): p.read_bytes() for p in store.root.rglob("*") if p.is_file()} == before +def test_saved_answer_reads_only_its_original_question_and_exact_answer(frozen_private_reply, private_snapshot): + store, session, turn, _, _, _, source_text, _ = frozen_private_reply + sid, tid = session["session_id"], turn["turn_id"] + answer = store.append_message(sid, role="agent", text="The saved answer", turn_id=tid) + store.append_message(sid, role="agent", text="Later answer from the same Turn", turn_id=tid) + no_turn = store.append_message(sid, role="agent", text="An older saved answer without a Turn") + other_session = store.create_session(goal_id="notes", agent_id="codex", adapter_kind="codex_app_server", + upstream_thread_id="another-conversation") + foreign = store.append_message(other_session["session_id"], role="agent", text="An answer from another Session") + journal = store.sessions_root / sid / "messages.jsonl" + before = journal.read_bytes() + + response = private_snapshot(report_message_id=answer["message_id"]) + assert response["session"]["session_id"] == sid + assert response["report_message_id"] == answer["message_id"] + assert response["active_turn"] is None + question, saved = response["messages"] + assert question["reply_context"]["source_text"] == source_text + assert saved == answer + assert private_snapshot(report_message_id=answer["message_id"], turn_id=tid) == response + assert private_snapshot(report_message_id=answer["message_id"], turn_id="unrelated-turn")["messages"] == [] + assert private_snapshot(report_message_id=no_turn["message_id"])["messages"] == [no_turn] + for unavailable in (foreign["message_id"], question["message_id"]): + assert private_snapshot(report_message_id=unavailable)["messages"] == [] + private_snapshot(report_message_id=answer["message_id"], message_limit=200, expected_status=400) + assert journal.read_bytes() == before + + def test_history_pages_reuse_unchanged_journal_but_reread_provider_receipts( frozen_private_reply, private_snapshot, monkeypatch): store, session, turn, request, *_ = frozen_private_reply