diff --git a/.changeset/untrusted-file-marks-ui.md b/.changeset/untrusted-file-marks-ui.md new file mode 100644 index 0000000000..3b9b9efc9c --- /dev/null +++ b/.changeset/untrusted-file-marks-ui.md @@ -0,0 +1,4 @@ +--- +"@schlessera/brain-ui-react": minor +--- +Files can mark a file untrusted (#2673). The viewer toolbar gains `Mark untrusted` between Copy path and Share. The owner sees a pressed `Untrusted: clear mark` control, and every reader sees a purple `untrusted` cue on the file and its tree row. A `Marked untrusted` list replaces the disabled `Untrusted only` filter: the owner's list shows retained marks on moved or deleted files, and readers see only present files they can open, with no marker identity. Every change waits for the host's reply. Races, refusals and uncertain replies use the approved copy, and focus follows the approved table. diff --git a/.changeset/untrusted-file-marks.md b/.changeset/untrusted-file-marks.md new file mode 100644 index 0000000000..9f5f4a07c3 --- /dev/null +++ b/.changeset/untrusted-file-marks.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-sdk": patch +--- +Let a user mark a brain file untrusted (#2673). Any principal that can read a file may mark it, and only the owner may clear a mark. A chat that then opens the file with its file tools records `taint` with `source: "user_marked"` and runs under the tainted session's outward and egress rules. Marks live in the UI database, survive a restart and `brain index --force`, and stay with their old path when a file moves, where only the owner sees them as missing. The capabilities note now names marked files among the untrusted sources. diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index 15557b7d6b..132ed01db2 100644 --- a/docs/decisions/async-collaboration.md +++ b/docs/decisions/async-collaboration.md @@ -241,7 +241,7 @@ suppressed-per-model Action; unknown usage cannot become a guessed zero. Subscription billing moves the turn counter even when spend is zero. The activity sum exposes unpriced runs (`sumEffectiveCost`, `packages/ui-server/src/activity/store.ts:179-194`) and settles only after execution -(`store.rollupRun(runId);`, `packages/ui-server/src/activity/recorder.ts:746`). +(`store.rollupRun(runId);`, `packages/ui-server/src/activity/recorder.ts:756`). Retrospective totals alone cannot enforce admission. The maintainer's [2026-10-01 ruling on #678](https://github.com/schlessera/brain-kit/issues/678#issuecomment-5926691626) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 80076ee763..e24216db42 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -2092,7 +2092,7 @@ limits from the same policy inputs and states independent hard limits. **What exists.** The audit trail is the Activity span record: tool name, the full input up to its cap, output and approval decisions -(`"tool_input"`, `packages/ui-server/src/activity/recorder.ts:334`). +(`"tool_input"`, `packages/ui-server/src/activity/recorder.ts:344`). **What changes:** @@ -3792,7 +3792,7 @@ document reader whose normalized path is under `.brain-ui/inbox/` or outside the brain and the strict area root counts any such segment); a fetching or unclassified Bash call; and any MCP tool whose server is not brain-kit's own `brain` or `brain-ui` -(`inputTaintSource`, `packages/ui-server/src/activity/ingestion-taint.ts:51-61`). +(`inputTaintSource`, `packages/ui-server/src/activity/ingestion-taint.ts:82-92`). The fixed list of external-content MCP sources is therefore "every other MCP server", following the rule above that erring towards taint costs only tighter rules (maintainer ruling, 2026-10-22). The first source is the session's one @@ -3828,6 +3828,52 @@ widens: deny and `allowlist` mode still apply first (`prepareTurnEgress`, native storage have no proxy, so the Bash classifier remains their shell rule and nothing narrows their egress. +**Files the user marks untrusted — 2026-11-02 +([#2673](https://github.com/schlessera/brain-kit/issues/2673)).** A user can +mark a brain file untrusted from Files, and the recorder above then treats an +admitted file-tool read of it as untrusted input: a `Read`, `Edit`, `Grep`, +`Glob`, pi `read_file`, `edit_file` or `grep`, or brain-kit's own document +reader, whose normalized brain-relative path is marked, or a search whose +output names it, records `taint` with `source: "user_marked"` as the session's +first source (`fileSource`, +`packages/ui-server/src/activity/ingestion-taint.ts:74-79`). An untrusted area +still names its own source first, and an absolute path outside the brain's +host path is not matched against marks. A mark is looked up when the call +completes; a lookup that fails counts as marked +(`const marked: MarkedLookup`, `packages/ui-server/src/activity/recorder.ts:236-242`). +Shell reads are covered only by the Bash rules above, reads are never +blocked, and a session that read the file before it was marked is not +tainted retroactively. + +The marks are host records in the UI database, never `brain.db` or +frontmatter, so they survive a restart and `brain index --force` +(`untrustedMarkOperations`, `packages/ui-server/src/files/untrusted-marks.ts:51-63`). +The maintainer settled five rules on 2026-10-23, and the host enforces each of +them on direct requests (`mountUntrustedMarks`, +`packages/ui-server/src/routes/files.ts:317-383`): + +- **Rename and move (B).** A mark is keyed by its brain-relative path. A file + that moves or disappears keeps its old-path record, which is listed as + missing so the owner can recover by marking the new path. Nothing follows + the rename, so the new path stays unmarked until it is marked, and the + old-path mark applies again if a file returns to that path. +- **Authority (B).** Any authenticated principal that can already read the + file may mark it; marking grants no further access. Only the owner may clear + a mark, including a retained missing one. The owner is the human owner the + storage and history routes already admit, an `owner` or `ambient` principal + (`isHumanOwner`, `packages/ui-server/src/routes/files.ts:145-147`); no + role is added. Clearing stops new sessions being tainted by that file and + never removes a session's recorded taint. +- **Visible scope (A).** Files views only: a toolbar control, viewer and tree + cues and a `Marked untrusted` list of user marks. Chat links and attachment + rows carry no cue. +- **Missing records (A).** Only the owner may list or inspect a retained + record whose file is gone. Every other principal sees only marks on files it + can currently read, even a mark it made itself; the host leaves the rest out + of rows and counts. +- **Marker identity (A).** The owner may see the marking principal's label. + Other principals' responses carry the marking date and no identity field. + **The runtime's own traffic — 2026-11-02 ([#3244](https://github.com/schlessera/brain-kit/issues/3244)).** The Claude runtime's own calls to its vendor were worker connections too. Its first-party diff --git a/docs/decisions/module-renderers.md b/docs/decisions/module-renderers.md index 146ed5cb41..f41a469484 100644 --- a/docs/decisions/module-renderers.md +++ b/docs/decisions/module-renderers.md @@ -102,7 +102,7 @@ Rejected: ``.** This was the first proposal. It cannot print white from the browser, it cannot theme on WebKit, and it cannot inherit the app's fonts: the raw-file CSP is `default-src 'none'` (`img-src 'self' data:`, - `packages/ui-server/src/routes/files.ts:160`) and an image may not fetch + `packages/ui-server/src/routes/files.ts:206`) and an image may not fetch fonts. It also leaves the figure an opaque, undiffable file beside markdown that is supposed to be the source of truth. - **Phase the work, files first and renderers later.** Rejected by the diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index 58fc171748..0cc59b0be6 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -204,7 +204,7 @@ credentials, not people. (`upsertRollup`, `activity/sql.ts:19-24`) — the rollup is what survives span pruning, so cost-by-actor dies at prune time without it. The precedent is profile/billing: a root-span attr that the rollup reads (`spanId: rootSpanId`, -`activity/recorder.ts:243-258`). Nullable for cron (`origin: "cron"`, +`activity/recorder.ts:253-268`). Nullable for cron (`origin: "cron"`, `activity/span-sink.ts:102`, `cron/run-job.ts:113`) and for pre-migration rows; nothing is backfilled. diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index c96791bcc1..aff78e7c84 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -490,7 +490,7 @@ An approval given by voice must be as reviewable afterwards as one given by tapping a card. Most of that already exists: every decision is written as an append-only `approval_decision` event carrying the principal, the decision and the request kind, and it patches the span -(`onApprovalDecision`, `packages/ui-server/src/activity/recorder.ts:674-689`), +(`onApprovalDecision`, `packages/ui-server/src/activity/recorder.ts:684-699`), fed from the bridge's `recorded()` wrapper (`const recorded`, `packages/ui-server/src/ws/bridge.ts:414-429`). diff --git a/docs/http-api.md b/docs/http-api.md index 2a5decfa32..9eff880da9 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, session-recovery interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant and retained-journal/user-revert routes mounted by `createApp`: 159 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, session-recovery interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant and retained-journal/user-revert and untrusted-mark routes mounted by `createApp`: 163 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -92,6 +92,10 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/files/resolve` | I | Resolve ancestor navigation and existence | React file browser; view/navigation helpers are paired UI transport. | | GET | `/api/files/tree` | I | List browsable directory entries | React file browser; view/navigation helpers are paired UI transport. | | GET | `/api/files/wikilinks` | I | Read or refresh cached slug-to-path map | React file browser; view/navigation helpers are paired UI transport. | +| GET | `/api/files/untrusted` | I | Read one path's untrusted mark as this principal may see it | React Files toolbar (#2673); paired UI transport. Its authority and disclosure rules are specified below. | +| PUT | `/api/files/untrusted` | I | Mark a readable file untrusted | React Files toolbar (#2673); paired UI transport. Its authority and disclosure rules are specified below. | +| DELETE | `/api/files/untrusted` | I | Clear a present or retained mark (owner only) | React Files toolbar and `Marked untrusted` list (#2673); paired UI transport. Its authority rules are specified below. | +| GET | `/api/files/untrusted/list` | I | List the marks this principal may see | React `Marked untrusted` list (#2673); paired UI transport. Its disclosure rules are specified below. | | GET | `/api/geo/coastline` | S | Read attributed map geometry for a bounding box | Independent map clients; preserve show_block map HTTP promise and graceful geometry degradation. | | GET | `/api/governance/roadblocks` | I | Retained roadblock rankings for the paired activity bridge | #1672; authenticated and local-only. The additive `query_activity` scope is the supported agent contract. | | GET | `/api/governance/events` | S | Read the governance events kept with session history | Independent diagnostics and the roadblock report; additive #1651 ([contract](integration-contract/http.md#governance-events-additive-1651)). Versioned per kind; never renders to the user. | @@ -192,7 +196,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 159 declared endpoints are mounted regardless of backend, renderer or +All 163 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. @@ -1073,6 +1077,35 @@ asserts the isolation and both accepted behaviours. In a split topology, where the client is served from another origin, `frame-ancestors 'self'` refuses the preview frame; the new-tab link is not subject to framing rules. +## Untrusted file marks (internal, #2673) + +The four `/api/files/untrusted` operations are protected, internal UI +transport: their payloads carry no independent-client guarantee, but their +authority and disclosure rules are security properties and are pinned by +`packages/ui-server/tests/untrusted-marks.test.ts`. + +- A mark is a host record in the UI database keyed by the normalized + brain-relative path, never a `brain.db` row or frontmatter key, so it + survives a restart and `brain index --force`. A moved or deleted file keeps + its old-path record; nothing follows a rename. +- `PUT` with JSON `{ path }` needs the read access `GET /api/files/content` + already grants and a regular file at the path: a missing path or directory + is 404 `not_found`, invalid path syntax 400 `invalid_path`. It answers + `{ status: "marked" | "already_marked", mark }`. Marking grants nothing else. +- `DELETE ?path=` is the human owner's alone (an `owner` or `ambient` + principal, the storage routes' rule); any other principal gets 403 + `owner_required`. It clears present and retained missing records and answers + `{ status: "cleared" | "already_cleared" }`. It never removes a session's + recorded taint. +- `GET ?path=` answers `{ path, marked: false, canClear }` or + `{ path, marked: true, markedAt, missing, markedBy?, canClear }`. A reader + asking about a path with no readable file gets 404 `not_found`, whether or + not a record is retained there. +- `GET /list` answers `{ marks, canClear }`, missing records first and then + newest first. The owner sees every record; any other principal sees only + records whose file it can currently read. Only the owner's rows and details + carry `markedBy: { label, you }`; other principals' responses omit the field. + ## Saved-audio transcription The protected `GET /api/voice/capabilities` returns `VoiceCapabilitiesResponse` diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index a8d7dd34cd..5d452e3664 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -39,6 +39,17 @@ hash directly. Missing/expired raw details never grant a download bypass. links use the embedding root's configured API base. Those read helpers do not execute mutations. + + +### Untrusted file marks (additive, #2673) + +Four internal `/api/files/untrusted` operations mark a readable brain file +untrusted, read one path's mark, list the marks a principal may see and let the +owner clear one. They are paired UI transport, specified with their authority +and disclosure rules in [the HTTP inventory](../http-api.md#untrusted-file-marks-internal-2673). +The `taint` governance event's shape is unchanged: its reserved +`source: "user_marked"` value is now produced. + ### Brain-wide configuration coverage (additive, #3257) diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index b546783c15..decf177cf9 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -253,7 +253,7 @@ Stated before the requirements because five of them derive from it. `persistSession: false`; pi provides `SessionManager.inMemory`. Drive this mode with a synthetic checkpoint bridge and server-selected authority; the recorder accepts autonomous origin and keeps runtime identity separate from an interactive session - (`export function createTurnRecorder(`, `packages/ui-server/src/activity/recorder.ts:125-203`). + (`export function createTurnRecorder(`, `packages/ui-server/src/activity/recorder.ts:126-204`). - R25. **Autonomous work gets its own pool** (`MAX_AUTONOMOUS_RUNS`, default 2) — but a second counter alone does not deliver "interactive always wins". The host cap applies only when starting WS sessions (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1336-1348`), and an autonomous @@ -343,7 +343,7 @@ Stated before the requirements because five of them derive from it. policy proposals, and discuss-session digest construction when those v2 features ship. Revision 1's "T2 is the entire bill" was false. - R41. **Budgets are enforced by reservation at claim time, not by summing history.** - `rollupRun` runs in `finish()` (`store.rollupRun(runId);`, `packages/ui-server/src/activity/recorder.ts:746`), so cost exists only after a + `rollupRun` runs in `finish()` (`store.rollupRun(runId);`, `packages/ui-server/src/activity/recorder.ts:756`), so cost exists only after a run ends: two runs can both start under the cap and finish over it, and unknown effective costs are excluded from the sum (`export function sumEffectiveCost(`, `packages/ui-server/src/activity/store.ts:179-194`) so the query **fails open**. Required: transactional reservations on claim, in-flight reservations counted, settlement at diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 65939d5ea0..8f30360a60 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -146,7 +146,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. - **Pi resources and extension gate:** (`export function createSessionResources(`, `packages/ui-backend-pi/src/session-resources.ts:29-152`) and (`export function createPermissionGate(`, `packages/ui-backend-pi/src/permission-gate.ts:96-125`). Built-ins are disabled, but ambient resources/extensions and in-process execution still need containment. -- **Cost timing:** (`store.rollupRun(runId);`, `packages/ui-server/src/activity/recorder.ts:746`) settles after execution; +- **Cost timing:** (`store.rollupRun(runId);`, `packages/ui-server/src/activity/recorder.ts:756`) settles after execution; (`export function sumEffectiveCost(`, `packages/ui-server/src/activity/store.ts:179-194`) explicitly counts unpriced runs. Reservations must cover in-flight work, not only this retrospective sum. - **Notifications:** (`CREATE TABLE IF NOT EXISTS notification_intents (`, `packages/ui-server/migrations/007_activity.sql:99-114`), @@ -1193,7 +1193,7 @@ and a server-selected tool policy. - Modify: `packages/ui-backend-claude/src/backend.ts` (`persistSession: false`, synthetic bridge) - Modify: `packages/ui-server/src/activity/recorder.ts` (server-selected - origin defaults to `"session"` at (`export function createTurnRecorder(`, `packages/ui-server/src/activity/recorder.ts:125-203`)) + origin defaults to `"session"` at (`export function createTurnRecorder(`, `packages/ui-server/src/activity/recorder.ts:126-204`)) - Test: `packages/ui-backend-claude/tests/autonomous-turn.test.ts` **Approach:** an autonomous request carrying persistence, tool policy, origin, and prompt diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index 7442d97504..593611c5a9 100644 --- a/docs/plans/navigation-recovery.md +++ b/docs/plans/navigation-recovery.md @@ -391,7 +391,7 @@ implementation. Any PR moving these lines owns their citation repairs. - Session summary shape: (`export interface ChatSession {`, `packages/ui-sdk/src/protocol.ts:1576-1592`). -- Run identity: (`const runId = turn.turnId;`, `packages/ui-server/src/activity/recorder.ts:154-155`). +- Run identity: (`const runId = turn.turnId;`, `packages/ui-server/src/activity/recorder.ts:155-156`). - Outcome vocabulary: (`export type ActivitySpanOutcome =`, `packages/ui-sdk/src/protocol.ts:2983-3006`). diff --git a/packages/ui-react/src/components/files/file-panel.tsx b/packages/ui-react/src/components/files/file-panel.tsx index 597f986507..f5e06769a6 100644 --- a/packages/ui-react/src/components/files/file-panel.tsx +++ b/packages/ui-react/src/components/files/file-panel.tsx @@ -1,4 +1,4 @@ -import { Suspense, useCallback, useEffect, useRef, type RefObject } from "react"; +import { Suspense, useCallback, useEffect, useRef, useState, type ReactNode, type RefObject } from "react"; import { Button, Overlay, TextButton, Label, Receipt, ScreenHeader } from "@schlessera/brain-ui-kit"; import type { ReceiptRow } from "@schlessera/brain-ui-kit"; import { ChevronDown, ChevronRight } from "lucide-react"; @@ -10,7 +10,7 @@ import { useMediaQuery } from "../../hooks/use-media-query.js"; import { splitFrontmatter } from "../../lib/frontmatter.js"; import { cn } from "../../lib/utils.js"; import { formatSize } from "./file-viewer-frame.js"; -import { DisabledToggleRow } from "../graph/graph-form.js"; +import { MarkedUntrustedEntry, MarkedUntrustedList, UntrustedMarksProvider, UntrustedRailBlock } from "./untrusted-marks.js"; import { useDestinationPress } from "../../hooks/use-destination-press.js"; import { focusFirst, scrollToStart, openModal } from "../../lib/destination-start.js"; import { STALE_AFTER_DAYS, ageInDays, formatAge } from "./staleness.js"; @@ -140,6 +140,7 @@ export function FilePanel({ open, onClose }: { open: boolean; onClose: () => voi return ( +
{/* Tree toggle strip — visible when a file is open */} {showContent && currentPath && ( @@ -160,9 +161,7 @@ export function FilePanel({ open, onClose }: { open: boolean; onClose: () => voi currentPath ? "max-h-[45vh] border-b border-border" : "flex-1" )} > - - - + } />
)} @@ -175,10 +174,38 @@ export function FilePanel({ open, onClose }: { open: boolean; onClose: () => voi )} +
); } +/** + * The tree area's `Marked untrusted` entry (#2673), which replaces the + * disabled `Untrusted only` filter, and the flat list it swaps in for the + * tree. The open viewer stays as it is. `All files` returns focus to the + * entry row; `Find it in Files` returns to the tree with a note. + */ +function MarksTreeArea({ tree, onListShown }: { tree: ReactNode; onListShown?: (shown: boolean) => void }) { + const [list, setList] = useState(false); + const [note, setNote] = useState(false); + const entry = useRef(null); + useEffect(() => { onListShown?.(list); }, [list, onListShown]); + const back = (withNote: boolean) => { setList(false); setNote(withNote); requestAnimationFrame(() => entry.current?.focus({ preventScroll: true })); }; + if (list) return
back(false)} onFind={() => back(true)} />
; + return ( + <> +
{ setNote(false); setList(true); }} />
+ {note ? ( +
+ Open the moved file and use Mark untrusted. + setNote(false)} style={{ minHeight: 44 }} /> +
+ ) : null} + {tree} + + ); +} + /** * D3 (the fifth design drop): from `laptop:` up Files is * not a drawer but a layer of panes over the content area, beside the rail — @@ -224,8 +251,11 @@ function FilePanes({ onClose, panelRef }: { onClose: () => void; panelRef: RefOb // turns gold — the same tone the tree's dot wears. const modified = loaded ? ageInDays(loaded.mtime) : null; const stale = modified !== null && modified >= STALE_AFTER_DAYS; + // While the `Marked untrusted` list shows, tree-only j / k and its hint are suspended. + const [listShown, setListShown] = useState(false); return ( +
void; panelRef: RefOb

Files

- {/* Untrusted only (sixth pass §3b): needs the provenance record — - origin, who, when — which no file carries yet. Drawn, disabled, - with its reason, never dropped: it is one of the two facts that - decide whether an answer may cite a file. */} -
- -
- {/* `j` / `k` move between tree items while one holds focus (D36: + {/* `Marked untrusted` (#2673) replaced the disabled `Untrusted only` + filter: the user's marks are the one untrusted fact a file carries. + `j` / `k` move between tree items while one holds focus (D36: focus-scoped, printed where they apply); the kit `FileRow` owns ↑↓, Home, End and the ← → fold. */} -
{ if (!singleKeyShortcuts) return; @@ -262,8 +287,8 @@ function FilePanes({ onClose, panelRef }: { onClose: () => void; panelRef: RefOb -
- {finePointer ?
+
} /> + {finePointer && !listShown ?
{singleKeyShortcuts ? "j / k move · " : ""}← → fold · ⏎ open
: null} @@ -318,10 +343,12 @@ function FilePanes({ onClose, panelRef }: { onClose: () => void; panelRef: RefOb )} + {loaded ? : null} {/* The design also draws "Linked from" (backlinks) and "Provenance" (git hash, host, date) here. The app has no API for either yet, so neither is drawn: an evidence rail shows what is known. */}
+
); } diff --git a/packages/ui-react/src/components/files/file-tree-view.tsx b/packages/ui-react/src/components/files/file-tree-view.tsx index c654c88346..d66d5c02aa 100644 --- a/packages/ui-react/src/components/files/file-tree-view.tsx +++ b/packages/ui-react/src/components/files/file-tree-view.tsx @@ -46,6 +46,11 @@ export interface TreeRowProps { * uses; the container decides from `mtime`, the row only prints. */ staleDays?: number; + /** + * The host lists this file as marked untrusted (#2673): the purple flag and + * the word `untrusted` in the meta, so the row's name says it too. + */ + untrusted?: boolean; children?: ReactNode; onClick: () => void; onRetry?: () => void; @@ -79,9 +84,9 @@ export function TreeRow(p: TreeRowProps) { kind={p.kind} depth={p.depth} active={p.active} - meta={p.loading ? "loading…" : p.staleDays !== undefined ? `stale ${p.staleDays}d` : undefined} - metaTone={!p.loading && p.staleDays !== undefined ? "gold" : undefined} - flag={p.staleDays !== undefined ? "gold" : undefined} + meta={p.loading ? "loading…" : [p.untrusted ? "untrusted" : "", p.staleDays !== undefined ? `stale ${p.staleDays}d` : ""].filter(Boolean).join(" · ") || undefined} + metaTone={p.loading ? undefined : p.untrusted ? "purple" : p.staleDays !== undefined ? "gold" : undefined} + flag={p.untrusted ? "purple" : p.staleDays !== undefined ? "gold" : undefined} onClick={p.onClick} onFold={p.onFold} /> diff --git a/packages/ui-react/src/components/files/file-tree.tsx b/packages/ui-react/src/components/files/file-tree.tsx index 6789b18586..a6e2e81a3b 100644 --- a/packages/ui-react/src/components/files/file-tree.tsx +++ b/packages/ui-react/src/components/files/file-tree.tsx @@ -3,6 +3,7 @@ import { useFileStore } from "../../stores/file-store.js"; import type { FileEntry } from "@schlessera/brain-ui-sdk/protocol"; import { FileTreeView, TreeRow, fileKind } from "./file-tree-view.js"; import { ageInDays, isStale } from "./staleness.js"; +import { useUntrustedMarks } from "./untrusted-marks.js"; /** * The container (S7): every node subscribes to the file store for its own @@ -47,6 +48,9 @@ function TreeNode({ entry, depth }: { entry: FileEntry; depth: number }) { const highlighted = useFileStore((s) => isDir && s.highlightedDir === entry.path); const setHighlightedDir = useFileStore((s) => s.setHighlightedDir); const clearHighlight = useCallback(() => setHighlightedDir(null), [setHighlightedDir]); + // Only the host's present records draw a cue; the tree never infers one. + const marks = useUntrustedMarks(); + const untrusted = !isDir && (marks?.present.has(entry.path) ?? false); // Staleness is a fact about a FILE's content. A directory's mtime moves // when an entry is added or removed, not when a note inside it changes, @@ -76,6 +80,7 @@ function TreeNode({ entry, depth }: { entry: FileEntry; depth: number }) { highlighted={highlighted} error={expanded ? childError : undefined} staleDays={staleDays} + untrusted={untrusted} onClick={() => void (isDir ? toggleDir(entry.path) : openFile(entry.path))} onRetry={() => void loadDir(entry.path)} onHighlightShown={clearHighlight} diff --git a/packages/ui-react/src/components/files/file-viewer-frame.tsx b/packages/ui-react/src/components/files/file-viewer-frame.tsx index fbd1a326ee..8039aee032 100644 --- a/packages/ui-react/src/components/files/file-viewer-frame.tsx +++ b/packages/ui-react/src/components/files/file-viewer-frame.tsx @@ -32,6 +32,10 @@ export interface ViewerToolbarProps { * tab (#1084). Absent for every other kind. */ openInTab?: string; + /** The untrusted-mark control (#2673), between Copy path and Share; null when none applies. */ + untrusted?: ReactNode; + /** The untrusted cue or lookup line under the path. */ + untrustedCue?: ReactNode; onMode: (mode: ViewMode) => void; onCopyPath: () => void; onReveal: () => void; @@ -51,8 +55,10 @@ export function ViewerToolbar(p: ViewerToolbarProps) { {p.fullPath} {p.size !== undefined && · {formatSize(p.size)}} + {p.untrustedCue} : } onClick={p.onCopyPath} /> + {p.untrusted} {p.openInTab && ( ; +} + +function FileViewerContent() { const root = useBrainUiRoot(); const declarations = useContentRendererDeclarations(); const viewer = useRef(null); @@ -61,6 +66,9 @@ export function FileViewer() { setViewMode={setViewMode} previewAvailable={previewAvailable} content={content ?? null} + // The mark applies to a file this view loaded: none on a failure, a forbidden or a missing file. + markLoaded={!loading && !error && !expired && content?.path === currentPath} + focusTitle={() => viewer.current?.querySelector("[data-file-title]")?.focus({ preventScroll: true })} onRevealInTree={() => setTreeExpanded(true)} /> @@ -110,6 +118,8 @@ function Toolbar({ setViewMode, previewAvailable, content, + markLoaded, + focusTitle, onRevealInTree, }: { fileName: string; @@ -119,10 +129,13 @@ function Toolbar({ setViewMode: (m: "preview" | "raw") => void; previewAvailable: boolean; content: FileContentResponse | null; + markLoaded: boolean; + focusTitle: () => void; onRevealInTree: () => void; }) { const root = useBrainUiRoot(); const [copied, setCopied] = useState(false); + const untrusted = useUntrustedToolbar(fullPath, markLoaded, fileName, focusTitle); const shareOptions = content ? buildFileShareOptions(root, content, fileName) : []; return ( 0 ? : null} openInTab={content?.kind === "html" ? htmlPreviewUrl(root, content.path) : undefined} + untrusted={untrusted.control} + untrustedCue={untrusted.cue} onMode={setViewMode} onCopyPath={() => { navigator.clipboard.writeText(fullPath); diff --git a/packages/ui-react/src/components/files/untrusted-marks.tsx b/packages/ui-react/src/components/files/untrusted-marks.tsx new file mode 100644 index 0000000000..809b1582ec --- /dev/null +++ b/packages/ui-react/src/components/files/untrusted-marks.tsx @@ -0,0 +1,522 @@ +/** + * Files the user marks untrusted (#2673): the toolbar control, the cue, the + * `Marked untrusted` list and its dialogs. The approved design is revision 3 + * plus the unchanged parts of revision 2 on the issue. + * + * The host owns every fact. Nothing here changes optimistically: a cue, a + * pressed control or a list row appears only from a host reply. Who may clear + * comes from the host's `canClear`, and a reader's replies carry neither + * missing records nor the marker's identity, so this code has nothing to hide. + */ +import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react"; +import { Button, Callout, Icon, IconButton, Overlay, Placeholder, TextButton } from "@schlessera/brain-ui-kit"; +import { ChevronLeft } from "lucide-react"; +import type { BrainUiRoot } from "../../root.js"; +import { useBrainUiRoot } from "../../root-context.js"; + +export interface MarkedBy { label: string | null; you: boolean } +export type MarkDetail = + | { path: string; marked: false; canClear: boolean } + | { path: string; marked: true; markedAt: number; missing: boolean; markedBy?: MarkedBy; canClear: boolean }; +export interface MarkRow { path: string; marked: true; markedAt: number; missing: boolean; markedBy?: MarkedBy } + +/** What one host request came back as. `uncertain`: it may or may not have applied. */ +type Failure = "unsupported" | "not-found" | "forbidden" | "owner-required" | "unreachable" | "uncertain" | "signed-out"; +type Reply = { ok: true; value: T } | { ok: false; failure: Failure }; + +const PURPLE = "var(--bk-purple-ink)"; + +async function call(root: BrainUiRoot, path: string, init?: RequestInit, valid: (body: unknown) => boolean = () => true): Promise> { + // A request never sent changed nothing; one whose reply was lost may have. + if (init?.method && init.method !== "GET" && typeof navigator !== "undefined" && navigator.onLine === false) return { ok: false, failure: "unreachable" }; + let response: Response; + try { response = await root.request(`${root.apiBase()}${path}`, { credentials: "include", cache: "no-store", ...init }); } + catch (error) { + if (error instanceof DOMException && error.name === "AbortError") return { ok: false, failure: "signed-out" }; + return { ok: false, failure: !init?.method || init.method === "GET" ? "unreachable" : "uncertain" }; + } + const body = await response.json().catch(() => null) as ({ error?: string } & T) | null; + // A success that isn't this route's shape is a server that doesn't have it. + if (response.ok) return body && valid(body) ? { ok: true, value: body } : { ok: false, failure: "unsupported" }; + // A server without the feature answers its generic not-found, never this route's own JSON error. + if (response.status === 404) return { ok: false, failure: body?.error === "not_found" ? "not-found" : "unsupported" }; + if (response.status === 405) return { ok: false, failure: "unsupported" }; + if (response.status === 403) return { ok: false, failure: body?.error === "owner_required" ? "owner-required" : "forbidden" }; + if (response.status === 400) return { ok: false, failure: "forbidden" }; + if (response.status === 401) return { ok: false, failure: "signed-out" }; + return { ok: false, failure: !init?.method || init.method === "GET" ? "unreachable" : "uncertain" }; +} +const query = (path: string) => `?path=${encodeURIComponent(path)}`; +const record = (body: unknown): body is Record => typeof body === "object" && body !== null; +const isDetail = (body: unknown) => record(body) && typeof body.path === "string" && typeof body.marked === "boolean" && typeof body.canClear === "boolean" + && (!body.marked || (typeof body.markedAt === "number" && typeof body.missing === "boolean")); +const readMark = (root: BrainUiRoot, path: string) => call(root, `/files/untrusted${query(path)}`, undefined, isDetail); +const readList = (root: BrainUiRoot) => call<{ marks: MarkRow[]; canClear: boolean }>(root, "/files/untrusted/list", undefined, + body => record(body) && typeof body.canClear === "boolean" && Array.isArray(body.marks) && body.marks.every(isRow)); +const isRow = (row: unknown) => record(row) && typeof row.path === "string" && typeof row.markedAt === "number" && typeof row.missing === "boolean"; +const sendMark = (root: BrainUiRoot, path: string) => call<{ status: "marked" | "already_marked"; mark: MarkDetail }>(root, "/files/untrusted", + { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ path }) }, + body => record(body) && (body.status === "marked" || body.status === "already_marked") && isDetail(body.mark)); +const sendClear = (root: BrainUiRoot, path: string) => call<{ status: "cleared" | "already_cleared" }>(root, `/files/untrusted${query(path)}`, { method: "DELETE" }, + body => record(body) && (body.status === "cleared" || body.status === "already_cleared")); + +/** `12 Jul`: the design's mark date. */ +export function markDate(at: number): string { + return new Date(at).toLocaleDateString("en-GB", { day: "numeric", month: "short" }); +} +/** Who marked, for the owner only: the host sends no `markedBy` to anyone else. */ +function byLine(markedBy: MarkedBy | undefined): string { + if (!markedBy) return ""; + return markedBy.you ? " by you" : markedBy.label ? ` by ${markedBy.label}` : ""; +} +function baseName(path: string): string { return path.split("/").pop() ?? path; } + +// ── The Files surface's shared state ─────────────────────────────────────── + +type ListState = + | { status: "loading" } + | { status: "ready"; marks: MarkRow[]; canClear: boolean } + | { status: "refused" } | { status: "offline" } | { status: "unsupported" }; + +interface MarksContext { + list: ListState; + /** Paths the host lists as present and marked, for the tree's cues. */ + present: ReadonlySet; + /** Bumped after every mark or clear, so a path's detail reads again. */ + revision: number; + refresh(): Promise; + /** Settles once the refetched list is in. */ + changed(): Promise; + announce(text: string): void; +} +const Marks = createContext(null); +export function useUntrustedMarks(): MarksContext | null { return useContext(Marks); } + +/** + * One per Files surface: the host's list, refetched on entry, after a mark or + * clear and when the window regains focus, and the surface's one polite live + * region. A viewer rendered without a Files surface makes its own. + */ +export function UntrustedMarksProvider({ children }: { children: ReactNode }) { + const root = useBrainUiRoot(); + const [list, setList] = useState({ status: "loading" }); + const [revision, setRevision] = useState(0); + const [message, setMessage] = useState(""); + const generation = useRef(0); + const refresh = useCallback(async () => { + const mine = ++generation.current; + const reply = await readList(root); + if (mine !== generation.current) return; + setList(reply.ok ? { status: "ready", marks: reply.value.marks, canClear: reply.value.canClear } + : reply.failure === "unsupported" ? { status: "unsupported" } + : reply.failure === "forbidden" || reply.failure === "owner-required" ? { status: "refused" } + : reply.failure === "signed-out" ? { status: "loading" } : { status: "offline" }); + }, [root]); + useEffect(() => { + void refresh(); + const onFocus = () => void refresh(); + window.addEventListener("focus", onFocus); + return () => { window.removeEventListener("focus", onFocus); generation.current++; }; + }, [refresh]); + // After sign-in the host state is read again (revision 2 §3, auth lock). + useEffect(() => root.authLock.state.subscribe((state, previous) => { + if (state.phase === "active" && previous.phase !== "active") { setRevision(value => value + 1); void refresh(); } + }), [root, refresh]); + const announce = useCallback((text: string) => { + // Clear first so the same sentence twice is announced twice. + setMessage(""); + queueMicrotask(() => setMessage(text)); + }, []); + const changed = useCallback(() => { setRevision(value => value + 1); return refresh(); }, [refresh]); + const present = useMemo(() => new Set(list.status === "ready" ? list.marks.filter(row => !row.missing).map(row => row.path) : []), [list]); + const value = useMemo(() => ({ list, present, revision, refresh, changed, announce }), [list, present, revision, refresh, changed, announce]); + return ( + + {children} + {/* A polite live region without the status role: the viewer's own `File status` stays the surface's one status. */} + {message} + + ); +} +/** A provider unless one is already above. */ +export function UntrustedMarksScope({ children }: { children: ReactNode }) { + return useUntrustedMarks() ? <>{children} : {children}; +} + +// ── One path's mark: the toolbar control, cue and rail ───────────────────── + +export type DetailState = + | { status: "checking" } | { status: "unsupported" } | { status: "unknown" } | { status: "absent" } + | { status: "ready"; mark: MarkDetail }; + +/** The mark of the open file, read from the host whenever the path or the surface's revision changes. */ +export function useMarkDetail(path: string | null): [DetailState, () => void, (mark: MarkDetail) => void] { + const root = useBrainUiRoot(); + const marks = useUntrustedMarks(); + const [state, setState] = useState<{ path: string | null; detail: DetailState }>({ path, detail: { status: "checking" } }); + const [retry, setRetry] = useState(0); + const revision = marks?.revision ?? 0; + useEffect(() => { + if (!path) return; + let live = true; + setState(current => current.path === path && current.detail.status === "ready" ? current : { path, detail: { status: "checking" } }); + void readMark(root, path).then(reply => { + if (!live) return; + setState({ path, detail: reply.ok ? { status: "ready", mark: reply.value } + : reply.failure === "unsupported" ? { status: "unsupported" } + : reply.failure === "not-found" || reply.failure === "forbidden" ? { status: "absent" } + : reply.failure === "signed-out" ? { status: "checking" } : { status: "unknown" } }); + }); + return () => { live = false; }; + }, [root, path, revision, retry]); + const detail = state.path === path ? state.detail : { status: "checking" as const }; + return [detail, () => setRetry(value => value + 1), (mark: MarkDetail) => setState({ path, detail: { status: "ready", mark } })]; +} + +/** `◆ untrusted · marked 12 Jul` (+ ` by …` for the owner): glyph and word, never colour alone. */ +export function MarkCue({ mark }: { mark: Extract }) { + return ( +
+ + untrusted · marked {markDate(mark.markedAt)}{byLine(mark.markedBy)} +
+ ); +} + +type Intent = "mark" | "clear"; +type DialogPhase = + | { kind: "confirm" } | { kind: "busy" } + | { kind: "failed"; text: string; retry: boolean } + | { kind: "checking" } | { kind: "still-unknown" }; + +const COPY = { + forbidden: "You don't have access to this file any more. Nothing was marked.", + owner: "Only the owner can clear this mark. Nothing changed.", + gone: "There's no file at this path any more. Nothing was marked.", + unreachable: "Couldn't reach your brain. Nothing has changed yet.", + checking: "Couldn't confirm the change. Checking…", + stillUnknown: "Still couldn't check. Try again.", + proxy: "On turns that run through the egress proxy, web access is limited to the untrusted allow-list and sites this chat already contacted. Your other web rules still apply.", +} as const; +export const PROXY_BULLET = COPY.proxy; + +/** + * Send one intent for one captured path, and settle it from the host. + * Returns the host's mark after success, the failure copy otherwise. An + * uncertain reply is resolved by a fresh read, never assumed. + */ +async function settle(root: BrainUiRoot, intent: Intent, path: string, onChecking: () => void): + Promise<{ done: true; mark: MarkDetail | null; already: boolean } | { done: false; phase: DialogPhase; signedOut?: boolean; gone?: boolean }> { + const reply = intent === "mark" ? await sendMark(root, path) : await sendClear(root, path); + if (reply.ok) { + if ("mark" in reply.value) return { done: true, mark: reply.value.mark, already: reply.value.status === "already_marked" }; + return { done: true, mark: null, already: reply.value.status === "already_cleared" }; + } + switch (reply.failure) { + case "forbidden": return { done: false, phase: { kind: "failed", text: intent === "mark" ? COPY.forbidden : COPY.owner, retry: false } }; + case "owner-required": return { done: false, phase: { kind: "failed", text: COPY.owner, retry: false } }; + case "not-found": return { done: false, gone: true, phase: { kind: "failed", text: COPY.gone, retry: false } }; + case "unreachable": return { done: false, phase: { kind: "failed", text: COPY.unreachable, retry: true } }; + case "signed-out": return { done: false, signedOut: true, phase: { kind: "confirm" } }; + case "unsupported": case "uncertain": { + onChecking(); + const check = await readMark(root, path); + if (!check.ok) return { done: false, phase: { kind: "still-unknown" } }; + const applied = intent === "mark" ? check.value.marked : !check.value.marked; + // The host shows the intent applied: that is the result. Otherwise nothing changed. + return applied ? { done: true, mark: check.value, already: false } : { done: false, phase: { kind: "failed", text: COPY.unreachable, retry: true } }; + } + } +} + +/** The dialog body's actions, stacked where they don't fit side by side at 320px. */ +function Actions({ cancelRef, children }: { cancelRef: RefObject; children: ReactNode }) { + return
{children}
; +} +/** The kit Button is a `role="button"` element, not a native button. */ +const CONTROL = '[role="button"], button'; +/** A ref whose current is the first control inside `wrap`: Cancel, for the Overlay's initial focus. */ +function firstButton(wrap: RefObject): RefObject { + return { get current() { return wrap.current?.querySelector(CONTROL) ?? null; } } as RefObject; +} + +function PhaseLine({ phase }: { phase: DialogPhase }) { + const text = phase.kind === "failed" ? phase.text : phase.kind === "checking" ? COPY.checking : phase.kind === "still-unknown" ? COPY.stillUnknown : null; + if (!text) return null; + return
; +} + +/** + * The mark or clear confirmation. `path` is captured when it opened; the + * caller closes it, sending nothing, if the viewer moves to another file. + */ +function ConfirmDialog({ intent, path, missing, reader, returnTo, onCancel, onDone, onGone, onSignedOut }: { + intent: Intent; path: string; missing?: boolean; reader: boolean; + /** Read by the Overlay as it closes, once the background is live again: the focus table's destination. */ + returnTo: () => HTMLElement | null; + onCancel(): void; onDone(mark: MarkDetail | null, already: boolean): void; onGone(): void; onSignedOut(): void; +}) { + const root = useBrainUiRoot(); + const [phase, setPhase] = useState({ kind: "confirm" }); + const wrap = useRef(null); + const live = useRef(true); + useEffect(() => () => { live.current = false; }, []); + const busy = phase.kind === "busy" || phase.kind === "checking"; + const run = async () => { + setPhase({ kind: "busy" }); + const result = await settle(root, intent, path, () => { if (live.current) setPhase({ kind: "checking" }); }); + if (!live.current) return; + if (result.done) return onDone(result.mark, result.already); + if (result.signedOut) return onSignedOut(); + if (result.gone) onGone(); + setPhase(result.phase); + }; + const title = intent === "mark" ? "Mark this file untrusted?" : missing ? "Clear the old mark?" : "Clear the untrusted mark?"; + const action = intent === "mark" ? "Mark untrusted" : missing ? "Clear old mark" : "Clear mark"; + const retry = phase.kind === "still-unknown" || (phase.kind === "failed" && phase.retry); + const refused = phase.kind === "failed" && !phase.retry; + return ( + { if (!busy) onCancel(); }} returnFocus={returnTo} data-untrusted-dialog={intent}> +
+

{path}

+ {intent === "mark" ? <> +

From now on, a chat that opens this file with its file tools is treated as handling untrusted content until the chat ends:

+
    +
  • Every outward action asks you first, even ones your policy allows.
  • +
  • Changes to skills, instructions or memory are flagged in the journal.
  • +
  • {COPY.proxy}
  • +
+

The agent can still read the file. Chats that already opened it don't change. If the file moves, the mark stays with this path.{reader ? " Only the owner can see or clear it then." : ""}

+ {reader ?

Only the owner can clear a mark.

: null} + : missing ? ( +

This removes the record for {path} only. If the file was moved, its new location isn't marked. Mark it there separately. Chats that already opened it stay untrusted until they end.

+ ) : <> +

New chats that open this file won't be treated as untrusted because of it.

+

Chats that already opened it stay untrusted until they end. A chat can still be untrusted for other reasons.

+ } + + +
+
+ ); +} + +/** + * The toolbar's slot between Copy path and Share, and the cue under the + * path. `focusTitle` puts focus on the file title when a reader's mark + * removes the button that held it. + */ +export function useUntrustedToolbar(filePath: string | null, loaded: boolean, fileName: string, focusTitle: () => void): { control: ReactNode; cue: ReactNode } { + const root = useBrainUiRoot(); + const marks = useUntrustedMarks(); + const path = loaded ? filePath : null; + const [detail, retry, apply] = useMarkDetail(path); + const [dialog, setDialog] = useState<{ intent: Intent; path: string } | null>(null); + const button = useRef(null); + // Where focus lands when the dialog closes: the button (now Mark or Clear), or the title when it went away. + const landing = useRef<"button" | "title">("button"); + const titleOf = () => { focusTitle(); return null; }; + const returnTo = () => landing.current === "button" && button.current?.isConnected ? button.current : titleOf(); + + // Switching files closes the dialog and sends nothing. A reload of the same file keeps it. + useEffect(() => { if (dialog && dialog.path !== filePath) setDialog(null); }, [filePath, dialog]); + const announce = (text: string) => marks?.announce(text); + + let control: ReactNode = null, cue: ReactNode = null; + if (!path) {} + else if (detail.status === "unknown") { + cue = ( +
+ Couldn't check the untrusted mark + +
+ ); + } else if (detail.status === "ready") { + const mark = detail.mark; + if (!mark.marked) { + control = } + onClick={() => setDialog({ intent: "mark", path })} data-untrusted-control="mark" />; + } else { + cue = ; + if (mark.canClear) control = } onClick={() => setDialog({ intent: "clear", path })} + style={{ color: PURPLE, background: "var(--bk-callout-tint-purple, transparent)" }} data-untrusted-control="clear" data-pressed="" />; + } + } + const reader = detail.status === "ready" ? !detail.mark.canClear : true; + const dialogNode = dialog ? ( + { landing.current = "button"; setDialog(null); }} + onSignedOut={() => setDialog(null)} + onGone={() => { void root.stores.file.getState().openFile(dialog.path); }} + onDone={(mark, already) => { + setDialog(null); + if (mark) apply(mark); + if (dialog.intent === "mark") { + announce(already ? "This file was already marked untrusted." : `${fileName} marked untrusted`); + landing.current = mark?.canClear ? "button" : "title"; + } else { + announce(already ? "This mark was already cleared." : "Untrusted mark cleared"); + if (!mark) apply({ path: dialog.path, marked: false, canClear: true }); + landing.current = "button"; + } + void marks?.changed(); + }} /> + ) : null; + return { control: control || dialogNode ? <>{control}{dialogNode} : null, cue }; +} + +// ── The `Marked untrusted` list ──────────────────────────────────────────── + +/** The entry row that replaces the disabled `Untrusted only` filter. Hidden on a server without marks. */ +export function MarkedUntrustedEntry({ onOpen, entryRef }: { onOpen(): void; entryRef?: RefObject }) { + const marks = useUntrustedMarks(); + // Drawn once the host answered with marks or a refusal: a row that appeared + // and then vanished on an unsupported server would take focus with it. An + // unreachable host draws no row until a refetch (on focus) reaches it. + if (!marks || (marks.list.status !== "ready" && marks.list.status !== "refused")) return null; + const count = marks.list.status === "ready" ? marks.list.marks.length : null; + const name = count === null ? "Marked untrusted" : `Marked untrusted, ${count === 0 ? "no files" : count === 1 ? "1 file" : `${count} files`}`; + return ( + + ); +} + +/** + * The flat list of host records that replaces the tree area. Present rows + * open their file; the owner's missing rows open the `Missing file` dialog. + */ +export function MarkedUntrustedList({ onAllFiles, onFind }: { onAllFiles(): void; onFind(): void }) { + const root = useBrainUiRoot(); + const marks = useUntrustedMarks(); + const heading = useRef(null); + const listRef = useRef(null); + const [missing, setMissing] = useState(null); + const [clearing, setClearing] = useState(null); + const returnRow = useRef(null); + useEffect(() => { heading.current?.focus({ preventScroll: true }); void marks?.refresh(); }, []); // eslint-disable-line react-hooks/exhaustive-deps + if (!marks) return null; + const list = marks.list; + const owner = list.status === "ready" && list.canClear; + const focusRow = (path: string | null) => requestAnimationFrame(() => { + const rows = [...(listRef.current?.querySelectorAll("[data-mark-row]") ?? [])]; + (rows.find(row => row.dataset.markRow === path) ?? heading.current)?.focus({ preventScroll: true }); + }); + const open = async (row: MarkRow) => { + // A stale row (the mark was cleared or the file left) refreshes the list instead. + const check = await readMark(root, row.path); + if (!check.ok || !check.value.marked || check.value.missing !== row.missing) { + await marks.refresh(); + marks.announce("The list was out of date and has been refreshed."); + return; + } + if (row.missing) { returnRow.current = row.path; setMissing(row); } + else void root.stores.file.getState().openFile(row.path); + }; + return ( +
+
} onClick={onAllFiles} style={{ minHeight: 44 }} />
+
+

