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
77 changes: 77 additions & 0 deletions docs/reference/remote-authority-task-service-v0.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,83 @@ Revocation prevents subsequent admissions. A request already admitted under a
policy snapshot may finish and retains that snapshot's revision in its receipt;
revocation does not claim to undo an in-flight commit.

### Scoped Todo reads

For a read-only listener with resource authorization, set `schema_version` to
`loopx_remote_authority_scoped_read_policy_v1` in the existing service policy.
Each scope requires `todo_read_acl`, an array of entries with `goal_ref`,
`todo_id`, `principal_id` and `actor_id`. Each credential grant also requires
`goal_ref` with the exact `goal_id` and `goal_instance_id`. Grant `read` or
`snapshot` for the actions the caller needs. The operator must approve each
Todo and audience for that lifetime. Grant and ACL entries must agree with the
service scope, authenticated principal and actor. An empty ACL grants no access.

For current Todo or snapshot reads, each entry also needs
`todo_origin_operation_id`: the canonical operation id of that Todo's successful
creation under this exact lifetime, or the trusted source owner's successful
first `bind_existing` transaction that adopted the existing Todo. The service
verifies that original receipt and projection through the existing PostgreSQL
checkpoint owner, bounded by the admitted current head. An ACL is permission,
not proof of ownership: a claim, update, successor activation, no-op rebind,
missing receipt or predecessor's receipt cannot move retained work into a new
lifetime. Entries without a valid origin are excluded; a direct/targeted read
without proof, or a snapshot with no proven resources, is rejected. Shared
first-bind proofs are read once per request; no authorization is cached between
requests. The origin operation id stays in the private policy and is not
returned to callers. Existing bound work without such evidence stays unavailable
until the source owner supplies valid historical proof; do not rebind or rewrite
its history to manufacture one.

Launch the service with the scoped policy and use the current TLS client with
the existing v0 request JSON. The server supplies the exact Goal reference
from its private policy and verifies it against the active lifecycle on the
same PostgreSQL head used to compose the response. Unbound, retiring and
mismatched lifetimes deny access. A direct read or targeted snapshot outside
the ACL returns rejection without revealing whether the Todo exists. The
scoped listener denies write commands.

Scoped successes use `loopx_remote_authority_scoped_read_response_v1`. They
return the exact Goal reference, authorized Todo status and assignment, and
matching lease metadata. Snapshots also include role and priority. Free-form
notes and lease keys are withheld. Scoped clients reject unknown nested Todo
and lease fields even when a snapshot digest matches; the trusted v0 decoder
keeps its existing compatibility behavior. The snapshot receipt digest covers only the
authorized projection and its scope. The global provider revision is withheld,
so changing a hidden Todo leaves the returned view and digest intact. Clients
that lack support for this response version report an unavailable read.

Revoke access by replacing the policy with a new version of the same schema
that removes the matching ACL entry or grant. The service pins the policy
schema at startup and fails closed on a schema change during reload. Stop the
listener to disable it. Keep the v0 policy for an explicitly configured
legacy listener with trusted access to the whole Goal.

#### Historical receipt proof

To authorize recovery of a specific remote operation, add its canonical
`operation_id` to `receipt_operation_ids` on the Todo's read ACL entry. The
credential also needs `read` in its grant. The ID comes from the original
operation or its trusted service receipt. An omitted or empty list grants
no receipt access. Use `--recover` with the complete original command.

The service checks the active Goal and allowed Todo before it opens the
receipt. The original request digest, principal and actor must match the
receipt. The original committed projection must prove the same Goal lifetime.
The service reuses the provider's bounded checkpoint and delta reader for that
exact cursor. Missing, unbound or cross-lifetime receipts are rejected, even
with a matching operation ID. The scoped service role needs read access to the
existing tenant-scoped `authority_checkpoints` table as part of this journal read.

A scoped success returns the exact Goal, Todo and operation, `historical_only`
and the original receipt digest. It withholds the original result payload,
lease key, cursor and provider revision. The original receipt confirms
recorded history. Execution authority still comes from a current lease and
the existing mutation owner. Remove the operation ID to revoke recovery while
leaving the authorized Todo read available.

Artifact versions, delegated sources and cross-person writes require separate
qualification before they can be exposed.

## Commands and recovery

POST JSON to `/v0/tasks/execute` with a `Bearer` credential. Every command includes
Expand Down
4 changes: 2 additions & 2 deletions examples/coordination/remote-authority-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ const port = Number(values.port);
if (!values.policy || !values.cert || !values.key || !Number.isSafeInteger(port) || port < 0 || port > 65535 ||
!process.env.LOOPX_AUTHORITY_DATABASE_URL) throw new Error("Provide policy, TLS certificate/key and service-owned database configuration");
// Validate before listening; updates are read again for each admission.
await readRemoteAuthorityPolicy(values.policy);
const policy = await readRemoteAuthorityPolicy(values.policy);
const pool = new Pool({connectionString: process.env.LOOPX_AUTHORITY_DATABASE_URL,
max: 8, connectionTimeoutMillis: 2000, query_timeout: 6000, idleTimeoutMillis: 10000,
statement_timeout: 5000, lock_timeout: 2000, idle_in_transaction_session_timeout: 10000});
pool.on("error", () => process.stderr.write("Authority database connection unavailable\n"));
const service = new RemoteAuthorityService({admit: fileRemoteAuthorityAdmission(values.policy),
const service = new RemoteAuthorityService({admit: fileRemoteAuthorityAdmission(values.policy, String(policy.schema_version)),
database: {connect: async () => {
const connection = await pool.connect();
return {query: (sql, args) => connection.query(sql, args ? [...args] : undefined),
Expand Down
Loading
Loading