Repository navigation
fix(workspace): the Files tab — uploads at once, an honest Download, preview and delete (#2582, abilityai/trinity-enterprise#548) - #2608
Conversation
#2582, Abilityai/trinity-enterprise#548) Trinity Rule #1 — the docs land before the code. - requirements/core-agent.md: new §5.30 (the six ACs, the permission matrix, the storage decision, the stated limits); §5.20 AC-2/AC-4 amended — the Files signal now covers uploads and the refresh triggers widen. - requirements/content-files.md: §13.10's flat "Content-Disposition: attachment" bullet was stale against shipped ent#461; rewritten as the server-decided allowlist plus the one-way ?download=1. - architecture/integrations.md: the ent#461 delivery-policy paragraph records the one-way flag, why it is applied in the handlers, why it is parsed tolerantly, and that sig is a stored bearer token rather than an HMAC over the URL — so appending the flag cannot invalidate it. - architecture/api-endpoints.md: GET row updated, the missing HEAD row added, and the three new client-portal routes catalogued. - architecture/workspace.md + database.md: the upload announcement, the session-type-dependent matrix, and portal_file_dismissals with the three reasons its shape is what it is. - feature-flows: workspace-rail.md gains Slice 3; file-sharing-outbound.md corrected on three counts that were stale since ent#461 and #568; workspace-agents-at-the-centre.md and the index updated. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
…, Abilityai/trinity-enterprise#548) A Workspace viewer needs to remove an agent-shared file from THEIR list without revoking the share. agent_shared_files has no audience column, so portal_documents lists every active share of an agent to every rostered client; and the one generic per-user preference store is FK'd to users.id, which a portal principal has no row in. So: new storage. - tables.py / schema.py (DDL + the sweeper's file_id index) / migrations.py (SQLite) / migrations/versions/0058 (PostgreSQL) — Invariant #9, both tracks, single head confirmed by scripts/ci/check_alembic_heads.py. - agent_name is on the table FOR the AgentRef registration: agent_shared_files is a CASCADE ref, so deleting an agent hard-deletes its shares without going through the revoke sweeper — every dismissal keyed on those ids would be orphaned forever, and a table with no agent column would sidestep the parity guard that exists to catch exactly this. - Both purge paths in db/agent_shared_files.py delete the matching dismissals in the same transaction. - PK leads with client_email (the read is WHERE client_email = ?, once per participant per turn end); the file_id index serves the sweeper. test_agent_cleanup_parity + test_schema_parity: 8 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
…bs (#2582, Abilityai/trinity-enterprise#548) routers/files.py - GET and HEAD accept `download`, which may only ever force `attachment`. There is no ?disposition= and no way to force `inline` — that direction is ent#461's XSS allowlist. `_format_disposition`'s docstring now records the asymmetry, so the next reader does not resolve the apparent contradiction in the wrong direction. - Typed Optional[str] with a truthy check, NOT bool: a bool query param 422s on ?download= or ?download=x, and this is the public link opened from Telegram / WhatsApp / iOS — a malformed query it ignores today must keep being ignored. - Applied in the handlers, never in _validate_download_request, whose arg list is AST-pinned by test_file_download_no_session_gate. - A ranged PREFIX read no longer bumps download_count. The Workspace preview reads from byte 0, so without this every preview would inflate the owner's numbers and bury the audit log. The audit row is kept and made separable instead: details.ranged_prefix. - `# mcp: none` header (Invariant #13). client_portal - portal_owns_agent + `owned` on the roster row and the card: the SAME membership the card renders, so the UI's "Delete for everyone" and the service's gate cannot disagree. - Three routes: read one of your own uploads back (attachment, nosniff, no-store), delete one (idempotent), and remove/revoke an agent share. Each is _require_roster -> rate_limiter -> service -> audit. - TWO limiter tiers, env-tunable, per router.py's own stated rule — and the burst tier is 20, tighter than upload's, because this is the first time a rostered client can reach extract_from_agent (sync docker-py iteration on the global 4-worker pool, ~3x file size resident). Delete gets its own looser counter; an rm is not a get_archive. - portal_revoke_shared_file is access-first (roster 404 -> owner 403 -> row 404), never existence-then-access (Invariant #8), and 404s where its operator sibling 204s — enumeration-uniformity on an external surface, stated in the docstring so nobody aligns it. - portal_dismiss_shared_file does NOT validate the file_id (an existence oracle over every share in the install) and caps rows instead — the same fork set_chat_star already resolved. - _inbox_path_for: `_safe_filename(name) == name` or a uniform 404. Every shell use is shlex.quote plus `--`, because _safe_filename admits a leading hyphen. - _read_inbox guesses mime_type, and PortalUploadItem declares it — the row's FileIcon has been rendering the generic icon since it shipped because the response model stripped the undeclared field. - portal_documents drops dismissed ids and appends &download=1. Only this base URL gets the flag; the agent's chat link is untouched. test_ent79_portal_exposure: the two download_url assertions updated (the AC changes the URL) and the fixtures gained the table portal_documents now reads. 71 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
…te (#2582, Abilityai/trinity-enterprise#548) stores/clientPortal.js - uploadDocument queues the agent in a pending-agent SET. It is the ONE funnel all three upload surfaces already call, so notifying here makes "Files you sent" update before any agent reply WITHOUT touching PortalConversation.vue or PortalRoom.vue — the files the delivery sequence is serialized to protect. - A set, not a scalar, because both real gestures defeat a scalar: a sequential multi-file batch (a consumer joining the in-flight read gets a listing taken before the later files landed) and a room's fan-out across three DIFFERENT agents in one Vue flush window (only the last value survives). - fetchUploadBlob / deleteUpload / deleteDocument. stores/portalRailFeeds.js - noteUpload(agent): shares _fetchToken with refresh() (a refresh issued before the upload but resolving after it would otherwise silently clobber the fresh listing), coalesces leading AND trailing, and re-checks participation after the await. upload() now delegates to it rather than carrying a second read. portalRail.js / usePortalRailFeeds.js - filesSignalItems(documents, uploads) projects uploads onto the created_at key the Files dot already reads, and BOTH the signal and markSeen read it — one mechanism, or opening the tab would mark documents seen and leave the uploads' dot lit forever. The collections stay separate; only the signal merges them. - The pending set is drained by the owner: clear-then-read, so a note arriving mid-drain is a new entry rather than one this drain already claimed. portalFiles.js (new, pure — vitest pins environment: node) - flattenFiles owns BOTH render order and preview index; two orderings drift and the lightbox opens the wrong file, silently. `groups` is a parameter so ent#484's shared folder becomes a third entry with no structural change. - previewKind is extension-first for text: Python's mimetypes maps .ts to video/mp2t and .toml to nothing, and a shared .md arrives as text/plain. - neighbour skips non-previewable rows and stops at the ends. - errorDetail reads a Blob body first: with responseType 'blob' the usual err.response.data.detail idiom yields undefined, so the promised "server's named reason" would degrade to a generic line for exactly the new verbs. PortalFilePreview.vue (new) - Images ONLY through <img :src>, never inline <svg>, never v-html. - Text capped at 256 KB, fetched whole and sliced: CORS allow_headers omits Range, so a ranged preview dies silently cross-origin — and slicing keeps preview off the transfer-start counter path. The cap is stated in the UI. - Escape/arrows registered with { capture: true } + preventDefault, because the conversation's turn-cancel listener is on document in the BUBBLE phase. - v-if not v-show (the column and the mobile sheet are siblings), z-40 below ConfirmDialog's z-50, focus on the safe action, a Tab trap. - Never a blank modal: an unpreviewable type, an over-cap image AND a failed byte fetch all land on the same name/size/type + Download card. PortalRailFiles.vue - One v-for over the flat list; Download on both lists; the delete matrix mirrored off the roster card's `owned`; one ConfirmDialog with copy that restates the consequence per case; per-row InlineError with the server's reason. The dead single-file upload() (zero callers) is gone. - AC-3's `download` attribute is deliberately dropped: the control is a button driving a blob save and cannot carry it, and it is inert on a cross-origin anchor anyway — which is why the server-side flag exists. npm run test:unit: 101 files, 2238 passed. check:tokens OK. Both new files scan 0 raw_nongray / 0 hardcoded; loading gates total 70, equal to baseline. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
#2582, Abilityai/trinity-enterprise#548) Three new files, registered in tests/registry.json, plus the ent#461 guard extended so the asymmetry is asserted where a future widening would be edited past. test_2582_download_flag.py (35) - Proves the ASYMMETRY, not the feature: the flag forces attachment and NO input forces inline (?download=0 on text/html stays attachment). - ?download= / ?download=x / a repeated pair never 422 — the regression a bool annotation would have shipped on the public link ent#461 exists to keep opening from a phone. - HEAD agrees with GET; the sig survives the extra query pair; every other ent#461 header is carried through; the flag rides the 206 branch. - A ranged prefix read is audited ranged_prefix:true and does NOT bump download_count; a full-file range and a plain GET do; a mid-file seek does neither. Mutation control: forcing is_ranged_prefix=False fails that test. test_2582_portal_uploads.py (28) - The traversal 404 asserted at the handler AND through the mounted route, with a positive control — %2F shapes never match the route while %2E%2E reaches the handler, and a status-only test cannot tell the two apart. - Gate order (off-roster before any docker work), ent#308's collision on the read side, the translated extract_from_agent exceptions (its 404 echoes the container path), the deliberate 409/502 on a stopped/missing agent, rm -f -- with quoting proven by a name that needs it, and both limiter tiers. test_ent548_portal_share_delete.py (23) - The matrix, including the two cases that read as bugs without the rule: a non-owner admin is a viewer, and so is an owner on a portal token. - Access-first revoke proven with a call-recording monkeypatch (the row must not be read before the caller is authorized). Mutation control: reordering to existence-then-access fails it. - The dismissal's non-validation and its row cap as a PAIR, both purge paths, the AgentRef registration, both migration tracks, the PK's leading column. Mutation control: dropping the delete_for_agent purge fails it. 218 passed across the plan's verification set; alembic heads still 1. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
…iew rules (#2582, Abilityai/trinity-enterprise#548) portalRailFiles.spec.js (19) — and it found a real defect. The room fan-out test failed against my own first cut: `noteUpload` shared `_fetchToken` with `refresh()`, so three concurrent per-agent reads each invalidated the last and two of three listings were discarded. The two questions are different — "has the chat moved on?" is global, "is this agent's listing still the newest?" is per agent — so the store now carries a `_scopeToken` (participant changes and clear only) and a per-agent `_uploadEpoch` that `refresh()` snapshots before its awaits. That snapshot is also what stops a refresh issued before an upload and resolving after it from silently clobbering the fresh listing. Three mutation controls, each failing exactly its own test: - a shared counter instead of the per-agent epoch -> the fan-out test and the clobber test fail; - dropping the trailing re-fire -> the two-file batch test fails; - refresh ignoring the epoch snapshot -> the clobber test fails. The spec mounts the composable inside an effectScope stopped after each test: its watcher on the SHARED portal mock has no component to unmount it, so the oldest surviving watcher drained the queue against a previous test's Pinia store. Diagnosed from the symptom (uploads.scout undefined, a fan-out noting one agent), not guessed. Also pinned: the dot lights with Files CLOSED after one targeted read; opening the tab clears it (markSeen must read the same projection or the upload's dot stays lit forever); a non-participant bump does nothing; a hidden rail drops the note rather than queueing it; and source guards that PortalConversation.vue and PortalRoom.vue are untouched and know nothing of the rail. portalFiles.spec.js (47) — previewKind's extension-first rule with the three cases that motivate it (.md arriving as text/plain, .ts as video/mp2t, .toml as nothing), neighbour skipping and stopping, flattenFiles order equalling render order, the fileActions matrix failing closed, sameOriginPath on a RELATIVE url (the default install), the Blob error path, and the component's source guards: an <img> and no v-html, no Range, capture + preventDefault, revokeObjectURL, z-40 below ConfirmDialog, v-if not v-show, never a blank modal including on a failed fetch, zero raw palette classes and zero hex. portalRailFeeds.spec.js: the portal mock is now reactive() with the new fields, so the owner's watcher is not permanently inert there. 103 files, 2304 passed. check:tokens OK; loading gates 70 (= baseline); both new files 0 raw_nongray / 0 hardcoded. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
…e third Escape owner (#2582, Abilityai/trinity-enterprise#548) Two corrections and one addition from the tail steps. The docs written before implementation said the drain "shares the feed store's _fetchToken with refresh()". That is no longer true and was never sufficient: the room fan-out test proved a shared counter makes three concurrent per-agent reads invalidate each other. The mechanism is a _scopeToken (chat identity) plus a per-agent _uploadEpoch that refresh() snapshots before its awaits. Corrected in requirements/core-agent.md §5.30, architecture/workspace.md, feature-flows/workspace-rail.md (Slice 3, with the finding recorded as the reason) and the feature-flows.md changelog row. /sync-feature-flows also surfaced one flow the docs commit missed: chat-turn-cancellation.md owns the "what may take Escape" rule, and this PR adds a THIRD way of owning it — a rail-mounted overlay with no ref the conversation could name, taking Escape in the capture phase with preventDefault() rather than joining the per-surface overlay list. The known residual (the voice-call branch above shouldCancelOnEscape never consults defaultPrevented) is recorded there too, with a revision-history row, and the index row now points at it. The Slice 3 Testing block names the effectScope the spec needs and the three mutation controls. NOTE: /update-tests also updated .claude/agents/test-runner.md, which lives in the private .claude submodule (detached HEAD in this worktree) — that edit is left UNCOMMITTED there rather than creating a dangling commit and dirtying the gitlink. It needs landing in trinity-dev separately. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
… blob (#2582) Self-review finding. The first cut fetched every row as a blob and handed it back through a synthetic <a download> — which made the one-way ?download=1 flag decorative on the one surface it was added for, pulled up to 50 MB into the tab to save a file the browser could stream itself, and used exactly the programmatic-blob-save path the plan's own risk register flags as the classic iOS Safari failure, on a surface whose primary form is a phone sheet. An agent share now saves by an anchor click on its already-attachment URL. A client upload keeps the blob path, because it has no URL at all — no DB row, no token — which is the whole reason that path exists. AC-3's `download` attribute rides on that anchor as belt-and-braces; a browser ignores it cross-origin, which is precisely why the server-side flag is the mechanism rather than the attribute. Pinned by a source guard with a mutation control (collapsing the branch fails it). 103 files, 2305 passed. Docs corrected in §5.30 and workspace-rail.md. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
… turn (#2582, Abilityai/trinity-enterprise#548) Review finding. The preview modal took Escape in the capture phase with preventDefault() so it could not reach the conversation's bubble-phase turn-cancel listener — but the ConfirmDialog it raises has no key handling of its own, and nothing was added for it. So Escape on an open delete confirm dismissed nothing and arrived at shouldCancelOnEscape with defaultPrevented still false: the dialog stayed up and an in-flight turn was destroyed. Same shape, same reason. And because two capture listeners on `document` fire in registration order — the tab body mounts before the modal it opens — the preview now returns early on event.defaultPrevented, so one keystroke closes one overlay rather than both. Also documents the three PORTAL_FILE_* limiters in .env.example, beside the PORTAL_CHAT_*/PORTAL_UPLOAD_* pair they were modelled on. They are the only bound on the newly-exposed extract_from_agent path, and an operator cannot tune a knob they cannot discover. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
…/trinity-enterprise#548) Review finding. `portalRailFeeds.upload()` awaited `noteUpload()` itself while `clientPortal.uploadDocument()` — which it calls one line earlier — already queued the same agent for the rail owner's drain. The drain's note therefore arrived while the store's own read was in flight, became its trailing re-fire, and every drop-zone upload cost two container execs: eight for a four-file batch, on the shared 4-worker executor. The funnel is the mechanism, so let it be the only one. `upload()` now just sends. The two specs that pinned "delegates to noteUpload / re-reads its own agent" pinned the redundancy, so they now pin ZERO reads from `upload()` and move the "skips a chat that moved on" property onto `noteUpload`, where it actually lives. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
…nity-enterprise#548) The plan listed four things to file and the docs said "filed as a follow-up" while nothing existed on either tracker. Filed, and named where a reader lands: trinity#2598 Escape during a voice call ends the call even when an overlay already claimed the keystroke — PortalConversation.vue's voice branch sits above shouldCancelOnEscape and reads no defaultPrevented, so preventDefault() cannot reach it trinity#2599 the Workspace Files routes are uncatalogued in api-endpoints.md ent#549 shared files have no audience — every rostered client sees every share of an agent, ?sig= included; a dismissal is a preference, not authorization ent#550 a client upload has no DB row, which is why listing, download, delete, preview and MIME are five different mechanisms Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
An overlay that claims Escape must claim it for the dialogs it raises too — the 4.14 incomplete-fix class in UI clothes, and destructive-and-silent here because the wrong Escape kills billed work with no sign. Plus the two rules that fall out: capture listeners on `document` fire in registration order, not z-order; and a `preventDefault()` protocol is only as good as the consumer branch that reads it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HxW9tCTd3RnrWrxN8Yk8Bq
… it is computed (#2582) `_apply_download_flag` is a pure function, and the existing test pins its asymmetry exactly. But a pure function cannot tell you the route handed it the right `inline=`. The plausible regression — a handler deriving the disposition from the query parameter instead of from `is_inline_safe(row["mime_type"])` — passes every helper-level assertion in this file and ships stored XSS on a public token-gated link. So the route fixture is now parametrized by type, and a `text/html` row is asserted `attachment` across every flag value, on GET and HEAD both. Verified by mutation: deriving the disposition from the parameter turns 6 tests red, 5 of them these. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
, Abilityai/trinity-enterprise#548) The three knobs were read by `client_portal/router.py` and documented in `.env.example` while being forwarded by NONE of the three compose files, and neither prod nor hosted uses `env_file:` — so the advertised `.env` lever was inert on every install. That is worse than an undocumented knob: the operator sets it, sees no effect, and has nothing to debug. The #1056 / trinity-enterprise#31 packaging-gap class, caught at the `/validate-pr` gate. Proven by render rather than grep — `docker compose config` showed NONE before and honours `PORTAL_FILE_HOURLY_LIMIT=7` over the 100 default after, on both dev and prod. Wiring prod also broke #2280's wholesale env parity against `docker-compose.hosted.yml`, which is the guard doing its job: the gap was three files wide, not two. Guarded so it cannot recur: the knobs must be forwarded by all three composes, with defaults agreeing across them AND with the module default. #2433's guard is scoped to its own two vars by a hardcoded tuple, so extending it would have been the wrong home. Mutation-verified — dropping one var from prod turns 2 tests red. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…e-2582 # Conflicts: # docs/memory/feature-flows.md # docs/memory/learnings.md # docs/memory/requirements/core-agent.md
Manual Files sign-off completed — 2026-09-08Validated on the PR's isolated sibling stack after fix The remaining defect was real: the preview fetched the whole blob, while the backend excluded only partial reads from download counting. Shared-file preview requests now carry
Validation: 110 focused backend tests passed; 2,371 frontend tests passed (105 files); frontend build, design-token check, and diff whitespace check passed. New regression tests failed before the fix and passed afterward. Live browser revalidation recorded no uncaught page errors. This completes the Files sign-off checklist. The previously disclosed active-voice-call Escape follow-up remains separate from the chat-turn checks above; this is not a voice-call sign-off or a merge approval. |
…w doc collision with #2601, both sections kept)
… merge (#2609) — mechanical, per the merge-train note on the PR Three portal files were paid down on dev after this branch forked and PortalRailFiles.vue grew by 3 raw_gray via #2608; the ratchet's own 'baseline is exact' property then failed on the merge ref. Regenerated with the documented command and carried the PR's 'refrozen' block forward (the generator drops it), noting the one absorbed growth.
…eachable Two review items from #2619. **Alembic head fork (#2068 class).** `0058_agent_canvases_pinned` shared `down_revision = 0057` with #2608's `0058_portal_file_dismissals`, which has since landed on `dev` — two heads, and `alembic upgrade head` resolves its single target before applying anything, so EVERY revision merged since the fork stops arriving, not just one. Re-parented onto `0058_portal_file_dismissals` and renumbered to `0059` so the prefix keeps being a usable ordering cue; the id is not applied anywhere yet, so the rename costs nothing. `check_alembic_heads.py` reports 1 head. **`CANVAS_MAX_PER_AGENT` was inert (#1039 class).** The refusal message names the number, but the variable was read only from `os.getenv` in `models.py` and appeared in no compose file — so an operator following the refusal's own advice would raise a lever that never reaches the container. Wired into `docker-compose.yml`, `.prod.yml` and `.hosted.yml` (the last two launch standalone, no base merge / no `env_file`) plus `.env.example`. Related to #2619 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP
…) (#2609) * fix(ci): the raw-colour ratchet is enforced, not just documented (#2605) CLAUDE.md and the design-system contract both stated raw-palette usage was ratcheted — per-file counts may only shrink. Nothing ran it. No workflow invoked the scanner and no spec read the baseline, so the guarantee had been false since it was written and a contributor reading "baseline not grown" in the PR self-check was reasonably trusting a machine check that did not exist. THE GUARD. `tests/unit/rawColorRatchet.spec.js`, modelled on its working sibling `loadingGateRatchet.spec.js` so it rides `npm run test:unit` — which the frontend job already runs — and needs no new CI wiring to bite. Three properties, mutation-tested one at a time: 1. no file grows past its entry (added one amber class -> red) 2. a file with NO entry is held to ZERO raw_nongray (new file with bg-emerald-500 -> red) 3. the baseline is exact, so a paydown must lower its entry (inflated an entry -> red) (3) is what stops a stale ceiling silently re-permitting regressions back up to it; (2) is the "new code starts at zero" rule, which was prose only — an absent entry read as "unmeasured" rather than "must be clean", which is exactly how ten post-freeze files accumulated raw palette classes unchallenged. THE SCANNER became importable. It parsed `process.argv` at top level and `process.exit(2)`d without a path argument, so importing it would have killed the test run. `scanRawColors()` is now exported and the CLI sits behind an `import.meta.url` entry-point check. Verified behaviour-identical rather than assumed: same 196-file set, same totals, zero files differing, and `--json` output byte-identical against the pre-refactor script on the same tree. THE DRIFT, dispositioned deliberately and in its own PR as the issue asks. `views/Portal.vue`'s six `amber-*` classes from #2261 — which the issue names as the exact thing the ratchet exists to catch — are PAID DOWN to semantic `status-warning` tokens (6 -> 0), using the house idiom already in `BindRepoPanel.vue`. The rest is re-frozen, with every increase named inside `raw-color-baseline.json` itself so the record travels with the file: raw_nongray 737 -> 815 (+78; 4 baselined files, 10 post-freeze files) raw_gray 6938 -> 8699 (+1761) hardcoded_colors 383 -> 456 (+73 — NOT reported in the issue; almost all FleetGrid.vue 102 -> 156) 19 files had improved below their old entries; recording their real values is what gives the stale-ceiling check something true to compare against. Frontend suite: 2255 passed (102 files). Related to #2605 * merge-train: regenerate raw-color-baseline.json against dev after the merge (#2609) — mechanical, per the merge-train note on the PR Three portal files were paid down on dev after this branch forked and PortalRailFiles.vue grew by 3 raw_gray via #2608; the ratchet's own 'baseline is exact' property then failed on the merge ref. Regenerated with the documented command and carried the PR's 'refrozen' block forward (the generator drops it), noting the one absorbed growth. --------- Co-authored-by: sim <[email protected]>
…ile (ent#553) (#2619) * feat(canvas): delete, pin, search and a stated bound for the canvas pile An agent that uses its canvas the way ent#438 intends accumulates dozens: one per report, per topic, per run. The Workspace could only ever ADD to that pile — the client-portal surface had no delete at all, the only ordering was "newest updated", and nothing bounded the table. Two decisions, both by operator ruling 2026-09-08, recorded because each had a plausible alternative: **Deleting is owner-or-admin.** The answer ent#548 gives for files — the owner deletes the shared artifact. This NARROWS the platform DELETE route, which accepted any user with agent access; safe because no UI called it, so no workflow depended on the wider gate. A canvas is one shared surface with no per-user copy, so a non-owner has no "hide it from my list" middle ground: per AC #2 they see no control at all rather than one that 403s. Agents keep clearing their own (`clear_canvas`, the #918 self-gate). **The bound is a per-agent CAP, not a retention window.** ent#438 recorded "no retention window" because the composite key bounds rows per canvas — but `canvas_id` is agent-chosen, so the COUNT was unbounded; the axis was missed, not decided. `CANVAS_MAX_PER_AGENT` (100, env-tunable) is checked inside `upsert_canvas`'s insert branch, in the same transaction as the INSERT, so it is not a check-then-act race. Updating an existing canvas is NEVER refused — a cap that froze updates would punish exactly the agent that reuses ids — and the refusal is a named 409 telling the agent to retire one, never an eviction: deleting a person's surfaces on a timer is the #1638 failure direction. Both surfaces resolve permission through `db.can_user_share_agent`, the same predicate `assert_agent_owner` uses, so Agent Detail and the Workspace cannot disagree about who owns an agent. The Workspace learns it from `PortalAgentCard.can_manage_canvases` — the portal's only capability channel (#2128), since a portal principal cannot read `/api/settings/feature-flags` — and it fails closed. `pinned` (dual-track: `agent_canvases_pinned` + Alembic 0058, NOT NULL DEFAULT 0, no backfill) is written only by the human pin route and is deliberately absent from every agent-facing tool: `audience` is the agent's decision about who may read, `pinned` is the reader's about what they see first, and an agent that could pin itself to the top would defeat the ordering. A pin survives the agent rewriting the canvas. Living with many is `CanvasPanel.vue`, shared by both surfaces (one rendering layer, per ent#475): search once the list passes six, a height-bounded strip so a long list does not cost the rail its other tabs, and a Manage mode giving each row its age, stale mark, pin and delete. Decidable rules are pure in `canvasUtils.js` — vitest runs `environment: 'node'` with no mount harness, so a rule inside the SFC is one no test can reach. Bulk delete is a POST, not a body-carrying DELETE (bodies on DELETE are permitted-but-unreliable and this one is not optional), declared above the parameterized routes on both routers (Invariant #4), and it reports the ids that EXISTED rather than the ids requested so "3 of 5 removed" is sayable. Three pre-existing guards failed and each was right to: `empty_canvas` was missing the new field (a real bug in this change, fixed), the self-gate guard needed to learn the new gate's name, and the positional-read guard needed its synthetic row extended — that one exists precisely because `_row_to_summary` reads by index. Tests: 20 new backend cases (cap refusal + update-at-cap, pin ordering and survival, bulk scoping, the permission matrix on both surfaces, route ordering, dual-track migration parity, and that the MCP tools cannot pin) and ~24 vitest cases for the pure rules. Verified against a real database: the cap refuses the 4th of 3, updates still succeed at the cap, a pin outranks recency and survives a rewrite, and bulk delete returns only the ids that existed. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * feat(canvas): audit the single delete, cover the default canvas, document the lifecycle Closes the three acceptance criteria the first commit left open: * AC #1 asked for the deletion to be audited and only the BULK route was — the single-canvas route is the one a person actually clicks. Logged only when something was removed, since the route is idempotent and a repeat click would otherwise fill the trail with events where nothing happened. * AC #8: deleting the DEFAULT canvas is allowed, comes back empty on the next write, and frees a slot against the cap. `main` is the id both the MCP tools and the voice panel fall back to, so it is the one most likely to be deleted by accident and the one whose deletion must strand nobody. * AC #9: the user doc gains a "Removing canvases" section stating the permission rule, the cap, and that nothing is ever deleted to make room. Also records a latent pre-existing mismatch found while testing: `empty_canvas` returns None timestamps while `models.Canvas` requires strings, so `Canvas(**empty_canvas(...))` raises. Not live — its only caller declares no `response_model` — but adding one there would turn the voice teardown poll into a 500. Left as a comment where the next person to reach for that will meet it, rather than fixed out of scope. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * test(canvas): patch the cap where the live code reads it, not where the test imports it Two ent#553 tests passed in isolation and failed in a full-suite run: `test_the_cap_refuses_a_new_canvas_by_name` and `test_deleting_the_default_canvas_frees_a_slot_against_the_cap`. Order-dependence, not a defect in the feature. They patched `db.canvas.CANVAS_MAX_PER_AGENT` via a fresh `import db.canvas`. Some earlier test in the suite evicts that module from `sys.modules`, so the fresh import hands back a NEW module object while the live `db._canvas_ops` is still an instance of the OLD class — whose `upsert_canvas` reads the OLD module's globals. The patch lands somewhere nothing consults, the cap stays at its default of 100, and the "refuses the 4th of 3" assertions fail. `_set_cap` patches the bound method's own `__globals__`, which is whichever module dict the running code actually closes over — correct whether or not an eviction happened, so it does not depend on knowing which test pollutes. Same failure and same fix as #2589, where the identical shape bit `mark_stale_activities_failed`. Worth noting the class: a monkeypatch on a module attribute is only as good as the assumption that the live object came from that module object, and in a suite that evicts modules that assumption is not free. The feature is unchanged — this touches only the test file. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * fix(canvas): re-parent the pinned revision, and make the canvas cap reachable Two review items from #2619. **Alembic head fork (#2068 class).** `0058_agent_canvases_pinned` shared `down_revision = 0057` with #2608's `0058_portal_file_dismissals`, which has since landed on `dev` — two heads, and `alembic upgrade head` resolves its single target before applying anything, so EVERY revision merged since the fork stops arriving, not just one. Re-parented onto `0058_portal_file_dismissals` and renumbered to `0059` so the prefix keeps being a usable ordering cue; the id is not applied anywhere yet, so the rename costs nothing. `check_alembic_heads.py` reports 1 head. **`CANVAS_MAX_PER_AGENT` was inert (#1039 class).** The refusal message names the number, but the variable was read only from `os.getenv` in `models.py` and appeared in no compose file — so an operator following the refusal's own advice would raise a lever that never reaches the container. Wired into `docker-compose.yml`, `.prod.yml` and `.hosted.yml` (the last two launch standalone, no base merge / no `env_file`) plus `.env.example`. Related to #2619 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP * chore(design-system): re-freeze CanvasPanel's raw-gray ceiling for ent#553 The raw-colour ratchet became enforceable on dev while this branch was open (#2605/#2609), and the merge brings it here: this PR's delete/pin/ search chrome takes `components/canvas/CanvasPanel.vue` from 25 to 46 `raw_gray`, so `tests/unit/rawColorRatchet.spec.js` fails the frontend build. That growth is the honest kind. The design-system contract SPELLS the neutral ink ladder as `gray-N` — surfaces gray-50/100/800/900, borders gray-200/300/700/800, ink gray-300/400/500/600 — and there is no semantic token for a neutral, which is exactly why the spec's own comment says gray is ratcheted but never held to zero for new files. The rule it does hold new code to is `raw_nongray`, and this file stays at **0**. Re-frozen in its OWN commit with the increase named in the baseline's `refrozen` block, which is what the ratchet's error message asks for — not absorbed silently into the feature diff. The entry is hand-edited rather than regenerated so #2605's provenance block survives; no other file's ceiling moves (verified: nothing grew, nothing is stale, no un-baselined file carries `raw_nongray`). Related to #553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP * fix(canvas): state the bound, audit the Workspace writes, gate Manage on ownership (ent#553) Three review findings, all in the same direction — the backend was right and the user-facing half did not arrive — plus the two smaller ones. 1. **The stated bound now reaches the user.** `canvasLimit` was a `ref(0)` nothing ever assigned, so `canvasHeadroom(n, 0)` returned `{label: null}` and the early warning could not render at any count. The ceiling rides `GET /api/settings/feature-flags` as `canvas_max_per_agent` — the established home for a value the browser needs to render a surface, and where `platform_default_model` / `install_source` already set the precedent for a non-boolean. Not a new route (Invariant #13 would owe three surfaces for one integer) and not an envelope around the canvas list (the MCP tool and the Workspace both read it as a bare array). It is a CONSTANT, not per-agent state, and the client already holds the count. `0` still means "not told" and still renders nothing, so an older backend is unchanged. 2. **The Workspace canvas writes are audited.** The three portal routes recorded nothing while their operator twins have logged since they shipped, and `docs/user-docs/agents/agent-canvas.md` tells users deletion is audited — so the claim was false for exactly the client-facing surface. `_audit_canvas_change` is the shared helper; the actor is `actor_email` (the documented #848 inline-auth path) rather than a fabricated `User`, which is honest because `_require_canvas_manager` is platform-only and owner-or-admin, so a real Trinity user is always behind it. Ids and counts only (G-04). The three routes become `async def` to await it, matching their operator twins, which already call the same sync db functions from an async handler. Pinning is audited too, on BOTH surfaces — the operator route was the one recording nothing. A pin decides which canvas an entire roster sees first, so it is an administrative act on a shared surface, not a per-viewer preference. 3. **`canManage` comes from the parent.** It was hardcoded `true` on the argument that the server decides. It does — but a merely-shared user was then shown Manage → Delete / Pin and got a 403, which is the failing-control problem `can_manage_canvases` exists to prevent on the Workspace. Agent Detail passes `agent.can_share`, the same predicate `ReportsPanel` five lines above already reads and the same one `_gate_human_removal` enforces. The prop defaults FALSE, so a caller that forgets it hides an affordance rather than offering one that refuses. 4. **`get_agent_card` resolves `can_manage_canvases`.** It omitted it, so the same owner read `true` in the sidebar and `false` on the agent's own page — the disagreement #2160's own docstring says that function exists to prevent. 5. **An agent genuinely cannot pin its own canvas now.** The user doc said so; `_gate_human_removal` allowed it (right for delete — an agent tidying up after itself — and wrong for pin), and "no MCP tool exposes it" is a property of the client, not of the route. `_gate_pin` is humans-only, which makes the documented sentence true rather than aspirational. Tests: the audit guard now walks the portal routes as well as `routers.canvas` (it only ever inspected the latter, which is why three unaudited routes passed it), plus pin-audit parity, the humans-only pin gate beside the still-permitted agent self-delete, the feature-flags constant being the same object the refusal is raised from, the agent-card/roster agreement, and four frontend wiring cases. 1025 backend / 2538 frontend tests green. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN * fix(canvas): the Workspace audit names the operator, not the platform (ent#553) Found re-reviewing my own audit fix. Adding the rows was right; the attribution was wrong, and a row that lands under the wrong actor is worse than the missing row it replaced — nothing fails, so the wrong answer is believed. `_audit_canvas_change` passed `actor_email` only. But `platform_audit_service._resolve_actor` derives `actor_type` from `actor_user` / `actor_agent_name` / `mcp_scope` / `mcp_key_id` and never from the email, so an email-only call falls through to its last branch: _resolve_actor(None, None, None, None) -> ("system", "trinity-system", None) So every Workspace canvas delete and pin was recorded as `actor_type="system"`, `actor_id="trinity-system"` — a named operator's action attributed to the platform, invisible to any `actor_type=user` query and to the audit UI's per-actor filter. Verified against the real resolver, not by reading the call. The `actor_email`-only path I cited (#848 inline auth) is right where the caller genuinely has no `users` row. That is not this route: `_require_canvas_manager` is platform-only and resolves through `db.can_user_share_agent`, so a row exists by construction. It now resolves that row and passes `actor_user`, producing the same `("user", <id>, <email>)` shape the operator twin has always written — which is the point, since auditing the two surfaces differently buys little more than auditing one of them. Best-effort by construction: the action has already happened, so a lookup that raises or misses must not drop the row. It falls back to the email-only call with a WARNING, since a miss would mean the gate admitted someone the user table does not know. Tests: the regression is pinned against the REAL `_resolve_actor` (both the shape the fix must not return to and the shape it produces now), plus a source guard that the helper resolves a row, passes `actor_user`, keeps the email as a fallback and cannot raise. Removing `actor_user=` reds it. 31 passed on the ent#553 file; 953 across canvas / portal / audit. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN * test(canvas): resolve CanvasLimitExceeded from the live method's globals The two cap tests imported the class from `db.canvas` while `_set_cap` already patches the cap through `upsert_canvas.__globals__` — because an earlier test can evict and re-import the module. The same eviction gives the test a different class object than the one the live code raises, and `pytest.raises` then reports the correct refusal as an unexpected exception. Seen once in a full local run after the dev merge (both tests pass in isolation and under CI's three seeds); resolve the class from the same globals the cap comes from. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht * fix(canvas): keep the selector visible when a search narrows to one match (ent#553 review) `CanvasPanel.vue` gated the chip strip on `visible.length > 1 || manage`, where `visible` is the FILTERED list. Searching down to exactly one canvas hid the strip while the previously selected canvas stayed on screen, and the auto-select watcher — keyed off the unfiltered `props.canvases` — never selected the match. Proven by execution: 7 canvases, query "Topic 3" → strip false, no-match message false. The one canvas the user just searched for was unreachable. Fix: - `canvasSelectorVisible({visible, manage, query})` — with a query, any hit shows the strip; without one, a single canvas is no choice (unchanged). - `canvasAutoSelect(visible, selectedId, query)` — while a query is active the selection follows the matches; no-op with no query or when the current selection already matches. - `CanvasPanel.vue` consumes both: `v-if="selectorVisible"` and a watcher on `[visible, query]`. Tests: - `canvasUtils.spec.js`: the two pure rules. - `canvasPanelSelectorGate.spec.js`: slices the `selectorVisible` computed out of the SFC and RUNS it against the ejection's numbers; pins that the template reads the computed, not a re-derived length test, and that the watcher calls `canvasAutoSelect`. - `test_ent553_canvas_lifecycle.py`: the second review ask — the per-agent cap reaches the wire as a 409 through the real router → service → db chain (only the Redis rate limiter stubbed), names the remedy, and the same PUT against an existing id stays an update. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht * fix(canvas): the search box outlives a shrink below the threshold (ent#553 review) `query` has exactly one writer — the search input's `v-model` — and that input was `v-if="showSearch"` with `showSearch = ordered.length > 6`. Seven canvases, type "Topic 3", delete the one match: six canvases, the box unmounts, `visible` still filters on the stale query, the strip collapses, and the panel says *No canvas matches "Topic 3"* with no control left to clear it. Every remaining canvas is unreachable via the chips until navigation. Also reachable with no operator action: the agent's own `clear_canvas` plus a rail refresh while a query is typed. The rule is pure — `canvasSearchVisible(count, threshold, query)` — and keeps the box while a query is active regardless of the count: the typed intent survives the shrink, and the no-match line keeps the one control that clears it. Resetting `query` when the box would flip off was the other option and was rejected: it erases a search the user was mid-way through because a sibling canvas went away. The gate spec that pinned the previous ejection drove `visible`/`query` in isolation from `showSearch`, which is why it could not see this one. It now slices the real `showSearch` computed out of the SFC and RUNS it against the ejection's own numbers (7 → 6 with "Topic 3" typed → box stays; 6 with no query → box gone), and pins that the input is gated on that computed and is the sole writer of `query`. Mutation-checked: reverting the gate to the old length test reds three cases. Four mechanical items from the same review ride along: - requirements/core-agent.md: the ent#438 "deliberately no retention window: bounded by construction" line now says why that reasoning was wrong (rows are bounded per canvas, the count was not) and what bounds it instead; FR-18..FR-22 record delete / bulk / cap / pin / search, which had no requirements entries at all. - raw-color-baseline.json: the `_ent553_note` naming CanvasPanel.vue's 25 → 46 raw_gray was added in 2794388 and dropped by the dev merge aa248f7; re-added so the growth is named in the file. - routers/canvas.py `# mcp:` header now says pin and bulk-delete are unexposed on purpose, and why — Invariant #13's deliberate-vs-forgotten signal. - feature-flows/agent-canvas.md: the two search-state rules and the defect class they close. Verified: vitest 2696 passed (121 files); canvas backend suites 101 passed; raw-colour ratchet and loading-gate ratchet unchanged. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RS8FBA7oEtAAv6GamZKong --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…#554) (#2623) * feat(canvas): delete, pin, search and a stated bound for the canvas pile An agent that uses its canvas the way ent#438 intends accumulates dozens: one per report, per topic, per run. The Workspace could only ever ADD to that pile — the client-portal surface had no delete at all, the only ordering was "newest updated", and nothing bounded the table. Two decisions, both by operator ruling 2026-09-08, recorded because each had a plausible alternative: **Deleting is owner-or-admin.** The answer ent#548 gives for files — the owner deletes the shared artifact. This NARROWS the platform DELETE route, which accepted any user with agent access; safe because no UI called it, so no workflow depended on the wider gate. A canvas is one shared surface with no per-user copy, so a non-owner has no "hide it from my list" middle ground: per AC #2 they see no control at all rather than one that 403s. Agents keep clearing their own (`clear_canvas`, the #918 self-gate). **The bound is a per-agent CAP, not a retention window.** ent#438 recorded "no retention window" because the composite key bounds rows per canvas — but `canvas_id` is agent-chosen, so the COUNT was unbounded; the axis was missed, not decided. `CANVAS_MAX_PER_AGENT` (100, env-tunable) is checked inside `upsert_canvas`'s insert branch, in the same transaction as the INSERT, so it is not a check-then-act race. Updating an existing canvas is NEVER refused — a cap that froze updates would punish exactly the agent that reuses ids — and the refusal is a named 409 telling the agent to retire one, never an eviction: deleting a person's surfaces on a timer is the #1638 failure direction. Both surfaces resolve permission through `db.can_user_share_agent`, the same predicate `assert_agent_owner` uses, so Agent Detail and the Workspace cannot disagree about who owns an agent. The Workspace learns it from `PortalAgentCard.can_manage_canvases` — the portal's only capability channel (#2128), since a portal principal cannot read `/api/settings/feature-flags` — and it fails closed. `pinned` (dual-track: `agent_canvases_pinned` + Alembic 0058, NOT NULL DEFAULT 0, no backfill) is written only by the human pin route and is deliberately absent from every agent-facing tool: `audience` is the agent's decision about who may read, `pinned` is the reader's about what they see first, and an agent that could pin itself to the top would defeat the ordering. A pin survives the agent rewriting the canvas. Living with many is `CanvasPanel.vue`, shared by both surfaces (one rendering layer, per ent#475): search once the list passes six, a height-bounded strip so a long list does not cost the rail its other tabs, and a Manage mode giving each row its age, stale mark, pin and delete. Decidable rules are pure in `canvasUtils.js` — vitest runs `environment: 'node'` with no mount harness, so a rule inside the SFC is one no test can reach. Bulk delete is a POST, not a body-carrying DELETE (bodies on DELETE are permitted-but-unreliable and this one is not optional), declared above the parameterized routes on both routers (Invariant #4), and it reports the ids that EXISTED rather than the ids requested so "3 of 5 removed" is sayable. Three pre-existing guards failed and each was right to: `empty_canvas` was missing the new field (a real bug in this change, fixed), the self-gate guard needed to learn the new gate's name, and the positional-read guard needed its synthetic row extended — that one exists precisely because `_row_to_summary` reads by index. Tests: 20 new backend cases (cap refusal + update-at-cap, pin ordering and survival, bulk scoping, the permission matrix on both surfaces, route ordering, dual-track migration parity, and that the MCP tools cannot pin) and ~24 vitest cases for the pure rules. Verified against a real database: the cap refuses the 4th of 3, updates still succeed at the cap, a pin outranks recency and survives a rewrite, and bulk delete returns only the ids that existed. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * feat(canvas): audit the single delete, cover the default canvas, document the lifecycle Closes the three acceptance criteria the first commit left open: * AC #1 asked for the deletion to be audited and only the BULK route was — the single-canvas route is the one a person actually clicks. Logged only when something was removed, since the route is idempotent and a repeat click would otherwise fill the trail with events where nothing happened. * AC #8: deleting the DEFAULT canvas is allowed, comes back empty on the next write, and frees a slot against the cap. `main` is the id both the MCP tools and the voice panel fall back to, so it is the one most likely to be deleted by accident and the one whose deletion must strand nobody. * AC #9: the user doc gains a "Removing canvases" section stating the permission rule, the cap, and that nothing is ever deleted to make room. Also records a latent pre-existing mismatch found while testing: `empty_canvas` returns None timestamps while `models.Canvas` requires strings, so `Canvas(**empty_canvas(...))` raises. Not live — its only caller declares no `response_model` — but adding one there would turn the voice teardown poll into a 500. Left as a comment where the next person to reach for that will meet it, rather than fixed out of scope. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * feat(canvas): share a canvas at a link, and download it as a PDF A canvas is where an agent's real output lives, and until now it could not leave the Workspace: no share link, no export, nothing in the tree that renders a PDF. **Sharing never widens the audience by accident.** Two scopes, and the default is the narrow one: `authorized` makes the link a DEEP link — opening it requires signing in and the server re-checks `can_user_access_agent`, so it reaches "the people who could already see it" and nobody else. `public` is an explicit, separate, audited choice. Failing narrow is enforced in five independent places (column default, Pydantic default, `normalize_scope`'s fallback, the order of `SHARE_SCOPES`, the radio the dialog preselects), because a link that reaches further than the sharer understood is the one failure this feature must not have. **`agent_canvas_shares` is deliberately its own table.** `agent_public_links` has a `type` column that looks purpose-built for this, and reusing it would have been a real vulnerability: nothing in that table's read path filters on type — `get_public_link_by_token`, `is_link_valid` and `routers/public.py::_validate_public_link` all resolve a token whatever it is — so a canvas row there would ALSO be a working public-CHAT token, and anyone sent a canvas could talk to the agent. (`type='site'` is the same trap already laid; it is unexploited only because nothing creates those rows today.) A separate table makes the isolation structural instead of dependent on every consumer remembering to check. **Live, and it says so** (AC #3, operator ruling): the link renders the canvas as it is now, carrying its `updated_at` and stale mark, and the page states it is not a copy taken at share time. That follows ent#438's model — a canvas is a surface an agent keeps current — and means a share stores nothing. The cost is drift after sharing; the mitigation is revocation, not freezing. **Revocation keeps the row.** `revoked_at` is stamped, never deleted, because a revoked link has to be able to SAY it was revoked (AC #2), which it cannot do once the row is gone. The status vocabulary splits along disclosure: `revoked` and `expired` are returned only for a token that MATCHED a row — whoever holds such a link was already told the canvas exists — while an unknown token and a canvas deleted out from under a link both collapse into one `not_found`, so a stranger guessing tokens learns nothing from the difference. An unparseable `expires_at` reads as expired: a lifetime we cannot read is one we cannot promise is live. **PDF is print-first**, the path the issue recommended: a print stylesheet plus the browser's own PDF. No headless service to run, and — the deciding reason — no second renderer to keep in step with `CanvasBlock`. A server-side renderer was the stated fallback and was not needed: pagination (`break-inside: avoid` per block) and fidelity both fall out of the same markup the screen uses. `CanvasDocument.vue` is the one printable form, rendered by both the shared page and every authenticated surface, so AC #7's "identical from every canvas surface" is true by construction rather than by three surfaces agreeing. It carries title, agent and generation date, forces the light rendering under `@media print`, and when `window.print` is unavailable the control says so and the share link still works. `ent#425` (hosted deliverable pages) is still open, so per this issue's own boundary rule this ships the narrower share link and #425 adopts it later. Verified against a real database, not stubs: the full resolution matrix (public/anonymous → ok, authorized/anonymous → sign-in, authorized/owner → ok, authorized/stranger → refused, unknown → not-found, revoked, expired, unparseable expiry → expired, canvas deleted → not-found), views counted only on a successful render, cross-agent revoke refused, and a second revoke keeping the first revocation time. 23 backend tests, 20 vitest cases for the pure rules. Related to Abilityai/trinity-enterprise#554 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * test(canvas): patch the cap where the live code reads it, not where the test imports it Two ent#553 tests passed in isolation and failed in a full-suite run: `test_the_cap_refuses_a_new_canvas_by_name` and `test_deleting_the_default_canvas_frees_a_slot_against_the_cap`. Order-dependence, not a defect in the feature. They patched `db.canvas.CANVAS_MAX_PER_AGENT` via a fresh `import db.canvas`. Some earlier test in the suite evicts that module from `sys.modules`, so the fresh import hands back a NEW module object while the live `db._canvas_ops` is still an instance of the OLD class — whose `upsert_canvas` reads the OLD module's globals. The patch lands somewhere nothing consults, the cap stays at its default of 100, and the "refuses the 4th of 3" assertions fail. `_set_cap` patches the bound method's own `__globals__`, which is whichever module dict the running code actually closes over — correct whether or not an eviction happened, so it does not depend on knowing which test pollutes. Same failure and same fix as #2589, where the identical shape bit `mark_stale_activities_failed`. Worth noting the class: a monkeypatch on a module attribute is only as good as the assumption that the live object came from that module object, and in a suite that evicts modules that assumption is not free. The feature is unchanged — this touches only the test file. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * fix(canvas): print the canvas, not the whole page Reported from hands-on testing: pressing PDF offered to export the entire page. Correct report — the print stylesheet only STYLED the document and never hid anything else, so `window.print()` printed the nav bar, the tabs, the on-screen panel AND the print copy. That is not "one clean column" by any reading (AC #4), and it is the first thing anyone pressing the button hits. Two halves, both required: * a print rule that hides every `body` child except `.canvas-print-root`; * the print copy TELEPORTED to <body>, so it is a body child and the rule can spare it. Nested inside the app the rule would hide its ancestor and print nothing at all — worse than the bug. `body > *` rather than a class on the app root: it needs no knowledge of how the app is mounted and works identically on the standalone shared page, which keeps AC #7's "identical from every surface" true rather than approximately true. The copy is rendered only while printing (`v-if="printing"` + a `nextTick` flush before `print()`, since printing a not-yet-rendered teleport yields a blank sheet), so the DOM carries no permanent hidden duplicate. `canvasPrintIsolation.spec.js` pins all three structural facts. Nothing automated can inspect a print preview, which is exactly why the bug shipped — so the guard asserts the mechanism instead: the hiding rule exists, the root is teleported to body, and the document mounts before print() is called. Mutation-tested: removing the hiding rule fails it. Also fixes a design-system violation the ratchet caught in the same file: `SharedCanvas` gated its skeleton on a bare `v-if="loading"`. Now `viewState()` — loading means "no data yet", never "a fetch is in flight" (#1927, design-system p13-p15). The page fetches once today, so this is the rule holding rather than a bug fixed; it stays correct if a refresh is added. Baselining my own new violation was the alternative and would have been the wrong one. Related to Abilityai/trinity-enterprise#554 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * fix(canvas): re-parent the pinned revision, and make the canvas cap reachable Two review items from #2619. **Alembic head fork (#2068 class).** `0058_agent_canvases_pinned` shared `down_revision = 0057` with #2608's `0058_portal_file_dismissals`, which has since landed on `dev` — two heads, and `alembic upgrade head` resolves its single target before applying anything, so EVERY revision merged since the fork stops arriving, not just one. Re-parented onto `0058_portal_file_dismissals` and renumbered to `0059` so the prefix keeps being a usable ordering cue; the id is not applied anywhere yet, so the rename costs nothing. `check_alembic_heads.py` reports 1 head. **`CANVAS_MAX_PER_AGENT` was inert (#1039 class).** The refusal message names the number, but the variable was read only from `os.getenv` in `models.py` and appeared in no compose file — so an operator following the refusal's own advice would raise a lever that never reaches the container. Wired into `docker-compose.yml`, `.prod.yml` and `.hosted.yml` (the last two launch standalone, no base merge / no `env_file`) plus `.env.example`. Related to #2619 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP * chore(design-system): re-freeze CanvasPanel's raw-gray ceiling for ent#553 The raw-colour ratchet became enforceable on dev while this branch was open (#2605/#2609), and the merge brings it here: this PR's delete/pin/ search chrome takes `components/canvas/CanvasPanel.vue` from 25 to 46 `raw_gray`, so `tests/unit/rawColorRatchet.spec.js` fails the frontend build. That growth is the honest kind. The design-system contract SPELLS the neutral ink ladder as `gray-N` — surfaces gray-50/100/800/900, borders gray-200/300/700/800, ink gray-300/400/500/600 — and there is no semantic token for a neutral, which is exactly why the spec's own comment says gray is ratcheted but never held to zero for new files. The rule it does hold new code to is `raw_nongray`, and this file stays at **0**. Re-frozen in its OWN commit with the increase named in the baseline's `refrozen` block, which is what the ratchet's error message asks for — not absorbed silently into the feature diff. The entry is hand-edited rather than regenerated so #2605's provenance block survives; no other file's ceiling moves (verified: nothing grew, nothing is stale, no un-baselined file carries `raw_nongray`). Related to #553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP * fix(canvas): state the bound, audit the Workspace writes, gate Manage on ownership (ent#553) Three review findings, all in the same direction — the backend was right and the user-facing half did not arrive — plus the two smaller ones. 1. **The stated bound now reaches the user.** `canvasLimit` was a `ref(0)` nothing ever assigned, so `canvasHeadroom(n, 0)` returned `{label: null}` and the early warning could not render at any count. The ceiling rides `GET /api/settings/feature-flags` as `canvas_max_per_agent` — the established home for a value the browser needs to render a surface, and where `platform_default_model` / `install_source` already set the precedent for a non-boolean. Not a new route (Invariant #13 would owe three surfaces for one integer) and not an envelope around the canvas list (the MCP tool and the Workspace both read it as a bare array). It is a CONSTANT, not per-agent state, and the client already holds the count. `0` still means "not told" and still renders nothing, so an older backend is unchanged. 2. **The Workspace canvas writes are audited.** The three portal routes recorded nothing while their operator twins have logged since they shipped, and `docs/user-docs/agents/agent-canvas.md` tells users deletion is audited — so the claim was false for exactly the client-facing surface. `_audit_canvas_change` is the shared helper; the actor is `actor_email` (the documented #848 inline-auth path) rather than a fabricated `User`, which is honest because `_require_canvas_manager` is platform-only and owner-or-admin, so a real Trinity user is always behind it. Ids and counts only (G-04). The three routes become `async def` to await it, matching their operator twins, which already call the same sync db functions from an async handler. Pinning is audited too, on BOTH surfaces — the operator route was the one recording nothing. A pin decides which canvas an entire roster sees first, so it is an administrative act on a shared surface, not a per-viewer preference. 3. **`canManage` comes from the parent.** It was hardcoded `true` on the argument that the server decides. It does — but a merely-shared user was then shown Manage → Delete / Pin and got a 403, which is the failing-control problem `can_manage_canvases` exists to prevent on the Workspace. Agent Detail passes `agent.can_share`, the same predicate `ReportsPanel` five lines above already reads and the same one `_gate_human_removal` enforces. The prop defaults FALSE, so a caller that forgets it hides an affordance rather than offering one that refuses. 4. **`get_agent_card` resolves `can_manage_canvases`.** It omitted it, so the same owner read `true` in the sidebar and `false` on the agent's own page — the disagreement #2160's own docstring says that function exists to prevent. 5. **An agent genuinely cannot pin its own canvas now.** The user doc said so; `_gate_human_removal` allowed it (right for delete — an agent tidying up after itself — and wrong for pin), and "no MCP tool exposes it" is a property of the client, not of the route. `_gate_pin` is humans-only, which makes the documented sentence true rather than aspirational. Tests: the audit guard now walks the portal routes as well as `routers.canvas` (it only ever inspected the latter, which is why three unaudited routes passed it), plus pin-audit parity, the humans-only pin gate beside the still-permitted agent self-delete, the feature-flags constant being the same object the refusal is raised from, the agent-card/roster agreement, and four frontend wiring cases. 1025 backend / 2538 frontend tests green. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN * fix(canvas): the Workspace audit names the operator, not the platform (ent#553) Found re-reviewing my own audit fix. Adding the rows was right; the attribution was wrong, and a row that lands under the wrong actor is worse than the missing row it replaced — nothing fails, so the wrong answer is believed. `_audit_canvas_change` passed `actor_email` only. But `platform_audit_service._resolve_actor` derives `actor_type` from `actor_user` / `actor_agent_name` / `mcp_scope` / `mcp_key_id` and never from the email, so an email-only call falls through to its last branch: _resolve_actor(None, None, None, None) -> ("system", "trinity-system", None) So every Workspace canvas delete and pin was recorded as `actor_type="system"`, `actor_id="trinity-system"` — a named operator's action attributed to the platform, invisible to any `actor_type=user` query and to the audit UI's per-actor filter. Verified against the real resolver, not by reading the call. The `actor_email`-only path I cited (#848 inline auth) is right where the caller genuinely has no `users` row. That is not this route: `_require_canvas_manager` is platform-only and resolves through `db.can_user_share_agent`, so a row exists by construction. It now resolves that row and passes `actor_user`, producing the same `("user", <id>, <email>)` shape the operator twin has always written — which is the point, since auditing the two surfaces differently buys little more than auditing one of them. Best-effort by construction: the action has already happened, so a lookup that raises or misses must not drop the row. It falls back to the email-only call with a WARNING, since a miss would mean the gate admitted someone the user table does not know. Tests: the regression is pinned against the REAL `_resolve_actor` (both the shape the fix must not return to and the shape it produces now), plus a source guard that the helper resolves a row, passes `actor_user`, keeps the email as a fallback and cannot raise. Removing `actor_user=` reds it. 31 passed on the ent#553 file; 953 across canvas / portal / audit. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN * fix(migrations): chain 0060_agent_canvas_shares off the renamed pinned revision ent#553 renamed its revision 0058_agent_canvases_pinned -> 0059 when it absorbed dev's 0058_portal_file_dismissals; this revision still pointed at the old id, so after the merge the directory resolved to two heads and `alembic upgrade head` would have applied nothing. Renumbered to 0060 as well so the numeric prefix stays a unique ordering cue. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht * chore(frontend): re-freeze CanvasPanel.vue raw_gray 46 -> 62 for ent#554 The share/PDF controls add gray chrome copied from the panel's existing header; the branch predates the #2605 ratchet, so the guard first bit when dev was merged in. Scoped to this one entry, in its own commit, as the guard's own message prescribes. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht * test(canvas): resolve CanvasLimitExceeded from the live method's globals The two cap tests imported the class from `db.canvas` while `_set_cap` already patches the cap through `upsert_canvas.__globals__` — because an earlier test can evict and re-import the module. The same eviction gives the test a different class object than the one the live code raises, and `pytest.raises` then reports the correct refusal as an unexpected exception. Seen once in a full local run after the dev merge (both tests pass in isolation and under CI's three seeds); resolve the class from the same globals the cap comes from. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht * fix(canvas): keep the selector visible when a search narrows to one match (ent#553 review) `CanvasPanel.vue` gated the chip strip on `visible.length > 1 || manage`, where `visible` is the FILTERED list. Searching down to exactly one canvas hid the strip while the previously selected canvas stayed on screen, and the auto-select watcher — keyed off the unfiltered `props.canvases` — never selected the match. Proven by execution: 7 canvases, query "Topic 3" → strip false, no-match message false. The one canvas the user just searched for was unreachable. Fix: - `canvasSelectorVisible({visible, manage, query})` — with a query, any hit shows the strip; without one, a single canvas is no choice (unchanged). - `canvasAutoSelect(visible, selectedId, query)` — while a query is active the selection follows the matches; no-op with no query or when the current selection already matches. - `CanvasPanel.vue` consumes both: `v-if="selectorVisible"` and a watcher on `[visible, query]`. Tests: - `canvasUtils.spec.js`: the two pure rules. - `canvasPanelSelectorGate.spec.js`: slices the `selectorVisible` computed out of the SFC and RUNS it against the ejection's numbers; pins that the template reads the computed, not a re-derived length test, and that the watcher calls `canvasAutoSelect`. - `test_ent553_canvas_lifecycle.py`: the second review ask — the per-agent cap reaches the wire as a 409 through the real router → service → db chain (only the Redis rate limiter stubbed), names the remedy, and the same PUT against an existing id stays an update. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht * fix(canvas): the search box outlives a shrink below the threshold (ent#553 review) `query` has exactly one writer — the search input's `v-model` — and that input was `v-if="showSearch"` with `showSearch = ordered.length > 6`. Seven canvases, type "Topic 3", delete the one match: six canvases, the box unmounts, `visible` still filters on the stale query, the strip collapses, and the panel says *No canvas matches "Topic 3"* with no control left to clear it. Every remaining canvas is unreachable via the chips until navigation. Also reachable with no operator action: the agent's own `clear_canvas` plus a rail refresh while a query is typed. The rule is pure — `canvasSearchVisible(count, threshold, query)` — and keeps the box while a query is active regardless of the count: the typed intent survives the shrink, and the no-match line keeps the one control that clears it. Resetting `query` when the box would flip off was the other option and was rejected: it erases a search the user was mid-way through because a sibling canvas went away. The gate spec that pinned the previous ejection drove `visible`/`query` in isolation from `showSearch`, which is why it could not see this one. It now slices the real `showSearch` computed out of the SFC and RUNS it against the ejection's own numbers (7 → 6 with "Topic 3" typed → box stays; 6 with no query → box gone), and pins that the input is gated on that computed and is the sole writer of `query`. Mutation-checked: reverting the gate to the old length test reds three cases. Four mechanical items from the same review ride along: - requirements/core-agent.md: the ent#438 "deliberately no retention window: bounded by construction" line now says why that reasoning was wrong (rows are bounded per canvas, the count was not) and what bounds it instead; FR-18..FR-22 record delete / bulk / cap / pin / search, which had no requirements entries at all. - raw-color-baseline.json: the `_ent553_note` naming CanvasPanel.vue's 25 → 46 raw_gray was added in 2794388 and dropped by the dev merge aa248f7; re-added so the growth is named in the file. - routers/canvas.py `# mcp:` header now says pin and bulk-delete are unexposed on purpose, and why — Invariant #13's deliberate-vs-forgotten signal. - feature-flows/agent-canvas.md: the two search-state rules and the defect class they close. Verified: vitest 2696 passed (121 files); canvas backend suites 101 passed; raw-colour ratchet and loading-gate ratchet unchanged. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RS8FBA7oEtAAv6GamZKong * fix(canvas): a share link is a grant, so only a human may mint one (ent#554 review) `create_canvas_share`'s docstring said "Owner-or-admin and human-only via `_gate_human_removal`". That gate is not human-only — its own docstring, one screen above, says an agent-scoped key may act on its own agent, which is correct for `clear_canvas` ("an agent tidying up after itself") and wrong for every verb that decides what someone OTHER than the agent may see. So a prompt-injected agent could POST /api/agents/<self>/canvas/<id>/share {"scope": "public"} with the TRINITY_MCP_API_KEY already in its container and publish its own canvas at an unauthenticated URL. Three things make that worse than it first reads: * the share is LIVE, not a snapshot, so one link is a self-updating channel rather than a one-time disclosure; * the agent is the only writer of canvas blocks, so anything it can read it can copy into a canvas and publish; * `audience` is not consulted on the share path, so ent#438's fail-closed "a canvas reaches a client only because the agent said so" would not have applied — the agent would have been choosing for itself. `list_canvas_shares` had the same gate and returns the TOKEN, which is the capability itself; `revoke_canvas_share` too, so an agent could also turn off a person's link. The fix is the grant-vs-use line (Invariant #8): the endpoint that USES a capability may be agent-callable, the one that GRANTS one is human-only. * `_gate_human_only(current_user, name, *, agent_detail)` is factored out of `_gate_pin` — the predicate was always right, only its NAME described one caller. A gate named for a verb ("removal") is one a fourth caller reaches past by accident; a gate named for its rule is not. `_gate_pin` and the new `_gate_share` both delegate to it, with per-caller refusal text because an agent reads that message to decide what to do next. * The three share routes now call `_gate_share`. * The delete routes deliberately KEEP `_gate_human_removal`, and a test guards that boundary in the other direction — the first attempt at this fix swept `clear_canvas` into the human-only gate, because one `str.replace` matched both bodies. That would have broken a real MCP tool for every agent: a security fix breeding the next bug, the /review §4.14 class. Six regression tests; four of them fail against the previous commit (the other two are the over-correction guards, which must pass both ways by design). The 23 tests already here covered scope defaults, expiry, revocation and enumeration, but none used an agent principal on any share route — which is how this shipped. Docs: the user doc now states that sharing is the owner's alone and that the routes refuse an agent's own key, beside the same sentence for pin; the flow doc records the decision, the blast radius, and why the delete routes stay permissive. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ * docs(canvas): record the share routes in the file's own mcp: convention (ent#554 review) The header comment lists which canvas routes are deliberately NOT exposed as MCP tools and why. ent#554 added three that qualify — minting, listing and revoking a share link — and the list did not grow with them. Worth more than a comment here: the ent#553 entry states the rule the share routes then failed to follow ("no tool exposes it" is a property of the client), so a reader consulting this header to decide a fourth route's gate would have found the reasoning but not the precedent. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ * docs(learnings): a gate named after a verb gets reached for by the wrong route (ent#554 review) Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]>
#2628) * feat(canvas): delete, pin, search and a stated bound for the canvas pile An agent that uses its canvas the way ent#438 intends accumulates dozens: one per report, per topic, per run. The Workspace could only ever ADD to that pile — the client-portal surface had no delete at all, the only ordering was "newest updated", and nothing bounded the table. Two decisions, both by operator ruling 2026-09-08, recorded because each had a plausible alternative: **Deleting is owner-or-admin.** The answer ent#548 gives for files — the owner deletes the shared artifact. This NARROWS the platform DELETE route, which accepted any user with agent access; safe because no UI called it, so no workflow depended on the wider gate. A canvas is one shared surface with no per-user copy, so a non-owner has no "hide it from my list" middle ground: per AC #2 they see no control at all rather than one that 403s. Agents keep clearing their own (`clear_canvas`, the #918 self-gate). **The bound is a per-agent CAP, not a retention window.** ent#438 recorded "no retention window" because the composite key bounds rows per canvas — but `canvas_id` is agent-chosen, so the COUNT was unbounded; the axis was missed, not decided. `CANVAS_MAX_PER_AGENT` (100, env-tunable) is checked inside `upsert_canvas`'s insert branch, in the same transaction as the INSERT, so it is not a check-then-act race. Updating an existing canvas is NEVER refused — a cap that froze updates would punish exactly the agent that reuses ids — and the refusal is a named 409 telling the agent to retire one, never an eviction: deleting a person's surfaces on a timer is the #1638 failure direction. Both surfaces resolve permission through `db.can_user_share_agent`, the same predicate `assert_agent_owner` uses, so Agent Detail and the Workspace cannot disagree about who owns an agent. The Workspace learns it from `PortalAgentCard.can_manage_canvases` — the portal's only capability channel (#2128), since a portal principal cannot read `/api/settings/feature-flags` — and it fails closed. `pinned` (dual-track: `agent_canvases_pinned` + Alembic 0058, NOT NULL DEFAULT 0, no backfill) is written only by the human pin route and is deliberately absent from every agent-facing tool: `audience` is the agent's decision about who may read, `pinned` is the reader's about what they see first, and an agent that could pin itself to the top would defeat the ordering. A pin survives the agent rewriting the canvas. Living with many is `CanvasPanel.vue`, shared by both surfaces (one rendering layer, per ent#475): search once the list passes six, a height-bounded strip so a long list does not cost the rail its other tabs, and a Manage mode giving each row its age, stale mark, pin and delete. Decidable rules are pure in `canvasUtils.js` — vitest runs `environment: 'node'` with no mount harness, so a rule inside the SFC is one no test can reach. Bulk delete is a POST, not a body-carrying DELETE (bodies on DELETE are permitted-but-unreliable and this one is not optional), declared above the parameterized routes on both routers (Invariant #4), and it reports the ids that EXISTED rather than the ids requested so "3 of 5 removed" is sayable. Three pre-existing guards failed and each was right to: `empty_canvas` was missing the new field (a real bug in this change, fixed), the self-gate guard needed to learn the new gate's name, and the positional-read guard needed its synthetic row extended — that one exists precisely because `_row_to_summary` reads by index. Tests: 20 new backend cases (cap refusal + update-at-cap, pin ordering and survival, bulk scoping, the permission matrix on both surfaces, route ordering, dual-track migration parity, and that the MCP tools cannot pin) and ~24 vitest cases for the pure rules. Verified against a real database: the cap refuses the 4th of 3, updates still succeed at the cap, a pin outranks recency and survives a rewrite, and bulk delete returns only the ids that existed. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * feat(canvas): audit the single delete, cover the default canvas, document the lifecycle Closes the three acceptance criteria the first commit left open: * AC #1 asked for the deletion to be audited and only the BULK route was — the single-canvas route is the one a person actually clicks. Logged only when something was removed, since the route is idempotent and a repeat click would otherwise fill the trail with events where nothing happened. * AC #8: deleting the DEFAULT canvas is allowed, comes back empty on the next write, and frees a slot against the cap. `main` is the id both the MCP tools and the voice panel fall back to, so it is the one most likely to be deleted by accident and the one whose deletion must strand nobody. * AC #9: the user doc gains a "Removing canvases" section stating the permission rule, the cap, and that nothing is ever deleted to make room. Also records a latent pre-existing mismatch found while testing: `empty_canvas` returns None timestamps while `models.Canvas` requires strings, so `Canvas(**empty_canvas(...))` raises. Not live — its only caller declares no `response_model` — but adding one there would turn the voice teardown poll into a 500. Left as a comment where the next person to reach for that will meet it, rather than fixed out of scope. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * feat(canvas): share a canvas at a link, and download it as a PDF A canvas is where an agent's real output lives, and until now it could not leave the Workspace: no share link, no export, nothing in the tree that renders a PDF. **Sharing never widens the audience by accident.** Two scopes, and the default is the narrow one: `authorized` makes the link a DEEP link — opening it requires signing in and the server re-checks `can_user_access_agent`, so it reaches "the people who could already see it" and nobody else. `public` is an explicit, separate, audited choice. Failing narrow is enforced in five independent places (column default, Pydantic default, `normalize_scope`'s fallback, the order of `SHARE_SCOPES`, the radio the dialog preselects), because a link that reaches further than the sharer understood is the one failure this feature must not have. **`agent_canvas_shares` is deliberately its own table.** `agent_public_links` has a `type` column that looks purpose-built for this, and reusing it would have been a real vulnerability: nothing in that table's read path filters on type — `get_public_link_by_token`, `is_link_valid` and `routers/public.py::_validate_public_link` all resolve a token whatever it is — so a canvas row there would ALSO be a working public-CHAT token, and anyone sent a canvas could talk to the agent. (`type='site'` is the same trap already laid; it is unexploited only because nothing creates those rows today.) A separate table makes the isolation structural instead of dependent on every consumer remembering to check. **Live, and it says so** (AC #3, operator ruling): the link renders the canvas as it is now, carrying its `updated_at` and stale mark, and the page states it is not a copy taken at share time. That follows ent#438's model — a canvas is a surface an agent keeps current — and means a share stores nothing. The cost is drift after sharing; the mitigation is revocation, not freezing. **Revocation keeps the row.** `revoked_at` is stamped, never deleted, because a revoked link has to be able to SAY it was revoked (AC #2), which it cannot do once the row is gone. The status vocabulary splits along disclosure: `revoked` and `expired` are returned only for a token that MATCHED a row — whoever holds such a link was already told the canvas exists — while an unknown token and a canvas deleted out from under a link both collapse into one `not_found`, so a stranger guessing tokens learns nothing from the difference. An unparseable `expires_at` reads as expired: a lifetime we cannot read is one we cannot promise is live. **PDF is print-first**, the path the issue recommended: a print stylesheet plus the browser's own PDF. No headless service to run, and — the deciding reason — no second renderer to keep in step with `CanvasBlock`. A server-side renderer was the stated fallback and was not needed: pagination (`break-inside: avoid` per block) and fidelity both fall out of the same markup the screen uses. `CanvasDocument.vue` is the one printable form, rendered by both the shared page and every authenticated surface, so AC #7's "identical from every canvas surface" is true by construction rather than by three surfaces agreeing. It carries title, agent and generation date, forces the light rendering under `@media print`, and when `window.print` is unavailable the control says so and the share link still works. `ent#425` (hosted deliverable pages) is still open, so per this issue's own boundary rule this ships the narrower share link and #425 adopts it later. Verified against a real database, not stubs: the full resolution matrix (public/anonymous → ok, authorized/anonymous → sign-in, authorized/owner → ok, authorized/stranger → refused, unknown → not-found, revoked, expired, unparseable expiry → expired, canvas deleted → not-found), views counted only on a successful render, cross-agent revoke refused, and a second revoke keeping the first revocation time. 23 backend tests, 20 vitest cases for the pure rules. Related to Abilityai/trinity-enterprise#554 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * test(canvas): patch the cap where the live code reads it, not where the test imports it Two ent#553 tests passed in isolation and failed in a full-suite run: `test_the_cap_refuses_a_new_canvas_by_name` and `test_deleting_the_default_canvas_frees_a_slot_against_the_cap`. Order-dependence, not a defect in the feature. They patched `db.canvas.CANVAS_MAX_PER_AGENT` via a fresh `import db.canvas`. Some earlier test in the suite evicts that module from `sys.modules`, so the fresh import hands back a NEW module object while the live `db._canvas_ops` is still an instance of the OLD class — whose `upsert_canvas` reads the OLD module's globals. The patch lands somewhere nothing consults, the cap stays at its default of 100, and the "refuses the 4th of 3" assertions fail. `_set_cap` patches the bound method's own `__globals__`, which is whichever module dict the running code actually closes over — correct whether or not an eviction happened, so it does not depend on knowing which test pollutes. Same failure and same fix as #2589, where the identical shape bit `mark_stale_activities_failed`. Worth noting the class: a monkeypatch on a module attribute is only as good as the assumption that the live object came from that module object, and in a suite that evicts modules that assumption is not free. The feature is unchanged — this touches only the test file. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * fix(canvas): print the canvas, not the whole page Reported from hands-on testing: pressing PDF offered to export the entire page. Correct report — the print stylesheet only STYLED the document and never hid anything else, so `window.print()` printed the nav bar, the tabs, the on-screen panel AND the print copy. That is not "one clean column" by any reading (AC #4), and it is the first thing anyone pressing the button hits. Two halves, both required: * a print rule that hides every `body` child except `.canvas-print-root`; * the print copy TELEPORTED to <body>, so it is a body child and the rule can spare it. Nested inside the app the rule would hide its ancestor and print nothing at all — worse than the bug. `body > *` rather than a class on the app root: it needs no knowledge of how the app is mounted and works identically on the standalone shared page, which keeps AC #7's "identical from every surface" true rather than approximately true. The copy is rendered only while printing (`v-if="printing"` + a `nextTick` flush before `print()`, since printing a not-yet-rendered teleport yields a blank sheet), so the DOM carries no permanent hidden duplicate. `canvasPrintIsolation.spec.js` pins all three structural facts. Nothing automated can inspect a print preview, which is exactly why the bug shipped — so the guard asserts the mechanism instead: the hiding rule exists, the root is teleported to body, and the document mounts before print() is called. Mutation-tested: removing the hiding rule fails it. Also fixes a design-system violation the ratchet caught in the same file: `SharedCanvas` gated its skeleton on a bare `v-if="loading"`. Now `viewState()` — loading means "no data yet", never "a fetch is in flight" (#1927, design-system p13-p15). The page fetches once today, so this is the rule holding rather than a bug fixed; it stays correct if a refresh is added. Baselining my own new violation was the alternative and would have been the wrong one. Related to Abilityai/trinity-enterprise#554 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * feat(canvas): the open canvas is shared context for the turn When a user with a canvas on screen says "add a column to this", the agent now knows which canvas they mean. Before this the turn carried the message and nothing about the surface around it, so the agent asked, guessed, or minted a new canvas beside the one being looked at. The mechanism is a per-turn context field — `schedule_executions.open_canvas_id`, the same shape as the `source_channel*` columns beside it — stamped at dispatch and read back by the tools and the prompt. It is CONTEXT, never AUTHORITY, and two independent halves keep it there: - `validated_open_canvas` decides what may be STAMPED. The id is client-supplied, so it is checked against the agent's own canvases and against what that caller can see: an operator-only canvas is invisible to an external client (otherwise the field is an existence oracle for canvases the agent keeps privately), and another agent's canvas is refused outright. Every failure degrades to "nothing open" — never an error, never a wider reach. - `effective_canvas_id` decides what a tool ACTS on, and cannot widen anything: every read and write still passes the existing ownership and audience gates. Precedence is stated once so all three tools agree: `explicit canvas_id > the canvas the user has open > the default canvas`. It returns WHY as well as WHICH, because with nothing named the agent has to be able to say which canvas it wrote to — "I updated the canvas" is not good enough when there are eight and the user is looking at one. Both delivery paths are needed, not one. The MCP tools resolve a missing `canvas_id` through `GET /api/agents/{name}/canvas/context` (declared above `/{canvas_id}` — Invariant #4, since "context" is a valid id shape), AND the turn prompt names the open canvas: a tool default handles a call that omits an id, but an agent must READ a canvas before editing it and cannot read what it cannot name. The prompt line rides the same prefix as the file manifest, so it is present on a resumed turn too — the open canvas changes between turns while the session's memory of it does not. A canvas deleted mid-conversation resolves to nothing, re-checked at read time rather than trusted from the stamp: ent#553 made deleting one click, and a surviving id would have the agent's next write CREATE a canvas under it, silently resurrecting something a person deleted. Voice inherits this by construction — ent#440 submits a spoken utterance through the same `deliver()` a typed one takes. The `canvas` tools in `gemini_voice.py` are deliberately untouched: that is VOICE-001's ephemeral display panel, a different surface with no persisted id. Dual-track migration (`execution_open_canvas` + Alembic `0060`); the column is nullable, so every existing row and every un-updated caller reads as "nothing open". Related to Abilityai/trinity-enterprise#555 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ * fix(canvas): re-parent the pinned revision, and make the canvas cap reachable Two review items from #2619. **Alembic head fork (#2068 class).** `0058_agent_canvases_pinned` shared `down_revision = 0057` with #2608's `0058_portal_file_dismissals`, which has since landed on `dev` — two heads, and `alembic upgrade head` resolves its single target before applying anything, so EVERY revision merged since the fork stops arriving, not just one. Re-parented onto `0058_portal_file_dismissals` and renumbered to `0059` so the prefix keeps being a usable ordering cue; the id is not applied anywhere yet, so the rename costs nothing. `check_alembic_heads.py` reports 1 head. **`CANVAS_MAX_PER_AGENT` was inert (#1039 class).** The refusal message names the number, but the variable was read only from `os.getenv` in `models.py` and appeared in no compose file — so an operator following the refusal's own advice would raise a lever that never reaches the container. Wired into `docker-compose.yml`, `.prod.yml` and `.hosted.yml` (the last two launch standalone, no base merge / no `env_file`) plus `.env.example`. Related to #2619 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP * chore(design-system): re-freeze CanvasPanel's raw-gray ceiling for ent#553 The raw-colour ratchet became enforceable on dev while this branch was open (#2605/#2609), and the merge brings it here: this PR's delete/pin/ search chrome takes `components/canvas/CanvasPanel.vue` from 25 to 46 `raw_gray`, so `tests/unit/rawColorRatchet.spec.js` fails the frontend build. That growth is the honest kind. The design-system contract SPELLS the neutral ink ladder as `gray-N` — surfaces gray-50/100/800/900, borders gray-200/300/700/800, ink gray-300/400/500/600 — and there is no semantic token for a neutral, which is exactly why the spec's own comment says gray is ratcheted but never held to zero for new files. The rule it does hold new code to is `raw_nongray`, and this file stays at **0**. Re-frozen in its OWN commit with the increase named in the baseline's `refrozen` block, which is what the ratchet's error message asks for — not absorbed silently into the feature diff. The entry is hand-edited rather than regenerated so #2605's provenance block survives; no other file's ceiling moves (verified: nothing grew, nothing is stale, no un-baselined file carries `raw_nongray`). Related to #553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP * fix(canvas): state the bound, audit the Workspace writes, gate Manage on ownership (ent#553) Three review findings, all in the same direction — the backend was right and the user-facing half did not arrive — plus the two smaller ones. 1. **The stated bound now reaches the user.** `canvasLimit` was a `ref(0)` nothing ever assigned, so `canvasHeadroom(n, 0)` returned `{label: null}` and the early warning could not render at any count. The ceiling rides `GET /api/settings/feature-flags` as `canvas_max_per_agent` — the established home for a value the browser needs to render a surface, and where `platform_default_model` / `install_source` already set the precedent for a non-boolean. Not a new route (Invariant #13 would owe three surfaces for one integer) and not an envelope around the canvas list (the MCP tool and the Workspace both read it as a bare array). It is a CONSTANT, not per-agent state, and the client already holds the count. `0` still means "not told" and still renders nothing, so an older backend is unchanged. 2. **The Workspace canvas writes are audited.** The three portal routes recorded nothing while their operator twins have logged since they shipped, and `docs/user-docs/agents/agent-canvas.md` tells users deletion is audited — so the claim was false for exactly the client-facing surface. `_audit_canvas_change` is the shared helper; the actor is `actor_email` (the documented #848 inline-auth path) rather than a fabricated `User`, which is honest because `_require_canvas_manager` is platform-only and owner-or-admin, so a real Trinity user is always behind it. Ids and counts only (G-04). The three routes become `async def` to await it, matching their operator twins, which already call the same sync db functions from an async handler. Pinning is audited too, on BOTH surfaces — the operator route was the one recording nothing. A pin decides which canvas an entire roster sees first, so it is an administrative act on a shared surface, not a per-viewer preference. 3. **`canManage` comes from the parent.** It was hardcoded `true` on the argument that the server decides. It does — but a merely-shared user was then shown Manage → Delete / Pin and got a 403, which is the failing-control problem `can_manage_canvases` exists to prevent on the Workspace. Agent Detail passes `agent.can_share`, the same predicate `ReportsPanel` five lines above already reads and the same one `_gate_human_removal` enforces. The prop defaults FALSE, so a caller that forgets it hides an affordance rather than offering one that refuses. 4. **`get_agent_card` resolves `can_manage_canvases`.** It omitted it, so the same owner read `true` in the sidebar and `false` on the agent's own page — the disagreement #2160's own docstring says that function exists to prevent. 5. **An agent genuinely cannot pin its own canvas now.** The user doc said so; `_gate_human_removal` allowed it (right for delete — an agent tidying up after itself — and wrong for pin), and "no MCP tool exposes it" is a property of the client, not of the route. `_gate_pin` is humans-only, which makes the documented sentence true rather than aspirational. Tests: the audit guard now walks the portal routes as well as `routers.canvas` (it only ever inspected the latter, which is why three unaudited routes passed it), plus pin-audit parity, the humans-only pin gate beside the still-permitted agent self-delete, the feature-flags constant being the same object the refusal is raised from, the agent-card/roster agreement, and four frontend wiring cases. 1025 backend / 2538 frontend tests green. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN * fix(canvas): the Workspace audit names the operator, not the platform (ent#553) Found re-reviewing my own audit fix. Adding the rows was right; the attribution was wrong, and a row that lands under the wrong actor is worse than the missing row it replaced — nothing fails, so the wrong answer is believed. `_audit_canvas_change` passed `actor_email` only. But `platform_audit_service._resolve_actor` derives `actor_type` from `actor_user` / `actor_agent_name` / `mcp_scope` / `mcp_key_id` and never from the email, so an email-only call falls through to its last branch: _resolve_actor(None, None, None, None) -> ("system", "trinity-system", None) So every Workspace canvas delete and pin was recorded as `actor_type="system"`, `actor_id="trinity-system"` — a named operator's action attributed to the platform, invisible to any `actor_type=user` query and to the audit UI's per-actor filter. Verified against the real resolver, not by reading the call. The `actor_email`-only path I cited (#848 inline auth) is right where the caller genuinely has no `users` row. That is not this route: `_require_canvas_manager` is platform-only and resolves through `db.can_user_share_agent`, so a row exists by construction. It now resolves that row and passes `actor_user`, producing the same `("user", <id>, <email>)` shape the operator twin has always written — which is the point, since auditing the two surfaces differently buys little more than auditing one of them. Best-effort by construction: the action has already happened, so a lookup that raises or misses must not drop the row. It falls back to the email-only call with a WARNING, since a miss would mean the gate admitted someone the user table does not know. Tests: the regression is pinned against the REAL `_resolve_actor` (both the shape the fix must not return to and the shape it produces now), plus a source guard that the helper resolves a row, passes `actor_user`, keeps the email as a fallback and cannot raise. Removing `actor_user=` reds it. 31 passed on the ent#553 file; 953 across canvas / portal / audit. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN * fix(migrations): chain 0060_agent_canvas_shares off the renamed pinned revision ent#553 renamed its revision 0058_agent_canvases_pinned -> 0059 when it absorbed dev's 0058_portal_file_dismissals; this revision still pointed at the old id, so after the merge the directory resolved to two heads and `alembic upgrade head` would have applied nothing. Renumbered to 0060 as well so the numeric prefix stays a unique ordering cue. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht * chore(frontend): re-freeze CanvasPanel.vue raw_gray 46 -> 62 for ent#554 The share/PDF controls add gray chrome copied from the panel's existing header; the branch predates the #2605 ratchet, so the guard first bit when dev was merged in. Scoped to this one entry, in its own commit, as the guard's own message prescribes. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht * fix(migrations): renumber execution_open_canvas to 0061 behind 0060_agent_canvas_shares Follows the ent#554 renumber so the chain reads 0059 pinned -> 0060 shares -> 0061 open-canvas with unique prefixes and a single head. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht * test(canvas): resolve CanvasLimitExceeded from the live method's globals The two cap tests imported the class from `db.canvas` while `_set_cap` already patches the cap through `upsert_canvas.__globals__` — because an earlier test can evict and re-import the module. The same eviction gives the test a different class object than the one the live code raises, and `pytest.raises` then reports the correct refusal as an unexpected exception. Seen once in a full local run after the dev merge (both tests pass in isolation and under CI's three seeds); resolve the class from the same globals the cap comes from. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht * fix(canvas): keep the selector visible when a search narrows to one match (ent#553 review) `CanvasPanel.vue` gated the chip strip on `visible.length > 1 || manage`, where `visible` is the FILTERED list. Searching down to exactly one canvas hid the strip while the previously selected canvas stayed on screen, and the auto-select watcher — keyed off the unfiltered `props.canvases` — never selected the match. Proven by execution: 7 canvases, query "Topic 3" → strip false, no-match message false. The one canvas the user just searched for was unreachable. Fix: - `canvasSelectorVisible({visible, manage, query})` — with a query, any hit shows the strip; without one, a single canvas is no choice (unchanged). - `canvasAutoSelect(visible, selectedId, query)` — while a query is active the selection follows the matches; no-op with no query or when the current selection already matches. - `CanvasPanel.vue` consumes both: `v-if="selectorVisible"` and a watcher on `[visible, query]`. Tests: - `canvasUtils.spec.js`: the two pure rules. - `canvasPanelSelectorGate.spec.js`: slices the `selectorVisible` computed out of the SFC and RUNS it against the ejection's numbers; pins that the template reads the computed, not a re-derived length test, and that the watcher calls `canvasAutoSelect`. - `test_ent553_canvas_lifecycle.py`: the second review ask — the per-agent cap reaches the wire as a 409 through the real router → service → db chain (only the Redis rate limiter stubbed), names the remedy, and the same PUT against an existing id stays an update. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht * fix(canvas): the search box outlives a shrink below the threshold (ent#553 review) `query` has exactly one writer — the search input's `v-model` — and that input was `v-if="showSearch"` with `showSearch = ordered.length > 6`. Seven canvases, type "Topic 3", delete the one match: six canvases, the box unmounts, `visible` still filters on the stale query, the strip collapses, and the panel says *No canvas matches "Topic 3"* with no control left to clear it. Every remaining canvas is unreachable via the chips until navigation. Also reachable with no operator action: the agent's own `clear_canvas` plus a rail refresh while a query is typed. The rule is pure — `canvasSearchVisible(count, threshold, query)` — and keeps the box while a query is active regardless of the count: the typed intent survives the shrink, and the no-match line keeps the one control that clears it. Resetting `query` when the box would flip off was the other option and was rejected: it erases a search the user was mid-way through because a sibling canvas went away. The gate spec that pinned the previous ejection drove `visible`/`query` in isolation from `showSearch`, which is why it could not see this one. It now slices the real `showSearch` computed out of the SFC and RUNS it against the ejection's own numbers (7 → 6 with "Topic 3" typed → box stays; 6 with no query → box gone), and pins that the input is gated on that computed and is the sole writer of `query`. Mutation-checked: reverting the gate to the old length test reds three cases. Four mechanical items from the same review ride along: - requirements/core-agent.md: the ent#438 "deliberately no retention window: bounded by construction" line now says why that reasoning was wrong (rows are bounded per canvas, the count was not) and what bounds it instead; FR-18..FR-22 record delete / bulk / cap / pin / search, which had no requirements entries at all. - raw-color-baseline.json: the `_ent553_note` naming CanvasPanel.vue's 25 → 46 raw_gray was added in 2794388 and dropped by the dev merge aa248f7; re-added so the growth is named in the file. - routers/canvas.py `# mcp:` header now says pin and bulk-delete are unexposed on purpose, and why — Invariant #13's deliberate-vs-forgotten signal. - feature-flows/agent-canvas.md: the two search-state rules and the defect class they close. Verified: vitest 2696 passed (121 files); canvas backend suites 101 passed; raw-colour ratchet and loading-gate ratchet unchanged. Related to Abilityai/trinity-enterprise#553 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RS8FBA7oEtAAv6GamZKong * fix(canvas): a share link is a grant, so only a human may mint one (ent#554 review) `create_canvas_share`'s docstring said "Owner-or-admin and human-only via `_gate_human_removal`". That gate is not human-only — its own docstring, one screen above, says an agent-scoped key may act on its own agent, which is correct for `clear_canvas` ("an agent tidying up after itself") and wrong for every verb that decides what someone OTHER than the agent may see. So a prompt-injected agent could POST /api/agents/<self>/canvas/<id>/share {"scope": "public"} with the TRINITY_MCP_API_KEY already in its container and publish its own canvas at an unauthenticated URL. Three things make that worse than it first reads: * the share is LIVE, not a snapshot, so one link is a self-updating channel rather than a one-time disclosure; * the agent is the only writer of canvas blocks, so anything it can read it can copy into a canvas and publish; * `audience` is not consulted on the share path, so ent#438's fail-closed "a canvas reaches a client only because the agent said so" would not have applied — the agent would have been choosing for itself. `list_canvas_shares` had the same gate and returns the TOKEN, which is the capability itself; `revoke_canvas_share` too, so an agent could also turn off a person's link. The fix is the grant-vs-use line (Invariant #8): the endpoint that USES a capability may be agent-callable, the one that GRANTS one is human-only. * `_gate_human_only(current_user, name, *, agent_detail)` is factored out of `_gate_pin` — the predicate was always right, only its NAME described one caller. A gate named for a verb ("removal") is one a fourth caller reaches past by accident; a gate named for its rule is not. `_gate_pin` and the new `_gate_share` both delegate to it, with per-caller refusal text because an agent reads that message to decide what to do next. * The three share routes now call `_gate_share`. * The delete routes deliberately KEEP `_gate_human_removal`, and a test guards that boundary in the other direction — the first attempt at this fix swept `clear_canvas` into the human-only gate, because one `str.replace` matched both bodies. That would have broken a real MCP tool for every agent: a security fix breeding the next bug, the /review §4.14 class. Six regression tests; four of them fail against the previous commit (the other two are the over-correction guards, which must pass both ways by design). The 23 tests already here covered scope defaults, expiry, revocation and enumeration, but none used an agent principal on any share route — which is how this shipped. Docs: the user doc now states that sharing is the owner's alone and that the routes refuse an agent's own key, beside the same sentence for pin; the flow doc records the decision, the blast radius, and why the delete routes stay permissive. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ * docs(canvas): record the share routes in the file's own mcp: convention (ent#554 review) The header comment lists which canvas routes are deliberately NOT exposed as MCP tools and why. ent#554 added three that qualify — minting, listing and revoking a share link — and the list did not grow with them. Worth more than a comment here: the ent#553 entry states the rule the share routes then failed to follow ("no tool exposes it" is a property of the client), so a reader consulting this header to decide a fourth route's gate would have found the reasoning but not the precedent. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ * docs(learnings): a gate named after a verb gets reached for by the wrong route (ent#554 review) Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]>
Fixes #2582 · implements abilityai/trinity-enterprise#548 (cross-tracker — GitHub auto-closes same-repo only, so #548 needs a manual
status-in-devbump and close at release).Sequence
Step 6 of 7 of the Workspace sequence. Merges after ent#535; trinity#2559 follows.
What this does
The Files tab in the Workspace rail: uploads land at once, a Download that actually downloads, a preview modal, and delete.
Three reported defects and one feature, in one PR (Andrii's Stage 2 ruling R1 — a split was argued and rejected; the schema and the bug fix are one behaviour):
?download=flag, below.The one-way
?download=flag, and why it does not contradict ent#461ent#461's posture is that
Content-Disposition: inlineis granted by an allowlist of types (_INLINE_SAFE_TYPES), because inline rendering of an attacker-suppliedtext/htmlon a token-gated public link is stored XSS. That posture is untouched.The flag is strictly one-way — it can only ever add restriction:
?download=1turnsinlineintoattachment.inline— not0, notfalse, notinline, not an empty or malformed value.attachmentis the strictly safer disposition, so letting a requester ask for more restriction over their own download grants no capability. The allowlist remains the only thing that can ever grantinline.Two details worth keeping:
bool. This route is the public link Telegram, WhatsApp and iOS open. Aboolannotation would422on?download=or?download=x, trading an outage for a type — so a malformed value is ignored rather than rejected.sigis a stored bearer token compared withsecrets.compare_digest, not an HMAC over the URL. That is why appending&download=1cannot invalidate it. "The token signs the URL" is the obvious wrong assumption, and it is pinned by a test.Proven in both directions at three levels: the pure helper, the mounted route on a
text/htmlrow across every flag value, and live against a running stack.Cross-client scoping
A client's uploads live in a per-client inbox directory, and the delete matrix is scoped to the caller.
<email-slug>-<sha256[:8]>. The hash suffix is what makes it injective: two emails that slug alike ([email protected]/[email protected]) resolve to different directories, so one client can never read, overwrite or delete another's files. Tested.portal_file_dismissalsis keyed(client_email, file_id). One client hiding a shared document does not hide it from anyone else, and does not revoke the share — verified live: after a viewer's delete the file left that client's list whileagent_shared_files.revoked_atstayedNULL.portal_owns_agentresolves ownership by exactly the rule the roster card renders, so the UI cannot offer a button the server refuses. Per ent#358 a non-owner admin and an owner on a magic-link portal token are both viewers — deliberate, and pinned by tests because it reads like a bug.Schema
portal_file_dismissalson both migration tracks (Invariant #9) — SQLitedb/migrations.pyand Alembic0058, plusschema.py/tables.py. Registered in the agent-cleanup registry so rows do not orphan on agent delete. The table was challenged at review and reaffirmed (ruling R2):user_ui_preferencesis FK'd tousers.idand aPortalPrincipalhas no user row, so no cheaper storage exists.Verification
/verify-localorigin/devworktree on the same interpreter; none from this branchdocker extractdownload,rm -f --on a quoting-sensitive filename, and the dismissal-vs-revoke distinctionFixed at this gate: the three
PORTAL_FILE_*limiter knobs were read by the code and documented in.env.examplewhile forwarded by none of the three compose files (neither prod nor hosted usesenv_file:), so the advertised.envlever was inert everywhere — the #1056 class. Now wired in all three and guarded, mutation-verified.Human sign-off outstanding
Not yet done, and not inferable from tests:
document: preview closes without cancelling the chat turn; delete-confirm the same; Escape still cancels a turn when neither is open.Follow-ups filed
Four, named in the code. The one to know: the voice-call branch at
PortalConversation.vue:1493-1500ignoresdefaultPrevented, so Escape during an active voice call with the preview open is a known residual. Debt #2556 (client_portal/service.pysize) deferred and recorded.🤖 Generated with Claude Code