Marked untrusted

+ {list.status === "ready" ?

{owner + ? "Files you or others marked. Doesn't list other untrusted sources." + : "Files marked by you or others. Doesn't list other untrusted sources. Marks on moved or deleted files are shown to the owner."}

: null} +
+ {list.status === "loading" ?
+ : list.status === "refused" ?

This list isn't available with your current access.

+ : list.status === "offline" || list.status === "unsupported" ?
+

Can't reach your brain right now.

+
+
+ : list.marks.length === 0 ?
+

{owner ? "No files are marked untrusted." : "No files you can open are marked untrusted."}

+

Open a file and use Mark untrusted.

+
+ :
    + {list.marks.map(row => { + const folder = row.path.includes("/") ? row.path.slice(0, row.path.lastIndexOf("/") + 1) : ""; + return ( +
  • + +
  • + ); + })} +
} + {missing ? { setMissing(null); focusRow(returnRow.current); }} + onFind={() => { setMissing(null); onFind(); }} + onClear={() => { setClearing(missing); setMissing(null); }} /> : null} + {clearing ? null} + onCancel={() => { setClearing(null); focusRow(clearing.path); }} + onSignedOut={() => setClearing(null)} onGone={() => {}} + onDone={async (_mark, already) => { + const rows = list.status === "ready" ? list.marks : []; + const next = rows[rows.findIndex(row => row.path === clearing.path) + 1]?.path ?? null; + setClearing(null); + marks.announce(already ? "This mark was already cleared." : "Untrusted mark cleared"); + await marks.changed(); + focusRow(next); + }} /> : null} +
+ ); +} + +/** The owner's dialog for a retained record whose file is gone. Readers never get one. */ +function MissingFileDialog({ row, owner, onClose, onFind, onClear }: { row: MarkRow; owner: boolean; onClose(): void; onFind(): void; onClear(): void }) { + const wrap = useRef(null); + // Focus goes to Close, the last action; the Overlay's own first stop would be Find it in Files. + const close = { get current() { return wrap.current?.querySelector(`[data-missing-close] :is(${CONTROL})`) ?? null; } } as RefObject; + return ( + +
+

{row.path}

+

marked {markDate(row.markedAt)}

+

There's no file at this path any more. It may have been moved, renamed or deleted. brain-kit doesn't follow moves, so a moved copy is not marked.

+

To protect it, open the file at its new location and use Mark untrusted.

+

This record stays so the mark comes back if a file returns to this path.

+
+
+
+ +
+ ); +} + +/** The wide evidence rail's block for the open file's mark. */ +export function UntrustedRailBlock({ path }: { path: string }) { + const [detail] = useMarkDetail(path); + if (detail.status !== "ready" || !detail.mark.marked || detail.mark.missing) return null; + const mark = detail.mark; + return ( +
+
+ Untrusted +
+
marked {markDate(mark.markedAt)}
+ {mark.markedBy && byLine(mark.markedBy) ?
{byLine(mark.markedBy).trim()}
: null} +
+ ); +} diff --git a/packages/ui-react/tests/fixtures/untrusted-marks-client.tsx b/packages/ui-react/tests/fixtures/untrusted-marks-client.tsx new file mode 100644 index 0000000000..8f26991119 --- /dev/null +++ b/packages/ui-react/tests/fixtures/untrusted-marks-client.tsx @@ -0,0 +1,28 @@ +import React from "react"; +import { createRoot } from "react-dom/client"; +import { FilePanel } from "../../src/components/files/file-panel.js"; +import { BrainUiProvider } from "../../src/root-context.js"; +import { createBrainUiRoot } from "../../src/root.js"; + +// #2673: the real Files panel (drawer below 900px, panes from there) against a real server. +const params = new URLSearchParams(location.search); +const root = createBrainUiRoot({ storage: null }); +const mount = document.getElementById("app"); +if (!mount) throw new Error("Untrusted marks fixture has no mount"); +document.documentElement.dataset.theme = params.get("theme") ?? "dark"; +document.documentElement.classList.toggle("dark", params.get("theme") !== "light"); +createRoot(mount).render( + + {}} /> + , +); +Object.assign(window, { __marks: { + open: (path: string) => root.stores.file.getState().openFile(path), + state: () => { + const state = root.stores.file.getState(); + return { path: state.currentPath, loading: state.contentLoading, error: state.contentError }; + }, + expandTree: () => root.stores.file.getState().setTreeExpanded(true), + collapseTree: () => root.stores.file.getState().setTreeExpanded(false), +} }); +window.addEventListener("pagehide", () => root.dispose(), { once: true }); diff --git a/packages/ui-react/tests/render/desktop-panes-sixth.test.tsx b/packages/ui-react/tests/render/desktop-panes-sixth.test.tsx index 4a4c077ce9..7d7d6f8664 100644 --- a/packages/ui-react/tests/render/desktop-panes-sixth.test.tsx +++ b/packages/ui-react/tests/render/desktop-panes-sixth.test.tsx @@ -133,15 +133,21 @@ describe("Files rail (sixth pass §3)", () => { view.unmount(); }); - test("Untrusted only is drawn, disabled, with its reason in mono — never omitted", async () => { - openFile({ path: "fresh.md", content: "x", kind: "text", mtime: Date.now() }); - const view = render( {}} />); - await act(flushPromises); - const toggle = view.getByRole("switch", { name: "Untrusted only" }); - expect(toggle.getAttribute("aria-disabled")).toBe("true"); - expect(toggle.getAttribute("tabindex")).toBe("-1"); - expect(toggle.closest("[data-disabled-row]")!.textContent).toContain("needs provenance"); - view.unmount(); + test("Marked untrusted (#2673) replaces the disabled Untrusted only filter", async () => { + const original = globalThis.fetch; + globalThis.fetch = (async (input: RequestInfo | URL) => String(input).includes("/files/untrusted/list") + ? Response.json({ marks: [], canClear: true }) : Response.json({ entries: [] })) as unknown as typeof fetch; + try { + openFile({ path: "fresh.md", content: "x", kind: "text", mtime: Date.now() }); + const view = render( {}} />); + await act(flushPromises); + await act(flushPromises); + expect(view.queryByRole("switch", { name: "Untrusted only" })).toBeNull(); + const entry = view.container.querySelector("[data-untrusted-entry]")!; + expect(entry.textContent).toContain("Marked untrusted · none"); + expect(entry.getAttribute("aria-label")).toBe("Marked untrusted, no files"); + view.unmount(); + } finally { globalThis.fetch = original; } }); }); diff --git a/packages/ui-react/tests/untrusted-marks-runtime.test.ts b/packages/ui-react/tests/untrusted-marks-runtime.test.ts new file mode 100644 index 0000000000..af9a9a5b69 --- /dev/null +++ b/packages/ui-react/tests/untrusted-marks-runtime.test.ts @@ -0,0 +1,410 @@ +import { runtimePackageBuild } from "./fixtures/runtime-package-build"; +// #2673: the Files panel's untrusted marks in real Chrome against a real +// password-mode server, as the owner and as an agent reader: the toolbar +// states, cues, list, dialogs, races, focus, live region, disclosure and +// layout at 320px and 1440px, light and dark, and 200% zoom at 320px. +import { runtimeHookPhases } from "./fixtures/runtime-hook-phases.ts"; +import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, statSync } from "node:fs"; +import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { generateSignedCookie } from "hono/cookie"; +import { chromium, type Browser, type Page } from "playwright"; +import { createRecordingObservability, createStaticBackendRegistry, resolveServerConfig } from "@schlessera/brain-ui-server"; +import { createFixtureApp as createApp } from "../../ui-server/tests/helpers/native-app-fixture.js"; +import { createPrincipal, type Principal } from "../../ui-server/src/db/principals.js"; +import { makeFakeBackend } from "../../ui-server/tests/helpers/fake-backend.ts"; + +const executablePath = [process.env.PUPPETEER_EXECUTABLE_PATH, process.env.BRAIN_UI_CHROME_PATH, + "/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"] + .find((path) => path && statSync(path, { throwIfNoEntry: false })?.isFile()); +if (!executablePath && process.env.BRAIN_REQUIRE_CHROME === "1") throw new Error("Untrusted marks runtime proof requires real Chrome"); +if (!executablePath) console.warn("SKIPPING untrusted marks runtime proof: no Chrome; the Files marks UI is unverified locally."); + +const repo = resolve(import.meta.dir, "../../.."); +const SECRET = "untrusted-marks-runtime-secret-0123456789"; +const MESSAGE = "inbox/message-from-eurymachus.md"; +const LETTER = "inbox/letter-from-antinous.md"; +const MOVED = "people/suitors/antinous-letter.md"; +const LOOM = "notes/penelope-loom.md"; +const HOSTILE = "inbox/[x](evil.invalid) bold .md"; +const JULY_12 = Date.UTC(2026, 6, 12, 9), JULY_11 = Date.UTC(2026, 6, 11, 9); +const PROXY = "On turns that run through the egress proxy, web access is limited to the untrusted allow-list and sites this chat already contacted. Your other web rules still apply."; + +let fixture: string | undefined; +let brain = "", origin = ""; +let app: Awaited> | undefined; +let server: ReturnType | undefined; +let browser: Browser | undefined; +let owner: Principal, reader: Principal; +const cookies: Record<"owner" | "reader", string> = { owner: "", reader: "" }; +const hook = runtimeHookPhases("untrusted-marks-runtime"); + +async function child(args: string[], cwd = repo): Promise { + const process = Bun.spawn(args, { cwd, stdout: "pipe", stderr: "pipe", stdin: "ignore" }); + const [out, err, code] = await hook.child("client-build", process); + if (code !== 0) throw new Error(`Untrusted marks fixture preparation failed (${code}): ${out}\n${err}`); +} + +beforeAll(async () => { + if (!executablePath) return; + await runtimePackageBuild(repo, ["ui-react", "ui-server", "core"], hook); + fixture = await mkdtemp(resolve(tmpdir(), "odysseus-untrusted-marks-")); + brain = resolve(fixture, "brain"); + for (const dir of ["inbox", "notes", "people/suitors"]) await mkdir(resolve(brain, dir), { recursive: true }); + const assets = resolve(fixture, "assets"); + await mkdir(assets); + await child([process.execPath, "-e", 'const r=await Bun.build({entrypoints:[process.argv[1]],target:"browser",outdir:process.argv[2],naming:"client.js"});if(!r.success){console.error(r.logs);process.exit(1)}', resolve(import.meta.dir, "fixtures/untrusted-marks-client.tsx"), assets]); + await writeFile(resolve(assets, "index.html"), 'Odysseus untrusted marks
'); + for (const [name, pkg] of [["kit.css", "ui-kit"], ["app.css", "ui-react"]]) await writeFile(resolve(assets, name!), await readFile(resolve(repo, `packages/${pkg}/dist/styles.css`))); + const backend = makeFakeBackend({ id: "marks-fixture" }); + app = await hook.phase("host-start", () => createApp({ config: resolveServerConfig({ BRAIN_PATH: brain, DB_PATH: resolve(fixture!, "ui.db"), + AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: "unused-fixture-hash", COOKIE_SECRET: SECRET, BRAIN_UI_ALLOW_LOOPBACK_ORIGIN: "1", + HOST: "127.0.0.1", NODE_ENV: "test", BRAIN_UI_PRICING_DISCOVERY: "0", BRAIN_UI_MODEL_DISCOVERY: "0" }), + registry: createStaticBackendRegistry([backend], backend.id), staticRoot: assets, observability: createRecordingObservability() })); + server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: app.fetch, websocket: app.websocket }); + origin = `http://127.0.0.1:${server.port}`; + owner = createPrincipal(app.db, { authMethod: "password", label: "Safari on iPhone", ttlSeconds: 3600 }); + reader = createPrincipal(app.db, { authMethod: "delegated", createdBy: owner.id, label: "Telemachus agent", ttlSeconds: 3600 }); + for (const [who, principal] of [["owner", owner], ["reader", reader]] as const) { + const signed = await generateSignedCookie("brain_ui_session", principal.id, SECRET); + cookies[who] = signed.split(";")[0]!.slice("brain_ui_session=".length); + } + browser = await hook.phase("chrome-launch", () => chromium.launch({ executablePath, headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"] })); +}, 180_000); + +afterAll(() => hook.phase("cleanup", async () => { + await browser?.close(); + server?.stop(true); + await app?.close(); + if (fixture) await rm(fixture, { recursive: true, force: true }); +})); + +/** The Odysseus fixture: a present Eurymachus message, Antinous's letter moved away, a hostile name, an unmarked loom note. */ +beforeEach(async () => { + if (!app) return; + for (const path of [MESSAGE, LOOM, HOSTILE]) await writeFile(resolve(brain, path), `# ${path}\n\nA fictional note for Penelope, dated 2026-07-12.\n`); + if (existsSync(resolve(brain, LETTER))) await rename(resolve(brain, LETTER), resolve(brain, MOVED)); + if (!existsSync(resolve(brain, MOVED))) await writeFile(resolve(brain, MOVED), "# To Penelope, from Antinous\n"); + app.db.query("DELETE FROM untrusted_marks").run(); + const seed = app.db.query("INSERT INTO untrusted_marks (path, marked_at, marked_by) VALUES (?, ?, ?)"); + seed.run(MESSAGE, JULY_12, owner.id); + // The reader originally marked the letter; it is now missing. + seed.run(LETTER, JULY_12, reader.id); + seed.run(HOSTILE, JULY_11, owner.id); +}); + +async function open(who: "owner" | "reader", width: number, height: number, theme: "light" | "dark", zoom = 1) { + const context = await browser!.newContext({ viewport: { width: Math.round(width / zoom), height: Math.round(height / zoom) }, deviceScaleFactor: zoom }); + await context.addCookies([{ name: "brain_ui_session", value: cookies[who], url: origin }]); + const outside: string[] = []; + const sent: string[] = []; + await context.route("**/*", (route) => { + const url = route.request().url(); + if (new URL(url).origin !== origin) { outside.push(url); return route.abort(); } + return route.fallback(); + }); + const page = await context.newPage(); + page.on("request", (request) => { if (request.method() !== "GET" && request.url().includes("/api/files/untrusted")) sent.push(`${request.method()} ${new URL(request.url()).search}`); }); + await page.goto(`${origin}/?theme=${theme}`); + await page.waitForFunction("window.__marks !== undefined"); + return { page, context, outside, sent }; +} +async function openFile(page: Page, path: string) { + await page.evaluate((target) => (window as unknown as { __marks: { open(path: string): Promise } }).__marks.open(target), path); + await page.waitForFunction(() => { const s = (window as unknown as { __marks: { state(): { loading: boolean } } }).__marks.state(); return !s.loading; }); +} +const dialog = (page: Page) => page.getByRole("dialog"); +const focusedName = (page: Page) => page.evaluate(() => { + const element = document.activeElement as HTMLElement | null; + return element ? element.getAttribute("aria-label") ?? element.textContent?.trim() ?? "" : ""; +}); +async function api(who: "owner" | "reader", method: string, path: string, body?: unknown) { + return fetch(`${origin}/api/files/untrusted${method === "PUT" ? "" : `?path=${encodeURIComponent(path)}`}`, { + method, headers: { cookie: `brain_ui_session=${cookies[who]}`, origin, "content-type": "application/json" }, + ...(method === "PUT" ? { body: JSON.stringify(body ?? { path }) } : {}), + }); +} +/** Nothing scrolls sideways and nothing in an open dialog leaves the viewport. */ +async function noHorizontalScroll(page: Page, label: string) { + const overflow = await page.evaluate(() => { + const scroller = document.scrollingElement!; + const outside = [...document.querySelectorAll("dialog[open] [data-untrusted-body] *")].filter(element => { + const rect = element.getBoundingClientRect(); + return rect.width > 0 && (rect.right > window.innerWidth + 0.5 || rect.left < -0.5); + }).map(element => element.tagName + ":" + (element.textContent ?? "").slice(0, 30)); + return { page: scroller.scrollWidth - scroller.clientWidth, outside }; + }); + expect(JSON.stringify({ label, ...overflow })).toBe(JSON.stringify({ label, page: 0, outside: [] })); +} +async function targetsAtLeast44(page: Page, selector: string, label: string) { + // Layout height: an opening dialog's scale animation shrinks client rects. + const small = await page.evaluate((sel) => [...document.querySelectorAll(sel)].filter(element => element.getClientRects().length > 0) + .map(element => ({ name: element.getAttribute("aria-label") ?? element.textContent?.trim(), height: element.offsetHeight })) + .filter(entry => entry.height < 44), selector); + expect(JSON.stringify({ label, small })).toBe(JSON.stringify({ label, small: [] })); +} + +describe.skipIf(!executablePath)("untrusted marks in the real Files panel", () => { + for (const [width, height, theme, zoom] of [[1440, 900, "light", 1], [1440, 900, "dark", 1], [320, 640, "dark", 1], [320, 640, "light", 1], [320, 640, "dark", 2]] as const) { + const shape = `${width}x${height} ${theme}${zoom > 1 ? " at 200%" : ""}`; + + test(`reader: marks with the exact copy and focus, sees dates only, and never a missing record (${shape})`, async () => { + const { page, context, outside } = await open("reader", width, height, theme, zoom); + try { + // The entry row counts only the present marks this reader can open. + const entry = page.locator("[data-untrusted-entry]"); + await page.waitForFunction(() => document.querySelector("[data-untrusted-entry]")?.getAttribute("aria-label")?.includes("2 files")); + expect(await entry.getAttribute("aria-label"), "READER_COUNT_PRESENT_ONLY").toBe("Marked untrusted, 2 files"); + expect(await page.content(), "READER_DOM_NO_MISSING_PATH").not.toContain("antinous"); + + await openFile(page, LOOM); + const markButton = page.getByRole("button", { name: "Mark untrusted", exact: true }); + await markButton.waitFor(); + // Toolbar order: reveal → title → copy → mark → share → mode. + const order = await page.evaluate(() => [...document.querySelectorAll("button[aria-label], h3[data-file-title]")] + .map(element => element.getAttribute("aria-label") ?? "title").filter(name => ["Reveal in tree", "title", "Copy path", "Mark untrusted", "Share"].includes(name))); + expect(order.indexOf("Copy path"), "TOOLBAR_ORDER").toBeLessThan(order.indexOf("Mark untrusted")); + await markButton.click(); + await dialog(page).getByText("Mark this file untrusted?").waitFor(); + expect(await focusedName(page), "MARK_DIALOG_FOCUS_CANCEL").toBe("Cancel"); + expect(await page.locator("[data-proxy-bullet]").textContent(), "PROXY_BULLET_EXACT").toBe(PROXY); + const body = await dialog(page).textContent(); + expect(body).toContain("Only the owner can see or clear it then."); + expect(body).toContain("Only the owner can clear a mark."); + await noHorizontalScroll(page, "reader mark dialog"); + await targetsAtLeast44(page, "[data-untrusted-body] [role=button]", "reader mark dialog"); + // Escape returns to the button. + await page.keyboard.press("Escape"); + await page.waitForFunction(() => !document.querySelector("dialog[open]")); + expect(await focusedName(page), "ESCAPE_RETURNS_TO_BUTTON").toBe("Mark untrusted"); + + await markButton.click(); + await dialog(page).getByRole("button", { name: "Mark untrusted" }).click(); + await page.waitForFunction(() => document.querySelector("[data-untrusted-announcer]")?.textContent === "penelope-loom.md marked untrusted"); + // The reader's button is gone: focus is on the file title, and the cue has a date and no identity. + expect(await page.getByRole("button", { name: "Mark untrusted", exact: true }).count()).toBe(0); + expect(await page.evaluate(() => document.activeElement?.hasAttribute("data-file-title")), "READER_MARK_FOCUS_TITLE").toBe(true); + const cue = await page.locator("[data-untrusted-cue]").first().textContent(); + expect(cue).toMatch(/^untrusted · marked \d{1,2} [A-Z][a-z]{2}$/); + expect(await page.getByRole("button", { name: "Untrusted: clear mark" }).count(), "READER_NO_CLEAR").toBe(0); + + // The list: present rows only, the reader's subtitle, inert hostile text. + if (width < 900) await page.evaluate(() => (window as unknown as { __marks: { expandTree(): void } }).__marks.expandTree()); + await page.waitForFunction(() => document.querySelector("[data-untrusted-entry]")?.getAttribute("aria-label") === "Marked untrusted, 3 files"); + await page.locator("[data-untrusted-entry]").click(); + await page.locator("[data-untrusted-heading]").waitFor(); + expect(await focusedName(page), "ENTER_LIST_FOCUS_HEADING").toBe("Marked untrusted"); + const list = page.locator("[data-untrusted-list]"); + await list.locator("[data-mark-row]").first().waitFor(); + const text = await list.textContent(); + expect(text).toContain("Files marked by you or others. Doesn't list other untrusted sources. Marks on moved or deleted files are shown to the owner."); + expect(await list.locator("[data-mark-row]").count(), "READER_LIST_THREE_PRESENT").toBe(3); + // The approved subtitle itself says "by you or others"; the rows carry no identity. + const rowsText = (await list.locator("[data-mark-row]").allTextContents()).join("\n"); + for (const forbidden of ["antinous", "missing", "Safari on iPhone", "Telemachus agent", "by you", " by "]) expect(rowsText, `READER_ROWS_NO_${forbidden}`).not.toContain(forbidden); + for (const forbidden of ["antinous", "missing", "Safari on iPhone", "Telemachus agent"]) expect(text, `READER_LIST_NO_${forbidden}`).not.toContain(forbidden); + expect(text, "HOSTILE_PATH_LITERAL").toContain("[x](evil.invalid) bold .md"); + expect(await list.locator("a, b, img").count(), "HOSTILE_PATH_INERT").toBe(0); + expect(await list.locator("[role=tree], [role=treeitem]").count(), "LIST_IS_NOT_A_TREE").toBe(0); + expect(await list.locator("[data-mark-row] button").count(), "ROWS_HAVE_NO_NESTED_CONTROLS").toBe(0); + await noHorizontalScroll(page, "reader list"); + await targetsAtLeast44(page, "[data-untrusted-list] :is(button, [role=button])", "reader list"); + if (width >= 900) expect(await page.getByText("j / k move").count(), "JK_HINT_SUSPENDED").toBe(0); + await page.getByRole("button", { name: "All files" }).click(); + await page.waitForFunction(() => document.activeElement?.hasAttribute("data-untrusted-entry")); + expect(outside).toEqual([]); + } finally { await context.close(); } + }, 60_000); + + test(`owner: cue with the label, pressed clear, missing first, missing dialog and clear focus (${shape})`, async () => { + const { page, context, outside } = await open("owner", width, height, theme, zoom); + try { + await openFile(page, MESSAGE); + const clear = page.getByRole("button", { name: "Untrusted: clear mark" }); + await clear.waitFor(); + expect(await page.locator("[data-untrusted-cue]").first().textContent(), "OWNER_CUE_BY_YOU").toBe("untrusted · marked 12 Jul by you"); + if (width >= 1440) expect(await page.locator('[data-rail-block="untrusted"]').textContent(), "OWNER_RAIL").toBe("Untrusted marked 12 Julby you"); + + if (width < 900) await page.evaluate(() => (window as unknown as { __marks: { expandTree(): void } }).__marks.expandTree()); + await page.waitForFunction(() => document.querySelector("[data-untrusted-entry]")?.getAttribute("aria-label") === "Marked untrusted, 3 files"); + await page.locator("[data-untrusted-entry]").click(); + const list = page.locator("[data-untrusted-list]"); + await list.locator("[data-mark-row]").first().waitFor(); + expect(await list.textContent()).toContain("Files you or others marked. Doesn't list other untrusted sources."); + const rows = await list.locator("[data-mark-row]").evaluateAll(elements => elements.map(element => element.getAttribute("data-mark-row"))); + expect(rows, "OWNER_MISSING_FIRST_THEN_NEWEST").toEqual([LETTER, MESSAGE, HOSTILE]); + expect(await list.locator(`[data-mark-row="${LETTER}"]`).textContent()).toContain("missing · marked 12 Jul"); + + await list.locator(`[data-mark-row="${LETTER}"]`).click(); + await dialog(page).getByText("Missing file").waitFor(); + expect(await focusedName(page), "MISSING_DIALOG_FOCUS_CLOSE").toBe("Close"); + expect(await dialog(page).textContent()).toContain("brain-kit doesn't follow moves, so a moved copy is not marked."); + await noHorizontalScroll(page, "missing dialog"); + await targetsAtLeast44(page, "[data-untrusted-body] [role=button]", "missing dialog"); + await page.locator("[data-missing-close] [role=button]").click(); + await page.waitForFunction((path) => document.activeElement?.getAttribute("data-mark-row") === path, LETTER); + + await list.locator(`[data-mark-row="${LETTER}"]`).click(); + await dialog(page).getByRole("button", { name: "Clear old mark" }).click(); + await dialog(page).getByText("Clear the old mark?").waitFor(); + expect(await focusedName(page)).toBe("Cancel"); + await dialog(page).getByRole("button", { name: "Clear old mark" }).click(); + await page.waitForFunction(() => document.querySelector("[data-untrusted-announcer]")?.textContent === "Untrusted mark cleared"); + await page.waitForFunction((path) => document.activeElement?.getAttribute("data-mark-row") === path, MESSAGE); + expect(app!.db.query("SELECT path FROM untrusted_marks ORDER BY path").all().map(row => (row as { path: string }).path)).toEqual([HOSTILE, MESSAGE]); + + // Clearing the present mark: confirmation copy, then the same button becomes Mark. + if (width < 900) await page.evaluate(() => (window as unknown as { __marks: { collapseTree(): void } }).__marks.collapseTree()); + await clear.click(); + await dialog(page).getByText("Clear the untrusted mark?").waitFor(); + expect(await dialog(page).textContent()).toContain("A chat can still be untrusted for other reasons."); + await dialog(page).getByRole("button", { name: "Clear mark" }).click(); + await page.waitForFunction(() => document.querySelector("[data-untrusted-announcer]")?.textContent === "Untrusted mark cleared"); + await page.waitForFunction(() => document.activeElement?.getAttribute("aria-label") === "Mark untrusted"); + expect(await page.locator("[data-untrusted-cue]").count()).toBe(0); + // Marking as the owner: focus stays on the same button, now Clear. + await page.getByRole("button", { name: "Mark untrusted", exact: true }).click(); + const ownerBody = await dialog(page).textContent(); + expect(ownerBody, "OWNER_DIALOG_NO_READER_LINES").not.toContain("Only the owner can clear a mark."); + await dialog(page).getByRole("button", { name: "Mark untrusted" }).click(); + await page.waitForFunction(() => document.activeElement?.getAttribute("aria-label") === "Untrusted: clear mark"); + expect(outside).toEqual([]); + } finally { await context.close(); } + }, 60_000); + } + + test("races, refusals, uncertain replies and a file switch settle from the host only", async () => { + const { page, context, sent } = await open("reader", 1440, 900, "dark"); + try { + // Already marked: another session marks first. + await openFile(page, LOOM); + await page.getByRole("button", { name: "Mark untrusted", exact: true }).click(); + expect((await api("owner", "PUT", LOOM)).status).toBe(200); + await dialog(page).getByRole("button", { name: "Mark untrusted" }).click(); + await page.waitForFunction(() => document.querySelector("[data-untrusted-announcer]")?.textContent === "This file was already marked untrusted."); + expect(await api("owner", "DELETE", LOOM).then(response => response.json())).toEqual({ status: "cleared" }); + + // A refusal keeps the dialog, with the access copy. + await openFile(page, LOOM); + await page.getByRole("button", { name: "Mark untrusted", exact: true }).waitFor(); + await page.route("**/api/files/untrusted", route => route.request().method() === "PUT" ? route.fulfill({ status: 403, json: { error: "forbidden" } }) : route.fallback()); + await page.getByRole("button", { name: "Mark untrusted", exact: true }).click(); + await dialog(page).getByRole("button", { name: "Mark untrusted" }).click(); + await dialog(page).getByText("You don't have access to this file any more. Nothing was marked.").waitFor(); + await page.unroute("**/api/files/untrusted"); + await page.locator("[data-untrusted-body]").getByRole("button", { name: "Cancel" }).click(); + + // A dropped reply that the host did apply: Checking…, then the host's result. + let release: () => void = () => {}; + const held = new Promise(done => { release = done; }); + await page.route("**/api/files/untrusted", async route => { + if (route.request().method() !== "PUT") return route.fallback(); + await route.fetch(); + await held; + return route.abort("failed"); + }); + await page.getByRole("button", { name: "Mark untrusted", exact: true }).click(); + await dialog(page).getByRole("button", { name: "Mark untrusted" }).click(); + expect(await page.locator("[data-untrusted-cue]").count(), "NO_OPTIMISTIC_CUE").toBe(0); + release(); + await page.waitForFunction(() => document.querySelector("[data-untrusted-announcer]")?.textContent === "penelope-loom.md marked untrusted"); + await page.unroute("**/api/files/untrusted"); + await page.locator("[data-untrusted-cue]").waitFor(); + expect(await api("owner", "DELETE", LOOM).then(response => response.json())).toEqual({ status: "cleared" }); + + // A reply lost before the host saw it: nothing changed, and Try again repeats the same intent. + await openFile(page, MESSAGE); + await openFile(page, LOOM); + await page.route("**/api/files/untrusted", route => route.request().method() === "PUT" ? route.abort("failed") : route.fallback()); + await page.getByRole("button", { name: "Mark untrusted", exact: true }).click(); + await dialog(page).getByRole("button", { name: "Mark untrusted" }).click(); + await dialog(page).getByText("Couldn't reach your brain. Nothing has changed yet.").waitFor(); + // The check itself failing: Still couldn't check. + await page.unroute("**/api/files/untrusted"); + await page.route("**/api/files/untrusted?*", route => route.abort("failed")); + await page.route("**/api/files/untrusted", route => route.request().method() === "PUT" ? route.abort("failed") : route.fallback()); + await dialog(page).getByRole("button", { name: "Try again" }).click(); + await dialog(page).getByText("Still couldn't check. Try again.").waitFor(); + await page.unroute("**/api/files/untrusted?*"); + await page.unroute("**/api/files/untrusted"); + const before = sent.length; + await dialog(page).getByRole("button", { name: "Try again" }).click(); + await page.waitForFunction(() => document.querySelector("[data-untrusted-announcer]")?.textContent === "penelope-loom.md marked untrusted"); + expect(sent.slice(before), "RETRY_REPEATS_MARK").toEqual(["PUT "]); + + // Switching files closes the dialog and sends nothing. + await api("owner", "DELETE", LOOM); + await openFile(page, MESSAGE); + await openFile(page, LOOM); + await page.getByRole("button", { name: "Mark untrusted", exact: true }).click(); + const count = sent.length; + await openFile(page, MESSAGE); + await page.waitForFunction(() => !document.querySelector("dialog[open]")); + expect(sent.slice(count), "FILE_SWITCH_SENDS_NOTHING").toEqual([]); + + // Gone before marking: the viewer reloads to File not found. + await openFile(page, LOOM); + await page.getByRole("button", { name: "Mark untrusted", exact: true }).click(); + await rm(resolve(brain, LOOM)); + await dialog(page).getByRole("button", { name: "Mark untrusted" }).click(); + await dialog(page).getByText("There's no file at this path any more. Nothing was marked.").waitFor(); + await page.locator("[data-untrusted-body]").getByRole("button", { name: "Cancel" }).click(); + await page.getByRole("heading", { name: "File not found", exact: true }).waitFor(); + expect(await page.locator("[data-untrusted-cue], [data-untrusted-control]").count()).toBe(0); + + // A deep link to the missing letter: File not found, no cue and no mark details. + await openFile(page, LETTER); + await page.getByRole("heading", { name: "File not found", exact: true }).waitFor(); + expect(await page.locator("[data-untrusted-cue], [data-untrusted-control], [data-untrusted-unknown]").count()).toBe(0); + } finally { await context.close(); } + }, 90_000); + + test("owner clear races and refusal: already cleared, then only-the-owner copy keeps the cue", async () => { + const { page, context } = await open("owner", 1440, 900, "light"); + try { + await openFile(page, MESSAGE); + await page.getByRole("button", { name: "Untrusted: clear mark" }).click(); + expect((await api("owner", "DELETE", MESSAGE)).status).toBe(200); + await dialog(page).getByRole("button", { name: "Clear mark" }).click(); + await page.waitForFunction(() => document.querySelector("[data-untrusted-announcer]")?.textContent === "This mark was already cleared."); + await api("owner", "PUT", MESSAGE); + await openFile(page, LOOM); + await openFile(page, MESSAGE); + await page.route("**/api/files/untrusted?*", route => route.request().method() === "DELETE" ? route.fulfill({ status: 403, json: { error: "owner_required" } }) : route.fallback()); + await page.getByRole("button", { name: "Untrusted: clear mark" }).click(); + await dialog(page).getByRole("button", { name: "Clear mark" }).click(); + await dialog(page).getByText("Only the owner can clear this mark. Nothing changed.").waitFor(); + expect(await page.locator("[data-untrusted-cue]").count(), "REFUSED_CLEAR_KEEPS_CUE").toBe(1); + } finally { await context.close(); } + }, 60_000); + + test("unknown, unsupported and forbidden lookups draw no control", async () => { + const { page, context } = await open("owner", 1440, 900, "dark"); + try { + await page.route("**/api/files/untrusted?*", route => route.fulfill({ status: 500, json: { error: "internal_error" } })); + await openFile(page, MESSAGE); + await page.getByText("Couldn't check the untrusted mark").waitFor(); + expect(await page.locator("[data-untrusted-control]").count(), "UNKNOWN_NO_CONTROL").toBe(0); + await page.unroute("**/api/files/untrusted?*"); + await page.getByRole("button", { name: "Retry" }).click(); + await page.getByRole("button", { name: "Untrusted: clear mark" }).waitFor(); + + await page.route("**/api/files/content?*", route => route.fulfill({ status: 403, json: { error: "forbidden" } })); + await openFile(page, LOOM); + await page.getByRole("heading", { name: "This file isn't available with your current access." }).waitFor(); + expect(await page.locator("[data-untrusted-cue], [data-untrusted-control], [data-untrusted-unknown]").count(), "FORBIDDEN_NO_CUE").toBe(0); + } finally { await context.close(); } + const unsupported = await open("owner", 1440, 900, "light"); + try { + await unsupported.page.route("**/api/files/untrusted**", route => route.fulfill({ status: 404, contentType: "text/plain", body: "404 Not Found" })); + await unsupported.page.reload(); + await unsupported.page.waitForFunction("window.__marks !== undefined"); + await openFile(unsupported.page, MESSAGE); + await unsupported.page.getByRole("button", { name: "Copy path" }).waitFor(); + await Bun.sleep(200); + expect(await unsupported.page.locator("[data-untrusted-cue], [data-untrusted-control], [data-untrusted-unknown], [data-untrusted-entry]").count(), "UNSUPPORTED_NOTHING").toBe(0); + } finally { await unsupported.context.close(); } + }, 60_000); +}); diff --git a/packages/ui-sdk/src/server/outward-policy.ts b/packages/ui-sdk/src/server/outward-policy.ts index 64c3d0c485..e7adfd197d 100644 --- a/packages/ui-sdk/src/server/outward-policy.ts +++ b/packages/ui-sdk/src/server/outward-policy.ts @@ -104,7 +104,7 @@ function workerOutwardRules(egressActive: boolean): string[] { /** The untrusted-input rules (G6), and this session's taint once one is recorded. */ function untrustedInputNote(egressActive: boolean, taint: WorkerSessionTaint | null): string[] { return ["# Untrusted input", - `WebFetch/WebSearch and web tool results, reads under .brain-ui/inbox/ or workspaces/, results from any MCP server other than brain-kit's own, and Bash calls that fetch or cannot be classified as network-free taint the session${egressActive ? ", as does any connection other than the inference relay" : ""}.`, + `WebFetch/WebSearch and web tool results, reads under .brain-ui/inbox/ or workspaces/ or of a file the user marked untrusted, results from any MCP server other than brain-kit's own, and Bash calls that fetch or cannot be classified as network-free taint the session${egressActive ? ", as does any connection other than the inference relay" : ""}.`, "A tainted session stays tainted: every outward action asks for approval even when outward.allow matches, and its steering-file changes are flagged in the turn journal.", egressActive ? "While tainted, this turn's egress reaches only the policy's taint.egress.allow hosts, hosts this session already contacted, and the inference relay." : "Tainted egress is not enforced for this turn: it does not run on the host egress proxy.", diff --git a/packages/ui-server/migrations/074_untrusted_marks.sql b/packages/ui-server/migrations/074_untrusted_marks.sql new file mode 100644 index 0000000000..9909d19be8 --- /dev/null +++ b/packages/ui-server/migrations/074_untrusted_marks.sql @@ -0,0 +1,9 @@ +-- Files the user marked untrusted (G6, #2673), keyed by brain-relative path. +-- A mark outlives its file: a moved or deleted path keeps its record (rename +-- ruling B). `marked_by` names the principal without a foreign key, so +-- pruning an expired principal keeps the mark and only loses its label. +CREATE TABLE untrusted_marks ( + path TEXT PRIMARY KEY, + marked_at INTEGER NOT NULL, + marked_by TEXT +); diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 5b1a2d1059..e327b14368 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -4,7 +4,10 @@ import { WORKER_AREA_ROOT } from "@schlessera/brain-ui-sdk/internal"; import { commandTaintSource } from "./command-taint.js"; export type IngestionSource = "web_fetch" | "web_search" | "staged_share" | "workspace_read" | "mcp_document" - | "fetching_command" | "unclassified_command"; + | "user_marked" | "fetching_command" | "unclassified_command"; + +/** Whether a brain-relative path carries the user's untrusted mark (#2673). */ +export type MarkedLookup = (path: string) => boolean; /** Claude's and pi-web-access's web tools. */ const WEB_TOOLS: Record = { WebFetch: "web_fetch", WebSearch: "web_search", fetch_content: "web_fetch", web_search: "web_search" }; @@ -47,8 +50,36 @@ function pathSource(path: string, brainPath: string | undefined): IngestionSourc return anyArea(absolute); } +/** + * The brain-relative record key a file-tool path names, or null when it names + * nothing inside the brain. A relative path resolves against the brain (the + * worker's cwd); an absolute one only counts below the brain's host path, so + * a view the host cannot name is not matched against marks. + */ +function brainRelative(path: string, brainPath: string | undefined): string | null { + if (!path) return null; + let relative: string; + if (!path.startsWith("/")) relative = posix.normalize(path); + else { + const root = brainPath && posix.normalize(brainPath).replace(/\/$/, ""); + const absolute = posix.normalize(path); + if (!root || !absolute.startsWith(root + "/")) return null; + relative = absolute.slice(root.length + 1); + } + relative = relative.replace(/\/$/, ""); + return relative && relative !== "." && relative !== ".." && !relative.startsWith("../") ? relative : null; +} + +/** The area a path reads, else whether it names a file the user marked untrusted. */ +function fileSource(path: string, brainPath: string | undefined, marked: MarkedLookup | undefined): IngestionSource | null { + const area = pathSource(path, brainPath); + if (area || !marked) return area; + const relative = brainRelative(path, brainPath); + return relative !== null && marked(relative) ? "user_marked" : null; +} + /** The source a call's input already establishes, before its result arrives. */ -export function inputTaintSource(tool: string, input: unknown, brainPath?: string): IngestionSource | null { +export function inputTaintSource(tool: string, input: unknown, brainPath?: string, marked?: MarkedLookup): IngestionSource | null { const command = commandTaintSource(tool, input); if (command) return command; if (WEB_TOOLS[tool]) return WEB_TOOLS[tool]; @@ -57,14 +88,14 @@ export function inputTaintSource(tool: string, input: unknown, brainPath?: strin // brain-kit's own document readers can still name a file in an untrusted area. const key = FILE_TOOLS[tool.replace(/^mcp__brain(?:-ui)?__/, "")]; const path = key && input && typeof input === "object" ? (input as Record)[key] : undefined; - return typeof path === "string" ? pathSource(path, brainPath) : null; + return typeof path === "string" ? fileSource(path, brainPath, marked) : null; } -/** A search from an ancestor directory taints when its output names a file in an untrusted area. */ -export function outputTaintSource(tool: string, output: string, brainPath?: string): IngestionSource | null { +/** A search from an ancestor directory taints when its output names a file in an untrusted area or a marked file. */ +export function outputTaintSource(tool: string, output: string, brainPath?: string, marked?: MarkedLookup): IngestionSource | null { if (!SEARCH_TOOLS.has(tool)) return null; for (const line of output.split("\n")) { - const source = pathSource(line.trim().split(":")[0]!, brainPath); + const source = fileSource(line.trim().split(":")[0]!, brainPath, marked); if (source) return source; } return null; diff --git a/packages/ui-server/src/activity/recorder.ts b/packages/ui-server/src/activity/recorder.ts index 3bb51b4c09..261a471b14 100644 --- a/packages/ui-server/src/activity/recorder.ts +++ b/packages/ui-server/src/activity/recorder.ts @@ -43,7 +43,8 @@ import { createGovernanceWrites, type GovernanceWrites } from "../governance/eve import { recordFirstTaint } from "../governance/session-taint.js"; import { redactCredentials, type RuntimeStatus } from "./runtime-status.js"; -import { inputTaintSource, outputTaintSource, type IngestionSource } from "./ingestion-taint.js"; +import { inputTaintSource, outputTaintSource, type IngestionSource, type MarkedLookup } from "./ingestion-taint.js"; +import { isMarkedUntrusted } from "../files/untrusted-marks.js"; import { MAX_PROVIDER_UNAVAILABLE_PER_TURN, providerUnavailablePayloads } from "../governance/provider-unavailable.js"; import type { AwaitableActivityStore, SpanOutcome, SpanUsage } from "./store.js"; import { orderedWrites } from "./store-writes.js"; @@ -230,6 +231,15 @@ export function createTurnRecorder( const governanceDb = deps.governanceDb, record = deps.governance; const firstTaint = deps.governanceWrites ? (input: GovernanceEventInput<"taint">) => deps.governanceWrites!.firstTaint(input) : governanceDb && record ? (input: GovernanceEventInput<"taint">) => { recordFirstTaint(governanceDb, input, record); return Promise.resolve(); } : undefined; + // A file the user marked untrusted (#2673), read when the call completes. A + // lookup that fails counts as marked: erring towards taint only tightens rules. + const marked: MarkedLookup | undefined = governanceDb ? path => { + try { return isMarkedUntrusted(governanceDb, path); } + catch (error) { + log?.emit({ severityText: "WARN", body: `untrusted mark lookup failed: ${error instanceof Error ? error.message : String(error)}` }); + return true; + } + } : undefined; const govern = (input: GovernanceEventInput) => { const committed = deps.governance?.(input); if (committed instanceof Promise) writes.after(() => committed); @@ -323,7 +333,7 @@ export function createTurnRecorder( break; } case "tool_use_complete": { - if (turn.origin !== "autonomous") ingestions.set(msg.toolUseId, { source: inputTaintSource(msg.toolName, msg.input, deps.brainPath), tool: msg.toolName }); + if (turn.origin !== "autonomous") ingestions.set(msg.toolUseId, { source: inputTaintSource(msg.toolName, msg.input, deps.brainPath, marked), tool: msg.toolName }); const traced = traceCall(msg.toolUseId, msg.toolName); if (traced) traced.input = boundedInput(msg.input); // The complete input object in one frame — tool_input_delta @@ -346,7 +356,7 @@ export function createTurnRecorder( const traced = calls.get(msg.toolUseId); const ingestion = ingestions.get(msg.toolUseId); ingestions.delete(msg.toolUseId); - const source = ingestion && (ingestion.source ?? outputTaintSource(ingestion.tool, msg.output, deps.brainPath)); + const source = ingestion && (ingestion.source ?? outputTaintSource(ingestion.tool, msg.output, deps.brainPath, marked)); if (ingestion && source && !traced?.denied && firstTaint && deps.governance) { const untracked = (error: unknown) => { log?.emit({ severityText: "WARN", body: `taint not recorded: ${error instanceof Error ? error.message : String(error)}` }); diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index be0eea1fc4..82f9abf59b 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1045,7 +1045,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise; +export type UntrustedMarkWrites = { [K in keyof Operations]: (...args: Parameters) => Promise> }; + +export function createUntrustedMarkWrites(db: Database, writer?: SqliteWriter): UntrustedMarkWrites { + const call = procedureCaller(db, { url, setup }, undefined, writer); + return { + mark: (...args) => call("mark", ...args), + clear: (...args) => call("clear", ...args), + }; +} diff --git a/packages/ui-server/src/files/untrusted-marks.ts b/packages/ui-server/src/files/untrusted-marks.ts new file mode 100644 index 0000000000..37b955fa1e --- /dev/null +++ b/packages/ui-server/src/files/untrusted-marks.ts @@ -0,0 +1,62 @@ +/** + * Files the user marked untrusted (G6, #2673). A mark is a host record keyed + * by the brain-relative path, kept in the server database rather than + * `brain.db`, so neither a restart nor `brain index --force` drops it. A file + * that moves or disappears keeps its old-path record; nothing follows a + * rename (maintainer ruling B, 2026-10-23). + */ +import type { Database } from "bun:sqlite"; +import { posix } from "node:path"; + +export interface UntrustedMark { + path: string; + markedAt: number; + /** The marking principal's id, or null when it was never known. */ + markedBy: string | null; + /** That principal's label while it is still on record. */ + markedByLabel: string | null; +} + +/** + * The record key for a brain-relative path, or null when the path cannot + * name a file in the brain. `./a` and `a//b` name the same record as `a` and + * `a/b`; the HTTP routes resolve the path against the brain before writing. + */ +export function markKey(path: string): string | null { + // The same syntax `safeResolve` refuses for a read. + if (!path || path.startsWith("/") || path.includes("\0") || path.includes("\\") || path.includes(":")) return null; + const normalized = posix.normalize(path).replace(/\/$/, ""); + if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null; + return normalized; +} + +const SELECT = `SELECT m.path, m.marked_at AS markedAt, m.marked_by AS markedBy, p.label AS markedByLabel + FROM untrusted_marks m LEFT JOIN principals p ON p.id = m.marked_by`; + +export function getUntrustedMark(db: Database, path: string): UntrustedMark | null { + return db.query(`${SELECT} WHERE m.path = ?`).get(path) as UntrustedMark | null; +} + +/** Every mark, newest first. */ +export function listUntrustedMarks(db: Database): UntrustedMark[] { + return db.query(`${SELECT} ORDER BY m.marked_at DESC, m.path`).all() as UntrustedMark[]; +} + +/** Whether a brain-relative path is marked: the recorder's lookup. */ +export function isMarkedUntrusted(db: Database, path: string): boolean { + return db.query("SELECT 1 FROM untrusted_marks WHERE path = ?").get(path) !== null; +} + +/** The record writes. Each reports whether it changed anything, so a race is told apart from a change. */ +export function untrustedMarkOperations(db: Database) { + return { + mark(path: string, principalId: string | null, at: number): "marked" | "already_marked" { + const inserted = db.query("INSERT INTO untrusted_marks (path, marked_at, marked_by) VALUES (?, ?, ?) ON CONFLICT(path) DO NOTHING") + .run(path, at, principalId); + return inserted.changes > 0 ? "marked" : "already_marked"; + }, + clear(path: string): "cleared" | "already_cleared" { + return db.query("DELETE FROM untrusted_marks WHERE path = ?").run(path).changes > 0 ? "cleared" : "already_cleared"; + }, + }; +} diff --git a/packages/ui-server/src/routes/files.ts b/packages/ui-server/src/routes/files.ts index 5819ee42e5..0f467a9122 100644 --- a/packages/ui-server/src/routes/files.ts +++ b/packages/ui-server/src/routes/files.ts @@ -1,8 +1,15 @@ import type { Logger } from "@opentelemetry/api-logs"; import { realpath, stat } from "node:fs/promises"; -import { Hono } from "hono"; +import { Hono, type Context } from "hono"; +import type { Database } from "bun:sqlite"; import { FILE_SIZE_CAP_BYTES } from "@schlessera/brain-ui-sdk/protocol"; +import type { AppEnv } from "../app-env.js"; +import type { Principal } from "../db/principals.js"; +import { getUntrustedMark, listUntrustedMarks, markKey, type UntrustedMark } from "../files/untrusted-marks.js"; +import { createUntrustedMarkWrites } from "../files/untrusted-mark-writes.js"; +import type { SqliteWriter } from "../db/write-worker.js"; import { + safeResolve, listDirectory, readFileContent, resolveAncestors, @@ -129,11 +136,50 @@ async function rangeResponse( return new Response(null, { status: 416, headers: { ...headers, "Content-Range": `bytes */${known}` } }); } -export function createFilesRoutes(deps: { brainRoot: string; log?: Logger }): Hono { +/** + * Who may clear an untrusted mark and see retained missing records and marker + * labels (#2673, authority ruling B): the human owner, by the same predicate + * the storage and history routes use. Every other authenticated principal is + * a reader. + */ +function isHumanOwner(principal: Principal | undefined): boolean { + return principal !== undefined && (principal.kind === "owner" || principal.kind === "ambient"); +} + +/** + * Whether `path` names a file this request may read: the `GET /files/content` + * rule, without reading it. A path that no longer resolves inside the brain + * (a parent became a link out of it) is as unreadable as a missing one. + */ +async function readableFile(path: string, brainRoot: string): Promise { + try { return (await stat(await safeResolve(path, brainRoot))).isFile(); } + catch (err) { if (err instanceof PathEscapeError || (err as NodeJS.ErrnoException).code) return false; throw err; } +} + +/** + * A mark as one principal may see it. Only the owner gets the marker's + * label, and `you` when the owner's own principal marked it; a reader's + * response carries no marker field at all (disclosure ruling A). + */ +function markView(mark: UntrustedMark, principal: Principal | undefined, missing: boolean) { + return { + path: mark.path, marked: true as const, markedAt: mark.markedAt, missing, + ...(isHumanOwner(principal) ? { markedBy: { label: mark.markedByLabel, you: mark.markedBy !== null && mark.markedBy === principal!.id } } : {}), + }; +} + +export interface FilesRouteDeps { + brainRoot: string; + log?: Logger; + /** The untrusted-mark records (#2673) and the hosted write worker they commit on. Absent: the mark routes are not mounted. */ + marks?: { db: Database; writer?: SqliteWriter }; +} + +export function createFilesRoutes(deps: FilesRouteDeps): Hono { const { brainRoot, log } = deps; let wikilinkBuild: Promise | null = null; let wikilinkCache: { generatedAt: number; map: Record } | null = null; - return new Hono() + const app = new Hono() .get("/files/tree", async (c) => { const path = c.req.query("path") ?? ""; try { @@ -257,4 +303,81 @@ export function createFilesRoutes(deps: { brainRoot: string; log?: Logger }): Ho return c.json(body, status); } }); + if (deps.marks) mountUntrustedMarks(app, brainRoot, deps.marks, log); + return app; +} + +/** + * The untrusted-mark routes (#2673). Marking needs the read access + * `GET /files/content` already grants and a file at the path; it grants + * nothing further. Clearing is the owner's alone, for present and missing + * records. A reader never learns of a record whose file is gone, nor who + * marked a file: those are filtered here, not in the UI. + */ +function mountUntrustedMarks(app: Hono, brainRoot: string, store: NonNullable, log?: Logger) { + const marks = { db: store.db, writes: createUntrustedMarkWrites(store.db, store.writer) }; + const failed = (c: Context, err: unknown) => { const { body, status } = errorResponse(err, log); return c.json(body, status); }; + /** The request's record key, after the same path validation as a read. */ + const keyFor = async (path: string | undefined) => { + if (!path) return { error: "missing_path" as const }; + const key = markKey(path); + if (key === null) throw new PathEscapeError(path); + return { key, readable: await readableFile(key, brainRoot) }; + }; + const detail = (key: string, readable: boolean, principal: Principal | undefined) => { + const mark = getUntrustedMark(marks.db, key); + const owner = isHumanOwner(principal); + if (!readable && !(owner && mark)) return null; + return mark ? { ...markView(mark, principal, !readable), canClear: owner } : { path: key, marked: false as const, canClear: owner }; + }; + + app.get("/files/untrusted", async (c) => { + try { + const target = await keyFor(c.req.query("path")); + if ("error" in target) return c.json(target, 400); + const view = detail(target.key, target.readable, c.get("principal")); + return view ? c.json(view) : c.json({ error: "not_found" }, 404); + } catch (err) { return failed(c, err); } + }); + + app.get("/files/untrusted/list", async (c) => { + const principal = c.get("principal"); + const owner = isHumanOwner(principal); + try { + const rows: ReturnType[] = []; + for (const mark of listUntrustedMarks(marks.db)) { + const readable = await readableFile(mark.path, brainRoot); + if (readable || owner) rows.push(markView(mark, principal, !readable)); + } + // Missing records first, because they need the owner's action; then newest first. + rows.sort((a, b) => Number(b.missing) - Number(a.missing) || b.markedAt - a.markedAt || a.path.localeCompare(b.path)); + return c.json({ marks: rows, canClear: owner }); + } catch (err) { return failed(c, err); } + }); + + app.put("/files/untrusted", async (c) => { + const body = await c.req.json().catch(() => null) as { path?: unknown } | null; + if (!body || typeof body !== "object" || Array.isArray(body)) return c.json({ error: "invalid_body" }, 400); + if (body.path !== undefined && typeof body.path !== "string") return c.json({ error: "invalid_path" }, 400); + try { + const target = await keyFor(body.path as string | undefined); + if ("error" in target) return c.json(target, 400); + if (!target.readable) return c.json({ error: "not_found" }, 404); + const principal = c.get("principal"); + const status = await marks.writes.mark(target.key, principal?.id ?? null, Date.now()); + return c.json({ status, mark: detail(target.key, true, principal) }); + } catch (err) { return failed(c, err); } + }); + + app.delete("/files/untrusted", async (c) => { + const principal = c.get("principal"); + if (!isHumanOwner(principal)) return c.json({ error: "owner_required" }, 403); + const path = c.req.query("path"); + if (!path) return c.json({ error: "missing_path" }, 400); + // A retained record is cleared by its key alone: its file may be gone. + const key = markKey(path); + if (key === null) return c.json({ error: "invalid_path" }, 400); + try { return c.json({ status: await marks.writes.clear(key) }); } + catch (err) { return failed(c, err); } + }); } diff --git a/packages/ui-server/tests/untrusted-marks.test.ts b/packages/ui-server/tests/untrusted-marks.test.ts new file mode 100644 index 0000000000..aa7b0c5e53 --- /dev/null +++ b/packages/ui-server/tests/untrusted-marks.test.ts @@ -0,0 +1,214 @@ +/** + * Files the user marks untrusted (#2673): the detector, the host's authority + * and disclosure rules on direct HTTP requests, persistence, the rename rule + * and the taint an interactive turn records when it reads a marked file. + */ +import { expect, test } from "bun:test"; +import { generateSignedCookie } from "hono/cookie"; +import { mkdirSync, renameSync, writeFileSync } from "node:fs"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { workerOutwardNote } from "@schlessera/brain-ui-sdk/internal"; +import { inputTaintSource, outputTaintSource } from "../src/activity/ingestion-taint"; +import { createPrincipal, type Principal } from "../src/db/principals"; +import { queryGovernanceEvents } from "../src/governance/events"; +import { createStaticBackendRegistry } from "../src/agent/backend"; +import { resolveServerConfig } from "../src/config/env"; +import { createRecordingObservability } from "../src/observability"; +import { createWsHandlers } from "../src/ws/connection"; +import type { WSContext } from "../src/ws/clients"; +import { createFixtureBrain } from "../../../scripts/captures/core-fixture.js"; +import { runCli } from "../../core/tests/cli-harness.ts"; +import { createFixtureApp } from "./helpers/native-app-fixture.js"; +import { httpContractApp } from "./helpers/http-contract-app"; +import { makeFakeBackend } from "./helpers/fake-backend"; + +const brain = "/srv/odysseus/brain"; +const LETTER = "inbox/letter-from-antinous.md"; +const MOVED = "people/suitors/antinous-letter.md"; +const MESSAGE = "inbox/message-from-eurymachus.md"; + +test("a file tool or search that reads a marked file is a user_marked source; other reads are not", () => { + const marked = (path: string) => path === MESSAGE; + for (const [tool, input] of [ + ["Read", { file_path: `${brain}/${MESSAGE}` }], ["Read", { file_path: `${brain}/./inbox/../${MESSAGE}` }], + ["Edit", { file_path: `${brain}/${MESSAGE}` }], ["Grep", { pattern: "Ithaca", path: MESSAGE }], + ["Glob", { pattern: "*.md", path: `./${MESSAGE}` }], ["read_file", { path: MESSAGE }], ["edit_file", { path: MESSAGE }], + ["grep", { pattern: "Ithaca", path: MESSAGE }], ["mcp__brain__brain_read", { path: MESSAGE }], + ] as const) expect(inputTaintSource(tool, input, brain, marked), `MARKED_SOURCE_${tool}_${JSON.stringify(input)}`).toBe("user_marked"); + for (const [tool, input] of [ + ["Read", { file_path: `${brain}/${LETTER}` }], ["Write", { file_path: `${brain}/${MESSAGE}` }], + // A view the host cannot name, and paths outside the brain, are not matched against marks. + ["Read", { file_path: `/home/odysseus/view/${MESSAGE}` }], ["Read", { file_path: `../${MESSAGE}` }], + ["Grep", { pattern: "Ithaca", path: "inbox" }], ["Bash", { command: `ls ${MESSAGE}` }], + ] as const) expect(inputTaintSource(tool, input, brain, marked), `MARKED_CLEAN_${tool}_${JSON.stringify(input)}`).toBeNull(); + // An untrusted area still names its own source first. + expect(inputTaintSource("Read", { file_path: `${brain}/workspaces/${MESSAGE}` }, brain, () => true)).toBe("workspace_read"); + // A search from an ancestor directory taints when its output names the marked file. + expect(outputTaintSource("Grep", `${brain}/notes/a.md\n${brain}/${MESSAGE}`, brain, marked), "MARKED_SEARCH_OUTPUT").toBe("user_marked"); + expect(outputTaintSource("grep", `${MESSAGE}:3: Ithaca`, brain, marked)).toBe("user_marked"); + expect(outputTaintSource("Glob", `${brain}/${LETTER}`, brain, marked)).toBeNull(); + // The capabilities note names marked files among the untrusted sources. + for (const egress of [false, true]) expect(workerOutwardNote(egress, null), "NOTE_NAMES_MARKED_FILES").toContain("or of a file the user marked untrusted"); +}); + +const SECRET = "untrusted-marks-fixture-secret-0123456789"; +async function passwordApp() { + const t = await httpContractApp({ env: { AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: "unused-fixture-hash", COOKIE_SECRET: SECRET, BRAIN_UI_ALLOW_LOOPBACK_ORIGIN: "1" } }); + for (const path of [LETTER, MESSAGE]) { + mkdirSync(join(t.brainPath, "inbox"), { recursive: true }); + writeFileSync(join(t.brainPath, path), `# ${path}\n\nA fictional message for Penelope, dated 2026-07-12.\n`); + } + const owner = createPrincipal(t.app.db, { authMethod: "password", label: "Safari on iPhone", ttlSeconds: 3600 }); + const agent = createPrincipal(t.app.db, { authMethod: "delegated", createdBy: owner.id, label: "Telemachus agent", ttlSeconds: 3600 }); + expect(agent.kind).toBe("agent"); + const as = async (principal: Principal) => { + const cookie = (await generateSignedCookie("brain_ui_session", principal.id, SECRET)).split(";")[0]!; + return (path: string, init: RequestInit = {}) => t.fetch(path, { ...init, headers: { cookie, origin: "http://localhost", host: "localhost", "content-type": "application/json" } }); + }; + return { t, owner, agent, asOwner: await as(owner), asReader: await as(agent) }; +} +const q = (path: string) => `?path=${encodeURIComponent(path)}`; +const mark = async (call: (path: string, init?: RequestInit) => Response | Promise, path: unknown) => + call("/api/files/untrusted", { method: "PUT", body: JSON.stringify({ path }) }); + +test("a reader with read access marks; only the owner clears; direct requests cannot bypass either", async () => { + const { t, asOwner, asReader, agent } = await passwordApp(); + try { + expect((await t.fetch(`/api/files/untrusted${q(MESSAGE)}`)).status, "MARK_ROUTES_NEED_AUTHENTICATION").toBe(401); + const before = await asReader(`/api/files/untrusted${q(MESSAGE)}`); + expect(await before.json()).toEqual({ path: MESSAGE, marked: false, canClear: false }); + + const marked = await mark(asReader, MESSAGE); + expect(marked.status, "READER_MARKS_READABLE_FILE").toBe(200); + const body = await marked.json() as { status: string; mark: Record }; + expect(body).toMatchObject({ status: "marked", mark: { path: MESSAGE, marked: true, missing: false, canClear: false } }); + expect(body.mark, "READER_RESPONSE_OMITS_MARKER").not.toHaveProperty("markedBy"); + expect(JSON.stringify(body)).not.toContain(agent.label); + expect(await (await mark(asReader, `./${MESSAGE}`)).json(), "SAME_RECORD_RACE").toMatchObject({ status: "already_marked" }); + + // Marking grants nothing: no file, no traversal, no other syntax. + expect((await mark(asReader, "inbox/no-such-letter.md")).status, "MARK_REFUSES_MISSING_FILE").toBe(404); + expect((await mark(asReader, "inbox")).status, "MARK_REFUSES_DIRECTORY").toBe(404); + for (const path of ["../outside.md", "/etc/passwd", "inbox/a:b.md"]) expect((await mark(asReader, path)).status, `MARK_REFUSES_${path}`).toBe(400); + expect((await mark(asReader, 7)).status).toBe(400); + expect(t.app.db.query("SELECT path FROM untrusted_marks ORDER BY path").all(), "REFUSALS_WROTE_NOTHING").toEqual([{ path: MESSAGE }]); + + const refused = await asReader(`/api/files/untrusted${q(MESSAGE)}`, { method: "DELETE" }); + expect(refused.status, "NON_OWNER_CLEAR_REFUSED").toBe(403); + expect(await refused.json()).toEqual({ error: "owner_required" }); + expect((await asOwner(`/api/files/untrusted${q(MESSAGE)}`)).status).toBe(200); + const owned = await (await asOwner(`/api/files/untrusted${q(MESSAGE)}`)).json(); + expect(owned, "OWNER_SEES_MARKER_LABEL").toMatchObject({ marked: true, canClear: true, markedBy: { label: "Telemachus agent", you: false } }); + + const cleared = await asOwner(`/api/files/untrusted${q(MESSAGE)}`, { method: "DELETE" }); + expect(await cleared.json(), "OWNER_CLEAR_SUCCEEDS").toEqual({ status: "cleared" }); + expect(await (await asOwner(`/api/files/untrusted${q(MESSAGE)}`, { method: "DELETE" })).json()).toEqual({ status: "already_cleared" }); + // Clearing grants no access: an unreadable path stays unreadable. + expect((await asReader(`/api/files/untrusted${q("../outside.md")}`)).status).toBe(400); + expect((await asReader(`/api/files/content${q(MESSAGE)}`)).status).toBe(200); + + await mark(asOwner, MESSAGE); + expect(await (await asOwner(`/api/files/untrusted${q(MESSAGE)}`)).json(), "OWNER_SEES_BY_YOU").toMatchObject({ markedBy: { label: "Safari on iPhone", you: true } }); + } finally { await t.close(); } +}); + +test("a moved file keeps its old-path mark, shown to the owner alone; the new path is not marked", async () => { + const { t, asOwner, asReader, owner, agent } = await passwordApp(); + try { + // The reader marks the letter itself, then the letter moves. + await mark(asReader, LETTER); + await mark(asOwner, MESSAGE); + mkdirSync(join(t.brainPath, "people/suitors"), { recursive: true }); + renameSync(join(t.brainPath, LETTER), join(t.brainPath, MOVED)); + + const ownerList = await (await asOwner("/api/files/untrusted/list")).json() as { marks: Array>; canClear: boolean }; + expect(ownerList.canClear).toBe(true); + expect(ownerList.marks.map(row => [row.path, row.missing]), "OWNER_LIST_MISSING_FIRST").toEqual([[LETTER, true], [MESSAGE, false]]); + expect(ownerList.marks[0]).toMatchObject({ markedBy: { label: agent.label, you: false } }); + expect(await (await asOwner(`/api/files/untrusted${q(LETTER)}`)).json(), "OWNER_MISSING_DETAIL").toMatchObject({ path: LETTER, marked: true, missing: true, canClear: true }); + + const readerResponse = await asReader("/api/files/untrusted/list"); + const readerText = await readerResponse.text(); + expect(JSON.parse(readerText), "READER_LIST_PRESENT_ONLY").toEqual({ canClear: false, marks: [{ path: MESSAGE, marked: true, markedAt: expect.any(Number), missing: false }] }); + expect(readerText, "READER_LIST_NO_MISSING_PATH").not.toContain("antinous"); + for (const label of [owner.label, agent.label, "markedBy", "\"you\""]) expect(readerText, `READER_LIST_NO_IDENTITY_${label}`).not.toContain(label); + const readerDetail = await asReader(`/api/files/untrusted${q(LETTER)}`); + expect(readerDetail.status, "READER_MISSING_DETAIL_REFUSED").toBe(404); + expect(await readerDetail.text()).not.toContain("marked"); + + // Rename ruling B: nothing follows the move. + expect(await (await asOwner(`/api/files/untrusted${q(MOVED)}`)).json(), "NEW_PATH_NOT_MARKED").toMatchObject({ path: MOVED, marked: false }); + expect((await asReader(`/api/files/untrusted${q(LETTER)}`, { method: "DELETE" })).status, "READER_CANNOT_CLEAR_MISSING").toBe(403); + expect(await (await asOwner(`/api/files/untrusted${q(LETTER)}`, { method: "DELETE" })).json(), "OWNER_CLEARS_MISSING").toEqual({ status: "cleared" }); + expect((await (await asOwner("/api/files/untrusted/list")).json() as { marks: unknown[] }).marks).toHaveLength(1); + } finally { await t.close(); } +}); + +async function until(check: () => boolean, diagnostic: () => unknown) { + const end = Date.now() + 10_000; + while (!check()) { if (Date.now() > end) throw new Error(JSON.stringify(diagnostic())); await Bun.sleep(5); } +} + +test("marks survive a restart and brain index --force; reading a marked file taints, clearing spares only new sessions", async () => { + const root = await mkdtemp(resolve(tmpdir(), "odysseus-untrusted-marks-")), brainPath = resolve(root, "brain"); + await createFixtureBrain(resolve(import.meta.dir, "../../.."), brainPath); + mkdirSync(join(brainPath, "inbox"), { recursive: true }); + for (const path of [LETTER, MESSAGE]) writeFileSync(join(brainPath, path), `# ${path}\n\nA fictional message for Penelope, dated 2026-07-12.\n`); + // Each prompt names the brain-relative file the fixture backend reads. + const backend = makeFakeBackend({ id: "claude", startTurn: async request => { + const sessionId = request.sessionId ?? `voyage-${request.turnId}`; + request.bridge.emit({ type: "session_info", sessionId, isNew: !request.sessionId }); + const file = request.prompt.trim(); + request.bridge.emit({ type: "tool_use_start", sessionId, toolUseId: `read-${request.turnId}`, toolName: "Read" }); + request.bridge.emit({ type: "tool_use_complete", sessionId, toolUseId: `read-${request.turnId}`, toolName: "Read", input: { file_path: join(brainPath, file) } }); + request.bridge.emit({ type: "tool_result", sessionId, toolUseId: `read-${request.turnId}`, output: "A fictional message for Penelope.", isError: false }); + request.bridge.emit({ type: "result", sessionId, outcome: "success", durationMs: 1, numTurns: 1, isError: false }); + } }); + const start = () => createFixtureApp({ config: resolveServerConfig({ BRAIN_PATH: brainPath, DB_PATH: resolve(root, "ui.db"), HOST: "127.0.0.1", AUTH_MODE: "none", NODE_ENV: "test", + BRAIN_UI_MODEL_DISCOVERY: "0", BRAIN_UI_PRICING_DISCOVERY: "0" }), registry: createStaticBackendRegistry([backend], backend.id), observability: createRecordingObservability() }); + const call = (app: Awaited>, path: string, init: RequestInit = {}) => + app.fetch(new Request(new URL(path, "http://localhost"), { ...init, headers: { origin: "http://localhost", host: "localhost", "content-type": "application/json" } })); + let app = await start(); + try { + expect((await mark((path, init) => call(app, path, init), LETTER)).status).toBe(200); + await app.close(); + renameSync(join(brainPath, LETTER), join(brainPath, "inbox/antinous-letter.md")); + const indexed = await runCli(brainPath, ["index", "--force"]); + expect(indexed.code, indexed.stderr).toBe(0); + app = await start(); + const list = await (await call(app, "/api/files/untrusted/list")).json() as { marks: Array<{ path: string; missing: boolean }> }; + expect(list.marks.map(row => [row.path, row.missing]), "MARK_SURVIVES_RESTART_AND_INDEX_FORCE").toEqual([[LETTER, true]]); + renameSync(join(brainPath, "inbox/antinous-letter.md"), join(brainPath, LETTER)); + expect((await mark((path, init) => call(app, path, init), MESSAGE)).status).toBe(200); + + const principal = createPrincipal(app.db, { authMethod: "password", label: "Odysseus marks", ttlSeconds: 60 }); + const chat = async (text: string, sessionId?: string) => { + const handlers = createWsHandlers(app.wsHost, principal), sent: string[] = []; + const ws = { send: (frame: string) => sent.push(frame), close() {}, readyState: 1 } as WSContext; + await handlers.onOpen(undefined as never, ws); + const before = sent.length; + handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text, requestId: `marks-${Math.random()}`, ...(sessionId ? { sessionId } : {}) }) } as MessageEvent, ws); + await until(() => sent.slice(before).some(frame => frame.includes("\"result\"")) && !app.wsHost.coordinator.isTurnActive(), () => sent); + handlers.onClose({ code: 1000 } as CloseEvent, ws); + const info = sent.map(frame => JSON.parse(frame) as { type: string; sessionId?: string }).find(frame => frame.type === "session_info" && frame.sessionId); + return info!.sessionId!; + }; + const taints = (sessionId: string) => queryGovernanceEvents(app.db, { sessionId, kinds: ["taint"], limit: 10 }).map(event => event.payload); + + const clean = await chat("notes/raft-reference.md"); + expect(taints(clean), "UNMARKED_READ_RECORDS_NOTHING").toEqual([]); + const tainted = await chat(MESSAGE); + expect(taints(tainted), "MARKED_READ_TAINTS").toEqual([{ source: "user_marked", tool: "Read", detail: null }]); + // The retained old-path record applies again once a file returns to it. + const returned = await chat(LETTER); + expect(taints(returned), "RETURNED_FILE_MARKED_AGAIN").toEqual([{ source: "user_marked", tool: "Read", detail: null }]); + + expect(await (await call(app, `/api/files/untrusted${q(MESSAGE)}`, { method: "DELETE" })).json()).toEqual({ status: "cleared" }); + const fresh = await chat(MESSAGE); + expect(taints(fresh), "CLEARED_MARK_SPARES_NEW_SESSION").toEqual([]); + await chat(MESSAGE, tainted); + expect(taints(tainted), "CLEARED_MARK_KEEPS_EXISTING_TAINT").toEqual([{ source: "user_marked", tool: "Read", detail: null }]); + } finally { await app.close(); await rm(root, { recursive: true, force: true }); } +}, 120_000); diff --git a/scripts/runtime-test-builds.ts b/scripts/runtime-test-builds.ts index 311d831fa6..dc856bcabb 100644 --- a/scripts/runtime-test-builds.ts +++ b/scripts/runtime-test-builds.ts @@ -4,7 +4,7 @@ import { isAbsolute, join, resolve } from "node:path"; export const runtimeTestBuilds: Readonly> = Object.fromEntries([ "answer-delivery", "approval-recovery", "artifact-recovery", "association-signout", "auth-expiry", "chat-focus", - "connection-continuity", "draft", "external-speech", "html-preview", "local-work", "parallel-sessions", "scratch-links", "tracker", "turn-journal", + "connection-continuity", "draft", "external-speech", "html-preview", "local-work", "parallel-sessions", "scratch-links", "tracker", "turn-journal", "untrusted-marks", ].map(name => [`packages/ui-react/tests/${name}-runtime.test.ts`, ["ui-react", "ui-server", "core"]])); const special: Readonly> = { "packages/ui-react/tests/haiku-model-runtime.test.ts": ["ui-react"], diff --git a/tests/runtime-build-selection.test.ts b/tests/runtime-build-selection.test.ts index 17adb72a5f..40ba5afdac 100644 --- a/tests/runtime-build-selection.test.ts +++ b/tests/runtime-build-selection.test.ts @@ -9,7 +9,7 @@ const root = resolve(import.meta.dir, ".."); test("every runtime package hook has one inventoried actual forward closure and no boolean bypass", async () => { const directory = join(root, "packages/ui-react/tests"); const hooks = readdirSync(directory).filter(name => name.endsWith(".test.ts") && readFileSync(join(directory, name), "utf8").includes("runtimePackageBuild(")); - expect(hooks).toHaveLength(17); + expect(hooks).toHaveLength(18); expect(hooks.map(name => `packages/ui-react/tests/${name}`).sort()).toEqual(Object.keys(runtimeBuildInventory).sort()); for (const file of hooks) { const text = readFileSync(join(directory, file), "utf8");