diff --git a/CLAUDE.md b/CLAUDE.md index 8c97b04d3f3..48f0695d6cb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,8 +26,6 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the | [docs/product.md](docs/product.md) | What Paseo is, who it's for, where it's going | | [docs/architecture.md](docs/architecture.md) | System design, package layering, WebSocket protocol, agent lifecycle, data flow | | [docs/agent-lifecycle.md](docs/agent-lifecycle.md) | Agent states, parent/child relationships, archive semantics, tabs vs archive, subagents track | -| [docs/companion-stream.md](docs/companion-stream.md) | Side-conversation stream and artifact ownership | -| [docs/queue-mirroring.md](docs/queue-mirroring.md) | Durable queued prompts and cross-client delivery | | [docs/data-model.md](docs/data-model.md) | File-based JSON persistence, Zod schemas, atomic writes, no migrations | | [docs/glossary.md](docs/glossary.md) | Authoritative terminology — UI label wins, no synonyms | | [docs/coding-standards.md](docs/coding-standards.md) | Type hygiene, error handling, state design, React patterns, file organization | diff --git a/docs/architecture.md b/docs/architecture.md index f6c0c9f5bb3..de6c619ae36 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -7,8 +7,6 @@ Your code never leaves your machine. Paseo is local-first. Daemon-owned outbound connections and routed API scope ownership are described in [Connected hosts](connected-hosts.md). -See [companion streams](companion-stream.md) for side-conversation ownership and [queue mirroring](queue-mirroring.md) for durable queued prompt delivery. - ## System overview ``` diff --git a/docs/artifact-feed.png b/docs/artifact-feed.png deleted file mode 100644 index ed12d2f8338..00000000000 Binary files a/docs/artifact-feed.png and /dev/null differ diff --git a/docs/companion-stream.md b/docs/companion-stream.md deleted file mode 100644 index 8b30c31b498..00000000000 --- a/docs/companion-stream.md +++ /dev/null @@ -1,68 +0,0 @@ -# Per-chat companion stream - -The managed-agent panel offers **Chat / Stream / Find in chat**. Stream is a quiet review surface -for the current conversation. The compact workspace tab menu also offers **View stream**. -The internal `artifacts` view identifier is retained so existing client-local tab actions keep working. - -The design borrows OpenChat's chat-scoped Thoughts idea: keep questions and useful context alongside -the conversation, with an obvious way back to it. V1 automatically captures moments; it does not -add manual notes, message pinning, model-generated summaries, or another agent execution loop. - -## Contents and meaning - -- Structured question and permission events appear immediately. Plan approvals are decision cards. - A provider resolution marks the request accepted or declined. Failed/interrupted turns and session - recreation expire requests that can no longer be answered. Reading Stream never answers a request. -- The final contiguous assistant response at a terminal turn becomes a review card. Intermediate tool - narration, tool logs, and reasoning do not become cards. A final prose response ending in a question - mark becomes a question card (code spans, fenced code, and URLs are excluded from this heuristic). - A subsequent user message labels a prose question **Reply sent**, not “resolved”. Structured - questions stay pending until the provider resolves them. -- Completed, failed, and canceled turns have distinct outcome cards. **Turn ended** is a lifecycle - fact, not certification that the requested task succeeded. Failure/interruption includes the reason. -- Existing file artifacts retain their cards, previews, and workspace-file open behavior. They still - represent the latest collected version of each path, not an immutable file history. - -Cards interleave by timestamp, newest first. **Needs a reply** filters unresolved questions and -requests without changing the chat. **Read** expands text in place. **Reply in chat** returns to -Chat's current bottom and its existing permission/composer controls; **Back to chat** preserves -its reading position. The mounted chat and composer survive view switches. New entries do not -switch tabs, focus the composer, prompt for approval, or add notification behavior. - -## Data and compatibility - -`packages/protocol/src/companion-stream.ts` owns the structural wire schema. The optional -`companionEntries` agent snapshot field is persisted with the ordinary agent record. The server -collector in `packages/server/src/server/agent/companion-stream.ts` sees accepted live events after -coalescing; provider history replay does not invent past turn outcomes or pending decisions. - -Capture starts after upgrading the host. V1 retains the most recent 50 moments with at most 4,000 -characters per entry. Longer content is explicitly marked as an excerpt; full context remains in -Chat. The bounded snapshot is independent of how much chat history the phone has paged in. -It survives reconnects and host reloads; an unfinished final response is not yet a captured moment. - -`server_info.features.companionStreamPortV1` gates the new feature once in the panel. Older hosts show an -upgrade message while preserving their existing file-artifact view. The client does not reconstruct -an approximate stream from legacy RPCs. Cached cards remain reviewable while disconnected, with a -notice that pending statuses may be stale. - -## Verification - -Focused tests cover collection/deduplication, split response chunks, agent isolation, question and -permission transitions, interruption, response bounds, coalescer integration, stored/wire snapshot -round-trips, old snapshot compatibility, file/moment ordering, pending filtering, and locale parity. - -For a prepared isolated phone build, verify the following without relaunching a shared app: - -1. Open a managed chat in compact layout; Chat, Stream and Find remain visible and tappable at large - text sizes. Stream is also available from the workspace tab menu. -2. Leave a composer draft, scroll up in Chat, open Stream, expand a response and return. The draft - and reading position remain. New incoming cards do not navigate or submit a response. -3. Trigger a structured question or plan approval. It appears under Needs a reply. Reply in chat - reaches the existing controls; accepting/declining updates the same card rather than duplicating it. -4. Finish, fail, or interrupt a turn; review the distinct outcome and generated file cards. Open a - Markdown/image artifact and return through the existing workspace navigation. -5. Disconnect and reconnect. Cached cards remain visible; reconnection refreshes status. Reopen the - conversation and verify saved moments. An older host shows its upgrade message and file artifacts. - -Provider-owned child timelines remain separate read-only panels, as before. diff --git a/docs/glossary.md b/docs/glossary.md index 237683cc4c9..c7a232f500d 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -57,8 +57,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here - **Agent controls** — Provider, model, mode, thinking, and provider-feature controls for an agent or draft agent. Code: `AgentControls` / `DraftAgentControls` (`packages/app/src/composer/agent-controls/index.tsx`). Forbidden: "Agent status bar". - **Composer footer** — Optional area rendered below the composer input but still inside the keyboard-shifted composer layout. Code: `Composer.footer` (`packages/app/src/composer/index.tsx`). - **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the ` track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the queue track is a lane inside the composer itself. Code: queue track inside `Composer` (`packages/app/src/composer/index.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`). -- **Queue track** — Queued prompts waiting for the agent to be free. When the host advertises `durableAgentQueueV1` the queue is the daemon's (`docs/queue-mirroring.md`): rows mirror `agent.queue.update` snapshots, every device sees the same queue, and rows survive restarts. Without the flag the track holds the legacy in-memory queue: this session, this device, gone when it ends — never presented as durable. UI: rows show edit, send now, and (durable only) move, delete, retry, discard. Code: `QueuedMessageRow` in `packages/app/src/composer/index.tsx`, outbox in `packages/app/src/stores/queue-outbox-store/`. Forbidden: "Delivery" as a label; "Queued prompt". -- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which holds follow-ups for when the agent is free and never enters the running turn. Forbidden: "Delivery", "Queued prompt". +- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which holds messages client-side until the turn ends and never enters the running turn. Forbidden: "Delivery", "Queued prompt". - **Subagent** — User-facing term for an agent session related to a parent agent session. Use **subagents** in UI copy and docs. Internal daemon/provider plumbing may say "child agent" or `child_session`, especially for provider-managed imports; do not surface "child agent" as a product term. - **Attachment tray** — The selected-attachments row inside the composer input, above the text input. Code: `renderAttachmentTray` (`packages/app/src/composer/index.tsx`). Forbidden: "Attachment bar". - **Fork** — Starting a NEW agent session seeded with a copy of another session's curated chat history. The history rides along as a `chat_history` composer attachment on a draft; the fork does **not** resume or branch the provider-side session, and the source session keeps running untouched. Two targets, one surface, one RPC (`agent.fork_context`, gated on the `agentForkContext` host feature). UI: the fork menu lives in the assistant turn footer and offers "Fork in a new tab" / "Fork in a new workspace". On a **completed** turn it sits beside the copy button and pins a boundary to that turn, so the fork stops where the turn ended. On the **in-flight** turn it sits beside the progress loader and elapsed timer, and omits the boundary entirely — `selectForkContextRows` projects the whole timeline when no boundary is given, so the fork captures everything **up to now**, including the response still streaming. That omission is what makes mid-run forking work; pinning a boundary there would silently drop the live response. Forbidden on provider-subagent (read-only) panes. Code: `useForkAgent` (`packages/app/src/hooks/use-fork-agent.ts`), `selectForkContextRows` (`packages/server/src/server/agent/activity-curator.ts`). Don't confuse with: git fork (unrelated; Paseo has no such concept), **Worktree** (filesystem isolation, not history copying). diff --git a/docs/queue-mirroring.md b/docs/queue-mirroring.md deleted file mode 100644 index b5037b21d38..00000000000 --- a/docs/queue-mirroring.md +++ /dev/null @@ -1,62 +0,0 @@ -# Queue mirroring - -The durable agent message queue holds prompts that a client admitted with an explicit delivery intent: `queue` (deliver when the agent is free) or `steer_strict` (deliver into the running turn without interrupting it). One daemon owns one queue per agent. Every connected device reads and mutates the same queue through the `agent.queue.*` RPCs, so a prompt queued from a phone is visible and editable everywhere, and it drains even when nothing is connected. - -The queue is daemon-only infrastructure (`packages/server/src/server/agent-queue/`). The composer's queue track is its client face (`packages/app/src/composer/` + `packages/app/src/stores/queue-outbox-store/`). - -## Gating - -- A client may send `agent.queue.*` only when `server_info.features.durableAgentQueueV1` is set; the delivery-intent enum postdates every released daemon. -- The daemon mirrors `agent.queue.update` broadcasts only to clients advertising `CLIENT_CAPS.durableAgentQueue`, so an old client never receives an event its outbound union cannot parse. -- Legacy `send_agent_message_request` keeps its released receipt-backed path. It never enqueues, and admission is never inferred from a message the daemon did not classify. - -## Delivery lifecycle - -``` -pending ──claim──▶ dispatching ──receipt completed──▶ removed (drainedIds) - │ └─ known failure ──▶ pending (attempts < 8) - │ └──▶ failed (attempts = 8) - └─ startup recovery finds an unresolved claim ──▶ uncertain -``` - -- The claim keeps the item in the queue in `dispatching` state, so a crash leaves recoverable state instead of a lost or duplicated prompt. Removal happens only after the receipt confirms the run started. -- Each attempt gets its own receipt keyed by a monotonic `attemptSeq`, so a retry can never collide with the previous attempt's receipt. `attempts` is the user-visible streak and resets on retry or edit. -- An `uncertain` item is never dispatched again automatically. `agent.queue.retry` is the only path that resends it. A `failed` item waits for an explicit retry or discard. -- The queue is strictly FIFO: an item that is not `pending` holds the line, because later prompts are follow-ups to the ones ahead of them. -- `steer_strict` goes through the shared steer admission and never replaces a turn. Refusal un-claims without burning an attempt; when the turn later ends the item is delivered as a normal run. - -## Images - -Image bytes are stored in the queue file and are never broadcast — snapshots carry descriptors (`id`, `mimeType`, `byteSize`). A device that did not queue the item fetches the bytes with `agent.queue.get_item_images.request` before pulling it back into its composer. Per-item image payload is bounded (16 MiB base64) along with queue length (50 items). - -## Persistence and crash points - -One JSON file per agent under `$PASEO_HOME/queues/`, written atomically at mode 0600. Every mutation appends a before/after journal entry (also 0600) before the queue file is replaced; the journal rotates under a byte bound keeping one previous generation, and elides image bytes to descriptors so it never becomes a second copy of user data. - -| Crash between | State on disk | Recovery (`activate()`) | -| ---------------------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | -| admission and claim | item `pending` | queued normally | -| claim and receipt write | item `dispatching`, attempt receipt may exist | receipt missing: `queue` intent resumes as `pending`; `steer_strict` holds as `uncertain` (the admission may have reached the provider) | -| receipt write and dispatch outcome | receipt `pending` | item held as `uncertain`, never auto-resent | -| dispatch and removal | receipt `completed` | treated as delivered: item removed, id recorded in `drainedIds` so a late enqueue retry is a no-op | - -`activate()` runs once after the server accepts connections, never during daemon initialization. It resolves claims, then resumes only never-dispatched items for agents that are already loaded and idle; agents that load on demand drain through their own running-to-idle transition. Archived agents keep their queue and never auto-run. Deleting an agent removes its queue through the normal delete lifecycle. - -## What the daemon never does - -- Never queues a prompt that arrived without an explicit intent. -- Never interrupts a turn to deliver a queue item. -- Never resends an item whose provider acceptance is unknown without an explicit retry. -- Never silently deletes an undelivered prompt; removal is a receipt or a user decision. - -## The composer side - -The queue track shows one row per queued prompt. Rows mirrored from the daemon carry the item's delivery state; rows the daemon has not acknowledged yet come from the outbox. Three contracts hold the two layers together: - -- **Snapshots replace, outbox survives.** A snapshot replaces an agent's rows wholesale behind a revision guard; entries in the outbox that the snapshot cannot know about are re-appended, so an un-acked enqueue never disappears because another device mutated the queue first. -- **The outbox is the durable copy of the enqueue.** It is written before the request goes out and cleared on the daemon's acknowledgement. A send that never got an ack — relay stall, suspended app — is retried on the next reconnect whose server info advertises the flag, verbatim, including its intent. -- **Exhausted retries stay visible.** After 8 failed flush attempts an entry is parked in a visible failed state with explicit retry and discard, not dropped. This deliberately diverges from the source, which deleted the entry and its row at the cap — that silently discards an undelivered prompt. - -Edit and send-now pull the item off the daemon queue (delete + image rehydration) before it re-enters the composer or the send path, so a taken message cannot also drain from the queue. Every mutation sends the revision the device last saw; a stale one is refused as a visible conflict and the queue refreshes — never a silent overwrite. - -Hosts without `durableAgentQueueV1` keep the pre-queue composer behavior: the queue track holds rows in memory for this session and this device only, and nothing presents them as durable. Outbox entries written against a capable host and never flushed (the host downgraded before the next connect) wait in storage; they are not shown as queued against a host that cannot honor them. diff --git a/fork/plans/tmad-desvio-0.11.1.md b/fork/plans/tmad-desvio-0.11.1.md deleted file mode 100644 index 4dec04d5297..00000000000 --- a/fork/plans/tmad-desvio-0.11.1.md +++ /dev/null @@ -1,77 +0,0 @@ -# Pluto TMAD delivery on Desvio v0.11.1 - -The user authorized adding the completed Pluto ports to the live Desvio plan, building the full basket, and deploying it on 2026-10-08. This delivery supersedes the historical no-promotion boundary in the copied Pluto evidence; it does not claim the outstanding device/provider checks passed. - -## Build inputs - -Keep Neptune's existing manifest order: `custom`, `fork/carries-0.11.1`, `fork/infi-backend-0.11.1`, `fork/infi-ui-0.11.1`. Append `fork/tmad-0.11.1`, based on the reviewed current basket `b388a10a742f7104d613facbc6661da17abfb839`. Keep `DESVIO_BASE=v0.11.1`. Do not merge Pluto's older upstream or external-carry ancestry into this basket. - -Port the feature delta from Pluto P0 `2bfcd2e19638484baf1651d69dc0be55df483bcd` to full approved basket `9584b2a669ce90a5df8c9eac66073e85124e90bb`. Exclude older custom/plugin/release-tooling changes: the current `custom` already owns those subjects. Preserve attribution through these refs and the copied [Pluto evidence](tmad-port/evidence/P6-assembly-2026-10-08.md). - -| Work | Reviewed input | Delivery | -| --- | --- | --- | -| TM-01 Stream/artifacts | `a8241e53530d6bd0a958971118d6b8b57ff80b0c` | UI, bounded storage, localized labels, optional wire facts, capability gate, artifact scan CLI | -| TM-02 durable queue | `91392d6beed3fc49f9be7496a70b8d5822957d4c` | Daemon-owned queue, receipts/recovery, dotted RPCs, permissions | -| TM-03 queue UI | `9ab91bb759be1951bdaa9cbe7bc991cafed2569d` | Revision-guarded snapshots, durable outbox, delivery badges, queue actions | -| TM-07 native Find | `5f3634ad43256c18f9f41667348c65fe1b03d7f4` | Native viewport, historical matches, menu and tab plumbing | -| TM-04 voice flow | `84f11381ceabec13d5deaff6c1e2c05dc67a6c62` | Independent capture/playback lifecycle, queued speech, receipt reconciliation, generation ownership, failure cues | -| Side-conversation repair | `fddb4fa8587ae377286ffbea3137df4c53bdc7a9` | Deliver update/removal events to capable attached clients | -| Assembly test fix | `e423a8666a30075a584f4a8e6f646a28054e6af0` | In-memory AsyncStorage in the existing session suite | -| Assembly startup fix | `9584b2a669ce90a5df8c9eac66073e85124e90bb` | One shared receipt owner injected before queue activation | - -The adapted branch carries the complete reviewed integration, including the menu union and duplicate queue-client cleanup. It is one manifest entry because the final Voice/Queue receipt wiring was reviewed as a basket. TM-05/06/08 and the typed-send default change were never implemented and remain outside this delivery. - -## Adaptations to the current base - -Upstream #5976 moved audio to `src/audio` and introduced shared plugin/voice playback. Keep that implementation; port cancellation during preparation into its shared queue, and retain browser microphone-track loss reporting. Port the existing Pluto regression tests to that module. Keep upstream #6255 archive rollback while adding queue preparation failure classification. App typecheck builds the native audio workspace first: the static import needs its generated declarations on a clean checkout, including CI and Desvio. - -## Verification and deployment - -1. Build server and app dependency stacks; format, typecheck, lint. Run focused changed-file protocol, queue, receipts, side-conversation, voice, audio, and Find tests serially. Run a synthetic-home daemon startup/recovery probe. -2. Push the durable carry branch. Append it to Neptune's manifest without reordering existing entries. Run `desvio build`; assert its result matches the tested tree. Run remote CI on the candidate; do not run full suites on a workstation. -3. Publish `mine` through the existing fork workflow, verify all seven exact npm packages, and package both desktop architectures plus Android from the verified runtime source. Record each artifact’s exact assembly SHA. -4. Deploy staged Intel bundles on Eris and Neptune first. Use detached launchd jobs and verify app/daemon version, code signature, health, and WebSocket upgrade. Deploy Saturn through launchd with a one-time continuation for the deploying agent. Deploy Linux hosts serially and verify each before continuing. -5. Record the exact source SHA, versions, check results, deployment results, and any remaining evidence gaps here. - -Physical iOS/Android captures, Korean UI review, voice-device capture/playback, credentialed provider E2E, and live-home migration behavior remain unverified. The copied-home probe and fake-provider E2E do not establish those results. Back up each live home before changing its daemon version. - -## Candidate validation - -Server/app dependencies build, typecheck, lint, and formatting passed. All 30 focused suites passed serially; the adapted native audio and prompt suites also passed (3 and 17 tests). The two-client queue E2E passed both tests. The synthetic-home startup/recovery probe recovered `pending-copy-1` at revision 1 with identical queue bytes before/read/stop and zero fake-provider turns. It first creates an isolated fake agent so the queue fixture references a real persisted record. - -Clean-checkout CI caught the missing native-audio declaration build; app `pretypecheck` now owns it. The carried script-health fixture now implements terminal activity. Pluto's Speak expectations retain upstream's deliberately independent voice-tool policy. The Hub leak check tracks newly acquired subscriptions: closed setup clients can expire after the 90-second reconnect grace, making an exact total subscriber count nondeterministic. These are build/test adaptations; they do not change deployed runtime behavior. - -## Built and deployed - -The final source is `mine@db4a750601fcd110ebec663536a66d643bc26acc`, assembled from carry `b0b92121ba4410b1392e65a9afb0e6d44bb56326`. Desvio assembly, full typecheck and lint passed. Neptune’s active manifest contains `fork/tmad-0.11.1` after the four existing entries. It retains the `v0.11.1` base. - -Both signed desktop bundles are `0.11.1-mine.261008-1523`, built from assembly `2c554ab82356116d0430baa29f28c0f0713c5235`. Its runtime source matches the final assembly exactly; the final delta contains tests and delivery evidence. The ARM bundle also passed isolated health and WebSocket startup checks. Intel bundles were staged before the build tree was reassembled. - -All seven exact `@camerontaylor/paseo-*` packages are published as `0.11.1-fork.2`. [Publication run 37728821931](https://github.com/camerontaylor/paseo/actions/runs/37728821931) succeeded; the release tag points to the final assembly. `latest` advances with publication; the optional `fork` dist-tag update was denied by npm’s trusted-publisher permissions. - -| Host | Installed version | Verified | -| --- | --- | --- | -| Saturn, Neptune, Eris | `0.11.1-mine.261008-1523` | Signed app, daemon version, IPv4/IPv6/localhost/Tailscale health 200, WebSocket 101; external daemon ownership retained | -| Ceres, Makemake, Pluto | `0.11.1-fork.2` | Exact systemd pin, active service, daemon version, IPv4/IPv6/localhost/Tailscale health 200, WebSocket 101 | -| Quaoar | Previous version | Host offline; not deployed | - -Each reachable host’s durable home was backed up before replacement. Mac deployment logs are `~/.paseo-fork/deploy--0.11.1-mine.261008-1523.log`; Linux logs are `~/.paseo-fork/deploy-tmad-fork.2.log`. Completed Mac deployment jobs were retired. Saturn’s one-time continuation resumed this conversation after its daemon restart. - -Pluto’s tracked NixOS pin and authoritative manifest were committed and pushed to infra `main` (`8ea923d`, integrated as `7b38f27`). The new system closure is `b8csffip3bmvxscxrab0xz1zvfzxybhz`; the closure change was limited to Paseo, and no failed system units remained. Package-age exceptions on Pluto and Makemake were temporary and scoped to the verified package. - -Android’s release build succeeded from the final assembly. Signature verification passed for `sh.paseo.debug`, version `0.11.1`, code `11001`, ARM64. Artifact: Neptune `~/.paseo-fork/Paseo-debug-0.11.1-tmad-db4a75060-arm64.apk`; SHA-256 `30815b3d4e907c38f90c3bb38018f01a001d1f3364ccc0206f9441ccc636ae44`. Taildrop delivery to `camerons-s24` succeeded, recorded in `/tmp/paseo-tmad-android-delivery.log`. Phone installation and device QA remain unverified. - -## CI limits - -[Final CI 37728476105](https://github.com/camerontaylor/paseo/actions/runs/37728476105) passed typecheck, lint, formatting, Linux server tests, macOS watcher tests, app tests, SDK, relay, all CLI shards, and both desktop suites. Windows passed 6,359 tests and failed one unchanged worktree-bootstrap assertion comparing the equivalent `RUNNER~1` and `runneradmin` temporary paths. - -Final browser results: - -| Shard | Passed | Failed | Remaining failures | -| --- | --- | --- | --- | -| 1 | 157 | 2 | First-prompt authoritative hydration and upward-scroll position | -| 2 | 196 | 1 | Chat-find setup locator matches both user row and pinned prompt; one other test passed on retry | -| 3 | 160 | 2 | Pinned-prompt transition and archived side-conversation removal; two other tests passed on retry | -| 4 | 195 | 5 | Four viewed-timeline locators match both user row and pinned prompt; nested script completion timeout | - -The side-conversation archive failure also occurs in pre-port [baseline CI 37718194103](https://github.com/camerontaylor/paseo/actions/runs/37718194103); the carried broadcast unit test passing does not establish the browser archive flow. The baseline also failed upward-scroll position. The other failures remain unresolved; do not label them baseline failures without matching evidence. CI completed with failure. Two CodeRabbit attempts failed to connect to its review service; neither produced a review verdict. diff --git a/fork/plans/tmad-maintained-port-plan.md b/fork/plans/tmad-maintained-port-plan.md deleted file mode 100644 index cd4028a55a2..00000000000 --- a/fork/plans/tmad-maintained-port-plan.md +++ /dev/null @@ -1,323 +0,0 @@ -# Maintained tmad feature ports - -Status: planning consensus reached with Opus 5.5; implementation has not started. -Date: 2026-10-02. - -## Outcome - -Carry the useful `tmad4000/paseo` features as independently removable Desvio inputs. Keep receiving source Stream fixes and UI improvements without importing the source fork's release machinery or replacing our `custom` and infi implementations. - -Stream is the first complete feature to port. Persistent message queues and voice follow-ups are a separate delivery sequence. A Stream triage queue contains captured moments; a message queue contains prompts awaiting delivery. Neither should create a dependency on the other. - -This plan authorizes no deployment. The next implementation step is the baseline and extraction rehearsal below. Production manifest edits, publication, and switching the daemon follow a reviewed implementation. - -## Evidence and baseline - -| Input | Snapshot checked on 2026-10-02 | How to use it | -| --- | --- | --- | -| Desvio release base | `v0.11.0-beta.3`, commit `6166a7aca5e3184e8ab505caad28f6a595816414` | Initial parent for independent ports. | -| Our custom branch | `cbd1210c7d15fbdaac02cab8375cdcf2dd6bd234` | Current custom behavior and integration requirements. | -| Source main | `f0d5507d21cf7f6d86c792d235f3c27156a27d7a` | Frozen intake snapshot; version reservations are excluded. | -| Source integration | `51fb7693d`, source PR #21 | Rebuilt upstream changes and fork features together; never import this entire commit. | -| Current Desvio manifest | `~/.paseo-fork/manifest.txt` | Community carries, then custom, then IP-01 through IP-14. Preserve this order. | -| Build branch | `mine` | Disposable and moving during concurrent work. Capture a successful assembly for verification; do not author against its current tip. | - -The source integration did not retain the claimed release as a Git ancestor. The merge base between the source snapshot and our current release is `dd8a111c30dcc6457a7c4eddaddc5346967fa57f`. A direct tree comparison now touches 1,158 paths, including unrelated upstream differences. That is evidence against merging source main; it is not a count of feature files or expected conflicts. - -Use the source's declared `v0.10.0-beta.1` integration tree to identify fork content, then adapt that content to our pinned release. Feature code in the integration commit needs extraction even when its original PR is known. Earlier PR patches are provenance and useful change boundaries, not guaranteed patches against beta.3. - -The research worktree is older than `custom`. Read current files using the pinned refs or a fresh worktree. Re-resolve these snapshots when implementation starts because custom and the manifest may have moved. - -Source references: [branch policy](https://github.com/tmad4000/paseo/blob/f0d5507d21cf7f6d86c792d235f3c27156a27d7a/FORK.md), [integration PR #21](https://github.com/tmad4000/paseo/pull/21), [Stream pins #19](https://github.com/tmad4000/paseo/pull/19), [voice follow-ups #23](https://github.com/tmad4000/paseo/pull/23), [queue controls #25](https://github.com/tmad4000/paseo/pull/25), [busy send choices #32](https://github.com/tmad4000/paseo/pull/32). - -Local constraints: [fork ownership](../README.md), [upstream sync](../upstream-sync.md), [protocol compatibility](../../docs/protocol-compatibility.md), [timeline ownership](../../docs/timeline-sync.md), [route ownership](../../docs/expo-router.md), and [infi work items](infi-pc-intake-work-items.md). Read current versions from custom before implementation; the infi intake's original base is historical. - -## Decisions - -1. Maintain a curated port, with a frozen source snapshot and a source-to-port ledger. -2. Preserve the source Stream modules, component boundaries, models, tests, and interaction design where compatible. Adapt shared host boundaries rather than rebuilding the feed. -3. Keep Stream as one complete vertical slice on a tracked branch. Separate persistent queue, queue UI, voice runtime, and unrelated standalone features. -4. Append new branches after the existing manifest. Their position does not establish independence; ancestry and actual runtime dependencies do. -5. Start Stream at the pinned upstream release. Start queue at a frozen custom commit, and queue UI/voice at their explicit prerequisite branches, so their own tests exercise our cancellation and submission contracts. Keep feature implementation commits out of custom. Put unavoidable Stream integration in an explicitly paired bridge if it cannot live in the independent feature branch. -6. Preserve existing send, cancellation, tab, route, and protocol contracts. Adopt source improvements into existing owners when a capability already exists here. - -### Branch order alternatives - -| Option | Advantages | Cost and restriction | Decision | -| --- | --- | --- | --- | -| Release-based port appended after current carries | Existing merge contexts stay stable for the initial addition; ancestry contains only upstream and the port; easy feature removal. | Shared files may need adapted merges or a small bridge; source sync still needs review. | Default. | -| Release-based port before custom | Custom integrates against the feature first; can be useful if custom is deliberately being redesigned to consume it. | Inserting changes subsequent merge contexts. Recorded resolutions may stop matching or remain textually applicable while becoming semantically wrong. Requires validating the entire suffix. | Viable, but no demonstrated benefit for initial intake. | -| Port based on custom and appended after custom | Matches existing infi intake practice; tests exercise custom-dependent behavior before assembly. | Captures a custom ancestor; cannot move ahead of custom while preserving branch independence. Need to audit inherited custom changes on later sync/removal. | Selected for queue/voice, whose correctness depends on custom; record the floor. | -| Merge source main | Receives all source changes directly. | Imports squashed upstream history, conflicting older implementations, branding and releases. Removal couples all features. | Rejected. | - -Do not merge custom or mine into a release-based port to solve an assembly conflict. That imports the other layer into its ancestry. An adaptation in a source branch must also compile on its declared base; otherwise use a small coupled bridge after the dependencies. - -Later upstream upgrades should merge the newly pinned upstream release into the Stream port and merge the updated custom branch into the queue root, then update dependent branches in order. Review each resulting feature delta against its declared base and rerun its gates. Keep source synchronization and base upgrades in separate review batches. Preserve existing local port commit identities; do not repeatedly regenerate every branch from a squash. If custom history is rewritten, re-anchor dependent ports explicitly and audit for superseded custom code; an ordinary merge is not sufficient. - -Reconsider an earlier Stream position only after measured recurring conflicts justify it. A base upgrade is a convenient time to compare both orders, but does not make reordering free or guarantee that every rerere entry is invalid. Require isolated assembly, semantic review and removal evidence for the proposed order before changing the live manifest. - -## Branch and removal contract - -Proposed branch names are stable ownership boundaries, not branches created by this planning task. - -| ID | Branch | Contents | Required branches | -| --- | --- | --- | --- | -| TM-01 | `intake/tmad-stream-flow` | Stream capture, storage, optional wire contract, artifacts, feed, pins, triage and Chat/Stream interaction. | None beyond its pinned release. | -| TM-01B | `intake/tmad-stream-bridge` | Only custom/infi adaptations that cannot compile in TM-01 alone. Create only if rehearsal establishes a need; cut from custom plus declared prerequisites and append immediately after TM-01. | TM-01 and the specific custom/infi owners it adapts. | -| TM-02 | `intake/tmad-message-queue` | Durable daemon queue, explicit API, idempotency, receipts and storage recovery; cut from pinned custom. | Its recorded custom floor. | -| TM-03 | `intake/tmad-queue-ui` | Durable outbox, edit/reorder/send controls, queue mirroring, explicit composer modes. | TM-02. | -| TM-04 | `intake/tmad-voice-flow` | Voice attachment lifecycle, queued speech, playback recovery and failure feedback. | TM-02; TM-03 only for shared UI that is actually required. | -| TM-05 | `intake/tmad-voice-mute` | Verbal input mute/unmute with visible capture state. | TM-04 unless verified separable. | -| TM-06 | `intake/tmad-ios-background-voice` | Native iOS background capture changes. | TM-04 and compatible native audio implementation. | -| TM-07 | `intake/tmad-native-find` | Reconciled native Find wrapper, matches and viewport on the existing search model/RPC; cut from `v0.11.0-beta.3`. | No Stream dependency in either direction; removal group Native Find. | -| TM-08+ | One branch per selected standalone feature | CLI daemon target, CLI tab opening, or other chosen enhancements. | Record per feature. | - -Dependent branches may start from their prerequisite feature branch. That dependency remains present even if its manifest line is removed. Maintain a removal group listing every dependent branch and bridge; commenting only the prerequisite is insufficient. - -Initial append block, once each branch passes acceptance: - -```text -# Existing community, custom and infi lines retain their current order. -intake/tmad-stream-flow # TM-01; source snapshot; verified base; removal group Stream. -# intake/tmad-stream-bridge # TM-01B; only if required; removal group Stream. -# Add queue and voice lines later, in dependency order, after their own gates. -``` - -Stream removal means disabling TM-01 and TM-01B, if present. No unrelated queue, voice, infi or custom branch may depend on Stream. Native Find removal means disabling TM-07 alone; both features must work when the other is absent. Queue removal disables TM-02, TM-03, TM-04 and their descendants. A queue-plus-voice bundle is removable together; each component is not necessarily independently runnable. - -Record each branch's base SHA, allowed ancestors, runtime requirements, and removal group beside its ledger entry. Compare its commits and delta against the declared base before adding it. A branch claiming release independence fails this check if custom, mine, or another unrecorded carry is an ancestor. - -## Scope and duplication decisions - -| Feature | Source | Disposition | -| --- | --- | --- | -| Stream/artifact feed, discoverability, pins and triage | #1, #10, #16, #19, reconciled by #21 | First delivery; preserve the complete interaction flow and source tests. | -| Durable follow-up queue, edit/send-now/recovery and visible send choices | #23–26, #30–32 | Next delivery sequence; adapt admission semantics before importing UI defaults. | -| Voice lifecycle, playback and failure recovery | #13–15, #22–23 | Follow durable queue; separate device verification from daemon tests. | -| Verbal mute/unmute | #17 | Optional voice follow-up, with capture semantics visible to the user. | -| iOS background dictation | #14 | Separate native build and physical-device gate. | -| Remember default CLI daemon | #8 | Independent small port after checking current CLI support. | -| CLI-created sessions open tabs | #5 | Separate API/tab-policy review; preserve custom subagent close behavior. | -| Native chat search wrapper | #11/#21 | Current custom's native `chat-find/index.tsx` is a no-op stub; web search exists. Port the reconciled native wrapper and viewport using the existing search model/RPC on its own branch. Preserve native Find in Chat through the tab menu. The current source panel has Chat/Stream segments, so native Find is not a strict Stream dependency. | -| Recent-focus Back | #9 | Existing infi navigation history owns this. Add a missing mobile control there only if needed; exclude the duplicate history store. | -| Stream pins | #19 | Distinct from IP-11's scroll-following prompt pin; both can coexist without sharing selection state. | -| Sidebar filtering/recency/unread/tab sorting | #25, #27, #33 | Defer until Stream is stable; reconcile with IP-09/10/12 and upstream attention behavior in a separate branch. | -| Summary default and Quiet tool calls | #34 | Optional. Existing tool presentation is the owner; do not add model summaries from infi. Quiet has a known approved-command visibility gap in the source PR; resolve before adopting it. | -| Long user message clamp | #18 | Optional standalone presentation change if still missing upstream. | -| Provider startup/ACP rejection messages | source post-#21 changes | Evaluate as independent fixes against current upstream; no automatic inclusion in Stream. | -| Branding, app identifiers, TestFlight, auto-updater, source CI, version reservations | #20/#21/#28/#29/#35 and fork build files | Excluded. Use our established packaging and release channel. | - -The [Quiet PR](https://github.com/tmad4000/paseo/pull/34) explicitly records that a successful approved command can disappear after approval resolves. Importing the source's latest code is therefore not an acceptance criterion by itself. - -## Source tracking - -Create `fork/plans/tmad-port-work-items.md` on custom during implementation as the single owner of tracking status. Keep this plan for the integration decision; put ongoing status and operational steps in the ledger. Link it from fork/README.md. Documentation belongs on custom so disabling a feature preserves its provenance and removal record. Mark removed features disabled; retain their rows. - -Each selected source change has: - -- Source repository, PR, full commit SHA or range, and effective source snapshot. -- Feature ID, source paths, test paths, and local branch. -- Disposition: applied unchanged, adapted, upstream already supplies it, intentionally excluded, or deferred. -- Source blob ID for every core file, local blob ID, any path mapping, and an explicit exception when our adaptation changes the contents. -- Local commit SHA after commit, adaptation rationale, dependencies, and the verification artifact. - -Keep three distinct markers: last source head inspected, last source head fully classified, and the effective source snapshot for each ported feature. A skipped source commit still gets a disposition. Advancing the classified cursor does not mean every feature has incorporated that head. - -Use `Source-Repo`, `Source-Commit`, and `Port-Feature` trailers on imported/adapted commits. A combined extraction cites all relevant source commits; a rewritten adaptation records why. Keep local-only fixes as separate commits so later source fixes can be recognized and compared. - -Preserve source directories such as `companion-stream/` and `artifacts/` unless our architecture requires a move. If a move is required, keep a path mapping. Maintain a seam table for source agent-panel integration, accepted-event capture, storage/projections, protocol delivery, and file navigation. This table owns the differences that future updates must revisit. - -Core files are unchanged between #21 and the inspected source head. They are not all unchanged between #19 and #21: the reconciliation updates the feeds and collectors and adds artifact backfill coverage. Use the reconciled source snapshot for fidelity checks. For unadapted files, the source and local blob IDs should match. For changed files, record the intentional delta and its tests instead of asserting byte equality. Shared connection files include `agent-panel.tsx`, `workspace-tab-menu.ts`, `segmented-control.tsx`, `turn-footer.tsx`, `message.tsx`, and `agent-stream/view.tsx`; review their Stream-specific changes alongside infi's plan, prompt-pin and file-link changes. - -The tab menu is an explicit shared seam: custom adds subagent/side-conversation behavior and source adds View Stream/Find actions. Preserve both, and record TM-01B if their integration needs a custom-dependent implementation. - -### Update loop - -1. Fetch source main into a research ref and record its SHA. Keep the previous reviewed SHA available. If history was rewritten, compare snapshots and PRs; do not assume a linear range. -2. Review every new source commit/PR, including integration commits. First-parent history identifies merged batches; blob comparisons detect changes despite squash/rewrite. Path filters find likely changes, but new files and shared helpers must be considered too. Check upstream's pinned release for equivalent features first. -3. Classify the whole range in the ledger. Keep the source and upstream sync batches separate. -4. Apply selected changes on a scratch branch from the relevant maintained port. Use `cherry-pick -x` when the complete patch fits; otherwise extract selected hunks and cite the full source change. Never cherry-pick the source's mixed upstream integration wholesale, including with `-m`. -5. Carry source tests, then run the relevant seam tests and UI checks. Review local fix overlaps before accepting source replacements. -6. Assemble against a frozen copy of the current manifest and refs. Inspect both conflicts and clean merges in shared files. Use rerere for repeated resolutions, then review what it staged. -7. Fast-forward the maintained port only after its review passes. Update the effective snapshot and verification entry. Rebuild the reviewed production basket through the normal process; source fetch alone must never change the shipped port. - -At the initial port, rehearse this loop on a real historical update: port Stream's feature content at PR #19 (`af247e4f4`), then apply only the Stream changes from `af247e4f4..51fb7693d` through the intended seams. This changes five core files by 200 additions and 65 deletions: the two feeds, collector, companion-stream and artifact backfill test. Compare the resulting core blobs against `51fb7693d`; record intentional local differences. Extract the relevant shared-file changes too, without importing the rest of #21. The endpoint is the reconciled content selected for delivery, not throwaway pre-feature code. Record changed paths, conflicts and adaptation effort as the first evidence that tracking remains economical. - -For UI fidelity, capture the frozen source snapshot and the port in the same states on desktop and compact web. Include native source reference captures where practical and require native evidence for our port. Compare the captures side by side: Chat/Stream switching, reply controls, pins/triage, artifacts, tab actions, long entries, errors and loading states. Record every visible difference as an intended adaptation or a defect. Hash parity cannot prove that a changed host panel preserves layout, reachability, gestures or focus. - -Reassess the architecture if successive Stream improvements repeatedly require changing the same host integration code. Prefer a narrower host interface or one contained adapter over duplicating Stream. Do not add abstractions merely to anticipate changes that have not occurred. - -No unattended updater or schedule is created by this plan. Check source during upstream syncs and before a feature release; a later automation can report candidates without promoting them. - -## Compatibility contracts - -### Stream - -- Capture accepted canonical live events after existing stream coalescing. Do not reconstruct invented historical outcomes or create a second timeline owner. -- Preserve bounded source moments and excerpt sizes, stable identities and ordering, persisted pins, triage state, and reconnect behavior. Verify pin and manual-entry bounds explicitly. Decide an explicit bound for artifact path metadata after measuring current storage; bounded captured moments alone do not bound pins or the whole record. -- Keep Chat mounted while switching to Stream. Preserve drafts, attachments, scroll position and the active agent. A Stream selection returns to the correct existing Chat control; it must not automatically send an answer or cancel work. -- Preserve questions, permissions, plans, final responses, failure outcomes and file links. Stream remains a projection of daemon facts; selecting a moment cannot grant permission or infer agent state. -- Keep artifact containment and file-open rules from current custom/IP-01. Do not restore recursive `fs.watch`; read the file-observation constraints first. End-turn scans need bounded work and explicit limits on attribution when other processes change files. -- Wire fields are optional. Gate Stream once on our daemon feature `companionStreamPortV1`; release observations when the owning view closes. Old clients must not receive unknown top-level events. -- Rename the source flat `update_companion_entry_request`/response to `agent.companion.update_entry.request`/response and record the mapping. Give mutations `workspace.write`, read operations `workspace.read`, and responses their matching permission; update every authorization map and client capability default. Do not advertise the source's `companionStream` capability for our renamed RPC contract: a source-built client would otherwise try an unsupported flat operation. Verify both cross-fork connections stay parse-compatible but correctly gate the unsupported feature. Tag necessary compatibility code with our release version and expiry rather than copying the source's version claim. -- Review errors and localization while preserving source layout. Surface failed mutations; do not retain silent catch blocks for pins or triage actions. - -### Queue and composer - -- Preserve the current behavior of old `send_agent_message_request` calls with no new queue intent: they go through the existing beta.3 receipt-backed interrupt path, including deduplication. The source currently queues omitted `activeTurnBehavior` and that path omits the receipt service; do not copy either change into our daemon. Durable queue admission requires explicit client intent. -- Define explicit queue and strict steering operations/capabilities. New enum values must not be sent to an old daemon. New requests and responses use the current dotted names and have exhaustive authorization entries and client defaults. -- If a port changes the source queue or voice feature contract, use a distinct capability/version and record its source mapping. Never advertise a source capability while accepting different requests or acknowledgement semantics under it. -- A queue item is durably accepted once by stable identity. Queue revisions govern edits, reorder and deletion. A stale device cannot silently overwrite another device's edit. -- Uncertain dispatch remains visible for reconciliation. Removal waits for a correlated receipt. Refused steering never interrupts a turn and never deletes the queued item. Automatic retry must not resend an item whose provider acceptance is unknown. -- Review the capped dedup horizon and crash points between admission, provider dispatch, receipt and queue removal. Repeated reconnect cannot create duplicate turns. -- Preserve the item after the source outbox's eight-attempt limit. Use a visible failed/pending state with explicit retry or discard; no silent deletion of an undelivered prompt. -- Define startup recovery: load existing queue state without dispatching during daemon initialization; after agents/providers are ready, resume only items known never dispatched. Hold ambiguous claims for inspection. Archived agents retain their queue and do not auto-run; deleting an agent removes its queue through the normal lifecycle. -- Treat queue persistence and journal as user data. Bound journal bytes and rotations, file permissions, image payloads and queue length. Avoid copying image bytes into repeated journal snapshots where a stable attachment reference suffices. Retention and recovery invariants must remain testable. -- The canonical app submission owner remains `dispatchComposerAgentMessage`. Introduce a queue admission action without creating a submitted timeline row prematurely; drain/send-now acknowledgement reconciles into the existing identity system. The server's accepted prompt creates one canonical user row. Speech and reconnect follow the same boundary. -- Existing local queues keep their existing meaning against old hosts. A capability gate must not portray them as durable cross-device queues. Follow the repo's dated COMPAT convention for any retained transition path. - -### Voice and lifecycle - -- Attach/detach, mute, playback interruption, transport loss and STT failure do not cancel the agent, pending permissions, children or side conversations. Agent interruption remains an explicit command. -- Speech gets a stable queue item ID and truthful queued/sent/error feedback. Voice does not claim provider delivery from a local transcript or socket send. -- Retain attachment ownership and transport-generation checks across reconnects; a different device cannot seize an active recording session accidentally. -- Verbal mute leaves capture active to hear unmute. Show that state clearly; hardware capture stop remains a separate action. Validate local STT/VAD and speech echo behavior before promoting verbal control. -- Preserve the custom ACP/GJC admission and cancellation fences and upstream provider-wrapper forwarding. A source manager merge that loses these fences fails even if TypeScript passes. -- Native background claims require a rebuilt native binary and physical-device evidence. Simulator or browser layout checks cannot establish microphone capture, audible playback or background behavior. - -### Existing custom/infi flow - -- Side conversations retain their own panel and routing semantics. Stream and voice must not convert side questions into foreground sends. -- Use the existing route/tab navigation owners. No parallel focus history store, startup restore loop, or duplicate route deck. -- Opening a subagent uses the existing per-client tab/open-label rules. Closing its tab must not archive the subagent; root-agent close follows the existing archive policy. Audit any source MCP close-tab implementation against this. -- Prompt pin, plan copy/handoff, recent agents, status pulse and source-aware file links retain their behavior with Stream on and off. The source branch may not silently replace these carries through a clean merge. -- Use distinct labels: Stream's persistent notes are `Stream pins`; IP-11's scroll-following context is `Pinned prompt`. Keep their state and actions separate, with localized labels matching the glossary. Preserve the source panel's Chat/Stream flow; native Find continues through the existing tab-menu/search owner, not a resurrected search scaffold. - -## Delivery sequence - -### P0 — freeze and prove the baseline - -Owner: integrator. Deliver a snapshot record before feature code changes. - -1. Freeze base, custom, source head, manifest order and every resolved carry SHA. Save the current successful assembly if one exists; do not follow moving mine during experiments. -2. Assemble the baseline in a separate clone with its own config, index, rerere cache, branch and build tree. A worktree shares repo state and is not sufficient isolation for a Desvio order experiment. Do not point scratch tooling at `~/.paseo-fork`'s live build tree. -3. Run baseline build/typecheck/lint and the relevant existing composer/lifecycle/navigation checks. Record pre-existing failures separately. A failing baseline is not evidence against the port. -4. Extract the source delta and classify selected features, duplicate behavior, build files and source-only dependencies. Confirm licensing/attribution for the copied files from the repository license. - -Exit: reproducible baseline; input SHA list; feature/file map; no unknown branch ancestry. - -### P1 — Stream extraction and maintenance rehearsal - -Owner: Stream porter. Deliver TM-01 and its provenance, with no production manifest edit. - -1. Start from the pinned release. Extract the reconciled Stream and artifact vertical slice rather than replaying all historical source ancestry. -2. Preserve modules and tests; add the smallest host seams necessary for current event capture, observations, storage, file navigation and the panel host. -3. Complete the PR19-to-#21 source-update rehearsal described above. Show where source UI changes apply unchanged and where adapters need updates; verify the final content against the reconciled snapshot. -4. Verify standalone compilation and focused tests. Merge into the frozen baseline assembly; resolve semantic interactions with custom and IP-01/09/10/11/12. -5. Create TM-01B only if a custom/infi adaptation cannot compile independently. Its scope and removal coupling must be explicit. -6. Capture matched source and port desktop/compact browser evidence and compare it side by side, classifying every visible difference. Then capture native evidence for the actual carried navigation and control surfaces, with native source references where practical. Check locale parity, including Korean and every locale in the current app. Use the source Stream doc's manual scenarios as a starting point and add current pins/triage behavior that the older prose omits. - -Exit: source snapshot parity for selected Stream behaviors; maintenance rehearsal recorded; no queue dependency; preservation of existing custom/infi flows. - -### P2 — prove independent removal - -Owner: integrator. Deliver with/without assembly evidence. - -1. Build the frozen baseline plus Stream. Build the same baseline with every Stream removal-group line absent. Preserve all unrelated line order and SHAs. -2. Confirm the disabled assembly's application source tree matches the original baseline, excluding explicitly recorded documentation changes. The merge histories may differ; compare trees and behavior. -3. Run the affected existing composer/navigation/subagent checks on the removal assembly. Confirm no compile-time imports or runtime calls remain dependent on Stream. -4. Expect data loss on a feature-free rollback: beta.3's agent storage uses a stripping `z.object` schema, and an ordinary record rewrite can discard `companionEntries`. Our default rollback policy is to back up agent records and export the Stream fields before disabling it; do not add a permanent generic-storage change to custom for this port. Confirm the loss and recovery using copied development data. Recovery restores only Stream fields for matching agent IDs after re-enabling; it must not replace newer non-Stream metadata with an old complete record. Document the backup/export and merge procedure before first promotion. A user can intentionally discard this feature data when removing the feature permanently. -5. Queue/voice later require their own removal-group exercise, with pending items present. Disabling the feature must not dispatch or delete those items. - -Exit: exact removal group, verified baseline restoration and explicit persisted-data rollback behavior. - -### P3 — durable queue foundation - -Owner: queue porter. Deliver TM-02 on the frozen custom base before queue UI or voice admission changes. Its focused tests run against the actual custom cancellation boundary, not an upstream-only stand-in. - -1. Write the explicit API/legacy behavior contract and reuse the current authorization, receipt and observation conventions. -2. Port persistence, atomic updates, revisions, claims and delivery acknowledgement. Address retry/dedup/startup/journal risks in the source implementation before exposing the feature. -3. Prove restart, ambiguous send, refused strict steer, image round-trip, concurrent edits and archive/delete behavior with focused service/daemon tests. -4. Verify old app/CLI/SDK requests against the new daemon and new feature-gated clients against an old daemon. - -Exit: durable queue contract established without changing legacy sends or cancellation. - -### P4 — queue UI and cross-device behavior - -Owner: composer porter. Deliver TM-03. - -1. Port outbox and controls through current composer/submission ownership. Preserve draft attachments and editing recovery. -2. Exercise two independent clients: enqueue/edit/reorder/delete, reconnect, queue mirroring and receipt-driven transition to one canonical submitted row. -3. Keep explicit Steer, Queue and Interrupt affordances. Choose the typed-send default after comparing source defaults with our current behavior; do not infer this product choice from a source merge. -4. Test retry exhaustion and uncertain delivery as visible recoverable states. - -Exit: user-visible state matches durable acceptance and provider delivery; no duplicate row, lost item or accidental interrupt. - -### P5 — voice in staged branches - -Owner: voice porter. Deliver TM-04, followed separately by TM-05/TM-06 if selected. - -1. Port lifecycle decoupling and playback/error recovery against current runtime owners. -2. Add speech-to-queue admission with stable identity and real queued/sent feedback. -3. Prove running-turn, pending-permission, subagent and side-conversation survival through voice attach/detach and transport failure. -4. Run focused real-provider proofs. Verify core behavior on Claude, Codex and our custom ACP/GJC paths; claim support only for providers exercised. Add another provider when its implementation differs at the seam. -5. Exercise physical microphone, playback, echo, lock/background/foreground, reconnect and owner contention on supported native platforms. iOS background work has its own native binary gate; Android foreground support must not inherit an iOS background claim. - -Exit: explicit per-provider/per-platform evidence. Unsupported or untested native options remain unpromoted. - -### P6 — standalone ports and promotion - -Port TM-07 Native Find from the pinned release with its own provenance and removal group. Verify it against the existing search service, including history loading, selected-row reveal/highlight, tab-menu invocation and cleanup on panel hide. Build/check both Stream without Native Find and Native Find without Stream. Then port the chosen CLI/navigation/presentation extras separately, after checking upstream and infi overlap. Each branch gets provenance, acceptance and a removal group before appending it. - -Before promotion, update the ledger with final inputs, local commits, tests, screenshots, device evidence, known limits and removability. Present the exact manifest additions and built artifacts for review. A push to mine publishes; production restart on 6767 needs the user's permission. Do neither as part of this plan or its experiments. - -## Verification matrix - -Run only relevant test files, serially where they are resource intensive. Extend existing suites and use their scripts. Never run the full local test suite. After implementation changes, rebuild owning packages, then run typecheck and lint. Format through npm scripts before commits. - -| Boundary | Required evidence | -| --- | --- | -| Stream model/capture/storage | Source companion model, server companion and artifact collector suites; pin/triage persistence, bounds and live-event ordering. | -| Protocol | Source artifact/Stream schema cases adapted to current schemas; generated validator build; old-client parsing and no unknown push delivery; capability-absent client behavior. | -| Authorization | Existing `packages/server/src/server/authorization/index.test.ts` and operation map checks for every added operation and event. | -| Stream UI | Matched source/port desktop and compact captures plus port native evidence: needs-a-reply, questions/permissions/plans, pins/triage, long entries, errors, file navigation, draft/scroll preservation and reconnect. Every visible difference classified. | -| Native Find | Native search model/RPC integration, loaded and historical match reveal, tab menu and hidden-panel cleanup; separate removal, with/without Stream checks. | -| Existing UI carries | Current plan copy/handoff, prompt pin, recent agents, navigation, status pulse, subagent tab close and side-conversation suites on the integrated assembly. | -| Queue | Source store/service/send-or-queue suites and daemon mirroring e2e, adapted for our explicit legacy contract and recovery behavior. | -| Composer | Existing actions/submit/queue-sync plus outbox model; two-client receipt, attachment and identity checks. | -| Cancellation/provider wrappers | Existing custom agent-manager, ACP/GJC and provider-wrapper tests; focused live-provider proof of refusal without turn replacement. | -| Voice | Source voice runtime/failure/session/turn-controller tests; running-agent survival and real microphone/playback/reconnection evidence. | -| Build/removal | Standalone feature build; isolated full basket build/typecheck/lint; removal assembly and copied-data re-enable exercise. | - -Resolve actual filenames from the target branch before dispatch. Useful source paths include `packages/app/src/companion-stream/model.test.ts`, `packages/server/src/server/agent/companion-stream.test.ts`, `packages/server/src/server/agent/artifacts/collector.test.ts`, `packages/server/src/server/agent-queue/{store,service,send-or-queue}.test.ts`, `packages/server/src/server/daemon-e2e/agent-queue-mirroring.e2e.test.ts`, and `packages/app/src/stores/queue-outbox-store/model.test.ts`. - -Use `npx vitest run --bail=1` only under the appropriate existing test config. Browser/native checks use the existing npm scripts and harnesses described in [QA](../../docs/qa.md) and [mobile testing](../../docs/mobile-testing.md). Save command, commit inputs, result and evidence paths; a historical green result does not verify a new base. - -## Failure scenarios and response - -| Failure | Detection | Response | -| --- | --- | --- | -| Source UI polish repeatedly conflicts with rewritten host code | Historical update rehearsal and later seam-change records. | Preserve more source layout and narrow the adapter. Defer the update rather than copy a partial flow. | -| A clean merge loses custom cancellation or submission identity | Focused ACP/GJC, provider-wrapper and canonical-row checks on the assembled tree. | Fix the owning port/bridge; do not patch mine or hide the fix in custom. | -| Old clients send different actions after queue import | Mixed-version tests, including absent activeTurnBehavior. | Restore legacy semantics and add explicit capability-gated intent. | -| Rerere stages an obsolete resolution | Review replayed diffs and execute affected tests. | Forget and relearn the specific resolution in the experiment clone first; never wipe the whole live cache. | -| Removing one manifest line leaves imported code through descendants | Ancestry audit and removal-group rebuild. | Remove the full declared dependency group; reduce accidental ancestry before promotion. | -| Rollback strips persisted pins or abandons queued prompts | Expected stripping in beta.3 storage; copied-data downgrade/re-enable exercise. | Back up/export feature data before rollback; restore only feature fields after re-enabling, preserving newer ordinary metadata. Export/recover pending prompts before disabling queue delivery. | -| Source main update pulls another upstream snapshot | Full range classification and file/base delta review. | Extract selected feature changes; upgrade our upstream base separately. | - -## Completion and consensus - -This planning task is complete when the plan identifies the selected feature boundaries, tracking workflow, branch/order decision, delivery steps, acceptance evidence, and rollback constraints, and the Opus advisor explicitly agrees after reviewing revisions. - -Implementation readiness is separate: P0/P1 must establish current baseline and maintenance feasibility before adding a port to the live manifest. Product choices for optional features and the typed-send default remain explicit decisions at their delivery stage; they do not block the Stream plan. - -Advisor: Opus 5.5, agent `7f4ace4b-f384-47a6-a7c0-7b6803203360`. -Review record: - -- First discussion: agreed on curated ports and appending; Opus recommended custom-based queue/voice and content hashes for Stream tracking. Incorporated both. -- Evidence corrections: reconciled Stream files differ from PR19; native Find uses the retained upstream search model rather than the removed scaffold; rerere entries can still replay after reordering; feature-free storage can strip optional data. Opus accepted all four corrections. -- Final review: Opus gave APPROVE conditional on a real PR19-to-#21 rehearsal, matched source/port UI captures, and an explicit Native Find branch/base/removal group. All three requirements are incorporated above. Opus stated no further review was needed once they were included. -- Additional recommendations incorporated: verb-based RPC naming, distinct feature capability, explicit tab-menu seam, and the expected-loss rollback policy. -- Confirmation after edits: Opus reread every condition and recommendation in the saved file, explicitly confirmed consensus, and reported no remaining blockers. P0/P1 remain implementation gates. - -Planning checks: no application source, live manifest or daemon was changed. This worktree lacks local `tsgo`/`oxfmt` executables; attempted typecheck failed before compilation, and lint reported errors in untouched existing files. The npm formatter explicitly excludes `fork/**/*.md`, so the plan is outside that formatting gate. No runtime compatibility or UI parity claim is made by this planning task; those remain P0–P6 acceptance work. diff --git a/fork/plans/tmad-port-work-items.md b/fork/plans/tmad-port-work-items.md deleted file mode 100644 index e57ab3a275b..00000000000 --- a/fork/plans/tmad-port-work-items.md +++ /dev/null @@ -1,198 +0,0 @@ -# tmad port work items — 2026-10-04 - -Single owner of tracking status for the maintained `tmad4000/paseo` feature ports. The -[intake plan](tmad-maintained-port-plan.md) owns the policy (branch order, contracts, update loop, -acceptance bars); this file owns the state. Per-feature provenance (full blob tables, seam tables, -command logs) lives in the [tmad-port/evidence/](tmad-port/evidence/) directory and is referenced per row — this -file carries the summary each future sync or removal needs. The `TM-` IDs are stable across branch -renames. Where this file and a branch's manifest comment disagree, this file wins until the next -reviewed manifest rebuild. - -**Location note:** the plan places this ledger on `custom`. It is drafted and maintained on the -`tmad-port/coordination` branch (with all evidence) because nothing is pushed to `custom` during -the port; landing it on `custom` (plus the [fork README](../README.md) link) is a promotion step for -the user. It relates to [feature-ledger.md](feature-ledger.md) as follows: that ledger owns -behavior absorbed into `custom`; the branches tracked here are manifest carries, which stay outside -`custom` by design. If a carry is ever absorbed into `custom`, its ownership moves there and this -row is marked disabled, not deleted. - -## Coordination correction — 2026-10-08 - -See the [corrected Pluto readiness audit](tmad-port/evidence/pluto-readiness-2026-10-08.md) for -ancestry, exact build/artifact provenance, current fork CI annotations, and next-step order. The -current `custom` head is not an ancestor of `mine` or P0; some earlier custom commits are. ACP -cancellation implementation is already present in current `custom`, P0, and `mine`; its old plan and -review are historical snapshots. Current agent, workspace, branch, and state assignments are maintained in the [STATUS worker -ownership table](tmad-port/STATUS.md#worker-ownership--2026-10-08). The corrected readiness audit -contains the historical custom CI failure and corrected CLI declaration-resolution result. Side-repair -commit `fddb4fa8587ae377286ffbea3137df4c53bdc7a9` is independently approved and is an integration -candidate outside `custom`/`mine`; it passed local full-rehearsal integration but awaits intended-path inclusion and CI, and has not been promoted. - -The selected full readiness candidate `rehearsal/p0-custom-voice-complete` at `9584b2a669ce90a5df8c9eac66073e85124e90bb` and the frozen-only Voice checkpoint are recorded in the [P6 report](tmad-port/evidence/P6-assembly-2026-10-08.md), which owns exact refs, integration deltas, and reproducible runtime evidence. Full checks are green; final integration review is APPROVED. Frozen-only retains the known side-conversation failure and is not release ready. Dormant copied-state preservation passed; provider dispatch was not exercised. Remote CI/full-suite, device/live-provider/live-migration gates remain open. Intake approvals do not cover every assembly adaptation. Keep TMAD out of live configuration; queue-root updates and promotion remain separate decisions. - -## Source cursors - -| Cursor | Value | -| --- | --- | -| Source repository | `tmad4000/paseo` | -| Frozen intake snapshot | `f0d5507d2` (`refs/research/tmad-main`) | -| Last source head inspected = fully classified | `929f1add3` (`refs/research/tmad-main-latest`, PR #36 — classified 2026-10-03, see below) | -| Effective source snapshot, all ported features | `51fb7693d` (source PR #21 integration); TM-01 rehearsal boundary `af247e4f4` (PR #19) | -| Desvio release base | `v0.11.0-beta.3` = `6166a7aca` | -| Custom floor (queue/voice lineage) | `cbd1210c7` — recorded at TM-02 intake | - -## Integration state - -| ID | Branch | Base | HEAD | Verdict | Removal group | -| --- | --- | --- | --- | --- | --- | -| P0 | `tmad-port/baseline-assembly` (on origin) | frozen manifest SHAs (`tmad-port/evidence/P0-inputs.txt`) | `2bfcd2e19` | APPROVED ([review](tmad-port/evidence/review-P0.md); 3 non-blocking dispositioned) | — (baseline, not a feature) | -| P2 | `tmad-with-stream` (clone-local, `/tmp/tmad-port/baseline-clone`) | P0 `2bfcd2e19` | `0ff83cbc5` | APPROVED ([review](tmad-port/evidence/review-P2.md)) | — (with/without proof) | -| P6 final rehearsals | `rehearsal/p0-custom-voice-complete` / `rehearsal/p6-approved-voice` (local) | Exact sequence in P6 | full `9584b2a669ce90a5df8c9eac66073e85124e90bb`; frozen `0169f9a839fcdc01d4df04da02872ef3167c6dc9` | Full green; final review APPROVED. Frozen-only retains known failure. [Evidence](tmad-port/evidence/P6-assembly-2026-10-08.md). | Queue+Voice / Native Find / Stream | -| TM-01 Stream | `intake/tmad-stream-flow` (on origin) | `6166a7aca` (release) | `a8241e535` (10 commits) | APPROVED twice ([review](tmad-port/evidence/review-TM-01.md), [delta](tmad-port/evidence/review-TM-01-delta.md)) | Stream | -| TM-01B bridge | not created | — | — | NOT NEEDED (TM-01 green on beta.3 alone) | Stream | -| TM-02 queue daemon | `intake/tmad-message-queue` (on origin) | custom floor `cbd1210c7` | `91392d6be` (6 commits) | APPROVED ([review](tmad-port/evidence/review-TM-02.md); no blocking) | Queue+Voice | -| TM-03 queue UI | `intake/tmad-queue-ui` (on origin) | TM-02 `91392d6be` | `9ab91bb75` (7 commits) | APPROVED ([review](tmad-port/evidence/review-TM-03.md); 3 non-blocking) | Queue+Voice | -| TM-04 voice flow | `intake/tmad-voice-flow` | TM-02 `91392d6be` | `84f11381ceabec13d5deaff6c1e2c05dc67a6c62` | Implementation complete; Pi/OpenCode Go Muse review APPROVED this exact HEAD (reviewer `6ff8658e-654d-4637-beeb-c24d238f9375`, workspace `wks_9d17ba714b1dcd50`). Local basket integration is complete; final integration review is APPROVED; physical/live-provider gates remain open. See [implementation evidence](tmad-port/evidence/TM-04-2026-10-08.md) and [review](tmad-port/evidence/review-TM-04-2026-10-08.md). | Queue+Voice | -| TM-07 native find | `intake/tmad-native-find` (on origin) | `6166a7aca` (release) | `5f3634ad4` (1 commit) | APPROVED ([review](tmad-port/evidence/review-TM-07.md); no findings) | Native Find | -| TM-05, TM-06, TM-08+ | not started | — | — | Product decisions for the user; do not start | — | - -Allowed ancestors, verified per report and re-checked by each reviewer: TM-01/TM-07 have only the -pinned release (custom, mine, and `51fb7693d` are NOT ancestors). TM-02 has only the custom floor. -TM-03 and TM-04 have only the TM-02 head; `intake/tmad-queue-ui` and -`intake/tmad-voice-flow` are siblings — neither may carry the other. - -## Feature rows - -### TM-01 — Stream/artifact vertical slice (`intake/tmad-stream-flow`) - -- Source: PR #19 (`af247e4f4`) reconciled to #21 (`51fb7693d`); effective snapshot `51fb7693d`. - Disposition: adapted (10 of 15 core files byte-identical to source; 4 intentional deltas — - pin/manual-entry/artifact bounds, feed localization + Stream-pin glossary, agent-view-store - narrowing, collector turn cap — each with rationale in the [report](tmad-port/evidence/TM-01.md)). -- Key seams (owner table in the report): agent-panel integration, accepted-event capture in - `agent-manager.ts` (post-coalescer, fire-and-forget artifact collection — restored by `a8241e535` - after the P2 assembly caught the await regression), storage/projections (incl. the strict-cache - schema fix the source lacked), protocol delivery (flat `update_companion_entry_request` renamed - to `agent.companion.update_entry.request/.response`; single `companionStreamPortV1` gate; source - capability names absent by test), file navigation (no watcher; bounded end-turn scan + explicit - CLI backfill). -- Tests carried/adapted: companion model/server suites, collector, backfill, auth index (7), - protocol messages (artifacts + renamed-RPC), locale parity (10 locales), capability-absent gate. -- Runtime requirement: gate `server_info.features.companionStreamPortV1`. -- Human gates (promotion-blocking): matched source/port UI captures (desktop + compact web), - native captures, locale parity screenshots incl. ko; informational decisions on the "Queue" tab - label and the 100/200 ceilings. - -### TM-02 — durable agent message queue (`intake/tmad-message-queue`) - -- Source: PRs #23–26, #30–32 at `51fb7693d`; source head (`f0d5507d2`) queue files are voice-coupled - and were NOT taken (recorded per-delta in the [report](tmad-port/evidence/TM-02.md)). Disposition: - adapted — explicit `intent` on admission (no queue-by-omission), claim-in-place dispatching with - per-attempt receipts, `uncertain`/`failed` states (8-attempt park, no silent deletion), revision - guards, startup recovery without dispatch, journal + 0600 atomic writes, archived-agent fence, - strict steer via the existing admission (refusal never interrupts or deletes). -- Legacy contract: `send_agent_message_request` without queue intent keeps the beta.3 - receipt-backed interrupt path — the source's queue-on-omission and receipt-service omission are - deliberately not copied (tested). -- Wire: `agent.queue.*` dotted set (`list/update/delete/reorder/retry/send_now` + subscribable - `agent.queue.update` event); feature flag `durableAgentQueueV1`, client capability - `durable_agent_queue`; source flat `agent.queue.remove` renamed `delete`. -- Tests: queue store/service/send-or-queue suites (49), protocol sub tests (9), auth (7), - ACP 130 / GJC 43 / agent-manager 210 on the custom floor. -- Known gaps carried: daemon e2e was re-anchored on the fake-provider harness in TM-03; the - pre-fix custom CI failure at `session.test.ts:259` is reproduced and repaired at - `fddb4fa8587ae377286ffbea3137df4c53bdc7a9`; Luna independently approved it. Local rehearsal integration passed; intended-path inclusion and CI - remain outstanding. Historical TM-02 evidence records the original floor reproduction. -- Removal note: removal group Queue+Voice — TM-03/TM-04 depend on this branch even if their own - lines are commented. - -### TM-03 — queue UI and cross-device behavior (`intake/tmad-queue-ui`) - -- Source: same queue PR set; every queue UI file at the source head is byte-identical to - `51fb7693d`, so the integration snapshot is the complete source UI. Disposition: adapted — - outbox entries carry intent and park visible as failed at exhaustion (source drops silently); - revision-guarded edit/reorder/delete/retry with visible conflict handling; take-into-composer - edit/send-now; delivery-state badges. Source's `interrupt?` wire field (PR #32) NOT taken - (protocol change outside the lease); typed-send default verified identical to ours — unchanged. -- `dispatchComposerAgentMessage` untouched; queue admission never creates a submitted timeline row; - drain yields exactly one canonical user row (e2e-asserted). -- Tests: composer/actions + queue-sync + outbox model + session-store (177 app), queue + auth - server (56), protocol (9), two-client mirroring + revision-conflict daemon e2e on the - fake-provider harness (2, run twice). -- Human gate: browser/native screenshot pass on the new queue UI (badges, row menu, failed overlay). -- CI history: public custom run 37187135673 shows the pre-fix manager-event test at - `packages/server/src/server/session.test.ts:259` failed with no update/removed events received. - Local repair is `fddb4fa8587ae377286ffbea3137df4c53bdc7a9`, independently approved; local rehearsal integration passed, while intended-path inclusion - and CI remain outstanding. Playwright shards 3/4 and 4/4 failed - with generic exit-code annotations and no established cause. -- Update-loop candidates from PR #36 (`929f1add3`): waiting-to-sync gating, per-agent blocking - flush, await-outbox-persistence before clearing the draft, exhaustion-UX product call. Classified, - not ported. - -### TM-07 — native Find wrapper (`intake/tmad-native-find`) - -- Source: #11 as delivered by `51fb7693d`; six core files byte-identical to source (incl. - `strategy-native.tsx`, viewport, matches + tests); shared seams adapted to exclude every Stream - artifact (full exclusion table in the [report](tmad-port/evidence/TM-07.md)). Uses the existing - search model/RPC (`agentHistorySearch` upstream flag; no new wire surface, protocol untouched). - No Stream dependency in either direction (grep-verified). -- Adapted merge: `agent-view-store.ts` (`findOpen` here vs TM-01's - `selectedViews`) and `workspace-tab-menu.ts` — completed in P6; see its conflict log. -- Human gate: the 10-point native device list in the report (reachability, historical-match reveal, - wrap-around, cleanup, older-host, keyboard, rotation, non-Latin locales). - -### TM-04 — voice flow (`intake/tmad-voice-flow`) — IMPLEMENTATION AND REVIEW APPROVED - -- Source: PRs #13, #15, #22, #23 (NOT #14 iOS background = TM-06, NOT #17 mute = TM-05). -- Final implementation HEAD: `84f11381ceabec13d5deaff6c1e2c05dc67a6c62`, including attributed - import `5ecb8324625de55dc80345f181518da26f2d42db`. Pi/OpenCode Go Muse reviewer - `6ff8658e-654d-4637-beeb-c24d238f9375` in `wks_9d17ba714b1dcd50` APPROVED this exact HEAD; - implementer and reviewer are archived. Preserve `6ab56eba1` only as recovery history. Base: - TM-02 `91392d6be`; only allowed extra ancestry. Local basket integration is complete; final integration review is APPROVED. Physical-device and live-provider checks remain open. See - [implementation evidence](tmad-port/evidence/TM-04-2026-10-08.md) and - [review](tmad-port/evidence/review-TM-04-2026-10-08.md). - -## Source-change classifications - -- `929f1add3` (PR #36, queued-message durability hardening): fully classified 2026-10-03. Covered - in stronger form by TM-03 (visible parked failure, revision-guarded reconciliation, intent-carrying - resends); four remaining candidates listed in [TM-03.md](tmad-port/evidence/TM-03.md). Not ported. -- Source head deltas beyond `51fb7693d` deliberately not taken (recorded per branch): TM-02 — - finish-notification queueing, `paseo-tools` queue integration, voice-coupled queue fields; - TM-03 — `interrupt?` wire field, session-store upstream noise; TM-07 — unrelated upstream layout/ - presentation changes. - -## Base moves - -- Custom moved `cbd1210c7` → `24f134618` (2026-10-04): plugin-SDK feature + fork docs. The delta - touches plugins only (`plugin-provider.ts` and wiring) — no tmad port seam. Recorded floors stand; - re-anchoring the queue root onto the new custom tip is a future update-loop batch per the plan - ("merge the updated custom branch into the queue root, then update dependents in order"), with its - own review. -- No upstream release move; `v0.11.0-beta.3` remains the release base for TM-01/TM-07. - -## Manifest append block (DRAFT — nothing live edited; frozen copy in -[evidence/manifest-frozen-2026-10-02.txt](tmad-port/evidence/manifest-frozen-2026-10-02.txt)) - -```text -# Existing community, custom and infi lines retain their current order. APPEND BELOW THEM. -intake/tmad-stream-flow # TM-01 a8241e535; source snapshot 51fb7693d reconciled; base v0.11.0-beta.3; removal group Stream (no bridge needed). -intake/tmad-message-queue # TM-02 91392d6be; custom floor cbd1210c7 (recorded); removal group Queue+Voice (with TM-03/TM-04). -intake/tmad-native-find # TM-07 5f3634ad4; source snapshot 51fb7693d; base v0.11.0-beta.3; removal group Native Find (independent of Stream and queue). -# TM-03 and TM-04 lines are added in dependency order only after their own gates; voice device evidence is a promotion gate. -``` - -Each line is valid only after its branch's Muse Spark review; assembly validation (P2-style with/ -without rebuild) is required per removal group before any live manifest edit. The copied pending-state removal/recovery exercise passed in P6; live-home migration is unproven. - -## Remaining human checks (complete list) - -- TM-01: matched source/port UI captures (desktop + compact web), native captures, locale parity - incl. ko; two informational decisions ("Queue" tab label; pin/artifact ceilings 100/200). -- TM-02: integrate independently approved side-conversation repair `fddb4fa85` through the intended - path and verify it in CI. The current repair branch remains outside `custom`/`mine`. -- TM-03: browser/native screenshot pass on the new queue UI. -- TM-04: review is approved; physical-device and per-provider checks remain open (mic, playback, - echo, lock/background, reconnect, owner contention; Claude, Codex, ACP/GJC) plus a rebuilt native - dev client for the `expo-two-way-audio` changes. Local integration is complete; final integration review is APPROVED. -- Promotion (P6): remote CI/full-suite and human/device/live-provider/live-migration gates remain open; see P6. diff --git a/fork/plans/tmad-port/STATUS.md b/fork/plans/tmad-port/STATUS.md deleted file mode 100644 index 9b5b8ff68c4..00000000000 --- a/fork/plans/tmad-port/STATUS.md +++ /dev/null @@ -1,182 +0,0 @@ -# tmad port — status (corrected 2026-10-08, orchestration on pluto) - -> **Durable readiness snapshot (2026-10-08):** Selected full local readiness candidate -> `rehearsal/p0-custom-voice-complete` at `9584b2a669ce90a5df8c9eac66073e85124e90bb` -> preserves P0 external/infi carries, four features, current custom, the approved side repair, -> and approved Voice last. Build/typecheck/lint and focused 373 client/server + 76 app tests passed. -> Queue-free and final enabled fake-provider runtimes proved dormant copied-state preservation -> with zero turns; provider dispatch was not exercised. -> Pi/Muse final integration review is **APPROVED**; remote CI/full-suite, device, live-provider, -> and live-migration gates remain open. -> Frozen-only `rehearsal/p6-approved-voice` at `0169f9a839fcdc01d4df04da02872ef3167c6dc9` -> omits the side repair and retains its known test failure; it is not release ready. -> Exact inputs, integration deltas (including the `e423a8666` AsyncStorage stub and shared -> receipt-owner startup fix), check results, and durable reproduction are owned by the -> [P6 report](evidence/P6-assembly-2026-10-08.md). Intake branches alone do not contain all adaptations. -> Historical ancestry, CI, ACP, and npm tag facts remain in the -> [audit](evidence/pluto-readiness-2026-10-08.md). No live promotion is authorized. - -## Worker ownership — 2026-10-08 - -| Work | Agent | Workspace | Branch | State | -|---|---|---|---|---| -| TM-04 voice implementation | `agent9307e007` (Sol, low) | `wks_9d17ba714b1dcd50` | `intake/tmad-voice-flow` (`voice-flow-r2`) | Complete at `84f11381ceabec13d5deaff6c1e2c05dc67a6c62` (includes attributed import `5ecb8324625de55dc80345f181518da26f2d42db`); implementer archived. Review APPROVED by Pi/OpenCode Go Muse reviewer `6ff8658e-654d-4637-beeb-c24d238f9375` (archived). Physical/live-provider gates remain open. See [implementation evidence](evidence/TM-04-2026-10-08.md) and [review](evidence/review-TM-04-2026-10-08.md). | -| TM-04 independent review | `6ff8658e-654d-4637-beeb-c24d238f9375` (Pi/OpenCode Go Muse) | `wks_9d17ba714b1dcd50` | `intake/tmad-voice-flow` | Complete, archived; APPROVE exact HEAD `84f11381ceabec13d5deaff6c1e2c05dc67a6c62`. See [review](evidence/review-TM-04-2026-10-08.md). | -| P0 assembly / basket integration | `agentfeb33ae6` (Luna, high) | `wks_6bd86ab884dc41ee` | `build/tmad-readiness-2026-10-08` | Complete, archived; final rehearsals and runtime evidence recorded in the [P6 report](evidence/P6-assembly-2026-10-08.md). Parent build worktree remains at `e423a8666`. | -| CLI declaration-resolution investigation | `agentfc3f12c9` (Sol, low) | `wks_95f92a2c629a806f` | `fix/pluto-cli-typecheck` | Complete and archived; no source fix indicated. | -| Side-conversation repair | `agentb1df5254` (Sol, low) | `wks_0a7dc387a32f7959` | `fix/pluto-side-conversation-events` | Complete, archived; `fddb4fa8587ae377286ffbea3137df4c53bdc7a9` approved, candidate outside `custom`/`mine`; integrated only in the local full rehearsal; intended-path inclusion and CI remain outstanding. See [repair evidence](evidence/pluto-side-conversation-events-2026-10-08.md). | -| Side-conversation independent review | `agentc28ebf9` (Luna, high) | `wks_0a7dc387a32f7959` | `fix/pluto-side-conversation-events` | Complete, archived; APPROVE at `fddb4fa8587ae377286ffbea3137df4c53bdc7a9`. CodeRabbit did not start (`environment_unsupported`); manual review is the approval. See [review](evidence/pluto-side-conversation-review-2026-10-08.md). | -| Final integration review | `agentf65ea3e2-16ee-4cb4-8c06-4e355a689a4e` (Pi/OpenCode Go Muse) | Not recorded in this snapshot | `rehearsal/p0-custom-voice-complete` | **APPROVED** exact full basket `9584b2a669ce90a5df8c9eac66073e85124e90bb`; reviewer archived. See [final review](evidence/review-P6-final-2026-10-08.md). | - -24 workers are closed/archived before this docs worker’s eventual close, including the inventory worker, integrator, and final reviewer. Only this docs worker remains active in this task at snapshot time. Agent and workspace IDs are separate in this table. - -Plan: [../tmad-maintained-port-plan.md](../tmad-maintained-port-plan.md). Briefs in `briefs/` were -written for neptune workers: read `/tmp/tmad-port/...` as the pluto scratch dir (populated from this -branch: plan.md, COMMON.md, flat briefs, evidence/, logs/, prompts/) and -`/Volumes/offload/neptune/repos/paseo` as `~/repos/paseo`. `~/.paseo-fork/manifest.txt` is frozen in -`evidence/manifest-frozen-2026-10-02.txt`; never edit a live manifest. - -Reviewer correction (2026-10-03, from the user): reviews run through **Pi on OpenCode Go** — provider -`pi`, model `opencode-go/muse-spark-1.3-contributor`, thinking `high`, feature `auto_accept: true` -(pluto's saved profile "Muse Spark 1.3 Contributor"). The `muse` (Muse Code) provider is NOT the -reviewer route and is not installed on pluto; the 2026-10-02 session wrongly waited on it. Reviewers -are read-only: no edits, no commits, no pushes. See `briefs/ORCHESTRATOR.md`. - -## Branch state - -| ID | Branch (local; intake branches not yet pushed to origin) | Base | HEAD | State | -| --- | --- | --- | --- | --- | -| P0 | `tmad-port/baseline-assembly` (on origin) | frozen manifest SHAs (`evidence/P0-inputs.txt`) | `2bfcd2e19` | DONE + **APPROVED** (evidence/review-P0.md, 2026-10-03): all exit criteria reproduce read-only; 3 non-blocking findings dispositioned in the coordinator note at the bottom of evidence/P0.md (script verdict-string bug; "29"→"31" count fixed; rr-cache informational). Gates for P2: none left. | -| TM-01 Stream | `intake/tmad-stream-flow` (on origin; history: `4dab8b364` WIP → `2197619bc` approved → `a8241e535` post-P2 fix, appended) | `v0.11.0-beta.3` (6166a7aca) | `a8241e535` | DONE + **APPROVED twice**: full review at `2197619bc` (evidence/review-TM-01.md) and delta re-review of the post-P2 seam fix at `a8241e535` (evidence/review-TM-01-delta.md — routing as a TM-01 local fix CONFIRMED, "TM-01B would be wrong, assembly-only would ship the regression"). The fix restores the source's fire-and-forget artifact collection that the P2 assembly showed breaking custom's steer-fallback fence. 3 non-blocking nits recorded (commit-message sentence, trailer spacing, log echo). UI capture remains P1 step 6 (human). | -| TM-02 queue daemon | `intake/tmad-message-queue` (on origin) | custom floor `cbd1210c7` (recorded) | `91392d6be` | DONE + **APPROVED** (evidence/review-TM-02.md): legacy send contract, wire/auth, queue semantics, custom fences, provenance all verified; no blocking findings (2 non-blocking report-wording notes). Gaps carried: daemon e2e needs provider creds (defer to TM-03/P4). Gates for TM-03/TM-04: none left. | -| TM-07 Native Find | `intake/tmad-native-find` (on origin) | `v0.11.0-beta.3` (6166a7aca) | `5f3634ad4` | DONE + **APPROVED** (evidence/review-TM-07.md, Muse Spark 1.3 Contributor via pi/OpenCode Go, 2026-10-03): no blocking findings, none non-blocking; provenance, blob parity, ancestry, diff correctness all verified by the reviewer. Promotion still wants the 10-point native device list in evidence/TM-07.md (human) ; the adapted Stream/Find merge is demonstrated in P6. | -| TM-01B bridge | — | — | — | NOT NEEDED (TM-01 compiles and tests green on beta.3 alone). | -| TM-03 queue UI | `intake/tmad-queue-ui` (on origin) | TM-02 `91392d6be` (approved) | `9ab91bb75` | DONE + **APPROVED** (evidence/review-TM-03.md): no blocking findings; 3 non-blocking notes (trailer convention on the docs commit; the inherited source optimistic-row race — small, self-healing, documented as gap #4, hardening optional; screenshot evidence for the new badges/menus deferred to a human dev-app pass). Canonical submission ownership, no-protocol-change, no typed-send flip, queue-removal coherence all verified by the reviewer. Remaining human check: browser/native screenshot pass on the new queue UI. | -| TM-04 voice flow | `intake/tmad-voice-flow` | TM-02 `91392d6be` (approved) | `84f11381ceabec13d5deaff6c1e2c05dc67a6c62` | Implementation complete; includes attributed import `5ecb8324625de55dc80345f181518da26f2d42db`. Pi/OpenCode Go Muse review APPROVES this exact HEAD; reviewer `6ff8658e-654d-4637-beeb-c24d238f9375` is archived. Local basket integration is complete; final integration review is APPROVED; physical-device and live-provider evidence remain open. `6ab56eba1` is retained only as recovery history. See [implementation evidence](evidence/TM-04-2026-10-08.md) and [review](evidence/review-TM-04-2026-10-08.md). | -| P2 removal proof | `tmad-with-stream` (clone-local) | baseline `2bfcd2e19` | `0ff83cbc5` | **DONE + APPROVED** (evidence/review-P2.md): with-stream delta = exactly the 53 TM-01 paths; Stream-free baseline; steer-fence defect fixed in the TM-01 branch (redundancy proven, trees byte-identical); rollback demonstrated on copied data; TM-01B not needed; final manifest block in P2.md Addendum 2. | -| P6 final rehearsals | `rehearsal/p0-custom-voice-complete` / `rehearsal/p6-approved-voice` (local) | P0 + four features; see exact sequence in P6 | full `9584b2a669ce90a5df8c9eac66073e85124e90bb`; frozen `0169f9a839fcdc01d4df04da02872ef3167c6dc9` | Full checks green; final review APPROVED. Frozen-only retains known failure. [Evidence and integration deltas](evidence/P6-assembly-2026-10-08.md). | -| TM-05, TM-06, TM-08+ | — | — | — | Product decisions for the user; do not start. Typed-send default is also the user's call. | - -## Source cursors - -- Inspected = fully classified = `929f1add3` (`refs/research/tmad-main-latest`; PR #36 "preserve - queued messages until host acknowledgement", 27 app files +939/−205, TM-03 scope — source-update - candidate after TM-03 lands; not ported). -- Effective source snapshot per ported feature: `51fb7693d` (TM-01 rehearsal boundary: `af247e4f4`). - -## Remaining human checks (regardless of review verdicts) - -- TM-07: native device evidence, 10-point list in `evidence/TM-07.md` (iOS sim + Android: - reachability, historical match reveal, wrap-around, cleanup, older-host, keyboard, rotation, - non-Latin locales). -- TM-01: matched source/port UI captures (desktop + compact web), native captures, locale parity - incl. ko; two informational decisions ("Queue" tab label; pin/artifact ceilings 100/200). -- TM-02: the pre-fix custom CI side-conversation failure at `session.test.ts:259` is reproduced and - repaired at `fddb4fa85`; Luna independently approved it. Local full-rehearsal integration passed; intended-path inclusion and post-fix CI remain - outstanding. Live-provider e2e remains open; TM-03 fake-provider evidence is recorded in P6. -- TM-04: review is approved; physical-device and live-provider evidence remain open. Local basket integration is complete; final review is APPROVED; see [TM-04 evidence](evidence/TM-04-2026-10-08.md) and [review](evidence/review-TM-04-2026-10-08.md). - -## Proposed manifest append block (DRAFT — nothing live edited; each line valid only after its Muse Spark review) - -```text -# Existing community, custom and infi lines retain their current order. APPEND BELOW THEM. -intake/tmad-stream-flow # TM-01 a8241e535; source snapshot 51fb7693d reconciled; base v0.11.0-beta.3; removal group Stream (no bridge needed). -intake/tmad-message-queue # TM-02 91392d6be; custom floor cbd1210c7 (recorded); removal group Queue+Voice (with TM-03/TM-04 when they land). -intake/tmad-native-find # TM-07 5f3634ad4; source snapshot 51fb7693d; base v0.11.0-beta.3; removal group Native Find (independent of Stream and queue). -# TM-03 (intake/tmad-queue-ui, base TM-02) and TM-04 (intake/tmad-voice-flow, base TM-02) lines are added -# in dependency order only after their own gates; voice device evidence is a promotion gate. -``` - -## Orchestration log - -- 2026-10-02 (neptune → handoff): P0 inputs frozen, baseline assembly merged, feature map done; - TM-02 protocol contract committed (`6f76c621e`); TM-07 done, unreviewed; TM-01 left one WIP commit. -- 2026-10-02 (pluto): scratch dir `/tmp/tmad-port/` populated; baseline clone created at - `/tmp/tmad-port/baseline-clone` (own index, rerere on) on `tmad-port/baseline-assembly`; - coordinator check: baseline tree == frozen mine. Implementers dispatched (claude-zai/glm-5.3-flash, - thinking high, bypassPermissions): TM-01 `59933eac` (wks_3919834322096f66), TM-02 `124d824b` - (wks_b6b4404597f90c74), P0 `c1c7b820` (wks_4c44bb8d08811ddb). The 2026-10-02 session wrongly - waited on the `muse` provider ("not found on PATH") and stopped with everything blocked; corrected - 2026-10-03 per the user. -- 2026-10-03: P0 finished (`evidence/P0.md`; note: clone rr-cache is empty after `git rerere gc`, so - P2 budgets fresh resolutions). TM-02 finished (`evidence/TM-02.md`; handoff blocker resolved — the - truncated typecheck failure was stale protocol `dist`; no branch-caused failures). TM-01 finished - (`evidence/TM-01.md`). Coordinator verified each: HEAD SHAs, ancestry, blob parity, trailers, test - logs (73 tm01-* logs, 320/320 P0 tests, 49 queue tests). -- 2026-10-03 (resume): reviews dispatching on pi/OpenCode Go per the corrected brief. Note: the CLI - cannot pass provider features at `paseo run` time, so the profile's `auto_accept: true` is not set - on reviewers; read-only reviewers ran without a single permission prompt, so this has not mattered. - If a future reviewer stalls on prompts, either approve via `paseo permit allow ` or create - it through the MCP surface where `settings.features` is available. -- 2026-10-03: **TM-07 APPROVED** (evidence/review-TM-07.md) — first review through the corrected - route; branch already on origin. P0/TM-02/TM-01 reviews dispatched in parallel (same reviewer - profile, read-only, verdict files `evidence/review-.md`). **All four reviews returned APPROVE** - (P0: 3 non-blocking, dispositioned; TM-02: no blocking, 2 wording notes; TM-01: no blocking, 2 doc - nits). Approved branches pushed to origin; `intake/tmad-stream-flow` required a lease-pinned - force-update because the approved history rewrites the superseded WIP tip `4dab8b364` (rewrites of - unreviewed WIP are allowed by `briefs/ORCHESTRATOR.md`; nobody else builds on that tip). Next per - the brief: P2 (baseline clone, reuse of the P0 worker's workspace), then TM-03 and TM-04 - (branch-off from the approved `intake/tmad-message-queue`), each followed by its review. -- 2026-10-03 (P2 wave): P2 worker finished (evidence/P2.md, `tmad-with-stream` @ `d17896891`) and - **caught a real TM-01 port defect at the assembly**: the port made terminal-event artifact - collection `await` where source `51fb7693d` is fire-and-forget (`void ...collectArtifactsForTurn` - with rationale comment); under custom's steer-fallback fence the cwd-walk window let a steer - admission leave a ghost tracked run (agent-manager 209/210 on the assembly, green on baseline). - Coordinator verified the hunk against source and routed it back to a glm implementer as an ITERATE - finding (agent `e5a7006f`): cherry-pick the one-hunk fix onto `intake/tmad-stream-flow` (append - only, no history rewrite), retest, addendum in TM-01.md. Sequencing: TM-01 delta re-review (Muse, - `2197619bc..new HEAD`) → push → P2 worker follow-up rebuilds `tmad-with-stream` from the updated - branch (the assembly fix `d17896891` should then be redundant) and finalizes the manifest SHA → - P2 review. The worker's alternative (record the assembly-only resolution and ship a manifest line - at `2197619bc`) was rejected: it would ship the steer regression in a manifest-only assembly. - TM-03 (`4a09bc95`) and TM-04 (`82cd1481`) running in parallel. -- 2026-10-03 (TM-01 fix round): fix implementer appended the seam fix → `intake/tmad-stream-flow` - `a8241e535` (no rewrite; `2197619bc` still an ancestor). Delta re-review **APPROVE** - (evidence/review-TM-01-delta.md): seam byte-equal to source, routing judgment confirmed, 192-vs-210 - test-count delta independently sanity-checked. Branch pushed to origin (fast-forward). P2 worker - now rebuilding `tmad-with-stream` from the updated branch (assembly fix `d17896891` should become - redundant; rerere-replay of the old tab-menu resolution to be inspected before keeping), then the - final manifest SHA and P2's own review. -- 2026-10-03 (P2 rebuild): `tmad-with-stream` = `0ff83cbc5` (baseline 2bfcd2e19 + one merge of - a8241e535). Redundancy proven: `git diff d17896891 0ff83cbc5` empty — byte-identical tree, no - extra assembly commit; steer-fallback passes on the bare merge (210/210). rerere replay inspected - before keeping (identical resolution). Gates + seam-critical tests green (build:server, typecheck, - lint 0/0 on 4604 files, agent-manager 210, companion 12, collector 3, auth 7). Addendum 2 in - evidence/P2.md carries the FINAL manifest block (TM-01 at `a8241e535`, no bridge). P2 review - dispatched (Muse, `02ccfa7a`). -- 2026-10-03 (P2 review): **P2 APPROVED** (evidence/review-P2.md). Non-blocking: N1 draft-manifest - SHA staleness (fixed in this file — TM-01 line now `a8241e535`); N2 wording note on the - "one textual conflict" claim. The tmad port's Phase 0-2 are now fully approved end to end: - P0 baseline, P1/TM-01 Stream (twice), P2 removal proof, TM-02 queue daemon, TM-07 Native Find. - Remaining: TM-03/TM-04 (running) + their reviews; the work-items ledger; human evidence gates - (device lists, UI captures). -- 2026-10-04 (takeover, TM-04 resume): New orchestrator session on pluto. Verified environment - (scratch dir + baseline clone intact; all approved branches at recorded SHAs; coordination branch - synced with origin). TM-04's first worker (`82cd1481`) was dead with no commit and no report; its - worktree held 72 uncommitted files. Verified the worktree state byte-identical (blob hashes) to - origin/backup/tmad-voice-flow-wip-2026-10-04 (`fa9dac92b`), committed it verbatim as wip commit - `6ab56eba1` on `intake/tmad-voice-flow` (local only; no push — unreviewed), archived the dead - worker's workspace (`wks_65cde3bf023cfc47`, worktree removed), and dispatched a fresh implementer - (claude-zai/glm-5.3-flash, thinking high, bypass; agent `4593e609`, workspace - `wks_9d17ba714b1dcd50`) with the resume prompt (`prompts/TM-04-resume.txt`): audit every WIP file - against the brief before trusting it, drop any TM-03/TM-05/TM-06 scope, rebuild proper trailer-ed - history (the wip commit is expected to be rewritten away), run all gates itself. Also noted: - custom moved `cbd1210c7` → `24f134618` (plugin-SDK feature + fork docs, including - `fork/feature-ledger.md`); the delta touches plugins only, no tmad port seams, so recorded floors - stand and queue-root re-anchoring stays a future update-loop step. The plan's work-items ledger - (`fork/plans/tmad-port-work-items.md`) remains a separate artifact — custom's feature ledger - explicitly covers custom-owned behavior only, not manifest carries. - -## Limits (unchanged) - -Nothing was pushed to `mine` or `custom`; no live manifest was edited; no daemon was restarted; no -desvio run against a live config. Intake branches get pushed to origin only after a reviewed -milestone. This coordination branch carries all evidence and is pushed. - -CLI TS7006 findings (2026-10-08): the exact original failing checkout was unavailable, so no -mainline source defect is established. At `24f134618`, the CLI worker rebuilt the owning stacks and -passed full workspace typecheck/lint plus targeted `delete.test.ts` (1/1). Removing local -`packages/protocol/dist` reproduced the six-file TS7006 pattern; restoring declarations cleared it -without a source fix. The coordination checkout initially had stale package-level links; after the -worktree initializer and client/server rebuild, full typecheck and lint passed. Both outcomes support -checking declaration resolution before considering a source change. See [CLI typecheck evidence](evidence/pluto-cli-typecheck-2026-10-08.md). diff --git a/fork/plans/tmad-port/briefs/COMMON.md b/fork/plans/tmad-port/briefs/COMMON.md deleted file mode 100644 index ebe312885c1..00000000000 --- a/fork/plans/tmad-port/briefs/COMMON.md +++ /dev/null @@ -1,50 +0,0 @@ -# Common rules for every tmad-port worker (read fully before starting) - -Repo: the Paseo fork (npm workspace monorepo). Your worktree is a git worktree of -/Volumes/offload/neptune/repos/paseo (shared object store; refs/research/tmad-main, -commits 51fb7693d, af247e4f4, f0d5507d2, v0.11.0-beta.3 = 6166a7aca, custom = cbd1210c7 all exist locally). - -The governing plan is /tmp/tmad-port/plan.md. Read it in full first; your brief names your phase. -Also useful: /tmp/tmad-port/infi-pc-intake-work-items.md (precedent ledger format), -/tmp/tmad-port/fork-README.md, /tmp/tmad-port/upstream-sync.md. Read the repo's CLAUDE.md and the docs it -lists that touch your area (docs/protocol-compatibility.md, docs/rpc-namespacing.md, docs/testing.md, -docs/file-observation.md, docs/expo-router.md, docs/coding-standards.md as relevant). - -Source fork = tmad4000/paseo. Its integration commit 51fb7693d (source PR #21) mixes an upstream sync with -fork features: NEVER merge or cherry-pick it (or refs/research/tmad-main) wholesale, not even with -m. -Extract feature files/hunks only. Use `git show 51fb7693d:` and `git diff -- `. -Exclude source branding, app ids, TestFlight, auto-updater, source CI, version bumps. - -HARD RULES -- Work ONLY inside your own worktree / scratch clone. Never `cd` into /Volumes/offload/neptune/repos/paseo - to change branches or files. Never touch ~/.paseo-fork (live build tree + manifest) except to READ manifest.txt. -- NEVER restart, stop or start the Paseo daemon on port 6767. Never run `desvio` against the live config. -- NEVER push anything to any remote (no origin, no mine, no custom). Commit locally on your branch only. -- Do not use bare `git stash`. Do not rewrite other branches. Do not merge custom or mine into a branch - whose brief says it is release-based. -- NEVER run a full test suite. Run only specific files: `npx vitest run --bail=1` from the owning - package dir (redirect long output to a file under /tmp and read it). Never `npm run test` for a workspace. -- After code changes: `npm run build:server` (or build:client) when cross-package types matter, then - `npm run typecheck` and `npm run lint` (scoped lint via `npm run lint -- ` is fine). - Format with `npm run format` (or `npm run format:files -- `) before each commit. Use npm scripts, - never npx eslint/oxlint/oxfmt directly. Record pre-existing failures separately from yours - (compare against the unmodified base when in doubt). -- Install deps in a fresh worktree with: `ONNXRUNTIME_NODE_INSTALL=skip npm ci` (if npm ci fails, `npm install`). -- Commits: conventional style; imported/adapted commits carry trailers - Source-Repo: tmad4000/paseo - Source-Commit: - Port-Feature: TM-xx - plus `Co-Authored-By:` is not required. Keep local-only fixes as separate commits from imports. -- Protocol: new wire fields optional; no .transform/.catch/.preprocess in wire schemas; new RPCs use dotted - namespaces with .request/.response; every new op needs entries in authorization maps - (packages/server/src/server/authorization/) and client capability defaults; run - packages/server/src/server/authorization/index.test.ts after any protocol change. -- If you are blocked or something contradicts the plan, stop and write it in your report rather than guessing - a product decision. - -REPORT: when done, write /tmp/tmad-port/evidence/.md with: branch name, base SHA, final HEAD SHA, -`git log --oneline ..HEAD`, allowed ancestors check (`git merge-base --is-ancestor` results for custom, -mine), files changed (stat), source->port ledger rows (source path, source blob `git rev-parse 51fb7693d:

`, -local blob, disposition: unchanged/adapted/excluded + rationale), commands run with pass/fail, pre-existing -failures, known gaps/deferred items, and anything requiring a human decision. Keep the final chat reply to a -short summary pointing at that file. diff --git a/fork/plans/tmad-port/briefs/ORCHESTRATOR.md b/fork/plans/tmad-port/briefs/ORCHESTRATOR.md deleted file mode 100644 index b8005a7814c..00000000000 --- a/fork/plans/tmad-port/briefs/ORCHESTRATOR.md +++ /dev/null @@ -1,73 +0,0 @@ -# tmad port orchestrator brief (pluto) - -You orchestrate the rest of the tmad port plan on pluto. You do not write feature code yourself: -you dispatch implementers, route their output to review, integrate status, and push branches. - -Read first, in this order: `fork/plans/tmad-maintained-port-plan.md`, `fork/plans/tmad-port/STATUS.md`, -`fork/plans/tmad-port/briefs/COMMON.md`, every other brief in `briefs/`, and `evidence/*`. Also the repo -CLAUDE.md and docs it points to for the area at hand. - -## Environment on pluto - -- Repo: `~/repos/paseo` (origin = camerontaylor/paseo). Source objects are present: - `refs/research/tmad-main` = frozen source snapshot f0d5507d2; `refs/research/tmad-main-latest` = 929f1add3 - (one newer source commit; classify it in the ledger, do not port it unless the plan's update loop selects it). -- You run in a worktree on branch `tmad-port/coordination`. Keep STATUS.md and evidence there; commit and - push it after every phase change. -- Path translation for the briefs (they were written on neptune): `/tmp/tmad-port/` -> a scratch dir - `/tmp/tmad-port/` on pluto that you populate from this branch (`briefs/*`, `evidence/*`, `plan.md` copy of - the plan); `/Volumes/offload/neptune/repos/paseo` -> `~/repos/paseo`; `~/.paseo-fork/manifest.txt` -> - `evidence/manifest-frozen-2026-10-02.txt`; the P0 baseline clone -> make a separate clone at - `/tmp/tmad-port/baseline-clone` and check out `tmad-port/baseline-assembly` (the already-merged frozen - baseline). Put this translation at the top of every worker prompt. -- The Paseo daemon on pluto port 6767 is the one running you. NEVER restart, stop or rebuild it. - -## Workers - -- Implementers: provider `claude-zai`, model `glm-5.3-flash`, thinking high, bypass/unattended mode. - One worker per branch, each in its own Paseo worktree workspace created with checkout-branch mode on the - existing branch (`intake/tmad-stream-flow`, `intake/tmad-native-find`, `intake/tmad-message-queue`), or - branch-off from the declared base for new branches (`intake/tmad-queue-ui` and `intake/tmad-voice-flow` - from `intake/tmad-message-queue`). Never point two workers at one branch at once. -- Reviewers: Muse Spark through Pi on OpenCode Go — provider `pi`, model - `opencode-go/muse-spark-1.3-contributor`, thinking `high`, feature `auto_accept: true` (pluto's saved - profile "Muse Spark 1.3 Contributor"). NOT the `muse` (Muse Code) provider; do not check or wait on - that one. Read-only task: review the branch diff against its declared base for correctness against - the plan's contracts and the brief, and verify the worker's evidence claims (blob matches, tests - actually run, ancestry). Tell reviewers explicitly: no edits, no commits, no pushes. Reviews return - APPROVE or ITERATE with concrete findings; send ITERATE findings back to an implementer on the same - branch, then re-review. A phase is done only after an APPROVE. -- If the reviewer route is unavailable, do not substitute another reviewer. Mark the branch - "awaiting review" in STATUS.md, keep implementing independent work, and re-check availability - (`paseo provider models pi` must list `opencode-go/muse-spark-1.3-contributor`) before each review - gate. If everything left is blocked on review, stop and say so. (Historical note: on 2026-10-02 the - orchestration wrongly waited on the `muse` provider, which is not installed on pluto; corrected - 2026-10-03 to the pi/OpenCode Go route.) -- Workers die sometimes. On a dead or stalled worker: commit its partial state with a `wip(...)` commit - (`--no-verify` allowed only for WIP), record it in STATUS.md, and start a fresh worker from the branch. -- Keep at most 4 implementers running at once. Wait on finish notifications; do not poll in tight loops. - -## Order of work - -1. Now, in parallel: TM-01 finish (brief-TM01; the branch has a WIP commit of the PR #19 core files — the - worker should restructure it into the PR #19 import commit, then the PR19->#21 rehearsal commit, then - contract-fix commits; rewriting this branch's unreviewed WIP history is allowed), TM-02 continue - (brief-TM02 plus evidence/TM-02.md remaining list; first reproduce the pre-commit typecheck failure with - full output), P0 remainder (brief-P0 steps 2, 4, 6 and the report, on the baseline clone), and the muse - review of TM-07. -2. After TM-01 and P0 are approved: P2 (brief-P2). -3. After TM-02 is approved: TM-03 and TM-04 (briefs exist), each then reviewed. -4. Then create `fork/plans/tmad-port-work-items.md` (the ledger the plan describes; precedent format: - `fork/plans/infi-pc-intake-work-items.md`) from all evidence, and the proposed manifest append block. - -## Limits (from the plan; these need the user) - -- Do NOT push to `mine` or `custom`, edit any live manifest, run desvio against a live config, or deploy. -- You MAY push `intake/tmad-*` and `tmad-port/*` branches to origin after each reviewed milestone. -- Do NOT start TM-05, TM-06, TM-08+, and do not change the typed-send default; those are user decisions. -- Device evidence (native Find on iOS/Android, voice mic/playback/background) cannot be produced here: - list exactly what a human must check. -- Never run full test suites; only specific files, as COMMON.md says. - -Finish with STATUS.md describing each branch: HEAD, review verdict, remaining human checks, and the -proposed manifest lines. Push the coordination branch. diff --git a/fork/plans/tmad-port/briefs/brief-P0.md b/fork/plans/tmad-port/briefs/brief-P0.md deleted file mode 100644 index b781de39325..00000000000 --- a/fork/plans/tmad-port/briefs/brief-P0.md +++ /dev/null @@ -1,14 +0,0 @@ -You are the P0 integrator for the tmad port. Read /tmp/tmad-port/COMMON.md first and obey it, then read /tmp/tmad-port/plan.md (sections "Evidence and baseline", "P0", "Source tracking", "Scope and duplication decisions"). -Your ID for the report: P0 (write /tmp/tmad-port/evidence/P0.md, plus the files named below). - -Objective: deliver the P0 snapshot record, isolated baseline assembly, and the source feature/file map. No feature code. - -1. Freeze inputs. Record full SHAs for: v0.11.0-beta.3, origin/custom (expect cbd1210c7...), refs/research/tmad-main (expect f0d5507d2...), 51fb7693d, af247e4f4, merge-base dd8a111c3, the current `mine` tip (it was rebuilt at 14:00 today; it MOVES — record and use the SHA, never the name), and for every non-comment line of ~/.paseo-fork/manifest.txt (READ ONLY) the resolved SHA of that branch/remote ref in /Volumes/offload/neptune/repos/paseo (use `git -C /Volumes/offload/neptune/repos/paseo rev-parse ` — read-only commands only there). Save as /tmp/tmad-port/evidence/P0-inputs.txt (ordered as the manifest). -2. Verify the frozen `mine` SHA is an assembly of exactly those inputs: walk its first-parent merges (`git log --first-parent --format='%H %P %s' v0.11.0-beta.3..`) and check each merged second parent equals the frozen ref SHA in manifest order. Report any mismatch. -3. Isolated baseline: create a SEPARATE CLONE (not a worktree): `git clone --no-hardlinks /Volumes/offload/neptune/repos/paseo /tmp/tmad-port/baseline-clone` (or --reference to save space), copy the live repo's .git/rr-cache into the clone's .git/rr-cache so recorded resolutions are available, enable rerere in the clone. Create branch `tmad-baseline` at the frozen v0.11.0-beta.3 and merge the frozen manifest SHAs in manifest order with `git merge --no-ff`. If a merge conflicts and rerere does not resolve it fully, instead compare: the tree of the frozen mine SHA is the reference baseline; record which lines conflicted and use `git checkout -- .` style reconciliation ONLY if you can prove the frozen mine assembly matches the inputs (step 2). Final check: `git diff --stat ` should be empty (or explain every difference). Do not run desvio against the live config. -4. In the clone: `ONNXRUNTIME_NODE_INSTALL=skip npm ci`, `npm run build:server`, `npm run typecheck`, `npm run lint`. Then run these focused existing tests individually (find the real paths first with `git ls-files | grep`): server authorization/index.test.ts; app composer submit tests (packages/app/src/composer/**/submit*.test.ts or similar); agent-manager tests related to cancellation/ACP; the infi navigation history and recent-agents tests; subagent tab close tests. Record every result; pre-existing failures are expected and must be listed, not fixed. -5. Feature/file map: classify every path changed by the source fork features. Use `git diff --name-status dd8a111c3 51fb7693d` and the source PRs (`gh pr view -R tmad4000/paseo --json files,mergeCommit,commits,title` for N in 1 5 8 9 10 11 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35; gh is read-only here and fine). Distinguish (a) fork-feature files, (b) upstream-sync noise (present in upstream releases: check with `git merge-base --is-ancestor` / `git log --all --oneline -- ` against upstream tags or compare the blob to v0.10.0-beta.1's), (c) build/branding/release files (excluded). Map each feature file to a feature ID from the plan's Branch table (TM-01 Stream, TM-02 queue daemon, TM-03 queue UI, TM-04 voice, TM-05 mute, TM-06 iOS background, TM-07 native find, TM-08+ standalone, EXCLUDED, DEFER). Also list the commits after 51fb7693d up to f0d5507d2 (`git log --oneline 51fb7693d..f0d5507d2`) with a proposed disposition for each. - Write /tmp/tmad-port/evidence/P0-feature-map.md (table: path | status | feature | source PR | note). -6. Licensing: read the source LICENSE at 51fb7693d vs ours; record whether attribution is needed. - -Exit criteria (from plan): reproducible baseline; input SHA list; feature/file map; no unknown branch ancestry. Put the final summary in /tmp/tmad-port/evidence/P0.md. Leave the clone in place (other phases reuse it); do not delete it. diff --git a/fork/plans/tmad-port/briefs/brief-P2.md b/fork/plans/tmad-port/briefs/brief-P2.md deleted file mode 100644 index 89218f28f17..00000000000 --- a/fork/plans/tmad-port/briefs/brief-P2.md +++ /dev/null @@ -1,9 +0,0 @@ -You are the P2 integrator (removal proof + Stream assembly). Read /tmp/tmad-port/COMMON.md and obey it, then /tmp/tmad-port/plan.md sections "Branch and removal contract", P1 step 4-5, and P2. Read /tmp/tmad-port/evidence/P0.md, P0-inputs.txt and TM-01.md first. -Report ID: P2. Work in the scratch clone /tmp/tmad-port/baseline-clone made by P0 (its own index/rerere). Fetch the port branch into it: `git -C /tmp/tmad-port/baseline-clone fetch /Volumes/offload/neptune/repos/paseo intake/tmad-stream-flow:refs/heads/intake/tmad-stream-flow` (read-only from the source repo). - -1. Assembly WITH Stream: branch `tmad-with-stream` from the frozen baseline branch `tmad-baseline`; merge `intake/tmad-stream-flow` (--no-ff). Resolve conflicts semantically against custom and IP-01/09/10/11/12 behaviors (file links, recent agents, navigation history, pinned prompt, status pulse) and custom's tab-menu subagent/side-conversation actions. Inspect clean merges too in shared files: agent-panel.tsx, workspace-tab-menu.ts, segmented-control.tsx, turn-footer.tsx, message.tsx, agent-stream/view.tsx, messages.ts, session.ts, authorization maps, i18n resources. If a resolution needs custom/infi-only code, that is TM-01B: create branch `intake/tmad-stream-bridge` in the clone, cut from the frozen custom SHA merged with only the specific infi branch(es) it adapts and TM-01 (never from mine or tmad-baseline), holding only the adaptation commit(s); it is merged immediately after TM-01. Report exactly what it contains. Keep it minimal. If no bridge is needed, say so with evidence. -2. Build/typecheck/lint the with-stream assembly (npm ci already in clone; npm run build:server, typecheck, lint). Run focused tests: Stream suites (from TM-01 report), authorization/index.test.ts, existing composer submit, navigation history, recent agents, pinned prompt, subagent tab close, side-conversation tests. Record results vs the P0 baseline results. -3. Removal: confirm `git diff --stat tmad-baseline ` is empty where removal-assembly = baseline with no Stream lines (that is tmad-baseline itself) and that the with-stream tree minus Stream paths equals baseline: `git diff tmad-baseline tmad-with-stream --stat` should only list TM-01 (+bridge) paths. Grep the baseline tree for any import of companion-stream/artifacts modules (must be none). -4. Persisted-data rollback exercise using COPIED dev data only (never ~/.paseo): create a temp PASEO_HOME under /tmp/tmad-port/rollback-home, write an agent record containing `companionEntries` (use the storage schema/code in the with-stream tree via a small tsx/vitest script), then load+rewrite it with the baseline storage code and show the stripping. Write a backup/export + restore procedure script /tmp/tmad-port/stream-rollback.md (+ a script if small) that exports Stream fields per agent ID before disabling and restores ONLY those fields for matching agent IDs after re-enabling, never replacing newer non-Stream metadata. Demonstrate it on the copied data. -5. Do not touch the live manifest. Produce the exact proposed manifest append block (text) in your report. -Report per COMMON.md plus: conflict list with resolutions, bridge decision, with/without results table, rollback demo transcript. diff --git a/fork/plans/tmad-port/briefs/brief-TM01.md b/fork/plans/tmad-port/briefs/brief-TM01.md deleted file mode 100644 index 444c76fdc4c..00000000000 --- a/fork/plans/tmad-port/briefs/brief-TM01.md +++ /dev/null @@ -1,25 +0,0 @@ -You are the Stream porter (P1, feature TM-01). Read /tmp/tmad-port/COMMON.md first and obey it, then read ALL of /tmp/tmad-port/plan.md, especially "Compatibility contracts > Stream", "Source tracking", "Update loop" and "P1". Your worktree is already on branch `intake/tmad-stream-flow`, branched from v0.11.0-beta.3 (6166a7aca). It is RELEASE-BASED: custom and mine must never become ancestors. -Report ID: TM-01 (/tmp/tmad-port/evidence/TM-01.md). - -Objective: a complete, standalone Stream/artifact vertical slice (capture, storage, optional wire contract, artifacts, feed, pins, triage, Chat/Stream switching) on beta.3, with provenance, and the PR19->#21 maintenance rehearsal. - -Source map (verify; find more with `git diff --name-status af247e4f4^ af247e4f4`, `gh pr view 19 -R tmad4000/paseo --json files,commits`, and PRs 1, 10, 16): packages/app/src/companion-stream/{feed.tsx,model.ts,model.test.ts}, packages/app/src/artifacts/feed.tsx, packages/protocol/src/companion-stream.ts, packages/protocol/src/messages.artifacts.test.ts, packages/server/src/server/agent/companion-stream{,.test}.ts, packages/server/src/server/agent/artifacts/{collector,collector.test,backfill.test}.ts, packages/cli/src/commands/agent/artifacts-scan.ts, docs/companion-stream.md, and the Stream-specific hunks in shared host files: agent-panel.tsx, workspace-tab-menu.ts, segmented-control.tsx, turn-footer.tsx, message.tsx, agent-stream/view.tsx, protocol messages.ts, session.ts / websocket server, agent storage schema, i18n resources. - -Steps: -1. ONNXRUNTIME_NODE_INSTALL=skip npm ci; record baseline typecheck/lint status on the untouched branch. -2. REHEARSAL FIRST COMMIT SERIES: port the Stream feature content as of PR #19 (af247e4f4) onto beta.3: copy the core module files from af247e4f4 and adapt only the host seams needed to compile/run. Commit (trailers Source-Commit: af247e4f4..., Port-Feature: TM-01). -3. Then apply ONLY the Stream changes from af247e4f4..51fb7693d (`git diff af247e4f4 51fb7693d -- `; expect the two feeds, collector, companion-stream and the artifact backfill test, ~+200/-65) through the same seams, plus the Stream-relevant shared-file hunks from #21. Commit separately (Source-Commit: 51fb7693d...). Record: changed paths, conflicts, adaptation effort (time/hunks), and compare each core file blob with `git rev-parse 51fb7693d:` vs `git hash-object `; list every intentional difference with reason. -4. Contracts (plan Stream section), each as separate local-fix commits where they diverge from source: - - Capture accepted canonical live events after existing stream coalescing; no second timeline owner, no invented history. - - Bounded moments/excerpts; explicit bounds for pins, manual entries and artifact path metadata (measure, choose, test). - - Do NOT restore recursive fs.watch (read docs/file-observation.md); end-turn scans bounded. - - Wire: optional fields only. Feature gate `companionStreamPortV1` in server_info.features; do NOT advertise source's `companionStream`. Rename flat `update_companion_entry_request`/response to `agent.companion.update_entry.request`/`.response`; mutations need workspace.write, reads workspace.read; update every authorization map + client capability default; old clients must not receive unknown top-level events; release observations when the owning view closes. Tag any compat code `// COMPAT(companionStreamPortV1): added in v0.11.0-beta.3-fork, remove after 2027-04-01`. - - Keep Chat mounted when switching to Stream (drafts, attachments, scroll, active agent preserved); selecting a moment never sends/cancels/grants. - - Surface failed pin/triage mutations (no silent catch). Localize labels in EVERY locale under packages/app/src/i18n/resources (incl. ko); label is "Stream pins" (distinct from IP-11's "Pinned prompt", which is not in this branch). - - Preserve the source tab-menu "View Stream" action alongside existing upstream menu items. If something can ONLY compile with custom/infi code, do NOT add it here: list it in the report as a TM-01B bridge requirement. - - Native Find is NOT part of this branch (separate TM-07). Don't port chat-find. -5. Tests: carry source tests (companion model, server companion, collector, backfill, protocol artifacts schema). Add tests for bounds, the renamed RPC, authorization entries, capability-absent behavior. Run each specific file, plus authorization/index.test.ts. npm run build:server, typecheck, lint, format. -6. UI evidence is a later step; but do a quick sanity check that the app typechecks and, if feasible, describe how to reach Stream in the UI in your report. -7. Verify `git merge-base --is-ancestor origin/custom HEAD` is FALSE and same for `mine`. - -Report per COMMON.md, including the rehearsal metrics and the seam table (agent-panel integration, accepted-event capture, storage/projections, protocol delivery, file navigation: source location -> port location -> why different). diff --git a/fork/plans/tmad-port/briefs/brief-TM02.md b/fork/plans/tmad-port/briefs/brief-TM02.md deleted file mode 100644 index 2d9cb9a63d6..00000000000 --- a/fork/plans/tmad-port/briefs/brief-TM02.md +++ /dev/null @@ -1,16 +0,0 @@ -You are the durable queue porter (P3, feature TM-02). Read /tmp/tmad-port/COMMON.md first and obey it, then ALL of /tmp/tmad-port/plan.md, especially "Compatibility contracts > Queue and composer", "Voice and lifecycle" (fences), and "P3". Your worktree is on branch `intake/tmad-message-queue`, cut from custom at cbd1210c7 (this is the recorded custom floor; record it). Do not merge anything else into it. -Report ID: TM-02. - -Source: packages/server/src/server/agent-queue/{store,service,send-or-queue}.ts + tests, packages/server/src/server/daemon-e2e/agent-queue-mirroring.e2e.test.ts, the protocol additions and session/agent-manager hooks in 51fb7693d (source PRs #23, #24, #25, #26, #30, #31, #32 — `gh pr view -R tmad4000/paseo --json files,commits,body`). Find hooks with `git diff cbd1210c7 51fb7693d -- packages/server/src/server/session* packages/server/src/server/agent/agent-manager* packages/protocol/src/messages.ts | grep -n -i queue`. - -Daemon-only scope (no app UI — that is TM-03). Required contract: -- Legacy `send_agent_message_request` without new queue intent keeps EXACTLY current behavior: existing receipt-backed interrupt path including dedup. Source queues omitted activeTurnBehavior and skips the receipt service — do NOT copy that. -- Explicit dotted RPCs (e.g. agent.queue.enqueue/.list/.update/.reorder/.delete/.send_now/.request/.response — choose names per docs/rpc-namespacing.md) and a strict steering intent; new capability flag (distinct from any source capability name, e.g. `durableAgentQueueV1`) in server_info.features; authorization entries for every op (mutations workspace.write, reads workspace.read) and client capability defaults; new enum values never sent to old daemons. -- Stable item identity, durable accept-once, revision-checked edit/reorder/delete (stale revision rejected, not overwritten). -- Dispatch: claim -> provider dispatch -> correlated receipt -> removal. Uncertain dispatch stays visible for reconciliation; never auto-resend an item whose provider acceptance is unknown. Refused steer never interrupts and never deletes. After 8 failed attempts keep the item in a visible failed state with explicit retry/discard. -- Startup: load without dispatching during init; after agents/providers ready, resume only never-dispatched items; hold ambiguous claims. Archived agents keep queue and don't auto-run; agent deletion removes its queue via normal lifecycle. -- Persistence: atomic writes (follow docs/data-model.md), bounded journal bytes/rotations, file perms 0600, bounded queue length and image payload size; store image attachments by reference where possible. -- Preserve custom ACP/GJC admission + cancellation fences and provider-wrapper forwarding (read custom's agent-manager and acp code; run their tests). - -Steps: npm ci; baseline typecheck/lint; port store/service with adaptations as separate commits from the verbatim import; tests: carry source store/service/send-or-queue tests adapted, plus tests for restart, ambiguous send, refused strict steer, image round-trip, concurrent edits (stale revision), archive/delete, legacy send unchanged, authorization/index.test.ts, and existing custom agent-manager/ACP cancellation tests. Daemon e2e: adapt agent-queue-mirroring e2e only if it runs without real provider auth; otherwise document. Mixed-version: write a protocol-level test that an old-shaped request parses and takes the legacy path, and that a client gates on the capability. -Report per COMMON.md, including a crash-point table (admission, claim, dispatch, receipt, removal: what state survives, what recovery does). diff --git a/fork/plans/tmad-port/briefs/brief-TM03.md b/fork/plans/tmad-port/briefs/brief-TM03.md deleted file mode 100644 index e75b51f6f6d..00000000000 --- a/fork/plans/tmad-port/briefs/brief-TM03.md +++ /dev/null @@ -1,13 +0,0 @@ -You are the queue UI porter (P4, feature TM-03). Read /tmp/tmad-port/COMMON.md and obey it, then /tmp/tmad-port/plan.md ("Queue and composer" contract, P4) and /tmp/tmad-port/evidence/TM-02.md (the daemon API you build on). Your worktree is on branch `intake/tmad-queue-ui`, branched from intake/tmad-message-queue (TM-02). Do not merge anything else. -Report ID: TM-03. - -Source: packages/app/src/stores/queue-outbox-store/{index,model,model.test}.ts and composer/queue UI hunks in 51fb7693d from source PRs #23-26, #30-32 (`gh pr view -R tmad4000/paseo --json files,commits,body`; `git diff cbd1210c7 51fb7693d -- packages/app/src | grep`-guided). Port with provenance trailers. -Requirements: -- Canonical submission owner stays `dispatchComposerAgentMessage`; add a queue admission action that does not create a submitted timeline row early; drain/send-now acknowledgement reconciles into the existing identity system so the server's accepted prompt yields exactly one canonical user row. -- Gate on the TM-02 capability flag; against old hosts existing local queues keep their existing meaning and are not portrayed as durable. COMPAT-tag any transition path. -- Edit / reorder / delete / send-now controls with revision handling (stale revision -> visible conflict, not silent overwrite). Preserve draft attachments and edit recovery. -- Outbox: after the source's 8-attempt limit, keep the item visible as failed with explicit Retry / Discard. Uncertain delivery visible as pending reconciliation. -- Explicit Steer, Queue and Interrupt affordances. KEEP our current typed-send default; write a short comparison of source default vs ours in the report for the human to decide (product decision, do not change it). -- Localize all strings in every locale; follow docs/design.md, docs/hover.md, docs/unistyles.md, docs/menus.md. -Tests: carry queue-outbox model tests; add tests for admission without early row, receipt reconciliation to one row, stale revision, retry exhaustion visible state, capability-absent behavior; run existing composer actions/submit/queue-sync tests individually. typecheck, lint, format. If feasible, a two-client daemon e2e (in-process daemon harness per docs/ad-hoc-daemon-testing.md) for enqueue/edit/reorder/delete/reconnect mirroring; otherwise document exactly what remains. -Report per COMMON.md. diff --git a/fork/plans/tmad-port/briefs/brief-TM04.md b/fork/plans/tmad-port/briefs/brief-TM04.md deleted file mode 100644 index 5ffeb970f45..00000000000 --- a/fork/plans/tmad-port/briefs/brief-TM04.md +++ /dev/null @@ -1,11 +0,0 @@ -You are the voice porter (P5, feature TM-04). Read /tmp/tmad-port/COMMON.md and obey it, then /tmp/tmad-port/plan.md ("Voice and lifecycle" contract, P5) and /tmp/tmad-port/evidence/TM-02.md. Your worktree is on branch `intake/tmad-voice-flow` from intake/tmad-message-queue (TM-02). Only if you find shared UI from TM-03 genuinely required, stop and report it (do not merge TM-03 yourself). -Report ID: TM-04. - -Source: source PRs #13, #15, #22, #23 (NOT #14 iOS background = TM-06, NOT #17 mute = TM-05). Files include packages/app/src/voice/{voice-runtime,audio-engine*,microphone-cue,realtime-voice-config}.ts(+tests), contexts/voice-context.tsx, components/realtime-voice-overlay.tsx(+test), packages/server/src/server/session/voice/{index,voice-input-command}.ts(+tests), session.voice-mcp-config.test.ts, providers/claude/agent.voice-history-regression.test.ts. Diff each against cbd1210c7 first; some may already exist upstream — adopt source improvements into existing owners. -Requirements: -- Voice attach/detach, playback interruption, transport loss, STT failure never cancel the agent, pending permissions, children or side conversations. Interruption only via explicit command. -- Speech admission goes through the TM-02 durable queue with a stable item ID; truthful queued/sent/error feedback; never claim provider delivery from a local transcript or socket send. -- Keep attachment ownership + transport-generation checks across reconnects; another device cannot seize an active recording. -- Preserve custom ACP/GJC admission/cancellation fences and provider-wrapper forwarding (run their tests). -Tests: carry source voice runtime/failure/session/turn-controller tests adapted; add survival tests (running turn, pending permission, subagent, side conversation through attach/detach and transport failure). Run each file individually; typecheck, lint, format. Real-provider and physical-device checks are NOT for you: list precisely what a human must verify on device (mic, playback, echo, lock/background, reconnect, owner contention) and per provider (Claude, Codex, ACP/GJC). -Report per COMMON.md. diff --git a/fork/plans/tmad-port/briefs/brief-TM07.md b/fork/plans/tmad-port/briefs/brief-TM07.md deleted file mode 100644 index e6ad13b855e..00000000000 --- a/fork/plans/tmad-port/briefs/brief-TM07.md +++ /dev/null @@ -1,12 +0,0 @@ -You are the Native Find porter (P6 item, feature TM-07). Read /tmp/tmad-port/COMMON.md first and obey it, then /tmp/tmad-port/plan.md (Scope table row "Native chat search wrapper", P6, Verification "Native Find"). Your worktree is on branch `intake/tmad-native-find`, from v0.11.0-beta.3 (6166a7aca). Release-based: custom/mine must never be ancestors. No Stream dependency in either direction. -Report ID: TM-07. - -Context: in our tree packages/app/src/agent-stream/chat-find/index.tsx (native) is a no-op stub while web search exists (index.web.tsx, model/matches/viewport). Source 51fb7693d has a reconciled native wrapper: packages/app/src/agent-stream/chat-find/{index.tsx,native-viewport.ts,native-viewport.test.ts,matches.ts,model.ts,...} (source PRs #11 and #21). Compare every chat-find file between v0.11.0-beta.3 and 51fb7693d first: `git diff v0.11.0-beta.3 51fb7693d -- packages/app/src/agent-stream/chat-find packages/app/e2e/browser/chat-find.spec.ts`, and find the native call sites/viewport hooks it needs in agent-stream/view*.tsx and the tab menu (`git diff v0.11.0-beta.3 51fb7693d -- packages/app/src/agent-stream packages/app/src/screens/workspace` filtered to find-related hunks). - -Steps: -1. ONNXRUNTIME_NODE_INSTALL=skip npm ci; record baseline typecheck/lint. -2. Port the native wrapper + native viewport onto the EXISTING search model/RPC (do not resurrect a removed search scaffold; reuse upstream's model/matches if source changes to them are not needed). Commit with trailers (Source-Commit: 51fb7693d..., Port-Feature: TM-07). -3. Requirements: history loading for matches outside loaded window, selected-row reveal/highlight, invocation via the existing tab menu "Find" (native), cleanup on panel hide/unmount. Must compile and run without any Stream code. Localize any new strings in every locale. -4. Tests: carry native-viewport.test.ts and any matches/model test changes; run each file; npm run typecheck, lint, format. -5. Verify custom/mine not ancestors. -Report per COMMON.md (ledger rows for every chat-find file). Note for the report: native device evidence is required later (iOS simulator/Android); say what to check. diff --git a/fork/plans/tmad-port/evidence/.baseline-merge-status.txt b/fork/plans/tmad-port/evidence/.baseline-merge-status.txt deleted file mode 100644 index d3a5533d203..00000000000 --- a/fork/plans/tmad-port/evidence/.baseline-merge-status.txt +++ /dev/null @@ -1,31 +0,0 @@ -OK fork/multi-account-beta3-2026-10-02 -OK muzhi1991/fix/codex-toolsurface-screenshot -CONFLICT dkribeiro/fix/2610-timeline-byte-bounded-hydration -OK fork/multi-account-beta3-2026-10-02 -OK muzhi1991/fix/codex-toolsurface-screenshot -OK dkribeiro/fix/2610-timeline-byte-bounded-hydration -RERERE-REPLAY timigod/fix/one-shot-workspace-observer-fanout -COMMITTED-AFTER-RERERE timigod/fix/one-shot-workspace-observer-fanout -RERERE-REPLAY bwestlund17/fix/zcode-slash-commands -COMMITTED-AFTER-RERERE bwestlund17/fix/zcode-slash-commands -OK ngothanhthien/fix/coalesced-flush-crashes-daemon-for-torn-down-agent -OK codebutler/claude-permission-reason -OK fork/pinned-cjk-terminal-switch-spacing-2026-10-02 -OK ThePharmer/fix/claude-thinking-display -OK custom -OK intake/infi-agent-file-links -OK intake/infi-fork-pr-lookup -OK intake/infi-desktop-quit-confirmation -OK intake/infi-package-scripts -RERERE-REPLAY intake/infi-plan-copy -COMMITTED-AFTER-RERERE intake/infi-plan-copy -OK intake/infi-plan-handoff -RERERE-REPLAY intake/infi-base-branch-contract -COMMITTED-AFTER-RERERE intake/infi-base-branch-contract -OK intake/infi-branch-header -OK intake/infi-recent-agents -OK intake/infi-pinned-prompt -OK intake/infi-status-pulse -OK intake/infi-project-pr-facts -OK intake/infi-navigation-history -OK intake/infi-project-pr-browser diff --git a/fork/plans/tmad-port/evidence/.manifest-refs.txt b/fork/plans/tmad-port/evidence/.manifest-refs.txt deleted file mode 100644 index 351bd0f3d23..00000000000 --- a/fork/plans/tmad-port/evidence/.manifest-refs.txt +++ /dev/null @@ -1,24 +0,0 @@ -fork/multi-account-beta3-2026-10-02 -muzhi1991/fix/codex-toolsurface-screenshot -dkribeiro/fix/2610-timeline-byte-bounded-hydration -timigod/fix/one-shot-workspace-observer-fanout -bwestlund17/fix/zcode-slash-commands -ngothanhthien/fix/coalesced-flush-crashes-daemon-for-torn-down-agent -codebutler/claude-permission-reason -fork/pinned-cjk-terminal-switch-spacing-2026-10-02 -ThePharmer/fix/claude-thinking-display -custom -intake/infi-agent-file-links -intake/infi-fork-pr-lookup -intake/infi-desktop-quit-confirmation -intake/infi-package-scripts -intake/infi-plan-copy -intake/infi-plan-handoff -intake/infi-base-branch-contract -intake/infi-branch-header -intake/infi-recent-agents -intake/infi-pinned-prompt -intake/infi-status-pulse -intake/infi-project-pr-facts -intake/infi-navigation-history -intake/infi-project-pr-browser diff --git a/fork/plans/tmad-port/evidence/P0-feature-map.md b/fork/plans/tmad-port/evidence/P0-feature-map.md deleted file mode 100644 index 36805e38c5d..00000000000 --- a/fork/plans/tmad-port/evidence/P0-feature-map.md +++ /dev/null @@ -1,308 +0,0 @@ -# P0 source feature/file map - -Source repo: `tmad4000/paseo`. Snapshot inspected: **`51fb7693d`** (source PR #21, the reconciled -integration). Later source commits `51fb7693d..f0d5507d2` are listed at the end. - -## Method - -`51fb7693d` is a **single squash commit** whose message carries an entire upstream sync, so -`git diff dd8a111c3 51fb7693d` touches **3,687 paths** and cannot be used as a feature map. The map -below uses the plan's "declared `v0.10.0-beta.1` integration tree" method instead: - -1. `git diff --name-status 51fb7693d v0.10.0-beta.1^{commit}` -> **190 paths** whose content in the - source snapshot differs from the upstream release #21 declares as its base (`52d345db7`). - These are the fork's own content. -2. The other **3,497 paths** are byte-identical to upstream `v0.10.0-beta.1`: pure upstream-sync - noise, zero port work. 3,487 of them are already carried by our own - `dd8a111c3..v0.11.0-beta.3` sync. The 10 that are not were removed again upstream before - `v0.11.0-beta.3` (`packages/app/src/hooks/use-compact-time-ago.ts`, - `packages/app/src/plugins/{runtime-boundary.tsx,sidebar-items.tsx,surface-runtime.ts,surface-runtime.test.tsx}`, - `packages/app/src/provider-usage/balance-bar.tsx`, two provider-usage e2e specs plus their helper, - `packages/server/src/services/quota-fetcher/providers/claude-keychain.test.ts`). Recorded as gaps - only; they are upstream churn, not fork content. -3. Feature attribution uses the per-PR file lists (`gh api --paginate - repos/tmad4000/paseo/pulls//files` for N in 1 5 8 9 10 11 13..35; raw output kept in - `evidence/gh/pr--files.txt`). **PR #21 is treated as the integration carrier and is never used - as a feature attribution**; content unique to #21 is mapped by inspection and flagged `#21 only`. - -`status` is the source snapshot's state against upstream `v0.10.0-beta.1`: `D` = file exists only in -the fork, `M` = exists in both with different content. - -## Summary - -| disposition | paths | -| --- | --- | -| EXCLUDED | 49 | -| TM-01 | 48 | -| TM-02/TM-03 | 34 | -| TM-08+ | 24 | -| TM-03/TM-08+ | 7 | -| TM-07 | 6 | -| TM-04 | 6 | -| TM-03 | 5 | -| TM-06 | 4 | -| TM-05 | 3 | -| TM-01 seam | 2 | -| TM-01/TM-07 | 2 | -| **total** | **190** | - -Reading notes: - -- `EXCLUDED` covers source branding, app ids/TestFlight, auto-updater, source CI and packaging, - version reservations, and fork-owned documentation (`FORK.md`, `NOTES.md`, the source's own - `docs/rpc-namespacing.md`). We keep our own release channel and our own protocol docs. -- Every `M` row on a shared host file (`panels/agent-panel.tsx`, `agent-stream/view.tsx`, - `screens/workspace/workspace-tab-menu.ts`, `components/ui/segmented-control.tsx`, - `agent-stream/turn-footer.tsx`, `components/message.tsx`, `contexts/session-context.tsx`, - `contexts/voice-context.tsx`, `composer/index.tsx`, `composer/input/input.tsx`, - `stores/session-store.ts`, `stores/panel-store/index.ts`, `i18n/resources/*.ts`, - `server/agent/agent-manager.ts`, `server/session.ts`, `websocket-server.ts`, `protocol/messages.ts`, - `server/authorization/operation-permissions.ts`, `client/daemon-client.ts`) is a **seam**: - infi/custom and the source both changed it. These are the TM-01B candidates. -- `packages/protocol/src/messages.ts` and `packages/server/src/server/authorization/operation-permissions.ts` - are touched by both TM-01 and TM-02/TM-03; they must be sequenced, never cherry-picked twice. -- 9 locale files (`i18n/resources/*.ts`) change for almost every feature; `ko.ts` is the one the - plan calls out for parity checking. - -## Per-path table - -| path | status | feature | source PR | note | -| --- | --- | --- | --- | --- | -| `.oxfmtrc.json` | M | EXCLUDED | #16 | build/branding/release/test-config or fork-owned doc - not ported | -| `CLAUDE.md` | M | EXCLUDED | #16 | build/branding/release/test-config or fork-owned doc - not ported | -| `FORK.md` | D | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `NOTES.md` | D | EXCLUDED | #1 | build/branding/release/test-config or fork-owned doc - not ported | -| `docs/agent-lifecycle.md` | M | EXCLUDED | #5 | build/branding/release/test-config or fork-owned doc - not ported | -| `docs/agent-tab-control.md` | D | TM-02/TM-03 | #32 | durable queue daemon + queue UI (#23-26,#30-32) | -| `docs/architecture.md` | M | EXCLUDED | #8 | build/branding/release/test-config or fork-owned doc - not ported | -| `docs/artifact-feed.png` | D | TM-01 | #1 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `docs/companion-stream.md` | D | TM-01 | #16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `docs/development.md` | M | EXCLUDED | #15,#17,#8 | build/branding/release/test-config or fork-owned doc - not ported | -| `docs/expo-router.md` | M | EXCLUDED | #16,#9 | build/branding/release/test-config or fork-owned doc - not ported | -| `docs/queue-mirroring.md` | D | TM-02/TM-03 | #23,#25 | durable queue daemon + queue UI (#23-26,#30-32) | -| `docs/rpc-namespacing.md` | M | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `docs/voice-input.md` | D | TM-02/TM-03 | #17,#22,#23,#32 | durable queue daemon + queue UI (#23-26,#30-32) | -| `nix/npm-deps.hash` | M | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `package-lock.json` | M | EXCLUDED | #25,#27,#28,#35 | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/app/app.config.js` | M | EXCLUDED | #14 | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/app/eas.json` | M | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/app/scripts/testflight-fork.sh` | D | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/app/src/agent-stream/chat-find/index.tsx` | M | TM-07 | #21 only | reconciled native Find wrapper (replaces the #11 scaffold); uses @/pane-find + existing search model | -| `packages/app/src/agent-stream/chat-find/matches.test.ts` | D | TM-07 | #21 only | native Find match projection test | -| `packages/app/src/agent-stream/chat-find/matches.ts` | D | TM-07 | #21 only | native Find match projection | -| `packages/app/src/agent-stream/chat-find/native-viewport.test.ts` | D | TM-07 | #21 only | native Find viewport test | -| `packages/app/src/agent-stream/chat-find/native-viewport.ts` | D | TM-07 | #21 only | native Find viewport reveal | -| `packages/app/src/agent-stream/strategy-native.tsx` | M | TM-07 | #21 only | native strategy mounts the Find wrapper | -| `packages/app/src/agent-stream/turn-footer.tsx` | M | TM-01 | #19 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/agent-stream/view.tsx` | M | TM-01 | #19 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/app/_layout.tsx` | M | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/artifacts/feed.tsx` | D | TM-01 | #1,#10,#16,#19 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/command-center/agent-control-contributions.test.ts` | M | TM-01 seam | #21 only | contribution ordering test | -| `packages/app/src/command-center/agent-control-contributions.ts` | M | TM-01 seam | #21 only | command-center contributions used by the Stream panel; shared seam | -| `packages/app/src/companion-stream/feed.tsx` | D | TM-01 | #16,#19 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/companion-stream/model.test.ts` | D | TM-01 | #16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/companion-stream/model.ts` | D | TM-01 | #16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/components/desktop/fork-badge.tsx` | D | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/app/src/components/headers/back-header.tsx` | M | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/components/headers/navigation-back-button.tsx` | D | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/components/message.tsx` | M | TM-01 | #18,#19 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/components/realtime-voice-overlay.test.tsx` | D | TM-02/TM-03 | #17,#22,#23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/components/realtime-voice-overlay.tsx` | M | TM-02/TM-03 | #13,#17,#22,#23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/components/ui/segmented-control.tsx` | M | TM-01 | #10,#16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/composer/actions.test.ts` | M | TM-02/TM-03 | #25 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/composer/actions.ts` | M | TM-02/TM-03 | #25 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/composer/index.tsx` | M | TM-02/TM-03 | #13,#23,#24,#25,#32 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/composer/input/input.tsx` | M | TM-02/TM-03 | #13,#17,#22,#23,#25,#30,#32 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/composer/input/state.test.ts` | M | TM-02/TM-03 | #13,#25 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/composer/input/state.ts` | M | TM-02/TM-03 | #13,#25 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/composer/queue-sync.test.ts` | D | TM-03 | #21 only | queue-sync test | -| `packages/app/src/composer/queue-sync.ts` | D | TM-03 | #21 only | daemon queue snapshot <-> local optimistic outbox reconciliation | -| `packages/app/src/contexts/session-context.tsx` | M | TM-02/TM-03 | #15,#17,#22,#23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/contexts/voice-context.tsx` | M | TM-02/TM-03 | #17,#22,#23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/data/push-router.test.ts` | M | TM-02/TM-03 | #21 only | push-router test | -| `packages/app/src/data/push-router.ts` | M | TM-02/TM-03 | #21 only | push delivery owner for queue snapshots; shared seam | -| `packages/app/src/hooks/use-keyboard-shortcuts.ts` | M | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/i18n/resources/ar.ts` | M | TM-01 | #1,#10,#16,#17,#22,#23,#25,#30,#32,#33,#34 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/i18n/resources/en.ts` | M | TM-01 | #1,#10,#16,#17,#22,#23,#25,#30,#32,#33,#34 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/i18n/resources/es.ts` | M | TM-01 | #1,#10,#16,#17,#22,#23,#25,#30,#32,#33,#34 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/i18n/resources/fr.ts` | M | TM-01 | #1,#10,#16,#17,#22,#23,#25,#30,#32,#33,#34 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/i18n/resources/ja.ts` | M | TM-01 | #1,#10,#16,#17,#22,#23,#25,#30,#32,#33,#34 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/i18n/resources/ko.ts` | M | TM-02/TM-03 | #22,#23,#25,#30,#32,#33,#34 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/i18n/resources/pt-BR.ts` | M | TM-01 | #1,#10,#16,#17,#22,#23,#25,#30,#32,#33,#34 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/i18n/resources/ru.ts` | M | TM-01 | #1,#10,#16,#17,#22,#23,#25,#30,#32,#33,#34 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/i18n/resources/zh-CN.ts` | M | TM-01 | #1,#10,#16,#17,#22,#23,#25,#30,#32,#33,#34 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/keyboard/actions.ts` | M | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/keyboard/keyboard-shortcuts.test.ts` | M | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/keyboard/keyboard-shortcuts.ts` | M | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/keyboard/route-shortcut.test.ts` | M | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/keyboard/route-shortcut.ts` | M | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/navigation/focus-history-runtime.test.ts` | D | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/navigation/focus-history-runtime.tsx` | D | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/navigation/focus-history.test.ts` | D | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/navigation/focus-history.ts` | D | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/panels/agent-panel.tsx` | M | TM-01 | #1,#10,#11,#16,#19 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/runtime/host-runtime.test.ts` | M | TM-01/TM-07 | #21 only | host-runtime test | -| `packages/app/src/runtime/host-runtime.ts` | M | TM-01/TM-07 | #21 only | host feature store (companionStreamPortV1 gate lives here); shared seam | -| `packages/app/src/runtime/replica-cache/index.test.ts` | M | TM-01 | #21 only | replica cache test added with artifact feed (#1) | -| `packages/app/src/runtime/replica-cache/index.ts` | M | TM-01 | #1 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/screens/workspace/workspace-desktop-tabs-row.tsx` | M | TM-01 | #10,#33 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/screens/workspace/workspace-screen.tsx` | M | TM-01 | #10,#16,#33,#9 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/screens/workspace/workspace-tab-menu.ts` | M | TM-01 | #10 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/screens/workspace/workspace-tab-trailing-accessory.test.tsx` | M | TM-08+ | #21 only | trailing control test | -| `packages/app/src/screens/workspace/workspace-tab-trailing-accessory.tsx` | M | TM-08+ | #21 only | tab trailing control used by CLI-opened tabs (#5) | -| `packages/app/src/stores/agent-view-store.ts` | D | TM-01 | #10,#11 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/stores/panel-store/index.ts` | M | EXCLUDED | #9 | Recent-focus Back is owned by IP-10 navigation history (duplicate store) | -| `packages/app/src/stores/queue-outbox-store/index.ts` | D | TM-03 | #21 only | local optimistic outbox store | -| `packages/app/src/stores/queue-outbox-store/model.test.ts` | D | TM-03 | #21 only | outbox model test | -| `packages/app/src/stores/queue-outbox-store/model.ts` | D | TM-03 | #21 only | outbox model + pending enqueue intent | -| `packages/app/src/stores/session-store.ts` | M | TM-01 | #1,#16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/stores/workspace-layout-store.ts` | M | TM-08+ | #21 only | tab layout/visibility store touched by #5 | -| `packages/app/src/ui-commands/listener.tsx` | D | TM-03/TM-08+ | #21 only | drains buffered ui.commands once the shell mounts | -| `packages/app/src/ui-commands/queue.ts` | D | TM-03/TM-08+ | #21 only | pre-mount ui.command buffer; lost commands are the risk to test | -| `packages/app/src/ui-commands/resolve.test.ts` | D | TM-03/TM-08+ | #21 only | ui.command resolution test | -| `packages/app/src/ui-commands/resolve.ts` | D | TM-03/TM-08+ | #21 only | ui.command resolution (tab open + queue control targets) | -| `packages/app/src/utils/agent-snapshots.ts` | M | TM-01 | #1,#16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/app/src/voice/audio-engine.native.test.ts` | D | TM-04 | #15 | voice lifecycle / playback recovery / failure feedback | -| `packages/app/src/voice/audio-engine.native.ts` | M | TM-04 | #14,#15 | voice lifecycle / playback recovery / failure feedback | -| `packages/app/src/voice/microphone-cue.ts` | D | TM-05 | #17 | verbal mute/unmute | -| `packages/app/src/voice/voice-runtime.test.ts` | M | TM-02/TM-03 | #15,#17,#22,#23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/voice/voice-runtime.ts` | M | TM-02/TM-03 | #15,#17,#22,#23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/app/src/workspace-tabs/agent-visibility.test.ts` | M | TM-08+ | #5 | CLI-created sessions open tabs - needs tab/subagent-close policy review | -| `packages/app/src/workspace-tabs/agent-visibility.ts` | M | TM-08+ | #5 | CLI-created sessions open tabs - needs tab/subagent-close policy review | -| `packages/app/test-stubs/lucide-react-native.ts` | M | EXCLUDED | #17 | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/app/tsconfig.json` | M | EXCLUDED | #15 | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/app/vitest.config.ts` | M | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/cli/package.json` | M | EXCLUDED | #25,#27,#35 | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/cli/src/cli-surface.test.ts` | M | TM-08+ | #8 | remember default CLI daemon target | -| `packages/cli/src/cli.ts` | M | EXCLUDED | #8 | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/cli/src/commands/agent/artifacts-scan.ts` | D | TM-01 | #21 only | CLI artifact scan against the artifact collector | -| `packages/cli/src/commands/agent/index.ts` | M | TM-08+ | #21 only | CLI agent command surface (#8 daemon target + #5 tab open) | -| `packages/cli/src/commands/agent/run.test.ts` | M | TM-08+ | #5 | CLI-created sessions open tabs - needs tab/subagent-close policy review | -| `packages/cli/src/commands/agent/run.ts` | M | TM-08+ | #5 | CLI-created sessions open tabs - needs tab/subagent-close policy review | -| `packages/cli/src/commands/open.ts` | M | TM-08+ | #21 only | CLI open/deep-link (#5) | -| `packages/cli/src/commands/target.test.ts` | D | TM-08+ | #8 | remember default CLI daemon target | -| `packages/cli/src/commands/target.ts` | D | TM-08+ | #8 | remember default CLI daemon target | -| `packages/cli/src/commands/ui/index.ts` | D | TM-08+ | #21 only | CLI ui command surface (#5) | -| `packages/cli/src/commands/ui/open-tab.ts` | D | TM-08+ | #21 only | CLI open-tab (#5) | -| `packages/cli/src/utils/client-target.ts` | D | TM-08+ | #8 | remember default CLI daemon target | -| `packages/cli/src/utils/daemon-target.ts` | M | TM-08+ | #21 only | persisted CLI daemon target (#8) | -| `packages/cli/tests/28-client-ipc-targets.test.ts` | M | TM-08+ | #8 | remember default CLI daemon target | -| `packages/client/src/daemon-client.ts` | M | TM-01 | #11,#15,#16,#17,#19,#23,#25 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/desktop/assets/icon-fork.icns` | D | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/desktop/assets/icon-fork.png` | D | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/desktop/bin/paseo` | M | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/desktop/electron-builder.fork.cjs` | D | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/desktop/package.json` | M | EXCLUDED | #25,#27,#35 | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/desktop/scripts/after-pack.js` | M | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/desktop/scripts/after-sign.js` | M | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/desktop/scripts/linux-sandbox/index.js` | M | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/desktop/scripts/make-fork-icon.py` | D | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/desktop/src/daemon/desktop-packaging.test.ts` | M | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/desktop/src/features/auto-updater.ts` | M | EXCLUDED | #20 | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/desktop/src/integrations/cli-install/paths.ts` | M | EXCLUDED | #21 only | build/branding/release/test-config or fork-owned doc - not ported | -| `packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/AudioEngine.kt` | M | TM-06 | #14 | iOS background dictation - own native gate | -| `packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/ExpoTwoWayAudioModule.kt` | M | TM-06 | #14 | iOS background dictation - own native gate | -| `packages/expo-two-way-audio/ios/AudioEngine.swift` | M | TM-06 | #14 | iOS background dictation - own native gate | -| `packages/expo-two-way-audio/ios/ExpoTwoWayAudioModule.swift` | M | TM-06 | #14 | iOS background dictation - own native gate | -| `packages/expo-two-way-audio/src/events.ts` | M | TM-04 | #15 | voice lifecycle / playback recovery / failure feedback | -| `packages/protocol/src/agent-deep-link.test.ts` | M | TM-08+ | #21 only | deep link test | -| `packages/protocol/src/agent-deep-link.ts` | M | TM-08+ | #21 only | agent deep link wire shape (#5) - new wire fields must be optional | -| `packages/protocol/src/agent-labels.test.ts` | M | TM-08+ | #5 | CLI-created sessions open tabs - needs tab/subagent-close policy review | -| `packages/protocol/src/agent-labels.ts` | M | TM-08+ | #5 | CLI-created sessions open tabs - needs tab/subagent-close policy review | -| `packages/protocol/src/agent-types.ts` | M | TM-01 | #1 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/protocol/src/companion-stream.ts` | D | TM-01 | #16,#19 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/protocol/src/messages.artifacts.test.ts` | D | TM-01 | #1,#16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/protocol/src/messages.ts` | M | TM-01 | #1,#11,#15,#16,#17,#19,#22,#23,#25 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/protocol/src/messages.ui-commands.test.ts` | D | TM-03/TM-08+ | #21 only | ui.command wire schema test | -| `packages/protocol/src/messages.voice-mute.test.ts` | D | TM-02/TM-03 | #17,#22,#23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/agent-queue/send-or-queue.test.ts` | D | TM-02/TM-03 | #23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/agent-queue/send-or-queue.ts` | D | TM-02/TM-03 | #23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/agent-queue/service.test.ts` | D | TM-02/TM-03 | #23,#25 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/agent-queue/service.ts` | D | TM-02/TM-03 | #23,#25,#31 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/agent-queue/store.ts` | D | TM-02/TM-03 | #23,#25 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/agent/agent-loading.ts` | M | TM-01 | #1,#16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/agent/agent-manager-stream-coalescing.test.ts` | M | TM-01 | #16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/agent/agent-manager.test.ts` | M | TM-02/TM-03 | #17,#25 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/agent/agent-manager.ts` | M | TM-01 | #1,#11,#16,#17,#19,#23 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/agent/agent-projections.ts` | M | TM-01 | #1,#16,#5 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/agent/agent-prompt.ts` | M | TM-02/TM-03 | #23,#25 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/agent/agent-storage.ts` | M | TM-01 | #1,#16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/agent/artifacts/backfill.test.ts` | D | TM-01 | #21 only | artifact backfill coverage added by #21 | -| `packages/server/src/server/agent/artifacts/collector.test.ts` | D | TM-01 | #1 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/agent/artifacts/collector.ts` | D | TM-01 | #1 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/agent/companion-stream.test.ts` | D | TM-01 | #16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/agent/companion-stream.ts` | D | TM-01 | #16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/agent/create-agent/create.ts` | M | TM-08+ | #21 only | creation path touched for CLI tab policy (#5) | -| `packages/server/src/server/agent/lifecycle-command.test.ts` | M | TM-01 | #21 only | lifecycle-command coverage from Stream pins (#19) | -| `packages/server/src/server/agent/lifecycle-command.ts` | M | TM-01 | #19 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/agent/mcp-server.test.ts` | M | TM-08+ | #15,#23,#5 | CLI-created sessions open tabs - needs tab/subagent-close policy review | -| `packages/server/src/server/agent/tools/paseo-tools.ts` | M | TM-02/TM-03 | #23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/agent/tts-manager.test.ts` | M | TM-04 | #15 | voice lifecycle / playback recovery / failure feedback | -| `packages/server/src/server/agent/tts-manager.ts` | M | TM-04 | #15 | voice lifecycle / playback recovery / failure feedback | -| `packages/server/src/server/authorization/operation-permissions.ts` | M | TM-02/TM-03 | #23,#25 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/bootstrap.ts` | M | TM-02/TM-03 | #23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/daemon-e2e/agent-queue-mirroring.e2e.test.ts` | D | TM-02/TM-03 | #25,#31 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/persistence-hooks.ts` | M | TM-01 | #1,#16 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/session.ts` | M | TM-01 | #11,#15,#16,#17,#19,#23,#25 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `packages/server/src/server/session/voice/index.ts` | M | TM-02/TM-03 | #23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/session/voice/voice-input-command.test.ts` | D | TM-05 | #17 | verbal mute/unmute | -| `packages/server/src/server/session/voice/voice-input-command.ts` | D | TM-05 | #17 | verbal mute/unmute | -| `packages/server/src/server/session/voice/voice-session.test.ts` | M | TM-02/TM-03 | #17,#22,#23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/session/voice/voice-session.ts` | M | TM-02/TM-03 | #13,#15,#17,#22,#23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/session/voice/voice-turn-controller.test.ts` | M | TM-04 | #17,#22 | voice lifecycle / playback recovery / failure feedback | -| `packages/server/src/server/session/voice/voice-turn-controller.ts` | M | TM-02/TM-03 | #17,#22,#23 | durable queue daemon + queue UI (#23-26,#30-32) | -| `packages/server/src/server/ui-commands.test.ts` | D | TM-03/TM-08+ | #21 only | ui.command test | -| `packages/server/src/server/ui-commands.ts` | D | TM-03/TM-08+ | #21 only | daemon-side ui.command fan-out (exists check only) | -| `packages/server/src/server/ui-tab-open.e2e.test.ts` | D | TM-08+ | #21 only | CLI-open tab e2e | -| `packages/server/src/server/websocket-server.ts` | M | TM-01 | #1,#15,#16,#17,#23,#25 | Stream/artifact capture + feed + pins/triage (#1,#10,#16,#19; reconciled by #21) | -| `public-docs/always-on-daemon.md` | D | EXCLUDED | #8 | build/branding/release/test-config or fork-owned doc - not ported | -| `public-docs/cli.md` | M | EXCLUDED | #8 | build/branding/release/test-config or fork-owned doc - not ported | -| `public-docs/configuration.md` | M | EXCLUDED | #8 | build/branding/release/test-config or fork-owned doc - not ported | - -## Commits after `51fb7693d` up to the frozen source head `f0d5507d2` - -`git log --oneline 51fb7693d..f0d5507d2` — 31 commits. Proposed disposition for each. None of -these are in the frozen source snapshot used for TM-01; they are **candidates for the update loop**, -not part of the first port. - -| sha | paths | subject | feature | proposed disposition | -| --- | --- | --- | --- | --- | -| `5c757bdddb` | 2 | fix(app): rebuild relay before TestFlight app deps; document M3 build steps | EXCLUDED | drop: TestFlight/source release machinery | -| `af517bc7ee` | 32 | #22 voice failure reasons | TM-04 | candidate; read `packages/server/src/server/session/voice/voice-recognition-issue.ts` at `f0d5507d2` when TM-04 starts | -| `e309257e61` | 53 | #23 keep agent work running while voice queues follow-ups | TM-02/TM-04 | candidate; **this is the durable queue's origin on the source side** — TM-02 must read it, but its admission semantics conflict with our receipt-backed interrupt path | -| `79e2c2e480` | 3 | #24 restore queued message text in the editor | TM-03 | candidate; composer draft recovery | -| `0bdb40e485` | 4 | fix(server): preserve structured provider startup errors | standalone | candidate independent fix; evaluate against our current upstream (plan: "provider startup/ACP rejection messages") | -| `2fd4c4778e` | 2 | fix(server): show ACP mode rejection details | standalone | candidate independent fix; **must not weaken the custom ACP/GJC admission fence** | -| `d6d640344f` | 21 | filter and sort sidebar sessions | DEFER (sidebar) | defer; reconcile with IP-09/IP-10/IP-12 | -| `fe206f5e40` | 25 | preserve queued messages + safe steer now | TM-02/TM-03 | candidate; source's "safe steer now" omits the receipt service on our side — do not copy as-is | -| `490c25e10f` | 21 | edit queued messages in place | TM-02/TM-03 | candidate; queue revisions | -| `72727a6e9c` | 12 | atomic send with strict steer | TM-02 | candidate; **strict steer must never interrupt a turn** | -| `5b6631b454` | 3 | keep send-now queued until receipt confirms | TM-02/TM-03 | candidate; this is the behaviour our receipt model already wants | -| `b9454b38b1` | 14 | chore: mark fork 0.10.0-beta.2 | EXCLUDED | drop: version reservation + workspace package.json churn | -| `11362e27d5` | 10 | collapse long queued message lists | TM-03 | candidate; presentation | -| `8c97ca3786` | 57 | merge #25 queue safety + sidebar controls | TM-02/TM-03/DEFER | mixed: split into the queue part (candidate) and the sidebar part (DEFER) | -| `d68969c647` | 1 | #26 journal POSIX mode only on POSIX | TM-02 | candidate; portability test, trivial | -| `1d1d3ddba0` | 1 | merge #26 | TM-02 | candidate (merge wrapper) | -| `fd35cb3dfa` | 18 | #27 sort project groups by recent activity | DEFER | defer; version/package churn + sidebar | -| `9d5c5a1510` | 2 | #28 restore xterm addon beta pins | EXCLUDED | drop: source dependency pins | -| `a84417ac51` | 1 | #29 parseable beta3 changelog heading | EXCLUDED | drop: source CHANGELOG | -| `ea20ccc76c` | 10 | #30 send actions in tooltip and menu | TM-03 | candidate | -| `b88762352e` | 6 | #31 queued send control tests | TM-03 | candidate; carry the tests | -| `794c9e0b35` | 20 | #32 busy send choices visible | TM-03 | candidate; **the typed-send default is a product decision, not a source merge** | -| `fe9086a39b` | 17 | #33 unread activity + agent tab sorting | DEFER | defer; reconcile with IP-12 status pulse | -| `e66cc56b84` | 17 | #34 quiet tool-call display | DEFER | optional; approved-command visibility gap recorded in the source PR | -| `da5b159af0` | 9 | default to Summary, keep failed calls visible | DEFER | optional; existing tool presentation is our owner | -| `6cae90316e` | 1 | Summary default settings test | DEFER | with the above | -| `a4bd8e3fe8` | 2 | keep answered questions/approvals visible in Quiet | DEFER | with the above | -| `5de785ea26` | 3 | document tool-call display | DEFER | with the above | -| `c40ee303ff` | 14 | #35 reserve beta.5 | EXCLUDED | drop: version reservations | -| `9c613486dc` | 3 | no-mistakes: apply CI fixes | EXCLUDED | drop: source CI | -| `f0d5507d21` | 22 | merge #34 | DEFER | merge wrapper for #34 | - -### Classification cursors for this snapshot - -- Last source head **inspected**: `f0d5507d21cf7f6d86c792d235f3c27156a27d7a` (`f0d5507d2`). -- Last source head **fully classified**: `f0d5507d2` — every commit in `51fb7693d..f0d5507d2` has a - disposition above and every path in the frozen 190-path fork delta has a feature ID. -- **Effective source snapshot for TM-01**: `51fb7693d` (the reconciled integration), with - `af247e4f4` (PR #19, Stream pins) as the pre-reconciliation boundary for the P1 rehearsal. diff --git a/fork/plans/tmad-port/evidence/P0-inputs.txt b/fork/plans/tmad-port/evidence/P0-inputs.txt deleted file mode 100644 index 0f627f59dd1..00000000000 --- a/fork/plans/tmad-port/evidence/P0-inputs.txt +++ /dev/null @@ -1,46 +0,0 @@ -# P0 frozen inputs — recorded 2026-10-02 (workdir /tmp/tmad-port, source repo /Volumes/offload/neptune/repos/paseo) - -## Named anchors -v0.11.0-beta.3^{commit} 6166a7aca5e3184e8ab505caad28f6a595816414 -v0.11.0-beta.3^{tag} 6dc2bb5a608923fa4723a4ceaa26d0722ad1bacc -refs/tags/v0.11.0-beta.3 6dc2bb5a608923fa4723a4ceaa26d0722ad1bacc -origin/custom cbd1210c7d15fbdaac02cab8375cdcf2dd6bd234 -refs/remotes/origin/custom cbd1210c7d15fbdaac02cab8375cdcf2dd6bd234 -refs/research/tmad-main f0d5507d21cf7f6d86c792d235f3c27156a27d7a -51fb7693d 51fb7693d39b0c888654c75fe596427e1e012872 -af247e4f4 af247e4f4805e0de4736b07aebf2592d9c2e7b39 -dd8a111c3 dd8a111c30dcc6457a7c4eddaddc5346967fa57f -mine 4cc94e07e870e1461640ce3256d1db2d0ab1bc2f - -## Manifest carries (order preserved, one line per manifest line) - 1 fork/multi-account-beta3-2026-10-02 428858190ff4a087aa26acda6dc5ad2a01bc846c - 2 muzhi1991/fix/codex-toolsurface-screenshot c56829d513108c8312a4a20c218ee2daa473d41c - 3 dkribeiro/fix/2610-timeline-byte-bounded-hydration 750c19dd99808ca94c54b7e338b4910038c0227a - 4 timigod/fix/one-shot-workspace-observer-fanout 18ba14b7d6d1e90daf6a0fff0a9c65fa7672d141 - 5 bwestlund17/fix/zcode-slash-commands cd55ef7b9bd7c4d83690571c9acc7d3c3b7135f8 - 6 ngothanhthien/fix/coalesced-flush-crashes-daemon-for-torn-down-agent 439719d9b4ae556c80bdad9af7c034bb39777feb - 7 codebutler/claude-permission-reason e7d556ef808dd1be25b9a7551cd3c0cc8d0bfcbd - 8 fork/pinned-cjk-terminal-switch-spacing-2026-10-02 c3707e6beebe19b8c6919f10f79b7c04702adbcd - 9 ThePharmer/fix/claude-thinking-display b61e3de5020d483f517a3b7afcf2a1d329b5ab89 -10 custom cbd1210c7d15fbdaac02cab8375cdcf2dd6bd234 -11 intake/infi-agent-file-links cabbc692d912209bda55a85775e5e534e27cdc8f -12 intake/infi-fork-pr-lookup 63736058421f4f017f0a24e22131964dca6b294f -13 intake/infi-desktop-quit-confirmation 0d4161b1cb017789ad6838d884a618e88aeb16bc -14 intake/infi-package-scripts 1967db56b366f2284d0665ffb1b4fb91873d2dc8 -15 intake/infi-plan-copy 422996012a12bd95e59861c2bb10cc943dbae5fb -16 intake/infi-plan-handoff fbc6af59cf5d755aa2ab55711924503f9c23eda4 -17 intake/infi-base-branch-contract 06b79b7c94b5b47d4a07dfcc977eb1851cac6352 -18 intake/infi-branch-header d2a06926093e16a1142280df06c22c38f0db2a0b -19 intake/infi-recent-agents 6795dbffec023a779ff19f5e0019e0017055f561 -20 intake/infi-pinned-prompt 97753d7c90413b88fab66607a061db0248720d3e -21 intake/infi-status-pulse bc2f2558072d1aa7c0ea392d78362fd8efd5e822 -22 intake/infi-project-pr-facts f3a66c4be32a9fa8bfc38ee061db0c876f037f17 -23 intake/infi-navigation-history 14b36be7c4cf5d975916f082939f237394411707 -24 intake/infi-project-pr-browser 739ec1c377e9b917528642376a17af65c1b6e11b - -## Frozen `mine` assembly verification (frozen mine = 4cc94e07e870e1461640ce3256d1db2d0ab1bc2f) -Command: git log --first-parent --reverse --format='%H %P %s' 6166a7aca..4cc94e07 -Result: 24 first-parent commits, all merges, in exactly manifest order; each merged -second parent equals the frozen manifest SHA for that line. Mismatches: 0. -Non-merge commits on the first-parent chain: 0. -Conclusion: frozen mine == v0.11.0-beta.3 + the 24 frozen carries, nothing else. diff --git a/fork/plans/tmad-port/evidence/P0.md b/fork/plans/tmad-port/evidence/P0.md deleted file mode 100644 index 3ca3a8874ca..00000000000 --- a/fork/plans/tmad-port/evidence/P0.md +++ /dev/null @@ -1,185 +0,0 @@ -# P0 report — frozen-baseline verification and assembly gates - -Worker: P0 integrator. Date: 2026-10-02. Workspace: isolated clone `/tmp/tmad-port/baseline-clone` -(own index/config; `origin` = `/home/ctaylor/repos/paseo`, read-only — **nothing pushed, nothing fetched**). -No application code was modified anywhere; the clone working tree is clean. - -## Snapshot record - -| Item | Value | -| --- | --- | -| Branch | `tmad-port/baseline-assembly` (the `tmad-baseline` assembly merges) | -| Base | `v0.11.0-beta.3` = `6166a7aca5e3184e8ab505caad28f6a595816414` | -| Final HEAD | `2bfcd2e19638484baf1651d69dc0be55df483bcd` | -| Frozen mine | `4cc94e07e870e1461640ce3256d1db2d0ab1bc2f` (never followed while it moved; SHA only) | -| Frozen inputs | `/tmp/tmad-port/evidence/P0-inputs.txt` (steps 1–2 record: anchors + 24 manifest carry SHAs in order) | -| Delta vs base | 329 files changed, 31611 insertions(+), 772 deletions(-) | - -`git log --oneline --first-parent 6166a7aca..HEAD` — exactly 24 merges, manifest order -(lines 1–24 of P0-inputs.txt; full list in `/tmp/tmad-port/logs/p0-baseline-log.txt`): - -``` -2bfcd2e19 merge intake/infi-project-pr-browser into tmad-baseline -3816f2ef1 merge intake/infi-navigation-history into tmad-baseline -20f6ae0c2 merge intake/infi-project-pr-facts into tmad-baseline -59a6aadf7 merge intake/infi-status-pulse into tmad-baseline -9ecfb45d3 merge intake/infi-pinned-prompt into tmad-baseline -7faf9571d merge intake/infi-recent-agents into tmad-baseline -dd9c9b6cb merge intake/infi-branch-header into tmad-baseline -4ff81d708 merge intake/infi-base-branch-contract into tmad-baseline -ecfe75ac2 merge intake/infi-plan-handoff into tmad-baseline -c3e32c570 merge intake/infi-plan-copy into tmad-baseline -5e14d6a8b merge intake/infi-package-scripts into tmad-baseline -bb98f8ea4 merge intake/infi-desktop-quit-confirmation into tmad-baseline -97d640450 merge intake/infi-fork-pr-lookup into tmad-baseline -0e1a3c9fe merge intake/infi-agent-file-links into tmad-baseline -edc8616e9 merge custom into tmad-baseline -05d6bba0f merge ThePharmer/fix/claude-thinking-display into tmad-baseline -38a63d8e2 merge fork/pinned-cjk-terminal-switch-spacing-2026-10-02 into tmad-baseline -5e51554d7 merge codebutler/claude-permission-reason into tmad-baseline -97d8b7ed2 merge ngothanhthien/fix/coalesced-flush-crashes-daemon-for-torn-down-agent into tmad-baseline -31eb00c80 merge bwestlund17/fix/zcode-slash-commands into tmad-baseline -131f0cd13 merge timigod/fix/one-shot-workspace-observer-fanout into tmad-baseline -2a0f60237 merge dkribeiro/fix/2610-timeline-byte-bounded-hydration into tmad-baseline -67c7cbbff merge muzhi1991/fix/codex-toolsurface-screenshot into tmad-baseline -0e5d18a5d merge fork/multi-account-beta3-2026-10-02 into tmad-baseline -``` - -Merge log of the assembly: `/tmp/tmad-port/evidence/.baseline-merge-status.txt` — one early aborted -attempt (conflict on carry 3 before the rerere cache was in place), then a clean restart: 21 clean -merges, 3 rerere replays (`timigod/one-shot-workspace-observer-fanout`, `bwestlund17/zcode-slash-commands`, -`intake/infi-plan-copy`) plus 2 more rerere-assisted (`infi-base-branch-contract`), all committed. - -## Reproducibility statement - -**The baseline assembly is reproducible and equals the frozen `mine` assembly exactly.** - -1. **Tree equality (step-3 final check, re-run by P0 finisher):** - `git diff --stat HEAD 4cc94e07e870e1461640ce3256d1db2d0ab1bc2f` → empty output, exit 0. - The coordinator had observed the same once before; this re-run confirms it. - Baseline tree == frozen mine tree. - -2. **Frozen mine is an assembly of exactly the frozen inputs (brief step 2, re-run and scripted):** - `git log --first-parent --reverse --format='%H %P' 6166a7aca..4cc94e07e` - (script `/tmp/tmad-port/logs/p0-verify-mine-chain.sh`, log `p0-verify-mine-chain.log`): - - 24 first-parent commits between base and frozen mine, every one a 2-parent merge, no non-merge commits. - - Each first parent equals the previous chain commit (unbroken chain from the base). - - Each second parent equals the frozen manifest SHA at that position in P0-inputs.txt — 24/24 OK, 0 mismatches. - - `git rev-list 4cc94e07e --not <24 carries>` = 24 commits, and that set is **identical** to the - 24 first-parent assembly merges — i.e. no commit exists in frozen mine that is not reachable from the - base or the carries except the assembly merges themselves. - - Conclusion: frozen mine == v0.11.0-beta.3 + the 24 frozen carries in manifest order, nothing else. - -3. **The clone's baseline branch has the same shape** (script `p0-verify-baseline-chain.sh`, log - `p0-verify-baseline-chain.log`): 24 first-parent merges in manifest order, correct second parents, - extra-commit set == the 24 assembly merges. Merge commit SHAs differ from frozen mine's (parallel - assembly), but the trees are equal per (1). - -## Branch-ancestry statement - -Exit criterion "no unknown branch ancestry": **met.** - -| `git merge-base --is-ancestor` | Result | Expected | -| --- | --- | --- | -| `v0.11.0-beta.3` (6166a7aca) → baseline HEAD | YES | YES — declared base | -| `custom` (cbd1210c7) → baseline HEAD | YES | YES — manifest line 10 | -| frozen `mine` (4cc94e07e) → baseline HEAD | NO | NO — mine is a parallel assembly, not an input | -| source head `refs/research/tmad-main` (f0d5507d2) → baseline HEAD | NO | NO — source fork must not be ancestry | -| source integration 51fb7693d → baseline HEAD | NO | NO — never imported wholesale | - -Every commit reachable from baseline HEAD is reachable from the base or one of the 24 frozen carries -(verified with `git rev-list HEAD --not `; remainder == the 24 assembly merges). -No custom/mine/source ancestry beyond what the manifest declares. - -## Commands and results - -| # | Command (from `/tmp/tmad-port/baseline-clone`) | Result | Log | -| --- | --- | --- | --- | -| 1 | `ONNXRUNTIME_NODE_INSTALL=skip npm ci` | **PASS** (exit 0; postinstall patches applied) | `logs/p0-npm-ci.log` | -| 2 | `npm run build:server` | **PASS** (exit 0) | `logs/p0-build-server.log` | -| 3 | `npm run typecheck` | **PASS** (exit 0, all packages) | `logs/p0-typecheck.log` | -| 4 | `npm run lint` | **PASS** (exit 0; oxlint: 0 warnings, 0 errors, 4589 files, 177 rules) | `logs/p0-lint.log` | -| 5 | `git diff --stat HEAD 4cc94e07e` | **PASS** (empty diff) | this report §Reproducibility | -| 6 | focused tests, individually (table below) | see below | `logs/p0-test-*.log` | - -Focused tests — each run as `npx vitest run --bail=1` from its owning package dir -(`packages/server` or `packages/app`), serially, never a full suite: - -| Test file | Feature area | Result | Log | -| --- | --- | --- | --- | -| `src/server/authorization/index.test.ts` | authorization maps | **PASS** — 7/7 | `logs/p0-test-auth.log` | -| `src/server/agent/agent-manager.test.ts` | cancellation / ACP fences | **PASS** — 210/210 | `logs/p0-test-agent-manager.log` | -| `src/composer/submit.test.ts` | composer submit | **PASS** — 6/6 | `logs/p0-test-composer-submit.log` | -| `src/navigation/history/model.test.ts` | infi navigation-history | **PASS** — 56/56 | `logs/p0-test-nav-model.log` | -| `src/navigation/history/record-location.test.ts` | infi navigation-history | **PASS** — 4/4 | `logs/p0-test-nav-record-location.log` | -| `src/navigation/history/recorder.test.tsx` | infi navigation-history | **PASS** — 9/9 | `logs/p0-test-nav-recorder.log` | -| `src/navigation/history/replay.test.ts` | infi navigation-history | **PASS** — 10/10 | `logs/p0-test-nav-replay.log` | -| `src/navigation/history/select-active-tab.test.ts` | infi navigation-history | **PASS** — 5/5 | `logs/p0-test-nav-select-active-tab.log` | -| `src/navigation/history/store.test.ts` | infi navigation-history | **PASS** — 6/6 | `logs/p0-test-nav-store.log` | -| `src/workspace-tabs/recently-closed.test.ts` | infi recent-agents | **PASS** — 4/4 | `logs/p0-test-recently-closed.log` | -| `src/subagents/close-tab-policy.test.ts` | subagent tab close | **PASS** — 3/3 | `logs/p0-test-close-tab-policy.log` | - -Total: 11 files, 320 tests, 0 failures on the assembled baseline. - -(A first attempt at this test batch exited 1 for every file before vitest started — a `cd` bug in my -runner script, wrong relative paths. No test ran in that attempt; the rerun above is the real result.) - -## Pre-existing failures - -Listed separately per plan ("a failing baseline is not evidence against the port"). **Not fixed.** - -**None observed.** All 11 focused test files passed on the assembled baseline (320/320 tests), so the -focused set carries no pre-existing failures to track. The plan's expectation of possible pre-existing -failures simply did not materialize on this snapshot; gates for later phases should still compare -against this green result rather than assume it. - -## Licensing (step 6) - -- Source `LICENSE` at `51fb7693d` vs our `LICENSE` in the baseline: **byte-identical** - (`diff` empty; both 211 lines; copy kept at `logs/p0-source-LICENSE.txt`). -- License terms: Apache-2.0, "Copyright (c) 2025-present Mohamed Boudra", third-party components remain - under their own licenses. The source fork (`tmad4000/paseo`) is a fork of `getpaseo/paseo` (its - `FORK.md` says so); it ships **no separate LICENSE or NOTICE** and no per-file license headers on the - feature files inspected (`companion-stream/model.ts`, `agent/companion-stream.ts`, - `agent/artifacts/collector.ts` — all start directly with imports). -- Conclusion: **no additional attribution is required** for ported files beyond what the repo already - carries. The identical Apache-2.0 LICENSE satisfies §4(a); there are no source copyright/NOTICE - notices to preserve under §4(b)/(d) (none exist upstream of us); and the §4 "state changes" obligation - is met by the `Source-Repo:` / `Source-Commit:` / `Port-Feature:` trailers COMMON.md already requires - on every imported/adapted commit. Fork branding/app-id/release machinery remains excluded per plan. - -## Source → port ledger - -No feature code was ported in P0, so no new ledger rows are created here. The classification inputs -live in: `/tmp/tmad-port/evidence/P0-feature-map.md` (step 5: fork-content map by feature ID with -source PRs, upstream-sync noise separation, EXCLUDED/DEFER dispositions, and the -`51fb7693d..f0d5507d2` post-integration commit list) and `/tmp/tmad-port/evidence/P0-inputs.txt` -(frozen SHAs). Later phases append ledger rows with source/local blob IDs when they actually port files. - -## Known gaps / state notes / deferred - -1. **Clone rerere cache is currently empty.** `rerere.enabled=true`, but `.git/rr-cache/` holds no - entries now (the shared repo's top-level rr-cache is also empty at this time). The assembly merge log - shows rerere replays worked during assembly, so resolutions were available then; entries may since - have been pruned by `git rerere gc`. P1/P2 merge phases reusing this clone must re-copy a live - rr-cache or budget for fresh conflict resolutions. -2. The assembly contains one artifact that P0-feature-map flags for later phases, not P0: the 10 - upstream-churn paths absent from `v0.11.0-beta.3` (listed there) — upstream churn, no port action. -3. Test coverage of the infi carries on the assembled baseline is limited to the files above (the - navigation-history suite's 6 files, recently-closed, close-tab-policy). The plan's broader - verification matrix (plan/prompt-pin/status-pulse suites etc.) belongs to P1/P2 per-merge gates. - -## Human decisions required - -None from P0. Pre-existing test failures (if any above) are recorded, not fixed, per plan; no product -or manifest decision was taken by this task. - -## Coordinator post-review note (2026-10-03, after review-P0.md APPROVE) - -Review non-blocking findings, dispositioned: NB-1 — `logs/p0-verify-mine-chain.sh` prints -`VERDICT: FAIL` because its predicate requires `extra == 0` instead of set-equality with the chain -length; every check line in the log is OK and the review independently confirmed the extra-commit set -is exactly the 24 assembly merges, so the written conclusions stand and the FAIL string is a script -bug, not an evidence problem. NB-2 — the feature map's "29 commits" is corrected to "31" (its own -table and git agree on 31). NB-3 — informational (rr-cache absent; already carried as a P2 note in -STATUS.md). diff --git a/fork/plans/tmad-port/evidence/P2.md b/fork/plans/tmad-port/evidence/P2.md deleted file mode 100644 index af61a9a0de1..00000000000 --- a/fork/plans/tmad-port/evidence/P2.md +++ /dev/null @@ -1,402 +0,0 @@ -# P2 report — removal proof + Stream assembly - -Worker: P2 integrator. Date: 2026-10-03. Workspace: isolated clone `/tmp/tmad-port/baseline-clone` -(own index/rerere; `origin` = `/home/ctaylor/repos/paseo`, fetch-only). Nothing pushed; the daemon on -6767 untouched; no live manifest touched; `~/.paseo-fork` untouched. Rollback exercise used copied -scratch data under `/tmp/tmad-port/rollback-home` only — never `~/.paseo`. - -**Headline: the assembly exposed one real defect.** TM-01's port of the terminal-event artifact -hook changed the source's fire-and-forget `void this.collectArtifactsForTurn(agent)` into an -`await`, which delays turn-completion waiter notification by the working-directory walk. Custom's -steer-fallback fence (the exact interaction the source comment warns about: "a steer or replace -admitted during the walk must see the run already settled") failed deterministically on the merged -tree: `agent-manager.test.ts` 209/210 → **fixed to 210/210** by restoring the source semantics -(commit `d17896891` on `tmad-with-stream`). Details in §Regression. - -## Identifiers - -| Item | Value | -| --- | --- | -| Assembly branch | `tmad-with-stream` (local to the clone) | -| Base | `tmad-port/baseline-assembly` = `2bfcd2e19638484baf1651d69dc0be55df483bcd` (the frozen P0 baseline) | -| Merged input | `intake/tmad-stream-flow` = `2197619bc4a656104e5ab5738de026e1c8353c0e` (fetched from origin; branch tip untouched) | -| Final HEAD | `d178968919e66e9bc32e5d8b9e34e389baacb343` (merge `d238504cf` + seam-fix `d17896891`) | - -`git log --oneline tmad-port/baseline-assembly..tmad-with-stream` (first two are P2's; the rest are -TM-01's nine commits arriving through the merge): - -``` -d17896891 fix(server): restore fire-and-forget artifact collection at the terminal-event seam -d238504cf merge intake/tmad-stream-flow into tmad-baseline -2197619bc docs(stream): rename the feature flag in the ported companion doc -b78389b8c refactor(stream): narrow the agent view store to chat and artifacts -cdf819820 test(stream): cover the capability-absent host gate -9edd6260d fix(stream): localize the remaining feed labels and adopt the Stream pins glossary -86d268768 fix(stream): bound pins, manual entries, and retained artifact metadata -1c1f3a196 fix(stream): surface failed pin and triage mutations instead of swallowing them -d39fc66e2 feat(stream): rename companion entry op to dotted namespace and gate on companionStreamPortV1 -717b87b18 feat(stream): apply PR19-to-#21 Stream delta through the port seams -b7672631a feat(stream): import companion Stream and artifact feed from PR #19 -``` - -`d17896891` is a local-only assembly fix (no Source-Commit trailer; it cites `51fb7693d:4012` in the -message). It is a candidate for adoption on `intake/tmad-stream-flow` — see §Regression / §Human decisions. - -## Allowed-ancestors check (with-stream assembly @ d17896891) - -| Ref → assembly HEAD | Result | Expected | -| --- | --- | --- | -| `v0.11.0-beta.3` (6166a7aca) | ancestor | YES — declared base of every input | -| `custom` (cbd1210c7) | ancestor | YES — manifest line 10, inside the baseline | -| `intake/tmad-stream-flow` (2197619bc) | ancestor | YES — the merged input | -| frozen `mine` (4cc94e07e) | NOT ancestor | NO — parallel assembly | -| source head (f0d5507d2) | NOT ancestor | NO | -| source integration (51fb7693d) | NOT ancestor | NO | - -Extra-commit set: `git rev-list tmad-with-stream --not 6166a7aca <24 frozen carry SHAs> 2197619bc` -= **exactly 26 commits** = the 24 baseline assembly merges + `d238504cf` + `d17896891`. Nothing -unknown in ancestry (`/tmp/tmad-port/logs/p2-extra-commits.txt`). - -## Files changed - -`git diff --stat tmad-port/baseline-assembly tmad-with-stream` = **53 files, +4135/−51** -(full stat: `/tmp/tmad-port/logs/p2-removal-diffstat.txt`). All 53 paths are TM-01 delta paths -(membership check vs `intake/tmad-stream-flow`'s 53-file delta: zero non-TM-01 paths; the +3 vs -TM-01's own +4132 is the seam-fix hunk, which lives in a file already in TM-01's path set). - -## Merge: conflict list with resolutions - -Exactly **one** textual conflict (the clone's rr-cache was empty, so all resolutions are fresh; -rerere recorded the tab-menu resolution during commit): - -| File | What conflicted | Resolution and why | -| --- | --- | --- | -| `packages/app/src/screens/workspace/workspace-tab-menu.ts` | Both sides added one icon to the `WorkspaceTabMenuEntry` union at the same position: baseline (custom) `+ "message-circle-plus"` (side-conversation entry), Stream `+ "file-code-2"` (View Stream/artifacts entry). | Keep **both** union members. This is the plan's predicted tab-menu seam: custom's subagent/side-conversation actions and Stream's View Stream action coexist. The auto-merge had already combined everything else in the file — both menu entries, both label keys, both input props (`onStartSideConversation`, `onViewArtifacts`) are present in the merged result. Purely additive; no custom/infi-only code needed. | - -### Clean merges inspected (both-sides-modified files) - -25 files were modified by both baseline and Stream relative to the merge base (list from -`comm` of the two delta file sets). 1 conflicted (above). The 24 auto-merged ones were each inspected -in both directions — "merged vs Stream parent" must contain only baseline-side content, "merged vs -baseline" only Stream-side content, and no deletion may remove the other side's additions. Mechanical -check: every deletion in either direction is a merge-base line (not a counterpart addition) — zero -dropped content. Semantically, key intersections: - -| File | Baseline side | Stream side | Merged result | -| --- | --- | --- | --- | -| `agent-panel.tsx`, `segmented-control.tsx`, `turn-footer.tsx` | untouched vs merge base | Stream's Chat/Stream panel, control, footer changes | Stream content applies wholesale; nothing to preserve | -| `agent-stream/view.tsx` | infi pinned-prompt, file-link path resolution | pin/Q&A callbacks, `onPin`/`onQAndA` threading | additive; dependency arrays updated correctly | -| `components/message.tsx` | infi deep-link `source` prop | pin/Q&A buttons | additive, disjoint hunks | -| `workspace-screen.tsx`, `workspace-desktop-tabs-row.tsx` | infi nav-history/recent-agents/side-conversation wiring | `onViewArtifacts` wiring + "View stream" label (`agentPanel.stream.viewStream`) | both wired; label mapping is TM-01's disclosed one | -| `protocol/messages.ts`, `agent-types.ts`, `client-capabilities.ts` | other infi-era fields | optional Stream fields, `companionStreamPortV1`, capability strings | additive; no narrowing, no new required fields | -| `client/connection/index.ts`, `daemon-client.ts` | existing capability defaults/RPCs | `companion_stream_port_v1` default, `updateCompanionEntry`/`scanAgentArtifacts` | additive | -| `server/agent/agent-manager.ts` | custom's cancel/interrupt/steer fences (rewrites of base lines) | capture seams + collector lifecycle | both present; capture after coalescer flush, history/timeline excluded; **see §Regression** | -| `server/agent/agent-storage.ts` | beta.3 schema | `artifacts`/`companionEntries` passthrough | additive | -| `authorization/operation-permissions.ts` | existing ops | 4 dotted entries (`agent.companion.update_entry.{request,response}` = workspace.write; `agent.artifacts.scan.{request,response}` = workspace.read) | verified present | -| `session.ts`, `websocket-server.ts` | custom-era changes | single `companionStreamPortV1` feature flag + dated COMPAT tags | additive | -| i18n ×9 locales | infi/custom keys | full Stream key set incl. ko | both sets present in every locale (`resources.test.ts` green) | - -## Bridge decision (TM-01B): **not needed** — with evidence - -- The only textual conflict resolves inside the assembly merge itself (icon-union superset); it - contains no code that must live on a custom/infi-dependent base. -- The one semantic fix required for custom's fence (`d17896891`) lives entirely in TM-01's own path - (`agent-manager.ts`), restores the reconciled source's own semantics (`51fb7693d:4012`), and was - **verified to compile and pass on the pure Stream branch**: the same one-hunk patch was applied to - `intake/tmad-stream-flow` (working tree only, then reverted) and `companion-stream.test.ts` 12/12, - `collector.test.ts` 3/3, `backfill.test.ts` 5/5 passed there - (`logs/p2-test-*-tm01-void.log`). It therefore does not need custom/infi code and belongs on - TM-01, not in a bridge. -- TM-01's claim "no bridge is needed" is **confirmed** by the assembly — with the one caveat that - TM-01 should absorb the seam fix (§Human decisions). - -## Regression found and fixed in assembly - -**Symptom.** After the clean merge, `npx vitest run src/server/agent/agent-manager.test.ts` → -209/210: *“does not replace a newer foreground turn after unavailable steer fallback is admitted”* -fails deterministically (single-test rerun fails too; the identical run on -`tmad-port/baseline-assembly` passes, same clone, same dist: -`logs/p2-test-agent-manager{,-baseline-run,-rerun}.log`). The steer path's next foreground start was -rejected with "Agent … already has an active run". - -**Mechanism (trace-verified, `logs/p2-test-agent-manager-trace.log`, with a temporary trace-level -test logger, reverted).** TM-01's port made `collectArtifactsForTurn` awaited inside -`dispatchSessionEvent`, between `handleStreamEvent` (run settled) and `runs.notifyWaiters` -(consumers released). The steer admission's barrier replay (a stray `turn_started`) slipped into -that new async window and was processed before the test could start turn B; its handler re-marked -the agent `running` and left a ghost tracked run (`hasTrackedRun=True`, -`activeForegroundTurnId=None`) that rejected B's start. On the baseline (no await), the same replay -lands only after B has already replaced the tracked run — harmless. - -**Source fidelity.** The reconciled source never awaits this call — `51fb7693d` line 4012: -`void this.collectArtifactsForTurn(agent);` with the comment: *"Artifact collection walks the -working directory. Never hold the turn's waiters on it: upstream settles and notifies at the -terminal event, and a steer or replace admitted during the walk must see the run already settled."* -TM-01's port changed `void` → `await` and dropped the comment (undisclosed in TM-01's seam table -and ledger, which list the hook's placement but not this delta). The fix restores source semantics -verbatim, comment included. - -**Fix.** `d17896891` (one hunk, `packages/server/src/server/agent/agent-manager.ts`): `await` → -`void` + source comment. Green after fix: agent-manager 210/210, steer test rerun pass, companion 12, -collector 3, backfill 5, authorization 7, all app/protocol suites re-run green (§Results). -Build/typecheck/lint re-run green. - -## Source → port ledger (P2 rows) - -P2 ports no new files. One row for the assembly correction: - -| Source path | Source blob (51fb7693d) | Local blob (d17896891) | Disposition | -| --- | --- | --- | --- | -| packages/server/src/server/agent/agent-manager.ts | c40f776a64f362376aa29e550843cc9c2ff2a661 | df9bf4c175d76b3e1b16eb7c9028dd4ccb064e35 | adapted (assembly) — terminal-event artifact hook restored to source `void` semantics + comment; TM-01's blob at 2197619bc is 787d73e63551c2f3679d6d580567b37a47730ba2 (holds `await`); baseline blob c9c78d920f33ebbd306a1ec70de97f9c77897b4f (no hook at all). Rationale: custom's steer fence requires the source's fire-and-forget placement. | - -## Removal proof (brief step 3) - -Removal assembly = `tmad-port/baseline-assembly` itself (Stream lines absent is the baseline's -definition here — Stream was appended, not interwoven). - -1. `git diff --stat tmad-port/baseline-assembly tmad-port/baseline-assembly` → **empty** (exit 0). - Removing the Stream manifest line yields exactly the frozen baseline tree. -2. `git diff tmad-port/baseline-assembly tmad-with-stream --stat` → 53 files, +4135/−51 — - **only TM-01 paths** (membership check: zero non-TM-01 paths). No bridge line exists. -3. Stream-free baseline greps clean: - `git grep -E 'companion-stream|AgentArtifact|companionEntries|companionStreamPortV1' tmad-port/baseline-assembly -- 'packages/**'` - → **0 hits** (including tests). Control: the same grep on `tmad-with-stream` hits the expected - Stream files. No compile-time import and no runtime call into Stream survives removal. - -## Build/typecheck/lint and test results — with vs without (brief step 2) - -Gates (never a full suite; focused files only, serially): - -| Command | P0 baseline (2bfcd2e19) | With-stream (d17896891) | -| --- | --- | --- | -| `npm run build:server` | PASS (`p0-build-server.log`) | PASS (`p2-build-server.log`; re-run PASS post-fix `p2-build-server-postfix.log`) | -| `npm run typecheck` | PASS | FAIL before dist rebuild (stale protocol/client `dist` — cross-package declarations, see note), PASS after rebuild (`p2-typecheck.log`); PASS post-fix (`p2-typecheck-postfix.log`) | -| `npm run lint` (full) | PASS (0/0, 4589 files) | PASS (0/0, 4604 files; +15 = Stream's new files) (`p2-lint.log`) | - -Note on the stale-dist typecheck failure: the first pre-commit typecheck failed with -"Cannot find module '@getpaseo/protocol/companion-stream'" / "no exported member 'AgentArtifact'" / -"not on type DaemonClient" across app/server/cli — the consuming packages resolving Stream's new -protocol/client exports through `dist/` built at the baseline. `npm run build:server` on the merged -tree cleared it; the merge was then committed with the pre-commit hook green -(`p2-merge-commit.log`). This is the documented cross-package rebuild requirement, not a merge defect. - -Focused tests — all run individually with `npx vitest run --bail=1` from the owning package: - -| Test file | Area | P0 baseline | With-stream (final tree) | Log | -| --- | --- | --- | --- | --- | -| `server: src/server/agent/companion-stream.test.ts` | Stream model/bounds | n/a (new) | **PASS 12/12** | `p2-test-companion-stream-postfix.log` | -| `server: src/server/agent/artifacts/collector.test.ts` | Stream collector cap | n/a (new) | **PASS 3/3** | `p2-test-collector-postfix.log` | -| `server: src/server/agent/artifacts/backfill.test.ts` | Stream backfill | n/a (new) | **PASS 5/5** | `p2-test-backfill-postfix.log` | -| `protocol: src/messages.artifacts.test.ts` | Stream wire | n/a (new) | **PASS 1/1** | `p2-test-messages.artifacts-postfix.log` | -| `protocol: src/messages.companion-update-entry.test.ts` | renamed RPC pair | n/a (new) | **PASS 5/5** | `p2-test-messages.companion-update-entry-postfix.log` | -| `app: src/companion-stream/model.test.ts` | Stream feed model | n/a (new) | **PASS 2/2** | `p2-test-companion-stream-model-postfix.log` | -| `app: src/runtime/host-features.test.ts` | capability-absent gate | n/a (new) | **PASS 3/3** | `p2-test-runtime-host-features-postfix.log` | -| `app: src/i18n/resources.test.ts` | locale parity | n/a | **PASS 37/37** (TM-01 alone reported 36; the parity test enumerates one more key group on the assembled tree — informational, green) | `p2-test-i18n-resources-postfix.log` | -| `server: src/server/authorization/index.test.ts` | authorization maps | **PASS 7/7** | **PASS 7/7** | `p2-test-index-postfix.log` | -| `server: src/server/agent/agent-manager.test.ts` | custom ACP/GJC + steer fences | **PASS 210/210** | pre-fix **FAIL 209/210** (§Regression); post-fix **PASS 210/210** | `p2-test-agent-manager{,-postfix}.log` | -| `app: src/composer/submit.test.ts` | composer submit | **PASS 6/6** | **PASS 6/6** | `p2-test-composer-submit-postfix.log` | -| `app: src/navigation/history/model.test.ts` | infi nav-history | **PASS 56/56** | **PASS 56/56** | `p2-test-navigation-history-model-postfix.log` | -| `app: src/navigation/history/record-location.test.ts` | infi nav-history | **PASS 4/4** | **PASS 4/4** | `p2-test-navigation-history-record-location-postfix.log` | -| `app: src/navigation/history/recorder.test.tsx` | infi nav-history | **PASS 9/9** | **PASS 9/9** | `p2-test-navigation-history-recorder-postfix.log` | -| `app: src/navigation/history/replay.test.ts` | infi nav-history | **PASS 10/10** | **PASS 10/10** | `p2-test-navigation-history-replay-postfix.log` | -| `app: src/navigation/history/select-active-tab.test.ts` | infi nav-history | **PASS 5/5** | **PASS 5/5** | `p2-test-navigation-history-select-active-tab-postfix.log` | -| `app: src/navigation/history/store.test.ts` | infi nav-history | **PASS 6/6** | **PASS 6/6** | `p2-test-navigation-history-store-postfix.log` | -| `app: src/workspace-tabs/recently-closed.test.ts` | infi recent agents | **PASS 4/4** | **PASS 4/4** | `p2-test-workspace-tabs-recently-closed-postfix.log` | -| `app: src/subagents/close-tab-policy.test.ts` | subagent tab close | **PASS 3/3** | **PASS 3/3** | `p2-test-subagents-close-tab-policy-postfix.log` | -| `app: src/agent-stream/pinned-prompt/model.test.ts` | IP-11 pinned prompt | not run at P0 | **PASS 6/6** | `p2-test-agent-stream-pinned-prompt-model-postfix.log` | -| `app: src/side-conversations/store.test.ts` | side conversations | not run at P0 | **PASS 10/10** | `p2-test-side-conversations-store-postfix.log` | -| `app: src/side-conversations/routing.test.ts` | side conversations | not run at P0 | **PASS 2/2** | `p2-test-side-conversations-routing-postfix.log` | -| `app: src/panels/side-conversation-panel-state.test.ts` | side conversations | not run at P0 | **PASS 5/5** | `p2-test-panels-side-conversation-panel-state-postfix.log` | - -Totals on the final with-stream tree: 23 files, **201 + 210 = 411 tests, 0 failures.** All P0-baseline -rows reproduce their P0 results; all Stream rows pass; the one regression found is fixed and its fix -is proven on the pure Stream branch too. - -## Persisted-data rollback exercise (brief step 4) - -Copied scratch home `/tmp/tmad-port/rollback-home` (never `~/.paseo`). Script: -`rollback-demo.mts` run via the repo's tsx against the checked-out tree per phase — canonical copy -`/tmp/tmad-port/logs/p2-rollback-demo.ts.txt`. The script uses the real `AgentStorage` -(`parseStoredAgentRecord` at load, atomic record rewrite on upsert), so the strip/restore is the -actual production code path, not a simulation of it. - -Transcript (also `logs/p2-rollback-{1..4}-*.log`): - -``` -[with-stream: ROLLBACK_PHASE=write] -[write] wrote 2 records via WITH-STREAM AgentStorage -[write] rb-agent-0001 keys: id, provider, cwd, createdAt, updatedAt, title, config, persistence, - lastStatus, labels, companionEntries, artifacts -[write] rb-agent-0001 companionEntries: 2 artifacts: 1 - -[with-stream: ROLLBACK_PHASE=export] -[export] backed up records to /tmp/tmad-port/rollback-home/backup -[export] Stream fields for 1 agent(s) -> /tmp/tmad-port/rollback-home/stream-export.json -{ "rb-agent-0001": { "companionEntries": [ {pin …}, {q_and_a …} ], "artifacts": [ … ] } } - -[baseline: ROLLBACK_PHASE=strip] -[strip] BASELINE load of rb-agent-0001: companionEntries present in file: true - | after parse, present on record: false -[strip] rb-agent-0001 keys after baseline rewrite: id, provider, cwd, createdAt, updatedAt, title, - labels, lastStatus, config, persistence -[strip] DATA LOSS CONFIRMED: companionEntries present: false | artifacts present: false - | title now: "Renamed while Stream was disabled" -[strip] rb-agent-0002 (control) untouched by stripping: companionEntries present: false - -[with-stream: ROLLBACK_PHASE=restore] -[restore] merged Stream fields into rb-agent-0001 -[restore] rb-agent-0001 title after restore: "Renamed while Stream was disabled" - (newer non-Stream metadata preserved) -[restore] rb-agent-0001 companionEntries restored: 2 | artifacts restored: 1 -[restore] round-trips through WITH-STREAM schema: true -``` - -Confirmed per plan P2.4: beta.3's plain `z.object` record schema strips `companionEntries`/`artifacts` -at parse and the next ordinary rewrite persists the loss (expected feature-removal data loss; no -generic-storage change made). The backup/export + restore-only-Stream-fields procedure is written to -**`/tmp/tmad-port/stream-rollback.md`**: export per agent ID before disabling, restore merges only -Stream fields onto the CURRENT record after re-enabling (newer non-Stream metadata — demonstrated -with a title rename from the disabled window — is preserved; deleted agents skipped; record -round-trips the with-stream schema). - -## Proposed manifest append block (brief step 5) - -Nothing live was touched. Block consistent with STATUS.md's draft, updated with this assembly's -result: - -```text -# Existing community, custom and infi lines retain their current order. APPEND BELOW THEM. -intake/tmad-stream-flow # TM-01 2197619bc (+ steer-fence seam fix — adopt d17896891's one-hunk - # fix upstream and refresh this SHA before promotion); source snapshot - # 51fb7693d reconciled; base v0.11.0-beta.3; removal group Stream; - # assembly-verified P2: no bridge needed (TM-01B stays uncreated). -intake/tmad-message-queue # TM-02 91392d6be; custom floor cbd1210c7 (recorded); removal group Queue+Voice (with TM-03/TM-04 when they land). -intake/tmad-native-find # TM-07 5f3634ad4; source snapshot 51fb7693d; base v0.11.0-beta.3; removal group Native Find (independent of Stream and queue). -# TM-03 (intake/tmad-queue-ui, base TM-02) and TM-04 (intake/tmad-voice-flow, base TM-02) lines are added -# in dependency order only after their own gates; voice device evidence is a promotion gate. -``` - -Until the seam fix is adopted on `intake/tmad-stream-flow`, an assembly from the manifest lines -alone reproduces the steer-fence regression unless the assembler replays `d17896891`'s resolution; -the assembly branch `tmad-with-stream` (d17896891) is the reference resolution. - -## Commands run (summary; full paths under /tmp/tmad-port/logs/) - -| Command | Result | -| --- | --- | -| `npm run build:server` (merge tree; post-fix) | PASS / PASS | -| `npm run typecheck` (merge tree post-rebuild; post-fix) | PASS / PASS | -| `npm run lint` (full) + `npm run lint -- ` scoped | PASS (0 warnings, 0 errors, 4604 files) | -| `npm run format:files -- ` before each commit | PASS | -| `git merge --no-ff intake/tmad-stream-flow` | 1 conflict, resolved + committed `d238504cf` (pre-commit hook green) | -| focused vitest runs (23 files, individually, serially) | all green post-fix; agent-manager 209/210 pre-fix (§Regression) | -| removal proofs (diff-stat, membership, greps) | all PASS | -| rollback demo (4 phases) | PASS (§Transcript) | - -## Pre-existing failures - -None observed on the baseline (P0's focused set was green and every P0 row reproduced green here). -The single with-stream failure was merge-induced and is fixed; pre-fix evidence preserved -(`p2-test-agent-manager.log`, `p2-test-agent-manager-rerun.log`). - -## Known gaps / deferred - -1. **UI capture evidence** (matched source/port desktop + compact browser, native captures, locale - screenshots) remains deferred per P1 step 6 — unchanged by P2; still owed before promotion. -2. TM-01's two informational decisions ("Queue" tab label; pin/artifact ceilings 100/200) remain - open product choices, unchanged by P2. -3. The seam-fix adoption on `intake/tmad-stream-flow` is pending (§Human decisions). TM-01's ledger - should also record the `void`-vs-`await` delta as an explicit adaptation row once adopted. -4. The i18n resources test enumerates 37 cases on the assembled tree vs 36 on the Stream branch - alone — informational only, both green. - -## Human decisions required - -1. **Adopt the seam fix upstream.** Recommend the TM-01 owner apply `d17896891`'s one-hunk change - (source-faithful, proven green on beta.3 alone) to `intake/tmad-stream-flow` and refresh the - manifest line's SHA; alternatively record `tmad-with-stream`'s resolution as the required - assembly step. I did not modify the reviewed TM-01 branch. -2. TM-01's informational items (Queue tab label; ceilings) remain the user's call, as flagged at P1. - -## State at handoff - -- Clone on `tmad-with-stream` @ `d17896891`, working tree clean; `intake/tmad-stream-flow` - unmodified at `2197619bc`; nothing pushed anywhere; no daemon, live manifest, or `~/.paseo-fork` - contact; rerere holds the tab-menu resolution for future assemblies. -- Evidence files: this report; `/tmp/tmad-port/stream-rollback.md`; - `/tmp/tmad-port/logs/p2-*` (builds, typecheck, lint, 30+ test logs incl. pre/post-fix and the - baseline control run, merge-commit hook log, trace log, removal diffstat, extra-commit list, - rollback phases + script copy). - -## Addendum 2 (assembly rebuild, 2026-10-03) - -The TM-01 owner applied the seam fix upstream: `intake/tmad-stream-flow` moved `2197619bc` → -`a8241e53530d6bd0a958971118d6b8b57ff80b0c` (commit "fix(server): restore fire-and-forget artifact -collection at the terminal-event seam" — the `d17896891` hunk and message cherry-picked onto -`2197619bc`; delta reviewed in `/tmp/tmad-port/evidence/review-TM-01-delta.md`). The assembly was -rebuilt so the manifest SHA is final. - -### New identifiers - -| Item | Value | -| --- | --- | -| Assembly branch | `tmad-with-stream` (recreated; old instance at `d17896891` deleted after verification) | -| Base | `tmad-port/baseline-assembly` = `2bfcd2e19` (unchanged) | -| Merged input | `intake/tmad-stream-flow` = `a8241e53530d6bd0a958971118d6b8b57ff80b0c` | -| **New merge SHA** | **`0ff83cbc5e31f4ec16e4b28c0694230c4a83debd`** | -| Commits on assembly | 11 = merge + TM-01's 10 (9 original + `a8241e535`). **No extra assembly commit.** | - -### Rebuild notes - -- Single textual conflict again, same hunk (tab-menu icon union). rerere replayed the recorded - resolution ("Resolved … using previous resolution"); inspected before keeping per the plan's rerere - rule: no markers, both `message-circle-plus` and `file-code-2` in the union, both label keys - (`newSideConversation`, `viewArtifacts`) and both menu entries present — identical to the P2 - resolution. Accepted via `git add`. -- Merge committed with the pre-commit hook green (format/lint/typecheck across all workspaces, - `logs/p2b-merge-commit.log`). - -### Redundancy proof — the separate assembly fix is gone and nothing is lost - -1. **Tree equality with the verified old assembly:** `git diff d17896891 0ff83cbc5` → **empty** - (exit 0). The rebuilt tree is byte-identical to the tree that passed the full P2 battery; only - the graph changed (the fix now arrives inside the merged branch instead of a follow-up commit). -2. **Steer-fence passes with NO extra commit:** on `0ff83cbc5` as merged (nothing added), - `agent-manager.test.ts` → **210/210** including "does not replace a newer foreground turn after - unavailable steer fallback is admitted" (isolated rerun also green) — `logs/p2b-test-*.log`. -3. **Ancestry re-checked:** base `6166a7aca`, `custom`, and `a8241e535` ancestors; - `mine`/source-head/`51fb7693d` NOT ancestors. Extra-commit set - (`rev-list 0ff83cbc5 --not base <24 carries> a8241e535`) = **25** = the 24 baseline merges + the - new merge — nothing unknown. -4. **Removal proof unchanged:** `git diff tmad-port/baseline-assembly 0ff83cbc5 --name-only` = 53 - files, membership check → zero non-TM-01 paths. - -### Gates and seam-critical tests (final tree `0ff83cbc5`; logs `logs/p2b-*.log`) - -| Command / test | Result | -| --- | --- | -| `npm run build:server` | **PASS** (`p2b-build-server.log`) | -| `npm run typecheck` | **PASS** (`p2b-typecheck.log`) | -| `npm run lint` | **PASS** (0 warnings, 0 errors, 4604 files) (`p2b-lint.log`) | -| `server: agent-manager.test.ts` | **PASS 210/210** (`p2b-test-agent-agent-manager.log`) | -| `server: agent-manager.test.ts` steer-fallback case (isolated) | **PASS 1/1** (`p2b-test-steer-single.log`) | -| `server: companion-stream.test.ts` | **PASS 12/12** (`p2b-test-agent-companion-stream.log`) | -| `server: artifacts/collector.test.ts` | **PASS 3/3** (`p2b-test-agent-artifacts-collector.log`) | -| `server: authorization/index.test.ts` | **PASS 7/7** (`p2b-test-authorization-index.log`) | - -(Other suites were not re-run: the rebuilt tree is byte-identical to the tree on which every one of -them passed in the original P2 battery — see redundancy proof (1).) - -### FINAL proposed manifest append block - -```text -# Existing community, custom and infi lines retain their current order. APPEND BELOW THEM. -intake/tmad-stream-flow # TM-01 a8241e53530d6bd0a958971118d6b8b57ff80b0c (2197619bc + steer-fence seam fix a8241e535, delta-reviewed); source snapshot 51fb7693d reconciled; base v0.11.0-beta.3; removal group Stream; assembly-verified P2/P2b: no bridge needed (TM-01B uncreated). -intake/tmad-message-queue # TM-02 91392d6be; custom floor cbd1210c7 (recorded); removal group Queue+Voice (with TM-03/TM-04 when they land). -intake/tmad-native-find # TM-07 5f3634ad4; source snapshot 51fb7693d; base v0.11.0-beta.3; removal group Native Find (independent of Stream and queue). -# TM-03 (intake/tmad-queue-ui, base TM-02) and TM-04 (intake/tmad-voice-flow, base TM-02) lines are added -# in dependency order only after their own gates; voice device evidence is a promotion gate. -``` - -State: clone clean on `tmad-with-stream` @ `0ff83cbc5`; `intake/tmad-stream-flow` = `a8241e535` -(fetched, not modified here); nothing pushed; no live manifest, daemon, or `~/.paseo*` contact. diff --git a/fork/plans/tmad-port/evidence/P6-assembly-2026-10-08.md b/fork/plans/tmad-port/evidence/P6-assembly-2026-10-08.md deleted file mode 100644 index 33233475318..00000000000 --- a/fork/plans/tmad-port/evidence/P6-assembly-2026-10-08.md +++ /dev/null @@ -1,149 +0,0 @@ -# P6 — final local assembly and build readiness - -Date: 2026-10-08. Worktree: `/home/ctaylor/.paseo/worktrees/3rzqjhby/tmad-build-readiness`, branch `build/tmad-readiness-2026-10-08`. Frozen P0 input: `2bfcd2e19638484baf1651d69dc0be55df483bcd`. No live manifest/config edits, no daemon restart, and no push. The raw TM-04 voice WIP `6ab56eba1` was not merged. - -## Approved basket and exact local history - -| Input | Approved SHA | Assembly commit | Parents / disposition | -| --- | --- | --- | --- | -| TM-01 Stream | `a8241e53530d6bd0a958971118d6b8b57ff80b0c` | `e7c7a83d2858d2e0290f8427a6d08016b0f71154` | P0 + Stream; 53 changed paths exactly match the approved Stream delta. | -| TM-02 queue daemon | `91392d6beed3fc49f9be7496a70b8d5822957d4c` | `78cecda43ba101218261375baeb951ea552e4c52` | Stream assembly + queue daemon; clean merge. First-parent delta exactly matches the approved branch delta from `cbd1210c7`. | -| TM-07 Native Find | `5f3634ad43256c18f9f41667348c65fe1b03d7f4` | `396628601d022ff143e253c2509ecc0f401a1582` | Queue assembly + Native Find; four overlap files resolved by union. | -| TM-03 queue UI | `9ab91bb759be1951bdaa9cbe7bc991cafed2569d` | `9e359ef03c7db4fe2c6a1e5a91af3315a9c9bb16` | Native Find assembly + queue UI; clean merge. Its 24 first-parent paths exactly match the approved UI delta from TM-02. | -| Test harness integration fix | — | `e423a8666a30075a584f4a8e6f646a28054e6af0` | Adds the in-memory AsyncStorage stub to the modified session-store suite. | - -Current frozen-basket worktree HEAD: `e423a8666a30075a584f4a8e6f646a28054e6af0`. The merge path lists are `/tmp/tmad-port/logs/p6-stream-{source,assembly}-paths.txt` and `/tmp/tmad-port/logs/p6-queue-ui-{source,assembly}-paths.txt`; `diff -u` returned empty for each pair. - -### Semantic merge review - -- Stream adds its artifacts action and the baseline side-conversation action independently. Their menu keys, labels, callbacks, and icons remain distinct. -- Queue daemon adds optional, dotted `agent.queue.*` calls and capability-gated updates. The legacy send path and typed-send behavior remain unchanged. -- Native Find conflicts were in the desktop tab row, mobile tab/screen plumbing, tab menu, and agent view store. Both artifacts and Find actions remain independently wired; `selectedViews` and `findOpen` keep separate state. The mobile menu emits one separator after its last optional item, while retaining the existing single-feature entries. -- Queue UI auto-merged. Review of the merged composer, session store, and client confirmed that snapshots remain revision-guarded; outbox writes precede enqueue requests; failed pending items remain visible; edits/removals/reorders carry the revision; and no typed-send-default change was introduced. - -The Native Find conflict resolution rationale is preserved in [the durable conflict log](P6-conflict-resolution-log-2026-10-08.md), with scoped check logs listed below. The isolated current-custom rehearsal repeated these feature unions separately. - -## Build, typecheck, lint, and focused tests - -Commands ran serially. `build:server`, root `typecheck`, and root `lint` passed after the full basket was assembled. The session-store suite initially surfaced six unhandled `window is not defined` rejections because the new outbox store used the real native AsyncStorage in this Node test. Adding the repository-standard in-memory AsyncStorage mock fixed the harness; all 28 assertions then passed without unhandled errors. This changed only the existing test file. - -| Command | Result | Raw output | -| --- | --- | --- | -| `npm run build:server` | PASS | `/tmp/tmad-port/logs/p6-build-server-full-basket.log` | -| `npm run typecheck` after build | PASS, all workspaces | `/tmp/tmad-port/logs/p6-typecheck-full-basket.log` | -| `npm run lint` after build | PASS, zero warnings/errors | `/tmp/tmad-port/logs/p6-lint-full-basket.log` | -| `npm run typecheck` after test harness fix | PASS | `/tmp/tmad-port/logs/p6-typecheck-after-session-test-fix.log` | -| `npm run lint` final | PASS, zero warnings/errors | `/tmp/tmad-port/logs/p6-lint-final-basket.log` | -| `npm run format:files -- ` | PASS | `/tmp/tmad-port/logs/p6-format-native-find-final.log` | -| `npm run lint -- ` | PASS, zero warnings/errors | `/tmp/tmad-port/logs/p6-lint-native-find-final.log` | -| `npm run typecheck --workspace=@getpaseo/app` | PASS | `/tmp/tmad-port/logs/p6-typecheck-app-native-find.log` | -| `npm run format:files -- packages/app/src/stores/session-store.test.ts` | PASS | `/tmp/tmad-port/logs/p6-format-session-test-fix.log` | -| `npm run lint -- packages/app/src/stores/session-store.test.ts` | PASS | `/tmp/tmad-port/logs/p6-lint-session-test-fix.log` | -| `npx vitest run packages/app/src/agent-stream/chat-find/matches.test.ts --bail=1` | PASS | `/tmp/tmad-port/logs/p6-test-packages-app-src-agent-stream-chat-find-matches-test-ts.log` | -| `npx vitest run packages/app/src/agent-stream/chat-find/native-viewport.test.ts --bail=1` | PASS | `/tmp/tmad-port/logs/p6-test-packages-app-src-agent-stream-chat-find-native-viewport-test-ts.log` | -| `npx vitest run packages/app/src/screens/workspace/workspace-tab-trailing-accessory.test.tsx --bail=1` | PASS | `/tmp/tmad-port/logs/p6-test-packages-app-src-screens-workspace-workspace-tab-trailing-accessory-test-tsx.log` | -| `npx vitest run packages/app/src/composer/actions.test.ts --bail=1` | PASS | `/tmp/tmad-port/logs/p6-test-packages-app-src-composer-actions-test-ts.log` | -| `npx vitest run packages/app/src/composer/queue-sync.test.ts --bail=1` | PASS | `/tmp/tmad-port/logs/p6-test-packages-app-src-composer-queue-sync-test-ts.log` | -| `npx vitest run packages/app/src/stores/queue-outbox-store/model.test.ts --bail=1` | PASS | `/tmp/tmad-port/logs/p6-test-packages-app-src-stores-queue-outbox-store-model-test-ts.log` | -| `npx vitest run packages/app/src/stores/session-store.test.ts --bail=1` after mock | PASS, 28 tests | `/tmp/tmad-port/logs/p6-test-session-store-rerun.log` | - -No full test suite was run. TM-01/P2 daemon/protocol tests remain covered by their already-approved branch evidence and were not repeated because server/protocol assembly introduced no overlap edits. - -The reported CLI `TS7006` errors were not patched. The first incomplete-stack check showed declaration-resolution errors; after the completed `build:server`, this frozen basket's full typecheck passed. The separate controlled investigation at current custom `24f134618` also reports that rebuilding the owning stack restores type inference without source edits: `fork/plans/tmad-port/evidence/pluto-cli-typecheck-2026-10-08.md`. - -## Feature-removal and copied-data checks - -### Native Find with and without Stream - -- Without Stream, approved TM-07 is based directly on beta.3 `6166a7aca5e3184e8ab505caad28f6a595816414`; its approved evidence records the Stream/companion grep as empty, and its focused tests plus full typecheck passed. This is `/home/ctaylor/.paseo/worktrees/3rzqjhby/tmad-port-coordination/fork/plans/tmad-port/evidence/TM-07.md`. -- With Stream and without either queue layer, the separate frozen P0 + Stream + Native Find tree is commit `97612a458f067b0cf32fe282e2aba1ec9f242293` (parents `e7c7a83d2` + `5f3634ad4`). It contains Stream and Find paths, has no `durableAgentQueueV1` or `agent.queue.*` references, and contains no server queue service or app queue outbox paths. `git grep` output: `/tmp/tmad-port/logs/p6-no-queue-grep.txt` (0 matches). This confirms queue/UI removal does not remove Stream or Native Find. The tree is structural evidence; no extra package install/build was run in that temporary worktree. -- On the integrated Stream + Native Find + queue basket, Native Find tests and app typecheck passed above. - -### Queue removal and copied-data runtime proof - -The source/storage evidence and runtime evidence are separate: - -- **Source/storage:** /tmp/tmad-port/noqueue-full-custom is the queue-free/voice-free rehearsal from P0 + Stream + Native Find, then exact current custom 24f134618cd8a7143615debf927c1ac60b9ba813 and side repair fddb4fa8587ae377286ffbea3137df4c53bdc7a9. Merge commits: cf4e8beae... and 365cd7a1c17d8e1511d2a5cd59a13417598edaf3. Its built tree has no Queue/Voice feature layer while preserving P0 carries, Stream, Find, current custom, and the side-conversation repair. Earlier P0 + Stream + Find structural grep remains /tmp/tmad-port/logs/p6-no-queue-grep.txt. -- **Queue-free runtime:** an in-process fake Codex provider harness activated against copied home /tmp/tmad-port/queue-runtime-custom-copy; the pending record was pending-copy-1. The queue-free runtime created an idle fake agent and ran for 1.5 seconds. SHA-256 was eb0fbafe6d8e339f6bf3d8fdc2f206328935e0405d570827560a6ec3a68b2ae3 before, while active, and after shutdown; provider queued turns: 0. Result: /tmp/tmad-port/logs/p6-noqueue-custom-runtime.log. -- **Final enabled runtime:** full current-custom basket, with approved Voice integrated, was started in-process against the same copied home /tmp/tmad-port/queue-runtime-custom-copy used by the queue-free phase. Queue list returned revision 1 and pending-copy-1; file hash stayed the same before/during/after shutdown; provider queued turns: 0. Result: /tmp/tmad-port/logs/p6-final-enabled-runtime.log. -- Both runs used only copied test data, ephemeral loopback listeners, fake providers, and createTestPaseoDaemon; no main daemon/service or user data was involved. - -The first enabled Voice runtime attempt exposed a real integration fault: bootstrap supplied its own MessageReceipts, then WebSocket startup tried to inject the shared owner into AgentQueueService and rejected the second instance. The assemblies now construct the queue without a second receipt owner, allowing WebSocket startup to inject the single shared owner before queue activation. This is an explicit integration delta in both final Voice trees, committed as 0169f9a839fcdc01d4df04da02872ef3167c6dc9 and 9584b2a669ce90a5df8c9eac66073e85124e90bb. The final enabled runtime proof above passes after this correction. - -The copied-data proof establishes dormant pending-state preservation and recovery only. Zero fake-provider turns means provider dispatch was not exercised. It does not prove provider credential behavior, voice-device capture/playback, or live-home migration. - -### Stream copied-data rollback - -Stream-only removal and copied-data backup/export/strip/restore were already approved against P0 in P2, including preservation of non-Stream fields across restore. See `/home/ctaylor/.paseo/worktrees/3rzqjhby/tmad-port-coordination/fork/plans/tmad-port/evidence/P2.md`, `review-P2.md`, and `stream-rollback.md`; this assembly did not change those storage seams. - -## Reviewed Voice and complete current-custom rehearsal - -The required Pi/OpenCode Go Muse review approved TM-04 exact SHA 84f11381ceabec13d5deaff6c1e2c05dc67a6c62 (/tmp/tmad-port/evidence/review-TM-04.md). Raw WIP 6ab56eba1 remains excluded. Voice was merged last in two separate baskets: - -| Basket | Exact feature/history sequence | Final assembly HEAD | -| --- | --- | --- | -| Frozen P6 | P6 checkpoint e423a8666a30075a584f4a8e6f646a28054e6af0 → approved Voice merge af9c9839a3a14c2bba1d40cd6a47703d773abb00 → shared-receipt startup fix | 0169f9a839fcdc01d4df04da02872ef3167c6dc9 | -| Full current custom | P6 e423... → current custom merge 505595ab2f8c6c0261d5e56c5468932cfd07bcb6 (exact 24f134618cd8a7143615debf927c1ac60b9ba813) → side repair merge 348e5b988b2ea9a866139b63033ebaaebbe97350 (exact fddb4fa8587ae377286ffbea3137df4c53bdc7a9) → approved Voice merge 6e9fab67399c2a3300cc68389158af0383e079e4 (exact 84f11381ceabec13d5deaff6c1e2c05dc67a6c62) → shared-receipt startup fix | 9584b2a669ce90a5df8c9eac66073e85124e90bb | - -The full custom basket retains P0 2bfcd2e19638484baf1651d69dc0be55df483bcd and both already-established external/infi carries, as well as all four reviewed TM features. The frozen basket retains its prior e423... four-feature checkpoint. The current-custom delta does not change typed-send defaults. - -### Integration deltas and overlap decisions - -- The merge surfaced a duplicate Voice-era listQueuedAgentMessages method and duplicate AgentQueueSnapshot import beside TM-02's namespaced durable queue client API. The redundant legacy flat-RPC method/import were removed; Voice consumes the existing namespaced queue API. The capability hello test expectation now explicitly includes Stream companion port, durable queue, and durable voice capabilities. -- Git conflicted in packages/app/src/composer/index.tsx in both Voice merges. The resolution was additive and retains the Queue selectors (supportsDurableQueue, snapshot, and failed outbox entries) and Voice capability (supportsVoiceConcurrentInput). No feature behavior was dropped. -- session.ts auto-merged the two approved changes. In the full basket, side-conversation demand still comes from capable attached sources, update/removed events are sent only to each capable source, and the no-source fallback remains demand-gated. Voice attachment ownership/generation checks and receipt filtering by voiceOwner remain intact. Full, unfiltered session tests pass; the side-conversation manager event test is not skipped. -- Voice and Queue initially failed in runtime because bootstrap passed a second receipt owner. The explicit fix removes bootstrap's separate MessageReceipts; the WebSocket server installs the shared receipt owner before agentQueueService.activate(). This preserves queue delivery receipts and makes them readable by Voice through the same store. It is committed in each assembly as listed above. -- The Pi/OpenCode Go Muse review notes voiceOwner is optional in the type although the current caller always supplies it. This was nonblocking; no scope was added. -- The session-store AsyncStorage test fix remains intact as its own explicit earlier integration commit e423a8666a30075a584f4a8e6f646a28054e6af0; its test file blob is 9a89a34f6b8b3b61fcd91e1a23c0f7c99f44d5df. Both final Voice trees contain that exact blob unchanged. The reviewed intake SHAs themselves were not edited. - -### Final Voice assembly build and test results - -All long commands were serialized and captured to files. npm ci was run separately in each Voice rehearsal; node_modules are not linked across worktrees. - -| Assembly / command | Result | Raw output | -| --- | --- | --- | -| Frozen P6 + Voice: npm run build:server | PASS | /tmp/tmad-port/logs/p6-frozen-voice-build-server.log | -| Frozen P6 + Voice: npm run build:app-deps | PASS | /tmp/tmad-port/logs/p6-frozen-voice-build-app-deps.log | -| Frozen P6 + Voice: root npm run typecheck | PASS | /tmp/tmad-port/logs/p6-frozen-voice-typecheck.log | -| Frozen P6 + Voice: root npm run lint | PASS, zero warnings/errors | /tmp/tmad-port/logs/p6-frozen-voice-lint.log | -| Frozen Voice app: composer state, voice runtime, session store tests | PASS, 76 tests | /tmp/tmad-port/logs/p6-frozen-voice-app-tests.log | -| Frozen Voice client/server focused set | 215 passed, 1 platform-skipped, and the known side conversation manager events reach every capable client test failed because this frozen basket omits the separate approved side repair | /tmp/tmad-port/logs/p6-frozen-voice-client-server-tests.log | -| Full custom + side repair + Voice: npm run build:server | PASS | /tmp/tmad-port/logs/p6-full-custom-voice-build-server.log | -| Full custom + side repair + Voice: npm run build:app-deps | PASS | /tmp/tmad-port/logs/p6-full-custom-voice-build-app-deps.log | -| Full custom + side repair + Voice: root npm run typecheck | PASS | /tmp/tmad-port/logs/p6-full-custom-voice-typecheck.log | -| Full custom + side repair + Voice: root npm run lint | PASS, zero warnings/errors | /tmp/tmad-port/logs/p6-full-custom-voice-lint.log | -| Full client, queue service, receipts, and unfiltered session tests | PASS, 373 tests across four files | /tmp/tmad-port/logs/p6-full-custom-voice-client-server-tests.log | -| Full composer state, voice runtime, session-store tests | PASS, 76 tests across three files | /tmp/tmad-port/logs/p6-full-custom-voice-app-tests.log | - -Both assembly-only startup-fix commits also passed their pre-commit format, lint, and root typecheck hooks. No full test suite was run. Worker-approved unchanged tests were not repeated. P0 carry tests and other already-green worker evidence remain trusted. - -The queue-free current-custom removal rehearsal builds the owning server stack (/tmp/tmad-port/logs/p6-noqueue-custom-build-server.log) and passes runtime preservation, but root typecheck/lint were not run on that removal-only tree. The queue-free P0 + Stream + Find check logs remain /tmp/tmad-port/logs/p6-noqueue-build-server.log, /tmp/tmad-port/logs/p6-noqueue-typecheck.log, and /tmp/tmad-port/logs/p6-noqueue-lint.log. - -## Human/platform evidence still open - -- Stream: matched desktop/compact-web and native captures, Korean locale review, and the recorded label/retention-limit decisions. -- Native Find: the 10-point iOS/Android device pass recorded in TM-07 (historical reveal, wrap-around, cleanup, old-host behavior, keyboard/rotation, locales). -- Queue UI: browser/native dev-app captures for badges, row menu, and failed overlay. -- Queue daemon: provider-credential E2E remains unavailable; TM-03's approved fake-provider two-client E2E covers daemon behavior. -- Voice device capture/playback, real-provider credentials, provider E2E, and live-home migration remain open. The copied-data queue-free/final-enabled runtime gate passed in isolated fake-provider daemons. - -## Final review and durable audit boundary - -Final integration review is **APPROVED**, assigned to Pi/OpenCode Go Muse -`agentf65ea3e2-16ee-4cb4-8c06-4e355a689a4e`. The reviewer is now archived; see [final review](review-P6-final-2026-10-08.md). -The selected concrete readiness candidate is the full local basket `rehearsal/p0-custom-voice-complete` at -`9584b2a669ce90a5df8c9eac66073e85124e90bb`. Frozen-only -`rehearsal/p6-approved-voice` at `0169f9a839fcdc01d4df04da02872ef3167c6dc9` -intentionally lacks the side repair and retains its known test failure; it is **not release ready**. -The parent build checkpoint stays at `e423a8666a30075a584f4a8e6f646a28054e6af0`. -Reviewed intake branches alone do not contain the merge adaptations, AsyncStorage stub, and -shared receipt-owner startup fix described above. - -Scratch paths in the historical command tables identify original executions, not permanent -storage. The core harnesses, synthetic pending fixture, runtime outputs, and final focused-test -outputs are copied into [P6-runtime](P6-runtime/README.md). That document gives plain commands -for reproduction from exact refs without a live home or `/tmp/tmad-port` dependency. Other -scratch logs are not durable evidence; reproduce their commands if raw output is needed. - -Remote CI/full suites, human/device/provider checks, provider dispatch, and live-home migration remain open. No live manifest/config changes, custom/mine moves, -main daemon operations, or publication are authorized by this snapshot. diff --git a/fork/plans/tmad-port/evidence/P6-conflict-resolution-log-2026-10-08.md b/fork/plans/tmad-port/evidence/P6-conflict-resolution-log-2026-10-08.md deleted file mode 100644 index feaa3eebfe9..00000000000 --- a/fork/plans/tmad-port/evidence/P6-conflict-resolution-log-2026-10-08.md +++ /dev/null @@ -1,10 +0,0 @@ -# Conflict resolution log - -- `packages/app/src/screens/workspace/workspace-tab-menu.ts` — class: `code-logic`; upstream context: TM-01 commit `b7672631a` (`feat(stream): import companion Stream and artifact feed from PR #19`) adds only the `file-code-2` icon arm and the optional artifacts menu item/label, while the frozen baseline already provides the `message-circle-plus` side-conversation arm and callback. The conflicts are additive entries in the icon union; no same identifier has differing values and the callbacks have separate keys, labels, and runtime owners. Resolution: union both icon arms and keep both existing menu features. Signals: overlap 0.0, contradiction 1.0, touched-symbol 0.0, upstream-context 0.5; weighted score 0.35. User's explicit instruction for this rehearsal is to keep unions unless a contract conflicts; no contract conflict was found. Both features remain independently wired. Verification: `npm run format:files -- packages/app/src/screens/workspace/workspace-tab-menu.ts` (exit 0); `npm run lint -- packages/app/src/screens/workspace/workspace-tab-menu.ts` (exit 0, 0 warnings/errors). -- `packages/app/src/screens/workspace/{workspace-desktop-tabs-row.tsx,workspace-screen.tsx,workspace-tab-menu.ts}` and `packages/app/src/stores/agent-view-store.ts` — class: `code-logic`; upstream context: TM-07 adds Find-in-chat state/actions alongside frozen baseline Stream artifacts and side-conversation actions. Resolution: retain all three independent actions and their icon/label/callback plumbing; keep selected Chat/Artifacts state separate from Find overlay state. The mobile menu has one separator after its final optional action, preserving the original single-feature entries while avoiding duplicate separators when both artifacts and Find are present. Removed one duplicate import introduced by combining both screen changes. Verification: `npm run format:files -- ` (exit 0); `npm run lint -- ` (exit 0); `npm run typecheck --workspace=@getpaseo/app` (exit 0). Logs: `/tmp/tmad-port/logs/p6-format-native-find-final.log`, `/tmp/tmad-port/logs/p6-lint-native-find-final.log`, `/tmp/tmad-port/logs/p6-typecheck-app-native-find.log`. - -- Approved TM-04 voice applied last to the frozen four-feature P6 checkpoint and separately to the full current-custom + side-repair basket. The composer overlap at packages/app/src/composer/index.tsx was additive; both the durable queue/outbox selectors and supportsVoiceConcurrentInput remain. The client merge auto-merged but duplicated AgentQueueSnapshot imports and listQueuedAgentMessages implementations. The Voice-era flat-RPC method/import were removed in favor of TM-02's existing namespaced queue API. The capability hello test expectation was updated for companion_stream_port_v1, durable_agent_queue, and durable_voice_input_v1. Frozen Voice final HEAD: 0169f9a839fcdc01d4df04da02872ef3167c6dc9; full current-custom final HEAD: 9584b2a669ce90a5df8c9eac66073e85124e90bb. -- The session.ts side-repair and voice receipt/owner changes auto-merged. Review found no discarded behavior: capable-source demand and per-source delivery remain, while Voice receipts remain attachment/generation/voiceOwner scoped. The full custom repaired session suite passed unfiltered, including “side conversation manager events reach every capable client.” The frozen-only basket lacks the side repair and retains the separately recorded failure for that test. -- Runtime found a constructor ownership overlap missed by compilation: bootstrap supplied a MessageReceipts instance while WebSocketServer also injects its single shared receipt owner. Remove the bootstrap instance so the queue receives WebSocketServer's owner before activate(). Final copied-data enabled-runtime recovery passes. This fix is an explicit integration delta, not a mutation of either reviewed intake SHA. -- The test-only AsyncStorage mock integration remains exactly at P6 commit e423a8666a30075a584f4a8e6f646a28054e6af0 and is inherited unchanged by both voice rehearsals (session-store.test.ts blob 9a89a34f6b8b3b61fcd91e1a23c0f7c99f44d5df). -- Detailed runtime, build, typecheck, lint, and scoped-test results are in [the owning P6 report](P6-assembly-2026-10-08.md); its durable runtime reproduction is linked there. No push, live config edit, custom/mine move, or daemon restart occurred. diff --git a/fork/plans/tmad-port/evidence/P6-runtime/README.md b/fork/plans/tmad-port/evidence/P6-runtime/README.md deleted file mode 100644 index 08ca88655a2..00000000000 --- a/fork/plans/tmad-port/evidence/P6-runtime/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# P6 copied pending-state reproduction - -These are audit attachments, not production source or a new test suite. The two harness copies -come from the integrator's scratch scripts; only the hardcoded home was replaced with -`TMAD_AUDIT_HOME`. They import the repository's existing in-process daemon and fake-provider -helpers. The fixture contains synthetic data only. No live-home contents or credentials are copied. - -The original runtime outputs and final focused-test summaries are retained alongside the harnesses. -The fixture is stored as `.json.txt` to preserve its exact bytes and SHA-256 -`eb0fbafe6d8e339f6bf3d8fdc2f206328935e0405d570827560a6ec3a68b2ae3`. -This proves dormant preservation only, not provider dispatch. Both phases observed that hash before/during/after shutdown and zero fake-provider turns; -the enabled phase recovered revision 1 and `pending-copy-1`. - -Run from a checkout with the recorded local refs available. Commands below create disposable -worktrees and a synthetic home; they were not rerun by the docs worker. Keep the same home between -phases. Each harness starts an ephemeral loopback daemon in-process; it never contacts port 6767. -Do not point `TMAD_AUDIT_HOME` at a live home. - -```bash -coordination_checkout="$PWD" -audit_root="$(mktemp -d)" -export TMAD_AUDIT_HOME="$audit_root/copied-home" -evidence="$coordination_checkout/fork/plans/tmad-port/evidence/P6-runtime" -mkdir -p "$TMAD_AUDIT_HOME/.paseo/queues" -cp "$evidence/pending-fixture.json.txt" "$TMAD_AUDIT_HOME/.paseo/queues/12345678-1234-4123-8123-123456789abc.json" -sha256sum "$TMAD_AUDIT_HOME/.paseo/queues/12345678-1234-4123-8123-123456789abc.json" -git worktree add --detach "$audit_root/queue-free" 365cd7a1c17d8e1511d2a5cd59a13417598edaf3 -git worktree add --detach "$audit_root/enabled" 9584b2a669ce90a5df8c9eac66073e85124e90bb -cp "$evidence/queue-removal-runtime-check.ts.txt" "$audit_root/queue-free/packages/server/src/p6-audit-runtime.ts" -cp "$evidence/queue-removal-enabled-runtime-check.ts.txt" "$audit_root/enabled/packages/server/src/p6-audit-runtime.ts" -cd "$audit_root/queue-free" -npm ci -npm run build:server -npx tsx packages/server/src/p6-audit-runtime.ts > "$audit_root/queue-free-runtime.log" 2>&1 -cat "$audit_root/queue-free-runtime.log" -cd "$audit_root/enabled" -npm ci -npm run build:server -npm run build:app-deps -npm run typecheck -npm run lint -npx tsx packages/server/src/p6-audit-runtime.ts > "$audit_root/enabled-runtime.log" 2>&1 -cat "$audit_root/enabled-runtime.log" -``` - -Reproduce focused tests individually from the enabled checkout, using `--bail=1` on each command. -The four client/server files are `packages/client/src/daemon-client.test.ts`, -`packages/server/src/server/agent-queue/service.test.ts`, -`packages/server/src/server/message-receipts/index.test.ts`, and -`packages/server/src/server/session.test.ts`. The three app files are -`packages/app/src/composer/input/state.test.ts`, `packages/app/src/voice/voice-runtime.test.ts`, and -`packages/app/src/stores/session-store.test.ts`. Use `npx vitest run --bail=1` and capture -output to a file. Do not run a workspace-wide suite. - -For the frozen-only comparison, repeat package setup and the session test in a separate disposable -checkout of `0169f9a839fcdc01d4df04da02872ef3167c6dc9`. Its known side-conversation failure is -expected because the separate side repair is absent; no passing release claim follows from it. - -Remove the two audit harness files before removing disposable worktrees with `git worktree remove`. -Retain reproduction outputs as needed before deleting the synthetic home. These checks do not -establish device behavior, credentialed provider behavior, or live-home migration. diff --git a/fork/plans/tmad-port/evidence/P6-runtime/p6-final-enabled-runtime.log b/fork/plans/tmad-port/evidence/P6-runtime/p6-final-enabled-runtime.log deleted file mode 100644 index 6bee999eae1..00000000000 --- a/fork/plans/tmad-port/evidence/P6-runtime/p6-final-enabled-runtime.log +++ /dev/null @@ -1,15 +0,0 @@ -mise WARN Failed to resolve tool version list for android-sdk: [/tmp/tmad-port/full-custom-plus-voice/.tool-versions] android-sdk@21.0: timed out after 3.00s -{ - "phase": "queue-enabled-runtime-recovery", - "isolatedHome": "/tmp/tmad-port/queue-runtime-custom-copy", - "queuePath": "/tmp/tmad-port/queue-runtime-custom-copy/.paseo/queues/12345678-1234-4123-8123-123456789abc.json", - "queueSha256Before": "eb0fbafe6d8e339f6bf3d8fdc2f206328935e0405d570827560a6ec3a68b2ae3", - "queueSha256DuringRead": "eb0fbafe6d8e339f6bf3d8fdc2f206328935e0405d570827560a6ec3a68b2ae3", - "queueSha256AfterStop": "eb0fbafe6d8e339f6bf3d8fdc2f206328935e0405d570827560a6ec3a68b2ae3", - "restoredRevision": 1, - "restoredPendingIds": [ - "pending-copy-1" - ], - "fakeProviderQueuedTurns": 0, - "daemonPortWasEphemeralLoopback": true -} diff --git a/fork/plans/tmad-port/evidence/P6-runtime/p6-frozen-voice-client-server-tests.log b/fork/plans/tmad-port/evidence/P6-runtime/p6-frozen-voice-client-server-tests.log deleted file mode 100644 index 3208ade31ab..00000000000 --- a/fork/plans/tmad-port/evidence/P6-runtime/p6-frozen-voice-client-server-tests.log +++ /dev/null @@ -1,64 +0,0 @@ - - RUN v4.1.7 /tmp/tmad-port/frozen-plus-voice - - ❯ packages/server/src/server/session.test.ts (160 tests | 1 failed) 197ms - × side conversation manager events reach every capable client 53ms - -⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ - - FAIL packages/server/src/server/session.test.ts > side conversation manager events reach every capable client -AssertionError: expected [] to deeply equal [ { …(2) }, { …(2) } ] - -- Expected -+ Received - -- [ -- { -- "payload": { -- "items": [ -- { -- "text": "What happened?", -- "type": "user_message", -- }, -- { -- "text": "A merge conflict.", -- "type": "assistant_message", -- }, -- ], -- "lastAnswer": { -- "content": "A merge conflict.", -- "status": "answered", -- "synthetic": false, -- "threading": "threaded", -- }, -- "parentAgentId": "11111111-1111-4111-8111-111111111111", -- "pendingQuestion": null, -- "threadId": "thread-1", -- }, -- "type": "agent.side_conversation.update", -- }, -- { -- "payload": { -- "parentAgentId": "11111111-1111-4111-8111-111111111111", -- "threadId": "thread-1", -- }, -- "type": "agent.side_conversation.removed", -- }, -- ] -+ [] - - ❯ packages/server/src/server/session.test.ts:404:20 - 402| }); - 403| - 404| expect(messages).toEqual([ - | ^ - 405| { type: "agent.side_conversation.update", payload: SIDE_CONVERSATI… - 406| { - -⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ - - - Test Files 1 failed | 3 passed (4) - Tests 1 failed | 215 passed (370) - Start at 11:02:32 - Duration 26.04s (transform 40.15s, setup 0ms, import 48.94s, tests 5.31s, environment 1ms) diff --git a/fork/plans/tmad-port/evidence/P6-runtime/p6-full-custom-voice-app-tests.log b/fork/plans/tmad-port/evidence/P6-runtime/p6-full-custom-voice-app-tests.log deleted file mode 100644 index 342454abc7b..00000000000 --- a/fork/plans/tmad-port/evidence/P6-runtime/p6-full-custom-voice-app-tests.log +++ /dev/null @@ -1,8 +0,0 @@ - - RUN v4.1.7 /tmp/tmad-port/full-custom-plus-voice - - - Test Files 3 passed (3) - Tests 76 passed (76) - Start at 11:09:35 - Duration 2.40s (transform 2.05s, setup 0ms, import 3.01s, tests 1.12s, environment 1ms) diff --git a/fork/plans/tmad-port/evidence/P6-runtime/p6-full-custom-voice-client-server-tests.log b/fork/plans/tmad-port/evidence/P6-runtime/p6-full-custom-voice-client-server-tests.log deleted file mode 100644 index b038ae51942..00000000000 --- a/fork/plans/tmad-port/evidence/P6-runtime/p6-full-custom-voice-client-server-tests.log +++ /dev/null @@ -1,9 +0,0 @@ -mise WARN Failed to resolve tool version list for android-sdk: [/tmp/tmad-port/full-custom-plus-voice/.tool-versions] android-sdk@21.0: timed out after 3.00s - - RUN v4.1.7 /tmp/tmad-port/full-custom-plus-voice - - - Test Files 4 passed (4) - Tests 373 passed (373) - Start at 11:23:33 - Duration 14.73s (transform 14.80s, setup 0ms, import 26.19s, tests 4.01s, environment 1ms) diff --git a/fork/plans/tmad-port/evidence/P6-runtime/p6-noqueue-custom-runtime.log b/fork/plans/tmad-port/evidence/P6-runtime/p6-noqueue-custom-runtime.log deleted file mode 100644 index d1dacf59c9c..00000000000 --- a/fork/plans/tmad-port/evidence/P6-runtime/p6-noqueue-custom-runtime.log +++ /dev/null @@ -1,14 +0,0 @@ -{ - "phase": "queue-free-runtime", - "isolatedHome": "/tmp/tmad-port/queue-runtime-custom-copy", - "queuePath": "/tmp/tmad-port/queue-runtime-custom-copy/.paseo/queues/12345678-1234-4123-8123-123456789abc.json", - "queueSha256Before": "eb0fbafe6d8e339f6bf3d8fdc2f206328935e0405d570827560a6ec3a68b2ae3", - "queueSha256WhileRuntimeActive": "eb0fbafe6d8e339f6bf3d8fdc2f206328935e0405d570827560a6ec3a68b2ae3", - "queueSha256AfterStop": "eb0fbafe6d8e339f6bf3d8fdc2f206328935e0405d570827560a6ec3a68b2ae3", - "pendingIds": [ - "pending-copy-1" - ], - "fakeProviderQueuedTurns": 0, - "daemonPortWasEphemeralLoopback": true, - "agentId": "12345678-1234-4123-8123-123456789abc" -} diff --git a/fork/plans/tmad-port/evidence/P6-runtime/pending-fixture.json.txt b/fork/plans/tmad-port/evidence/P6-runtime/pending-fixture.json.txt deleted file mode 100644 index 9b283e7b28f..00000000000 --- a/fork/plans/tmad-port/evidence/P6-runtime/pending-fixture.json.txt +++ /dev/null @@ -1,15 +0,0 @@ -{ - "agentId": "12345678-1234-4123-8123-123456789abc", - "revision": 1, - "items": [ - { - "id": "pending-copy-1", - "text": "keep this queued prompt", - "intent": "queue", - "deliveryState": "pending", - "attempts": 0, - "attemptSeq": 0, - "createdAt": "2026-10-08T00:00:00.000Z" - } - ] -} \ No newline at end of file diff --git a/fork/plans/tmad-port/evidence/P6-runtime/queue-removal-enabled-runtime-check.ts.txt b/fork/plans/tmad-port/evidence/P6-runtime/queue-removal-enabled-runtime-check.ts.txt deleted file mode 100644 index 23bc5f29ebc..00000000000 --- a/fork/plans/tmad-port/evidence/P6-runtime/queue-removal-enabled-runtime-check.ts.txt +++ /dev/null @@ -1,56 +0,0 @@ -import { createHash } from "node:crypto"; -import { readFile, rm } from "node:fs/promises"; -import { createTestPaseoDaemon } from "./test-utils/paseo-daemon.js"; -import { createTestAgentClient } from "./test-utils/fake-agent-client.js"; -import { DaemonClient } from "./test-utils/daemon-client.js"; - -async function main() { - const homeRoot = process.env.TMAD_AUDIT_HOME!; - const agentId = "12345678-1234-4123-8123-123456789abc"; - const queuePath = `${homeRoot}/.paseo/queues/${agentId}.json`; - const sha = (value: Buffer) => createHash("sha256").update(value).digest("hex"); - const before = sha(await readFile(queuePath)); - let providerTurns = 0; - let daemon: Awaited> | undefined; - let client: DaemonClient | undefined; - try { - daemon = await createTestPaseoDaemon({ - paseoHomeRoot: homeRoot, - cleanup: false, - mcpEnabled: false, - agentClients: { - codex: createTestAgentClient("codex", { onStartTurn: () => { providerTurns += 1; } }), - }, - }); - client = new DaemonClient({ - url: `ws://127.0.0.1:${daemon.port}/ws`, - appVersion: "0.1.82", - reconnect: { enabled: false }, - }); - await client.connect(); - const restored = await client.listQueuedAgentMessages(agentId); - const during = sha(await readFile(queuePath)); - if (restored.items.length !== 1 || restored.items[0]?.id !== "pending-copy-1" || restored.items[0]?.deliveryState !== "pending") { - throw new Error("enabled queue runtime did not recover copied pending state"); - } - await client.close(); - client = undefined; - const staticDir = daemon.staticDir; - await daemon.close(); - daemon = undefined; - await rm(staticDir, { recursive: true, force: true }); - const after = sha(await readFile(queuePath)); - if (before !== during || before !== after) throw new Error("enabled recovery changed pending queue bytes"); - if (providerTurns !== 0) throw new Error(`fake provider received ${providerTurns} queued turns during recovery check`); - console.log(JSON.stringify({ phase: "queue-enabled-runtime-recovery", isolatedHome: homeRoot, queuePath, queueSha256Before: before, queueSha256DuringRead: during, queueSha256AfterStop: after, restoredRevision: restored.revision, restoredPendingIds: restored.items.map((item) => item.id), fakeProviderQueuedTurns: providerTurns, daemonPortWasEphemeralLoopback: true }, null, 2)); - } finally { - await client?.close().catch(() => undefined); - if (daemon) { - const staticDir = daemon.staticDir; - await daemon.close().catch(() => undefined); - await rm(staticDir, { recursive: true, force: true }); - } - } -} - -await main(); diff --git a/fork/plans/tmad-port/evidence/P6-runtime/queue-removal-runtime-check.ts.txt b/fork/plans/tmad-port/evidence/P6-runtime/queue-removal-runtime-check.ts.txt deleted file mode 100644 index cf7fcd7e767..00000000000 --- a/fork/plans/tmad-port/evidence/P6-runtime/queue-removal-runtime-check.ts.txt +++ /dev/null @@ -1,88 +0,0 @@ -import { createHash } from "node:crypto"; -import { readFile, rm } from "node:fs/promises"; -import { createTestPaseoDaemon } from "./test-utils/paseo-daemon.js"; -import { createTestAgentClient } from "./test-utils/fake-agent-client.js"; -import { DaemonClient } from "./test-utils/daemon-client.js"; - -async function main() { - const homeRoot = process.env.TMAD_AUDIT_HOME!; - const queuePath = `${homeRoot}/.paseo/queues/12345678-1234-4123-8123-123456789abc.json`; - const sha = (value: Buffer) => createHash("sha256").update(value).digest("hex"); - const before = sha(await readFile(queuePath)); - let providerTurns = 0; - let daemon: Awaited> | undefined; - let client: DaemonClient | undefined; - try { - daemon = await createTestPaseoDaemon({ - paseoHomeRoot: homeRoot, - cleanup: false, - mcpEnabled: false, - agentClients: { - codex: createTestAgentClient("codex", { onStartTurn: () => { providerTurns += 1; } }), - }, - }); - client = new DaemonClient({ - url: `ws://127.0.0.1:${daemon.port}/ws`, - appVersion: "0.1.82", - reconnect: { enabled: false }, - }); - await client.connect(); - const agent = await client.createAgent({ - agentId: "12345678-1234-4123-8123-123456789abc", - provider: "codex", - cwd: "/tmp", - title: "Copied pending queue runtime proof", - }); - await new Promise((resolve) => setTimeout(resolve, 1500)); - const live = await readFile(queuePath); - const afterLive = sha(live); - await client.close(); - client = undefined; - const staticDir = daemon.staticDir; - await daemon.close(); - daemon = undefined; - await rm(staticDir, { recursive: true, force: true }); - const afterStop = await readFile(queuePath); - const after = sha(afterStop); - if (before !== afterLive || before !== after) { - throw new Error("queue bytes changed in queue-free runtime"); - } - if (providerTurns !== 0) throw new Error(`fake provider received ${providerTurns} queued turns`); - const parsed = JSON.parse(afterStop.toString("utf8")); - if ( - parsed.agentId !== agent.id || - parsed.items?.length !== 1 || - parsed.items[0]?.id !== "pending-copy-1" || - parsed.items[0]?.deliveryState !== "pending" - ) { - throw new Error("copied pending item did not remain intact"); - } - console.log( - JSON.stringify( - { - phase: "queue-free-runtime", - isolatedHome: homeRoot, - queuePath, - queueSha256Before: before, - queueSha256WhileRuntimeActive: afterLive, - queueSha256AfterStop: after, - pendingIds: parsed.items.map((item: { id: string }) => item.id), - fakeProviderQueuedTurns: providerTurns, - daemonPortWasEphemeralLoopback: true, - agentId: agent.id, - }, - null, - 2, - ), - ); - } finally { - await client?.close().catch(() => undefined); - if (daemon) { - const staticDir = daemon.staticDir; - await daemon.close().catch(() => undefined); - await rm(staticDir, { recursive: true, force: true }); - } - } -} - -await main(); diff --git a/fork/plans/tmad-port/evidence/TM-01.md b/fork/plans/tmad-port/evidence/TM-01.md deleted file mode 100644 index f607bcd56d4..00000000000 --- a/fork/plans/tmad-port/evidence/TM-01.md +++ /dev/null @@ -1,287 +0,0 @@ -# TM-01 — Stream/artifact vertical slice port (P1) - -Worker: Stream porter (P1). Date finished: 2026-10-03. -Worktree: `/home/ctaylor/.paseo/worktrees/3rzqjhby/tmad-stream-flow` (branch `intake/tmad-stream-flow`). - -## Identifiers - -- Branch: `intake/tmad-stream-flow` -- Base SHA: `6166a7aca` (v0.11.0-beta.3, release-based; custom and mine are NOT ancestors) -- Final HEAD SHA: `2197619bc` (reviewed state; superseded by the post-P2 fix — HEAD is now - `a8241e535`, see the addendum at the bottom) -- The unreviewed WIP commit `4dab8b364` that this branch started from was rewritten away per - plan/brief. Its content was re-derived: all 11 core-file blobs it carried were verified equal to - `af247e4f4` before the reset (recorded in the transcript), and its four partial seams were - superseded by the complete seam set below. - -## Commits (`git log --oneline 6166a7aca..HEAD`) - -``` -2197619bc docs(stream): rename the feature flag in the ported companion doc -b78389b8c refactor(stream): narrow the agent view store to chat and artifacts -cdf819820 test(stream): cover the capability-absent host gate -9edd6260d fix(stream): localize the remaining feed labels and adopt the Stream pins glossary -86d268768 fix(stream): bound pins, manual entries, and retained artifact metadata -1c1f3a196 fix(stream): surface failed pin and triage mutations instead of swallowing them -d39fc66e2 feat(stream): rename companion entry op to dotted namespace and gate on companionStreamPortV1 -717b87b18 feat(stream): apply PR19-to-#21 Stream delta through the port seams -b7672631a feat(stream): import companion Stream and artifact feed from PR #19 -``` - -Commit 1 = brief step 2 (PR #19 import, trailers `Source-Commit: af247e4f4…`). -Commit 2 = brief step 3 (PR19→#21 rehearsal, trailers `Source-Commit: 51fb7693d`). -Commits 3–9 = brief step 4 contract fixes, one subject per contract; they are local-only fixes and -carry no Source-Commit trailer (per COMMON: keep local fixes separate from imports). - -## Allowed-ancestors check (brief step 7) - -- `git merge-base --is-ancestor origin/custom HEAD` → false ✔ (custom not an ancestor) -- `git merge-base --is-ancestor refs/heads/mine HEAD` → false ✔ -- `git merge-base --is-ancestor origin/mine HEAD` → false ✔ -- Nothing was pushed; all commits are local to the branch. No refs outside the branch were created - or modified. - -## Files changed: 53 files, +4129 / −51 (`git diff --stat 6166a7aca..HEAD`) - -New: docs/companion-stream.md + docs/artifact-feed.png, app companion-stream/{feed,model,model.test}, -app artifacts/feed, app stores/agent-view-store, protocol/companion-stream + messages.artifacts.test -+ messages.companion-update-entry.test, server companion-stream{,.test}, server -artifacts/{collector,collector.test,backfill.test}, cli commands/agent/artifacts-scan. -Adapted seams: agent-panel.tsx, agent-stream/{view,turn-footer}, components/message, ui/segmented-control, -workspace-{screen,tab-menu,desktop-tabs-row}, i18n ×9 locales, session-store, agent-snapshots, -replica-cache, host-runtime, daemon-client, client connection defaults, protocol messages + -agent-types + client-capabilities, server agent-manager, session, lifecycle-command, agent-storage, -agent-loading, agent-projections, persistence-hooks, websocket-server, operation-permissions. - -## Source→port ledger (core files; blob IDs `git rev-parse :` vs `HEAD:`) - -Disposition key: **unchanged** = local blob equals the source blob at `51fb7693d` (the reconciled -snapshot); **adapted** = intentional port delta (reason given); **excluded** = source content not -carried. - -| Source path | Source blob (51fb7693d) | Local blob (2197619bc) | Disposition | -| --- | --- | --- | --- | -| docs/companion-stream.md | 10a5903f3 | 10a5903f3 | unchanged (1-word flag rename is post-parity; see note) | -| docs/artifact-feed.png | (binary) | same object | unchanged | -| packages/app/src/artifacts/feed.tsx | 08442fd52 | 08442fd52 | unchanged | -| packages/app/src/companion-stream/feed.tsx | 8d45953f5 | 01eb4cf6e | adapted — localized card titles/triage buttons/empty states/toggle (source hardcodes English); pin vocabulary renamed to "Stream pin" per fork glossary; mutation failures surfaced via toast | -| packages/app/src/companion-stream/model.ts | 9b6f3e01f | 9b6f3e01f | unchanged | -| packages/app/src/companion-stream/model.test.ts | 466e33b3d | 466e33b3d | unchanged | -| packages/app/src/stores/agent-view-store.ts | 69d25d1c1 | (adapted, see below) | adapted — #21's narrowing adopted; `findOpen` overlay state NOT carried (belongs to native Find, TM-07) | -| packages/protocol/src/companion-stream.ts | f8d745755 | f8d745755 | unchanged | -| packages/protocol/src/messages.artifacts.test.ts | 4e055a88b | 4e055a88b | unchanged | -| packages/server/src/server/agent/companion-stream.ts | 4f1a315ed | e73093fca | adapted — sticky eviction (captured-moment churn never evicts pins/Q&A) + `appendManualCompanionEntry` bounds helper (count cap, text/answer clipping) | -| packages/server/src/server/agent/companion-stream.test.ts | 736841742 | e8dcf06b3 | adapted — adds the three bounds tests | -| packages/server/src/server/agent/artifacts/collector.ts | eb24e052b | 98ef672d6 | adapted — turn collection now capped at MAX_RETAINED_ARTIFACTS=200 like backfill (source passes `null` for turns); constant renamed DEFAULT_BACKFILL_LIMIT→MAX_RETAINED_ARTIFACTS | -| packages/server/src/server/agent/artifacts/collector.test.ts | cc69ccd0c | 55b2a9260 | adapted — adds the turn-cap test | -| packages/server/src/server/agent/artifacts/backfill.test.ts | b5d2751da | b5d2751da | unchanged | -| packages/cli/src/commands/agent/artifacts-scan.ts | 4d75d3928 | 4d75d3928 | unchanged | - -Note on docs/companion-stream.md: parity blob 10a5903f3 equals source; commit 2197619bc afterwards -changed one word (`companionStream` → `companionStreamPortV1`) in the prose, so HEAD's blob differs -from source by that single intentional rename. - -Local-only additions (no source counterpart): packages/protocol/src/messages.companion-update-entry.test.ts -(renamed-RPC wire tests), packages/app/src/runtime/host-features.test.ts (capability-absent gate). - -## Rehearsal metrics (PR19 `af247e4f4` → integration `51fb7693d`, brief step 3) - -Scope extracted from the 2,885-file reconciliation delta: exactly the Stream content. - -- Core delta applied: `app/src/companion-stream/feed.tsx` (localization + themed note input), - `app/src/artifacts/feed.tsx` (fontSize token only), `server/.../companion-stream.ts` (`mapChanged` - reference-stability), `server/.../companion-stream.test.ts` (no-op observation test), - `server/.../artifacts/collector.ts` (fs.watch removed → bounded end-of-turn scan; explicit - `scanExisting` backfill with 200 ceiling), NEW `backfill.test.ts`. -- Shared-file hunks applied: protocol messages.ts (scan RPC pair + COMPAT comment), daemon-client - (`scanAgentArtifacts`), agent-manager (`scanAgentArtifacts`), session.ts (scan handler), - operation-permissions (scan request/response entries), CLI registration, i18n stream keys. -- Shared-file hunks inspected and intentionally NOT imported (upstream-sync reconciliation, not - Stream): message.tsx ActivityLog→Notification flip, agent-panel.tsx base reconciliation, - workspace-tab-menu.ts `findInChat` (TM-07), websocket-server `agentMessageQueue` flag (TM-02+), - storage-chain `projectPersistenceHandleForWire` shuffle (beta.3 already has its own newer form), - desktop/e2e/linux-artifact-smoke.js (packaging smoke, "artifact" false positive). -- Conflict/adaptation effort: two real reworks. (1) The feed's note input — my commit-1 adaptation - (EditingTextInput via ref) was superseded by #21's `NoteInput` + `pinText` state; resolved by - converging on the #21 content (blob parity). (2) The panel and storage chain required hand-merging - because the source base (upstream v0.10.0-beta.1) is older than beta.3; every hunk was matched by - content, not position. Everything else applied directly. -- End-state blob comparison vs `51fb7693d`: 11 of 15 core files byte-identical; the 4 intentional - deltas are the bounds work, the feed localization/glossary, the store narrowing, and the collector - turn cap — each listed in the ledger with its reason. The one pleasant surprise: my commit-1 - `fontSize.sm` adaptation of artifacts/feed.tsx exactly anticipated #21's only change to that file, - so the rehearsal delta applied as a no-op there. -- Key rehearsal finding: **the source's own #21 already removed the recursive `fs.watch`** and - replaced it with the bounded end-of-turn scan, citing the same ENOENT/Linux walk concern as - docs/file-observation.md. The "do not restore recursive fs.watch" contract is satisfied by the - reconciled source content itself, not by a port-side patch. Effort: the rehearsal was a normal - extraction-plus-adaptation pass, no source update required re-plumbing a seam. - -## Seam table (source location → port location → why different) - -| Seam | Source (af247e4f4 / 51fb7693d) | Port | Why different | -| --- | --- | --- | --- | -| Agent-panel integration | `panels/agent-panel.tsx` ChatAgentReadyContent: SegmentedControl (chat/artifacts/find) + `CompanionFeed` + RetainedPanel, `useHostFeature("companionStream")`/`"artifactFeed"` | Same component in the port; chat/artifacts only, single `companionStreamPortV1` gate for feed + artifacts; composer kept mounted via RetainedPanelActivity + hiddenPane; RetainedPanel wrap lives inside the streamContent variable | beta.3's panel has a different draft API (textSource/editText), ChatSurface/ComposerDock structure, and oxlint jsx-max-depth=6; the wrapper was placed where depth allows. Find option is TM-07. Gate renamed per contract. | -| Accepted-event capture | `agent-manager.ts`: capture in `appendTimelineItem` (user_message), `recordAndDispatchTimelineItem` (timeline), `handleStreamEvent` (`!fromHistory && type!=="timeline"`), artifacts `beginTurn/cancelTurn/finishTurn` on turn lifecycle | Identical placement, adapted to beta.3's `startPendingForegroundTurn` try/catch (cancelTurn on start failure) and the `isTurnTerminalEvent → collectArtifactsForTurn` hook after `handleStreamEvent` | beta.3 factored turn start into `startPendingForegroundTurn`; the source's inline try/catch no longer exists. Capture still runs after the coalescer flush at the top of handleStreamEvent; history replay stays excluded, so no invented history and no second timeline owner. | -| Storage/projections | agent-storage `STORED_AGENT_SCHEMA` + agent-loading + agent-projections + persistence-hooks `extractTimestamps` pass artifacts/companionEntries through; replica-cache serializes them | Same four server files plus app `replica-cache` — where the port also EXTENDS `StoredAgentSnapshotSchema` (z.strictObject) with `artifacts`/`companionEntries` | The source serialized the fields but never added them to its strict cache schema — its own parse would reject them. The port fixes the schema so cache round-trips preserve Stream data. Bounds (pin/Q&A/manual ceilings, 200-artifact cap) are port additions per contract. | -| Protocol delivery | Flat `update_companion_entry_request` (fire-and-forget, no response); features flags `artifactFeed` + `companionStream`; artifacts/companionEntries optional snapshot fields | Correlated `agent.companion.update_entry.request`/`.response` (accepted/error payload); features flag `companionStreamPortV1` only; same optional snapshot fields; `agent.artifacts.scan.request/response` carried as source designed (already dotted) | Contract: dotted namespace + response so failures surface; distinct capability name so a source-built client can't mistake this daemon for one speaking its flat contract. Old clients strip unknown optional snapshot fields and never receive the new response types (only the requesting client gets them). COMPAT tags use v0.11.0-beta.3-fork / 2027-04-01, not the source's version claims. | -| File navigation | Collector walks cwd on turn end (post-#21; #19 had recursive fs.watch), artifact cards open via `onOpenWorkspaceFile({location:{path}, disposition:"side"})` through `@/workspace/file-open` | Same module (blob-parity collector + the 200-cap); same file-open path — beta.3's existing `@/workspace/file-open` owner, no new watcher, no recursion | `@/workspace/file-open` already exists in beta.3. No fs.watch anywhere in the port; end-turn scans bounded by MAX_SCANNED_ENTRIES=20,000 visited entries and MAX_RETAINED_ARTIFACTS=200 kept; backfill is explicit (CLI `agent artifacts-scan`), never automatic. | - -## Commands run (all from the repo root unless noted) - -| Command | Result | -| --- | --- | -| `ONNXRUNTIME_NODE_INSTALL=skip npm ci` | pass (needed 3 attempts: two failed on tar/ENOENT races while other workers ran npm on this host; clean `rm -rf node_modules` between) | -| baseline `npm run typecheck` at 6166a7aca | FAIL before fix — `tsgo` missing; installed `@typescript/native-preview@7.0.0-dev.20260423.1` via the lockfile version; after that, base typecheck is green | -| baseline `npm run lint` at 6166a7aca | FAIL (pre-existing, untouched files — see below) | -| `npm run build:server` | pass (run after each contract-changing step) | -| `npm run typecheck` (final) | pass, 0 errors | -| `npm run lint -- ` (scoped, per CLAUDE.md) | pass, 0 findings on port files | -| `npm run format:files -- ` / pre-commit `format:check` | pass | -| `npx vitest run src/server/agent/companion-stream.test.ts` | pass (12 tests: 8 source + 1 #21 + 3 port bounds) | -| `npx vitest run src/server/agent/artifacts/collector.test.ts` | pass (3: 2 source + 1 turn cap) | -| `npx vitest run src/server/agent/artifacts/backfill.test.ts` | pass (4, source) | -| `npx vitest run src/server/authorization/index.test.ts` | pass (7) — run after every protocol change | -| `npx vitest run src/messages.artifacts.test.ts` (protocol) | pass (1, source) | -| `npx vitest run src/messages.companion-update-entry.test.ts` (protocol) | pass (5, new) | -| `npx vitest run src/companion-stream/model.test.ts` (app) | pass (2, source) | -| `npx vitest run src/i18n/resources.test.ts` (app) | pass (36 — includes the locale-parity check over all 10 locales) | -| `npx vitest run src/runtime/host-features.test.ts` (app) | pass (3, new) | -| ancestry checks | pass (see above) | - -No full test suite was run, per COMMON/CLAUDE.md. - -## Pre-existing failures (present on untouched 6166a7aca, NOT introduced by this port) - -- `npm run lint` (full repo): errors in `packages/app/src/composer/index.tsx` (react(refs) during - render ×~10, react(purity) Math.random), `packages/app/src/panels/agent-panel.tsx` (16: - set-state-in-effect, exhaustive-effect-dependencies, refs, preserve-manual-memoization, hooks), - `packages/app/src/lib/overlay-root.ts` (refs), `packages/app/src/attachments/store.ts` and - `packages/app/src/git/actions-store.ts` (no-underscore-dangle). Baseline log: - `/tmp/tmad-port/logs/tm01-baseline-lint.log`. The port adds zero new findings on the files it - touches (scoped lint clean); agent-panel still carries its 16 baseline findings plus none new. -- tsgo was absent from `node_modules/.bin` after the first npm ci — environment quirk on this host - (possibly another worker's concurrent npm run), resolved by reinstall. - -## Contract compliance summary (plan "Compatibility contracts > Stream" + brief step 4) - -- Capture after coalescing, no second timeline owner, no invented history: capture sits after the - coalescer flush in `handleStreamEvent`; `fromHistory` events and timeline events (outside the - dedicated timeline hooks) are excluded; source tests assert reference stability. -- Bounds: captured moments 50 × 4000-char excerpts (source); NEW — pins/Q&A never evicted by moment - churn, manual-entry ceiling 100 with explicit refusal, manual text/answer clipped, artifact - metadata ceiling 200/agent for turns and backfill. All tested. Rough persisted-size worst case per - agent record: ~200KB captured + ~400KB manual notes + ~40KB artifact metadata. -- No recursive fs.watch; end-turn scans bounded; backfill explicit only (CLI). docs/file-observation.md - constraints respected — the port adds no observer and no watcher. -- Wire: optional fields only; no `.transform/.catch/.preprocess` added to any wire schema; renamed - dotted RPC pair with exhaustive authorization entries (`agent.companion.update_entry.request` = - workspace.write, `.response` = workspace.write; `agent.artifacts.scan.request`/`response` = - workspace.read); client capability default added (client `connection/index.ts` DEFAULT_CLIENT_CAPABILITIES) - and declared by the app at connect; single `companionStreamPortV1` gate; source capability names - absent from schema, advertisement, and client registry (tested); no new pushed top-level events - exist — both new outbound types are request-correlated responses only; dated COMPAT tags throughout. -- Chat stays mounted when switching to Stream (RetainedPanel keeps the stream, composer stays - mounted with activity gated and hidden); selecting a moment only navigates back to chat or updates - triage state — it never sends, cancels, or grants (source behavior preserved; feed has no send path). -- Failed pin/triage mutations surface via panel toast (client throws on `accepted:false`). -- Locales: every locale under packages/app/src/i18n/resources (ar en es fr ja ko pt-BR ru zh-CN) has - the full Stream key set; Korean translations are port-authored (source has no ko.ts; parity test - enforces). Label vocabulary: "Stream pin(s)" for persistent notes; no "Pinned prompt" exists on - this branch so there is no live collision. -- Tab menu: mobile tab menu gains "View stream" (source's `viewArtifacts` entry, label - `agentPanel.stream.viewStream`) alongside the existing upstream items; desktop context menu is - unchanged. No item required custom/infi code. -- Observations release: nothing to release — the port runs no daemon-side observation tied to a view - (collection is turn-scoped) and the app-side view store is plain state. -- TM-01B (bridge): NOT NEEDED. The slice compiles and tests green on beta.3 alone; nothing in it - requires custom/infi code. Native Find (TM-07) stays out; its seam is documented in - agent-view-store.ts for the later branch. - -## Reaching Stream in the UI (sanity description; full UI evidence is the later P1 step 6) - -1. Connect the app to a daemon running this branch; `server_info.features.companionStreamPortV1` is - true. The agent panel header shows a two-segment switcher: **Chat** / **Stream** - (`testID="agent-view-switcher"`, per-agent selection persisted by `agent-view-store`). -2. **Stream** shows the companion feed (`testID="companion-stream"`): needs-a-reply section and - filters (All/Questions/Q&A/Features/Decisions/Outcomes), pinned tab ("Stream pins") with a note - input, artifact cards inline. On hosts without the feature it shows the update-host notice with - the artifact list only. -3. In Chat, user messages and completed assistant turns show pin (and Q&A for user messages) - buttons (hover/always-visible per platform); pinning adds a Stream pin. The mobile workspace tab - menu gains "View stream" which opens the agent tab with the Stream segment preselected. -4. CLI: `npm run cli -- agent artifacts-scan [--limit N]` backfills a pre-existing agent's feed. - -## Known gaps / deferred - -- UI capture evidence (matched source/port desktop + compact browser screenshots, native captures, - locale screenshots) — explicitly deferred per brief step 6; this report covers the compile + test - sanity bar only. -- The feed's "Queue" tab label (`agentPanel.stream.queueTab`, value "큐"/"Queue") is the source's - name for the moments list. It has no dependency on the future durable queue (TM-02), but if the - glossary wants a different word to avoid confusion with the message queue, it is a one-line i18n - change — flagged here as a naming decision, not changed unilaterally beyond the pins glossary the - plan fixed. -- #21's feed still hardcodes nothing else: remaining English-adjacent strings are i18n `|| fallback` - literals in artifacts/feed.tsx (keys exist and are localized). -- `sendAgentMessage`/queue/composer contracts: untouched (no queue code on this branch) — verified by - the file list; the daemon's legacy send path is unmodified. -- agent-manager tests for the capture seam are the source's collector/companion suites; a - beta.3-harness agent-manager-level capture test was not added (would need the full manager test - fixture). The placement is identical to the source's, which its tests cover. - -## Human decisions requested - -None blocking. Two informational: (1) the "Queue" tab label above; (2) the manual-entry ceiling -value (100) and artifact ceiling (200) were chosen from the backfill default the source itself -picked (200) and a generous note budget — both are single-constant changes if the numbers should -differ. - -## Environment notes for the next worker on this host - -- The first two `npm ci` attempts failed with tar/ENOENT races (other port workers were running npm - concurrently); a clean `rm -rf node_modules` + fresh `npm ci` succeeded (log: - `/tmp/tmad-port/logs/tm01-npm-ci3.log`). `tsgo` required the explicit local install noted above. -- The Paseo daemon on 6767 was never touched. No remotes were pushed. `~/.paseo-fork` was not read or - written beyond what COMMON allows (not touched at all). - -## Addendum (post-P2 assembly finding, 2026-10-03) - -**Defect.** The P2 assembly (report `/tmp/tmad-port/evidence/P2.md`, fix commit `d17896891` on -`tmad-with-stream` in `/tmp/tmad-port/baseline-clone`) found a port fidelity defect at the -terminal-event seam in `dispatchSessionEvent`: this port had changed the reconciled source's -fire-and-forget artifact collection (source `51fb7693d`, -`packages/server/src/server/agent/agent-manager.ts:4012`, `void this.collectArtifactsForTurn(agent)` -with its rationale comment) into `await this.collectArtifactsForTurn(agent)` and dropped the -comment. Holding the turn's waiter notification on the working-directory walk let a steer admitted -during the walk see the run unsettled and leave a ghost tracked run, so the next foreground start -was rejected with "already has an active run" — deterministically breaking the agent-manager -steer-fallback test on the merged tree (209/210; green on baseline). - -**Fix.** Applied the assembly's identical one-hunk fix by hand: the fix commit object was not -reachable from this worktree (it lives in the baseline clone's store), so its patch was extracted -with `git --git-dir=/tmp/tmad-port/baseline-clone/.git show d17896891` and applied verbatim, -committing with the same message. Committed locally on `intake/tmad-stream-flow` as **`a8241e535`** -("fix(server): restore fire-and-forget artifact collection at the terminal-event seam") — one -commit appended on top of the reviewed `2197619bc`; no history rewritten, nothing pushed. - -**Verification.** - -- The seam is byte-equal to the source hunk: `git diff 51fb7693d -- ` no longer shows any - difference at the call site; the method's relocation elsewhere in the file remains the only - (pre-existing, intentional) port delta. Aligned byte comparison of the seam region against - `51fb7693d`: identical. Diff captured at `/tmp/tmad-port/logs/tmad-seam-vs-source.diff`. -- `npx vitest run src/server/agent/agent-manager.test.ts --bail=1`: **192/192 passed** (log: - `/tmp/tmad-port/logs/fix-agent-manager-test.txt`). Count differs from the merged tree's 210 - because the baseline contributes tests not on this pure branch. The critical case was also run - individually by name ("does not replace a newer foreground turn after unavailable steer fallback - is admitted"): **passes** (log: `/tmp/tmad-port/logs/fix-steer-fallback-test.txt`). -- `npx vitest run src/server/agent/companion-stream.test.ts src/server/agent/artifacts/collector.test.ts - src/server/authorization/index.test.ts --bail=1`: **22/22 passed** (log: - `/tmp/tmad-port/logs/fix-adjacent-tests.txt`). -- `npm run build:server`: exit 0. `npm run typecheck`: exit 0 (log: - `/tmp/tmad-port/logs/fix-typecheck.txt`). Scoped lint and format via npm scripts on the touched - file: clean; pre-commit hooks (lint, format:check, full-workspace typecheck) green at commit. - -**Correction of the report's "Final HEAD SHA".** `2197619bc` was the reviewed state. The branch -HEAD is now **`a8241e53530d6bd0a958971118d6b8b57ff80b0c`**. diff --git a/fork/plans/tmad-port/evidence/TM-02.md b/fork/plans/tmad-port/evidence/TM-02.md deleted file mode 100644 index 26eacc513ce..00000000000 --- a/fork/plans/tmad-port/evidence/TM-02.md +++ /dev/null @@ -1,189 +0,0 @@ -# TM-02 — durable agent message queue (P3) — final report - -Supersedes the earlier handoff at this path. The handoff's blocker #1 -(truncated pre-commit typecheck failure) is resolved: the failure was stale -protocol `dist` declarations consumed by `packages/client`; the committed -protocol contract landed in `6f76c621e` and every commit since passed the -lefthook typecheck. Reproduction details under "Baseline" below. - -## Identity - -- Branch: `intake/tmad-message-queue` (worktree - `/home/ctaylor/.paseo/worktrees/3rzqjhby/tmad-message-queue`, host pluto) -- Recorded custom floor / base SHA: `cbd1210c7d15fbdaac02cab8375cdcf2dd6bd234` -- Final HEAD SHA: `91392d6be` (full sha below) -- `git log --oneline cbd1210c7..HEAD`: - -``` -91392d6be docs: add queue mirroring doc -ee8c0d84b feat(queue): wire the durable queue into the daemon -68f863134 feat(queue): durable delivery states, receipts and recovery -21b80e206 feat(protocol): make agent.queue.update subscribable -eefbfc134 feat(queue): import tmad agent-queue store, service and send-or-queue -6f76c621e feat(protocol): durable agent message queue wire contract (landed by the previous worker) -``` - -Final HEAD full sha: `91392d6beed3fc49f9be7496a70b8d5822957d4c` (local only — -nothing was pushed, per COMMON.md). - -## Allowed ancestors - -| Ref | Result | Verdict | -| --- | --- | --- | -| `custom` = `cbd1210c7…` | ANCESTOR | ✓ the declared custom floor (P3 decision: queue is custom-based) | -| `v0.11.0-beta.3` = `6166a7aca…` | ANCESTOR | ✓ upstream release, reaches HEAD through custom | -| source integration `51fb7693d…` | NOT ancestor | ✓ extraction only, never merged | -| source head `f0d5507d2…` | NOT ancestor | ✓ | -| `mine` | ref does not exist on this host | not checkable here; branch ancestry is exactly custom + the six commits above, none derived from mine | - -## Files changed (base → HEAD) - -20 files, +3792 / −20. Highlights: protocol wire contract (+321 messages.ts, -+189 test, capability + flag), `agent-queue/{store,service,send-or-queue}` + -tests (all new files), session dispatch (+253), bootstrap (+17), -websocket-server (+14), authorization (+17), additive changes to -`agent-prompt.ts` (replaceRunning param), `atomic-file.ts` (mode option), -`message-receipts` (outcome reader), `docs/queue-mirroring.md` (new), -CLAUDE.md docs-table row. - -## Source → port ledger - -Effective source snapshot: `51fb7693d` (integration commit; PRs #23, #24, -#25, #26, #30, #31, #32). The source head `f0d5507d2` carries newer queue -files that couple the queue to the voice feature (`origin: "voice"`, -`wrapSpokenInput`, `waitForPendingDispatch`); voice is TM-04, so the queue -ports from the integration snapshot and the head's journal implementation is -cited as the model for the persistence adaptation. - -| Source path | Source blob (`git rev-parse 51fb7693d:

`) | Local blob (HEAD) | Disposition | -| --- | --- | --- | --- | -| `packages/server/src/server/agent-queue/store.ts` | `7039d635f…` | `5134cea2…` | adapted — import commit carries 2 compile hunks (wire-required intent/deliveryState/attempts); adaptation commit makes them authoritative and adds: journal (before/after, image bytes elided, byte-bounded rotation, 0600, fsync — modeled on the head implementation at `f0d5507d2`), 0600 atomic queue writes, revision-guarded mutation (`QueueRevisionConflictError`), `ids()` enumeration for recovery. Local-only. | -| `packages/server/src/server/agent-queue/service.ts` | `ba9ff72eb…` | `f0bee779…` | adapted (local contract) — explicit `intent` on admission; claim-in-place `dispatching` state with per-attempt receipts (`attemptSeq` keys) instead of remove-before-send; `uncertain`/`failed` states with 8-attempt limit; revision-checked update/remove/reorder/retry/send_now; FIFO hold-the-line; archived-agent fence; `activate()` recovery; strict steer via the existing `steerAgentRun` admission (refusal un-claims, never replaces); enqueue bounds (50 items, 16 MiB images). The source's remove-before-send drain and drainedIds-only dedup are superseded; drainedIds retained for post-delivery accept-once. | -| `packages/server/src/server/agent-queue/send-or-queue.ts` | `95561c9fb…` | `af81c749…` | adapted — queueing requires explicit `intent`; without it the helper is a plain send, so no surface can queue by omission. The legacy send handler is NOT rewired through it (source wired it in; we did not — see exclusions). | -| `packages/server/src/server/agent-queue/service.test.ts` | `d60a755de…` | `062944a3…` | adapted — source cases kept (17), plus new cases: revision conflict, bounds, edit rules, retry/send-now, refused/accepted strict steer, 8-attempt failed state, and a startup-recovery describe block over the real `MessageReceipts` (completed / pending / missing receipts; archived agent; load-without-dispatch). | -| `packages/server/src/server/agent-queue/send-or-queue.test.ts` | `ec208522…` | `b7b21ee6…` | adapted — source cases kept with explicit intents, plus "a busy agent without queue intent keeps the legacy direct send". | -| `packages/server/src/server/agent-queue/store.test.ts` | absent at `51fb7693d` (exists only at head, `3c6f5446…`) | `local` | adapted from the head journal tests (rotation, 0600) plus local tests: revision conflict, ids/delete, empty-parse, journal image elision. | -| `packages/server/src/server/daemon-e2e/agent-queue-mirroring.e2e.test.ts` | `072169c6…` | not ported | excluded here — see "Known gaps". | -| protocol block (messages.ts agent.queue.*), client-capabilities, client default, operation-permissions | n/a (landed in `6f76c621e`, names renamed per docs/rpc-namespacing.md: source flat `agent.queue.remove.request` → `agent.queue.delete.request`, plus new `retry`/`send_now`) | n/a | adapted at the wire layer by the previous worker; this lease added the `agent.queue.update` subscribable-event enum value. | - -Source deltas deliberately NOT taken (recorded so a future update can -classify them again): - -- `agent-prompt.ts` finish-notification queueing when the caller is busy and - `create-agent/create.ts` queueService plumbing — changes existing - notification/steer behavior; not in the TM-02 wiring lease. -- `paseo-tools` queue integration (agents calling the queue as a tool). -- Voice fields (`origin`, `voiceOwner`, `wrapSpokenInput` receipt-backed - voice parity) — TM-04 scope. -- Head's async queue mutators (`QueueMutator` returning promises) — not - needed by this design. - -## Crash-point table - -| Crash between | State on disk | What `activate()` recovery does | -| --- | --- | --- | -| admission → claim | item `pending` (attempts 0) | queued normally; delivered exactly once (identity + drainedIds) | -| claim → receipt write | item `dispatching`, attempts/attemptSeq already bumped; receipt file absent for this attempt | `queue` intent: prompt never sent (receipt pending is committed before any send) → resumes `pending` and delivers. `steer_strict`: admission may have reached the provider → held `uncertain` (`queue_claim_interrupted`) | -| receipt write → dispatch outcome | receipt `pending` | item held `uncertain` (`agent_request_outcome_unknown`); never auto-resent; `agent.queue.retry` is the only resend path | -| dispatch → removal | receipt `completed` | treated as delivered: item removed, id recorded in `drainedIds` so a late enqueue retry of the same id is a no-op | - -Repeated reconnect cannot duplicate turns: enqueue is accept-once by item id -(including after delivery, via `drainedIds`), claims are atomic under the -per-agent store lock, and dispatch work is serialized on a per-agent tail. -After 8 known-failed attempts the item parks in the visible `failed` state -with `lastError`, resumable only by explicit retry/discard. Full narrative in -`docs/queue-mirroring.md`. - -## Baseline (handoff blocker #1, reproduced with full output) - -Log: `/tmp/tmad-port/logs/tm02-typecheck-baseline.log`. - -- First attempt failed environmentally: this host's shared `~/.npm` cache was - corrupted (ENOENT in `_cacache`), so `npm ci` had failed (masked by a - compound-command echo), leaving `zod-aot` and `tsgo` missing → - `build:client` exit 1, root typecheck exit 127. -- Repair: `npm ci` with a private cache (`--cache /tmp/tmad-port/npm-cache`), - then the dependency-stack builds the repo docs require - (`build:client`, `build:plugin`, `build:highlight`, then `build:server`). - Each intermediate root-typecheck failure (401 → 35 → 3 error lines) was - exclusively `TS2307 Cannot find module '@getpaseo/'` + implicit-any - cascades from never-built `dist` declarations in untouched workspaces. -- Result at HEAD with built stacks: `build:client` exit 0; root - `npm run typecheck` exit 0 with 0 errors - (`/tmp/tmad-port/logs/tm02-final-root-typecheck.log`). Every commit also - passed the lefthook pre-commit typecheck, which resolves the handoff's - blocker: the earlier failure was the same stale-`dist` class, observable at - commit time only because `build:client` had not been run in that session. -- Classification: no typecheck failure was caused by the branch; the - verified-green HEAD (superset check) plus per-commit green hooks cover it. - No throwaway-worktree check was needed for typecheck once HEAD was green. - -## Commands run (pass/fail) - -| Command | Result | Log | -| --- | --- | --- | -| `ONNXRUNTIME_NODE_INSTALL=skip npm ci --cache /tmp/tmad-port/npm-cache` | exit 0 | `logs/tm02-npm-ci-2.log` | -| `npm run build:client` / `build:plugin` / `build:highlight` / `build:server` | all exit 0 | `logs/tm02-build-*.log` | -| root `npm run typecheck` (final state) | exit 0, 0 errors | `logs/tm02-final-root-typecheck.log` | -| `npx vitest run src/server/agent-queue/service.test.ts` (verbatim import) | 17 passed | `logs/tm02-test-service-verbatim.log` | -| `npx vitest run src/server/agent-queue/send-or-queue.test.ts` (verbatim import) | 6 passed | `logs/tm02-test-send-or-queue-verbatim.log` | -| `npx vitest run src/server/messages.agent-queue.test.ts` (protocol) | 9 passed | `logs/tm02-test-protocol-sub.log` | -| `npx vitest run src/server/agent-queue/{store,service,send-or-queue}.test.ts` (final) | 49 passed | `logs/tm02-test-all-queue6.log` | -| `npx vitest run src/server/message-receipts/index.test.ts src/server/agent/agent-prompt.test.ts` | 17 passed | `logs/tm02-test-shared-files.log` | -| `npx vitest run src/server/authorization/index.test.ts` | 7 passed | `logs/tm02-test-auth.log` | -| `npx vitest run src/server/agent/agent-manager.test.ts` | 210 passed | `logs/tm02-test-agent-manager.log` | -| `npx vitest run src/server/agent/providers/acp-agent.test.ts` | 130 passed | `logs/tm02-test-acp.log` | -| `npx vitest run src/server/agent/providers/gjc-acp-agent.test.ts` | 43 passed | `logs/tm02-test-gjc.log` | -| `npx vitest run src/server/session.test.ts` (full file) | 157 passed, 1 pre-existing failure (below) | `logs/tm02-test-session-full2.log` | -| every commit | lefthook lint + format + typecheck green | per-commit output | - -Individual files only; no full suite was run locally (COMMON.md). - -## Pre-existing failures (not caused by this branch) - -- `session.test.ts > "side conversation manager events reach every capable - client"` fails at clean HEAD `6f76c621e` with the working-tree changes - stashed (verified twice: `logs/tm02-test-sideconversation-base.log`). The - test exercises side-conversation event delivery, a path this branch never - touches. Attribution to the custom floor `cbd1210c7` specifically could not - be isolated on this host: a detached scratch worktree at the floor cannot - share this worktree's `node_modules` because the lockfile moved between the - floor and HEAD (`@opencode-ai/sdk` subpath resolution fails), and a fresh - `npm ci` there was not justified for one classification datum. Needs a - human/owner look on neptune where the floor toolchain exists. - -## Known gaps / deferred - -1. **Daemon e2e not ported or run.** `agent-queue-mirroring.e2e.test.ts` - parks a real `claude` provider agent on a Bash permission to make the - queue observable; that needs real provider auth (`packages/server/.env.test` - credentials) which this host does not have (no `~/.claude/.credentials.json`), - and the repo forbids auth gates in tests. It also depends on - DaemonClient queue helpers that do not exist in our client test-utils yet. - Recommendation: port it in TM-03/P4 on a machine with provider creds, or - re-anchor it on a fake-provider daemon harness if one is built. -2. Mixed-version coverage is split across layers rather than one test: - parse-compat and capability gating in `messages.agent-queue.test.ts` - (9 tests), legacy-path behavior in - `session.test.ts > "a legacy send_agent_message_request never reaches the - queue service"` (receipt-backed response shape asserted, queue untouched). -3. `send_now` may deliver a later item ahead of a still-pending head — an - explicit, revision-checked user action; the response carries the - post-attempt queue so the client sees the outcome. Flagged as a design - call, not a gap. -4. A refused `steer_strict` item is retried on lifecycle wakeups; if none - come, it delivers as a normal run when the turn ends (never interrupts, - never deletes). Documented in `docs/queue-mirroring.md`. -5. Startup resume covers agents already loaded and idle at `activate()`; - on-demand agents resume on their next running→idle transition. A queued - prompt for an agent nobody opens after restart waits — deliberate, so the - daemon never spawns providers just to drain queues. -6. `docs/queue-mirroring.md` added as the subject doc (the ported code's - comments reference that path); CLAUDE.md docs table has the row. - -## Human decisions requested - -None blocking. Two design calls were made inside the plan's fences and are -recorded above (send_now cross-head delivery; strict-steer idle fallback). -The pre-existing side-conversation test failure needs an owner on neptune. -Per the plan, no manifest edit, no push, and no daemon restart were performed. diff --git a/fork/plans/tmad-port/evidence/TM-03.md b/fork/plans/tmad-port/evidence/TM-03.md deleted file mode 100644 index aa4dab7d2c4..00000000000 --- a/fork/plans/tmad-port/evidence/TM-03.md +++ /dev/null @@ -1,252 +0,0 @@ -# TM-03 — queue UI and cross-device behavior (P4) — final report - -Branch `intake/tmad-queue-ui`, based on `intake/tmad-message-queue` at its APPROVED head -`91392d6be` (custom floor `cbd1210c7`). Nothing pushed; all commits local. No daemon on 6767 -was touched; no manifest was edited. - -## Identity - -- Branch: `intake/tmad-queue-ui` (worktree - `/home/ctaylor/.paseo/worktrees/3rzqjhby/tmad-queue-ui`, host pluto) -- Base SHA: `91392d6beed3fc49f9be7496a70b8d5822957d4c` (TM-02 APPROVED head) -- Final HEAD: `9ab91bb759be1951bdaa9cbe7bc991cafed2569d` -- `git log --oneline 91392d6be..HEAD`: - -``` -9ab91bb75 docs: queue track client contract and glossary -5561f172b test(queue): two-client queue mirroring daemon e2e -9390e664a feat(queue): queue track controls for the durable queue -6d96da519 feat(queue): mirror daemon queue snapshots into the session store -0a0f90d99 feat(queue): daemon-owned queue actions in the composer layer -cdc42f6a1 feat(queue): port queue outbox store and composer queue-sync -c6f2612fe feat(client): add durable agent queue client methods -``` - -## Allowed ancestors - -| Ref | Result | Verdict | -| --- | --- | --- | -| `intake/tmad-message-queue` head `91392d6be` | ANCESTOR | ✓ the only declared prerequisite | -| custom `cbd1210c7` | ANCESTOR | ✓ (through the TM-02 floor) | -| `v0.11.0-beta.3` `6166a7aca` | ANCESTOR | ✓ (through custom) | -| source integration `51fb7693d` | NOT ancestor | ✓ extraction only | -| source head `f0d5507d2` | NOT ancestor | ✓ | -| `refs/research/tmad-main-latest` `929f1add3` | NOT ancestor | ✓ classified below, not merged | -| `mine` `4cc94e07e` | NOT ancestor | ✓ | - -`git rev-list --count 91392d6be..HEAD` = 7. No other merges; the branch adds exactly these -seven commits on top of the TM-02 head. - -## Files changed (base → HEAD) - -24 files, +3126 / −54. New: `stores/queue-outbox-store/{model,index,model.test}` -(+563), `composer/queue-sync{,.test}` (+305), daemon-e2e -`agent-queue-mirroring.e2e.test.ts` (+297). Modified: `composer/actions{,.test}` (+831), -`composer/index.tsx` (+668 net incl. queue track UI), `client/daemon-client.ts` (+157), -`stores/session-store{,.test}` (+194 net), `contexts/session-context.tsx` (+22), nine i18n -locale files (+14 each), `docs/queue-mirroring.md`, `docs/glossary.md`. - -## Source → port ledger - -Effective source snapshot for the app layer: `51fb7693d` (PRs #23–26, #30–32). The newer -source head `f0d5507d2` is byte-identical for every queue UI file (verified by empty diff -`51fb7693d..f0d5507d2` on the outbox store, queue-sync, and ui-commands), so the -integration snapshot is the complete queue UI the source ever shipped. - -| Source path | Source blob (`git rev-parse 51fb7693d:

`) | Local blob (HEAD) | Disposition | -| --- | --- | --- | --- | -| `packages/app/src/stores/queue-outbox-store/model.ts` | `3d6130d60e17ee76bcd115ca907f9fec24409f47` | `9e636fd3513c540fb1e5b5b10d17059611348aaa` | adapted — entry carries the admission intent (our wire requires it; re-sends verbatim); exhaustion parks the entry in a visible `failedAt` state instead of remove+drop (plan contract: no silent deletion of an undelivered prompt); `QueueOutboxAccess` gains `markFailed`. | -| `packages/app/src/stores/queue-outbox-store/index.ts` | `8b278e1a317d07ca60e8f7b1700c1b4a2fd99732` | `f6529a56d4acf1d8fd50e9e5ed5ff4a5109d5f58` | adapted — `markFailed`/`retryEntry` actions; the flush list skips failed entries (retry is explicit, never automatic); `retryFailedOutboxEntry` retries one entry without touching others. | -| `packages/app/src/stores/queue-outbox-store/model.test.ts` | `ce83ee9ccafe8e0ef0a19cab98cff0edbe446aa2` | `534e55972c7d23bfc4489f057e7a694b871f1ff2` | adapted — all source cases kept (fixtures gain the wire-required intent/deliveryState), plus: verbatim-intent resend, exhaustion stays visible, failed entries skipped by flush, success on a later flush removes. | -| `packages/app/src/composer/queue-sync.ts` | `64537da472b5f324df8905a9675c21e5e88afee3` | `75608bc25233928c45c05aa85ee1efb52b557534` | adapted — snapshot rows carry `deliveryState`/`lastError`; `appendPendingQueueRows` marks re-appended rows with their outbox `syncState` (`pending`/`failed`). Everything else unchanged (revision guard, image/composer-attachment mapping). | -| `packages/app/src/composer/queue-sync.test.ts` | `6d6b77074e795e02255f840593105b913d3e8dd3` | `0962a02ee1f41c5c0afbe79496eef6f52eb2ca9f` | adapted — all source cases kept, plus state-carry and failed-sync assertions. | -| `packages/app/src/composer/actions.ts` (queue section) | file `57b2bdcb6577e6a74fc2946e8588bf3aa58164a3` | file `a239be783779155b4055421df842683953e58ff6` | adapted — `queueComposerMessageOnServer` (optimistic row, outbox-first, snapshot apply) and `takeQueuedComposerMessage` (delete + image rehydration) ported with our deltas: explicit `intent: "queue"` admission, `expectedRevision` on every mutation, `queue_revision_conflict` mapped to a `conflict` outcome. Local additions: `deleteQueuedComposerMessage`, `reorderQueuedComposerMessages`, `retryQueuedComposerMessage`, `isQueueRevisionConflictError`, `removeQueuedComposerMessageLocally` (source helper), `QueuedComposerMessage` extended with `deliveryState`/`lastError`/`syncState`. | -| `packages/app/src/composer/actions.test.ts` (queue cases) | file (see above) | file (see above) | adapted — all six source `queueComposerMessageOnServer` cases and all four `takeQueuedComposerMessage` cases kept (client fake upgraded to the revision-checked API), plus: admission-without-submission-row, stale-revision-conflict outcomes for take/delete/retry, reorder/retry revision pass-through, conflict-code recognition. | -| `packages/app/src/composer/index.tsx` (queue track) | file `86f083914d6af091abffa1780a016d1b5280269c` | file `253475fb2d31d7d611f510d91b9e840df988cd9d` | adapted — the source's four durable branches ported (gate + outbox writer + list-on-connect + durable queue/edit/send-now with take-then-compose and requeue-on-failed-submit). Local additions beyond the source: durable row menu (move up/down, delete), retry/discard on failed or unconfirmed rows, delivery-state badges (``), failed-outbox overlay, visible conflict handling with queue refresh, confirmDialog for delete/discard. | -| `packages/app/src/stores/session-store.ts` | file `edafc51cf8d75c72b61e9758af2853fb87e0f010` | file `2d39d84ebb8f2a8891f2c7999a89dc6d84698306` | adapted — `applyAgentQueueSnapshot` + `queuedMessageRevisions` ported as-is in shape; rows typed as `QueuedComposerMessage` so delivery state flows. Source's unrelated deltas (companion/artifacts fields, `toDaemonServerInfo` removal) NOT taken. | -| `packages/app/src/contexts/session-context.tsx` | file `d8d84e20b1b9561728480bc71a00f36e69148947` | file `ff0e8571c71e87758fec13ec846811e1a1f46a1a` | adapted — `agent.queue.update` subscription and reconnect outbox flush ported; flush gates on OUR `features.durableAgentQueueV1` (source used its own `agentMessageQueue` flag) with a dated COMPAT tag; `dropAbandonedQueueRow` NOT ported (we keep exhausted rows visible; nothing is silently dropped). Source's removal of custom's side-conversation handlers NOT taken (fork-lineage noise). | -| `packages/client/src/daemon-client.ts` (queue section) | file `01d1f698118c51f389342868f594cde9971a7354` | file `fece6e2c04c5cc61514f2a32aa48528695f882d1` | adapted — the source's client queue methods ported onto our wire: dotted RPC names, required `intent` on enqueue, `expectedRevision` on update/reorder/delete/retry/send_now, `requireAgentQueuePayload` surfacing the daemon's machine-readable error code. | -| `packages/server/src/server/daemon-e2e/agent-queue-mirroring.e2e.test.ts` | source `072169c6…` (parked at `51fb7693d`) | local, new | re-anchored — source version parked a real `claude` provider on a Bash permission (needs provider credentials this host lacks) and DaemonClient helpers that did not exist. Rebuilt on the in-process fake-provider harness (`docs/ad-hoc-daemon-testing.md`): the fake's permission flow parks the turn, two DaemonClients exercise the full contract. | -| i18n (9 locales) | n/a — source strings for queue controls already exist in custom; this port adds new strings for the new controls | n/a | local — `composer.queued.*` (menu, move, delete, discard, retry, sending, unconfirmed, failed, conflict, confirm dialog) translated in ar/en/es/fr/ja/ko/pt-BR/ru/zh-CN; key parity enforced by `resources.test.ts`. | -| `docs/queue-mirroring.md`, `docs/glossary.md` | n/a | local | local — composer-side contracts and the Queue track term (durable vs legacy meaning); Steer cross-reference updated. | - -### Source deltas deliberately NOT taken (recorded for future classification) - -- `interrupt?: boolean` on `send_agent_message_request` + `dispatchComposerAgentMessage` - (source PR #32's wire field). Our wire has no such field (TM-02 froze the legacy send - path); our Interrupt affordance remains the stop button and the `interrupt` send - behavior. Porting it would require a protocol change outside this lease. -- `toggleGithubAttachment = toggleForgeAttachment` alias — source-internal naming shim. -- `input.tsx` / `input/state.ts` diffs at `51fb7693d` — voice mute/cancel plumbing - (TM-05/TM-06 scope), not queue. -- Source's removal of custom's side-conversation handlers in `session-context.tsx` — - fork-lineage noise; custom's handlers are preserved. -- Source's session-store additions unrelated to the queue (companion/artifacts fields, - `toDaemonServerInfo` removal) — upstream-sync noise. - -## Brief requirements — how each is met - -1. **Canonical submission owner.** `dispatchComposerAgentMessage` is untouched. Queue - admission (`queueComposerMessage` / `queueComposerMessageOnServer`) only appends to the - queue writer and never sees a submission writer; the optimistic row is a queued row, not - a timeline row. Tested: `actions.test.ts > "admits with the explicit queue intent and - never touches a submission writer"`, `session-store.test.ts > "never creates a submitted - timeline row"`, and the e2e asserts exactly one canonical `user_message` row carrying - the delivered (edited) text after drain. -2. **Capability gate.** Every durable path gates on `server_info.features.durableAgentQueueV1` - (composer selector + session-context flush), tagged - `COMPAT(durableAgentQueue): added in v0.11.0-beta.3+custom (TM-02/TM-03)`. Against old - hosts the composer keeps the existing local in-memory queue with today's rendering and - actions; nothing labels it durable. The outbox is written only in durable mode. -3. **Edit / reorder / delete / send-now with revision handling.** Edit = take (delete + - image rehydration into the composer, draft recovery via `replaceUserInput` + - `setSelectedAttachments`); reorder = full-id-list `agent.queue.reorder` from the row - menu; delete = confirmed `agent.queue.delete`; send-now = take then the regular submit - path, requeueing (at the end) if the submit fails. Every mutation sends the revision the - device last saw; `queue_revision_conflict` surfaces as a visible localized conflict - message plus an automatic queue refresh — never a silent overwrite. Tested in actions - tests and e2e test 2. -4. **Retry exhaustion / uncertain delivery visible.** Daemon `failed`/`uncertain` rows show - a status badge and Retry/Discard; retry is the only resend path (daemon contract from - TM-02, UI honors it). Outbox entries exhausted after 8 failed flushes park visible with - Retry/Discard instead of the source's silent drop. Tested in the outbox model tests and - e2e drain assertions. -5. **Steer / Queue / Interrupt affordances.** Unchanged from custom: send-behavior setting - (`steer` default), the running-state queue button, and the stop button. The queue path - behind the Queue affordance now lands in the durable queue when the host supports it. -6. **Typed-send default comparison (product decision — unchanged, as instructed).** - Source default and ours are identical: `sendBehavior: "steer"` with the same - `"interrupt" | "steer" | "queue"` enum, same settings section, same labels - (`sendAndSteer` / `sendAndInterrupt` / `queueMessage`) — verified identical at both - `51fb7693d` and the newer source head `f0d5507d2` - (`packages/app/src/hooks/use-settings/storage.ts`). There is no default to reconcile; - the only behavioral difference after this port is what "queue" queues (durable daemon - queue when gated, local otherwise). No product decision is required on the default; the - open product question below is the outbox exhaustion UX (item 4 in update-loop - candidates). - -## Design / platform conformance - -`` for state pills, `` (the one menu engine) for the row menu, -`confirmDialog` for destructive confirms, `StyleSheet.create((theme) => …)` only (no -`useUnistyles`), spacing/typography on theme tokens, no `onPointerEnter` (menu trigger -hover only styles its own icon, which hover.md permits), native gets the same always-visible -controls (nothing is hover-revealed). Glossary respected in UI copy: "Delivery" and -"Queued prompt" do not appear as labels; the revision-conflict copy names the other device. - -## Commands run (pass/fail) - -| Command (from owning package) | Result | Log | -| --- | --- | --- | -| `ONNXRUNTIME_NODE_INSTALL=skip npm ci --cache /tmp/tmad-port/npm-cache` | exit 0 | `logs/tm03-npm-ci.log` | -| `npm run build:client` / `build:server` | both exit 0 | `logs/tm03-build-client.log`, `logs/tm03-build-server.log` | -| root `npm run typecheck` (final HEAD) | exit 0 | `logs/tm03-typecheck-final.log` | -| root `npm run lint -- ` (final HEAD) | exit 0, 0 errors | `logs/tm03-lint-final.log` | -| `npm run format:files -- ` before each commit; lefthook format+lint+typecheck green on all 7 commits | pass | per-commit hook output | -| app: `npx vitest run src/composer/actions.test.ts src/composer/queue-sync.test.ts src/stores/queue-outbox-store/model.test.ts src/composer/submit.test.ts src/composer/input/state.test.ts src/composer/input/labels.test.ts src/i18n/resources.test.ts src/stores/session-store.test.ts` | 8 files, 177 passed | `logs/tm03-test-app-final.log` | -| server: `npx vitest run src/server/agent-queue/{service,store,send-or-queue}.test.ts src/server/authorization/index.test.ts` | 4 files, 56 passed (49 TM-02 queue + 7 auth) | `logs/tm03-test-server-final.log` | -| protocol: `npx vitest run src/messages.agent-queue.test.ts` | 9 passed | `logs/tm03-test-protocol-final.log` | -| server e2e: `npx vitest run src/server/daemon-e2e/agent-queue-mirroring.e2e.test.ts` | 2 passed, run twice (stability check) | `logs/tm03-test-e2e-8.log`, `logs/tm03-test-e2e-9.log` | - -Individual files only; no full suite run (COMMON.md). Every commit passed the lefthook -typecheck against built workspace declarations. - -### Pre-existing failures - -None observed in the files run. `session.test.ts` (which carries TM-02's documented -pre-existing side-conversation failure) was not rerun: no server-session code changed on -this branch (the server diff is the additive e2e test file only), and TM-02's report already -records that failure against the floor for an owner on neptune. - -## The two-client daemon e2e (feasible — done) - -Ran on the in-process fake-provider harness, no provider credentials, no auth gates: - -- **Mirroring test:** two independent `DaemonClient`s against one daemon. Client B enqueues - while the agent is parked on a fake permission request; client A receives the same queue - via `agent.queue.update`. B edits in place (`agent.queue.update`), A enqueues a second - item, B reorders, a fresh client reconnects and `agent.queue.list` returns the reordered, - edited queue; B deletes the second item; the permission resolves, the turn ends, the - drain delivers the surviving item, both live clients see the queue empty, and the - canonical timeline contains exactly one `user_message` with the edited text. -- **Conflict test:** client A mutates at revision N; client B's write carrying revision N is - rejected with `queue_revision_conflict` and the queue still shows A's edit. - -Coverage note: capability-absent behavior is split across layers rather than forced into the -e2e — an old-client simulation would need capability overrides in the test client; parse -compat and event gating for old/new peers are already covered by TM-02's -`messages.agent-queue.test.ts` (9 tests, rerun green), and the composer's old-host path is -the pre-existing local queue behavior exercised by the existing actions/submit/state tests. - -## tmad-main-latest (`929f1add3`, PR #36) — update-loop classification - -PR #36 ("preserve queued messages until host acknowledgement") is a durability hardening of -the same client layer this port ships, written against the source's own 51fb7693d shape. - -Already covered by this port, in a different or stronger form: - -- No silent deletion at the retry cap — we go further and park the entry visible with - explicit retry/discard (PR #36 keeps retrying behind a one-time attention message; both - preserve the payload). -- Snapshot reconciliation with a revision guard; outbox entries re-sent verbatim (PR #36 - adds intent-carrying resends against a wire that gained intent — ours has that natively). -- A failed send keeps its durable entry and its visible row. -- No ghost rows after acknowledgement: our rows converge through snapshots (an ack applies a - snapshot containing the id; later snapshots keep it because it is a daemon row). - -Remaining update-loop candidates if #36 is later classified for adoption: - -1. **"Waiting to sync" label + action gating** for rows the latest snapshot does not - contain (PR #36 blocks edit/send-now on un-accepted rows; ours surfaces a daemon error - instead if a device acts on an un-acked row mid-flight). -2. **Per-agent blocking flush** — PR #36 makes a failing enqueue block later items for that - agent while other agents proceed; ours flushes oldest-first across the server and bumps - failures individually. -3. **Await durable outbox persistence before clearing the composer draft** (and gating - dispatch on it), plus their `index.test.ts` persistence tests. Our `outbox.add` is a - synchronous store write; AsyncStorage persistence lands asynchronously, so a hard kill - in that window can lose the entry. -4. **Exhaustion UX product decision:** PR #36's one-time attention message with indefinite - auto-retry vs. our parked-failed-with-explicit-retry. The plan's queue contract - ("Preserve the item after the source outbox's eight-attempt limit… explicit retry or - discard") is what we implemented; adopting #36's shape would need that contract line - revisited by a human. - -## Known gaps / deferred - -1. **In-place item edit has no composer affordance.** The client ships - `updateQueuedAgentMessage` and the daemon supports it, but the UI's edit is - take-into-composer (source parity, same UX as the local queue). The composer additions - beyond source are menu reorder, delete, retry, discard. An inline edit field is new - product surface, not ported. -2. **`steer_strict` intent is not admitted by this UI.** Admission sends `intent: "queue"` - only; the outbox carries the intent so a future voice admission (TM-04) can reuse the - path unchanged. `agent.queue.retry`/`send_now` on `steer_strict` items work from the - client methods. -3. **Send-now uses take+submit, not `agent.queue.send_now`.** Deliberate: the daemon's - send-now is a head-of-line attempt that no-ops against a busy agent (and burns an - attempt), while take+submit delivers immediately through the user's send behavior - (steer default) — matching the button's promise and the source's UX, and still yielding - exactly one canonical row. The `sendQueuedAgentMessageNow` client method ships for wire - parity and tests. Design call recorded here for review. -4. **Optimistic-row race inherited from the source:** between the optimistic add and - `outbox.add` (the image-encoding await), a concurrent broadcast can briefly erase the - row; the enqueue response's snapshot restores it. Window is small and self-healing. -5. **Host downgrade with pending outbox entries:** entries written against a capable host - stay in storage if the host later loses the flag; they are not flushed and not shown as - queued against a host that cannot honor them. Documented in `docs/queue-mirroring.md`; - a purge/adopt policy would be new product surface. -6. **UI parity captures not taken.** The plan's UI-fidelity bar (matched source/port - captures on desktop/compact/native) applies to the Stream port's rehearsal pattern; the - queue track's source UI is byte-identical to ours at the row level and the additions - (badges, menu) have no source counterpart to compare against. Browser/native screenshot - evidence was not produced on this host; a human pass on the dev app is the natural next - check. - -## Human decisions requested - -None blocking. Two design calls are recorded above with rationale (send-now via take+submit; -exhaustion parking vs PR #36's attention-message shape). The PR #36 update-loop candidates -(especially item 4) are the ones a human may want to rule on at the next source sync. - -Per the plan and COMMON.md: no manifest edit, no push, no daemon restart, no full test suite. diff --git a/fork/plans/tmad-port/evidence/TM-04-2026-10-08.md b/fork/plans/tmad-port/evidence/TM-04-2026-10-08.md deleted file mode 100644 index 3179d94edfe..00000000000 --- a/fork/plans/tmad-port/evidence/TM-04-2026-10-08.md +++ /dev/null @@ -1,299 +0,0 @@ -# TM-04 implementation evidence - -Branch: `intake/tmad-voice-flow`. Workspace: `/home/ctaylor/.paseo/worktrees/3rzqjhby/tmad-voice-flow-r2`. - -Base TM-02: `91392d6beed3fc49f9be7496a70b8d5822957d4c`. Final HEAD: `84f11381ceabec13d5deaff6c1e2c05dc67a6c62`. -Recovered raw WIP: `6ab56eba1ae1efe2d2696ca090d6ec82f579f2f8` (initial clean worktree). -Recovery backup: `origin/backup/tmad-voice-flow-wip-2026-10-04` and `/home/ctaylor/.local/state/backups/tmad-voice-flow-wip-2026-10-04.tar.gz`; left intact. - -## Outcome and scope - -TM-04 implementation is complete for coordinator review. No push, PR, manifest/custom/mine edit, live daemon operation, deployment, provider run, or physical-device claim. No agents delegated. TM-02 is the only feature dependency; TM-03 is not required. Final native module files, bootstrap, tool policy, and app test configuration are byte-identical to TM-02. TM-05 verbal command parsing and TM-06 background/native changes are excluded. Existing typed send defaults and receipt-backed interrupt behavior are preserved. - -The source feature `voiceConcurrentInput` maps to our distinct `durableVoiceInputV1` feature/client capability (`durable_voice_input_v1`). Source #23 inferred queue semantics are not imported: speech explicitly enters TM-02's durable queue regardless of busy/idle state, while typed sends keep their existing admission choices. Source attachment tokens and receipt RPC names remain optional/backward-parseable additions; the distinct gate selects the adapted feature. An in-process receipt can be sending, but the wire remains queued/submitted/removed/unknown; queued never claims provider acceptance. Completed receipts map to submitted and UI “sent to agent”, not completed work or heard audio. Failed/ambiguous queue items map to unknown. - -Audit corrections: - -- Save the Session principal/client owner and scope attachment receipt reads by that owner and current source/generation. -- Observe queue updates only while this server owns active gated voice; reconcile receipts after drain/removal so queued feedback reaches sent without waiting for a later agent turn. -- Validate queue revision and dispatch state before writing a removal tombstone, under the queue mutation lock. -- Preserve a logical speech receipt beyond TM-02's 100 drained-ID window. Write logical completion before attempt completion; a crash before known completion stays pending/uncertain instead of replaying. Completed/removed records dominate older attempt records in attachment reads. -- Fence admission success and failure against released attachment/generation; durable acceptance survives detach, while old transport acknowledgements do not leak to a replacement. -- Hold queued dispatch behind pending permissions and reserve the run atomically. An archived agent reached during preparation rejects as never submitted; no false turn-start receipt. -- Register native and browser playback before preparation; cancel late preparation and retain one queue processor across immediate stop/replacement. Retain foreground native duration completion; no PR14 native playback-complete event or background implementation. -- Restore PR22's web track-ended interruption and source turn-controller timeout/speech-duration assertions. Microphone-loss UI stays visible through the existing toast/failure owner. -- Migrate the touched voice overlay from forbidden `useUnistyles()` to `withUnistyles`; hardware-muted state displays Not listening. Keep separate Stop voice and explicit agent interrupt actions. - -## Attribution and history - -Source repo: `tmad4000/paseo`. Selected commits: - -- `2ec044bfdaeb43ce9637542e90e8ee57e93e8887` — PR #13 -- `de19368240c8ae70d6c142fe02db4eb5b0fe0a0d` — PR #15 -- `af517bc7eecaf5772b2395f7e6542f3d424bafde` — PR #22 -- `e309257e613e94524e5f2b6fdcbb7d5a220bbeb8` — PR #23 - -Source integration `51fb7693d39b0c888654c75fe596427e1e012872` is a lookup snapshot only, never merged. PR22/23 postdate integration; the ledger includes both the required integration blob and the effective selected source blob. Existing repository LICENSE retains Apache-2.0 and third-party notices; the embedded failure-phrase generator identifies Kokoro Apache-2.0 and remains unexecuted here. - -The recovered WIP commit is rewritten on this branch only into an attributed adapted import plus a separate local correction commit. The backup remains available. Both commits are required for the final reviewed result. - -``` -84f11381ceabec13d5deaff6c1e2c05dc67a6c62 fix(voice): reconcile durable receipts and fence released transports -5ecb8324625de55dc80345f181518da26f2d42db feat(voice): port queued speech and independent audio lifecycle -``` - -## Ancestry - -Commands: `git rev-parse --verify ` and `git merge-base --is-ancestor HEAD`. - -| Ref | Resolved SHA | Result | -| --- | --- | --- | -| TM02 base | `91392d6beed3fc49f9be7496a70b8d5822957d4c` | exit 0: ancestor | -| pinned custom floor | `cbd1210c7d15fbdaac02cab8375cdcf2dd6bd234` | exit 0: ancestor | -| current custom | `24f134618cd8a7143615debf927c1ac60b9ba813` | exit 1: not ancestor | -| pinned release | `6166a7aca5e3184e8ab505caad28f6a595816414` | exit 0: ancestor | -| source integration | `51fb7693d39b0c888654c75fe596427e1e012872` | exit 1: not ancestor | -| source head | `f0d5507d21cf7f6d86c792d235f3c27156a27d7a` | exit 1: not ancestor | -| mine | absent ref | not checkable | - -The pinned custom floor is expected ancestry through TM-02. A moving current custom ref need not be an ancestor. No source integration/head ancestry is permitted; none was merged. `mine` is absent on this host. - -## Validation - -Commands ran from this workspace unless a package cwd is specified. Builds and checks were serialized within this worker. Other coordinator builds were visible on the host; no shared dependency/typecheck defect was found. - -| Command | Result | Log | -| --- | --- | --- | -| `npm run build:server` (owning dependency stack, before cross-package typecheck) | PASS, exit 0; initial and final rebuild | `/tmp/tmad-port/logs/tm04-build-server.log`, `/tmp/tmad-port/logs/tm04-build-server-final.log` | -| `npm run build --workspace=@getpaseo/expo-two-way-audio` | PASS, exit 0; exposes existing JS entry for native mock tests | `/tmp/tmad-port/logs/tm04-build-native-module.log` | -| `npm run typecheck` | PASS, exit 0 after owning builds | `/tmp/tmad-port/logs/tm04-typecheck.log` | -| `npm run lint -- ` | PASS, exit 0; exact command saved | `/tmp/tmad-port/logs/tm04-lint-command.txt`, `/tmp/tmad-port/logs/tm04-lint.log` | -| `npm run format` | PASS, exit 0 before each commit; full formatter, no unrelated source delta | `/tmp/tmad-port/logs/tm04-format.log`, `/tmp/tmad-port/logs/tm04-format-final.log`, `/tmp/tmad-port/logs/tm04-format-pre-fix-commit.log` | -| `git diff --check` | PASS | command output empty | - -Each test used `npx vitest run --bail=1` from its owning package. No workspace/full test suite ran. Lists and runners: `/tmp/tmad-port/tm04-tests.txt`, `/tmp/tmad-port/tm04-run-tests.py`, `/tmp/tmad-port/tm04-rerun-tests.txt`, `/tmp/tmad-port/tm04-rerun-tests.py`, `/tmp/tmad-port/tm04-final-tests.txt`, `/tmp/tmad-port/tm04-final-tests.py`; result TSVs under `/tmp/tmad-port/logs/`. Final queue command: `npx vitest run src/server/agent-queue/service.test.ts --bail=1` from `packages/server`, rerun after its lint fixture adjustment. Final Session command: `npx vitest run src/server/session.test.ts --bail=1 -t '^(?!side conversation manager events reach every capable client$)'` from `packages/server`. - -| File | Final result | Log | -| --- | --- | --- | -| `packages/app/src/components/realtime-voice-overlay.test.tsx` | exit 0; 5 passed (5) | `/tmp/tmad-port/logs/tm04-packages_app_src_components_realtime-voice-overlay.test.tsx.log` | -| `packages/app/src/composer/input/state.test.ts` | exit 0; 17 passed (17) | `/tmp/tmad-port/logs/tm04-packages_app_src_composer_input_state.test.ts.log` | -| `packages/app/src/voice/audio-engine.native.test.ts` | exit 0; 3 passed (3) | `/tmp/tmad-port/logs/tm04-packages_app_src_voice_audio-engine.native.test.ts.log` | -| `packages/app/src/voice/audio-engine.web.test.ts` | exit 0; 2 passed (2) | `/tmp/tmad-port/logs/tm04-packages_app_src_voice_audio-engine.web.test.ts.log` | -| `packages/app/src/voice/voice-failure.test.ts` | exit 0; 6 passed (6) | `/tmp/tmad-port/logs/tm04-packages_app_src_voice_voice-failure.test.ts.log` | -| `packages/app/src/voice/voice-runtime.test.ts` | exit 0; 31 passed (31) | `/tmp/tmad-port/logs/tm04-packages_app_src_voice_voice-runtime.test.ts.log` | -| `packages/protocol/src/messages.voice-flow.test.ts` | exit 0; 5 passed (5) | `/tmp/tmad-port/logs/tm04-packages_protocol_src_messages.voice-flow.test.ts.log` | -| `packages/server/src/server/agent-queue/send-or-queue.test.ts` | exit 0; 9 passed (9) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_agent-queue_send-or-queue.test.ts.log` | -| `packages/server/src/server/agent-queue/service.test.ts` | exit 0; 41 passed (41) | `/tmp/tmad-port/logs/tm04-queue-service-final.log` | -| `packages/server/src/server/agent-queue/store.test.ts` | exit 0; 8 passed (8) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_agent-queue_store.test.ts.log` | -| `packages/server/src/server/agent/agent-manager.test.ts` | exit 0; 210 passed (210) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_agent_agent-manager.test.ts.log` | -| `packages/server/src/server/agent/agent-prompt.test.ts` | exit 0; 17 passed (17) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_agent_agent-prompt.test.ts.log` | -| `packages/server/src/server/agent/mcp-server.test.ts` | exit 0; 126 passed (126) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_agent_mcp-server.test.ts.log` | -| `packages/server/src/server/agent/paseo-tool-policy.test.ts` | exit 0; 2 passed (2) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_agent_paseo-tool-policy.test.ts.log` | -| `packages/server/src/server/agent/providers/acp-agent.test.ts` | exit 0; 130 passed (130) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_agent_providers_acp-agent.test.ts.log` | -| `packages/server/src/server/agent/providers/acp-wrapper-smoke.test.ts` | exit 0; 12 skipped (12) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_agent_providers_acp-wrapper-smoke.test.ts.log` | -| `packages/server/src/server/agent/providers/claude/agent.voice-history-regression.test.ts` | exit 0; 5 passed (5) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_agent_providers_claude_agent.voice-history-regression.test.ts.log` | -| `packages/server/src/server/agent/providers/gjc-acp-agent.test.ts` | exit 0; 43 passed (43) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_agent_providers_gjc-acp-agent.test.ts.log` | -| `packages/server/src/server/agent/tts-manager.test.ts` | exit 0; 10 passed (10) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_agent_tts-manager.test.ts.log` | -| `packages/server/src/server/authorization/index.test.ts` | exit 0; 7 passed (7) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_authorization_index.test.ts.log` | -| `packages/server/src/server/message-receipts/index.test.ts` | exit 0; 9 passed (9) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_message-receipts_index.test.ts.log` | -| `packages/server/src/server/session.test.ts` | exit 0; 159 passed / 1 skipped (160); exclude only the independently reproduced base broadcast failure | `/tmp/tmad-port/logs/tm04-session-final.log` | -| `packages/server/src/server/session.voice-mcp-config.test.ts` | exit 0; 3 passed (3) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_session.voice-mcp-config.test.ts.log` | -| `packages/server/src/server/session/voice/index.test.ts` | exit 0; 1 passed (1) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_session_voice_index.test.ts.log` | -| `packages/server/src/server/session/voice/voice-recognition-issue.test.ts` | exit 0; 4 passed (4) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_session_voice_voice-recognition-issue.test.ts.log` | -| `packages/server/src/server/session/voice/voice-session.test.ts` | exit 0; 16 passed (16) | `/tmp/tmad-port/logs/tm04-voice-session-final.log` | -| `packages/server/src/server/session/voice/voice-turn-controller.test.ts` | exit 0; 15 passed (15) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_session_voice_voice-turn-controller.test.ts.log` | -| `packages/server/src/server/websocket-server.relay-reconnect.test.ts` | exit 0; 31 passed (31) | `/tmp/tmad-port/logs/tm04-packages_server_src_server_websocket-server.relay-reconnect.test.ts.log` | - -Deterministic lifecycle checks use synthetic STT/turn detection and spy-backed agent state through the actual Session/VoiceSession boundary. They prove the host does not call cancel/reload/replace/permission/side-question/history operations through voice attach, playback abort, STT error, detach and transport-owner release. Worker/child state assertions are simulated, not proof of an actual provider's child process or a physical audio path. Custom ACP/GJC, manager, queue/store and authorization suites run separately against existing implementations. The ACP wrapper smoke file exits zero with all 12 provider-dependent cases skipped; it supplies no live-provider proof. No provider source implementation changed. - -## Failures and corrections - -- Full `session.test.ts --bail=1` fails on `side conversation manager events reach every capable client`: expected two broadcasts, received `[]`. Reproduced on detached unmodified TM-02 `91392d6beed3fc49f9be7496a70b8d5822957d4c` at `/tmp/tmad-port/tm04-base-check`; source tree unchanged, existing dependency/build dirs reused via symlinks. Log `/tmp/tmad-port/logs/tm04-base-session.log`. Port full-file initial failure `/tmp/tmad-port/logs/tm04-packages_server_src_server_session.test.ts.log`. Final filtered run excludes that one base case and executes all remaining cases. This remains a shared base failure for the coordinator; no TM03/side-conversation behavior was patched to mask it. -- Initial native test could not resolve the unbuilt audio workspace. Built it, then filled the source mock's existing `releaseAudioSession` export. Native test is included normally; the WIP exclusion was removed. Intermediate failure `/tmp/tmad-port/logs/tm04-native-rerun.log`; final pass is in the test table. -- Initial root typecheck caught WIP UI/wire receipt type confusion and narrow overlay-test props; fixed by deriving wire receipt items from the protocol union and props from the component type. Initial log `/tmp/tmad-port/logs/tm04-typecheck-initial.log`; final result is recorded above. No shared declaration failure. -- The first import commit hook rejected staged-only source capability/wire/UI types against the built host declarations. Moved capability/type adaptations into the import commit so both commits compile independently; kept behavioral corrections separate. Failed hook log `/tmp/tmad-port/logs/tm04-commit-import.log`; successful normal-hook logs `/tmp/tmad-port/logs/tm04-commit-import-final.log` and `/tmp/tmad-port/logs/tm04-commit-fixes.log`. No hook bypass. -- The recovered tool-policy change failed the existing speak-policy test. Reverted the source policy rewrite to TM-02, then reran green. -- New lifecycle-test fixtures initially lacked the existing load-close barrier and agent registry; corrected fixtures. New deferred-admission test initially awaited detach before releasing its deliberate barrier; corrected to complete admission during detach. These were test harness failures, corrected before final validation. -- One Session invocation accidentally ran from repo root and overlapped a package invocation, writing the same intermediate log; neither result is accepted as final evidence. The accepted final run uses a unique log and the owning package cwd. All other heavy runs were serialized by this worker. - -## Remaining coordinator and human gates - -Coordinator: perform independent review of both commits and the source ledger. Evaluate the reproduced TM-02 broadcast failure with its owner. Run CI/full suites remotely and an isolated manifest assembly/removal rehearsal against the frozen basket. Reconcile any adjacent TM-03 adapter changes with the new durableVoiceInputV1 name. No merge/push/deployment was performed here. - -Desktop/compact web and native UI: verify mid-turn voice entry is available only on a supporting host; old-host busy restriction remains; queued/sent/removed/uncertain status text and Stop voice/Interrupt controls fit at compact widths and large text; hardware mute and blocking failures show Not listening. Capture comparable screenshots; no browser/native visual capture is claimed by this report. - -Per provider, using isolated test agents for Claude, Codex, custom ACP and GJC: start a long-running turn with a pending permission, a live child/subagent and an active side-conversation thread. Attach/detach repeatedly, interrupt playback, force STT failure, disconnect/reconnect transport, and confirm the same turn, child, permission and thread survive without synthetic user turns. Queue at least two spoken prompts during busy work and permission wait; confirm no foreground cancellation, one durable queue item and one canonical provider user row per stable ID, in-order dispatch only after admission fences clear, and queued then sent feedback from receipts. Test delivery-loss/crash reconciliation without automatic replay of uncertain items; test explicit interrupt separately and confirm provider cancellation refusal is surfaced. Verify readable chat replies alongside speak/fallback audio and no replay of historical assistant text on attach. - -Physical iOS and Android: verify mic permission grant/refusal, capture start/stop, hardware mute, microphone track/OS interruption, VAD endpointing and recognition timeout/empty utterance announcements, audible segmented playback, interruption during initialization/decode/TTS, immediate replacement playback, echo suppression (agent audio must not become queued user speech), queued/sent tones, and one failure announcement per episode. Verify device lock/background and foreground-return behavior only for the existing native binary; TM06 background capture is not included and must not be inferred from timers. Test network loss/reconnect while queued speech remains admitted; stale-generation frames and late acknowledgements must be ignored. - -Two devices: while device A owns recording, device B must receive an ownership refusal without revoking A or modifying the agent. A reconnect with the same principal/client/attachment rotates generation and revokes its obsolete source. An old source cannot stop/unmute/ack/read the new attachment; another principal/client cannot read A's receipts. Then explicitly detach A and verify B can attach. Exercise relay and direct transport independently. - -These human checks are required before promotion; they are not implementation blockers and no result is fabricated. - -## Final file delta - -``` -.../app/scripts/generate-voice-failure-phrases.mjs | 132 +++++ - .../src/components/realtime-voice-overlay.test.tsx | 116 ++++ - .../app/src/components/realtime-voice-overlay.tsx | 109 +++- - packages/app/src/composer/index.tsx | 17 +- - packages/app/src/composer/input/input.tsx | 41 +- - packages/app/src/composer/input/state.test.ts | 37 +- - packages/app/src/composer/input/state.ts | 13 +- - packages/app/src/contexts/session-context.tsx | 67 ++- - packages/app/src/contexts/voice-context.tsx | 16 +- - packages/app/src/i18n/resources/ar.ts | 19 +- - packages/app/src/i18n/resources/en.ts | 19 +- - packages/app/src/i18n/resources/es.ts | 20 +- - packages/app/src/i18n/resources/fr.ts | 22 +- - packages/app/src/i18n/resources/ja.ts | 19 +- - packages/app/src/i18n/resources/ko.ts | 20 +- - packages/app/src/i18n/resources/pt-BR.ts | 19 +- - packages/app/src/i18n/resources/ru.ts | 20 +- - packages/app/src/i18n/resources/zh-CN.ts | 19 +- - packages/app/src/voice/audio-engine.native.test.ts | 113 ++++ - packages/app/src/voice/audio-engine.native.ts | 35 +- - packages/app/src/voice/audio-engine.web.test.ts | 105 ++++ - packages/app/src/voice/audio-engine.web.ts | 73 +-- - packages/app/src/voice/input-receipt-cue.ts | 24 + - packages/app/src/voice/voice-failure-cue.ts | 89 ++++ - .../app/src/voice/voice-failure-phrases.mulaw.ts | 28 + - packages/app/src/voice/voice-failure.test.ts | 98 ++++ - packages/app/src/voice/voice-failure.ts | 124 +++++ - packages/app/src/voice/voice-runtime.test.ts | 378 ++++++++++++- - packages/app/src/voice/voice-runtime.ts | 591 +++++++++++++++++---- - packages/app/test-stubs/lucide-react-native.ts | 1 + - packages/client/src/connection/index.ts | 1 + - packages/client/src/daemon-client.ts | 87 ++- - packages/protocol/src/client-capabilities.ts | 4 + - packages/protocol/src/messages.ts | 67 +++ - packages/protocol/src/messages.voice-flow.test.ts | 100 ++++ - .../src/server/agent-queue/send-or-queue.test.ts | 49 ++ - .../server/src/server/agent-queue/send-or-queue.ts | 28 +- - .../server/src/server/agent-queue/service.test.ts | 212 ++++++++ - packages/server/src/server/agent-queue/service.ts | 187 ++++++- - packages/server/src/server/agent-queue/store.ts | 13 +- - packages/server/src/server/agent/agent-manager.ts | 42 +- - .../server/src/server/agent/agent-prompt.test.ts | 94 ++++ - packages/server/src/server/agent/agent-prompt.ts | 77 ++- - .../server/src/server/agent/agent-sdk-types.ts | 2 + - .../server/src/server/agent/mcp-server.test.ts | 111 +++- - .../server/src/server/agent/tools/paseo-tools.ts | 22 +- - .../server/src/server/agent/tts-manager.test.ts | 80 ++- - packages/server/src/server/agent/tts-manager.ts | 63 ++- - .../server/authorization/operation-permissions.ts | 2 + - .../src/server/message-receipts/index.test.ts | 172 ++++++ - .../server/src/server/message-receipts/index.ts | 163 +++++- - packages/server/src/server/session.test.ts | 152 +++++- - packages/server/src/server/session.ts | 242 ++++++--- - .../src/server/session.voice-mcp-config.test.ts | 39 +- - .../server/src/server/session/voice/index.test.ts | 5 - - packages/server/src/server/session/voice/index.ts | 64 ++- - .../session/voice/voice-recognition-issue.test.ts | 58 ++ - .../session/voice/voice-recognition-issue.ts | 25 + - .../src/server/session/voice/voice-session.test.ts | 396 ++++++++++++-- - .../src/server/session/voice/voice-session.ts | 516 +++++++++++++----- - .../session/voice/voice-turn-controller.test.ts | 29 + - .../server/session/voice/voice-turn-controller.ts | 18 +- - .../server/src/server/test-utils/session-stubs.ts | 1 + - packages/server/src/server/voice-config.ts | 40 +- - packages/server/src/server/voice-types.ts | 2 +- - .../websocket-server.relay-reconnect.test.ts | 35 ++ - packages/server/src/server/websocket-server.ts | 100 +++- - 67 files changed, 4968 insertions(+), 714 deletions(-) -``` - -## Complete source-to-port ledger - -`unchanged` means selected source bytes retained, or an existing upstream/TM02 owner retained where the rationale says so. `adapted` means feature hunks adopted into current owners. `excluded` means no TM04 delta for that path. Local-only files have no source blob. Blob hashes are computed from committed HEAD; absent files are explicit. - -| Path | Source blob at integration 51fb7693d | Effective selected commit:blob | Local HEAD blob | Disposition and rationale | -| --- | --- | --- | --- | --- | -| `docs/development.md` | `c4175ccca3794f29074642cb6a992d3857acd3d0` | `e309257e613e:c4175ccca3794f29074642cb6a992d3857acd3d0` | `c5ed2896dfa56a59c0a0959be5328ad40a7e6250` | excluded: Source docs describe source admission/defaults; repository owners and this evidence describe the adapted contract. | -| `docs/queue-mirroring.md` | `23e21f6315f7dfc385fb5983df6f8e882a7b74fa` | `e309257e613e:d1b642a8cb7e102d9c8d222cb6ad785c23833443` | `14438c957daad2de7e4b9b6cecb4f0fb28fc2528` | excluded: Source docs describe source admission/defaults; repository owners and this evidence describe the adapted contract. | -| `docs/voice-input.md` | `fbfb912b30cc81b8842ae9c8fd7326cbb43bb3a0` | `e309257e613e:ee45b4f6195bd7552f95cf6b123b7b3b7a33782b` | `absent` | excluded: Source docs describe source admission/defaults; repository owners and this evidence describe the adapted contract. | -| `packages/app/scripts/generate-voice-failure-phrases.mjs` | `absent` | `e309257e613e:dba28c9705de91dcbfe3c939e6b1e29c834bdb97` | `dba28c9705de91dcbfe3c939e6b1e29c834bdb97` | unchanged: Selected source feature content retained byte-for-byte. | -| `packages/app/src/components/realtime-voice-overlay.test.tsx` | `94552a2910c562c9c943b163d71116d84e3d3552` | `e309257e613e:ea424d93bb52b00dc00f9921a58f0c8528d775a2` | `8bdf287c6049eeceb1d1e2766e302bfe2d270d3e` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/app/src/components/realtime-voice-overlay.tsx` | `b333d1782e0fb8e0be437b012d30c60c2891bae3` | `e309257e613e:36cf33406476467eac206999ad479412f12b0baa` | `fef244eadca281c669e3156eb154b4da6f1b0101` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/app/src/composer/index.tsx` | `86f083914d6af091abffa1780a016d1b5280269c` | `e309257e613e:b9e64ab5df9d6fcf6cfd9cfc7520cdaead31344e` | `abf61c2003961799f6eb451a756fa14f073af702` | adapted: Existing composer owner; mid-turn voice capability gate and explicit interrupt control only, no send default or TM03 UI. | -| `packages/app/src/composer/input/input.tsx` | `c323910bfb10ac47a2cf16f2ff3e6cdcaa46269f` | `e309257e613e:035f4947c28246fc0e0e7c4962277f99f5e842ee` | `a7607da8d7cb5fd1c9ef53be29952aaa9656d281` | adapted: Existing composer owner; mid-turn voice capability gate and explicit interrupt control only, no send default or TM03 UI. | -| `packages/app/src/composer/input/state.test.ts` | `89e1f4bd4003edb013a039ef917d529c7b643d03` | `e309257e613e:89e1f4bd4003edb013a039ef917d529c7b643d03` | `9858f99dbfb2872f47ed59dc53ae8a0f7102ef4d` | adapted: Existing composer owner; mid-turn voice capability gate and explicit interrupt control only, no send default or TM03 UI. | -| `packages/app/src/composer/input/state.ts` | `3ef85bedc1bed5589c407a51f6349d07d66f094d` | `e309257e613e:3ef85bedc1bed5589c407a51f6349d07d66f094d` | `be7afb9a4aaaebd0d6e7813acb0e8441b7da208c` | adapted: Existing composer owner; mid-turn voice capability gate and explicit interrupt control only, no send default or TM03 UI. | -| `packages/app/src/contexts/session-context.tsx` | `d8d84e20b1b9561728480bc71a00f36e69148947` | `e309257e613e:1cef5e8e5acaa72415d1751348b686d0b8c784d5` | `11732f4ea39151054bfb29905911d01e0e428d59` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/app/src/contexts/voice-context.tsx` | `5c72b8b1c66ed51b79e95d3234a6d0ec5911ef9e` | `e309257e613e:bede29aa4723ab772575585bba251f3720f3caed` | `543999a295e5b7291e81293c413029c362f614ed` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/app/src/i18n/resources/ar.ts` | `0f978044b3c40a264989b1422665be9abc7fe7e0` | `e309257e613e:660848890209ea71a9e29ef6f7df3aed6fbacce1` | `7b91b233e2872fce3f51a4a0361caa3cc5f835ef` | adapted: Source voice failure/status/action copy in existing locales; preserve other product text. | -| `packages/app/src/i18n/resources/en.ts` | `14569fbb094cb001a794205f2c28f9d2b470121d` | `e309257e613e:f0624a546653a9cffe221960f7b8ba7cbdbf559e` | `28ff7e89df0649840a9e8e6731d90301adcbf170` | adapted: Source voice failure/status/action copy in existing locales; preserve other product text. | -| `packages/app/src/i18n/resources/es.ts` | `f6f4abaa36ed6b6d5a09cc8b5f1e529b4f4dfba6` | `e309257e613e:fcdb1d73bd1027bfce7b46746205256d9e2f7929` | `26178a0cae4a842ef09dd94f7ce666b067d66d63` | adapted: Source voice failure/status/action copy in existing locales; preserve other product text. | -| `packages/app/src/i18n/resources/fr.ts` | `b494c25b9d36e5ab2cc3108fba01b35bb6e0f97c` | `e309257e613e:f733508ecbea0bc01e8030b9c8d9222bbad59893` | `379f6ca27cf75c22eee5488b815a7734d4c621b0` | adapted: Source voice failure/status/action copy in existing locales; preserve other product text. | -| `packages/app/src/i18n/resources/ja.ts` | `628d7bf1e59ccaefba7eb7568b38e76a9369579c` | `e309257e613e:184802bfef183d7297ddc7216c95b29aee569ac6` | `6e3478809b150b8cc2e3c1173afb65df9e065e0d` | adapted: Source voice failure/status/action copy in existing locales; preserve other product text. | -| `packages/app/src/i18n/resources/ko.ts` | `e0bebb76126156648f480ebcc9920aa63a0b74e3` | `e309257e613e:6d3a1e303ad128ca557b1c5c81f3b5e2a4b0b588` | `9beba8a8dfb497e1c1fedcad92bb244d75abe01c` | adapted: Source voice failure/status/action copy in existing locales; preserve other product text. | -| `packages/app/src/i18n/resources/pt-BR.ts` | `1514a4af6d00e28f89a1b2eb651331b85bd6fdc6` | `e309257e613e:235ba18b024ec320137285bf53f02f1cf0a9830d` | `786a276cd2c5a5abf5ca668555fcc50bf2802434` | adapted: Source voice failure/status/action copy in existing locales; preserve other product text. | -| `packages/app/src/i18n/resources/ru.ts` | `3cd8fabd425d3fc584c6968b8c31cf8ea45cdaad` | `e309257e613e:0122748cebe0577002b98f0fa07804636bcb1d0a` | `609c647e2daad5eef04bd84d4cacca16a03b0e5d` | adapted: Source voice failure/status/action copy in existing locales; preserve other product text. | -| `packages/app/src/i18n/resources/zh-CN.ts` | `7c34a6a112bc8e15d5a1a8766a8177d56f4a964c` | `e309257e613e:27b1afe7d31533f073d5d747af953aa55714c4aa` | `329e9ba07339c71669f171ef646cbdbfa188420a` | adapted: Source voice failure/status/action copy in existing locales; preserve other product text. | -| `packages/app/src/voice/audio-engine-types.ts` | `03108b5cf67db57e0ffd6382788d9e8681c5b1bd` | `e309257e613e:e06a1b41b37469b17069513b473cf95e8d49c4bf` | `03108b5cf67db57e0ffd6382788d9e8681c5b1bd` | unchanged: Existing upstream/TM02 owner retained; no duplicate implementation or configuration override. | -| `packages/app/src/voice/audio-engine.native.test.ts` | `78c23186ec89e9250f28b51eba88bab043258d1b` | `e309257e613e:78c23186ec89e9250f28b51eba88bab043258d1b` | `3e2b22e4c6d7a8656b906bda6414b05c8ef67c3d` | adapted: Preparation cancellation adapted to existing foreground native API; no PR14 playback-complete/background module event. | -| `packages/app/src/voice/audio-engine.native.ts` | `ec5806e1a9b3524ad3fa96a96356e9ac2190d554` | `e309257e613e:ec5806e1a9b3524ad3fa96a96356e9ac2190d554` | `09a8b29937a0811bf071e51ec9758dfc8fdfb66d` | adapted: Preparation cancellation adapted to existing foreground native API; no PR14 playback-complete/background module event. | -| `packages/app/src/voice/audio-engine.web.test.ts` | `absent` | `e309257e613e:absent` | `239bc93ebba626e2c184947ce5d4d5b6b027a917` | adapted: Local host integration/regression; no source file. | -| `packages/app/src/voice/audio-engine.web.ts` | `0453c0ae331974b2731a2eb243da053bf41997a4` | `e309257e613e:49645d060d1b76039cb2cecb19f1868a5ddff257` | `5c57543c9e19a3e2a4b9190cfe49a232975417ad` | adapted: PR22 track-loss callback plus local browser preparation cancellation/regression. | -| `packages/app/src/voice/input-receipt-cue.ts` | `absent` | `e309257e613e:a5f5994202d57a23a7d9a1dc30e979b7571cc165` | `a5f5994202d57a23a7d9a1dc30e979b7571cc165` | unchanged: Selected source feature content retained byte-for-byte. | -| `packages/app/src/voice/microphone-cue.ts` | `c9345c989b6a6e45b6a519d5d67b91c1698ec13a` | `e309257e613e:c9345c989b6a6e45b6a519d5d67b91c1698ec13a` | `absent` | unchanged: Existing upstream/TM02 owner retained; no duplicate implementation or configuration override. | -| `packages/app/src/voice/realtime-voice-config.ts` | `698c80cbec83c3510e4c40b4dd1509fb3096ebb1` | `e309257e613e:698c80cbec83c3510e4c40b4dd1509fb3096ebb1` | `698c80cbec83c3510e4c40b4dd1509fb3096ebb1` | unchanged: Existing upstream/TM02 owner retained; no duplicate implementation or configuration override. | -| `packages/app/src/voice/voice-failure-cue.ts` | `absent` | `e309257e613e:4b775dcc62c489d90910169a08a68d01ade895fd` | `4b775dcc62c489d90910169a08a68d01ade895fd` | unchanged: Selected source feature content retained byte-for-byte. | -| `packages/app/src/voice/voice-failure-phrases.mulaw.ts` | `absent` | `e309257e613e:9c056e7ccc1684579b107b4c6d7e989e88993d27` | `9c056e7ccc1684579b107b4c6d7e989e88993d27` | unchanged: Selected source feature content retained byte-for-byte. | -| `packages/app/src/voice/voice-failure.test.ts` | `absent` | `e309257e613e:5e43aac90cdffb91fcf08b7bedeb127812507b3f` | `5e43aac90cdffb91fcf08b7bedeb127812507b3f` | unchanged: Selected source feature content retained byte-for-byte. | -| `packages/app/src/voice/voice-failure.ts` | `absent` | `e309257e613e:b98b2b391cc0ee50927c83b9de5a30d61f3f112f` | `b98b2b391cc0ee50927c83b9de5a30d61f3f112f` | unchanged: Selected source feature content retained byte-for-byte. | -| `packages/app/src/voice/voice-runtime.test.ts` | `e2a8b21e870350efaf5801d2a55e7fa4e1922c46` | `e309257e613e:e9b3b1858377f6137955f5b0ce74386eb748c214` | `a50b777ba1d310d96412bebd1dc7236acc42e277` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/app/src/voice/voice-runtime.ts` | `6f7eefdd522c6d870392a492e5037efe8dc0c5dd` | `e309257e613e:cd604d57da64c3aa150f3ca5d3c49c4e88dfcdd5` | `d68cbdfa57d602b690b0c9740a182562c2f0b133` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/app/test-stubs/lucide-react-native.ts` | `f4cab7bd9ba7ee5dd1f36c2a7aaeb21ecdfcf8a6` | `e309257e613e:f4cab7bd9ba7ee5dd1f36c2a7aaeb21ecdfcf8a6` | `f093a481a03efb99d7ec82f290e04973064d3b51` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/app/tsconfig.json` | `bc1d0595f849ab36fe5d4559a5d7b565a326b687` | `e309257e613e:bc1d0595f849ab36fe5d4559a5d7b565a326b687` | `1098a159e130a4c8610e46f7b6958d2a4c7b2dde` | unchanged: Existing upstream/TM02 owner retained; no duplicate implementation or configuration override. | -| `packages/client/src/connection/index.ts` | `d939b3c72b58fdec813dae4999c14f3164fb4ded` | `e309257e613e:d939b3c72b58fdec813dae4999c14f3164fb4ded` | `39d54b221c8b18de5048ed0cb7a88b61818f5222` | adapted: Optional wire additions, separate durableVoiceInputV1 gate, current client/authorization owners; verbal mute excluded. | -| `packages/client/src/daemon-client.ts` | `01d1f698118c51f389342868f594cde9971a7354` | `e309257e613e:35603f6d693e5f61e76429256a0bef01f9dba0f1` | `3b27fff58c48361912e517d79fff8f4229cbcb8e` | adapted: Optional wire additions, separate durableVoiceInputV1 gate, current client/authorization owners; verbal mute excluded. | -| `packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/AudioEngine.kt` | `b08f90262e97f0dbdb6bfebc23aba536e0479486` | `e309257e613e:b08f90262e97f0dbdb6bfebc23aba536e0479486` | `a6fe25303e40efa8ad93846baf65a6eb0f870415` | excluded: TM06/native substrate excluded; base blob retained. | -| `packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/ExpoTwoWayAudioModule.kt` | `86978edfc57b13eb6deaa92af920017e545beb65` | `e309257e613e:86978edfc57b13eb6deaa92af920017e545beb65` | `f9b107c99f8a9679a68607b01ed39b792dea2901` | excluded: TM06/native substrate excluded; base blob retained. | -| `packages/expo-two-way-audio/ios/AudioEngine.swift` | `0759afbe27d2f4fcf907908e5dd24dfe91990192` | `e309257e613e:0759afbe27d2f4fcf907908e5dd24dfe91990192` | `d385dab7aa018cd0df9666ad8b44b000b37eed56` | excluded: TM06/native substrate excluded; base blob retained. | -| `packages/expo-two-way-audio/ios/ExpoTwoWayAudioModule.swift` | `b5ab94dfcb60566677955f70885119ef7be8d051` | `e309257e613e:b5ab94dfcb60566677955f70885119ef7be8d051` | `baec747995f7d83be46baf51a55720e5fef31fa0` | excluded: TM06/native substrate excluded; base blob retained. | -| `packages/expo-two-way-audio/src/events.ts` | `1cf984229fa0e8f196cbe89839345d8c94f75745` | `e309257e613e:1cf984229fa0e8f196cbe89839345d8c94f75745` | `c3fb0176a5cb97f9d9773d597a69e923f5a09488` | excluded: TM06/native substrate excluded; base blob retained. | -| `packages/protocol/src/client-capabilities.ts` | `0947b810279475a0fefb55cdb76f9baa5ecc7191` | `e309257e613e:0947b810279475a0fefb55cdb76f9baa5ecc7191` | `710a0646fc1853637f8fa18ed3cd33dc5888c982` | adapted: Optional wire additions, separate durableVoiceInputV1 gate, current client/authorization owners; verbal mute excluded. | -| `packages/protocol/src/messages.ts` | `e6c0dc88a16c4afa280583cb03d1c4775aac7ab1` | `e309257e613e:e3d4ac1e6a0a7e334eeebc5270f101a9dfc4f17e` | `4b5fb1bdb734be1f077312d5b0737f181d9a2b35` | adapted: Optional wire additions, separate durableVoiceInputV1 gate, current client/authorization owners; verbal mute excluded. | -| `packages/protocol/src/messages.voice-flow.test.ts` | `absent` | `e309257e613e:absent` | `63e82ca2b1dbced659362dac5f627180f902973b` | adapted: Local host integration/regression; no source file. | -| `packages/protocol/src/messages.voice-mute.test.ts` | `0eb8d127a2b49f608c6224608e2f1b4fdaeac0e6` | `e309257e613e:6d142f63a29a40cbfc7913bbf7bed3c35a58d474` | `absent` | excluded: TM05 verbal mute/control contract excluded; upstream/base behavior retained. | -| `packages/server/src/server/agent-queue/send-or-queue.test.ts` | `ec208522791ee9286b9495d5609dbac6814ddc4f` | `e309257e613e:f0f1787f5e55eefeb63d67c42188d79bcc4cd8c2` | `58bcb93eee567993142da1c0b9416360c8a684c3` | adapted: TM-02 admission, per-attempt receipts, permission/reservation fences, durable logical speech identity and scoped reads. | -| `packages/server/src/server/agent-queue/send-or-queue.ts` | `95561c9fbe2daf7416ea65b02bbeb1bbc9b87e3e` | `e309257e613e:72e7efbed249f1ed9af4b8403fb7b16c576ec8f2` | `e200fcc431445e82cc8a78b34b7ad4837fef1d13` | adapted: TM-02 admission, per-attempt receipts, permission/reservation fences, durable logical speech identity and scoped reads. | -| `packages/server/src/server/agent-queue/service.test.ts` | `d60a755ded32ca9947d5b6064c5cebd9410c6d15` | `e309257e613e:71b2ffda410093cffc3ccd497a060ce4807e671a` | `37e257828dbd4343a54c9e21b35700643c8f2169` | adapted: TM-02 admission, per-attempt receipts, permission/reservation fences, durable logical speech identity and scoped reads. | -| `packages/server/src/server/agent-queue/service.ts` | `ba9ff72ebb4b714417911f2d346e2130fa0ee05f` | `e309257e613e:fa8d99007fd6073d7858678be3190d37ea0622b4` | `afbc6928dbf098ff037e42d5e9ceb761ccfb3c52` | adapted: TM-02 admission, per-attempt receipts, permission/reservation fences, durable logical speech identity and scoped reads. | -| `packages/server/src/server/agent-queue/store.ts` | `7039d635f719ee793e0195ced9bdc795af4c67de` | `e309257e613e:90469808527900aa3d803dab8bbae196dc89a093` | `a32667166c0617314d8b0b10083db257534d2633` | adapted: TM-02 admission, per-attempt receipts, permission/reservation fences, durable logical speech identity and scoped reads. | -| `packages/server/src/server/agent/agent-manager.ts` | `c40f776a64f362376aa29e550843cc9c2ff2a661` | `e309257e613e:677cd917acba49fb1b57bce94c3f1b0f1c010e79` | `1fc21fdc1a0b7f417936a06e5ff987c66f86e95e` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/agent/agent-prompt.test.ts` | `08bd66a79c6d14a0b763e2ebf89f8214b0fcce19` | `e309257e613e:f8414825cf93a1d46bea33c9ed6b1c678c5c94f6` | `9add56dac2d3ac8416240ec4cfa95a0d18ba7705` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/agent/agent-prompt.ts` | `3ccbf030449989219708333f5db2013c3095eed5` | `e309257e613e:6c5af0e2a6b78c9587f8364bb6228e2296cd793f` | `02a04c759fa392d056a52d3169cdc97c899a4154` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/agent/agent-sdk-types.ts` | `e2fb9779b98814fb3a7bedae49cac40cb4dbdfdb` | `e309257e613e:d6d4ed9d50606b5550d276345095fb2bc3ffd74e` | `8e734929de499c669fc9a2e0293c4fe18a02bfbe` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/agent/mcp-server.test.ts` | `e1441e77dad8129b2bfd3fe080810ded7b5a1c3c` | `e309257e613e:ebc82f98fceda6d038a5e191b793370e7c17c374` | `a39ff7aef2dc555dc1c90e6fff923941c328bda0` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/agent/paseo-tool-policy.test.ts` | `d5bc6c648bd865e92cc88b53310fad95719e2e3c` | `e309257e613e:0d3718e25a7ad3459e621491b45701e223f91185` | `d5bc6c648bd865e92cc88b53310fad95719e2e3c` | excluded: Preserve existing speak-tool policy; source default/policy rewrite rejected. | -| `packages/server/src/server/agent/paseo-tool-policy.ts` | `1089fb76e81c5317853106452fb3a2831eae0be2` | `e309257e613e:8914249039d7232233cee972152e443aa46b9f3b` | `1089fb76e81c5317853106452fb3a2831eae0be2` | excluded: Preserve existing speak-tool policy; source default/policy rewrite rejected. | -| `packages/server/src/server/agent/providers/claude/agent.voice-history-regression.test.ts` | `6dab8d205cb9fd5b2c6194524f962ac3ca3d52db` | `e309257e613e:6dab8d205cb9fd5b2c6194524f962ac3ca3d52db` | `6dab8d205cb9fd5b2c6194524f962ac3ca3d52db` | unchanged: Existing upstream/TM02 owner retained; no duplicate implementation or configuration override. | -| `packages/server/src/server/agent/tools/paseo-tools.ts` | `2de1a86454e07114012ccd34c422dc7a4102ccb4` | `e309257e613e:15799bf4612c6f3417b0d07c1350ff3daf7ebc68` | `c7ea338b2a17ad23bbf02c7407a3c45376dcdcd4` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/agent/tts-manager.test.ts` | `a58478c67c2878b52873a4180ee11b8fb21af196` | `e309257e613e:a58478c67c2878b52873a4180ee11b8fb21af196` | `98da7af9aa4f25444c7deb90f1bd84359073f3dc` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/agent/tts-manager.ts` | `37b1af9f084bde584bc2b9cf8a31d11b3fbe472c` | `e309257e613e:37b1af9f084bde584bc2b9cf8a31d11b3fbe472c` | `37b1af9f084bde584bc2b9cf8a31d11b3fbe472c` | unchanged: Selected source feature content retained byte-for-byte. | -| `packages/server/src/server/authorization/operation-permissions.ts` | `4a85d25ef3c52af1d98eee1258773b6e32ad6646` | `e309257e613e:2e30b67a91c6c61c91e855980091188a8cba2e15` | `698316df0c7fc76c7f98b8d8d1b1a9dc6739515b` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/bootstrap.ts` | `87102b339a5fa7cef74908797fdd4b8e05444d5b` | `e309257e613e:5b04f505058395c78a7c7e96cdfc584ec75685fe` | `e73a9fd7ff74426e21c24dacabdfa75ccfd985e2` | excluded: Ad-hoc real-provider proof injection removed; provider checks belong to humans. | -| `packages/server/src/server/message-receipts/index.test.ts` | `10c1615a6a0b3f99c48766cbdffb3f00199c51fa` | `e309257e613e:4507429ebf92835c818c8f3c1f6a8b07249048c5` | `44390941c16b9a84b253c8d330464bfb5fa1be0f` | adapted: TM-02 admission, per-attempt receipts, permission/reservation fences, durable logical speech identity and scoped reads. | -| `packages/server/src/server/message-receipts/index.ts` | `6103160b12d4cdef07c39506746e9ddd467d2be0` | `e309257e613e:0d8f297f543605bf074f6ae5bbf4659155b8ae1b` | `c5d7c29122bd18af1183a1157930bb0640417f90` | adapted: TM-02 admission, per-attempt receipts, permission/reservation fences, durable logical speech identity and scoped reads. | -| `packages/server/src/server/session.test.ts` | `ab43c023ccfce27b881d91d0456d3af306955811` | `e309257e613e:ab43c023ccfce27b881d91d0456d3af306955811` | `e3d5e622016abeb4e51aa2ecec9fc317a617ec11` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/session.ts` | `3fbb888b818c941e45832cc16766ff5e460f850a` | `e309257e613e:97ad8e7caf518f6de4f609982b64a8e097349c99` | `b2d15b85b46ed85d6a26d92afe18b083ca502295` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/session.voice-mcp-config.test.ts` | `98b1d41020a7bd507ad4efb0867d2f37a7b95d92` | `e309257e613e:fdf47fddbd34d1cc404bcde4b6ad6f0d4d629920` | `3ead2469027a9a6c1f90216df26725ad78a1ac67` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/session/voice/index.test.ts` | `043b759d1efa2739f895c041e52f9d108ef9b3a7` | `e309257e613e:7556529bce53636b189072ae84c0e1b8c99743b6` | `7556529bce53636b189072ae84c0e1b8c99743b6` | unchanged: Selected source feature content retained byte-for-byte. | -| `packages/server/src/server/session/voice/index.ts` | `760cdd81b16e761f16b2c22f07a4a22671d761fc` | `e309257e613e:536a54ada8ec4a27b887a68720835203cd830dcc` | `bdbb8f2c40d5212c3ee2798ac2141caa2854ac48` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/session/voice/voice-input-command.ts` | `8b1078249deb98386d0d41b2a2a5b1ac76f5435b` | `e309257e613e:8b1078249deb98386d0d41b2a2a5b1ac76f5435b` | `absent` | excluded: TM05 verbal mute/control contract excluded; upstream/base behavior retained. | -| `packages/server/src/server/session/voice/voice-recognition-issue.test.ts` | `absent` | `e309257e613e:f322ed67ce105eadc27c58cbd25320ba555d2b7a` | `f322ed67ce105eadc27c58cbd25320ba555d2b7a` | unchanged: Selected source feature content retained byte-for-byte. | -| `packages/server/src/server/session/voice/voice-recognition-issue.ts` | `absent` | `e309257e613e:708121068a1f3b0f9425d397e8e83adda527c6b0` | `708121068a1f3b0f9425d397e8e83adda527c6b0` | unchanged: Selected source feature content retained byte-for-byte. | -| `packages/server/src/server/session/voice/voice-session.test.ts` | `a45728aaa642caf23de7a95ecc44b39bc2f4a16d` | `e309257e613e:bbb92ceecb5f191ea0466f9c2c6fb0d8079f5e65` | `c7c3d0049e3bdeb6c17139958401cf5bc4e63282` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/session/voice/voice-session.ts` | `8d92da8c16dbe18619a2cae04c12a77d45d48037` | `e309257e613e:5e24fb2e82665bf67c7e85861230fafa1334636a` | `b129ec1a06c2a7f011b88e94429a92d15cd850d5` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/session/voice/voice-turn-controller.test.ts` | `32ec932f36fd5c7e4e7c437a8f4e7cc876e96c32` | `e309257e613e:60d9be469e6bb2549f77527c346a7a84507cf4c7` | `e3badb663dcb1ba86d810f2246600001e64df59c` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/session/voice/voice-turn-controller.ts` | `4b177c7a1594ad629c26f9e4a302fd8175192f4b` | `e309257e613e:58e53c6b1934eaed59de66abd5d339f9e32b0489` | `8d588e17ad3be71d4b4776f0ce73bbdedd7f7ed2` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/test-utils/session-stubs.ts` | `1c9868604284f79d42f8b5510090f376ec51c0cd` | `e309257e613e:1c9868604284f79d42f8b5510090f376ec51c0cd` | `212166a96f275e67e76f807c8c3d64af06ff3f2f` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/test-utils/voice-concurrency-proof.ts` | `absent` | `e309257e613e:22b13f760f98d9896e2a4b9ddb0897c838668de1` | `absent` | excluded: Ad-hoc real-provider proof injection removed; provider checks belong to humans. | -| `packages/server/src/server/voice-config.ts` | `d8cb1992f4fc1d195da10e388eca2dd960be0b89` | `e309257e613e:6ff552a5462963821f81706d70c70b1759bd0579` | `00a17607f06fb045bdf40783c6f217c7048a851e` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/voice-types.ts` | `9533b10c38e2517def5c133ea04e8341fd7c52f4` | `e309257e613e:8d74af62588f5e949a48da8e19ff9466735e87ad` | `8d74af62588f5e949a48da8e19ff9466735e87ad` | unchanged: Selected source feature content retained byte-for-byte. | -| `packages/server/src/server/websocket-server.relay-reconnect.test.ts` | `25acb9946b75a5fbf9e29c626d0ab0cc15f6f77f` | `e309257e613e:25acb9946b75a5fbf9e29c626d0ab0cc15f6f77f` | `d6e78935058490f38fb4c174058990822ca97244` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/websocket-server.ts` | `ca0f2b0498329f4b8c95b4b5ee3f3c50c82931ca` | `e309257e613e:de6ecf0ba448abbc3c731197b75b01a46d6b30ae` | `d82604e6ace82585313393e852b86c8c717ea957` | adapted: Selected voice behavior adopted into current upstream/custom owners; local lifecycle/transport/receipt regressions. | -| `packages/server/src/server/workspace-same-cwd-isolation.e2e.test.ts` | `139f8a37955c4d7f347b2007f11a7b465df519b6` | `e309257e613e:0402189ea27603767b86f1d05752839a623184fb` | `139f8a37955c4d7f347b2007f11a7b465df519b6` | excluded: Unrelated workspace/provider end-to-end proof excluded. | -| `public-docs/mcp.md` | `a52327174a12c7d0550b99e01977fe917c36114b` | `e309257e613e:cdd17d7d0cfbf3480bb92c798e67255524ac7c2d` | `a52327174a12c7d0550b99e01977fe917c36114b` | excluded: Source docs describe source admission/defaults; repository owners and this evidence describe the adapted contract. | diff --git a/fork/plans/tmad-port/evidence/TM-07.md b/fork/plans/tmad-port/evidence/TM-07.md deleted file mode 100644 index 2e88d58e208..00000000000 --- a/fork/plans/tmad-port/evidence/TM-07.md +++ /dev/null @@ -1,263 +0,0 @@ -# TM-07 — Native Find wrapper (evidence) - -## Identity - -| Field | Value | -| --- | --- | -| Report ID | TM-07 | -| Branch | `intake/tmad-native-find` | -| Base SHA | `6166a7aca5e3184e8ab505caad28f6a595816414` (`v0.11.0-beta.3`) | -| Final HEAD SHA | `5f3634ad43256c18f9f41667348c65fe1b03d7f4` | -| Declared base kind | Release-based (per brief) | -| Removal group | Native Find (TM-07 alone) | -| Runtime requirements | None beyond the pinned release. No Stream dependency in either direction. | - -### Commits - -``` -5f3634ad4 feat(chat-find): native Find wrapper, matches and viewport -``` - -Single commit. Trailers: `Source-Repo: tmad4000/paseo`, `Source-Commit: 51fb7693d`, `Port-Feature: TM-07`. - -### Allowed-ancestors check - -``` -git merge-base --is-ancestor custom HEAD -> not an ancestor (PASS) -git merge-base --is-ancestor mine HEAD -> not an ancestor (PASS) -``` - -Verified before and after commit. - -### Independence from Stream - -``` -git diff 6166a7aca..HEAD -- packages/app/src | rg -i "companion|updateCompanionEntry|add_pin|add_q_and_a|agentPanel.stream" - -> no matches -rg -i "companion|stream-feed|selectedView" - -> no matches -``` - -TM-07 introduces no Stream import, RPC, capability, store or type. Conversely, nothing in -this branch requires TM-07, so disabling TM-07 restores the beta.3 tree apart from this -commit. The two branches are independent in both directions. - -## Files changed - -21 files, +499 / -9. - -``` -packages/app/src/agent-stream/chat-find/index.tsx 174 +++++- -packages/app/src/agent-stream/chat-find/matches.test.ts 22 ++ (new) -packages/app/src/agent-stream/chat-find/matches.ts 23 ++ (new) -packages/app/src/agent-stream/chat-find/native-viewport.test.ts 66 ++ (new) -packages/app/src/agent-stream/chat-find/native-viewport.ts 84 ++ (new) -packages/app/src/agent-stream/strategy-native.tsx 39 ++ -packages/app/src/i18n/resources/{ar,en,es,fr,ja,ko,pt-BR,ru,zh-CN}.ts 2 + each -packages/app/src/screens/workspace/workspace-desktop-tabs-row.tsx 5 + -packages/app/src/screens/workspace/workspace-screen.tsx 25 + -packages/app/src/screens/workspace/workspace-tab-menu.ts 24 +- -packages/app/src/screens/workspace/workspace-tab-trailing-accessory.test.tsx 1 + -packages/app/src/screens/workspace/workspace-tab-trailing-accessory.tsx 4 + -packages/app/src/stores/agent-view-store.ts 23 ++ (new) -``` - -## Source -> port ledger - -### Core feature files (blob-identical to source) - -`git rev-parse 51fb7693d:` vs `git rev-parse HEAD:`. - -| Source path | Source blob | Local blob | Disposition | -| --- | --- | --- | --- | -| `packages/app/src/agent-stream/chat-find/index.tsx` | `ee2a2a58850608e5d03a8ae0318af27518bf2f7c` | `ee2a2a58850608e5d03a8ae0318af27518bf2f7c` | **unchanged** | -| `packages/app/src/agent-stream/chat-find/matches.ts` | `ce070d6771c1b7a31013dca904bd33d3206b7c48` | `ce070d6771c1b7a31013dca904bd33d3206b7c48` | **unchanged** | -| `packages/app/src/agent-stream/chat-find/matches.test.ts` | `13fc31138f5004c0b0b7f63078f6e3c892ed64b1` | `13fc31138f5004c0b0b7f63078f6e3c892ed64b1` | **unchanged** | -| `packages/app/src/agent-stream/chat-find/native-viewport.ts` | `269fc7a9ba3f0e54f92d7b16c65c99f10beb3744` | `269fc7a9ba3f0e54f92d7b16c65c99f10beb3744` | **unchanged** | -| `packages/app/src/agent-stream/chat-find/native-viewport.test.ts` | `685a7c89254276343aec0f40f148eea1af8a59d5` | `685a7c89254276343aec0f40f148eea1af8a59d5` | **unchanged** | -| `packages/app/src/agent-stream/strategy-native.tsx` | `5256ffaa2818223e23a922ff025ef7fbc73b1dc8` | `5256ffaa2818223e23a922ff025ef7fbc73b1dc8` | **unchanged** | - -All six are byte-identical, including the full native viewport and both carried test -files. `strategy-native.tsx` matching the source exactly means the source's changes to -that file were entirely Find-scoped; nothing was dropped. - -`chat-find/index.tsx` compiles unchanged against our tree because every import it -needs already exists in beta.3 (`@/pane-find`, `@/runtime/host-features`, -`@/runtime/host-runtime`, `@/timeline/timeline-sync-plan`, `./model`, -`../presentation`, `getStreamItemMessageId`, `StreamViewportHandle.scrollToMessage`). -No removal-scaffold was resurrected: `model.ts`, `model.test.ts`, `index.web.tsx`, -`viewport.web.ts`, `ranges.web.ts` and both web test files are untouched and their -blobs are identical between beta.3 and `51fb7693d`. - -### Adapted files (intentional delta) - -| Source path | Source blob | Local blob | Disposition and rationale | -| --- | --- | --- | --- | -| `packages/app/src/stores/agent-view-store.ts` | `69d25d1c17a6109180f4327d8b0ee87d874c3e96` | `f4fb214970426dd9d0f5b00cd9005a5d4711da9d` | **adapted.** New file in both trees. The source store also owns `selectedViews` / `setSelectedView` / `getSelectedView` for the Chat/Stream/Artifacts segmented control, which is Stream (TM-01) scope. Ported `findOpen` / `setFindOpen` only. TM-01 will need to add the selected-view fields back when it lands. | -| `packages/app/src/screens/workspace/workspace-tab-menu.ts` | `c3c266fb0d0f45f0e0f8c3db6f48fc705fd1d32e` | `bfd55d2eb4abf05f42778d9237685697c7003a7a` | **adapted.** Added `findInChat` label, `search` icon, `onFindInChat` input and the mobile Find entry. Excluded `viewArtifacts` and the `file-code-2` icon (Stream). The source gates both entries behind `surface === "mobile" && input.onViewArtifacts`; ours gates Find behind `surface === "mobile" && input.onFindInChat` so the entry appears without the artifacts sibling. Separator key is `find-in-chat-separator`. | -| `packages/app/src/screens/workspace/workspace-screen.tsx` | `c9445ddaabd3d16196303a267947f7c15decf533` | `28ef095a7450ea07e0a28531fe96bd22d9378b9c` | **adapted.** Ported `handleFindInChat` and threaded `onFindInChat` through `MobileWorkspaceTabSwitcher` -> `MobileWorkspaceTabOption` -> menu. Dropped the source's `setSelectedView(..., "chat")` call (Stream). Excluded `NavigationBackButton` (Recent-focus Back, separate feature), the `use-compact-time-ago` rename, and the `formatAgentTooltipActivity` helper. | -| `packages/app/src/screens/workspace/workspace-desktop-tabs-row.tsx` | `14e500cb5dc0d54a642cbff12b4453e1877be3a2` | `a3d833db6c6b293f73c88402523d211f32263b3a` | **adapted.** Added the `findInChat` label (required by `WorkspaceTabMenuLabels`) and the `search` icon case. Excluded `viewArtifacts` label, `FileCode2`, `formatAgentTooltipActivity`, `use-compact-time-ago`, `enabledOnMobile` and the `onPressIn` change. Desktop does not render the Find entry (mobile-gated); only the label and icon are needed there. | -| `packages/app/src/screens/workspace/workspace-tab-trailing-accessory.tsx` | `da51086cbf3ed2173510bc7b499cb0fd6b248f6c` | `576dd550ce022895bdeafde19090ecad305a3963` | **adapted.** Added `Search` icon + `search` case only. Excluded `FileCode2`. | -| `packages/app/src/screens/workspace/workspace-tab-trailing-accessory.test.tsx` | `8560f7c4cc79156f168eb53dc1288b00fbdbcb46` | `196a11813a1dd0d43c1ae8ec207b7305c02429f9` | **adapted.** Added the `Search: StubIcon` mock. Excluded `FileCode2: StubIcon`. | -| `packages/app/src/i18n/resources/{ar,en,es,fr,ja,ko,pt-BR,ru,zh-CN}.ts` | see per-file blobs below | see HEAD | **adapted.** Added `paneFind.updateHost` and `workspace.tabs.menu.findInChat` to all 9 locales. Excluded `workspace.tabs.menu.viewArtifacts` (Stream). Translations taken verbatim from source. | - -Locale blob deltas (source -> local), all `adapted`: - -| Locale | Source blob (12) | Local blob (12) | -| --- | --- | --- | -| ar | `0f978044b3c4` | `7c783d0532a4` | -| en | `14569fbb094c` | `494e07ff33f2` | -| es | `f6f4abaa36ed` | `1c47790a5a6b` | -| fr | `b494c25b9d36` | `c473acbb4048` | -| ja | `628d7bf1e59c` | `90ad8b25feda` | -| ko | `e0bebb761261` | `f0b4cbd45a08` | -| pt-BR | `1514a4af6d00` | `9770c486166e` | -| ru | `3cd8fabd425d` | `4660824860ff` | -| zh-CN | `7c34a6a112bc` | `71b8fe37ac18` | - -All nine are `adapted` for the same reason: two keys added, `viewArtifacts` omitted. - -### Excluded from the same source diff, with rationale - -| Excluded | Why | -| --- | --- | -| `agent-view-store.ts` `selectedViews` / `setSelectedView` / `getSelectedView` | Stream/Artifacts Chat-Stream segmented control. Would create a Stream dependency. | -| `workspace-tab-menu.ts` `viewArtifacts` entry + label + `file-code-2` icon | Stream. | -| `workspace-screen.tsx` `handleViewArtifacts` | Stream. | -| `workspace-desktop-tabs-row.tsx` `viewArtifacts` label, `FileCode2` | Stream. | -| `workspace-tab-trailing-accessory.tsx` `FileCode2` | Stream. | -| `view.tsx` `handlePin` / `handleQAndA` / `onPin` / `updateCompanionEntry` | Stream companion pins and Q&A. | -| `view.tsx` `ChatFindExpansion` around `UserMessage` | **Already present in beta.3** (`view.tsx:726`). Upstream already supplies it; no change needed. | -| `strategy.ts` / `strategy-web.tsx` / `view.tsx` `contentMaxWidth` -> `MAX_CONTENT_WIDTH` | Unrelated upstream layout change, not Find. | -| `presentation.ts` trailing-blank-line regex change + `presentation.test.ts` mermaid test removal | Unrelated upstream stream-rendering change. Removing the test would be a coverage regression. | -| `presentation.test.ts` `paseo`/`invoke` host-field removal | Plugin-host API churn unrelated to Find. | -| `chat-outline/*`, `web-virtualization*`, `turn-footer.tsx` | Stream/chat-outline changes. | -| `panel-store/index.ts` `restoreNavigationView` | Recent-focus Back (separate feature). | -| `workspace-route-state-views.tsx` archive-recovery simplification | Unrelated upstream change. | -| `workspace-desktop-tabs-row.tsx` `enabledOnMobile` / `onPressIn` | Unrelated upstream tab-chip change. | -| `agent-stream/chat-find/index.web.tsx`, `model.ts`, `model.test.ts`, `viewport.web.ts`, `ranges.web.ts`, both web tests, `types.ts` | Blobs already identical between beta.3 and `51fb7693d`; upstream already supplies them. No change required. | - -## Requirements coverage - -| Requirement | Implementation | Where | -| --- | --- | --- | -| History loading for matches outside the loaded window | `ChatFindModel.navigate` calls `operations.load` -> `getHostRuntimeStore().fetchAgentTimeline` with `planTimelinePromptJump`, then `waitForTarget` polls history listeners. Shared with web. | `chat-find/index.tsx` `load()` | -| Selected-row reveal / highlight | `createNativeFindViewport.reveal` calls `revealLoadedMessage` until the row mounts, then `viewportRef.current.scrollToMessage(messageId)`; `ChatFindExpansion` tints the selected row and lifts its render cap. | `native-viewport.ts`, `chat-find/index.tsx`, `strategy-native.tsx` | -| Invocation via existing tab menu "Find" (native) | `buildWorkspaceTabMenuEntries` adds a mobile `find-in-chat` item; `handleFindInChat` sets `findOpen`, focuses the agent tab via `openWorkspaceTabFocused` + `navigateToTabId`. | `workspace-tab-menu.ts`, `workspace-screen.tsx` | -| Cleanup on panel hide / unmount | `useEffect(() => () => model.close(), [model])` and `useEffect(() => { if (!active) close(); }, [active, close])` with `useRetainedPanelActive()`. | `chat-find/index.tsx` | -| Compiles and runs with no Stream code | Verified by grep (above) and by full-workspace typecheck. | — | -| New strings localized in every locale | `paneFind.updateHost` + `workspace.tabs.menu.findInChat` added to all 9 locales; `resources.test.ts` key-parity test passes. | `packages/app/src/i18n/resources/*` | - -The `agentHistorySearch` host-feature gate was carried from the source unchanged, -including its `COMPAT(agentHistorySearch)` comment. It is an existing upstream flag -(protocol `messages.ts:3615`), so no new wire field, RPC, capability or authorization -entry was added. `packages/server/src/server/authorization/index.test.ts` is therefore -not implicated; no protocol file was touched. - -## Commands run - -| Command | Result | -| --- | --- | -| `ONNXRUNTIME_NODE_INSTALL=skip npm ci` | PASS (EXIT=0) | -| `npm run build:client` | PASS (EXIT=0) | -| `npm run build:server` | PASS (EXIT=0) | -| `npx vitest run src/agent-stream/chat-find/matches.test.ts src/agent-stream/chat-find/native-viewport.test.ts` (packages/app) | PASS — 2 files, 7 tests | -| `npx vitest run src/agent-stream/chat-find/model.test.ts src/screens/workspace/workspace-tab-menu.test.ts src/screens/workspace/workspace-tab-trailing-accessory.test.tsx src/i18n/resources.test.ts` (packages/app) | PASS — 6 files, 64 tests | -| `npm run typecheck` (all workspaces) | PASS — 0 TS errors | -| `npm run lint -- <21 changed paths>` | PASS — 0 warnings, 0 errors on 30 files | -| `npm run format:files -- ` | PASS | -| pre-commit hooks (format:check, lint, typecheck) | PASS | -| `git merge-base --is-ancestor custom HEAD` / `mine HEAD` | PASS — neither is an ancestor | - -Logs: `/tmp/tmad-port/tm07-*.log`. - -### Reproduction - -```bash -for f in packages/app/src/i18n/resources/{ar,en,es,fr,ja,ko,pt-BR,ru,zh-CN}.ts; do - echo "$f src=$(git rev-parse 51fb7693d:$f) local=$(git rev-parse HEAD:$f)" -done -``` - -## Pre-existing failures (NOT caused by this port) - -1. **`npm run typecheck` before `build:server`** produced 401 `TS2307` errors, all - "Cannot find module `@getpaseo/server/*`" in `packages/cli`. Cause: a fresh worktree - with unbuilt workspace declarations. Resolved by `npm run build:server`; typecheck was - then clean across every workspace. Not a code failure. - -2. **`native-viewport.test.ts` first run** failed to resolve - `@getpaseo/protocol/tool-name-normalization` transitively via - `../presentation` -> tool-calls. Same root cause (unbuilt protocol/client `dist`). - Resolved by `npm run build:client`. Not a code failure. - -3. **pi-lens advisory**: two pre-existing `as unknown as` type assertions in - `workspace-desktop-tabs-row.tsx` (base lines 620 and 836) are reported as needing a - `SAFETY:` comment. Both lines are present verbatim in `v0.11.0-beta.3` - (`git show v0.11.0-beta.3:packages/app/src/screens/workspace/workspace-desktop-tabs-row.tsx`) - and are **not** in this commit's diff — this file's diff adds 5 lines, none of them - those. The repository's own gate, `npm run lint` (oxlint), reports **0 warnings and 0 - errors** on the file, so pi-lens is stricter than the project lint configuration. - Left unchanged as out-of-scope base code; recorded rather than silently patched. - -## Known gaps / deferred - -1. **No native device evidence.** No iOS simulator or Android run was performed. All - verification here is compile-time (typecheck) and unit-level (vitest under Node). - See "Native evidence still required" below. -2. **No browser/UI capture.** The e2e spec `packages/app/e2e/browser/chat-find.spec.ts` - covers the web wrapper only and its blob is identical between beta.3 and `51fb7693d`, - so it was not carried. It does not exercise the native path. -3. **`strategy-native.tsx` scroll behaviour is untested by a unit test.** The source - ships no test for `scrollToMessage` or `onScrollToIndexFailed`; the viewport's - interaction with a real `FlatList` is only covered by the source's `native-viewport` - test through an injected stub. Same coverage as source — not a regression, but it is - where device evidence matters most. -4. **Desktop tab menu has no Find entry.** By design: the entry is mobile-gated exactly - as in source, because web opens Find with Cmd+F. If a desktop-web gap is ever - reported, `findShortcutPlatform()` in `index.web.tsx` is the owner. -5. **TM-01 interaction.** When TM-01 lands, it will re-add `selectedViews` to - `agent-view-store.ts` and a `viewArtifacts` tab entry. That store is a shared seam: - two branches will touch `stores/agent-view-store.ts` and - `workspace-tab-menu.ts`. Expect a small adapted merge there, not a clean one. - -## Native evidence still required - -Run on an iOS simulator and an Android device/emulator before promotion. Per state: - -1. **Reachability.** Open a chat tab -> open the tab menu (mobile kebab) -> confirm - "Find in chat" appears with a search icon, is localized, and is tappable. -2. **Open + focus.** Confirm the Find widget opens with the text field focused, and - that tapping the same menu item for a background agent focuses that agent's tab and - opens Find there. -3. **Loaded match.** Query a term present in the on-screen history. Expect the - occurrence counter to read `1 of N`, the match to advance with next/previous, and the - selected row to be tinted. -4. **Historical match (the key case).** Query a term that only exists far above the - loaded window. Expect: the list scrolls to the row, the row mounts, the counter shows - the whole-chat position, and the tinted row is visible. Verify `onScrollToIndexFailed` - retry does not visibly jump-then-snap on a long chat with variable row heights. -5. **Live head match.** Query a term in the most recent assistant turn (rendered in the - inverted list header). Expect scroll-to-offset 0, not a wrong index. -6. **Wrap-around and zero matches.** Next/previous past the ends should wrap; a - no-match query should show "No matches" and not leave a stale tint. -7. **Cleanup.** Background the panel (switch tabs / open the Stream-free panel switcher) - and return: Find must be closed, no tint remaining, and reopening must show an empty - query. Unmount the agent tab mid-search and confirm no setState-after-unmount warning. -8. **Older host.** Connect to a daemon without `agentHistorySearch` and confirm the - widget stays reachable and shows the "Update the host to use Find" status rather than - hiding or erroring. -9. **Keyboard.** Confirm the on-screen keyboard does not cover the widget and that - dismiss/scroll still behaves with the widget open. -10. **Orientation / rotation** and both locales with non-Latin scripts (ko, ja, zh-CN) to - check the overlay's `left`/`right` insets and status text truncation. - -## Human decisions - -1. **Should Find appear in the desktop tab context menu?** Currently mobile-only, as in - source. No decision needed unless a desktop gap is reported. -2. **Store ownership.** `stores/agent-view-store.ts` will be a two-branch seam (TM-07 - `findOpen`, TM-01 `selectedViews`). The integrator may prefer to pre-declare a shared - owner or accept the adapted merge. Not blocking this port. -3. **Native evidence gate** is unmet and is the only thing standing between this branch - and P6 promotion. diff --git a/fork/plans/tmad-port/evidence/desvio-0.11.1-focused-tests.txt b/fork/plans/tmad-port/evidence/desvio-0.11.1-focused-tests.txt deleted file mode 100644 index c1c3d070dea..00000000000 --- a/fork/plans/tmad-port/evidence/desvio-0.11.1-focused-tests.txt +++ /dev/null @@ -1,28 +0,0 @@ -app/src/audio/audio-engine.web.test.ts: PASS -app/src/audio/playback.test.ts: PASS -app/src/voice/voice-runtime.test.ts: PASS -app/src/voice/voice-failure.test.ts: PASS -app/src/composer/input/state.test.ts: PASS -app/src/composer/queue-sync.test.ts: PASS -app/src/composer/actions.test.ts: PASS -app/src/stores/queue-outbox-store/model.test.ts: PASS -app/src/stores/session-store.test.ts: PASS -app/src/agent-stream/chat-find/matches.test.ts: PASS -app/src/agent-stream/chat-find/native-viewport.test.ts: PASS -app/src/companion-stream/model.test.ts: PASS -app/src/runtime/host-features.test.ts: PASS -protocol/src/messages.agent-queue.test.ts: PASS -protocol/src/messages.voice-flow.test.ts: PASS -protocol/src/messages.artifacts.test.ts: PASS -protocol/src/messages.companion-update-entry.test.ts: PASS -client/src/daemon-client.test.ts: PASS -server/src/server/agent-queue/store.test.ts: PASS -server/src/server/agent-queue/service.test.ts: PASS -server/src/server/agent-queue/send-or-queue.test.ts: PASS -server/src/server/message-receipts/index.test.ts: PASS -server/src/server/session.test.ts: PASS -server/src/server/session/voice/index.test.ts: PASS -server/src/server/session/voice/voice-turn-controller.test.ts: PASS -server/src/server/agent/companion-stream.test.ts: PASS -server/src/server/agent/artifacts/collector.test.ts: PASS -server/src/server/daemon-e2e/agent-queue-mirroring.e2e.test.ts: PASS diff --git a/fork/plans/tmad-port/evidence/desvio-0.11.1-runtime.txt b/fork/plans/tmad-port/evidence/desvio-0.11.1-runtime.txt deleted file mode 100644 index fd517a22ed3..00000000000 --- a/fork/plans/tmad-port/evidence/desvio-0.11.1-runtime.txt +++ /dev/null @@ -1,14 +0,0 @@ -{ - "phase": "queue-enabled-runtime-recovery", - "isolatedHome": "/Users/ctaylor/.tmp/paseo-tmad-runtime-nk_jcz5y", - "queuePath": "/Users/ctaylor/.tmp/paseo-tmad-runtime-nk_jcz5y/.paseo/queues/489bebcf-f0a7-4441-9fe3-751696d64fa9.json", - "queueSha256Before": "61f1666ad5b20d305ab6d6c12a7dc98c953c5ad9e15ce96d673ca408d3ff87bb", - "queueSha256DuringRead": "61f1666ad5b20d305ab6d6c12a7dc98c953c5ad9e15ce96d673ca408d3ff87bb", - "queueSha256AfterStop": "61f1666ad5b20d305ab6d6c12a7dc98c953c5ad9e15ce96d673ca408d3ff87bb", - "restoredRevision": 1, - "restoredPendingIds": [ - "pending-copy-1" - ], - "fakeProviderQueuedTurns": 0, - "daemonPortWasEphemeralLoopback": true -} diff --git a/fork/plans/tmad-port/evidence/manifest-frozen-2026-10-02.txt b/fork/plans/tmad-port/evidence/manifest-frozen-2026-10-02.txt deleted file mode 100644 index 1edcf72b50c..00000000000 --- a/fork/plans/tmad-port/evidence/manifest-frozen-2026-10-02.txt +++ /dev/null @@ -1,202 +0,0 @@ -# Branches merged into paseo-mine, in this order. `#` starts a comment; whatever -# follows a branch name is printed back in the build summary, so it is the reason -# the line still exists. -# -# ORDER MATTERS: the front is frozen, the back moves. Merges resolve against -# everything already merged, so moving a line re-resolves every line below it and -# throws away their recorded resolutions. APPEND; DO NOT INSERT. -# -# Carries reviewed against getpaseo/paseo on 2026-09-23. The earlier sweep is -# fork/upstream-prs-2026-09-12.md. -# Re-check before trusting: -# gh pr view -R getpaseo/paseo --json state,mergeable,updatedAt -# -# BASE: v0.11.0-beta.3, latest beta release as of 2026-10-02. -# custom is synced to this tag. #5227 is included, retaining the external-volume -# protection that replaced #3089. A base change re-resolves every carried line, -# so the first build on a new base needs full verification. -# -# --------------------------------------------------------------------------- -# WE REFERENCE AUTHOR FORK BRANCHES, NOT `upstream/pull/N/head`. -# -# `refs/pull/N/head` STOPS UPDATING the moment a PR closes. The author's fork -# branch does not. On 2026-09-07..09 the maintainer adopted a policy of -# auto-closing feature PRs (CONTRIBUTING.md, "This PR remains closed unless I -# explicitly follow up"), which closed eight lines of this basket in three days. -# A PR ref now means "frozen at the instant upstream slammed the door", and the -# rot becomes ours to pay. -# -# Measured 2026-09-10: seven of eight carried branches were still byte-identical -# to their frozen PR ref, because the closes were only days old. #2785 was not — -# colonelpanic8 rebased onto upstream/main of 09-09, the day AFTER the close, and -# added three commits: "adapt provider accounts to refreshed interfaces", -# "adapt provider account styles to current theme", "adapt provider account -# harness to current services". That is exactly the silently-rotting joint the -# fork README warns about, and the author is still paying for it. The frozen ref -# throws all three away. -# -# Each line's remote is configured in DESVIO_REPO with a SINGLE-BRANCH refspec, -# so `git fetch ` costs one branch and not a whole fork: -# git remote add https://github.com//.git -# git config remote..fetch "+refs/heads/
:refs/remotes//
" -# Use braces. Bare `$br:refs/...` loses the `:r` to zsh's root-name modifier and -# writes a refspec with no colon in it; the fetch then fails with -# "couldn't find remote ref", which is not what a missing colon sounds like. -# --------------------------------------------------------------------------- -# -# Dropped since 2026-08-22: -# #2582 notification sounds — MERGED upstream 2026-08-08. Already in the base. -# #2319 wide chars in terminal captures — superseded by #4101, which is rebased -# onto the tree's actual shape and MERGEABLE. Was never in our base; -# the 09-07 sweep corrected the belief that it had merged. -# #3672 draft pending leak — superseded by #4442 on merit, not by policy. -# #4442 is the maintainer's own canonical fix and covers the daemon -# boundary too. -# #467 hidden-terminal battery drain — closed unmerged; revive as a local -# branch if we want it, it is a front-of-manifest case. -# #4421 restore cached conversations — MERGED 2026-09-07, in v0.8.0-beta.1. -# #3440 low-order X25519 peer keys — hole already closed in base by #3669. -# #4442 duplicate workspaces and agents on retries — DROPPED 2026-09-12, -# on merit, while still open. It is a SECOND ANSWER to a question -# v0.8.0 already answers: upstream ships keyed creation end to end -# (protocol messages.ts:1684 idempotencyKey; session.ts:3574 routing -# to agentRequests.create; agent/requests/index.ts; daemon-client.ts -# :2550 gated on requireAgentRequestReceipts). #4442 does not use it — -# 8bfc5c2e1 RENAMES agent/requests/ to request-receipts/ and 467363659 -# adds a parallel client/src/creation/ + server/creation/ subsystem. -# Carrying it means two idempotency mechanisms in one tree, and the -# desvio gate is typecheck+lint, which cannot tell you which one owns -# agent creation at runtime. -# The bug is real and still live: the app never sends a key (empty -# grep for idempotencyKey in packages/app on upstream/main), so the -# UI path cannot dedupe. Upstream knows — #3217 OPEN, #2673 OPEN. -# Nothing is extractable: the app-side wiring exists ONLY on this -# branch, fused into the rework. Five upstream attempts (#3272 #2614 -# #3546 #4280 #4585) are all CLOSED and all added a client-side -# single-flight guard, which stops concurrent duplicates but not a -# retry seconds later — the exact hole agentRequests closes. -# Replacement: write the two call sites fresh against upstream's key -# (create-agent-request.ts and new-workspace-screen.tsx), gated on -# the receipts capability. Small, and an upstream candidate. -# Revive this line only if upstream merges #4442 itself. -# fork/reseat-side-conversations-0.8 — overtaken 2026-09-12, per its own -# delete condition: the v0.8.0 sync landed both of its commits on -# custom itself. Verified, not assumed: both files are byte-identical -# between the two refs, and merging the branch into custom yields -# custom's own tree OID unchanged, so the line is a no-op merge. -# The panel fix is still the NOOP one — select.ts:250 returns -# providerRows alone once providerParentSubagentId is set, so no -# side-conversation row reaches the nested track. Reading -# selectSideConversationsForParent instead of the hook's return -# makes "wire it for real" look correct; it is not. See -# fork/upstream-sync.md → v0.8.0 row. -# #3089 external-volume startup workaround — removed 2026-09-23. Upstream -# #5227 covers missing mounts at startup and during periodic scans. -# #5227 landed after v0.9.1, so a build pinned to that tag alone does -# not include the replacement; use current upstream/main for the basket. -# #3727 separate selectable Opus 5 [1m] model — removed 2026-09-23 by choice. -# Upstream v0.9.1 defaults to Opus 5.5 with a 1M context window. -# This drops the explicit Opus 5 [1m] runtime choice; the plain Opus 5 -# entry remains upstream-owned. - -# ---- FRONT: the two biggest conflict payers, at the bottom of the stack where -# ---- nothing above them disturbs their resolutions. - -# PR #2785 multi-provider accounts, rebased onto v0.11.0-beta.3 with Sol's -# usage-source conflict resolution and the beta.3 route/test compatibility fix. -# The local branch preserves the author merge as its parent. -fork/multi-account-beta3-2026-10-02 - -# ---- MIDDLE: open and policy-closed upstream PRs, oldest first. When one lands, -# ---- delete its line; only the lines below it re-resolve. - -muzhi1991/fix/codex-toolsurface-screenshot # PR #2237 materialize Codex toolSurface screenshots — +177/2f, also relieves the relay cap. OPEN. -dkribeiro/fix/2610-timeline-byte-bounded-hydration # PR #2664 byte-bound timeline pages — fixes #2610. OPEN. Its replacement #4153 is CLOSED, so this stays. -timigod/fix/one-shot-workspace-observer-fanout # PR #3117 one-shot inventory skips Git observers — kills a 26 s connect stall. Closed 09-08 for want of a test. -bwestlund17/fix/zcode-slash-commands # PR #3369 async initial commands for custom ACP providers — 51 lines, replaces the hard-coded "" at acp-agent.ts:2688. OPEN. -# PR #3474 retired on v0.11.0-beta.3: the old quota-fetcher was removed and -# the Claude usage plugin already returns 403 as a rejected credential response. -ngothanhthien/fix/coalesced-flush-crashes-daemon-for-torn-down-agent # PR #3545 coalesced flush for a torn-down agent crashes the daemon — 17 lines. The crash is live in our tree. Closed 09-08 for want of a test. -codebutler/claude-permission-reason # PR #3950 canUseTool decisionReason — permission cards say why they appeared. +37/0, additive. OPEN. -# Pin #4101 to the last verified author head. The 2026-10-02 author rebase -# c3707e6be..701bf00d7 pulls over 1,000 changed paths from upstream/main, -# beyond the published beta.3 base. Review that base drift separately. -fork/pinned-cjk-terminal-switch-spacing-2026-10-02 # PR #4101 CJK spacing across retained rows — c3707e6be. Supersedes #2319/#3458/#3767. -# PR #4113 removed on v0.11.0-beta.1: upstream forwards steerActiveTurn -# and tests call propagation plus failure without turn replacement. -ThePharmer/fix/claude-thinking-display # PR #4355 send display:"summarized" so Claude thinking blocks render — 12 lines. OPEN. - -# ---- BACK: our own branches. Churn belongs here, where it disturbs least. - -custom # the fork itself: side conversations, the ACP cancellation - # boundary, fork/ and fork CI. Includes v0.9.1 as of the - # 2026-09-23 sync. Still true after any protocol change: run - # server/authorization/index.test.ts — fork/upstream-sync.md owns - # the joints that rot without conflicting, now including contracts - # the fork widened that upstream keeps calling. - -# ---- INFI-PC INTAKE: isolated ports on custom/v0.10.1. See -# ---- fork/plans/infi-pc-intake-work-items.md for acceptance and dependencies. -intake/infi-agent-file-links # IP-01 0f0ba1f1d; source checkout paths, workspace containment. -intake/infi-fork-pr-lookup # IP-02 160430f94; fork-local PR first, full-page fallback. -intake/infi-desktop-quit-confirmation # IP-03 884ac282d; managed daemon quit and signal path. -intake/infi-package-scripts # IP-04 41b31a3dd+fixes; nested scripts, service preservation. -intake/infi-plan-copy # IP-05 fe676b131/f777bc1b3; live and historical plan copy. -intake/infi-plan-handoff # IP-06 fe676b131/f777bc1b3; editable draft, manual Send. -intake/infi-base-branch-contract # IP-07 fae603ccb; qualified refs, optional wire/API. -intake/infi-branch-header # IP-08 fae603ccb; gated branch pair picker, follows IP-07. -intake/infi-recent-agents # IP-09 f777bc1b3; recently closed menu, archive intact. -intake/infi-pinned-prompt # IP-11 6843b4ff7+fixes; desktop visible-response pin. -intake/infi-status-pulse # IP-12 6843b4ff7; bounded attention animation. -intake/infi-project-pr-facts # IP-13 80c69f95c; forge search CI facts, follows IP-02. -intake/infi-navigation-history # IP-10 f777bc1b3; route/tab history, follows IP-09. -intake/infi-project-pr-browser # IP-14 80c69f95c; project PR overlay and workspace seed, follows IP-13. - -# If the first build is rough, comment out from the BOTTOM UP — one `#` each. -# Order survives, and re-enabling costs one character. `custom` and #2785 are the -# two that will want attention first. -# -# ---- Disabled, with the reason. These are NOT merge conflicts; each needs a -# ---- code change, so re-enabling one is a task, not a character. -# -# upstream/pull/280/head # PR #280 Cursor provider via headless CLI. DISABLED 2026-08-22. -# Upstream registers CursorACPAgentClient under the same `cursor` key in -# PROVIDER_CLIENT_FACTORIES that this PR registers CursorCliAgentClient under, and the -# PR's client still implements the removed listModels/listModes API instead of the -# required fetchCatalog. Landing it means porting providers/cursor-cli-agent.ts. -# Upstream has never ruled on ACP-vs-CLI for Cursor. Closed 2026-09-07. -# -# upstream/pull/1813/head # PR #1813 image diff viewer. DISABLED 2026-08-22. -# Upstream replaced the React DiffFileBody/SharedDiffView renderer with the -# canvas-painted DiffDocument, deleting the only mount point for the PR's -# ImageDiffBody. Neither side can be kept. To land it: union the six easy files -# (messages.ts keeps HEAD's COMPAT(diffOldPath) comment + shared oldPath + both -# capability blocks; checkout-git.ts keeps HEAD's unconditional oldPath spread + the -# topic's binaryKind; union the new RPC into workspace-git-service.ts, its stub, and -# the features advertisement in websocket-server.ts) THEN port ImageDiffBody as a new -# row kind across diff-document/{types,model}.ts and surface.{web,native}.tsx. -# -# upstream/pull/1826/head # PR #1826 persist queued messages. DISABLED 2026-08-22. -# Merges fine (rerere has the resolution) but is stale against upstream drift in five -# places that produce NO conflict markers: -# composer/draft-coordinator.ts switch no longer exhaustive over UserComposerAttachment -# composer/submit.test.ts still passes clearDraft, which this PR removed -# runtime/directory-sync/*.test stubs missing onAgentInactive/onAgentDirectoryCommitted -# schedule/service.ts ScheduleAgentManager Pick missing waitForAgentRunStart -# Closed 2026-09-07. Re-add if the author rebases — they have rebased it 4x already. -# -# upstream/pull/1834/head # PR #1834 provider-native session fork. DISABLED 2026-08-22. -# Costs 4 local patches: a duplicate TraeACPAgentClient import inside its own recorded -# rerere resolution (needs --forget to re-record), i18n/resources/ko.ts missing -# workspace.tabs.menu.forkAgent, the onForkAgent input in -# workspace-tab-trailing-accessory.test.tsx, and fork/mobile-fork-icon below. -# Closed 2026-09-07. -# -# fork/mobile-fork-icon # ours. Companion to #1834 — disabled with it. Re-enable together. -# # Adds the "git-branch" case to the mobile tab-menu icon switch. - # That switch has a default: arm, so the missing case draws the - # wrong icon rather than failing to compile — nothing would catch - # it. The resolver kept making this edit itself and tripping - # desvio's out-of-set guard; carried as a branch it survives, - # because rerere only replays MARKER resolutions and this file - # never conflicts. Merge after #1834. diff --git a/fork/plans/tmad-port/evidence/pluto-cli-typecheck-2026-10-08.md b/fork/plans/tmad-port/evidence/pluto-cli-typecheck-2026-10-08.md deleted file mode 100644 index 0e1981678f6..00000000000 --- a/fork/plans/tmad-port/evidence/pluto-cli-typecheck-2026-10-08.md +++ /dev/null @@ -1,49 +0,0 @@ -# Pluto CLI typecheck investigation — 2026-10-08 - -## Result - -Environment recovery; no source fix or commit needed. At the assigned SHA, both owning-stack builds and the complete workspace typecheck pass. The reported claim that these callback errors persist after successful builds was not reproduced. A controlled missing-protocol-declarations experiment reproduces TS7006 in all six reported files, and restoring those declarations makes CLI typecheck pass again without changing source. - -## Identity and constraints - -- Worktree: /home/ctaylor/.paseo/worktrees/3rzqjhby/pluto-cli-typecheck -- Branch: fix/pluto-cli-typecheck -- Initial and final HEAD: 24f134618cd8a7143615debf927c1ac60b9ba813 -- Reported drift ref resolves to 0110302b6fd172933ef9ba615fc9f0a08e420668; not integrated or used as the reproduction baseline. -- Node v22.20.0; TypeScript 5.9.3; tsgo 7.0.0-dev.20260423.1; Zod 4.4.3; test runner reports Vitest 4.1.7. -- No delegation, daemon operations, deployment, push, live manifest edits, or custom/mine branch edits. -- Read CLAUDE.md, listed docs/, read coding-standards.md, testing.md, development.md and fork/worktrees.md. - -## Causal mechanism - -The six CLI commands receive a DaemonClient from utils/client.ts. Its fetchAgents overload returns Promise. In packages/client/src/daemon-client.ts:766, FetchAgentsPayload derives from Extract["payload"]. SessionOutboundMessage is inferred from the canonical protocol Zod schema; its response entries are a Zod array of AgentDirectoryResponseEntrySchema. - -Package exports resolve to compiled dist declarations. Removing this worktree's packages/protocol/dist breaks the type dependency beneath the client declaration. With skipLibCheck enabled, errors within imported declarations do not provide a useful upstream diagnostic at every consumer; callback inference degrades and the CLI reports implicit-any parameters. Direct CLI protocol imports also report TS2307 in the controlled experiment. - -This establishes a declaration-resolution cause for the reported error pattern, not proof of the exact state of the original failing checkout. Its logs/artifacts were not supplied. Missing/stale/wrong-checkout declarations remain possible explanations for that original run. No evidence supports a defect in these callbacks at the assigned SHA. - -## Commands and results - -Heavy checks were run sequentially with logs in /tmp. Root build:server internally uses the repository's existing concurrent highlight/plugin/relay build stage. One premature CLI check briefly overlapped the server rebuild; this was recorded and excluded from final verification. - -1. `node fork/scripts/init-worktree.mjs --no-dist --no-seed > /tmp/pluto-init.log 2>&1` — exit 0. Shared third-party packages from /home/ctaylor/repos/paseo; verified workspace package resolution inside this worktree. node_modules is a local directory, not a whole-directory symlink. @getpaseo/client and protocol links both point to ../../packages/. -2. `npm run build:client > /tmp/pluto-build-client.log 2>&1 && npm run build:server > /tmp/pluto-build-server.log 2>&1` — exit 0. Full server/CLI owning stack rebuilt before final diagnosis. -3. Premature `npm run typecheck --workspace=@getpaseo/cli > /tmp/pluto-cli-typecheck.log 2>&1` — exit 2 while server output was not yet built. Missing server exports caused TS2307 and downstream errors; none of the six target files had TS7006. This is not the completed-stack result. -4. `npm run typecheck > /tmp/pluto-typecheck.log 2>&1` — exit 0, all workspaces. -5. `npm run lint > /tmp/pluto-lint.log 2>&1` — exit 0, 0 warnings and 0 errors, 4535 files. -6. Controlled reproduction: moved only worktree-local packages/protocol/dist to a fresh /tmp directory, with an EXIT trap restoring it. `npm run typecheck --workspace=@getpaseo/cli > /tmp/pluto-missing-protocol-typecheck.log 2>&1` — exit 2. No source or shared dependency files changed. Target diagnostics: - - archive.ts:60,70 — entry TS7006 - - delete.ts:54,58,60,78 — entry/a/agent TS7006 - - detach.ts:34 — entry TS7006 - - reload.ts:55 — entry TS7006 - - stop.ts:58,63,66,86 — entry/a/agent TS7006 - - worktree/ls.ts:53,74 — entry/wt TS7006 -7. After automatic dist restoration, `npm run typecheck --workspace=@getpaseo/cli > /tmp/pluto-cli-recovered-typecheck.log 2>&1` — exit 0. -8. `npm exec --workspace=@getpaseo/cli -- vitest run src/commands/agent/delete.test.ts --bail=1 > /tmp/pluto-delete-test.log 2>&1` — exit 0, 1 file / 1 test passed. No full test suites run. -9. `git diff --exit-code` — exit 0. No tracked changes. Initializer-created package-level node_modules symlinks appear as untracked setup artifacts; they were not staged. - -## Recovery - -From this isolated worktree, initialize dependencies using fork/scripts/init-worktree.mjs (never link the whole node_modules directory), then run npm run build:client and npm run build:server. Verify that the build commands actually exit successfully and that workspace package symlinks resolve into this worktree. Run npm run typecheck and npm run lint afterward. Seeded dist output is a snapshot and cannot substitute for the owning-stack rebuild. - -No duplicate types, callback annotations, or source workaround were added. Existing fork/worktrees.md and docs/development.md already document the recovery. No commit was made because there is no necessary tracked change; the evidence requested by the task lives in this file. diff --git a/fork/plans/tmad-port/evidence/pluto-readiness-2026-10-08.md b/fork/plans/tmad-port/evidence/pluto-readiness-2026-10-08.md deleted file mode 100644 index 41223dbd251..00000000000 --- a/fork/plans/tmad-port/evidence/pluto-readiness-2026-10-08.md +++ /dev/null @@ -1,65 +0,0 @@ -# Paseo fork-build readiness audit — corrected 2026-10-08 - -Scope: read-only reconciliation of TMAD and other Paseo fork work from the `tmad-port/coordination` checkout. This correction replaces the earlier audit’s ancestry, ACP status, CI, and promotion-path claims. No source edits, tests, daemon operations, or manifest edits were performed in this coordination checkout. Initial typecheck showed 14 CLI TS7006 diagnostics; after repairing stale package-level dependency links with the worktree initializer and rebuilding client/server, full typecheck and lint passed. This is a recovered worktree setup issue; no source defect or permanent hook bypass is claimed. No tests were run in this coordination checkout. Active `voice-flow-r2` was not entered. The requested docs/tracker edits are separate from source. - -## Recommendation - -Keep TMAD out of the live manifest pending the remote CI/full-suite and human/device/live-provider/live-migration gates. The selected readiness candidate is `rehearsal/p0-custom-voice-complete` at `9584b2a669ce90a5df8c9eac66073e85124e90bb`, integration-approved by Pi/Muse; the frozen-only Voice basket retains the known side-conversation failure and is not release ready. Exact final refs, carry-preserving sequence, integration deltas, runtime hash proof, and check results are owned by the [P6 report](P6-assembly-2026-10-08.md). Reviewed intake branches alone do not include all assembly adaptations. Queue-root re-anchoring remains a separate update-loop decision. - -The published fork build is identifiable: npm’s `@camerontaylor/paseo-cli@0.11.0-beta.3.fork.1` SLSA provenance resolves to `mine` at `4cc94e07e870e1461640ce3256d1db2d0ab1bc2f`; this artifact predates TMAD inclusion. Consumers should use `latest`/the default install path for the current CLI build. The stale `fork` tag is a documented operational gap: `fork/scripts/release-fork.mjs:596-604` and the fork publish workflow state trusted publishing may publish but cannot write dist-tags; updating `fork` is best-effort and can return E401. A credentialed operator may repair the tag; this is not a code defect. The current live manifest/config remains unavailable in this environment, so this does not establish its present contents. - -## Git and artifact facts - -- Prior coordination HEAD for this durable snapshot: `a4f75b6e5c5575666d4008c8ce8bc462646bad4e`. Historical audit observations below retain their original scope. -- `origin/main`/`upstream/main`: `cc8fe41e2828a34d4d9706c0b8353c0e91987a25`. -- `origin/custom`: `24f134618cd8a7143615debf927c1ac60b9ba813`. -- `origin/mine`: `4cc94e07e870e1461640ce3256d1db2d0ab1bc2f`. -- Direct ancestry checks return false (`git merge-base --is-ancestor` exit 1) for current `custom` → `origin/mine`, current `custom` → `tmad-port/baseline-assembly` (P0), and `1ff3847aa` (plugin SDK import wiring) → `origin/mine`. The current custom/Zcode SDK integration is not in the published mine tree. -- Historical commits `acc60db36`, `816d7dcc0`, `7353f6181`, `300eec342`, `28b167ed3`, `5b2e21d83`, `f8c5b791b`, side-conversation commit `7308e46e7`, and local Zcode patch script commit `57317859a` are ancestors of both `origin/mine` and P0. Thus the old mine/P0 snapshot contains those older custom behaviors and the completed ACP fix-pass code; “current custom is not an ancestor” does not mean all custom-originated work is absent. -- `origin/mine` has no ancestry from TM-01 `a8241e535`, TM-02 `91392d6be`, TM-03 `9ab91bb75`, or TM-07 `5f3634ad4`. -- Frozen manifest copy: `fork/plans/tmad-port/evidence/manifest-frozen-2026-10-02.txt`; no TMAD lines. The documented live path `/home/ctaylor/.paseo-fork/manifest.txt`, `desvio.conf`, and `/Volumes/offload/neptune/repos/paseo` are absent here. Do not infer live state from the frozen copy. -- Public npm metadata reports `latest=0.11.0-beta.3.fork.1`, while `fork=0.8.0-fork.1` is stale by documented design/credential limits. Consumers should use `latest` or the default install path. The release script makes the `fork` re-point best-effort because trusted publishing lacks dist-tag permission; a credentialed operator can repair it if needed. For the CLI version, npm has no `gitHead`, but its SLSA provenance names workflow `.github/workflows/fork-npm-publish.yml`, repo `camerontaylor/paseo`, ref `refs/heads/mine`, commit `4cc94e07e870e1461640ce3256d1db2d0ab1bc2f`, and publish run `36963052999` (success). The provenance’s SHA-512 subject matches the npm tarball `dist.integrity`. This verifies this package artifact’s build source, not every package in the release. -- GitHub Actions run `37187135673` is `Fork CI` on `custom` SHA `24f134618…`, conclusion failure. Upstream/main run `37186340343` on `cc8fe41e2…` succeeded. -- Public jobs/annotations identify `packages/server/src/server/session.test.ts:259`, test “side conversation manager events reach every capable client”: expected update and removed events, received `[]`. It failed in `fork-checks (makemake)`, full-matrix server tests on ubuntu and Windows. This is the pre-fix historical run. Repair commit `fddb4fa8587ae377286ffbea3137df4c53bdc7a9` has independent approval and remains an integration candidate outside `custom`/`mine`, integrated only in the local full rehearsal; intended-path inclusion and CI remain outstanding. Typecheck, lint, and format jobs are green. Playwright shards 3/4 and 4/4 failed with generic exit-code annotations; public annotations provide no detailed cause. Do not attribute those failures to a particular test or feature. -- Active worktrees observed during the initial audit: coordination, custom, P0 assembly, TM-01, TM-02, TM-03, and TM-04. The TM-04 worktree was not entered during that audit. The later implementation report records final HEAD `84f11381ceabec13d5deaff6c1e2c05dc67a6c62`; see [TM-04 evidence](TM-04-2026-10-08.md). GitHub API/npm public endpoints were used read-only. No `gh` auth was needed for those APIs. - -## TMAD readiness - -“Approved” refers to the recorded read-only branch review. It does not by itself clear human evidence or integrated removal checks. - -| Item | Exact ref / evidence | Readiness and remaining gates | -|---|---|---| -| P0 | `2bfcd2e19638484baf1651d69dc0be55df483bcd`; `P0.md`, `review-P0.md` | Approved frozen baseline. It is retained in the selected full candidate. It does not contain current `custom` HEAD `24f134618` and is not proof of the live basket. | -| TM-01 Stream | `a8241e53530d6bd0a958971118d6b8b57ff80b0c`; `TM-01.md`, both reviews; P2 `0ff83cbc5` and `review-P2.md` | Approved; Stream-only removal and copied-data rollback proof complete. Promotion still owes matched desktop/compact-web, native, and locale captures including Korean, plus the noted label/ceiling decisions. Integrated check evidence is recorded in P6. No TM-01B bridge is needed. | -| P6 final rehearsals | [P6 exact refs and results](P6-assembly-2026-10-08.md) | Full local basket green; final integration review APPROVED. Frozen-only Voice retains known failure; not release ready. | -| TM-02 queue daemon | `91392d6beed3fc49f9be7496a70b8d5822957d4c`; `TM-02.md`, `review-TM-02.md` | Approved intake. Existing base is historical custom floor `cbd1210c7`; do not treat that as a reason to alter the branch before the frozen-basket rehearsal. Copied pending-state runtime proof passed; see P6. The pre-fix `session.test.ts:259` failure has repair commit `fddb4fa8587ae377286ffbea3137df4c53bdc7a9`, independently approved by Luna; intended-path inclusion and CI remain outstanding; local full-rehearsal tests passed. TM-03 has fake-provider two-client daemon E2E; provider-credential E2E remains a limitation. | -| TM-03 queue UI | `9ab91bb759be1951bdaa9cbe7bc991cafed2569d`; `TM-03.md`, `review-TM-03.md` | Approved intake; browser/native dev-app captures for delivery badges, row menu, and failed overlay remain open. Copied pending-state runtime proof is recorded in P6. Typed-send default remains unchanged. | -| TM-04 voice | `84f11381ceabec13d5deaff6c1e2c05dc67a6c62` (includes attributed import `5ecb8324625de55dc80345f181518da26f2d42db`); [implementation evidence](TM-04-2026-10-08.md), [review](review-TM-04-2026-10-08.md) | Implementation complete; agent `agent9307e007` is archived. Pi/OpenCode Go Muse reviewer `6ff8658e-654d-4637-beeb-c24d238f9375` (workspace `wks_9d17ba714b1dcd50`) APPROVED this exact HEAD and is archived. Local basket integration is complete; final review is APPROVED; physical-device/live-provider checks remain open. The recovered `6ab56eba1` WIP is history only. | -| TM-07 Native Find | `5f3634ad43256c18f9f41667348c65fe1b03d7f4`; `TM-07.md`, `review-TM-07.md` | Approved intake. 10-point iOS/Android device matrix remains open. Known adapted merge with Stream at `agent-view-store.ts` and `workspace-tab-menu.ts` is demonstrated in P6; final integration review is APPROVED. | -| TM-05/06/08+, typed-send default | No branches | Product decisions for the user; do not start or flip the default. | - -### Build path and boundaries - -Use the [P6 report](P6-assembly-2026-10-08.md) for final local basket and removal evidence. The dormant copied-state preservation/recovery gate passed; provider dispatch was not exercised; live-home migration, physical devices, and live providers remain open. The live manifest append block is still a proposal. No TMAD promotion to `custom`/`mine` or live configuration occurred. - -## Other fork work and current ownership - -| Work | Actual inclusion status | -|---|---| -| ACP cancellation boundary / GJC | The historical fix-pass plan and review are stale as implementation plans. The units landed in current `custom` and are also ancestors of P0 and `mine`: `816d7dcc0` observed-death settlement (`deathSettled`/`transport_death`), `7353f6181` issue-and-return, `300eec342` terminal-kind precedence, `28b167ed3` deny routing and `deny_cancel_suppressed`; `5b2e21d83` repaired the manager test terminator and records 186 passing tests; `f8c5b791b` updated lifecycle/provider docs. Do not dispatch redundant ACP implementation. The 2026-09-04 plan/review still record the earlier snapshot accurately but not current status; they are marked historical in this correction. Current fork CI has the separate side-conversation test failure described above. | -| Side conversations | Older implementation commit `7308e46e7` is in P0 and `mine`. Repair commit `fddb4fa8587ae377286ffbea3137df4c53bdc7a9` reproduces the base failure and restores delivery; final session file (157), authorization (7), build, typecheck, lint, format, and hooks passed in the worker report. Luna independently APPROVED it. It is an integration candidate outside `custom`/`mine`, integrated only in the local full rehearsal; intended-path inclusion and CI remain outstanding; it is not promoted. The original failing CI run remains historical until the fix reaches CI. CodeRabbit did not start because browser authentication returned `environment_unsupported`. See [repair evidence](pluto-side-conversation-events-2026-10-08.md) and [independent review](pluto-side-conversation-review-2026-10-08.md). | -| Zcode | Legacy local plugin patch/reapply machinery (`57317859a`) is in P0 and `mine`. Current plugin SDK import wiring commit `1ff3847aa` and current custom head `24f134618` are not ancestors of `mine`. Plugin patch scripts target installed plugin files, distinct from the core SDK change. | -| Fork release and worktree plumbing | Older fork release/worktree features are in the P0/mine snapshot. The released CLI artifact is proven above. Current custom-only additions are not included merely because the branch named `custom` exists. | -| Infi-PC IP-01…IP-14 | The `mine` history contains the infi integration sequence through IP-14 at `4cc94e07e`. The 2026-09-30 ledger documents integrated Desvio gates and browser checks; branch-pair picker browser QA and native device QA remain noted gaps. | -| Source PR #36 / TM-03 update candidates | Classified at source `929f1add3`; not ported. Revisit through the update loop after the relevant queue work; this is not a current implementation task. | - -## Worker ownership and test ownership - -Exact worker ownership and the snapshot archive count are owned by the [STATUS table](../STATUS.md#worker-ownership--2026-10-08). Pi/OpenCode Go Muse final reviewer `agentf65ea3e2-16ee-4cb4-8c06-4e355a689a4e` APPROVED the exact full basket and is archived; see [final review](review-P6-final-2026-10-08.md). Do not rerun worker-owned suites or builds. - -## Concrete next steps - -1. Run remote CI/full suites and close the device/UI/live-provider/live-migration gates listed in P6. The exact full basket is integration-approved. -2. Verify intended-path side-repair inclusion and post-fix CI. Local rehearsal success does not replace CI; historical Playwright shard failures remain unexplained. -3. Initialize dependencies and rebuild owning stacks before diagnosing CLI type errors. Reconcile live configuration on its owning host before a live build decision. -4. Any current-custom update-loop batch or promotion is separate work. No publication or daemon switch is authorized by this snapshot. diff --git a/fork/plans/tmad-port/evidence/pluto-side-conversation-events-2026-10-08.md b/fork/plans/tmad-port/evidence/pluto-side-conversation-events-2026-10-08.md deleted file mode 100644 index 91e681ea5f2..00000000000 --- a/fork/plans/tmad-port/evidence/pluto-side-conversation-events-2026-10-08.md +++ /dev/null @@ -1,87 +0,0 @@ -# Pluto side-conversation event blocker — 2026-10-08 - -Worktree: `/home/ctaylor/.paseo/worktrees/3rzqjhby/pluto-side-conversation-events` -Branch: `fix/pluto-side-conversation-events` -Reproduced base SHA: `24f134618cd8a7143615debf927c1ac60b9ba813` -Reported Fork CI: https://github.com/camerontaylor/paseo/actions/runs/37187135673 -Local environment: Linux 6.12.63, Node v22.20.0, npm 10.9.3. - -## Reproduction - -Initialized the worktree with `node fork/scripts/init-worktree.mjs --no-seed` -and rebuilt declarations with `npm run build:server`. Both passed. Initialization -verified that workspace packages resolve inside this worktree. No daemon or live -state was started, stopped, restarted, or edited. - -On the unchanged base SHA, from `packages/server`: - -```sh -npx vitest run src/server/session.test.ts --bail=1 > /tmp/paseo-side-baseline.log 2>&1 -``` - -Exit 1: three tests passed, then `side conversation manager events reach every -capable client` failed at `src/server/session.test.ts:259`. Expected update and -removed messages; received `[]`. This reproduces the reported public CI symptom -without provider authentication or an environment workaround. - -## Cause and fix - -Session manager observation became demand-driven. The constructor no longer -subscribes eagerly. `updateClientCapabilities()` refreshed producers only when -given a source, and the manager demand calculation omitted side-conversation -capability. The existing test advertises that capability without a source, so -there was no manager subscription to receive its dispatched events. A modern -source advertising only side conversations had the same missing-demand problem. - -The old forwarding arm also used the session's most recently negotiated -capabilities, then broadcast through `emit()`. In a shared session this could -suppress capable clients when an incapable client connected last, or broadcast -to incapable clients when a capable client connected last. - -The two-file fix refreshes observation after capability updates, includes -side-conversation demand, and forwards update/removal events to each capable -source. Source-free demand is tracked separately so the last detached source's -stale capability snapshot cannot reactivate delivery. The existing outbound -authorization check remains in the forwarding path: these observations still -require `workspace.read`; asking still requires `workspace.write`. No permission -map, protocol schema, capability name, or assertion was weakened. No auth checks -were added to tests. - -The original failing assertion remains intact. Added cases cover modern sources -with mixed capabilities in both connection orders, multiple capable sources, -individual and complete detach, and capability removal. The existing event -adapter now actually removes unsubscribed listeners. - -## Validation - -Commands ran serially within this worktree; output was captured to files. - -| Command | Result | Output | -| --- | --- | --- | -| `node fork/scripts/init-worktree.mjs --no-seed` | passed | `/tmp/paseo-side-init.log` | -| `npm run build:server` | passed | `/tmp/paseo-side-build.log` | -| baseline session file, `--bail=1` | reproduced failure | `/tmp/paseo-side-baseline.log` | -| final session file, `--bail=1` | 157 passed | `/tmp/paseo-side-final-session.log` | -| `npx vitest run src/server/authorization/index.test.ts --bail=1` from server | 7 passed | `/tmp/paseo-side-authorization.log` | -| `npm run format` | passed | `/tmp/paseo-side-format.log` | -| `npm run typecheck` | passed across workspaces | `/tmp/paseo-side-typecheck.log` | -| `npm run lint` | 0 warnings, 0 errors | `/tmp/paseo-side-lint.log` | -| `git diff --check` | passed | no diagnostics | - -The exact authorization file was justified by the fork/upstream-sync guard for -carried message permissions and the retained outbound permission boundary. No -full suite ran. Local execution proves Linux behavior; Windows and macOS remain -for the parent's CI/integration pass. Parent owns review and assembly. No push, -deployment, custom/mine edit, or live manifest/config change was performed. - -## Local commit - -Commit: `fddb4fa8587ae377286ffbea3137df4c53bdc7a9` -Subject: `fix(server): Restore side conversation event delivery` -Normal pre-commit format, lint, and workspace typecheck all passed. -Hook output: `/tmp/paseo-side-commit.log`. - -Tracked working tree is clean. Worktree initialization created seven untracked -per-package `node_modules` symlinks (app, cli, desktop, expo-two-way-audio, plugin, -protocol, website); the repository's directory-only ignore pattern does not -hide these symlinks. They are dependency setup artifacts and are not committed. diff --git a/fork/plans/tmad-port/evidence/pluto-side-conversation-review-2026-10-08.md b/fork/plans/tmad-port/evidence/pluto-side-conversation-review-2026-10-08.md deleted file mode 100644 index 42900f2ec07..00000000000 --- a/fork/plans/tmad-port/evidence/pluto-side-conversation-review-2026-10-08.md +++ /dev/null @@ -1,32 +0,0 @@ -# Independent review: Pluto side-conversation event delivery - -**Verdict: APPROVE** - -## Scope - -- Branch: `fix/pluto-side-conversation-events` -- Reviewed commit: `fddb4fa8587ae377286ffbea3137df4c53bdc7a9` -- Exact base: `24f134618cd8a7143615debf927c1ac60b9ba813` (the supplied `base24f134618`; also recorded in the reproduction evidence) -- Changed tracked files: `packages/server/src/server/session.ts` and `packages/server/src/server/session.test.ts` only. -- Worktree status at review: the only untracked items were seven package `node_modules` symlinks, excluded from scope. - -## Findings - -No actionable correctness or authorization findings. - -## Review evidence - -- The manager subscription is demand-driven at `session.ts:1647-1667`. `updateClientCapabilities()` now refreshes producer demand after every update (`:1236-1276`); side-conversation capability contributes demand (`:1670-1675`). When that demand goes away and no other agent observation remains, the existing unsubscribe branch runs (`:1661-1665`). Session cleanup also releases the manager subscription (`:8606-8614`). -- Source-free fallback state is recorded independently (`:1241-1245`) and is consulted only when there are no attached sources (`:1670-1675`). With attached sources, demand comes from their current capability snapshots, so a detached source's stale capability cannot restore demand. -- Side-conversation events are sent once to each attached source whose own capability set includes `sideConversations` (`:1678-1693`). The source-free path emits once only when source-free demand exists. In real WebSocket sessions, `onMessageToSource` verifies the socket remains attached (`websocket-server.ts:1387-1395`); the capability-aware path does not also call the shared broadcast emitter. The tests cover both capable/incapable connection orders, two capable sources, individual detach, full detach, capability removal, and the source-free case (`session.test.ts:233-379`). -- The outbound authorization guard remains before either delivery path (`session.ts:1684`). The existing permission map assigns `workspace.read` to update/removal and `workspace.write` to ask responses (`authorization/operation-permissions.ts:233-237`); inbound ask authorization remains `workspace.write` (`:16-18`). No authorization mapping or test checks were weakened. -- The diff is limited to the stated two tracked files and `git diff --check` produced no diagnostics. I did not rerun tests, builds, typecheck, lint, or formatting, per instruction. The supplied evidence records 157 session tests, 7 authorization tests, build/typecheck/lint/format passing. -- Read `docs/permissions.md`, `docs/architecture.md`, `docs/protocol-compatibility.md`, and `fork/upstream-sync.md` plus the side-conversations feature-ledger entry. This change does not modify protocol schemas or permission mappings; the relevant sync guard is retaining per-message authorization and preserving capability-specific routing. - -## CodeRabbit - -- `/home/ctaylor/.local/bin/coderabbit --version`: `0.8.2`. -- `coderabbit review --help` advertises both `--committed` and `--base-commit`; I used the supported exact-scope command: - `coderabbit review --agent --committed --base-commit 24f134618cd8a7143615debf927c1ac60b9ba813` -- The CLI review did not start: authentication returned `environment_unsupported` because browser login is unavailable. Raw output: `/tmp/paseo-side-conversation-coderabbit-review.txt`. No credentials were requested and no login was attempted. -- CodeRabbit's official CLI page documents its Linux/macOS install channel at `cli.coderabbit.ai`; the local binary reports the expected version and help options. Its local binary provenance could not be cryptographically verified in this review. Official page: https://www.coderabbit.ai/cli diff --git a/fork/plans/tmad-port/evidence/review-P0.md b/fork/plans/tmad-port/evidence/review-P0.md deleted file mode 100644 index b5993cd60ac..00000000000 --- a/fork/plans/tmad-port/evidence/review-P0.md +++ /dev/null @@ -1,135 +0,0 @@ -APPROVE - -# Review: P0 frozen-baseline verification — report under audit `/tmp/tmad-port/evidence/P0.md` - -Reviewer: read-only audit on pluto. No files edited except this report. No npm ci, -installs, builds, or tests run. No commits, pushes, or ref modifications. All -verification via read-only git commands (`rev-parse`, `cat-file`, `diff`, `log`, -`merge-base`, `rev-list`, `ls-tree`) in `/tmp/tmad-port/baseline-clone` and -`git -C /home/ctaylor/repos/paseo`, plus reading source files, the cited logs -under `/tmp/tmad-port/logs/`, and the actual LICENSE text. - -Inputs read: `/tmp/tmad-port/brief-P0.md`; plan sections "Evidence and baseline", -"P0", "Source tracking"; `P0-inputs.txt`; `.baseline-merge-status.txt`; -`P0-feature-map.md`. (TM-07 material in the request is covered by the existing -`evidence/review-TM-07.md` (APPROVE) and is out of scope for this report.) - -## 1. Reproducibility — CONFIRMED - -- `git -C /tmp/tmad-port/baseline-clone diff --stat HEAD 4cc94e07e870e1461640ce3256d1db2d0ab1bc2f` - → empty output, exit 0. Baseline tree == frozen mine tree. PASS. -- `HEAD` is `2bfcd2e19638484baf1651d69dc0be55df483bcd` (`2bfcd2e19`). Matches the - report's claimed final HEAD. PASS. -- First-parent chain `6166a7aca..HEAD`: 24 commits, every one a 2-parent merge, - unbroken first-parent linkage from the base, and each second parent equals the - frozen carry SHA at that manifest position in `P0-inputs.txt` (verified - position-by-position against all 24 lines, order multi-account → … → - infi-project-pr-browser). 24/24 OK, 0 mismatches. The report prints this chain - newest-first while listing manifest lines 1–24; both orders were checked and agree. -- Frozen-mine chain `6166a7aca..4cc94e07e`: independently re-verified — 24 merges, - same manifest order, same second parents, 0 mismatches. Merge SHAs differ from - the clone's (parallel assembly, as the report states); trees are equal per above. -- Extra-commit check: `git rev-list HEAD --not <24 carries>` returns exactly - the 24 assembly merges — I diffed that set against the first-parent chain set: - IDENTICAL. Same holds for frozen mine vs its chain. "Nothing else" conclusion is - correct. PASS. -- Delta-vs-base figure spot-checked: `git diff --stat 6166a7aca..HEAD` → - `329 files changed, 31611 insertions(+), 772 deletions(-)`. Matches the report - exactly. PASS. - -## 2. Ancestry statement — CONFIRMED (all five rows re-run) - -| Ref → baseline HEAD | Observed | Report claims | Verdict | -| --- | --- | --- | --- | -| base 6166a7aca | ancestor | YES | PASS | -| custom cbd1210c7 | ancestor | YES (manifest line 10) | PASS | -| frozen mine 4cc94e07e | NOT ancestor | NO | PASS | -| source head f0d5507d2 (full SHA; `refs/research/tmad-main` exists in the shared repo, absent by name in the clone — objects present, check run by SHA) | NOT ancestor | NO | PASS | -| source integration 51fb7693d | NOT ancestor | NO | PASS | - -"No unknown branch ancestry" exit criterion: met. - -## 3. Command-evidence audit — ALL CITATIONS MATCH - -Every cited log exists; every tail shows the claimed result: - -- `p0-npm-ci.log` (EXIT=0), `p0-build-server.log` (build:server EXIT=0), - `p0-typecheck.log` (typecheck EXIT=0), `p0-lint.log` - (0 warnings, 0 errors, 4589 files, 177 rules; lint EXIT=0). PASS. -- 11 `p0-test-*.log` files, each `1 passed` file with the exact claimed counts: - 7 + 210 + 6 + 56 + 4 + 9 + 10 + 5 + 6 + 4 + 3 = **320/320, 0 failures**. - `p0-test-summary.txt` shows exit 0 for all 11. The report's 320/320 claim is - arithmetically exact. PASS. -- `.baseline-merge-status.txt`: 1 aborted attempt on carry 3, clean restart, rerere - replays on timigod/one-shot, bwestlund17/zcode, infi-plan-copy (+assisted - infi-base-branch-contract) — consistent with the report's "21 clean, 3 replays + - 2 assisted" account. PASS. -- `p0-baseline-log.txt` head matches the report's 24-merge list. PASS. -- `P0-inputs.txt`: named anchors (base, tag, custom, tmad-main, 51fb7693d, - af247e4f4, dd8a111c3, mine) and all 24 manifest SHAs verified against the - objects used above. PASS. -- `p0-source-LICENSE.txt` is 211 lines, matching the claimed LICENSE length. PASS. - -## 4. Licensing conclusion — SOUND - -- `rev-parse 51fb7693d:LICENSE` = `rev-parse HEAD:LICENSE` = - `2f5903143b08de0aa991ab535d9582aca6b9b44a`; `diff` of the two blobs is empty. - Byte-identical claim CONFIRMED (read-only; nothing executed). -- LICENSE text read: "Copyright (c) 2025-present Mohamed Boudra", third-party - components under their own licenses, remainder Apache-2.0. No top-level NOTICE - file in the source snapshot; no per-file license headers on the inspected - feature files (`companion-stream.ts`, `artifacts/collector.ts`, - `companion-stream/model.ts` all begin with imports). The only NOTICE-named hits - are pre-existing subpackage/operational files (e.g. `expo-two-way-audio/LICENSE`, - provider notice toasts), not source-copyright notices requiring preservation. - The §4(a)/§4(b)/(d) reasoning and the trailers-satisfy-change-notice conclusion - are a fair reading of the actual text. No additional attribution required. PASS. - -## 5. Exit criteria (plan) — ALL MET - -- Reproducible baseline: yes (§1). Input SHA list: yes (`P0-inputs.txt`, verified). - Feature/file map: yes (`P0-feature-map.md`; method spot-checked — - `git diff --name-only 51fb7693d v0.10.0-beta.1` returns exactly **190** paths as - the map states; TM-07 rows and FORK.md presence confirmed; post-integration - range table covers the full span — see non-blocking note NB-2 on its header - count). No unknown branch ancestry: yes (§2). -- "No pre-existing failures" claim: fairly scoped — the report says the *focused - set* (11 files) carries no pre-existing failures and explicitly defers the - broader verification matrix to P1/P2 gates (§Known gaps #3). Not overstated as - written; later phases must still compare against this green result rather than - assume it. No blocking overstatement found. - -## Findings (all NON-BLOCKING — no claim fails, no redo required) - -- **NB-1 (log hygiene): `p0-verify-mine-chain.log` ends with `VERDICT: FAIL`.** - Contradicting evidence: every check line in that log is `OK` (24/24 second-parent - matches), and I independently confirmed the extra-commit set == the 24 assembly - merges (IDENTICAL). The FAIL string comes from a script bug in - `p0-verify-mine-chain.sh`: it requires `extra == 0`, but the 24 assembly merges - themselves are (correctly) reachable from mine and not from base+carries, so - `extra` is 24 by construction. The report never cites the script's verdict - string and its written conclusion is correct. Action: fix the script's verdict - predicate (`extra == chain length` with set-equality) or annotate the log; do not - re-run the assembly. -- **NB-2 (doc count): `P0-feature-map.md` says "29 commits" for - `51fb7693d..f0d5507d2`, but its own table lists 31 rows and - `git log --oneline 51fb7693d..f0d5507d2` returns 31 commits — row-for-row - identical sets.** Content is complete; only the header number is wrong. - Action: correct "29" → "31". -- **NB-3 (informational): clone `.git/rr-cache/` is absent (report says "empty").** - `rerere.enabled=true` confirmed; working tree clean confirmed. Consistent with - the report's warning that P1/P2 must re-copy a live rr-cache or budget fresh - resolutions. No action for P0. - -## Verdict rationale - -Every P0 exit criterion reproduces read-only: tree equality, HEAD SHA, both 24-merge -chains with manifest-order second parents, all five ancestry rows, all log -citations with exact test arithmetic (320/320), LICENSE blob identity with the -reasoning checked against the real text, and the feature-map method/counts. The -three findings above are documentation/script-hygiene issues that contradict no -evidence and require no rework of the baseline. Per the brief, no code, manifest, -or daemon state was touched by the worker (clone working tree verified clean), -and none was touched by this review. - -APPROVE — P0 baseline is frozen, reproducible, and correctly recorded; P1 may proceed. diff --git a/fork/plans/tmad-port/evidence/review-P2.md b/fork/plans/tmad-port/evidence/review-P2.md deleted file mode 100644 index 938e8d1b82f..00000000000 --- a/fork/plans/tmad-port/evidence/review-P2.md +++ /dev/null @@ -1,195 +0,0 @@ -APPROVE - -# Review: P2 with/without-Stream assembly + removal proof + rollback — report under audit `/tmp/tmad-port/evidence/P2.md` including Addendum 2 - -Reviewer: read-only audit on pluto. No file edited except this report. No npm ci, -installs, builds, or tests executed. No commits, pushes, or ref modifications. -All verification via read-only git commands (`rev-parse`, `cat-file`, `diff`, -`log`, `merge-base`, `rev-list`, `grep`, `show`) inside `/tmp/tmad-port/baseline-clone`, -reading source files at pinned refs, and reading implementer logs under -`/tmp/tmad-port/logs/` and scratch data under `/tmp/tmad-port/rollback-home`. -Anything requiring code execution is marked "not verifiable read-only". - -Inputs read first, in order: `/tmp/tmad-port/COMMON.md`, `/tmp/tmad-port/plan.md` -("Branch and removal contract", P1 steps 4–5, P2, Stream compatibility contracts), -`/tmp/tmad-port/brief-P2.md`, `/tmp/tmad-port/evidence/P2.md` (report under audit, -headline through Addendum 2), plus `evidence/P0.md` (+ coordinator post-review note), -`evidence/TM-01.md` (+ post-P2 addendum), `evidence/review-TM-01.md` (APPROVE), -`evidence/review-TM-01-delta.md` (APPROVE), `/tmp/tmad-port/stream-rollback.md` -(note: lives at top level, not `evidence/` as the task description suggests), -and the draft manifest block in `STATUS.md`. - -Final assembly under review: branch `tmad-with-stream` = `0ff83cbc5e31f4ec16e4b28c0694230c4a83debd` -(Addendum 2 rebuild; interim `d17896891` assembly superseded, branch deleted, commit object retained). -Clone verified clean on `tmad-with-stream` at review time. - -## 1. With-stream assembly — PASS - -- `git rev-parse tmad-with-stream` = `0ff83cbc5…` ✔; base `tmad-port/baseline-assembly` = - `2bfcd2e19…` (unchanged frozen P0 baseline) ✔; `intake/tmad-stream-flow` = `a8241e535…` ✔. -- Merge structure: `git log --format='%H %P'` on `0ff83cbc5` → parents exactly - `2bfcd2e19` (baseline) + `a8241e535` (TM-01 tip). Single merge, `--no-ff` shape ✔. -- `git log --oneline tmad-port/baseline-assembly..tmad-with-stream` → **11 lines**: - the merge + TM-01's 10 commits (9 original + `a8241e535` seam fix). No extra assembly - commit — the fix arrives inside the merged branch ✔. -- Superseded-assembly redundancy: `d17896891` still resolves - (`d178968919e66e9bc32e5d8b9e34e389baacb343`); `git diff d17896891 0ff83cbc5` → - **empty, exit 0**. Rebuilt tree is byte-identical to the tree that passed the full P2 - battery; only the graph changed ✔. -- Fallback path (had the object been gone) not needed, but the equivalent check was also - run: `git diff tmad-with-stream --stat` = 53 files, and the sorted name list - is **identical** (`diff` empty) to `git diff 6166a7aca a8241e535 --name-only` — exactly - the 53 TM-01 paths ✔. - -## 2. Removal proof — PASS - -- Removal assembly = `tmad-port/baseline-assembly` itself (Stream appended, not interwoven; - the self-diff trivially empty — stated honestly as definitional, not as evidence). -- Substantive check re-run: with-stream minus baseline = 53 files, `+4135/−51`, and the - path set is byte-identical to TM-01's own 53-file delta (see §1). Zero non-TM-01 paths; - no bridge line exists ✔. -- Baseline cleanliness: `git grep -E 'companion-stream|AgentArtifact|companionEntries|companionStreamPortV1' - tmad-port/baseline-assembly -- 'packages/**'` → **0 hits** ✔. (A bare `grep -l "companion"` - returns 7 hits; each inspected — e.g. "desktop companion pane", "companion tools" test - description — plain English, feature-irrelevant ✔.) Control direction (Stream files present - on the with-stream tree) is established by the 53-path diff itself. - -## 3. Ancestry on the new graph — PASS (all rows re-run) - -| Ref → `0ff83cbc5` | Observed | Expected | -|---|---|---| -| base `6166a7aca` | ancestor ✔ | YES | -| `custom` `cbd1210c7` | ancestor ✔ | YES (via baseline) | -| all 24 frozen carries (P0-inputs.txt order) | all ancestors ✔ | YES | -| TM-01 `a8241e535` | ancestor ✔ | YES | -| frozen `mine` `4cc94e07e` | NOT ancestor ✔ | NO | -| source head `f0d5507d2` | NOT ancestor ✔ | NO | -| source integration `51fb7693d` | NOT ancestor ✔ | NO | - -- Extra-commit set: `git rev-list 0ff83cbc5 --not <24 carries> a8241e535` → **25 - commits** = the 24 baseline assembly merges + the new with-stream merge. Listed and - eyeballed: second entry is `2bfcd2e19` (baseline tip), remainder are the 24 carry merges. - Nothing unknown ✔. - -## 4. TM-01 seam-defect handling — PASS - -- Pre-fix failure confirmed in logs: `p2-test-agent-manager.log` → `210 tests | 1 failed`, - FAIL on "does not replace a newer foreground turn after unavailable steer fallback is - admitted"; isolated rerun `p2-test-agent-manager-rerun.log` fails the same single test - deterministically (`1 failed | 209 skipped`) ✔. Matches the report's 209/210 account. -- Post-fix green confirmed: `p2-test-agent-manager-postfix.log` → 210/210 ✔; on the - rebuilt tree `p2b-test-agent-agent-manager.log` → 210/210 ✔ and `p2b-test-steer-single.log` - → `1 passed | 209 skipped` ✔. -- Fix routing verified in the graph: `2197619bc..a8241e535` = exactly the one commit - `a8241e535`, whose parent is `2197619bc` on `intake/tmad-stream-flow` — the fix lives in - the TM-01 branch, and the with-stream history contains exactly the merge + TM-01's 10 - commits with **no assembly-side fix commit** ✔ (this is precisely what the brief required: - fix in the branch, not in the assembly). -- Source fidelity of the call site re-checked: `git diff 51fb7693d a8241e535 -- - packages/server/src/server/agent/agent-manager.ts | grep -c 'isTurnTerminalEvent|shouldNotifyWaiters'` - = **0** — no divergence remains at the terminal-event region ✔ (consistent with - review-TM-01-delta's byte-equality finding; not re-litigated here). -- Mechanism/trace claims (ghost tracked run, await window) are taken from the P2 trace log - and the deterministic pre/post-fix pair; the mechanism itself is not re-verifiable - read-only, but the evidence pair (209/210 → 210/210 on identical trees modulo one hunk) - is present in the logs and supports the claim. - -## 5. Rollback exercise — PASS - -- `/tmp/tmad-port/stream-rollback.md` read in full: coherent backup (`cp -a agents…`) + - per-agent-ID Stream-field export procedure, disable step with expected-stripping warning, - restore-only-Stream-fields rules (never replace whole record, skip deleted agents, don't - clobber newer Stream fields, schema round-trip assertion), verification steps, and honest - limits (point-in-time snapshot, last-write-wins on double-edit). Matches plan P2.4 - (backup/export before disabling; restore merges only Stream fields; no generic-storage - change) ✔. -- Transcript confirmed in phase logs (not just the report's quote): write phase records - `companionEntries: 2 artifacts: 1`; strip phase shows parse-level stripping - (`present in file: true | after parse: false`) plus rewrite persistence and the - disabled-window title rename; restore phase shows `title … preserved` with `restored: 2 | 1` - and schema round-trip true ✔. -- Isolation: demo script (`logs/p2-rollback-demo.ts.txt`) hardcodes - `HOME = "/tmp/tmad-port/rollback-home"`; the only `~/.paseo` mention is the "never …" - guard comment. Scratch `rollback-home/` contains `agents/`, `backup/`, `stream-export.json` - ✔. No live-home contact. - -## 6. Conflict/merge record — PASS - -- End state verified: merged `workspace-tab-menu.ts` contains **both** union members - (`message-circle-plus` + `file-code-2`), both label keys (`newSideConversation`, - `viewArtifacts`), both input props (`onStartSideConversation`, `onViewArtifacts`), and - **zero** conflict markers ✔. The keep-both resolution is sound for the manifest context: - the two icons belong to disjoint features (custom side-conversations vs Stream - view-artifacts) sharing only a union position — a superset union preserves both behaviors - with no semantic interaction. -- Replay consistency: `git diff d238504cf 0ff83cbc5 -- ` → empty - (the only inter-merge delta is the agent-manager fix hunk arriving via the branch). - The rerere replay reproduced the original resolution bit-for-bit, consistent with the - "inspected before keeping" account ✔. -- Report lists the single conflicted file with its resolution plus a 24-file clean-merge - inspection table covering the plan-named shared seams (agent-panel, segmented-control, - turn-footer, message, agent-stream/view, protocol/authorization/i18n maps). The - conflict *count* (exactly one) itself rests on worker testimony — a merge commit does not - record how many files conflicted — but every independently checkable artifact (union - end state, replay identity, additive clean-merge claims spot-checked against the 53-path - set) is consistent with it. No contradicting evidence found. -- Pre-commit hook on the rebuild merge green per `p2b-merge-commit.log` (format check, - 0-warning lint, full-workspace typecheck) ✔. - -## 7. TM-01B decision ("not needed") — CONFIRMED - -- The report's evidence holds: the only textual conflict resolves as a feature-disjoint - union inside the merge (no custom/infi code involved); the one semantic fix restores - reconciled-source semantics and compiles/passes on the release base alone (per the - approved delta review: build/typecheck/lint green, 192/192 + 22/22 on the pure branch). -- Graph-level corroboration re-run here: the with-stream tree delta is exactly TM-01's - 53 paths (PATHS-IDENTICAL, §1) — the merge's non-TM-01 delta is nil beyond the merge - itself, so no commit in the with-stream graph smuggles custom/infi code to make Stream - compile standalone ✔. - -## 8. Manifest block — PASS - -- The FINAL block (Addendum 2) complies with the plan's append rules: existing order - untouched ("retain their current order. APPEND BELOW THEM"), no insertion, TM-03/TM-04 - deferred with dependency-order notes, removal groups named per line (Stream; Queue+Voice; - Native Find), TM-01B explicitly recorded as uncreated, TM-01 SHA refreshed to `a8241e535` - with the fix's delta-reviewed status noted ✔. -- Consistent with STATUS.md's draft in structure and ordering; differs only in the TM-01 - SHA (draft still shows superseded `2197619bc`) and the added fix/verification notes — - the expected update, not a contradiction. STATUS.md itself is the coordinator's file to - refresh (see N1). - -## Gate results audit (spot-checked, not re-run — read-only) - -- Rebuild gates present and green: `p2b-build-server.log` (relay/highlight/plugin exit 0), - `p2b-typecheck.log`, `p2b-lint.log` (0/0, 4604 files = 4589 baseline + 15 Stream files, - consistent with P2's arithmetic), companion 12/12, collector 3/3, auth 7/7 ✔. -- Non-rerun justification accepted: tree equality (§1) makes the rebuilt tree the same - artifact the full 23-file/411-test battery passed on; re-running everything would add no - information. The seam-critical suites (agent-manager incl. isolated steer case) plus - build/typecheck/lint were re-run on the final tree ✔. - -## Findings - -No blocking findings. Two non-blocking notes: - -- (N1, non-blocking) `STATUS.md`'s draft manifest block still pins TM-01 at superseded - `2197619bc`. Coordinator action: refresh to the Addendum 2 FINAL block (`a8241e535`) - when recording this review. No P2 redo — the report already carries the correct block. -- (N2, non-blocking) The "exactly one textual conflict" claim, while consistent with all - checkable artifacts, is not independently provable from the commit graph alone (merge - commits don't record conflict counts). Future assembly reports could preserve the - `git merge` stdout showing the conflicted-file list as a log file. Nothing to redo here: - the resolution end state and replay identity both verify. - -## Verdict rationale - -Final assembly `0ff83cbc5` = frozen baseline + exactly one merge of TM-01 at its fixed tip; -rebuilt tree byte-identical to the fully-batteried interim tree; ancestry clean (carries + -TM-01 in, mine/source/integration out, 25-commit extra set exact); with-stream delta is -exactly the 53 TM-01 paths with a Stream-free baseline; the steer-fence defect is proven -fixed by the pre/post log pair and now lives in the TM-01 branch (no assembly-side commit); -rollback is a coherent export/restore-only procedure demonstrated on copied data with newer -non-Stream metadata preserved; the tab-menu resolution is a sound disjoint-union, replayed -identically; TM-01B correctly unneeded; the FINAL manifest block follows the plan's append -rules. → APPROVE. diff --git a/fork/plans/tmad-port/evidence/review-P6-final-2026-10-08.md b/fork/plans/tmad-port/evidence/review-P6-final-2026-10-08.md deleted file mode 100644 index 5804256b2fa..00000000000 --- a/fork/plans/tmad-port/evidence/review-P6-final-2026-10-08.md +++ /dev/null @@ -1,164 +0,0 @@ -# P6 final integration review (READ-ONLY, Pi/Muse route) - -Verdict: **APPROVE** — full basket `9584b2a669ce90a5df8c9eac66073e85124e90bb`. -Separate frozen+voice `0169f9a839fcdc01d4df04da02872ef3167c6dc9` is a -consistent voice-integration checkpoint with one known, by-design omission -(see §7). No CodeRabbit claim; reviewer route is Pi/Muse per intake rule. - -Reviewer performed zero source edits, commits, pushes, daemon operations, or -test re-runs. All verification is read-only (`git rev-parse/merge-base/show/ -grep`, file reads, existing log inspection) against the EXACT final refs in -their scratch worktrees — not the primary workspace cwd HEAD `e423a8666` -(earlier P6 checkpoint). Test/build claims below are the assembler's evidence -in `/tmp/tmad-port/evidence/P6-assembly.md` plus raw logs, assessed for -honesty and scope, not re-executed. - -Inputs read: `P6-assembly.md`, `P6-conflict-resolution-log.md`, -`review-TM-04.md` (APPROVE of exact `84f11381`). - -## 1. Reviewed refs (exact) - -| Basket | HEAD reviewed | Worktree inspected | -| --- | --- | --- | -| Full current-custom + side-repair + Voice + receipt fix | `9584b2a669ce90a5df8c9eac66073e85124e90bb` | `/tmp/tmad-port/full-custom-plus-voice` (clean) | -| Frozen P6 + Voice + receipt fix | `0169f9a839fcdc01d4df04da02872ef3167c6dc9` | `/tmp/tmad-port/frozen-plus-voice` (clean) | - -Both `git status --short` clean at review time. `git rev-parse HEAD` matches -the SHAs above. - -## 2. Ancestry (all required inputs present, unmutated) - -`merge-base --is-ancestor` at the exact final refs: - -Full `9584` — all YES: -- P0 `2bfcd2e19638484baf1651d69dc0be55df483bcd` YES -- current custom `24f134618cd8a7143615debf927c1ac60b9ba813` YES -- side repair `fddb4fa8587ae377286ffbea3137df4c53bdc7a9` YES -- TM-01 `a8241e53530d6bd0a958971118d6b8b57ff80b0c` YES -- TM-02 `91392d6beed3fc49f9be7496a70b8d5822957d4c` YES -- TM-03 `9ab91bb759be1951bdaa9cbe7bc991cafed2569d` YES -- TM-07 `5f3634ad43256c18f9f41667348c65fe1b03d7f4` YES -- TM-04 `84f11381ceabec13d5deaff6c1e2c05dc67a6c62` YES (via import `5ecb83246`) - -Frozen `0169` — YES for P0 + all four TM SHAs + TM-04 + `e423a8666`; -correctly NO for custom `24f134618` and side repair `fddb4fa85` -(frozen basket by design). - -History shape confirmed: -- `9584` → `6e9fab673` (Voice merge of exact `84f11381`) → `348e5b988` - (side-repair merge) → `505595ab2` (custom merge) → P6 `e423…`. -- `0169` → `af9c9839a` (Voice merge of exact `84f11381`) → P6 `e423…`. -- All five/six reviewed intake SHAs resolve (`rev-parse --verify` OK); - no intake SHA was edited — the only post-merge deltas are the two - assembly-owned commits (`9584`, `0169`) plus the previously approved - `e423a8666` harness mock. - -## 3. Merge/adaptation deltas reviewed (nothing beyond assembly log) - -1. **Native Find / Stream / artifacts menu union** — PASS. At `9584`, - `workspace-tab-menu.ts` retains side-conversation (`message-circle-plus`), - artifacts (`view-artifacts` + separator), and Find (`find-in-chat` + - separator) as independent entries with distinct keys/labels/callbacks. - No contract conflict; matches conflict-log rationale. -2. **Voice+queue composer/client API cleanup + cap hello** — PASS. Single - `listQueuedAgentMessages` at `daemon-client.ts:3764` uses the namespaced - `agent.queue.list.request/response` pair; the duplicate Voice-era - flat-RPC method/import is gone. Composer keeps both Queue selectors - (`supportsDurableQueue`, snapshot, failed outbox) and - `supportsVoiceConcurrentInput`. Cap-hello test expects all three caps - (`companion_stream_port_v1`, `durable_agent_queue`, - `durable_voice_input_v1`). -3. **Session voice ownership × capable-source observation/delivery** — - PASS. `session.ts` at `9584` keeps `hasSideConversationDemand` - (capable-attached-source OR demand flag) and per-source - `forwardSideConversationUpdate` delivery, alongside - `ownsAttachment`/`voiceOwner`/generation gating on the receipt-read - path (`≈L8490–8510`). No dropped behavior found in the read-only - inspection; consistent with the full-basket unfiltered session pass - (373 tests, see §6). -4. **AsyncStorage mock `e423` inherited** — PASS. `session-store.test.ts` - blob `9a89a34f6b8b3b61fcd91e1a23c0f7c99f44d5df` identical in both - finals; the reviewed intake SHAs themselves untouched. -5. **Bootstrap receipt-owner startup fix (`9584`/`0169`)** — PASS and the - only new integration delta since the TM-04 review. Each commit is a - 2-line deletion in `bootstrap.ts` (drop `MessageReceipts` import + - `receipts:` construction arg). Post-fix wiring verified at `9584`: - - `AgentQueueService` constructed receipt-free; `setMessageReceipts` - throws on double-provide (fail-closed against a second owner). - - Sole production `new MessageReceipts` is `websocket-server.ts:707`; - injection `setMessageReceipts` runs at construction, and - `agentQueueService.activate()` runs at `bootstrap.ts:1752` — after - `wsServer` construction and `beginAcceptingConnections`. - - Therefore exactly one shared receipt owner exists BEFORE queue - activation in the daemon startup path. Receipt-gated writes are - `if (this.receipts)`-guarded, so there is no second-owner fork and - no lost-receipt behavior outside the WebSocket startup path; the - pre-injection window is construction-only with dispatch gated on - `activate()`. Unit tests inject explicitly and are unaffected. - -## 4. Rollback / removal evidence (source vs runtime separated) - -- Source/storage: queue-free rehearsals (`365cd7a1c` from P0+Stream+Find+ - custom+side-repair; `97612a458` P0+Stream+Find) structurally lack queue/ - voice layers while preserving carries. Accepted as structural evidence; - root typecheck/lint were not run on the removal-only tree (disclosed). -- Runtime (copied home `/tmp/tmad-port/queue-runtime-custom-copy`, - fake Codex provider, ephemeral loopback, `createTestPaseoDaemon`): - queue-free run and final enabled run both preserve `pending-copy-1` - (rev 1), SHA-256 `eb0fbafe…b2ae3` unchanged before/during/after, 0 - provider queued turns. Logs: `p6-noqueue-custom-runtime.log`, - `p6-final-enabled-runtime.log`. -- Limitation (non-blocking, must stay on the gate list): **zero turns - means dormant preservation, not provider dispatch.** The copied pending - item is synthetic test data attached to a copied idle agent, not an - exercised live agent. This proves no deletion/clobber across - removal→recovery, but proves nothing about provider credentials, - voice-device capture/playback, or live-home migration. The assembly doc - states this honestly; the claim is proportionate. - -## 5. No lost-receipt confirmation - -Single shared `MessageReceipts` initialized in `WebSocketServer` and -injected via `setMessageReceipts` before `activate()`. No second -construction path in production code (`grep new MessageReceipts` at -`9584` hits only `websocket-server.ts` plus `*.test.ts`). Double-provide -throws. No evidence of receipt writes bypassing the shared owner. - -## 6. Build/test log honesty spot-check (not re-run) - -- Full+Voice: `build:server`, `build:app-deps`, root `typecheck`, root - `lint` PASS; client/server focused set 373 passed; composer/voice/ - session set 76 passed. Log tails inspected; no anomalies. -- Frozen+Voice: same build/typecheck/lint PASS; app set 76 passed; - client/server set 215 passed + 1 failed — the known side-conversation - manager broadcast test, expected because frozen omits side repair - `fddb4fa85`. Correctly disclosed, not a merge defect. -- No full suite run (disclosed, per constraint). Worker-approved - unchanged tests trusted without repetition — acceptable. - -## 7. Findings - -No blocking findings. Notes: - -1. Frozen `0169` retains the known side-conversation test failure by - design (missing repair). It is a valid voice-integration checkpoint, - not the ship candidate. The ship candidate is full `9584`. -2. `voiceOwner` optional-typed but single-caller-supplied (already noted - non-blocking in review-TM-04). No action required here. -3. Runtime proof limits in §4 remain open gates, not review failures. - -## 8. Result - -**APPROVE** full basket `9584b2a669ce90a5df8c9eac66073e85124e90bb` -(and, as a checkpoint only, frozen `0169f9a839fcdc01d4df04da02872ef3167c6dc9`). -Reviewed intake SHAs unchanged: P0 `2bfcd2e1`, custom `24f13461`, -side repair `fddb4fa8`, TM-01 `a8241e53`, TM-02 `91392d6b`, TM-03 -`9ab91bb7`, TM-07 `5f3634ad`, TM-04 `84f11381`. - -Remaining gates (coordinator/root, not this review): CI/full suites -remotely; Stream desktop/compact-web + native captures, Korean locale, -label/retention decisions; Native Find 10-point device pass; queue-UI -browser/native captures; provider-credential E2E; voice device -capture/playback, real-provider, and live-home migration; keep parent P6 -worktree at `e423a8666` until root picks a basket; no live-manifest edits, -custom/mine moves, daemon restarts, pushes, or TM-05/06/08 scope. diff --git a/fork/plans/tmad-port/evidence/review-TM-01-delta.md b/fork/plans/tmad-port/evidence/review-TM-01-delta.md deleted file mode 100644 index 160b1253e53..00000000000 --- a/fork/plans/tmad-port/evidence/review-TM-01-delta.md +++ /dev/null @@ -1,148 +0,0 @@ -APPROVE - -# Delta re-review: TM-01 terminal-event seam fix — `2197619bc..a8241e535` - -Reviewer: read-only audit on pluto. No file edited except this report. No npm ci, -installs, builds, or tests executed. No commits, pushes, or ref modifications. -All verification via read-only `git -C /home/ctaylor/repos/paseo` commands -(rev-parse, show, diff, log, merge-base, grep), reading source files at pinned -refs, and reading logs under `/tmp/tmad-port/logs/`. Anything requiring code -execution is marked "not verifiable read-only". - -Inputs read first: `/tmp/tmad-port/plan.md` (Compatibility contracts, Source -tracking, Branch and removal contract, P1/P2), `/tmp/tmad-port/COMMON.md`, -`/tmp/tmad-port/brief-TM01.md`, `/tmp/tmad-port/evidence/TM-01.md` (incl. the -post-P2 addendum), `/tmp/tmad-port/evidence/review-TM-01.md` (prior APPROVE at -2197619bc), `/tmp/tmad-port/evidence/P2.md`. - -## Identity (verified) - -- Claimed HEAD `a8241e53530d6bd0a958971118d6b8b57ff80b0c` resolves exactly ✔ -- `git log --oneline 2197619bc..intake/tmad-stream-flow` → exactly one commit: - `a8241e535 fix(server): restore fire-and-forget artifact collection at the - terminal-event seam` ✔ (one commit appended, no rewrite) -- Single parent `2197619bc4a656104e5ab5738de026e1c8353c0e` (not a merge) ✔ -- `2197619bc` is an ancestor of the branch tip ✔ -- Ancestry still clean at new HEAD (`merge-base --is-ancestor`, all NOT ancestors): - `cbd1210c7` (custom) ✔, `4cc94e07e` (mine) ✔, `51fb7693d` (source) ✔ — - the branch remains release-based; the fix imports no foreign ancestry. - -## 1. Delta scope — PASS - -`git diff 2197619bc..intake/tmad-stream-flow`: **1 file, -`packages/server/src/server/agent/agent-manager.ts`, +4/−1, single hunk**: - -```diff - if (isTurnTerminalEvent(event)) { -- await this.collectArtifactsForTurn(agent); -+ // Artifact collection walks the working directory. Never hold the turn's waiters -+ // on it: upstream settles and notifies at the terminal event, and a steer or -+ // replace admitted during the walk must see the run already settled. -+ void this.collectArtifactsForTurn(agent); - } -``` - -Nothing else touched. The delta is exactly what the fix requires. - -Seam fidelity vs reconciled source `51fb7693d` (line 4012): -- Extracted source lines 4008–4013 vs port lines 3962–3967: `diff` → **BYTE-EQUAL** - (`void` + the two-line rationale comment, verbatim). -- Stronger check: `git diff 51fb7693d a8241e535 -- ` contains - **no hunk mentioning `isTurnTerminalEvent` or the `shouldNotifyWaiters` terminal - region** — the whole dispatch seam now matches source; the P2-reported - `await` divergence is gone. -- The port's separate intentional method relocation remains elsewhere in the file - and is untouched by this delta: the full-file source-vs-port diff shows - `collectArtifactsForTurn` only as a `-` block at the source position and an - identical `+` block beside the backfill helper (bodies identical; pure move, - pre-existing and documented in the TM-01 seam table). All other full-file hunks - are pre-existing beta.3-vs-source-base differences (imports, interfaces), none - introduced by this delta. -- The addendum's archived diff (`/tmp/tmad-port/logs/tmad-seam-vs-source.diff`, - header `c40f776a6..0ec670ac8`) is genuine: target blob `0ec670ac8` equals - `rev-parse a8241e535:`, and its only `collectArtifacts*` entries are the - relocation pair — no call-site divergence remains. - -## 2. Commit message — PASS - -- Local-fix framing ✔ ("TM-01's port changed the source's …", "Restores the - reconciled source semantics", "Assembly semantic resolution"). -- Cites the source line ✔ (`51fb7693d:4012`). -- Carries `Port-Feature: TM-01` ✔, carries **no** `Source-Commit` trailer ✔ - (local fixes stay separate from imports per COMMON.md; `grep -i Source-Commit` - on the message is empty). -- Non-blocking nits (N1/N2 below): a stale P2-assembly sentence copied verbatim, - and trailer-block contiguity. Neither affects code or provenance tooling that - greps the trailer line. - -## 3. Evidence audit — PASS - -Addendum claims vs logs (all under `/tmp/tmad-port/logs/`): - -| Claim | Log | Result | -|---|---|---| -| agent-manager 192/192 on pure branch | `fix-agent-manager-test.txt` | **192 passed (192)** ✔ | -| steer-fallback case passes by name | `fix-steer-fallback-test.txt` | **1 passed \| 191 skipped (192)** ✔ — total reconciles with the full-file count; the test name `"does not replace a newer foreground turn after unavailable steer fallback is admitted"` verified present at line 1107 of the branch's test file. Caveat N3: the log does not echo the `-t` filter, so the by-name selection is consistent-but-not-self-documenting. | -| 22/22 adjacent suites (companion 12 + collector 3 + auth 7) | `fix-adjacent-tests.txt` | **3 files, 22 passed** ✔ | -| build / typecheck / lint green | `fix-build-server.txt` (exit-0 builds incl. cli), `fix-typecheck.txt` (all workspaces, no errors), `fix-lint.txt` (`oxlint `, 0 warnings/0 errors), `fix-format.txt` | ✔ | - -192-vs-210 count explanation — verified plausible, no flag: -- `agent-manager.test.ts` is **not** in the TM-01 delta (`diff --name-only - 6166a7aca..a8241e535` grep count 0), so the pure-branch file is the base file: - base `6166a7aca` version has 190 `it(`/`test(` grep hits (≈192 vitest; the - 2-gap is immaterial — likely parameterized/dynamic cases). -- Custom `cbd1210c7` version has 212 grep hits; the merged tree ran 210. The - baseline/custom side contributes roughly 18–20 fence tests (ACP/GJC/steer), - exactly the direction and magnitude the addendum claims. ✔ - -Not verifiable read-only: that the logged runs reflect the exact HEAD tree -(logs could in principle be stale); scheduling/timing behavior beyond the -unit-tested seam. The mechanism itself (await-window → ghost tracked run) was -trace-verified in P2 and the P2 pre/post-fix 209/210→210/210 pair is the -deterministic proof; this delta review confirms the branch now carries the -identical fix. - -## 4. Routing judgment — CONFIRMED: local fix on TM-01 is correct - -- **Not TM-01B.** The Branch and removal contract creates TM-01B only for - "custom/infi adaptations that cannot compile in TM-01 alone." This fix - restores reconciled-source semantics, needs no custom/infi code, and compiles - + passes on the declared beta.3 base alone (build/typecheck/lint + 192/192 + - 22/22 per logs). A bridge would be the wrong home. -- **Not assembly-only.** P2 §Human decisions is explicit: a manifest line at - `2197619bc` ships the steer regression; assembly-only would leave the defect - in the maintained branch and force every assembler to replay `d17896891`. - The plan's Source tracking rule ("keep local-only fixes as separate - commits") and Update-loop rule ("fix the owning port") both require the fix - to land on TM-01 as its own commit — which is what happened. -- **Source-fidelity restoration, not a custom adaptation** ✔ — the hunk is - byte-equal to `51fb7693d`, comment included; no custom fence code was - touched or needed. - -## Findings - -No blocking findings. Three non-blocking nits: -- (N1, non-blocking) Commit message retains P2's assembly-side sentence "the - same one-hunk fix should be applied to intake/tmad-stream-flow" though it now - lives on that branch (verbatim copy, disclosed in the addendum). Stale - sentence in an immutable message; do not rewrite history to fix it. -- (N2, non-blocking) `Port-Feature: TM-01` is separated by a blank line from the - trailing `Co-Authored-By`, so `git %(trailers)` parses only the latter (prior - branch commits put `Port-Feature` last). The line is present and grep-able; - keep the trailer block contiguous (no blank line) on future commits. -- (N3, non-blocking) Fix-test logs lack command echo (same class as prior - review's N2): `fix-steer-fallback-test.txt` records "1 passed | 191 skipped" - without the `-t` filter string. Future evidence logs should echo the exact - invocation. Credibility is established by count reconciliation + the verified - test name; nothing to re-run. - -## Verdict rationale - -One commit appended, no rewrite, ancestry still release-clean; delta is a single -seam hunk byte-equal to the reconciled source (void + rationale comment) with -the pre-existing relocation untouched; message framing/trailers correct per -COMMON.md; all claimed evidence present in logs with the 192-vs-210 delta -independently sanity-checked against the test files; routing as a TM-01 local -fix is what the plan requires (TM-01B would be wrong, assembly-only would ship -the regression). Prior APPROVE at 2197619bc stands; the delta removes the one -known defect. → APPROVE. diff --git a/fork/plans/tmad-port/evidence/review-TM-01.md b/fork/plans/tmad-port/evidence/review-TM-01.md deleted file mode 100644 index 4928de2c6a8..00000000000 --- a/fork/plans/tmad-port/evidence/review-TM-01.md +++ /dev/null @@ -1,177 +0,0 @@ -APPROVE - -# Review: TM-01 Stream/artifact vertical slice — `intake/tmad-stream-flow` - -Reviewer: read-only audit on pluto. No files edited except this report. No npm ci, -installs, builds, or tests executed. No commits, pushes, or ref modifications. -All verification via read-only `git -C /home/ctaylor/repos/paseo` commands -(rev-parse, show, diff, log, merge-base, grep), reading source files at pinned -refs, and reading implementer logs under `/tmp/tmad-port/logs/`. Anything that -would require executing code is marked "not verifiable read-only". - -Inputs read first, in order: `/tmp/tmad-port/COMMON.md`, `/tmp/tmad-port/plan.md` -(Compatibility contracts > Stream, Source tracking incl. PR19->#21 rehearsal -requirement, Update loop, P1, Branch and removal contract), `/tmp/tmad-port/brief-TM01.md`, -`/tmp/tmad-port/evidence/TM-01.md` (report under audit). - -## Identity (verified) - -- Branch: `intake/tmad-stream-flow`. Declared base `6166a7aca` (v0.11.0-beta.3). -- Claimed HEAD `2197619bc` resolves to `2197619bc4a656104e5ab5738de026e1c8353c0e` — matches. -- Nine commits, `git log --oneline 6166a7aca..HEAD`, in order (oldest first): - `b7672631a` (PR#19 import) → `717b87b18` (rehearsal) → `d39fc66e2`, `1c1f3a196`, - `86d268768`, `9edd6260d`, `cdf819820`, `b78389b8c`, `2197619bc` — matches the report. -- Diff stat `6166a7aca..HEAD`: 53 files, +4132/-51 (report says +4129/-51; trivial - recount delta, same file list). No push performed (read-only; refs verified local-only - by inspection — not verifiable read-only beyond the implementer's claim, accepted). - -## 1. Ancestry — PASS - -`git merge-base --is-ancestor` against HEAD, all FALSE (not ancestors): -- `cbd1210c7` (custom, also `origin/custom` — same SHA) → not-ancestor ✔ -- `4cc94e07e` (also `origin/mine` — same SHA) → not-ancestor ✔ -- `51fb7693d` (source integration) → not-ancestor ✔ -- Cross-branch: `intake/tmad-stream-flow` and `intake/tmad-native-find` are - ancestors of each other in neither direction ✔ (independent in both directions). - -## 2. Commit structure and trailers — PASS - -- Commit 1 (`b7672631a`): trailers `Source-Repo: tmad4000/paseo`, - `Source-Commit: af247e4f4805e0de4736b07aebf2592d9c2e7b39`, `Port-Feature: TM-01` ✔ -- Commit 2 (`717b87b18`): trailers `Source-Repo: tmad4000/paseo`, - `Source-Commit: 51fb7693d`, `Port-Feature: TM-01` ✔ -- Commits 3–9: each carries only `Port-Feature: TM-01`, no `Source-Commit` trailer ✔ - (separate local-fix commits per COMMON.md). Commit subjects map 1:1 to brief step 4 - contracts (wire rename, failure surfacing, bounds, localization, capability gate, - store narrowing, doc flag rename) ✔. - -## 3. Rehearsal claims — PASS with one non-blocking doc nit - -Blob parity recomputed (`git rev-parse :`, source `51fb7693d`): - -At rehearsal commit `717b87b18`: 14 of 15 core files byte-identical to source; -only `stores/agent-view-store.ts` differs (intentional: `findOpen` excluded as TM-07 -scope — verified in file content, seam comment documents it). `docs/artifact-feed.png` -identical. This confirms the rehearsal genuinely converged on the reconciled snapshot. - -At HEAD `2197619bc`: 8 of 15 identical (artifacts/feed, companion model + test, -protocol companion-stream, messages.artifacts.test, backfill.test, artifacts-scan, png). -7 intentional deltas, each matching its stated reason (verified by reading the diffs): -- `docs/companion-stream.md`: single-word `companionStream` → `companionStreamPortV1` - prose rename (commit `2197619bc`; disclosed in report) ✔ -- `companion-stream/feed.tsx`: i18n-ified card titles/triage/empty states/toggle + - "Stream pin" glossary + toast on `accepted:false` ✔ -- `agent-view-store.ts`: `selectedViews: chat|artifacts`, no `findOpen` ✔ -- `server/.../companion-stream.ts` + `.test.ts`: sticky pin/Q&A eviction, - `appendManualCompanionEntry` 100-cap with refusal, 4000-char clipping ✔ -- `artifacts/collector.ts` + `.test.ts`: turn collection capped at - `MAX_RETAINED_ARTIFACTS=200` (source passed `null` for turns), constant renamed - `DEFAULT_BACKFILL_LIMIT` → `MAX_RETAINED_ARTIFACTS` ✔ - -Rehearsal-commit scope (`git show --stat 717b87b18`): 21 files, all Stream-scope -(feed, collector, companion-stream + test, backfill test, scan RPC pair + -authorization + session handler + daemon-client + CLI + i18n keys). No upstream-sync -noise: `message.tsx` ActivityLog→Notification flip absent (message.tsx diff at HEAD -is pin/Q&A-only, +95), no `findInChat`, no `agentMessageQueue` flag (websocket-server -diff is the single `companionStreamPortV1` advertisement hunk only) ✔. - -Non-blocking nit (N1): the report's rehearsal-metrics prose says "11 of 15 core files -byte-identical" at end-state — this number matches neither the rehearsal commit (14/15) -nor HEAD (8/15). The per-file ledger table itself is accurate and every delta is -justified; only the summary sentence is stale. Fix: restate as "14/15 at rehearsal -commit; 8/15 at HEAD after contract fixes" if the report is ever revised. - -## 4. Wire contract — PASS (all verified in file content) - -- Flat `update_companion_entry_request` GONE as a wire op: the only remaining mention - is a code comment explaining the rename (`messages.ts:955`). Dotted pair - `agent.companion.update_entry.request/.response` present with `accepted/error` - payload enabling failure surfacing ✔ -- Authorization exhaustive with correct permissions: - `agent.companion.update_entry.request/.response` = `workspace.write`, - `agent.artifacts.scan.request/.response` = `workspace.read` (responses match their - requests per plan) ✔ -- Single feature flag `companionStreamPortV1` in `server_info.features` (session.ts + - websocket-server advertisement, dated COMPAT tags `v0.11.0-beta.3-fork / 2027-04-01`); - source `companionStream`/`artifactFeed` names appear nowhere in schema, advertisement, - or client registry except an explanatory comment ✔ -- Client capability default `companion_stream_port_v1` present - (protocol client-capabilities + client connection defaults); app declares it at connect; - capability-absent gate covered by new `host-features.test.ts` ✔ -- No `.transform/.catch/.preprocess` in `companion-stream.ts` or the new message schemas ✔; - all new fields optional (`limit?`, `entryId?`, `status?`, `text?`, feature flag optional); - both new outbound types are request-correlated responses (`payload.requestId`), - no pushed top-level events — old clients receive nothing unknown ✔ - -## 5. Behavior contracts — PASS (all verified in file content) - -- Capture after coalescing: `agent-manager.ts` capture guards on `fromHistory` - (`handleStreamEvent` line ~4318 excludes `fromHistory` and `timeline` events; - `attachManagedTurnIdentity`/`collectArtifactsForTurn` placement matches the source seam) — - no second timeline owner, no invented history ✔ -- Bounds: `COMPANION_ENTRY_LIMIT=50` × `COMPANION_TEXT_LIMIT=4000` (source) + - `COMPANION_MANUAL_ENTRY_LIMIT=100` with explicit refusal + pins/Q&A exempt from moment - eviction + `MAX_RETAINED_ARTIFACTS=200` for turns and backfill + - `MAX_SCANNED_ENTRIES=20,000` end-turn scan ceiling ✔ -- NO recursive `fs.watch` anywhere: sole match is a comment citing - docs/file-observation.md for why the scan is bounded ✔ -- Chat stays mounted: `RetainedPanel` wraps chat content, composer stays mounted via - `RetainedPanelActivity` + `hiddenPane` in `agent-panel.tsx` ✔; feed contains no - `sendAgentMessage`/`dispatchComposer`/`cancelTurn`/`grantPermission` path — - selecting a moment navigates/triages only ✔ -- Failed pin/triage mutations surface via panel toast (`toast?.error(t(...mutationFailed))`; - client throws on `accepted:false`) ✔ -- Locales: all 9 files (ar en es fr ja ko pt-BR ru zh-CN) contain the full Stream key set - incl. `streamPin`; ko is port-authored as disclosed (source has no ko parity source) ✔ -- Vocabulary: "Stream pin(s)" throughout; "Pinned prompt" absent from this branch — - no IP-11 collision ✔ -- Tab menu: mobile `view-artifacts` entry (`file-code-2` icon, `onViewArtifacts` input) - alongside existing items; needs no custom/infi code — TM-01B correctly not needed ✔ - -## 6. Scope exclusions — PASS - -- No TM-07 content: `findInChat`/`find-in-chat`/`findOpen` appear on this branch only in - the store seam's explanatory comment; no chat-find code, no search RPC changes ✔ -- No queue/composer changes: diff file list contains no composer/queue/outbox paths; - legacy `send_agent_message` path untouched ✔ -- No `viewArtifacts`-vs-`viewStream` confusion beyond the disclosed mapping (menu label - `workspace.tabs.menu.viewArtifacts` = "View artifacts"; in-feed `agentPanel.stream.viewStream` - = "View stream") — both present, correctly separated ✔ - -## 7. Evidence audit — logs exist; spot-checked - -- `/tmp/tmad-port/logs/tm01-*` present (60+ files): baseline lint/typecheck, per-commit - build/typecheck/test logs, final app/proto/srv test logs, scoped lint logs ✔ -- Spot checks: `tm01-final-app-tests.log` 3 files/41 tests (matches 2 model + 36 i18n + - 3 host-features); `tm01-final-proto-tests.log` 2 files/6 tests (matches 1 artifacts + - 5 update-entry); `tm01-final-srv-tests.log` 4 files/27 tests green; - `tm01-baseline-lint.log` shows the claimed pre-existing failures in untouched files - (`composer/index.tsx` refs/purity, `agent-panel.tsx`, `overlay-root.ts`, stores) ✔ -- Non-blocking nit (N2): `tm01-final-srv-tests.log` records only the vitest summary, not - the invoked command/file list, and 27 does not obviously reconcile with the report's - per-file counts (12 companion + 3 collector + 4 backfill + 7 auth = 26). Future logs - should echo the exact command. The one-test gap is unaccounted for but immaterial - (all green either way). - -Not verifiable read-only: that the logged test/typecheck runs reflect the exact HEAD -tree (logs could in principle be stale); that UI/layout/focus behavior is preserved -(matched source/port screenshots + native evidence are deferred per brief step 6 and -plan P1.6 — correctly flagged as outstanding, not blocking this code review); -device/host-interop behavior (old-client parse-compat, capability gating across forks) -beyond the unit-tested schemas. - -## Findings - -No blocking findings. Two non-blocking documentation nits: -- (N1, non-blocking) Stale "11 of 15" parity summary sentence — ledger table is correct; - fix only if revising the report. -- (N2, non-blocking) Srv-test log lacks command echo; 27 vs 26 count reconciliation — - process improvement for future evidence logs. - -## Verdict rationale - -Ancestry clean, provenance trailers correct, rehearsal converged then intentionally -diverged only for contracted reasons, every Stream wire/behavior contract verified in -file content, scope exclusions hold, TM-01B correctly unneeded, removal group is TM-01 -alone per the Branch and removal contract. UI/native evidence remains deferred work -owned by P1.6, explicitly not part of this branch's acceptance. → APPROVE. diff --git a/fork/plans/tmad-port/evidence/review-TM-02.md b/fork/plans/tmad-port/evidence/review-TM-02.md deleted file mode 100644 index b987ef76812..00000000000 --- a/fork/plans/tmad-port/evidence/review-TM-02.md +++ /dev/null @@ -1,199 +0,0 @@ -APPROVE - -# Review: TM-02 durable queue daemon — `intake/tmad-message-queue` - -Reviewer: read-only audit. No files edited, nothing built or run, no commits, -no pushes, no ref changes. All verification by read-only git inspection -(`rev-parse`, `show`, `diff`, `merge-base --is-ancestor`, `grep`, `log`) and -reading logs under `/tmp/tmad-port/logs/`. Branch HEAD at review time: -`91392d6beed3fc49f9be7496a70b8d5822957d4c` (matches the report's claimed HEAD). -Declared base (custom floor): `cbd1210c7d15fbdaac02cab8375cdcf2dd6bd234`. -Six commits base..HEAD, matching the report's `git log`. - -Read first, in order: `COMMON.md`, `plan.md` (Queue and composer, Voice and -lifecycle, Branch and removal contract, P3), `brief-TM02.md`, `evidence/TM-02.md`. -All section references below are to those documents. - -## 1. Ancestry — PASS - -| Ref | Check | Result | -| --- | --- | --- | -| custom `cbd1210c7` | `merge-base --is-ancestor` vs branch | ANCESTOR — expected floor ✓ | -| mine `4cc94e07e` (= `origin/mine`, same SHA) | `merge-base --is-ancestor` vs branch | NOT ancestor ✓ | -| source integration `51fb7693d` | `merge-base --is-ancestor` vs branch | NOT ancestor ✓ | -| source head `f0d5507d2` | `merge-base --is-ancestor` vs branch | NOT ancestor ✓ | -| commit count `cbd1210c7..HEAD` | `rev-list --count` | 6 ✓ | - -Minor report stale-note (non-blocking, §6.2): the report says the `mine` ref -"does not exist on this host". It does — `4cc94e07e` and `origin/mine` -resolve to the same SHA — and the conclusion still holds (NOT ancestor). -No action needed beyond the correction recorded here. - -## 2. Legacy send contract (plan's hardest line) — PASS - -- Extracted `handleSendAgentMessageRequest` from base (`cbd1210c7`) and branch - and diffed: **IDENTICAL**. Old `send_agent_message_request` with no queue - intent keeps exactly the receipt-backed interrupt path including dedup - (`messageReceipts.send` with `prepare` + `send`, `activeTurnBehavior ?? - "interrupt"` defaulting, `messageId`-less direct send fallback). -- The source's two moves are both absent: - (a) no queuing on omitted `activeTurnBehavior` — the handler never consults - the queue; (b) no receipt bypass — the receipt service call is untouched. -- `send-or-queue.ts` (the helper the source wired the legacy path through) - requires explicit `intent: QueuedAgentDeliveryIntent`; without it the helper - is a plain send. The legacy handler is NOT routed through it (report's - exclusion claim confirmed: `dispatchAgentQueueMessage` handles only - `agent.queue.*`; `send_agent_message_request` dispatches to the unchanged - legacy handler). The branch's `sendOrQueuePromptToAgent` correctly inverts - the source default (source queues any busy prompt; branch queues only with - explicit intent). -- Corroborating test exists on the branch: - `session.test.ts:6055 "a legacy send_agent_message_request never reaches - the queue service"`. - -## 3. Wire / authorization — PASS - -- Dotted `agent.queue.*` `.request`/`.response` names: enqueue, update, - reorder, delete, retry, send_now, list, get_item_images (+ `agent.queue.update` - subscribable event). No flat source names; source `agent.queue.remove` was - renamed to `agent.queue.delete` per `docs/rpc-namespacing.md` as claimed. -- Feature flag `durableAgentQueueV1` in `server_info.features`; distinct - capability `durableAgentQueue` (`durable_agent_queue`) in - `client-capabilities.ts`; client default present - (`packages/client/src/connection/index.ts:150` → `true`). -- `expectedRevision` on all five mutations via shared base - `AgentQueueMutationRequestSchema` (update/reorder/delete/retry/send_now - all `.extend` it); stale revision rejected with `queue_revision_conflict`, - never overwritten (`store.mutateWithExpectedRevision` throws - `QueueRevisionConflictError`, queue untouched). -- Authorization maps exhaustive: all 8 inbound requests in - `INBOUND_PERMISSION` (mutations `workspace.write`, list/get_item_images - `workspace.read`) and all 8 responses plus the `agent.queue.update` event - in `OUTBOUND_PERMISSION` (event is `workspace.read`). -- No `.transform`/`.catch`/`.preprocess` in the new queue schemas. The only - `.transform` lines in the protocol diff are a wire-purity refactor of the - pre-existing `TextAttachmentSchema` (pure `TextAttachmentWireSchema` split - out; queue attachment fields use `AgentAttachmentWireSchema`), consistent - with `docs/protocol-validation.md` — not a violation. -- New enum values (`queue`/`steer_strict` intents, delivery states) gated: - wire comment requires clients to gate on `server_info.features. - durableAgentQueueV1`; daemon only emits `agent.queue.update` to sources - advertising the capability (`canDeliverEventToSource`, both subscribed and - implicit-legacy paths); old-shaped requests parse and take the legacy path - (covered by `messages.agent-queue.test.ts` parse-compat + capability tests). -- No image bytes in snapshots: `QueuedAgentMessageImageSchema` is - descriptor-only (id/mimeType/fileName/byteSize); bytes fetched per-item via - `agent.queue.get_item_images.request` (`service.getItemImages`). - -## 4. Queue semantics (service/store) — PASS - -- Stable identity + accept-once incl. `drainedIds` (bounded - `MAX_REMEMBERED_DRAINED_IDS = 100`); enqueue rejects duplicate ids - including post-delivery. -- Revision-checked edit/reorder/delete (stale rejected, §3); dispatching items - refuse edit/delete; uncertain items require explicit retry/discard first. -- Claim→dispatch→correlated receipt→removal: claim persists `dispatching` - with bumped `attempts`/`attemptSeq` before any send; per-attempt receipt ids - (`itemId#attemptSeq`) through the real `MessageReceipts.send`; removal only - after success, recording `drainedIds`. -- Uncertain vs failed: `activate()` recovery resolves `dispatching` claims - against receipt outcomes (completed→remove; pending→`uncertain` - `agent_request_outcome_unknown`; no receipt→`pending` for `queue` intent, - `uncertain` `queue_claim_interrupted` for `steer_strict`). Never auto-resent: - only explicit `retry` resends uncertain/failed. After - `DELIVERY_ATTEMPT_LIMIT = 8` known failures the item parks in visible - `failed` with `lastError`, explicit retry/discard only. -- Refused steer: `QueueSteerRefusedError` un-claims (`dispatching`→`pending`, - attempt unbumped), never interrupts, never deletes; strict steer goes - through existing `steerAgentRun` admission. -- FIFO hold-the-line: non-head/non-pending items block the drain; `send_now` - cross-head delivery is an explicit revision-checked user action carrying the - post-attempt queue (report flags it as a design call — accepted, inside the - plan's fences). -- Startup: `bootstrap.ts` constructs the service at init but calls - `activate()` only after `beginAcceptingConnections()`; recovery loads - without dispatching, resumes only never-dispatched items on already-idle - agents, holds ambiguous claims; on-demand agents drain on their next - running→idle transition (deliberate, documented). -- Archive/delete: `dispatchPendingItem`/`scheduleDrain` fence on - `isArchived` (archived agents keep queue, never auto-run); agent deletion - calls `agentQueueService?.deleteForAgent` through the normal lifecycle. -- Persistence: atomic writes via `writeJsonFileAtomic(..., { mode: 0o600 })` - (mode applied at temp-file creation, additive `atomic-file.ts` change); - journal before/after with image bytes elided, 64 MiB bound with - previous-generation rotation; queue bound 50 items; image payload bound - 16 MiB; images by reference in journal and snapshots. - -## 5. Custom fences — PASS - -- `agent-manager`/ACP/GJC diff base..HEAD: **untouched** (only - `agent-prompt.ts` changed, +7/−1, additive `replaceRunning?` param defaulting - to `true` = current behavior). Provider-wrapper forwarding intact. -- Queue delivery passes `replaceRunning: false` (losing a busy race fails the - attempt instead of replacing the turn); legacy path keeps the default - (`true`). Fence-preserving by construction. -- Cited fence tests present in logs with claimed counts (§7). - -## 6. Provenance and evidence - -### 6.1 Trailers — PASS with one non-blocking note -- Import commit `eefbfc134`, adaptation `68f863134` (cites both `51fb7693d` - and `f0d5507d2` — correctly records the head journal model), protocol-event - `21b80e206`, wiring `ee8c0d84b`: all carry `Source-Repo: tmad4000/paseo`, - `Source-Commit`, `Port-Feature: TM-02`. Local-only docs commit `91392d6be` - carries `Port-Feature: TM-02` only — acceptable for a local file. -- (Non-blocking) The protocol wire commit `6f76c621e` (landed by the previous - worker) carries **no trailers**. History rewrite to fix one prior commit is - not warranted; record the wire contract's source derivation here instead: - adapted from the `51fb7693d` protocol block with renames per - `docs/rpc-namespacing.md` (`remove`→`delete`, plus new `retry`/`send_now`) - and a distinct capability/flag. Future imports should trailer every commit. - -### 6.2 Blob ledger — recomputed, claims hold -Source blobs at `51fb7693d` vs branch blobs for the five ledger rows all -differ (adapted, as claimed — the report claims no byte-identical files): -`store.ts 7039d635…→5134cea2…`, `service.ts` `ba9ff72e…`→`f0bee779…`, -`send-or-queue.ts 95561c9f…→af81c749…`, `service.test.ts d60a755d…→062944a3…`, -`send-or-queue.test.ts ec208522…→b7b21ee6…`. `store.test.ts` absent at -`51fb7693d` (confirmed) and present at head as `3c6f5446…` (confirmed) — -adapted-from-head claim holds. Deliberate exclusions verified present-as-absent: -no `voiceOwner`/`wrapSpokenInput`/`waitForPendingDispatch` in agent-queue, no -`create-agent` queue plumbing, no `finish-notification` queueing, no -paseo-tools queue integration, no async-`QueueMutator` (local mutator is the -intended sync type under the per-agent lock/tail). - -### 6.3 Logs — cited results confirmed in `/tmp/tmad-port/logs/` -| Claim | Log tail | -| --- | --- | -| 49 queue tests | `tm02-test-all-queue6.log`: 3 files, 49 passed | -| auth 7 | `tm02-test-auth.log`: 7 passed | -| agent-manager 210 | `tm02-test-agent-manager.log`: 210 passed | -| ACP 130 | `tm02-test-acp.log`: 130 passed | -| GJC 43 | `tm02-test-gjc.log`: 43 passed | -| session 157 + 1 pre-existing | `tm02-test-session-full2.log`: 157 passed, 1 failed (`side conversation manager events reach every capable client`), same failure reproduced at base in `tm02-test-sideconversation-base.log` | -| protocol 9, shared 17, queue-session 4 | `tm02-test-protocol-sub`, `tm02-test-shared-files`, `tm02-test-session-queue2` tails match | - -### 6.4 Not verifiable read-only -Test execution itself (relied on the logs above — no `npm`/`vitest` run per -the read-only constraint); daemon e2e behavior (not ported — needs real -provider auth, documented as deferred to TM-03/P4); live crash-recovery and -live mixed-version daemon↔client interop; the side-conversation failure's -root cause below the base commit (report honestly scopes it to the custom -floor and requests a neptune owner — endorsed). - -## 7. Plan contracts — PASS -- Native Find / Stream independence: no `companion` references added; no - stream-file changes in the diff (only pre-existing generic "stream" words); - removal group is additive queue files + narrow seams (`session.ts` - dispatch/delegate, `bootstrap.ts` construct/activate/stop, `websocket-server` - plumb-through, `agent-prompt.ts` optional param, `atomic-file.ts` mode - option, `message-receipts` outcome reader, auth maps, protocol block, docs). -- No removed scaffold resurrected; no Stream dependency in either direction. -- Known gaps (e2e deferral, split mixed-version coverage, send_now cross-head, - strict-steer idle fallback, on-demand resume) are all documented in the - report with rationale inside the plan's fences — no hidden gaps found. - -## Findings -No blocking findings. Non-blocking notes: §6.1 (prior protocol commit -trailers), §1 table (mine-ref wording staleness), both corrected/recorded -above with no code action required. diff --git a/fork/plans/tmad-port/evidence/review-TM-03.md b/fork/plans/tmad-port/evidence/review-TM-03.md deleted file mode 100644 index f5bf1cdd35b..00000000000 --- a/fork/plans/tmad-port/evidence/review-TM-03.md +++ /dev/null @@ -1,197 +0,0 @@ -APPROVE - -# Review: TM-03 queue UI and cross-device behavior — `intake/tmad-queue-ui` - -Reviewer: read-only audit. No files edited except this report, nothing built -or run, no commits, no pushes, no ref changes. All verification by read-only -git inspection (`rev-parse`, `show`, `diff`, `merge-base --is-ancestor`, -`grep`, `log`) against `/home/ctaylor/repos/paseo`, reading source files at -pinned refs, and reading the implementer's logs under `/tmp/tmad-port/logs/`. -Branch HEAD at review time: `9ab91bb759be1951bdaa9cbe7bc991cafed2569d` -(matches the report's claimed HEAD). Declared base: TM-02 APPROVED head -`91392d6beed3fc49f9be7496a70b8d5822957d4c`. - -Read first, in order: `COMMON.md`, `plan.md` ("Queue and composer" contract, -P4, "Branch and removal contract", TM-02 daemon contract), `brief-TM03.md`, -`evidence/TM-03.md`, `evidence/TM-02.md`, `evidence/review-TM-02.md`. - -## 1. Ancestry — PASS (7 commits, no extra ancestry) - -| Ref | Check | Result | -| --- | --- | --- | -| `intake/tmad-message-queue` head `91392d6be` | `rev-parse` both | Identical SHA — base IS the approved TM-02 head ✓ | -| `rev-list --count 91392d6be..HEAD` | count | 7 ✓ | -| custom `cbd1210c7` | `merge-base --is-ancestor` | ANCESTOR (through TM-02 floor) ✓ | -| `v0.11.0-beta.3` `6166a7aca` | `merge-base --is-ancestor` | ANCESTOR (through custom) ✓ | -| source integration `51fb7693d` | `merge-base --is-ancestor` | NOT ancestor ✓ | -| source head `f0d5507d2` | `merge-base --is-ancestor` | NOT ancestor ✓ | -| `929f1add3` (tmad-main-latest) | `merge-base --is-ancestor` | NOT ancestor ✓ | -| `mine` `4cc94e07e` (= `origin/mine`, same SHA) | `merge-base --is-ancestor` | NOT ancestor ✓ | -| `intake/tmad-stream-flow` | both directions | NEITHER is ancestor of the other ✓ | - -Linear history, no merges (`git log --merges base..HEAD` empty). The -`git log --oneline` matches the report exactly (7 commits, same SHAs and -subjects). Custom and beta.3 reach HEAD only via the TM-02 head, which is -the declared and only prerequisite. - -Trailers: all six feature/test commits carry `Source-Repo: tmad4000/paseo`, -`Source-Commit: 51fb7693d…`, `Port-Feature: TM-03`. The docs commit -`9ab91bb75` carries `Port-Feature: TM-03` only — acceptable for a local-only -file (same convention accepted in the TM-02 review). Non-blocking note only. - -## 2. Canonical submission ownership — PASS - -- `dispatchComposerAgentMessage` (actions.ts:220) is byte-untouched: the - base..HEAD diff on `actions.ts` has hunks only at imports, the - `QueuedComposerMessage` interface, and the appended queue section - (@@ line 436+). The submit path (`submit.ts`, `composer/input/`) has an - empty diff — untouched. -- Queue admission (`queueComposerMessage`, actions.ts:264) writes only to - the queue writer (`input.queue.write`, new id via `generateMessageId`); - no submission writer is referenced anywhere in the queue section. -- `queueComposerMessageOnServer` (actions.ts:550): optimistic queued row + - outbox-first write + `enqueueAgentMessage` with explicit `intent: "queue"`, - then `applySnapshot`. On failure with an outbox present it keeps the row - (durable retry path); without an outbox it rolls back the optimistic row. - Never creates a timeline row. -- Tests present on the branch: actions.test.ts:1124 "admits with the - explicit queue intent and never touches a submission writer", - session-store.test.ts:909 "never creates a submitted timeline row: - snapshots only touch the queue", and the e2e asserts exactly one - canonical `user_message` carrying the edited text after drain - (`expect(userRows).toHaveLength(1)`, e2e test file :251). - -## 3. Capability gating — PASS - -- Every durable path gates on `features.durableAgentQueueV1`: - composer selector (index.tsx:1532) and session-context flush - (session-context.tsx:582). Both call sites carry dated - `COMPAT(durableAgentQueue)` comments naming TM-02/TM-03. -- Against old hosts the composer keeps the existing local in-memory queue - with today's rendering/actions; the outbox is written only in durable - mode. Nothing labels the legacy queue durable (glossary Queue-track entry - states both meanings explicitly). -- Protocol diff base..HEAD is EMPTY (no new wire fields — this branch adds - none, as required). Server diff is exactly one additive file: the e2e - test. TM-02's wire contract is consumed unchanged. - -## 4. Controls and revisions — PASS - -- Edit = take (delete + image rehydration via `persistImage`, draft - recovery through returned `{text, attachments}`); reorder = full-id-list - `agent.queue.reorder` from the row menu; delete = confirmed - `agent.queue.delete` (`confirmDialog`); send-now = take-then-submit. - Every mutation sends `expectedRevision`; `queue_revision_conflict` - maps to a visible `conflict` outcome plus queue refresh — never a silent - overwrite (index.tsx:1857-1858, 2228-2229, 2283-2284). -- `isQueueRevisionConflictError` branches on the machine-readable error - code surfaced by the new daemon-client helpers (no prose parsing). -- Outbox exhaustion: `QUEUE_OUTBOX_MAX_ATTEMPTS = 8` (model.ts:48); - entries park with `failedAt` instead of being dropped (model.ts:101-102), - flush skips failed entries, `retryFailedOutboxEntry` is the explicit - retry. Daemon `failed`/`uncertain` rows show `` + - last-error + Retry/Discard (index.tsx:748-750, 791-864). -- Steer/Queue/Interrupt affordances: no diff hunks touching them (grep for - steer/interrupt in the index.tsx diff returns only queue-track lines). -- Typed-send default UNCHANGED: `sendBehavior: "steer"` identical in - branch, base, and source (`storage.ts` diff base..branch is empty); - source-vs-ours comparison present in the report (§"Typed-send default - comparison"). The worker correctly made no product decision. -- Draft attachments / edit recovery: `userAttachmentsOnly` filtering and - image rehydration preserved through take (actions.ts:308, 681); - `plugin_resource` passthrough kept in queue-sync mapping. - -## 5. Two-client daemon e2e — PASS - -- Re-anchored on the in-process harness (`createDaemonTestContext`, - `DaemonClient` from `../test-utils/`, fake permission request parks the - turn) — no provider credentials, consistent with - docs/ad-hoc-daemon-testing.md. No `claude`/credential references in the - test file. -- Coverage confirmed by reading the test: enqueue/edit/reorder/delete - across two clients, `agent.queue.update` mirroring, fresh-client - reconnect via `agent.queue.list`, drain to one canonical row, plus a - stale-revision conflict test. -- Log pair `tm03-test-e2e-8.log` / `tm03-test-e2e-9.log`: 2 passed twice - (22:16, 22:19). Earlier runs e2e-1..4 (1 failed of 2), e2e-5 (error), - e2e-6 (1 failed) are honestly part of the iteration trail; e2e-7 was the - first green run and 8/9 are the claimed stability re-runs. The report does - not hide the failing runs — they exist in `logs/` and the report's claim - is scoped to the final pair. Supersession is honest. -- Coverage split for capability-absent behavior (TM-02 parse-compat + - existing local-queue tests rather than an old-client e2e) is documented - with rationale. Accepted — forcing it into the e2e would need capability - overrides the test client does not have. - -## 6. Localization and docs — PASS - -- `composer.queued.*` (12 keys: menu, moveUp/Down, delete, discard, retry, - sending, unconfirmed, failed, changedOnAnotherDevice, deleteTitle, - deleteMessage) present in ALL nine locales; key-name parity verified by - extracting the `queued: {…}` block per locale — all 8 non-en locales - match en exactly. Each locale file is +14 lines (12 keys + block lines). -- `docs/queue-mirroring.md` gains the composer-side contracts (snapshots - replace/outbox survives, outbox as durable copy, exhaustion parking as a - deliberate source divergence, downgrade behavior). `docs/glossary.md` - gains the Queue-track entry (durable vs legacy meanings distinct) and the - Steer cross-reference keeps the forbidden terms ("Delivery", - "Queued prompt" not used as labels — confirmed absent from UI copy grep). - Terminology matches the plan ("durable" vs "legacy"/"local in-memory"). - -## 7. Provenance and evidence — PASS - -- Ledger recomputed: all five source blobs at `51fb7693d` match the - reported values exactly (`3d6130d6…`, `8b278e1a…`, `ce83ee9c…`, - `64537da4…`, `6d6b7707…`); all five local blobs differ (adapted, as - claimed — no false byte-identical claim). The - `51fb7693d..f0d5507d2` diff on the queue UI paths is empty, confirming - the "newer head is byte-identical" claim. -- Exclusions verified present-as-absent: no `interrupt?: boolean` on sends - (no "interrupt" in the protocol/server diff or daemon-client queue - section), no `voiceOwner`/`wrapSpokenInput`/`waitForPendingDispatch`, - no `companion`/`viewArtifacts`/`selectedViews`/Stream references in the - app diff, side-conversation handlers preserved in session-context - (diff shows only additive queue subscription + flush + unsub). -- Cited logs match claimed results (tails read): - app 8 files/177 passed, server 4 files/56 passed, protocol 9 passed, - typecheck 0 `error TS`, scoped lint 0 warnings/0 errors. -- Source-vs-ours typed-send comparison, PR #36 classification, six known - gaps, and the two design calls (send-now via take+submit; exhaustion - parking) are all recorded with rationale inside the plan's fences. - -## Findings - -No blocking findings. Non-blocking notes (no code action required): - -1. (non-blocking) Prior-commit trailer gap, same class as TM-02 §6.1: the - local-only docs commit carries `Port-Feature` without `Source-*` - trailers. Correct as-is; recorded here for the ledger. -2. (non-blocking) The optimistic-row race (broadcast between optimistic add - and `outbox.add` briefly erases the row, self-heals on the enqueue - response snapshot) is inherited from the source and honestly documented - as gap #4. A future hardening could write the outbox entry - synchronously before the image-encoding await; not required for approval - since the window is small and self-healing. -3. (non-blocking) Gap #6 (no browser/native screenshot evidence for the new - badges/menu rows) is openly declared; a human pass on the dev app is the - natural next check, per the report. - -## Not verifiable read-only - -Test execution itself (relied on the logs above — no `npm`/`vitest` run -per the read-only constraint); live two-device daemon interop and -crash-recovery behavior; native rendering of the new queue-track controls; -the PR #36 update-loop candidates (correctly deferred, not claimed). - -## Plan contracts — PASS - -- Native Find / Stream independence: no companion/Stream references added; - removal group is additive queue files + narrow seams (composer actions, - session-store snapshot applier, session-context subscription/flush, - daemon-client helpers, i18n, docs, e2e test). No removed scaffold - resurrected; no Stream dependency in either direction. -- Queue removal (TM-02 + TM-03 + descendants) remains coherent: this branch - layers strictly on the TM-02 head with no other ancestry. -- The branch respects its lease: no protocol change, no typed-send flip, no - silent deletion at the retry cap, no manifest edit, no push, no daemon - restart, no full-suite run. diff --git a/fork/plans/tmad-port/evidence/review-TM-04-2026-10-08.md b/fork/plans/tmad-port/evidence/review-TM-04-2026-10-08.md deleted file mode 100644 index f3f33b59905..00000000000 --- a/fork/plans/tmad-port/evidence/review-TM-04-2026-10-08.md +++ /dev/null @@ -1,145 +0,0 @@ -# TM-04 independent review (READ-ONLY, Pi/OpenCode Go Muse route) - -Verdict: **APPROVE** — reviewed SHA `84f11381ceabec13d5deaff6c1e2c05dc67a6c62`. - -Reviewer route: Muse Spark via Pi (this session). No source edits, commits, -pushes, daemon operations, external messages, or test executions were performed. -All verification is read-only (`git rev-parse/log/diff/show/status`, -`rg --files`, file reads). Test/validation claims below are the worker's -evidence in `/tmp/tmad-port/evidence/TM-04.md`, assessed for honesty and scope — -not re-executed here per the no-duplicate/no-broad-test constraint. - -## Identity and ancestry - -- Workspace: `/home/ctaylor/.paseo/worktrees/3rzqjhby/tmad-voice-flow-r2` - (branch `intake/tmad-voice-flow`, clean worktree at review time). -- Base TM02 `91392d6beed3fc49f9be7496a70b8d5822957d4c`: ancestor ✓ -- Pinned custom floor `cbd1210c7`: ancestor ✓ -- Pinned release `6166a7aca`: ancestor ✓ -- Source integration `51fb7693d`: NOT ancestor ✓ (extraction only, never merged) -- `mine`: absent ref on this host ✓ (nothing to check) -- Commit stack is linear on the base, both required commits present: - `91392d6be` → `5ecb83246` (import) → `84f11381` (fix). `git status` clean. - -## Commit trailers - -- Import `5ecb8324625de55dc80345f181518da26f2d42db`: `Source-Repo: - tmad4000/paseo` + four `Source-Commit` trailers - (`2ec044bf…` PR13, `de193682…` PR15, `af517bc7…` PR22, `e309257e…` PR23) + - `Port-Feature: TM-04`. Compliant. -- Fix `84f11381ceabec13d5deaff6c1e2c05dc67a6c62`: `Port-Feature: TM-04` only, - no source trailers. Correct as a local-only correction commit per COMMON.md - (keep local fixes separate from imports); its message describes receipt - reconciliation and transport fencing, which matches its 17-file stat. - -## Scope boundaries (all pass) - -- Native deltas byte-identical to TM02: `git diff HEAD -- - packages/expo-two-way-audio/` is empty. No TM06 background/native substrate. -- TM05 excluded: no `voice-input-command`, `voice-mute`, or mute paths anywhere - in the base→HEAD name list; both TM05-only paths confirmed absent at HEAD. -- Typed send unchanged: `composer/input/state.ts` diff touches only - `stopRealtimeVoice` (removes the agent-cancel path); send defaults, - `paseo-tool-policy.ts`, and `bootstrap.ts` are untouched. `paseo-tools.ts` - speak change is graceful degradation when voice is detached (settle with a - chat-continuation message), not a policy rewrite. -- `useUnistyles()` → `withUnistyles` migration present in the touched overlay. - -## Protocol compatibility and capability/authorization (pass) - -- New wire fields (`attachmentId`, `generation`, `error`, receipt - request/response, `SetVoiceMode` echo) are all `z.…​.optional()`; no - `.transform()/.catch()/.preprocess()` in the diff. New RPC uses the dotted - `voice.input.receipts.read.request/.response` pair. -- Capability `durableVoiceInputV1` carries a `COMPAT(durableVoiceInputV1)` tag; - UI gates mid-turn voice entry on `serverInfo.features.durableVoiceInputV1` - (old-host busy restriction retained). -- Authorization maps cover the new RPC in both directions - (`workspace.read`). Client defaults advertise the cap; `DaemonClient` adds - receipt-read and `VoiceTransport`-threaded audio/abort/played calls. - -## Queue durability / crash / replay / revision / removal (pass) - -- Spoken input always enters the TM-02 durable queue (idle or busy) with a - stable `${attachmentId}:${requestId}` identity; typed prompts keep the TM-02 - busy precondition and the out-of-band escape (out-of-band is skipped for - speech, with a justified complexity-disable comment). -- Permission fences: `blockPendingPermissions: true` on queued dispatch, - `replaceRunning: false`, drain holds while a permission is pending, and - `permission_resolved` / count-to-zero drain wakeups. -- Archived-agent fence: `replaceRunning === false` path throws "Queued agent - is archived" before provider entry — no false turn-start receipt. -- Removal validates under the queue mutation lock (revision-checked) and writes - the `removed` tombstone before filtering; re-admission of a - completed/removed id is refused via the receipt record, which outlives the - bounded `drainedIds` window. -- `message-receipts`: logical speech completion is written before attempt - completion (crash stays pending/uncertain, never replays); completed/removed - dominate older attempts; attachment reads are scoped by - `attachmentId`+`voiceOwner`; in-process `sending` maps to wire `queued` and - completed receipts to wire `submitted` ("sent to agent", not heard audio). - -## Ownership, cancellation, audio lifecycle (pass) - -- `voiceOwner` is the `principalId/clientId` pair, saved at session creation; - receipt reads require `ownsAttachment` (stale device refused); generation - rotates per attachment registration and mismatched generations are rejected - across audio/abort/played/admission paths (fenced in both commits). -- Voice stop ≠ agent cancellation: `stopRealtimeVoice` now detaches mic/playback - only; the overlay keeps a separate explicit Interrupt control. Attach/detach - never restarts, replaces, or interrupts the running turn (code comment and - `voice-session.ts` paths agree). -- Audio: playback/preparation registration precedes init/decode so stop cancels - preparation; one queue processor retained across stop/replacement; no PR14 - native playback-complete event or background implementation. -- System-prompt handling no longer rewrites the running session on attach; - spoken prompts are wrapped (`wrapSpokenInput`) with a chat-visible-reply - instruction. - -## Provenance ledger (pass, sampled) - -- Spot-checked HEAD blobs match the evidence ledger: generator script - `dba28c97…`, `voice-failure.ts` `b98b2b39…`, voice-history regression test - `6dab8d20…` (byte-for-byte retained, as is the TTS manager). TM05-only paths - confirmed absent. Full-ledger re-verification is the coordinator's - prerogative; no mismatch was found in the sample or in the structural claims - (unchanged/adapted/excluded rationale is coherent throughout). -- Source integration `51fb7693d` ancestry correctly absent; ledger's dual-blob - (integration + effective selected commit) treatment of PR22/23 postdating the - integration snapshot is sound. - -## Evidence honesty and the known base failure (pass) - -- TM-04.md discloses scope honestly: synthetic STT/turn/agent-state harnesses - (not provider or physical-audio proof), ACP smoke 12-skipped supplying no - live proof, no provider implementation changed, serialized builds, the - accidental overlapping Session log excluded from final evidence. -- The `session.test.ts` side-conversation broadcast failure is reproduced on - unmodified TM02 base and left unpatched here — correctly NOT treated as a - voice regression. The separate fix/review `fddb4fa8587ae377286ffbea3137df4c53bdc7a9` - is out of scope for this review; root integrates it separately. No - side-conversation/subagent/child paths appear in the TM-04 diff, consistent - with that attribution. -- Physical/live-provider gates are listed as open human checks with no - fake-based claims. No merge/push/deployment performed by the worker. - -## Findings - -No blocking findings. Two non-blocking notes for the integrator (not review -failures): - -1. `voiceOwner` is documented "Required when origin is set" but typed optional; - the sole voice admission path (`session.ts`) always supplies it. A - fail-closed `throw` in `enqueue` would harden this, but the current - single-caller invariant is acceptable. -2. The fix commit could reference the reproduced base failure SHA in its body - for future archaeology; the evidence file already records it. - -## Result - -**APPROVE** for final HEAD `84f11381ceabec13d5deaff6c1e2c05dc67a6c62` -(over base TM02 `91392d6beed3fc49f9be7496a70b8d5822957d4c`, via required import -`5ecb8324625de55dc80345f181518da26f2d42db`). Remaining gates are the -coordinator's: CI/full suites remotely, human device/provider checks per -TM-04.md, and separate integration of the side-conversation fix. No follow-up -review iteration requested. diff --git a/fork/plans/tmad-port/evidence/review-TM-07.md b/fork/plans/tmad-port/evidence/review-TM-07.md deleted file mode 100644 index 37d6025b911..00000000000 --- a/fork/plans/tmad-port/evidence/review-TM-07.md +++ /dev/null @@ -1,144 +0,0 @@ -APPROVE - -# Review: TM-07 Native Find — `intake/tmad-native-find` - -Reviewer: read-only audit on pluto. No files edited except this report. No builds, -tests, installs, commits, or ref modifications performed. All verification via -read-only `git -C /home/ctaylor/repos/paseo` commands (rev-parse, cat-file/show, -diff, log, merge-base, grep) plus reading source files and `/tmp/tmad-port/logs/`. - -Inputs read first, in order: `/tmp/tmad-port/COMMON.md`, `/tmp/tmad-port/plan.md` -(Scope row "Native chat search wrapper", Branch/removal TM-07 row, Verification -"Native Find" row, P6), `/tmp/tmad-port/brief-TM07.md`, -`/tmp/tmad-port/evidence/TM-07.md`. - -## Identity (verified) - -- Branch: `intake/tmad-native-find`. Base: `6166a7aca` (v0.11.0-beta.3) — HEAD's - sole parent is `6166a7aca` (`log --format='%H %P'` → `5f3634ad… 6166a7aca…`). -- HEAD `5f3634ad43256c18f9f41667348c65fe1b03d7f4` matches the claimed SHA exactly. -- Single commit (`log --oneline 6166a7aca..intake/tmad-native-find` → one line). -- Trailers present on the commit: `Source-Repo: tmad4000/paseo`, - `Source-Commit: 51fb7693d`, `Port-Feature: TM-07`. (blocking-grade provenance OK) -- Diff stat matches the report: 21 files, +499 / -9, same file list. - -## 1. Diff vs declared base — correctness (verified by reading the diff) - -- Base stub confirmed no-op: `6166a7aca:…/chat-find/index.tsx` renders `children` - directly and `useChatFindSelectedMessageId` returns null. The port replaces it - with the real wrapper; no removed search scaffold resurrected (`model.ts`, - `index.web.tsx`, `viewport.web.ts`, `ranges.web.ts`, both web tests, `types.ts` - all have identical blobs across base→source→HEAD; rechecked `model.ts`, - `index.web.tsx`, `viewport.web.ts`, `ranges.web.ts`, `types.ts` myself). -- History loading for out-of-window matches: `chat-find/index.tsx` `load()` calls - `getHostRuntimeStore().fetchAgentTimeline(serverId, agentId, - planTimelinePromptJump({epoch, seq}))` — the existing search model/RPC path, - shared with web. Present as claimed. -- Selected-row reveal/highlight: `native-viewport.ts` `reveal()` polls - `revealLoadedMessage` until mounted, then `viewportRef.current.scrollToMessage`, - counts via `countTextMatches`; `strategy-native.tsx` implements - `scrollToMessage` (history index → `scrollToIndex` viewPosition 0.5; live-head → - `scrollToOffset` 0) plus `onScrollToIndexFailed` estimate-and-retry. Row tint via - `ChatFindExpansion` in `index.tsx` + `strategy-native.tsx` wiring. Present. -- Tab-menu invocation (native): `workspace-tab-menu.ts` adds mobile-gated - `find-in-chat` item (`search` icon, `onFindInChat` input); `workspace-screen.tsx` - `handleFindInChat` sets `findOpen` then focuses the agent tab via - `openWorkspaceTabFocused` + `navigateToTabId`, threaded through - `MobileWorkspaceTabSwitcher → MobileWorkspaceTabOption → menu`. Present. -- Cleanup on hide/unmount: `useEffect(() => () => model.close(), [model])` and - `useEffect(() => { if (!active) close(); }, [active, close])` with - `useRetainedPanelActive()`. Present. -- No Stream code: full-branch `grep -in companion|selectedView|updateCompanionEntry| - viewArtifacts|stream-feed|agent-queue|queue-outbox` over the touched chat-find, - strategy, store, and tab-menu paths → no matches; full `diff base..HEAD` piped - through the same patterns → clean. No protocol/server/authorization files in the - diff (`--name-only | grep protocol|server/|authorization` → empty), so the - report's "no new wire field/RPC/capability, authorization suite not implicated" - claim holds structurally. -- Locales: all 9 locales (`ar en es fr ja ko pt-BR ru zh-CN` — the complete set in - `packages/app/src/i18n/resources/` besides non-locale `plugin-settings.ts`) gain - exactly the two keys `paneFind.updateHost` and `workspace.tabs.menu.findInChat`. - Spot-checked `en`/`ar`: `updateHost`/`findInChat` values verbatim match source; - `viewArtifacts` count is 0 in every local locale file. (Note: source `ar` - `viewArtifacts` is untranslated English; correctly excluded regardless.) - -## 2. Provenance (verified by recomputation) - -All six claimed byte-identical blobs recomputed and MATCH: -`chat-find/index.tsx` ee2a2a5…, `matches.ts` ce070d6…, `matches.test.ts` 13fc311…, -`native-viewport.ts` 269fc7a…, `native-viewport.test.ts` 685a7c8…, -`strategy-native.tsx` 5256ffa… (`rev-parse 51fb7693d:

` == `rev-parse -intake/tmad-native-find:

` for each). -- Adapted-file exclusions spot-checked: source `agent-view-store.ts` owns - `selectedViews/setSelectedView/getSelectedView`, local has `findOpen` only; - source `workspace-tab-menu.ts` gates Find *inside* the `onViewArtifacts` block - with a `view-artifacts-separator`, local gates Find independently on - `onFindInChat` with its own `find-in-chat-separator` (disclosed adaptation, so - Find works without the artifacts sibling); local `handleFindInChat` drops the - source's `setSelectedView(…, "chat")` call and there is no `handleViewArtifacts`; - no `viewArtifacts`/`FileCode2`/`selectedView`/`companion` strings on the branch - in the touched screen files. The excluded-items table (MAX_CONTENT_WIDTH, - NavigationBackButton, compact-time-ago rename, mermaid/presentation churn, - chat-outline, panel-store restoreNavigationView, enabledOnMobile/onPressIn) is - consistent with the observed diff, which contains none of them. - -## 3. Ancestry and independence (verified) - -- `merge-base --is-ancestor` → NOT ancestor for each of: custom (`cbd1210c7`), - frozen mine (`4cc94e07e`), `origin/mine`, source integration (`51fb7693d`), - PR#19 (`af247e4f4`). Base `6166a7aca` IS an ancestor. Release-based: PASS. -- Both directions vs `intake/tmad-stream-flow` and `intake/tmad-message-queue`: - neither contains the other in any of the four checks. No companion/queue - references on this branch (see §1 grep). No Stream dependency either direction: - PASS. Removal group TM-07-alone is structurally sound (single commit, no - descendants required). - -## 4. Plan contracts (verified) - -- Reuses existing search model/RPC (`ChatFindModel`, `searchAgentTimeline`, - `fetchAgentTimeline`, `agentHistorySearch` host flag); no scaffold resurrected - (web/model blobs untouched — §1). The `COMPAT(agentHistorySearch)` carry matches - an existing upstream flag; no protocol files touched, so no authorization-map or - capability entries were owed. PASS. -- Scope-row contract ("not a strict Stream dependency", Chat/Stream segments are - TM-01 scope): honored — segmented-control/store-view and artifacts entries - excluded, Find entry independently gated. PASS. -- Removal group Native Find alone: PASS (§3). - -## 5. Evidence audit - -Personally verified (method in §§1–4): identity/HEAD/trailers/diff-stat; -all six blob-parity claims; all adapted-file exclusion spot-checks; locale keys -in all 9 files + verbatim values + zero `viewArtifacts`; history-load, -reveal/highlight, menu-invocation, and cleanup code paths by reading the branch -content; no-Stream and no-protocol-touch by diff-wide grep; all five ancestry -non-ancestor results + base ancestry; four-direction independence from the Stream -and queue branches; base stub no-op status. -- Not verifiable read-only on this host: every test-run claim (vitest files, - typecheck, lint, format, builds, pre-commit hooks). The cited logs - `/tmp/tmad-port/tm07-*.log` do not exist here (`ls /tmp/tmad-port/tm07-*` → - no such file) and `/tmp/tmad-port/logs/` contains no `tm07*` entries (implementer - ran on neptune). This includes the "pre-existing failures" resolutions and the - pi-lens advisory disposition. None is contradicted by the repo; the typecheck- - before-build failure mode described is plausible for a fresh worktree. -- No claim found that contradicts the repo. Minor note (not a discrepancy): the - report's per-locale "source blob → local blob" table lists 12-char prefixes that - were not individually recomputed here; the substantive content (two keys added, - `viewArtifacts` omitted, values verbatim) was verified directly and holds. - -## Findings - -No blocking findings. No non-blocking code findings either — the diff is -Find-scoped, the adaptations are disclosed and correct, and the bar (plan -contracts + brief, not style) is met. - -Non-blocking follow-ups for promotion (already owned by the report's "Native -evidence still required" section; not gates on this review since the brief defers -device evidence to later): -1. (non-blocking) Run the report's 10-item native checklist (reachability, - focus, loaded/historical/live-head matches, wrap-around, cleanup, older host, - keyboard, rotation, non-Latin locales) on iOS simulator + Android before P6 - promotion. -2. (non-blocking) Expect the known adapted merge with TM-01 on - `stores/agent-view-store.ts` + `workspace-tab-menu.ts` (`findOpen` vs - `selectedViews`/`viewArtifacts`); integrator-owned, not a defect in this branch. diff --git a/fork/plans/tmad-port/evidence/stream-rollback.md b/fork/plans/tmad-port/evidence/stream-rollback.md deleted file mode 100644 index 4ec942504d3..00000000000 --- a/fork/plans/tmad-port/evidence/stream-rollback.md +++ /dev/null @@ -1,75 +0,0 @@ -# Stream rollback — backup/export and restore procedure (TM-01 removal group) - -Applies when disabling the Stream port (`intake/tmad-stream-flow`) on a host whose agent records -may contain Stream data. P2 proved the mechanics on copied data (`/tmp/tmad-port/rollback-home`, -logs `p2-rollback-{1-write,2-export,3-strip,4-restore}.log`); this is the operator procedure for a -real host. **Never point any of this at a live `~/.paseo` without the user's explicit OK.** - -## What beta.3 storage does to Stream data - -`STORED_AGENT_SCHEMA` in `packages/server/src/server/agent/agent-storage.ts` is a plain `z.object`. -When Stream is absent, parse **silently strips** `companionEntries` and `artifacts`, and the next -ordinary record rewrite persists the stripped form. This is expected beta.3 behavior — do not "fix" -it with a generic-storage change (plan P2.4). - -- `companionEntries`: Stream pins, questions, Q&A, outcomes (bounded per TM-01: ≤100 manual, - ≤50 captured moments). -- `artifacts`: artifact feed metadata (bounded ≤200/agent). - -## Before disabling (while Stream is still running) - -Per agent record file under `$PASEO_HOME/agents/**/.json`: - -1. **Back up** the whole agents dir: `cp -a $PASEO_HOME/agents $PASEO_HOME/agents.backup-`. -2. **Export** the Stream fields per agent ID into one JSON file: - - ```jsonc - // stream-export.json — { "": { "companionEntries": [...], "artifacts": [...] } } - // Only agents that actually carry Stream fields get an entry. - ``` - - The P2 demo script does both steps (fs.cp backup + export): - `/tmp/tmad-port/logs/p2-rollback-demo.ts.txt` — phase `export`. Adapt the two constants at the - top (`AGENTS_DIR`, `EXPORT_PATH`) to the host and run it with the repo's tsx on a tree that has - Stream enabled. - -3. Verify `stream-export.json` parses and covers every agent you expect (count keys vs agents with - Stream data). - -## Disable Stream - -Remove/comment the `intake/tmad-stream-flow` line (and TM-01B if it ever exists) from the manifest -and rebuild/restart per the normal desvio process. Expect the stripping above: any agent record the -disabled daemon rewrites loses `companionEntries`/`artifacts` but keeps every non-Stream field. -A user removing Stream permanently can skip the export and intentionally discard the data. - -## After re-enabling: restore only Stream fields - -For each exported agent ID, load the **current** record and merge **only** `companionEntries` and -`artifacts` onto it, then save. Rules the demo proves (phase `restore`): - -- **Never replace the whole record.** Newer non-Stream metadata written while Stream was disabled - (title, labels, config, status, timestamps) must survive. Demo: a title rename from the disabled - window survived the restore. -- **Skip deleted agents** (`get(id)` returns null → skip with a note; do not resurrect). -- **Do not restore if the current record already has newer Stream fields.** Restore is meant to run - right after re-enabling, before the user creates new Stream data. If in doubt, ask; the backup - from step 1 remains the fallback. -- After the merge, the record must round-trip `parseStoredAgentRecord` (the demo asserts this). - -The demo script's phase `restore` implements the merge; phase `write` shows the record shape used. - -## Verification after restore - -1. `parseStoredAgentRecord` accepts every restored record (no schema drift). -2. The feed shows the restored pins/Q&A/artifacts for a re-enabled agent. -3. Non-Stream fields compare equal to the pre-restore current record. - -## Limits - -- The export is a point-in-time snapshot: Stream data written after the export and before disabling - is not in it. Export immediately before disabling. -- The restore is not a three-way merge: if Stream data changed both in the export and on the record - since, last write (the export) wins for the Stream fields. Hence rule 3 above. -- Both scripts assume the on-disk layout `$PASEO_HOME/agents/**/.json` (beta.3 - `AgentStorage.buildRecordPath`). diff --git a/fork/tmad-removal.md b/fork/tmad-removal.md new file mode 100644 index 00000000000..7996e614ab7 --- /dev/null +++ b/fork/tmad-removal.md @@ -0,0 +1,29 @@ +# TMAD-derived code removal + +The 0.16 basket carried a port of `tmad4000/paseo` work: a durable agent message queue, the companion-stream feed, stream artifacts, native Find, and optional voice input. This branch removes it and keeps the rest of the fork. + +## Provenance + +- Port commit `6b5d24312` ("feat(tmad): Port Pluto stream, queue, Find and voice work"), parent `b388a10a7`. +- Follow-ups on the same surface: `36f5b74fa`, `b0b92121b`, `139e0c81e`, `913689b2e`. +- Basket carries: `27daed7df` (0.12 baseline merge), `5198bd3a5` (0.14 adaptation). The TMAD delta itself is `84ba5a691..79422b485`. +- Source is Apache-2.0; no licence obligation outlives the code. + +## How the removal was made + +Reverse-apply `84ba5a691..79422b485` onto the released 0.16.0-beta.2 tree (`99e212869`, identical to `origin/custom` `1c46a58f6`), then resolve every conflict toward upstream 0.16 and the fork's own carries. `23bae6153` is the upstream line to compare against when a hunk is ambiguous. + +Two resolutions are worth reading before touching this area again: + +- **`speak` registration.** The carry registered the tool for every agent-scoped catalog (`scope === "agent"`), so agent sessions that never attached voice advertised a tool that then failed. Registration is back to `voiceOnly || enableVoiceTools || callerContext.enableVoiceTools`, and an unattached call throws instead of settling. App-level voice chat still works because `voice-session` registers the caller context with `enableVoiceTools: true`. +- **Protocol schemas.** The TMAD request/response pairs are gone from `packages/protocol` rather than retained behind per-RPC shims. A 0.16.0-beta.2 app that still sends one fails inbound validation and gets a structured `rpc_error` with `code: "unknown_schema"` and its `requestId` (`websocket-server.ts`, `handleInvalidInboundMessage`), which its pending request surfaces as a rejection. A re-port has to restore the schemas and the removed `CLIENT_CAPS` entries. + +## What stays + +Fork carries that are not TMAD: side conversations, retained panels, provider accounts and rename migration, checkout base refs, outbound-byte metrics, the turn timing footer, the pinned prompt, plan copy sources, shared-turn steering (`PeerTurnActiveError`), app-level voice (`voice-session`, `speak`, TTS playback), and upstream 0.16's own composer queue (`sendBehavior: "queue"`), which is unrelated to the removed durable queue. + +## Evidence + +- `rg 'AgentQueueService|companionEntries|AgentArtifactSchema|durableAgentQueueV1|companionStreamPortV1|durableVoiceInputV1|voiceOwner' packages` is empty. +- No removed module has an importer; the file-level check that found `agent-stream/native-message-scroll.ts` orphaned is why it is gone too. +- `websocket-server.relay-reconnect.test.ts` asserts the legacy-RPC `rpc_error` path. diff --git a/packages/app/e2e/browser/agent-message-submission.spec.ts b/packages/app/e2e/browser/agent-message-submission.spec.ts index 78ec9c975d8..24f26f1c44f 100644 --- a/packages/app/e2e/browser/agent-message-submission.spec.ts +++ b/packages/app/e2e/browser/agent-message-submission.spec.ts @@ -22,8 +22,6 @@ import { fillComposerDraft, holdSendButton, sendDraftToQueue, - configureComposerQueueSend, - queueComposerWithButton, startRunningMockAgent, submitMessage, } from "../support/helpers/composer"; @@ -75,150 +73,6 @@ const IMAGE = { ), }; -for (const width of [1280, 390]) { - baseTest( - `U2d durable queue admits, deletes and promotes independent items at ${width}px`, - async ({ page }, testInfo) => { - await page.setViewportSize({ width, height: 960 }); - await configureComposerQueueSend(page); - const wire = await installDaemonWebSocketGate(page); - const agent = await seedRunningMockAgentWorkspaceForQueue(page, width); - const receipts = []; - try { - for (const action of ["delete", "promote"] as const) { - const prompt = `U2d ${action} independent item ${width}`; - await fillComposerDraft(page, prompt); - await queueComposerWithButton(page); - await expect - .poll(async () => - (await agent.client.listQueuedAgentMessages(agent.agentId)).items.map((item) => ({ - text: item.text, - deliveryState: item.deliveryState, - })), - ) - .toEqual([{ text: prompt, deliveryState: "pending" }]); - receipts.push(await agent.client.listQueuedAgentMessages(agent.agentId)); - await expect(page.getByText(prompt, { exact: true })).toBeVisible(); - await expect(page.getByRole("button", { name: "Send queued message now" })).toBeVisible(); - await expect(page.getByText("Sending...", { exact: true })).toHaveCount(0); - await expect(page.getByText("Unconfirmed", { exact: true })).toHaveCount(0); - await page.screenshot({ path: testInfo.outputPath(`queue-${action}-pending.png`) }); - if (action === "delete") { - await page.getByRole("button", { name: "Queued message options" }).click(); - const confirmation = page.waitForEvent("dialog"); - const deleting = page.getByText("Delete", { exact: true }).click(); - const dialog = await confirmation; - expect(dialog.type()).toBe("confirm"); - expect(dialog.message()).toBe( - "Delete queued message?\n\nIt will be removed for every device connected to this agent", - ); - await dialog.accept(); - await deleting; - await expect(page.getByText(prompt, { exact: true })).toHaveCount(0); - await expect(page.getByTestId("user-message").filter({ hasText: prompt })).toHaveCount( - 0, - ); - } else { - await page.getByRole("button", { name: "Send queued message now" }).click(); - await expect( - page.getByTestId("user-message").filter({ hasText: prompt }), - ).toBeVisible(); - } - await expect - .poll(async () => (await agent.client.listQueuedAgentMessages(agent.agentId)).items) - .toEqual([]); - await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount( - 0, - ); - receipts.push(await agent.client.listQueuedAgentMessages(agent.agentId)); - } - expect(wire.getClientRequestCount("agent.queue.enqueue.request")).toBe(2); - expect(wire.getClientRequestCount("agent.queue.delete.request")).toBe(2); - await testInfo.attach("queue-daemon-and-wire", { - body: JSON.stringify({ receipts, requests: wire.getClientRequestCounts() }, null, 2), - contentType: "application/json", - }); - await page.screenshot({ path: testInfo.outputPath("queue-promoted.png") }); - } finally { - await agent.cleanup(); - } - }, - ); - - baseTest( - `U2d absent queue capability keeps the local queue with zero durable RPC at ${width}px`, - async ({ page }, testInfo) => { - await page.setViewportSize({ width, height: 960 }); - await configureComposerQueueSend(page); - const wire = await installDaemonWebSocketGate(page); - wire.setServerFeaturesStripped(["durableAgentQueueV1"]); - const agent = await seedRunningMockAgentWorkspaceForQueue(page, width); - try { - const prompt = `U2d local queue ${width}`; - await fillComposerDraft(page, prompt); - await queueComposerWithButton(page); - await expect(page.getByText(prompt, { exact: true })).toBeVisible(); - await expect(page.getByRole("button", { name: "Send queued message now" })).toBeVisible(); - expect((await agent.client.listQueuedAgentMessages(agent.agentId)).items).toEqual([]); - expect( - Object.keys(wire.getClientRequestCounts()).filter((type) => - type.startsWith("agent.queue."), - ), - ).toEqual([]); - await page.getByRole("button", { name: "Send queued message now" }).click(); - await expect(page.getByTestId("user-message").filter({ hasText: prompt })).toBeVisible(); - await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(0); - expect((await agent.client.listQueuedAgentMessages(agent.agentId)).items).toEqual([]); - expect( - Object.keys(wire.getClientRequestCounts()).filter((type) => - type.startsWith("agent.queue."), - ), - ).toEqual([]); - await testInfo.attach("local-queue-wire", { - body: JSON.stringify(wire.getClientRequestCounts(), null, 2), - contentType: "application/json", - }); - await page.screenshot({ path: testInfo.outputPath("local-queue-sent.png") }); - } finally { - await agent.cleanup(); - } - }, - ); -} - -async function seedRunningMockAgentWorkspaceForQueue(page: Page, width: number) { - const agent = await seedMockAgentWorkspace({ - repoPrefix: `u2d-queue-${width}-`, - title: `U2d queue ${width}`, - model: "five-minute-stream", - initialPrompt: "Keep running while independent queue items are exercised.", - }); - try { - await agent.client.waitForAgentUpsert( - agent.agentId, - (snapshot) => snapshot.status === "running", - 15_000, - ); - await openAgentRoute(page, agent); - await expectComposerVisible(page); - if (width === 390) { - await page.getByTestId("workspace-tab-switcher-trigger").click(); - await expect(page.getByText(`U2d queue ${width}`, { exact: true })).toBeVisible(); - await expect(page.getByRole("progressbar", { name: "Agent running" })).toBeVisible(); - await page.mouse.click(width / 2, 24); - await expect(page.getByTestId("workspace-tab-switcher-new-agent")).not.toBeVisible(); - await expect(page.getByRole("button", { name: "Stop agent", exact: true })).toBeVisible(); - await expectInlineWorkingIndicator(page); - } else { - await expectRunningAgentChrome(page, `U2d queue ${width}`); - } - return agent; - } catch (error) { - await agent.cleanup().catch(() => {}); - throw error; - } -} - interface SubmissionScenario { existingPrompt: string; } diff --git a/packages/app/e2e/browser/agent-stream-ui.spec.ts b/packages/app/e2e/browser/agent-stream-ui.spec.ts index c3f3e21cd60..80832e5fe10 100644 --- a/packages/app/e2e/browser/agent-stream-ui.spec.ts +++ b/packages/app/e2e/browser/agent-stream-ui.spec.ts @@ -1,6 +1,4 @@ import { test, expect } from "../support/fixtures"; -import type { Page } from "@playwright/test"; -import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate"; import { awaitAssistantMessage, expectAgentIdle, @@ -20,13 +18,7 @@ import { import { delayCreatedAgentInitialTailResponse } from "../support/helpers/agent-timeline-gate"; import { selectModel } from "../support/helpers/app"; import { clickNewChat } from "../support/helpers/launcher"; -import { closeSheet } from "../support/helpers/sheet"; -import { - expectComposerVisible, - expectComposerDraft, - fillComposerDraft, - startRunningMockAgent, -} from "../support/helpers/composer"; +import { expectComposerVisible, startRunningMockAgent } from "../support/helpers/composer"; import { openAgentRoute, seedMockAgentWorkspace, @@ -35,195 +27,6 @@ import { const SCROLL_AWAY_MIN_SCROLLABLE_DISTANCE = 360; -async function openCompactAgentMenu(page: Page) { - await page.getByTestId("workspace-tab-switcher-trigger").click(); - await page - .locator('[data-testid^="workspace-tab-menu-"][data-testid$="-trigger"]') - .filter({ visible: true }) - .first() - .click(); -} - -async function openArtifactView(page: Page, width: number) { - await expect(page.getByTestId("agent-view-switcher")).toBeVisible(); - if (width === 390) { - await openCompactAgentMenu(page); - await expect(page.getByText("Find in chat", { exact: true })).toBeVisible(); - await page.getByText("View artifacts", { exact: true }).click(); - await page - .getByRole("button", { name: "Bottom sheet backdrop", exact: true }) - .first() - .click({ position: { x: 10, y: 10 } }); - await expect(page.getByTestId("workspace-tab-switcher-new-agent")).not.toBeVisible(); - } else { - await page.getByTestId("agent-view-artifacts").click(); - } -} - -function featureRequestCounts(counts: Record) { - return Object.fromEntries( - Object.entries(counts).filter( - ([type]) => type.startsWith("agent.artifacts.") || type.startsWith("agent.companion."), - ), - ); -} - -async function openArtifactAndReturn(page: Page, width: number, draft: string) { - await page.getByTestId("artifact-card-u2d-report.html").click(); - await expect(page.getByTestId("file-html-preview")).toBeVisible(); - await expect( - page.frameLocator('[data-testid="file-html-preview"]').getByRole("heading", { - name: "Collected file evidence", - exact: true, - }), - ).toBeVisible(); - if (width === 390) { - await closeSheet(page, "u2d-report.html"); - await expect(page.getByTestId("file-html-preview")).toHaveCount(0); - } - await expectComposerVisible(page); - await expectComposerDraft(page, draft); -} - -for (const width of [1280, 390]) { - test(`U2d populated artifacts use the canonical entry without artifact RPC at ${width}px`, async ({ - page, - }, testInfo) => { - await page.setViewportSize({ width, height: 960 }); - const wire = await installDaemonWebSocketGate(page); - const agent = await seedMockAgentWorkspace({ - repoPrefix: `u2d-artifacts-${width}-`, - title: "U2d collected artifacts", - repo: { - files: [ - { - path: "u2d-report.html", - content: "U2d report

Collected file evidence

", - }, - ], - }, - }); - try { - const collection = await agent.client.scanAgentArtifacts(agent.agentId); - expect(collection.addedOrUpdated).toBeGreaterThan(0); - await openAgentRoute(page, agent); - await expectComposerVisible(page); - const draft = `Preserved artifact draft ${width}`; - await fillComposerDraft(page, draft); - const before = wire.getClientRequestCounts(); - await openArtifactView(page, width); - const filter = page.getByTestId("companion-stream-pending"); - await expect(filter).toHaveText("Show All"); - await filter.click(); - await expect(filter).toHaveText("Show Open Only"); - await expect(page.getByTestId("artifact-card-u2d-report.html")).toBeVisible(); - await expect(page.getByTestId("artifact-card-u2d-report.html")).toContainText( - "u2d-report.html", - ); - await page.screenshot({ path: testInfo.outputPath("populated-artifacts.png") }); - await page.getByTestId("agent-view-chat").click(); - await expectComposerDraft(page, draft); - await page.getByTestId("agent-view-artifacts").click(); - await expect(filter).toHaveText("Show All"); - await filter.click(); - await expect(filter).toHaveText("Show Open Only"); - await expect(page.getByTestId("artifact-card-u2d-report.html")).toBeVisible(); - await openArtifactAndReturn(page, width, draft); - const after = wire.getClientRequestCounts(); - const artifactRequests = featureRequestCounts(after); - expect(featureRequestCounts(before)).toEqual({}); - expect(artifactRequests).toEqual({}); - expect(wire.getClientRequestCount("session.events.set_subscription.request")).toBeGreaterThan( - 0, - ); - await testInfo.attach("collected-artifacts-and-opening-wire", { - body: JSON.stringify({ collection, before, after, artifactRequests }, null, 2), - contentType: "application/json", - }); - } finally { - await agent.cleanup(); - } - }); - - test(`U2d absent companion capability retains supplied files without feature RPC at ${width}px`, async ({ - page, - }, testInfo) => { - await page.setViewportSize({ width, height: 960 }); - const wire = await installDaemonWebSocketGate(page); - wire.setServerFeaturesStripped(["companionStreamPortV1"]); - const agent = await seedMockAgentWorkspace({ - repoPrefix: `u2d-artifacts-absent-${width}-`, - title: "U2d absent artifacts", - repo: { - files: [ - { - path: "u2d-report.html", - content: "U2d report

Collected file evidence

", - }, - ], - }, - }); - try { - const collection = await agent.client.scanAgentArtifacts(agent.agentId); - expect(collection.addedOrUpdated).toBeGreaterThan(0); - await openAgentRoute(page, agent); - await expectComposerVisible(page); - const draft = `Preserved old-host draft ${width}`; - await fillComposerDraft(page, draft); - const serverInfo = wire.getDeliveredServerMessages("status"); - expect(serverInfo).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - payload: expect.objectContaining({ - status: "server_info", - features: expect.not.objectContaining({ companionStreamPortV1: expect.anything() }), - }), - }), - ]), - ); - const snapshots = wire.getDeliveredServerMessages("fetch_agent_timeline_response"); - expect(snapshots).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - payload: expect.objectContaining({ - agent: expect.objectContaining({ - id: agent.agentId, - artifacts: expect.arrayContaining([ - expect.objectContaining({ path: "u2d-report.html" }), - ]), - }), - }), - }), - ]), - ); - const before = wire.getClientRequestCounts(); - await openArtifactView(page, width); - await expect(page.getByTestId("companion-stream-unsupported")).toBeVisible(); - await expect(page.getByTestId("companion-stream-unsupported")).toContainText( - "Update the host to use Stream", - ); - await expect(page.getByTestId("artifact-card-u2d-report.html")).toBeVisible(); - await expect(page.getByTestId("companion-stream-pending")).toHaveCount(0); - await expect(page.getByText("Add note", { exact: true })).toHaveCount(0); - await page.screenshot({ path: testInfo.outputPath("retained-artifacts-upgrade-notice.png") }); - await page.getByTestId("agent-view-chat").click(); - await expectComposerDraft(page, draft); - await page.getByTestId("agent-view-artifacts").click(); - await openArtifactAndReturn(page, width, draft); - const after = wire.getClientRequestCounts(); - expect(featureRequestCounts(before)).toEqual({}); - expect(featureRequestCounts(after)).toEqual({}); - await testInfo.attach("absent-artifact-wire", { - body: JSON.stringify({ collection, serverInfo, snapshots, before, after }, null, 2), - contentType: "application/json", - }); - await page.screenshot({ path: testInfo.outputPath("retained-draft-after-file-open.png") }); - } finally { - await agent.cleanup(); - } - }); -} - test.describe("Agent stream UI", () => { test("keeps running agent chrome after page refresh", async ({ page }) => { const title = "Running agent refresh"; diff --git a/packages/app/e2e/support/helpers/daemon-websocket-gate.ts b/packages/app/e2e/support/helpers/daemon-websocket-gate.ts index 8721fd968e8..c33976879f1 100644 --- a/packages/app/e2e/support/helpers/daemon-websocket-gate.ts +++ b/packages/app/e2e/support/helpers/daemon-websocket-gate.ts @@ -109,22 +109,15 @@ function stripCanonicalSubmittedPrompts( message: string | Buffer, enabled: boolean, messageType: unknown, - additionalFeatures: readonly string[] = [], ): string | Buffer { - if ( - (!enabled && additionalFeatures.length === 0) || - messageType !== "status" || - typeof message !== "string" - ) - return message; + if (!enabled || messageType !== "status" || typeof message !== "string") return message; const envelope = JSON.parse(message) as { message?: { payload?: { status?: unknown; features?: Record } }; payload?: { status?: unknown; features?: Record }; }; const payload = envelope.message?.payload ?? envelope.payload; if (payload?.status !== "server_info" || !payload.features) return message; - if (enabled) delete payload.features.canonicalSubmittedPrompts; - for (const feature of additionalFeatures) delete payload.features[feature]; + delete payload.features.canonicalSubmittedPrompts; return JSON.stringify(envelope); } @@ -309,7 +302,6 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n let forceTimelineEpochReset = false; let stripAssistantMessageIds = false; let stripCanonicalSubmittedPromptsFeature = false; - let strippedServerFeatures: readonly string[] = []; let shellToolCommandOverride: string | null = null; let failingTimelineAgentId: string | null = null; let holdingTimelineAgentId: string | null = null; @@ -338,14 +330,6 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n const clientRequests = new Map(); const timelineRequestCounts = new Map(); const serverMessageCounts = new Map(); - const deliveredServerMessages = new Map(); - const recordDeliveredServerMessage = (message: string | Buffer): void => { - const delivered = readSessionMessage(message); - if (typeof delivered?.type !== "string") return; - const messages = deliveredServerMessages.get(delivered.type) ?? []; - messages.push(delivered); - deliveredServerMessages.set(delivered.type, messages); - }; const agentStreamEventCounts = new Map(); const agentStreamItemCounts = new Map(); const serverMessageWaiters = new Set<() => void>(); @@ -535,7 +519,6 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n outboundMessage, stripCanonicalSubmittedPromptsFeature, serverMessage?.type, - strippedServerFeatures, ); const isTimelineResponse = serverMessage?.type === "fetch_agent_timeline_response"; if (isTimelineResponse) { @@ -561,7 +544,6 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n if (holdReadyFileUpdate(ws, outboundMessage, fileMessage)) return; try { ws.send(outboundMessage); - recordDeliveredServerMessage(outboundMessage); } catch { activeSockets.delete(ws); } @@ -869,15 +851,6 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n getClientRequestCount(type: string): number { return clientRequestCounts.get(type) ?? 0; }, - getClientRequestCounts(): Record { - return Object.fromEntries(clientRequestCounts); - }, - getDeliveredServerMessages(type: string): ReadonlyArray { - return [...(deliveredServerMessages.get(type) ?? [])]; - }, - setServerFeaturesStripped(features: readonly string[]): void { - strippedServerFeatures = [...features]; - }, getClientRequests(type: string): ReadonlyArray { return [...(clientRequests.get(type) ?? [])]; }, diff --git a/packages/app/e2e/support/helpers/seed-client.ts b/packages/app/e2e/support/helpers/seed-client.ts index 15e67117d74..a5a8973f516 100644 --- a/packages/app/e2e/support/helpers/seed-client.ts +++ b/packages/app/e2e/support/helpers/seed-client.ts @@ -1,7 +1,6 @@ import path from "node:path"; import { readFileSync } from "node:fs"; import type { TerminalActivity } from "@getpaseo/protocol/terminal-activity"; -import type { AgentQueueSnapshot } from "@getpaseo/protocol/messages"; import { connectDaemonClient } from "./daemon-client-loader"; import { withProjectOwnership } from "./project-ownership"; import { createTempDirectory, createTempGitRepo } from "./workspace"; @@ -33,8 +32,6 @@ export interface SeedDaemonClient { config: import("@getpaseo/protocol/messages").MutableDaemonConfigPatch, ): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>; getDaemonConfig(): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>; - listQueuedAgentMessages(agentId: string): Promise; - scanAgentArtifacts(agentId: string): Promise<{ addedOrUpdated: number; total: number }>; connect(): Promise; close(): Promise; addProject(cwd: string): Promise<{ diff --git a/packages/app/scripts/generate-voice-failure-phrases.mjs b/packages/app/scripts/generate-voice-failure-phrases.mjs deleted file mode 100644 index dba28c9705d..00000000000 --- a/packages/app/scripts/generate-voice-failure-phrases.mjs +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env node -// Render the spoken voice-failure phrases to 12 kHz mu-law and embed them in the app. -// The phrases must play when the host is unreachable, so they ship with the app instead -// of coming from host TTS. -// -// Usage: node scripts/generate-voice-failure-phrases.mjs [kokoro-model-dir] -// Default model dir: ~/.paseo/models/local-speech/kokoro-en-v0_19 (Kokoro, Apache-2.0) - -import { createRequire } from "node:module"; -import { homedir } from "node:os"; -import { writeFileSync } from "node:fs"; -import { fileURLToPath } from "node:url"; -import { dirname, resolve } from "node:path"; - -const here = dirname(fileURLToPath(import.meta.url)); -const target = resolve(here, "../src/voice/voice-failure-phrases.mulaw.ts"); -const modelDir = - process.argv[2] ?? resolve(homedir(), ".paseo/models/local-speech/kokoro-en-v0_19"); - -// A different Kokoro voice from the agent's default (sid 0), so a failure never sounds -// like the agent talking. 9 is bm_george. -const SPEAKER_ID = 9; -const OUTPUT_RATE = 12000; -const PEAK = 0.45; - -const PHRASES = { - "nothing-recognized": "Didn't catch that.", - "recognition-stalled": "Recognition stalled.", - "recognition-failed": "Recognition failed.", - "recognition-unavailable": "Recognition unavailable.", - "host-disconnected": "Host disconnected.", - "microphone-lost": "Microphone lost.", - reconnected: "Reconnected.", -}; - -const require = createRequire(resolve(here, "../../server/package.json")); -const sherpa = require("sherpa-onnx-node"); -const tts = new sherpa.OfflineTts({ - model: { - numThreads: 2, - provider: "cpu", - kokoro: { - model: `${modelDir}/model.onnx`, - voices: `${modelDir}/voices.bin`, - tokens: `${modelDir}/tokens.txt`, - dataDir: `${modelDir}/espeak-ng-data`, - lengthScale: 1.0, - }, - }, - maxNumSentences: 1, -}); - -function trimSilence(samples) { - const threshold = 0.01; - let start = 0; - let end = samples.length; - while (start < end && Math.abs(samples[start]) < threshold) start += 1; - while (end > start && Math.abs(samples[end - 1]) < threshold) end -= 1; - return samples.subarray(start, end); -} - -function resample(input, inputRate) { - // Box low-pass before decimating so sibilance above the new Nyquist does not alias. - const width = Math.max(1, Math.round(inputRate / OUTPUT_RATE)); - const samples = new Float32Array(input.length); - for (let i = 0; i < input.length; i += 1) { - let sum = 0; - for (let k = 0; k < width; k += 1) sum += input[Math.min(i + k, input.length - 1)]; - samples[i] = sum / width; - } - const length = Math.floor((samples.length * OUTPUT_RATE) / inputRate); - const out = new Float32Array(length); - for (let i = 0; i < length; i += 1) { - const position = (i * inputRate) / OUTPUT_RATE; - const index = Math.floor(position); - const fraction = position - index; - const next = samples[Math.min(index + 1, samples.length - 1)]; - out[i] = samples[index] * (1 - fraction) + next * fraction; - } - return out; -} - -// G.711 mu-law: half the size of PCM16 at telephone quality. The app expands it back. -function encodeMuLaw(sample) { - const BIAS = 0x84; - const CLIP = 32635; - const sign = sample < 0 ? 0x80 : 0; - let magnitude = Math.min(CLIP, Math.abs(sample)) + BIAS; - let exponent = 7; - for (let mask = 0x4000; (magnitude & mask) === 0 && exponent > 0; mask >>= 1) exponent -= 1; - const mantissa = (magnitude >> (exponent + 3)) & 0x0f; - return ~(sign | (exponent << 4) | mantissa) & 0xff; -} - -function toMuLaw(samples) { - let peak = 0; - for (const sample of samples) peak = Math.max(peak, Math.abs(sample)); - const gain = peak > 0 ? PEAK / peak : 1; - const out = Buffer.alloc(samples.length); - for (let i = 0; i < samples.length; i += 1) { - const value = Math.max(-1, Math.min(1, samples[i] * gain)); - out[i] = encodeMuLaw(Math.round(value * 32767)); - } - return out; -} - -const lines = [ - "// Generated by scripts/generate-voice-failure-phrases.mjs. Do not edit by hand.", - `// Kokoro (Apache-2.0) voice ${SPEAKER_ID}, G.711 mu-law mono ${OUTPUT_RATE} Hz, base64.`, - "", - `export const VOICE_FAILURE_PHRASE_SAMPLE_RATE = ${OUTPUT_RATE};`, - "", - "export const VOICE_FAILURE_PHRASE_MULAW_BASE64 = {", -]; -for (const [key, text] of Object.entries(PHRASES)) { - const audio = await tts.generateAsync({ - text, - sid: SPEAKER_ID, - speed: 1.05, - enableExternalBuffer: false, - }); - const samples = trimSilence(Float32Array.from(audio.samples)); - const encoded = toMuLaw(resample(samples, audio.sampleRate)); - const ms = Math.round((encoded.length / OUTPUT_RATE) * 1000); - console.log(`${key}: "${text}" ${ms} ms, ${encoded.length} bytes`); - lines.push(` // "${text}" (${ms} ms)`); - lines.push(` ${JSON.stringify(key)}:`); - lines.push(` "${encoded.toString("base64")}",`); -} -lines.push("} as const;", ""); -writeFileSync(target, lines.join("\n")); -console.log(`Wrote ${target}`); diff --git a/packages/app/src/agent-stream/chat-find/index.tsx b/packages/app/src/agent-stream/chat-find/index.tsx index a71d566dede..daa78baea28 100644 --- a/packages/app/src/agent-stream/chat-find/index.tsx +++ b/packages/app/src/agent-stream/chat-find/index.tsx @@ -1,170 +1,12 @@ -import { - createContext, - useCallback, - useContext, - useEffect, - useMemo, - useRef, - useSyncExternalStore, -} from "react"; -import { Text, View } from "react-native"; -import { StyleSheet } from "react-native-unistyles"; -import { useTranslation } from "react-i18next"; -import { PaneFind, type PaneFindHandle } from "@/pane-find"; -import { Button } from "@/components/ui/button"; -import { useRetainedPanelActive } from "@/components/retained-panel"; -import { useHostFeature } from "@/runtime/host-features"; -import { getHostRuntimeStore } from "@/runtime/host-runtime"; -import { useAgentViewStore } from "@/stores/agent-view-store"; -import { planTimelinePromptJump } from "@/timeline/timeline-sync-plan"; -import { ChatFindModel, type ChatFindFailure } from "./model"; -import { createNativeFindViewport } from "./native-viewport"; import type { ChatFindProps, ChatFindExpansionProps } from "./types"; -/** - * Native chat find. The search model, host RPC and history loading are the same as - * the web wrapper's; only the viewport differs (see `viewport.ts`), and the widget is - * opened from the tab menu through `useAgentViewStore` instead of Cmd+F. - */ - -const Selected = createContext(null); -const FAILURE_TEXT: Record = { - connection: "paneFind.connectionFailure", - historyChanged: "paneFind.historyChangedFailure", - reveal: "paneFind.revealFailure", -}; - -export function useChatFindSelectedMessageId(): string | null { - return useContext(Selected); +export function ChatFind({ children }: ChatFindProps) { + return children; } - -/** Native cannot highlight a range inside a rendered row, so the selected row is tinted. */ -export function ChatFindExpansion({ messageId, children }: ChatFindExpansionProps) { - const selected = useChatFindSelectedMessageId() === messageId; - return {children(selected)}; +export function ChatFindExpansion({ children }: ChatFindExpansionProps) { + return children(false); } - -export function ChatFind({ - agentId, - serverId, - epoch, - items, - viewportRef, - revealLoadedMessage, - visibleMessageIds, - children, -}: ChatFindProps) { - const { t } = useTranslation(); - const widget = useRef(null); - const bindings = useRef({ viewportRef, revealLoadedMessage, visibleMessageIds, items }); - bindings.current = { viewportRef, revealLoadedMessage, visibleMessageIds, items }; - const active = useRetainedPanelActive(); - // COMPAT(agentHistorySearch): upstream flag, added in v0.3.0. The widget stays - // reachable on an older host and explains itself instead of hiding. - const supported = useHostFeature(serverId, "agentHistorySearch"); - const key = `${serverId}:${agentId}`; - const requested = useAgentViewStore((state) => state.findOpen[key] ?? false); - const setFindOpen = useAgentViewStore((state) => state.setFindOpen); - const model = useMemo( - () => - new ChatFindModel({ - search(query, cursor) { - const client = getHostRuntimeStore().getClient(serverId); - if (!client) return Promise.reject(new Error("Host disconnected")); - return client.searchAgentTimeline({ agentId, query, cursor }); - }, - load(targetEpoch, seq) { - return getHostRuntimeStore().fetchAgentTimeline( - serverId, - agentId, - planTimelinePromptJump({ epoch: targetEpoch, seq }), - ); - }, - ...createNativeFindViewport({ getBindings: () => bindings.current }), - }), - [agentId, serverId], - ); - const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot); - useEffect(() => { - model.updateHistory(epoch, items); - }, [model, epoch, items]); - useEffect(() => () => model.close(), [model]); - const close = useCallback(() => { - setFindOpen(serverId, agentId, false); - model.close(); - }, [agentId, model, serverId, setFindOpen]); - useEffect(() => { - if (!active) close(); - }, [active, close]); - useEffect(() => { - if (requested) { - model.open(); - widget.current?.focus(); - } else { - model.close(); - } - }, [model, requested]); - const setQuery = useCallback( - (query: string) => { - if (supported) model.setQuery(query); - }, - [model, supported], - ); - let status = ""; - if (!supported) status = t("paneFind.updateHost"); - else if (state.phase === "searching") status = t("paneFind.searching"); - else if (state.phase === "loading") status = t("paneFind.loading"); - else if (state.phase === "error") status = t("paneFind.failed"); - else if (state.query.trim()) - status = state.count - ? t("paneFind.position", { current: state.occurrence + 1, total: state.count }) - : t("paneFind.noMatches"); - return ( - - {children} - {state.open ? ( - - 0} - onQueryChange={setQuery} - onNext={model.next} - onPrevious={model.previous} - onClose={close} - /> - {supported && state.failure ? ( - - {t(FAILURE_TEXT[state.failure])} - - - ) : null} - - ) : null} - - ); +/** Native has no chat find, so no message is ever selected by one. */ +export function useChatFindSelectedMessageId(): string | null { + return null; } - -const styles = StyleSheet.create((theme) => ({ - root: { flex: 1, minHeight: 0 }, - overlay: { - position: "absolute", - top: theme.spacing[2], - right: theme.spacing[3], - left: theme.spacing[3], - zIndex: 10, - alignItems: "flex-end", - }, - error: { - flexDirection: "row", - alignItems: "center", - padding: theme.spacing[2], - backgroundColor: theme.colors.surface1, - borderRadius: theme.borderRadius.md, - }, - errorText: { color: theme.colors.foreground, fontSize: theme.fontSize.sm, flex: 1 }, - selectedRow: { backgroundColor: theme.colors.surface2 }, -})); diff --git a/packages/app/src/agent-stream/chat-find/matches.test.ts b/packages/app/src/agent-stream/chat-find/matches.test.ts deleted file mode 100644 index 13fc31138f5..00000000000 --- a/packages/app/src/agent-stream/chat-find/matches.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { buildFindPattern, countTextMatches } from "./matches"; - -describe("countTextMatches", () => { - it("counts case-insensitive occurrences", () => { - expect(countTextMatches("Deploy the deploy script. DEPLOY!", "deploy")).toBe(3); - }); - - it("matches a wrapped phrase across any whitespace run", () => { - expect(countTextMatches("run the\n failing tests", "the failing")).toBe(1); - }); - - it("escapes regex metacharacters in the query", () => { - expect(countTextMatches("a.b a-b a.b", "a.b")).toBe(2); - expect(countTextMatches("what? (yes)", "(yes)")).toBe(1); - }); - - it("ignores an empty or whitespace-only query", () => { - expect(buildFindPattern(" ")).toBeNull(); - expect(countTextMatches("anything", "")).toBe(0); - }); -}); diff --git a/packages/app/src/agent-stream/chat-find/matches.ts b/packages/app/src/agent-stream/chat-find/matches.ts deleted file mode 100644 index ce070d6771c..00000000000 --- a/packages/app/src/agent-stream/chat-find/matches.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Plain-text occurrence counting for platforms without DOM ranges. Matching mirrors - * `ranges.web.ts`: case-insensitive, and any run of whitespace in the query matches - * any run of whitespace in the text, so a query typed with one space still finds a - * line-wrapped phrase. - */ -export function buildFindPattern(query: string): RegExp | null { - const trimmed = query.trim(); - if (!trimmed) return null; - const pattern = trimmed - .split(/\s+/) - .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) - .join("\\s+"); - return new RegExp(pattern, "giu"); -} - -export function countTextMatches(text: string, query: string): number { - const pattern = buildFindPattern(query); - if (!pattern) return 0; - let count = 0; - for (const _ of text.matchAll(pattern)) count += 1; - return count; -} diff --git a/packages/app/src/agent-stream/chat-find/native-viewport.test.ts b/packages/app/src/agent-stream/chat-find/native-viewport.test.ts deleted file mode 100644 index 685a7c89254..00000000000 --- a/packages/app/src/agent-stream/chat-find/native-viewport.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import type { StreamItem } from "@/types/stream"; -import type { StreamViewportHandle } from "../strategy"; -import { createNativeFindViewport } from "./native-viewport"; - -function userMessage(id: string, text: string): StreamItem { - return { - kind: "user_message", - id, - messageId: id, - text, - timestamp: new Date(0), - } as unknown as StreamItem; -} - -describe("createNativeFindViewport", () => { - it("mounts, scrolls to and counts the selected message", async () => { - const scrollToMessage = vi.fn(); - const visible = new Set(); - const revealLoadedMessage = vi.fn((messageId: string) => { - visible.add(messageId); - return true; - }); - const viewport = createNativeFindViewport({ - getBindings: () => ({ - viewportRef: { current: { scrollToMessage } as unknown as StreamViewportHandle }, - revealLoadedMessage, - visibleMessageIds: visible, - items: [userMessage("m1", "fix the tests, then fix the docs")], - }), - }); - const result = await viewport.reveal("m1", "fix", -1, new AbortController().signal); - expect(revealLoadedMessage).toHaveBeenCalledWith("m1"); - expect(scrollToMessage).toHaveBeenCalledWith("m1"); - expect(result).toEqual({ occurrence: 1, count: 2 }); - }); - - it("reports zero when the text no longer contains the query", async () => { - const viewport = createNativeFindViewport({ - getBindings: () => ({ - viewportRef: { current: null }, - revealLoadedMessage: () => true, - visibleMessageIds: new Set(["m1"]), - items: [userMessage("m1", "nothing here")], - }), - }); - await expect( - viewport.reveal("m1", "missing", 0, new AbortController().signal), - ).resolves.toEqual({ occurrence: 0, count: 0 }); - }); - - it("rejects when the search is cancelled while waiting for the row", async () => { - const controller = new AbortController(); - const viewport = createNativeFindViewport({ - getBindings: () => ({ - viewportRef: { current: null }, - revealLoadedMessage: () => false, - visibleMessageIds: new Set(), - items: [], - }), - }); - const reveal = viewport.reveal("m1", "x", 0, controller.signal); - controller.abort(); - await expect(reveal).rejects.toThrow("Search cancelled"); - }); -}); diff --git a/packages/app/src/agent-stream/chat-find/native-viewport.ts b/packages/app/src/agent-stream/chat-find/native-viewport.ts deleted file mode 100644 index 269fc7a9ba3..00000000000 --- a/packages/app/src/agent-stream/chat-find/native-viewport.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { getStreamItemMessageId } from "../presentation"; -import { countTextMatches } from "./matches"; -import type { ChatFindOperations } from "./model"; -import type { ChatFindProps } from "./types"; - -interface ViewportInput { - getBindings(): Pick< - ChatFindProps, - "viewportRef" | "revealLoadedMessage" | "visibleMessageIds" | "items" - >; -} - -const REVEAL_TIMEOUT_MS = 5000; -const POLL_INTERVAL_MS = 50; - -/** - * Native reveal. The web viewport reads the rendered DOM to find and highlight the - * exact range; native has no DOM to read, so the message's row is mounted, the list - * scrolls to it, and occurrences are counted in the message text. The selected row - * is tinted by `ChatFindExpansion` so "jumped" is always visible even without a - * range highlight. - */ -export function createNativeFindViewport({ - getBindings, -}: ViewportInput): Pick { - return { - clear() {}, - reveal(messageId, query, occurrence, signal) { - return new Promise((resolve, reject) => { - const deadline = Date.now() + REVEAL_TIMEOUT_MS; - let timer: ReturnType | undefined; - let scrolled = false; - const cleanup = () => { - clearTimeout(timer); - signal.removeEventListener("abort", cancelled); - }; - const cancelled = () => { - cleanup(); - reject(new Error("Search cancelled")); - }; - const poll = () => { - if (signal.aborted) { - cancelled(); - return; - } - if (Date.now() >= deadline) { - cleanup(); - reject(new Error("Could not reveal this match; retry")); - return; - } - const current = getBindings(); - const rows = current.items.filter( - (item) => item.id === messageId || getStreamItemMessageId(item) === messageId, - ); - const mounted = - current.visibleMessageIds.has(messageId) || - rows.some((item) => current.visibleMessageIds.has(getStreamItemMessageId(item))); - if (!mounted) { - current.revealLoadedMessage(messageId); - timer = setTimeout(poll, POLL_INTERVAL_MS); - return; - } - if (!scrolled) { - current.viewportRef.current?.scrollToMessage?.(messageId); - scrolled = true; - } - const text = rows - .map((item) => ("text" in item && typeof item.text === "string" ? item.text : "")) - .join("\n"); - const count = countTextMatches(text, query); - cleanup(); - if (!count) { - resolve({ occurrence: 0, count: 0 }); - return; - } - const index = occurrence < 0 ? count - 1 : Math.min(occurrence, count - 1); - resolve({ occurrence: index, count }); - }; - signal.addEventListener("abort", cancelled, { once: true }); - poll(); - }); - }, - }; -} diff --git a/packages/app/src/agent-stream/native-message-scroll.test.ts b/packages/app/src/agent-stream/native-message-scroll.test.ts deleted file mode 100644 index 832d4fca06c..00000000000 --- a/packages/app/src/agent-stream/native-message-scroll.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import type { StreamItem } from "@/types/stream"; -import { createNativeMessageScroller } from "./native-message-scroll"; - -const message = (id: string) => ({ kind: "user_message", id }) as StreamItem; - -function harness(initialRows: StreamItem[]) { - let rows = initialRows; - let nextFrame = 0; - const frames = new Map void>(); - const order: string[] = []; - const detach = vi.fn(() => order.push("detach")); - const scrollToIndex = vi.fn((index: number) => order.push(`scroll:${index}`)); - const scroller = createNativeMessageScroller({ - getRows: () => rows, - detach, - scrollToIndex, - requestFrame: (callback) => { - const frame = ++nextFrame; - frames.set(frame, callback); - return frame; - }, - cancelFrame: (frame) => { - frames.delete(frame); - }, - }); - return { - ...scroller, - detach, - scrollToIndex, - order, - setRows: (next: StreamItem[]) => { - rows = next; - }, - flush: () => { - const pending = [...frames.values()]; - frames.clear(); - for (const callback of pending) callback(); - }, - }; -} - -describe("native message scrolling", () => { - it.each([ - ["history", 0], - ["live", 2], - ["source", 1], - ] as const)("addresses %s in forward combined list order", (id, index) => { - const h = harness([ - message("history"), - { kind: "plugin", id: "replacement", sourceId: "source" } as StreamItem, - message("live"), - ]); - h.scrollToMessage(id); - expect(h.order).toEqual(["detach"]); - h.flush(); - expect(h.order).toEqual(["detach", `scroll:${index}`]); - }); - - it("resolves the latest row index after the pin release commits", () => { - const h = harness([message("first"), message("target")]); - h.scrollToMessage("target"); - h.setRows([message("older"), message("first"), message("target")]); - h.flush(); - expect(h.scrollToIndex).toHaveBeenCalledExactlyOnceWith(2); - }); - - it("cancels an earlier search jump when another match is selected", () => { - const h = harness([message("first"), message("second")]); - h.scrollToMessage("first"); - h.scrollToMessage("second"); - h.flush(); - expect(h.scrollToIndex).toHaveBeenCalledExactlyOnceWith(1); - }); - - it("ignores missing or removed rows", () => { - const h = harness([message("target")]); - h.scrollToMessage("missing"); - expect(h.detach).not.toHaveBeenCalled(); - h.scrollToMessage("target"); - h.setRows([]); - h.flush(); - expect(h.scrollToIndex).not.toHaveBeenCalled(); - }); - - it("cancels a pending jump when the viewport is disposed", () => { - const h = harness([message("target")]); - h.scrollToMessage("target"); - h.dispose(); - h.flush(); - expect(h.scrollToIndex).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/app/src/agent-stream/native-message-scroll.ts b/packages/app/src/agent-stream/native-message-scroll.ts deleted file mode 100644 index 4e2a14a4b31..00000000000 --- a/packages/app/src/agent-stream/native-message-scroll.ts +++ /dev/null @@ -1,32 +0,0 @@ -import type { StreamItem } from "@/types/stream"; -import { getStreamItemMessageId } from "./presentation"; - -export function createNativeMessageScroller(input: { - getRows: () => readonly StreamItem[]; - detach: () => void; - scrollToIndex: (index: number) => void; - requestFrame: (callback: () => void) => number; - cancelFrame: (frame: number) => void; -}) { - let frame: number | null = null; - const dispose = () => { - if (frame !== null) input.cancelFrame(frame); - frame = null; - }; - return { - dispose, - scrollToMessage(messageId: string) { - dispose(); - const matches = (item: StreamItem) => - item.id === messageId || getStreamItemMessageId(item) === messageId; - if (!input.getRows().some(matches)) return; - input.detach(); - // The native end pin must unmount before the imperative jump reaches the scroll view. - frame = input.requestFrame(() => { - frame = null; - const index = input.getRows().findIndex(matches); - if (index >= 0) input.scrollToIndex(index); - }); - }, - }; -} diff --git a/packages/app/src/agent-stream/strategy-native.tsx b/packages/app/src/agent-stream/strategy-native.tsx index fed1c1c8638..106c9c3bb49 100644 --- a/packages/app/src/agent-stream/strategy-native.tsx +++ b/packages/app/src/agent-stream/strategy-native.tsx @@ -33,7 +33,6 @@ import type { Theme } from "@/styles/theme"; import { useStableEvent } from "@/hooks/use-stable-event"; import { shouldAnimateNativeScrollToBottom } from "./native-scroll-animation"; import { useRevisedHistoryRows } from "./history-row-revision"; -import { createNativeMessageScroller } from "./native-message-scroll"; import { useBottomAnchorController } from "./bottom-anchor-controller"; import { useScrollKeyboardDismiss } from "./scroll-keyboard-dismiss/use-scroll-keyboard-dismiss"; import { @@ -205,9 +204,6 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat return nextRows; }, [newRowEstimates, historyRows, liveRows]); const getEstimatedItemSize = useStableEvent((item: StreamItem) => newRowEstimates.estimate(item)); - // Chat find addresses the same combined rows that LegendList renders. - const rowsRef = useRef(rows); - rowsRef.current = rows; const getHistoryStartPaginationInput = useStableEvent((): HistoryStartPaginationInput => { const metrics = streamViewportMetricsRef.current; const hasMeasuredViewport = @@ -452,23 +448,6 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat }; }, [clearPendingUserScrollEnd, disposeHistoryStart, evaluateHistoryStart]); - const detachForMessageScroll = useStableEvent(() => { - cancelDisclosureHold(); - bottomAnchorController.detachByUser(); - }); - const [messageScroller] = useState(() => - createNativeMessageScroller({ - getRows: () => rowsRef.current, - detach: detachForMessageScroll, - scrollToIndex: (index) => { - void listRef.current?.scrollToIndex({ index, viewPosition: 0.5, animated: true }); - }, - requestFrame: requestAnimationFrame, - cancelFrame: cancelAnimationFrame, - }), - ); - useEffect(() => () => messageScroller.dispose(), [messageScroller]); - useEffect(() => { const handle: StreamViewportHandle = { scrollToBottom: (reason = "jump-to-bottom") => { @@ -481,7 +460,6 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat bottomAnchorController.prepareForStickyViewportChange(); }, holdRow, - scrollToMessage: messageScroller.scrollToMessage, }; viewportRef.current = handle; return () => { @@ -489,7 +467,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat viewportRef.current = null; } }; - }, [agentId, bottomAnchorController, holdRow, messageScroller, viewportRef]); + }, [agentId, bottomAnchorController, holdRow, viewportRef]); // The scroll-to-bottom button shows whenever following would not resume on its own. A detached // list resumes only from the end, so the button shows anywhere short of it. While following, the diff --git a/packages/app/src/agent-stream/turn-footer.tsx b/packages/app/src/agent-stream/turn-footer.tsx index fcdc4437e1d..1e92ac6802b 100644 --- a/packages/app/src/agent-stream/turn-footer.tsx +++ b/packages/app/src/agent-stream/turn-footer.tsx @@ -53,7 +53,6 @@ export const TurnFooter = memo(function TurnFooter({ supportsTimelineCursor, onForkAssistantTurn, onForkInFlightTurn, - onPin, }: { isRunning: boolean; inFlightTurnStartedAt: Date | null; @@ -62,7 +61,6 @@ export const TurnFooter = memo(function TurnFooter({ supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; onForkInFlightTurn?: InFlightTurnForkHandler; - onPin?: (text: string) => void; }) { if (isRunning) { return ( @@ -85,7 +83,6 @@ export const TurnFooter = memo(function TurnFooter({ startIndex={host.startIndex} supportsTimelineCursor={supportsTimelineCursor} onForkAssistantTurn={onForkAssistantTurn} - onPin={onPin} /> ); }); @@ -97,7 +94,6 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ startIndex, supportsTimelineCursor, onForkAssistantTurn, - onPin, }: { strategy: TurnContentStrategy; items: StreamItem[]; @@ -105,7 +101,6 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ startIndex: number; supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; - onPin?: (text: string) => void; }) { return ( @@ -116,7 +111,6 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ startIndex={startIndex} supportsTimelineCursor={supportsTimelineCursor} onForkAssistantTurn={onForkAssistantTurn} - onPin={onPin} /> ); @@ -173,7 +167,6 @@ function CompletedTurnFooter({ startIndex, supportsTimelineCursor, onForkAssistantTurn, - onPin, }: { strategy: TurnContentStrategy; items: StreamItem[]; @@ -181,7 +174,6 @@ function CompletedTurnFooter({ startIndex: number; supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; - onPin?: (text: string) => void; }) { const getContent = useCallback( () => @@ -213,7 +205,6 @@ function CompletedTurnFooter({ completedAt={timing?.completedAt} durationMs={timing?.durationMs} onFork={boundary && onForkAssistantTurn ? handleFork : undefined} - onPin={onPin} /> ); diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index 5933de06f6c..9b630b1d517 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -211,7 +211,6 @@ function renderStreamItemWithTurnFooter(input: { strategy: TurnContentStrategy; supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; - onPin?: (text: string) => void; }): ReactNode { if (!input.content) { return null; @@ -226,7 +225,6 @@ function renderStreamItemWithTurnFooter(input: { startIndex={footerHost.startIndex} supportsTimelineCursor={input.supportsTimelineCursor} onForkAssistantTurn={input.onForkAssistantTurn} - onPin={input.onPin} /> ) : null; const content = ( @@ -778,31 +776,6 @@ const AgentStreamViewComponent = forwardRef { - if (!agentId || !client) return; - client - .updateCompanionEntry({ agentId, action: "add_pin", text }) - .catch(() => toast?.error(t("agentPanel.stream.mutationFailed"))); - }, - [agentId, client, t, toast], - ); - - const handleQAndA = useCallback( - (text: string, messageId?: string) => { - if (!agentId || !client) return; - client - .updateCompanionEntry({ - agentId, - action: "add_q_and_a", - text, - sourceId: messageId ? `msg:${messageId}` : undefined, - }) - .catch(() => toast?.error(t("agentPanel.stream.mutationFailed"))); - }, - [agentId, client, t, toast], - ); - const renderUserMessageItem = useCallback( (layoutItem: StreamLayoutItem, item: Extract) => { return ( @@ -816,8 +789,6 @@ const AgentStreamViewComponent = forwardRef ); }, - [ - context.capabilities, - agentId, - client, - pendingClientMessageIds, - resolvedServerId, - handlePin, - handleQAndA, - ], + [context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId], ); const renderAssistantMessageItem = useCallback( @@ -1075,13 +1038,11 @@ const AgentStreamViewComponent = forwardRef ) : null, [ handleForkAssistantTurn, handleForkInFlightTurn, - handlePin, readOnly, isTurnActive, baseRenderModel.turnTiming.runningStartedAt, diff --git a/packages/app/src/artifacts/feed.tsx b/packages/app/src/artifacts/feed.tsx deleted file mode 100644 index 41e81441472..00000000000 --- a/packages/app/src/artifacts/feed.tsx +++ /dev/null @@ -1,353 +0,0 @@ -import type { AgentArtifact } from "@getpaseo/protocol/agent-types"; -import { Image as ExpoImage } from "expo-image"; -import { FileCode2, FileDiff, FileText, Image as ImageIcon } from "lucide-react-native"; -import { useCallback, useMemo, type ComponentType } from "react"; -import { ActivityIndicator, Pressable, ScrollView, Text, View } from "react-native"; -import { useTranslation } from "react-i18next"; -import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { persistAttachmentFromBytes } from "@/attachments/service"; -import { createPreviewAttachmentId, getFileNameFromPath } from "@/attachments/utils"; -import { useAttachmentPreviewUrl } from "@/attachments/use-attachment-preview-url"; -import type { AttachmentMetadata } from "@/attachments/types"; -import { useFetchQuery } from "@/data/query"; -import { useHostRuntimeClient, useHostRuntimeConnectionStatus } from "@/runtime/host-runtime"; -import { formatMessageTimestamp } from "@/utils/time"; -import type { WorkspaceFileOpenRequest } from "@/workspace/file-open"; -import type { Theme } from "@/styles/theme"; - -interface ArtifactFeedProps { - serverId: string; - cwd: string; - artifacts: readonly AgentArtifact[]; - onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void; - onReturnToChat?: () => void; - onPinArtifact?: (artifact: AgentArtifact) => void; -} - -interface ArtifactCardProps { - artifact: AgentArtifact; - serverId: string; - cwd: string; - onOpen: (artifact: AgentArtifact) => void; - onPin?: () => void; -} - -const ICON_BY_KIND: Record< - AgentArtifact["kind"], - ComponentType<{ size?: number; color?: string }> -> = { - html: FileCode2, - markdown: FileText, - image: ImageIcon, - svg: ImageIcon, - pdf: FileText, - diff: FileDiff, -}; - -function ArtifactKindIcon({ - kind, - size, - color, -}: { - kind: AgentArtifact["kind"]; - size: number; - color: string; -}) { - const Icon = ICON_BY_KIND[kind]; - return ; -} - -const ThemedArtifactKindIcon = withUnistyles(ArtifactKindIcon); -const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); - -export function ArtifactFeed({ - serverId, - cwd, - artifacts, - onOpenWorkspaceFile, - onReturnToChat, - onPinArtifact, -}: ArtifactFeedProps) { - const { t } = useTranslation(); - const connectionStatus = useHostRuntimeConnectionStatus(serverId); - - const handleOpen = useCallback( - (artifact: AgentArtifact) => { - onOpenWorkspaceFile?.({ - location: { path: artifact.path }, - disposition: "side", - }); - onReturnToChat?.(); - }, - [onOpenWorkspaceFile, onReturnToChat], - ); - - if (connectionStatus === "connecting") { - return ( - - - - ); - } - - if (connectionStatus === "offline" || connectionStatus === "error") { - return ( - - - {t("agentPanel.states.offline") || "Offline"} - - {t("agentPanel.states.offlineDescription") || "Cannot connect to the host."} - - - ); - } - - if (artifacts.length === 0) { - return ( - - - {t("agentPanel.artifacts.emptyTitle")} - {t("agentPanel.artifacts.emptyDescription")} - - ); - } - - return ( - - {artifacts.map((artifact) => ( - onPinArtifact(artifact) : undefined} - /> - ))} - - ); -} - -export function ArtifactCard({ artifact, serverId, cwd, onOpen, onPin }: ArtifactCardProps) { - const { t } = useTranslation(); - const handlePress = useCallback(() => onOpen(artifact), [artifact, onOpen]); - const pressableStyle = useCallback( - ({ hovered, pressed }: { hovered?: boolean; pressed: boolean }) => [ - styles.card, - hovered && styles.cardHovered, - pressed && styles.cardPressed, - ], - [], - ); - const metadata = `${artifact.kind.toUpperCase()} · ${formatSize(artifact.size)} · ${formatMessageTimestamp(new Date(artifact.updatedAt))}`; - - return ( - - {artifact.kind === "image" || artifact.kind === "svg" ? ( - - ) : null} - - - - - - - {artifact.name} - - - {artifact.path} - - {metadata} - - {t("agentPanel.artifacts.openLabel")} - - - ); -} - -function ArtifactImage({ - artifact, - serverId, - cwd, -}: { - artifact: AgentArtifact; - serverId: string; - cwd: string; -}) { - const { t } = useTranslation(); - const client = useHostRuntimeClient(serverId); - const query = useFetchQuery({ - queryKey: ["artifactPreview", serverId, cwd, artifact.path, artifact.updatedAt], - enabled: Boolean(client), - staleTimeMs: 30_000, - dataShape: "value", - queryFn: async () => { - if (!client) { - return null; - } - const file = await client.readFile(cwd, artifact.path); - if (file.kind !== "image") { - return null; - } - return persistAttachmentFromBytes({ - id: createPreviewAttachmentId({ - mimeType: file.mime, - path: file.path, - size: file.size, - modifiedAt: file.modifiedAt, - contentLength: file.bytes.byteLength, - }), - bytes: file.bytes, - mimeType: file.mime, - fileName: getFileNameFromPath(file.path), - }); - }, - }); - const previewUrl = useAttachmentPreviewUrl(query.data); - const source = useMemo(() => ({ uri: previewUrl ?? "" }), [previewUrl]); - - if (query.isPending) { - return ( - - - - ); - } - if (query.isError || !previewUrl) { - return ( - - - - {t("agentPanel.artifacts.previewMissing") || "Preview unavailable"} - - - ); - } - return ( - - - - ); -} - -function formatSize(size: number): string { - if (size < 1024) { - return `${size} B`; - } - if (size < 1024 * 1024) { - return `${(size / 1024).toFixed(1)} KB`; - } - return `${(size / (1024 * 1024)).toFixed(1)} MB`; -} - -const previewImageStyle = { - width: "100%", - height: "100%", -} as const; - -const styles = StyleSheet.create((theme) => ({ - scroll: { - flex: 1, - backgroundColor: theme.colors.surface0, - }, - feed: { - width: "100%", - maxWidth: 760, - alignSelf: "center", - padding: theme.spacing[4], - gap: theme.spacing[3], - }, - card: { - overflow: "hidden", - borderWidth: 1, - borderColor: theme.colors.border, - borderRadius: theme.borderRadius.lg, - backgroundColor: theme.colors.surface1, - }, - cardHovered: { - borderColor: theme.colors.borderAccent, - backgroundColor: theme.colors.surface2, - }, - cardPressed: { - opacity: theme.opacity[50], - }, - preview: { - width: "100%", - height: 220, - backgroundColor: theme.colors.surface2, - }, - previewState: { - width: "100%", - height: 120, - alignItems: "center", - justifyContent: "center", - backgroundColor: theme.colors.surface2, - gap: theme.spacing[2], - }, - missingPreviewText: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.sm, - }, - cardBody: { - flexDirection: "row", - alignItems: "center", - padding: theme.spacing[3], - gap: theme.spacing[3], - }, - iconFrame: { - width: 34, - height: 34, - borderRadius: theme.borderRadius.md, - alignItems: "center", - justifyContent: "center", - backgroundColor: theme.colors.surface3, - }, - cardText: { - flex: 1, - minWidth: 0, - gap: theme.spacing[1], - }, - name: { - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.medium, - }, - path: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.sm, - }, - metadata: { - color: theme.colors.foregroundExtraMuted, - fontSize: theme.fontSize.sm, - }, - openLabel: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.sm, - }, - emptyState: { - flex: 1, - alignItems: "center", - justifyContent: "center", - padding: theme.spacing[6], - gap: theme.spacing[2], - }, - emptyTitle: { - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.medium, - }, - emptyDescription: { - maxWidth: 380, - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.sm, - textAlign: "center", - }, -})); diff --git a/packages/app/src/audio/audio-engine.native.test.ts b/packages/app/src/audio/audio-engine.native.test.ts deleted file mode 100644 index 37c98bd583c..00000000000 --- a/packages/app/src/audio/audio-engine.native.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import * as native from "@getpaseo/expo-two-way-audio"; -import { createAudioEngine } from "./audio-engine.native"; -import type { AudioPlaybackSource } from "./audio-engine-types"; - -vi.mock("expo-audio", () => ({ createAudioPlayer: vi.fn(), setAudioModeAsync: vi.fn() })); -vi.mock("expo-file-system", () => ({ File: vi.fn(), Paths: { cache: "cache" } })); - -const listeners: Record void> = {}; - -vi.mock("@getpaseo/expo-two-way-audio", () => ({ - initialize: vi.fn().mockResolvedValue(true), - addExpoTwoWayAudioEventListener: vi.fn((event, cb) => { - listeners[event] = cb; - return { - remove: vi.fn(() => { - delete listeners[event]; - }), - }; - }), - playPCMData: vi.fn(), - resumePlayback: vi.fn(), - releaseAudioSession: vi.fn(), - stopPlayback: vi.fn(), - tearDown: vi.fn(), -})); - -function source(arrayBuffer: () => Promise): AudioPlaybackSource { - return { type: "audio/pcm;rate=16000", size: 32000, arrayBuffer }; -} - -beforeEach(() => { - vi.useFakeTimers(); - vi.clearAllMocks(); - for (const key of Object.keys(listeners)) { - delete listeners[key]; - } -}); - -afterEach(() => { - vi.useRealTimers(); -}); - -it("keeps canceled audio preparation from stealing the next clip's completion", async () => { - const engine = createAudioEngine({ onCaptureData: vi.fn(), onVolumeLevel: vi.fn() }); - await engine.initialize(); - let finishPreparation!: (buffer: ArrayBuffer) => void; - const preparing = vi.fn( - () => - new Promise((resolve) => { - finishPreparation = resolve; - }), - ); - const canceled = engine.play(source(preparing)).catch((error: Error) => error.message); - await vi.waitFor(() => expect(preparing).toHaveBeenCalledOnce()); - engine.stop(); - engine.clearQueue(); - const completed = vi.fn(); - const next = engine.play(source(async () => new ArrayBuffer(32000))).then(completed); - expect(await canceled).toBe("Playback stopped"); - await vi.waitFor(() => expect(native.playPCMData).toHaveBeenCalledOnce()); - finishPreparation(new ArrayBuffer(64000)); - await vi.advanceTimersByTimeAsync(2100); - - expect(completed).toHaveBeenCalledWith(1); - expect(native.playPCMData).toHaveBeenCalledOnce(); - await next; - await engine.destroy(); -}); - -it("cancels before initialization completes and plays only the replacement", async () => { - let finishInitialize!: (initialized: boolean) => void; - vi.mocked(native.initialize).mockImplementationOnce( - () => - new Promise((resolve) => { - finishInitialize = resolve; - }), - ); - const engine = createAudioEngine({ onCaptureData: vi.fn(), onVolumeLevel: vi.fn() }); - const discardedSource = vi.fn(async () => new ArrayBuffer(32000)); - const canceled = engine.play(source(discardedSource)).catch((error: Error) => error.message); - await vi.waitFor(() => expect(native.initialize).toHaveBeenCalledOnce()); - engine.stop(); - engine.clearQueue(); - expect(await canceled).toBe("Playback stopped"); - finishInitialize(true); - - const next = engine.play(source(async () => new ArrayBuffer(32000))); - await vi.advanceTimersByTimeAsync(1100); - expect(await next).toBe(1); - expect(discardedSource).toHaveBeenCalledOnce(); - expect(native.playPCMData).toHaveBeenCalledOnce(); - await engine.destroy(); -}); - -it("ignores an old preparation failure while the replacement is playing", async () => { - const engine = createAudioEngine({ onCaptureData: vi.fn(), onVolumeLevel: vi.fn() }); - let failPreparation!: (error: Error) => void; - const preparing = vi.fn( - () => - new Promise((_resolve, reject) => { - failPreparation = reject; - }), - ); - const canceled = engine.play(source(preparing)).catch((error: Error) => error.message); - await vi.waitFor(() => expect(preparing).toHaveBeenCalledOnce()); - engine.stop(); - engine.clearQueue(); - expect(await canceled).toBe("Playback stopped"); - - const next = engine.play(source(async () => new ArrayBuffer(32000))); - await vi.waitFor(() => expect(native.playPCMData).toHaveBeenCalledOnce()); - failPreparation(new Error("late decode error")); - await vi.advanceTimersByTimeAsync(1100); - expect(await next).toBe(1); - await engine.destroy(); -}); diff --git a/packages/app/src/audio/audio-engine.native.ts b/packages/app/src/audio/audio-engine.native.ts index 68697f32c99..ed9f15a7650 100644 --- a/packages/app/src/audio/audio-engine.native.ts +++ b/packages/app/src/audio/audio-engine.native.ts @@ -1,4 +1,3 @@ -import * as native from "@getpaseo/expo-two-way-audio"; import type { AudioEngine, AudioEngineCallbacks, @@ -16,6 +15,8 @@ export function createAudioEngine( callbacks: AudioEngineCallbacks, options?: AudioEngineOptions, ): AudioEngine { + const native = require("@getpaseo/expo-two-way-audio"); + const refs: { initialized: boolean; captureActive: boolean; diff --git a/packages/app/src/audio/audio-engine.web.test.ts b/packages/app/src/audio/audio-engine.web.test.ts deleted file mode 100644 index 866c857b88c..00000000000 --- a/packages/app/src/audio/audio-engine.web.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { afterEach, expect, test, vi } from "vitest"; -import { createAudioEngine } from "./audio-engine.web"; - -vi.mock("@/desktop/host", () => ({ isElectronRuntime: () => false })); -afterEach(() => vi.unstubAllGlobals()); - -test("microphone track loss interrupts capture, and an old track cannot interrupt its replacement", async () => { - const callbacks: Array<() => void> = []; - const streams = [0, 1].map(() => { - const track = { - stop: vi.fn(), - addEventListener: (_event: string, callback: () => void) => callbacks.push(callback), - }; - return { getAudioTracks: () => [track], getTracks: () => [track] }; - }); - const node = () => ({ connect: vi.fn(), disconnect: vi.fn(), gain: { value: 0 } }); - class CaptureContext { - state = "running"; - destination = {}; - createMediaStreamSource = node; - createScriptProcessor = node; - createGain = node; - close = vi.fn().mockResolvedValue(undefined); - } - vi.stubGlobal("window", { AudioContext: CaptureContext, isSecureContext: true }); - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn().mockResolvedValueOnce(streams[0]).mockResolvedValueOnce(streams[1]), - }, - }); - const onInterruption = vi.fn(); - const engine = createAudioEngine({ - onCaptureData: vi.fn(), - onVolumeLevel: vi.fn(), - onInterruption, - }); - await engine.startCapture(); - callbacks[0](); - expect(onInterruption).toHaveBeenCalledOnce(); - await engine.stopCapture(); - await engine.startCapture(); - callbacks[0](); - expect(onInterruption).toHaveBeenCalledOnce(); - callbacks[1](); - expect(onInterruption).toHaveBeenCalledTimes(2); - await engine.destroy(); -}); - -test("stopping browser audio preparation cannot play a stale clip or complete its replacement", async () => { - const played: Array<{ start: ReturnType; end: () => void }> = []; - class PlaybackContext { - state = "running"; - destination = {}; - close = vi.fn().mockResolvedValue(undefined); - createBuffer(_channels: number, length: number, rate: number) { - return { duration: length / rate, getChannelData: () => new Float32Array(length) }; - } - createBufferSource() { - const clip = { start: vi.fn(), end: () => {} }; - played.push(clip); - return { - connect: vi.fn(), - disconnect: vi.fn(), - start: clip.start, - stop: vi.fn(), - addEventListener: (_event: string, callback: () => void) => { - clip.end = callback; - }, - }; - } - } - vi.stubGlobal("window", { AudioContext: PlaybackContext }); - const engine = createAudioEngine({ onCaptureData: vi.fn(), onVolumeLevel: vi.fn() }); - let finish!: (buffer: ArrayBuffer) => void; - const preparation = vi.fn( - () => - new Promise((resolve) => { - finish = resolve; - }), - ); - const canceled = engine - .play({ type: "audio/pcm;rate=16000", size: 32000, arrayBuffer: preparation }) - .catch((error: Error) => error.message); - await vi.waitFor(() => expect(preparation).toHaveBeenCalledOnce()); - engine.stop(); - engine.clearQueue(); - expect(await canceled).toBe("Playback stopped"); - const completed = vi.fn(); - const next = engine - .play({ - type: "audio/pcm;rate=16000", - size: 32000, - arrayBuffer: async () => new ArrayBuffer(32000), - }) - .then(completed); - await vi.waitFor(() => expect(played).toHaveLength(1)); - finish(new ArrayBuffer(64000)); - await Promise.resolve(); - await Promise.resolve(); - expect(played).toHaveLength(1); - expect(completed).not.toHaveBeenCalled(); - played[0].end(); - await next; - expect(completed).toHaveBeenCalledWith(1); - await engine.destroy(); -}); diff --git a/packages/app/src/audio/audio-engine.web.ts b/packages/app/src/audio/audio-engine.web.ts index 0a7f436a99c..5516575e695 100644 --- a/packages/app/src/audio/audio-engine.web.ts +++ b/packages/app/src/audio/audio-engine.web.ts @@ -285,12 +285,6 @@ export function createAudioEngine( processor.connect(gain); gain.connect(context.destination); - for (const track of stream.getAudioTracks()) { - track.addEventListener("ended", () => { - if (refs.stream === stream) callbacks.onInterruption?.(); - }); - } - refs.started = true; refs.stream = stream; refs.source = source; diff --git a/packages/app/src/audio/playback.test.ts b/packages/app/src/audio/playback.test.ts index 498b4175d79..2627d899cf6 100644 --- a/packages/app/src/audio/playback.test.ts +++ b/packages/app/src/audio/playback.test.ts @@ -113,10 +113,9 @@ test("ending the voice waiting cue leaves a plugin's active audio playing", asyn }); runtime.registerSession({ serverId: "host", - setVoiceMode: async () => ({}), + setVoiceMode: async () => {}, sendVoiceAudioChunk: async () => {}, audioPlayed: async () => {}, - readVoiceInputReceipts: async () => ({ items: [], nextCursor: null }), abortRequest: async () => {}, setAssistantAudioPlaying: () => {}, }); diff --git a/packages/app/src/audio/playback.ts b/packages/app/src/audio/playback.ts index 4f714d72e73..8d0744b79c5 100644 --- a/packages/app/src/audio/playback.ts +++ b/packages/app/src/audio/playback.ts @@ -24,18 +24,7 @@ export function createPlaybackQueue( active = item; try { if (item.controller.signal.aborted) throw new Error("Playback stopped"); - // Decoding can outlive cancellation. Release this owner immediately; - // the engine checks the same signal before starting prepared audio. - let cancelPlayback: () => void = () => {}; - const canceled = new Promise((_resolve, reject) => { - cancelPlayback = () => reject(new Error("Playback stopped")); - item.controller.signal.addEventListener("abort", cancelPlayback, { once: true }); - }); - try { - item.resolve(await Promise.race([start(item.source, item.controller.signal), canceled])); - } finally { - item.controller.signal.removeEventListener("abort", cancelPlayback); - } + item.resolve(await start(item.source, item.controller.signal)); } catch (error) { item.reject(error); } finally { diff --git a/packages/app/src/companion-stream/feed.test.tsx b/packages/app/src/companion-stream/feed.test.tsx deleted file mode 100644 index 1409524e047..00000000000 --- a/packages/app/src/companion-stream/feed.test.tsx +++ /dev/null @@ -1,97 +0,0 @@ -// @vitest-environment jsdom -import React from "react"; -import { cleanup, fireEvent, render, screen } from "@testing-library/react"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { AgentArtifact } from "@getpaseo/protocol/agent-types"; - -const { updateCompanionEntry } = vi.hoisted(() => ({ updateCompanionEntry: vi.fn() })); -vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) })); -vi.mock("react-native-unistyles", () => ({ - StyleSheet: { create: () => ({}) }, - withUnistyles: (component: T) => component, -})); -vi.mock("@/runtime/host-runtime", () => ({ - useHostRuntimeConnectionStatus: () => "online", - useHostRuntimeClient: () => ({ updateCompanionEntry }), -})); -vi.mock("expo-image", () => ({ Image: () => null })); -vi.mock("@/attachments/service", () => ({ persistAttachmentFromBytes: vi.fn() })); -vi.mock("@/attachments/use-attachment-preview-url", () => ({ useAttachmentPreviewUrl: vi.fn() })); -vi.mock("@/data/query", () => ({ useFetchQuery: vi.fn() })); -vi.mock("@/components/ui/button", () => ({ Button: () => null })); -vi.mock("@/components/ui/text-input", () => ({ EditingTextInput: () => null })); -vi.mock("@/components/ui/segmented-control", () => ({ SegmentedControl: () => null })); -vi.mock("@/components/markdown/renderer", () => ({ MarkdownRenderer: () => null })); -vi.mock("lucide-react-native", () => ({ - FileCode2: () => null, - FileDiff: () => null, - FileText: () => null, - Image: () => null, -})); - -import { CompanionFeed } from "./feed"; - -const artifact: AgentArtifact = { - path: "report.html", - name: "report.html", - kind: "html", - mimeType: "text/html", - size: 120, - createdAt: "2026-09-21T12:01:00Z", - updatedAt: "2026-09-21T12:01:00Z", -}; - -function mountUnsupported(artifacts: readonly AgentArtifact[]) { - const openFile = vi.fn(); - const returnToChat = vi.fn(); - render( - , - ); - return { openFile, returnToChat }; -} - -beforeEach(() => { - vi.stubGlobal("React", React); - updateCompanionEntry.mockClear(); -}); -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -describe("unsupported companion stream", () => { - it("retains supplied file cards and opens them without companion mutations", () => { - const { openFile, returnToChat } = mountUnsupported([artifact]); - expect(screen.getByTestId("companion-stream-unsupported")).toBeTruthy(); - const card = screen.getByTestId("artifact-card-report.html"); - fireEvent.click(card); - expect(openFile).toHaveBeenCalledExactlyOnceWith({ - location: { path: "report.html" }, - disposition: "side", - }); - expect(returnToChat).toHaveBeenCalledTimes(1); - expect(screen.queryByTestId("companion-stream")).toBeNull(); - expect(screen.queryByTestId("companion-stream-pending")).toBeNull(); - expect(updateCompanionEntry).not.toHaveBeenCalled(); - }); - - it("shows the upgrade notice and ordinary empty state without supplied files", () => { - const { openFile } = mountUnsupported([]); - expect(screen.getByTestId("companion-stream-unsupported")).toBeTruthy(); - expect(screen.getByTestId("artifact-feed-empty")).toBeTruthy(); - expect(screen.queryByTestId("artifact-feed")).toBeNull(); - expect(screen.queryByTestId("companion-stream")).toBeNull(); - expect(openFile).not.toHaveBeenCalled(); - expect(updateCompanionEntry).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/app/src/companion-stream/feed.tsx b/packages/app/src/companion-stream/feed.tsx deleted file mode 100644 index 8be892f92b4..00000000000 --- a/packages/app/src/companion-stream/feed.tsx +++ /dev/null @@ -1,539 +0,0 @@ -import type { AgentArtifact } from "@getpaseo/protocol/agent-types"; -import { isCompanionEntryPending, type CompanionEntry } from "@getpaseo/protocol/companion-stream"; -import { useCallback, useMemo, useRef, useState } from "react"; -import { ActivityIndicator, FlatList, Text, View } from "react-native"; -import { useTranslation } from "react-i18next"; -import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { ArtifactCard, ArtifactFeed } from "@/artifacts/feed"; -import { Button } from "@/components/ui/button"; -import { EditingTextInput, type EditingTextInputHandle } from "@/components/ui/text-input"; -import { MarkdownRenderer } from "@/components/markdown/renderer"; -import { SegmentedControl } from "@/components/ui/segmented-control"; -import type { ToastApi } from "@/components/toast-host"; -import { useHostRuntimeConnectionStatus, useHostRuntimeClient } from "@/runtime/host-runtime"; -import { formatMessageTimestamp } from "@/utils/time"; -import type { WorkspaceFileOpenRequest } from "@/workspace/file-open"; -import { buildCompanionFeed, type CompanionFeedItem } from "./model"; - -interface CompanionFeedProps { - serverId: string; - agentId: string; - cwd: string; - entries: readonly CompanionEntry[]; - artifacts: readonly AgentArtifact[]; - isSupported: boolean; - onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void; - onReturnToChat: () => void; - onReplyInChat: () => void; - toast?: ToastApi | null; -} - -const keyExtractor = (item: CompanionFeedItem) => item.id; -const NoteInput = withUnistyles(EditingTextInput, (theme) => ({ - placeholderTextColor: theme.colors.foregroundMuted, -})); - -type ViewTab = "stream" | "pinned"; -type StreamFilter = "all" | "question" | "feature_request" | "permission" | "outcome" | "q_and_a"; - -export function CompanionFeed({ - serverId, - agentId, - cwd, - entries, - artifacts, - isSupported, - onOpenWorkspaceFile, - onReturnToChat, - onReplyInChat, - toast, -}: CompanionFeedProps) { - const { t } = useTranslation(); - const connection = useHostRuntimeConnectionStatus(serverId); - const client = useHostRuntimeClient(serverId); - - const [viewTab, setViewTab] = useState("stream"); - const [filter, setFilter] = useState("all"); - const [onlyOpen, setOnlyOpen] = useState(true); - const [pinText, setPinText] = useState(""); - const noteInput = useRef(null); - - const items = useMemo(() => buildCompanionFeed(entries, artifacts), [entries, artifacts]); - - const visible = useMemo(() => { - return items.filter((item) => { - if (viewTab === "pinned") { - return item.kind === "entry" && item.entry.kind === "pin"; - } else { - // Stream / Queue - if (item.kind === "entry" && item.entry.kind === "pin") return false; - - if (item.kind === "artifact") { - return filter === "all" && !onlyOpen; - } - - if (filter !== "all" && item.entry.kind !== filter) return false; - - if (onlyOpen) { - if (item.entry.kind === "question" || item.entry.kind === "feature_request") { - return item.entry.status === "open"; - } - if (item.entry.kind === "permission") { - return item.entry.status === "pending"; - } - return false; - } - - return true; - } - }); - }, [items, viewTab, filter, onlyOpen]); - - const openArtifact = useCallback( - (artifact: AgentArtifact) => { - onOpenWorkspaceFile?.({ location: { path: artifact.path }, disposition: "side" }); - onReturnToChat(); - }, - [onOpenWorkspaceFile, onReturnToChat], - ); - - const reportFailure = useCallback(() => { - toast?.error(t("agentPanel.stream.mutationFailed")); - }, [toast, t]); - - const handleUpdateStatus = useCallback( - (entryId: string, status: "open" | "reviewed" | "done") => { - client - ?.updateCompanionEntry({ agentId, entryId, action: "update_status", status }) - .catch(reportFailure); - }, - [client, agentId, reportFailure], - ); - - const handleRemovePin = useCallback( - (entryId: string) => { - client?.updateCompanionEntry({ agentId, entryId, action: "remove_pin" }).catch(reportFailure); - }, - [client, agentId, reportFailure], - ); - - const handlePinArtifact = useCallback( - (artifact: { path: string }) => { - client - ?.updateCompanionEntry({ - agentId, - action: "add_pin", - text: `Artifact: ${artifact.path}`, - sourceId: `artifact:${artifact.path}`, - }) - .catch(reportFailure); - }, - [client, agentId, reportFailure], - ); - - const renderItem = useCallback( - ({ item }: { item: CompanionFeedItem }) => - item.kind === "artifact" ? ( - handlePinArtifact(item.artifact)} - /> - ) : ( - - ), - [ - serverId, - cwd, - openArtifact, - handlePinArtifact, - onReturnToChat, - onReplyInChat, - handleUpdateStatus, - handleRemovePin, - ], - ); - - const handleToggleOnlyOpen = useCallback(() => setOnlyOpen((v) => !v), []); - const handleSubmitPin = useCallback(() => { - if (!pinText.trim()) return; - client - ?.updateCompanionEntry({ agentId, action: "add_pin", text: pinText.trim() }) - .catch(reportFailure); - setPinText(""); - noteInput.current?.replaceText(""); - }, [client, agentId, pinText, reportFailure]); - - const header = useMemo( - () => ( - - {t("agentPanel.stream.title")} - {t("agentPanel.stream.description")} - - {connection !== "online" ? ( - - {connection === "connecting" ? : null} - {t("agentPanel.stream.offline")} - - ) : null} - - - - {viewTab === "stream" && ( - - - - - )} - - {viewTab === "pinned" && ( - - - - - )} - - ), - [connection, viewTab, filter, onlyOpen, t, handleToggleOnlyOpen, handleSubmitPin], - ); - - const empty = useMemo( - () => ( - - - {viewTab === "pinned" - ? t("agentPanel.stream.noPinnedItems") - : t("agentPanel.stream.noItemsFound")} - - - - ), - [viewTab, onReturnToChat, t], - ); - - const hasItems = visible.length > 0; - const footer = useMemo( - () => - hasItems && viewTab === "stream" ? ( - - {t("agentPanel.stream.outcomeDescription")} - {t("agentPanel.stream.retention")} - - ) : null, - [hasItems, viewTab, t], - ); - - if (!isSupported) { - return ( - - - {t("agentPanel.stream.updateHost")} - {t("agentPanel.stream.updateHostDescription")} - - - - ); - } - - return ( - - ); -} - -function CardSeparator() { - return ; -} - -// eslint-disable-next-line complexity -function EntryCard({ - entry, - onReturnToChat, - onReplyInChat, - onUpdateStatus, - onRemovePin, -}: { - entry: CompanionEntry; - onReturnToChat: () => void; - onReplyInChat: () => void; - onUpdateStatus: (id: string, status: "open" | "reviewed" | "done") => void; - onRemovePin: (id: string) => void; -}) { - const { t } = useTranslation(); - const [expanded, setExpanded] = useState(false); - const toggleExpanded = useCallback(() => setExpanded((value) => !value), []); - const handleSetOpen = useCallback( - () => onUpdateStatus(entry.id, "open"), - [onUpdateStatus, entry.id], - ); - const handleSetReviewed = useCallback( - () => onUpdateStatus(entry.id, "reviewed"), - [onUpdateStatus, entry.id], - ); - const handleSetDone = useCallback( - () => onUpdateStatus(entry.id, "done"), - [onUpdateStatus, entry.id], - ); - const handleRemovePinLocal = useCallback(() => onRemovePin(entry.id), [onRemovePin, entry.id]); - const pending = isCompanionEntryPending(entry); - const expandedAccessibilityState = useMemo(() => ({ expanded }), [expanded]); - - let title: string; - let status: string = ""; - if (entry.kind === "question") { - title = t("agentPanel.stream.question"); - status = entry.status; - } else if (entry.kind === "feature_request") { - title = t("agentPanel.stream.featureRequest"); - status = entry.status; - } else if (entry.kind === "permission") { - const titles = { - question: "question", - plan: "decision", - tool: "permission", - mode: "permission", - other: "permission", - } as const; - title = t(`agentPanel.stream.${titles[entry.requestKind]}`); - status = t( - entry.status === "pending" - ? "agentPanel.stream.pendingStatus" - : `agentPanel.stream.${entry.status}`, - ); - } else if (entry.kind === "pin") { - title = t("agentPanel.stream.streamPin"); - } else if (entry.kind === "q_and_a") { - title = t("agentPanel.stream.qAndA"); - } else { - title = t(`agentPanel.stream.${entry.status}`); - } - - let body = null; - if (entry.text) { - body = expanded ? ( - - - {entry.kind === "q_and_a" && entry.answer && ( - - {t("agentPanel.stream.answerLabel")} - - - )} - - ) : ( - - - {entry.text} - - {entry.kind === "q_and_a" && entry.answer && ( - - {t("agentPanel.stream.answerLabel")} - - {entry.answer} - - - )} - - ); - } - - return ( - - - {formatMessageTimestamp(new Date(entry.timestamp))} - {entry.kind === "pin" ? ( - - ) : null} - - - {title} - {status ? ( - {status} - ) : null} - - {body} - - {entry.truncated ? ( - {t("agentPanel.stream.excerpt")} - ) : null} - - - {entry.text ? ( - - ) : null} - - - {(entry.kind === "question" || entry.kind === "feature_request") && ( - - - - - - )} - - - ); -} - -const styles = StyleSheet.create((theme) => ({ - root: { flex: 1, backgroundColor: theme.colors.surface0 }, - feed: { width: "100%", maxWidth: 760, alignSelf: "center", padding: theme.spacing[4] }, - header: { gap: theme.spacing[2], paddingBottom: theme.spacing[6] }, - notice: { - padding: theme.spacing[3], - gap: theme.spacing[2], - backgroundColor: theme.colors.surface2, - }, - title: { - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.semibold, - }, - description: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm }, - eyebrow: { color: theme.colors.foregroundExtraMuted, fontSize: theme.fontSize.sm }, - card: { - padding: theme.spacing[4], - borderWidth: 1, - borderColor: theme.colors.border, - borderRadius: theme.borderRadius.lg, - backgroundColor: theme.colors.surface1, - gap: theme.spacing[2], - }, - pendingCard: { borderLeftWidth: 3, borderLeftColor: theme.colors.accent }, - pendingText: { color: theme.colors.accent }, - body: { - color: theme.colors.foreground, - fontSize: theme.fontSize.sm, - lineHeight: 22, - marginTop: theme.spacing[2], - }, - actions: { - flexDirection: "row", - flexWrap: "wrap", - gap: theme.spacing[2], - marginTop: theme.spacing[2], - }, - touchTarget: { minHeight: 44 }, - empty: { gap: theme.spacing[3], paddingVertical: theme.spacing[6] }, - separator: { height: theme.spacing[3] }, - footer: { - gap: theme.spacing[2], - paddingVertical: theme.spacing[6], - }, - segmentContainer: { gap: theme.spacing[2], marginTop: theme.spacing[2] }, - pinInputContainer: { flexDirection: "row", gap: theme.spacing[2], marginTop: theme.spacing[2] }, - pinInput: { - flex: 1, - borderWidth: 1, - borderColor: theme.colors.border, - padding: theme.spacing[2], - borderRadius: theme.borderRadius.md, - color: theme.colors.foreground, - }, - qaAnswerContainer: { - marginTop: theme.spacing[2], - paddingLeft: theme.spacing[2], - borderLeftWidth: 2, - borderLeftColor: theme.colors.border, - }, - qaAnswerLabel: { - fontWeight: "bold", - marginBottom: theme.spacing[1], - fontSize: theme.fontSize.sm, - color: theme.colors.foregroundMuted, - }, - entryHeaderRow: { flexDirection: "row", justifyContent: "space-between" }, - statusActionsRow: { - flexDirection: "row", - gap: theme.spacing[2], - marginTop: theme.spacing[2], - width: "100%", - }, -})); diff --git a/packages/app/src/companion-stream/model.test.ts b/packages/app/src/companion-stream/model.test.ts deleted file mode 100644 index 466e33b3d4a..00000000000 --- a/packages/app/src/companion-stream/model.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { buildCompanionFeed } from "./model"; -import { isCompanionEntryPending, type CompanionEntry } from "@getpaseo/protocol/companion-stream"; - -describe("companion feed", () => { - it("interleaves file cards and moments by newest timestamp, with stable identities", () => { - const entries: CompanionEntry[] = [ - { - id: "question:one", - kind: "question", - text: "Ship it?", - timestamp: "2026-09-21T12:00:00Z", - status: "open", - truncated: false, - }, - { - id: "outcome:two", - kind: "outcome", - text: "Done", - timestamp: "2026-09-21T12:02:00Z", - status: "completed", - truncated: false, - }, - ]; - const artifact = { - path: "report.md", - name: "report.md", - kind: "markdown" as const, - mimeType: "text/markdown", - size: 120, - createdAt: "2026-09-21T12:01:00Z", - updatedAt: "2026-09-21T12:01:00Z", - }; - const feed = buildCompanionFeed(entries, [artifact]); - expect(feed).toEqual([ - { id: "outcome:two", kind: "entry", timestamp: entries[1].timestamp, entry: entries[1] }, - { id: "artifact:report.md", kind: "artifact", timestamp: artifact.updatedAt, artifact }, - { id: "question:one", kind: "entry", timestamp: entries[0].timestamp, entry: entries[0] }, - ]); - expect(entries.map((entry) => entry.id)).toEqual(["question:one", "outcome:two"]); - }); - it("filters only unresolved questions and approvals", () => { - const base = { - id: "one", - timestamp: "2026-09-21T12:00:00Z", - text: "Question", - truncated: false, - }; - const entries: CompanionEntry[] = [ - { ...base, kind: "question", status: "open" }, - { ...base, kind: "question", status: "reply_sent" }, - { ...base, kind: "permission", requestId: "p", requestKind: "plan", status: "pending" }, - { ...base, kind: "permission", requestId: "p", requestKind: "plan", status: "expired" }, - { ...base, kind: "outcome", status: "completed" }, - ]; - expect(entries.filter(isCompanionEntryPending)).toEqual([entries[0], entries[2]]); - }); -}); diff --git a/packages/app/src/companion-stream/model.ts b/packages/app/src/companion-stream/model.ts deleted file mode 100644 index 9b6f3e01f1c..00000000000 --- a/packages/app/src/companion-stream/model.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { AgentArtifact } from "@getpaseo/protocol/agent-types"; -import type { CompanionEntry } from "@getpaseo/protocol/companion-stream"; - -export type CompanionFeedItem = - | { id: string; kind: "artifact"; timestamp: string; artifact: AgentArtifact } - | { id: string; kind: "entry"; timestamp: string; entry: CompanionEntry }; - -export function buildCompanionFeed( - entries: readonly CompanionEntry[], - artifacts: readonly AgentArtifact[], -): CompanionFeedItem[] { - return [ - ...entries.map( - (entry): CompanionFeedItem => ({ - id: entry.id, - kind: "entry", - timestamp: entry.timestamp, - entry, - }), - ), - ...artifacts.map( - (artifact): CompanionFeedItem => ({ - id: `artifact:${artifact.path}`, - kind: "artifact", - timestamp: artifact.updatedAt, - artifact, - }), - ), - ].sort((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp)); -} diff --git a/packages/app/src/components/agent-view-switcher.tsx b/packages/app/src/components/agent-view-switcher.tsx deleted file mode 100644 index 341610924f7..00000000000 --- a/packages/app/src/components/agent-view-switcher.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import { useMemo } from "react"; -import { ListFilter, MessageSquare } from "lucide-react-native"; -import { useTranslation } from "react-i18next"; -import { StyleSheet } from "react-native-unistyles"; -import { SegmentedControl } from "@/components/ui/segmented-control"; -import { useIsCompactFormFactor } from "@/constants/layout"; - -export function AgentViewSwitcher({ - value, - onValueChange, - disabled = false, -}: { - value: "chat" | "artifacts"; - onValueChange: (value: "chat" | "artifacts") => void; - disabled?: boolean; -}) { - const { t } = useTranslation(); - const isCompact = useIsCompactFormFactor(); - const options = useMemo( - () => [ - { - value: "chat" as const, - label: t("agentPanel.artifacts.chatTab"), - icon: ({ color, size }: { color: string; size: number }) => ( - - ), - testID: "agent-view-chat", - disabled, - }, - { - value: "artifacts" as const, - label: t("agentPanel.stream.tab"), - icon: ({ color, size }: { color: string; size: number }) => ( - - ), - testID: "agent-view-artifacts", - disabled, - }, - ], - [t, disabled], - ); - return ( - - ); -} -const styles = StyleSheet.create((theme) => ({ - rail: { - minHeight: 40, - flexShrink: 0, - flexDirection: "row", - alignItems: "center", - justifyContent: "center", - paddingHorizontal: theme.spacing[3], - paddingVertical: theme.spacing[2], - borderBottomWidth: 1, - borderBottomColor: theme.colors.border, - }, - compactSegment: { minHeight: 44 }, -})); diff --git a/packages/app/src/components/message.tsx b/packages/app/src/components/message.tsx index 4fd5ee88dea..dcad4a3ed55 100644 --- a/packages/app/src/components/message.tsx +++ b/packages/app/src/components/message.tsx @@ -42,10 +42,8 @@ import { CircleDot, Copy, FileSymlink, - HelpCircle, Info, MicVocal, - Pin, Plus, Scissors, TriangleAlertIcon, @@ -105,8 +103,6 @@ interface UserMessageProps { images?: UserMessageImageAttachment[]; attachments?: AgentAttachment[]; timestamp: number; - onPin?: (text: string) => void; - onQAndA?: (text: string, messageId?: string) => void; capabilities?: AgentCapabilityFlags; client?: DaemonClient | null; isFirstInGroup?: boolean; @@ -407,8 +403,6 @@ export const UserMessage = memo(function UserMessage({ images = [], attachments = [], timestamp, - onPin, - onQAndA, capabilities, client, isFirstInGroup = true, @@ -439,11 +433,6 @@ export const UserMessage = memo(function UserMessage({ const handlePointerEnter = useCallback(() => setIsHovered(true), []); const handlePointerLeave = useCallback(() => setIsHovered(false), []); const getMessageContent = useCallback(() => message, [message]); - const handlePin = useCallback(() => onPin?.(message), [onPin, message]); - const handleQAndA = useCallback( - () => onQAndA?.(message, messageId), - [onQAndA, message, messageId], - ); const handleRewind = useCallback( (input: { mode: RewindMode; rewoundText: string }) => { return rewindMutation.rewindAgent(input); @@ -550,15 +539,6 @@ export const UserMessage = memo(function UserMessage({ onRewind={handleRewind} /> ) : null} - {onPin ? ( - - ) : null} - {onQAndA ? ( - - ) : null} Promise | void; - onPin?: (text: string) => void; } const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({ @@ -636,7 +615,6 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({ completedAt, durationMs, onFork, - onPin, }: AssistantTurnFooterProps) { const { t } = useTranslation(); const [hovered, setHovered] = useState(false); @@ -685,23 +663,13 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({ }, [onFork], ); - const handlePin = useCallback(() => { - if (onPin && getContent) { - onPin(getContent()); - } - }, [onPin, getContent]); + const canFork = Boolean(onFork); return ( - {onPin || getContent || canFork ? ( + {getContent || canFork ? ( - {onPin ? ( - - ) : null} {getContent ? ( ({ }, })); -interface TurnPinButtonProps { - onPin: () => void; - containerStyle?: StyleProp; -} - -export const TurnPinButton = memo(function TurnPinButton({ - onPin, - containerStyle, -}: TurnPinButtonProps) { - const pressableStyle = useMemo( - () => [turnCopyButtonStylesheet.container, containerStyle], - [containerStyle], - ); - - return ( - - {({ hovered }) => { - const iconColor = hovered - ? turnCopyButtonStylesheet.iconHoveredColor.color - : turnCopyButtonStylesheet.iconColor.color; - return ; - }} - - ); -}); - -interface TurnQAndAButtonProps { - onQAndA: () => void; - containerStyle?: StyleProp; -} - -export const TurnQAndAButton = memo(function TurnQAndAButton({ - onQAndA, - containerStyle, -}: TurnQAndAButtonProps) { - const pressableStyle = useMemo( - () => [turnCopyButtonStylesheet.container, containerStyle], - [containerStyle], - ); - - return ( - - {({ hovered }) => { - const iconColor = hovered - ? turnCopyButtonStylesheet.iconHoveredColor.color - : turnCopyButtonStylesheet.iconColor.color; - return ; - }} - - ); -}); - interface TurnCopyButtonProps { getContent: () => string; containerStyle?: StyleProp; diff --git a/packages/app/src/components/realtime-voice-overlay.test.tsx b/packages/app/src/components/realtime-voice-overlay.test.tsx deleted file mode 100644 index 8bdf287c604..00000000000 --- a/packages/app/src/components/realtime-voice-overlay.test.tsx +++ /dev/null @@ -1,116 +0,0 @@ -/** @vitest-environment jsdom */ -import React, { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { createInstance } from "i18next"; -import { I18nextProvider } from "react-i18next"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { en } from "@/i18n/resources/en"; - -// Native styling and live microphone telemetry are outside this rendered UI test. -vi.mock("react-native-unistyles", async () => { - const { darkTheme } = await import("@/styles/theme"); - return { - StyleSheet: { create: (factory: (theme: typeof darkTheme) => unknown) => factory(darkTheme) }, - withUnistyles: (component: unknown) => component, - useUnistyles: () => ({ theme: darkTheme }), - }; -}); -vi.mock("@/contexts/voice-context", () => ({ - useVoiceTelemetry: () => ({ volume: 0, isSpeaking: false }), -})); -vi.mock("./volume-meter", () => ({ VolumeMeter: () => null })); -vi.stubGlobal("React", React); -vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); -import { RealtimeVoiceOverlay } from "./realtime-voice-overlay"; - -describe("voice microphone controls", () => { - let root: Root; - let container: HTMLDivElement; - const i18n = createInstance(); - const onToggleMute = vi.fn(); - const onStop = vi.fn(); - const onCancelAgent = vi.fn(); - const baseProps: React.ComponentProps = { - isMuted: true, - isSwitching: false, - failure: null, - lastInputStatus: null, - onToggleMute, - onStop, - }; - - beforeEach(async () => { - container = document.createElement("div"); - document.body.appendChild(container); - if (!i18n.isInitialized) { - await i18n.init({ lng: "en", resources: { en: { translation: en } } }); - } - root = createRoot(container); - }); - - afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - onToggleMute.mockClear(); - onStop.mockClear(); - onCancelAgent.mockClear(); - }); - - async function render(props: Partial = {}) { - await act(async () => { - root.render( - - - , - ); - }); - } - - it("says it is not listening and why when input stops reaching the agent", async () => { - await render({ isMuted: false, failure: "host-disconnected" }); - expect(container.textContent).toContain("Not listening"); - expect(container.textContent).not.toContain("Microphone on"); - expect(container.querySelector('[role="alert"]')?.textContent).toBe( - "Host disconnected. Microphone input is paused until it reconnects.", - ); - await render({ isMuted: false, failure: "recognition-stalled" }); - expect(container.textContent).toContain("Not listening"); - expect(container.querySelector('[role="alert"]')?.textContent).toBe( - "Speech recognition stopped responding. Stop and restart voice.", - ); - }); - - it("keeps listening status for a single missed utterance", async () => { - await render({ isMuted: false, failure: "nothing-recognized" }); - expect(container.textContent).toContain("Microphone on"); - expect(container.querySelector('[role="alert"]')?.textContent).toBe( - "Didn't catch that. Say it again.", - ); - }); - - it("shows delivery status beside the controls", async () => { - await render({ isMuted: false, lastInputStatus: "queued" }); - expect(container.textContent).toContain("Speech queued for agent"); - await render({ isMuted: false, lastInputStatus: "sent" }); - expect(container.textContent).toContain("Speech sent to agent"); - await render({ isMuted: false, lastInputStatus: "unknown" }); - expect(container.textContent).toContain("Speech delivery uncertain"); - }); - - it("keeps Interrupt agent separate from Stop voice", async () => { - await render({ isMuted: false, isAgentRunning: true, onCancelAgent }); - const interrupt = container.querySelector('[aria-label="Interrupt agent"]')!; - const stop = container.querySelector('[aria-label="Stop realtime voice"]')!; - await act(async () => stop.click()); - expect(onStop).toHaveBeenCalledOnce(); - expect(onCancelAgent).not.toHaveBeenCalled(); - await act(async () => interrupt.click()); - expect(onCancelAgent).toHaveBeenCalledOnce(); - }); - - it("hides Interrupt agent while the agent is idle", async () => { - await render({ isMuted: false, isAgentRunning: false, onCancelAgent }); - expect(container.querySelector('[aria-label="Interrupt agent"]')).toBeNull(); - expect(container.querySelector('[aria-label="Stop realtime voice"]')).not.toBeNull(); - }); -}); diff --git a/packages/app/src/components/realtime-voice-overlay.tsx b/packages/app/src/components/realtime-voice-overlay.tsx index fef244eadca..88b2e378b41 100644 --- a/packages/app/src/components/realtime-voice-overlay.tsx +++ b/packages/app/src/components/realtime-voice-overlay.tsx @@ -1,65 +1,30 @@ import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { Pressable, Text, View } from "react-native"; -import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { Mic, MicOff, PhoneOff, Square } from "lucide-react-native"; +import { Pressable, View } from "react-native"; +import { StyleSheet, useUnistyles } from "react-native-unistyles"; +import { Mic, MicOff, Square } from "lucide-react-native"; import { FOOTER_HEIGHT } from "@/constants/layout"; import { useVoiceTelemetry } from "@/contexts/voice-context"; -import type { VoiceFailureKind } from "@/voice/voice-failure"; -import { isVoiceFailureBlocking } from "@/voice/voice-failure"; -import type { VoiceInputStatus } from "@/voice/voice-runtime"; -import type { Theme } from "@/styles/theme"; import { VolumeMeter } from "./volume-meter"; -const VoiceMic = withUnistyles(Mic); -const VoiceMicOff = withUnistyles(MicOff); -const VoicePhoneOff = withUnistyles(PhoneOff); -const VoiceSquare = withUnistyles(Square); -const VoiceSpinner = withUnistyles(LoadingSpinner); -const whiteIcon = (theme: Theme) => ({ - size: theme.iconSize.lg, - color: theme.colors.palette.white, -}); -const filledWhiteIcon = (theme: Theme) => ({ - ...whiteIcon(theme), - fill: theme.colors.palette.white, -}); -const muteIcon = (theme: Theme) => ({ size: theme.iconSize.lg, color: theme.colors.foreground }); -const whiteSpinner = (theme: Theme) => ({ color: theme.colors.palette.white }); - interface RealtimeVoiceOverlayProps { isMuted: boolean; isSwitching: boolean; - failure: VoiceFailureKind | null; - lastInputStatus?: VoiceInputStatus | null; - isAgentRunning?: boolean; - isCancellingAgent?: boolean; onToggleMute: () => void; onStop: () => void; - onCancelAgent?: () => void; } const OVERLAY_BUTTON_SIZE = 44; const OVERLAY_VERTICAL_PADDING = (FOOTER_HEIGHT - OVERLAY_BUTTON_SIZE) / 2; -const inputStatusLabels = { - queued: { key: "realtimeVoice.inputQueued", defaultValue: "Speech queued for agent" }, - sent: { key: "realtimeVoice.inputSent", defaultValue: "Speech sent to agent" }, - removed: { key: "realtimeVoice.inputRemoved", defaultValue: "Speech removed from queue" }, - unknown: { key: "realtimeVoice.inputUnknown", defaultValue: "Speech delivery uncertain" }, -} as const; export function RealtimeVoiceOverlay({ isMuted, isSwitching, - failure, - lastInputStatus, - isAgentRunning, - isCancellingAgent, onToggleMute, onStop, - onCancelAgent, }: RealtimeVoiceOverlayProps) { + const { theme } = useUnistyles(); const { t } = useTranslation(); const { volume, isSpeaking } = useVoiceTelemetry(); const muteButtonStyle = useMemo( @@ -75,26 +40,8 @@ export function RealtimeVoiceOverlay({ () => [styles.actionButton, styles.stopButton, isSwitching ? styles.buttonDisabled : undefined], [isSwitching], ); - const notListening = isMuted || (failure !== null && isVoiceFailureBlocking(failure)); return ( - - - {notListening ? t("realtimeVoice.notListening") : t("realtimeVoice.listening")} - - {failure && ( - - {t(`realtimeVoice.failure.${failure}`)} - - )} - {lastInputStatus && ( - - {t(inputStatusLabels[lastInputStatus].key, { - defaultValue: inputStatusLabels[lastInputStatus].defaultValue, - })} - - )} - - {isAgentRunning && onCancelAgent && ( - - {isCancellingAgent ? ( - - ) : ( - - )} - - )} - {isMuted ? ( - + ) : ( - + )} @@ -147,9 +76,14 @@ export function RealtimeVoiceOverlay({ style={stopButtonStyle} > {isSwitching ? ( - + ) : ( - + )} @@ -171,23 +105,8 @@ const styles = StyleSheet.create((theme) => ({ borderWidth: theme.borderWidth[1], borderColor: theme.colors.border, }, - status: { - flex: 1, - gap: theme.spacing[1], - }, - label: { - color: theme.colors.foreground, - fontSize: theme.fontSize.sm, - fontWeight: theme.fontWeight.medium, - }, - mutedLabel: { - color: theme.colors.destructive, - fontSize: theme.fontSize.sm, - fontWeight: theme.fontWeight.medium, - }, - hint: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm }, - error: { color: theme.colors.destructive, fontSize: theme.fontSize.sm }, meterContainer: { + flex: 1, alignItems: "center", justifyContent: "center", }, diff --git a/packages/app/src/components/ui/segmented-control.tsx b/packages/app/src/components/ui/segmented-control.tsx index 918875ecbd3..05d7fedec4e 100644 --- a/packages/app/src/components/ui/segmented-control.tsx +++ b/packages/app/src/components/ui/segmented-control.tsx @@ -26,9 +26,7 @@ interface SegmentedControlProps { onValueChange: (value: T) => void; size?: ControlSize; hideLabels?: boolean; - textWrap?: boolean; style?: StyleProp; - segmentStyle?: StyleProp; testID?: string; } @@ -53,9 +51,7 @@ export function SegmentedControl({ onValueChange, size: sizeProp, hideLabels = false, - textWrap = false, style, - segmentStyle, testID, }: SegmentedControlProps) { const containedSize = useContainedControlSize(); @@ -65,10 +61,7 @@ export function SegmentedControl({ md: { container: styles.containerMd, segment: styles.segmentMd, label: styles.labelMd }, }[size]; const containerSizeStyle = sizeStyles.container; - const segmentSizeStyle = useMemo( - () => [sizeStyles.segment, segmentStyle], - [sizeStyles.segment, segmentStyle], - ); + const segmentSizeStyle = sizeStyles.segment; const labelSizeStyle = sizeStyles.label; const iconSize = controlIconSize[size]; @@ -89,7 +82,6 @@ export function SegmentedControl({ isSelected={isSelected} iconSize={iconSize} hideLabels={hideLabels} - textWrap={textWrap} segmentSizeStyle={segmentSizeStyle} labelSizeStyle={labelSizeStyle} currentValue={value} @@ -106,7 +98,6 @@ function SegmentItem({ isSelected, iconSize, hideLabels, - textWrap, segmentSizeStyle, labelSizeStyle, currentValue, @@ -116,20 +107,14 @@ function SegmentItem({ isSelected: boolean; iconSize: number; hideLabels: boolean; - textWrap: boolean; segmentSizeStyle: StyleProp; labelSizeStyle: StyleProp; currentValue: T; onValueChange: (value: T) => void; }) { const labelStyle = useMemo( - () => [ - styles.label, - labelSizeStyle, - isSelected && styles.labelSelected, - textWrap && styles.labelWrap, - ], - [labelSizeStyle, isSelected, textWrap], + () => [styles.label, labelSizeStyle, isSelected && styles.labelSelected], + [labelSizeStyle, isSelected], ); const handlePress = useCallback(() => { if (!option.disabled && option.value !== currentValue) { @@ -140,13 +125,12 @@ function SegmentItem({ ({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [ styles.segment, segmentSizeStyle, - textWrap && styles.segmentWrap, isSelected && styles.segmentSelected, Boolean(hovered) && !isSelected && styles.segmentHover, pressed && !isSelected && styles.segmentPressed, option.disabled && styles.segmentDisabled, ], - [isSelected, option.disabled, segmentSizeStyle, textWrap], + [isSelected, option.disabled, segmentSizeStyle], ); const accessibilityState = useMemo( () => ({ selected: isSelected, disabled: option.disabled }), @@ -170,7 +154,7 @@ function SegmentItem({ /> ) : null} {hideLabels ? null : ( - + {option.label} )} @@ -236,13 +220,5 @@ const styles = StyleSheet.create((theme) => { labelSelected: { color: theme.colors.foreground, }, - labelWrap: { - flexShrink: 1, - textAlign: "center", - }, - segmentWrap: { - height: "auto", - paddingVertical: theme.spacing[2], - }, }; }); diff --git a/packages/app/src/composer/actions.test.ts b/packages/app/src/composer/actions.test.ts index 28380e6acbd..697f848a09a 100644 --- a/packages/app/src/composer/actions.test.ts +++ b/packages/app/src/composer/actions.test.ts @@ -1,9 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import type { - AgentAttachment, - AgentQueueSnapshot, - ForgeSearchItem, -} from "@getpaseo/protocol/messages"; +import type { AgentAttachment, ForgeSearchItem } from "@getpaseo/protocol/messages"; import type { AttachmentMetadata, ComposerAttachment, @@ -24,27 +20,20 @@ import { import { uploadFileAttachments, cancelComposerAgent, - deleteQueuedComposerMessage, dispatchComposerAgentMessage, editQueuedComposerMessage, findForgeItemByOption, isAttachmentSelectedForForgeItem, - isQueueRevisionConflictError, openComposerAttachment, pickAndPersistImages, queueComposerMessage, - queueComposerMessageOnServer, removeComposerAttachmentAtIndex, - reorderQueuedComposerMessages, - retryQueuedComposerMessage, sendQueuedComposerMessageNow, - takeQueuedComposerMessage, toggleForgeAttachment, toggleForgeAttachmentFromPicker, type MessageSubmissionWriter, type AttachmentPersister, type ComposerCancelClient, - type ComposerQueueClient, type ComposerSendClient, type QueueWriter, type QueuedComposerMessage, @@ -1052,460 +1041,6 @@ describe("findForgeItemByOption / isAttachmentSelectedForForgeItem", () => { }); }); -function createFakeQueueClient( - overrides: Partial = {}, -): ComposerQueueClient & { - enqueued: Array[0]>; - removed: Array<[string, string, number]>; -} { - const enqueued: Array[0]> = []; - const removed: Array<[string, string, number]> = []; - return { - enqueued, - removed, - enqueueAgentMessage: async (input) => { - enqueued.push(input); - return { - agentId: input.agentId, - revision: 1, - items: [ - { - id: input.itemId, - text: input.text, - intent: input.intent, - deliveryState: "pending", - attempts: 0, - createdAt: "2026-01-01T00:00:00.000Z", - }, - ], - }; - }, - updateQueuedAgentMessage: async () => { - throw new Error("not expected in this test"); - }, - reorderQueuedAgentMessages: async () => { - throw new Error("not expected in this test"); - }, - deleteQueuedAgentMessage: async (agentId, itemId, expectedRevision) => { - removed.push([agentId, itemId, expectedRevision]); - return { agentId, revision: 2, items: [] }; - }, - retryQueuedAgentMessage: async () => { - throw new Error("not expected in this test"); - }, - getQueuedAgentMessageImages: async () => [], - ...overrides, - }; -} - -describe("queueComposerMessageOnServer", () => { - it("shows the message locally before the daemon answers, then applies the snapshot", async () => { - const queue = createFakeQueue(); - const client = createFakeQueueClient(); - const snapshots: AgentQueueSnapshot[] = []; - - const result = await queueComposerMessageOnServer({ - client, - agentId: "agent", - text: " queued from the phone ", - attachments: [], - encodeImages: passthroughEncodeImages, - queue, - applySnapshot: (snapshot) => snapshots.push(snapshot), - }); - - expect(result.queued?.text).toBe("queued from the phone"); - expect(client.enqueued).toHaveLength(1); - expect(client.enqueued[0]?.itemId).toBe(result.queued?.id); - expect(snapshots).toHaveLength(1); - expect(snapshots[0]?.items[0]?.id).toBe(result.queued?.id); - }); - - it("admits with the explicit queue intent and never touches a submission writer", async () => { - const queue = createFakeQueue(); - const client = createFakeQueueClient(); - - await queueComposerMessageOnServer({ - client, - agentId: "agent", - text: "queued, not sent", - attachments: [], - encodeImages: passthroughEncodeImages, - queue, - applySnapshot: () => {}, - }); - - // Admission is a queue write only: the input takes no submission writer and - // the row it creates is a queued composer row, not a submitted timeline - // message. The daemon's accepted delivery creates the canonical user row. - expect(client.enqueued[0]?.intent).toBe("queue"); - expect(queue.state.get("agent")?.[0]).toMatchObject({ - id: client.enqueued[0]?.itemId, - text: "queued, not sent", - }); - expect(queue.state.get("agent")?.[0]).not.toHaveProperty("clientMessageId"); - expect(queue.state.get("agent")?.[0]).not.toHaveProperty("deliveryState"); - }); - - it("sends image bytes and keeps the composer-side attachments for other devices", async () => { - const queue = createFakeQueue(); - const client = createFakeQueueClient(); - - await queueComposerMessageOnServer({ - client, - agentId: "agent", - text: "look", - attachments: [ - { kind: "image", metadata: imageMetadata }, - { kind: "forge_issue", item: issueItem }, - ], - encodeImages: passthroughEncodeImages, - queue, - applySnapshot: () => {}, - }); - - expect(client.enqueued[0]?.images).toEqual([{ data: "img-1", mimeType: "image/png" }]); - expect(client.enqueued[0]?.composerAttachments).toEqual([ - { kind: "forge_issue", item: issueItem }, - ]); - }); - - it("rolls the local row back when the daemon rejects the write", async () => { - const queue = createFakeQueue(); - const client = createFakeQueueClient({ - enqueueAgentMessage: async () => { - throw new Error("daemon said no"); - }, - }); - - const result = await queueComposerMessageOnServer({ - client, - agentId: "agent", - text: "doomed", - attachments: [], - encodeImages: passthroughEncodeImages, - queue, - applySnapshot: () => {}, - }); - - expect(result.queued).toBeNull(); - expect(result.error).toBe("daemon said no"); - expect(queue.state.get("agent")).toEqual([]); - }); - - it("writes the outbox entry before sending and clears it on ack", async () => { - const queue = createFakeQueue(); - const client = createFakeQueueClient(); - const added: string[] = []; - const removed: string[] = []; - - const result = await queueComposerMessageOnServer({ - client, - agentId: "agent", - text: "durable", - attachments: [], - encodeImages: passthroughEncodeImages, - queue, - applySnapshot: () => {}, - outbox: { - add: (entry) => added.push(entry.itemId), - remove: (itemId) => removed.push(itemId), - }, - }); - - expect(added).toEqual([result.queued?.id]); - expect(removed).toEqual([result.queued?.id]); - }); - - it("keeps the row and the outbox entry when the send never gets an ack", async () => { - const queue = createFakeQueue(); - const client = createFakeQueueClient({ - enqueueAgentMessage: async () => { - throw new Error("Transport not connected"); - }, - }); - const added: string[] = []; - const removed: string[] = []; - - const result = await queueComposerMessageOnServer({ - client, - agentId: "agent", - text: "survives the relay stall", - attachments: [], - encodeImages: passthroughEncodeImages, - queue, - applySnapshot: () => {}, - outbox: { - add: (entry) => added.push(entry.itemId), - remove: (itemId) => removed.push(itemId), - }, - }); - - expect(result.queued).not.toBeNull(); - expect(result.error).toBeUndefined(); - expect(added).toEqual([result.queued?.id]); - expect(removed).toEqual([]); - expect(queue.state.get("agent")?.map((row) => row.id)).toEqual([result.queued?.id]); - }); - - it("does not reach the daemon for an empty message", async () => { - const queue = createFakeQueue(); - const client = createFakeQueueClient(); - - const result = await queueComposerMessageOnServer({ - client, - agentId: "agent", - text: " ", - attachments: [], - encodeImages: passthroughEncodeImages, - queue, - applySnapshot: () => {}, - }); - - expect(result.queued).toBeNull(); - expect(client.enqueued).toEqual([]); - }); -}); - -describe("takeQueuedComposerMessage", () => { - it("removes the message on the daemon and hands its content back", async () => { - const queue = createFakeQueue( - new Map([["agent", [{ id: "item-1", text: "draft", attachments: [] }]]]), - ); - const client = createFakeQueueClient(); - const snapshots: AgentQueueSnapshot[] = []; - - const result = await takeQueuedComposerMessage({ - client, - agentId: "agent", - messageId: "item-1", - expectedRevision: 3, - queue, - persistImage: async () => imageMetadata, - applySnapshot: (snapshot) => snapshots.push(snapshot), - }); - - expect(result).toEqual({ status: "taken", text: "draft", attachments: [] }); - expect(client.removed).toEqual([["agent", "item-1", 3]]); - expect(snapshots).toHaveLength(1); - }); - - it("rehydrates images from the daemon so a second device keeps them", async () => { - const queue = createFakeQueue( - new Map([["agent", [{ id: "item-1", text: "look", attachments: [] }]]]), - ); - const client = createFakeQueueClient({ - getQueuedAgentMessageImages: async () => [ - { id: "srv-1", mimeType: "image/png", fileName: "shot.png", data: "AAAA" }, - ], - }); - const persisted: string[] = []; - - const result = await takeQueuedComposerMessage({ - client, - agentId: "agent", - messageId: "item-1", - expectedRevision: 0, - queue, - persistImage: async (input) => { - persisted.push(input.dataUrl); - return imageMetadata; - }, - applySnapshot: () => {}, - }); - - expect(persisted).toEqual(["data:image/png;base64,AAAA"]); - expect(result).toEqual({ - status: "taken", - text: "look", - attachments: [{ kind: "image", metadata: imageMetadata }], - }); - }); - - it("reports missing when the message already drained", async () => { - const queue = createFakeQueue(); - const client = createFakeQueueClient(); - - const result = await takeQueuedComposerMessage({ - client, - agentId: "agent", - messageId: "gone", - expectedRevision: 0, - queue, - persistImage: async () => imageMetadata, - applySnapshot: () => {}, - }); - - expect(result).toEqual({ status: "missing" }); - expect(client.removed).toEqual([]); - }); - - it("leaves the message queued when the daemon rejects the removal", async () => { - const queue = createFakeQueue( - new Map([["agent", [{ id: "item-1", text: "draft", attachments: [] }]]]), - ); - const client = createFakeQueueClient({ - deleteQueuedAgentMessage: async () => { - throw new Error("offline"); - }, - }); - - const result = await takeQueuedComposerMessage({ - client, - agentId: "agent", - messageId: "item-1", - expectedRevision: 0, - queue, - persistImage: async () => imageMetadata, - applySnapshot: () => {}, - }); - - expect(result).toEqual({ status: "failed", errorMessage: "offline" }); - expect(queue.state.get("agent")).toHaveLength(1); - }); - - it("reports a stale revision as a conflict instead of removing the row", async () => { - const queue = createFakeQueue( - new Map([["agent", [{ id: "item-1", text: "draft", attachments: [] }]]]), - ); - const client = createFakeQueueClient({ - deleteQueuedAgentMessage: async () => { - throw new Error("queue_revision_conflict"); - }, - }); - - const result = await takeQueuedComposerMessage({ - client, - agentId: "agent", - messageId: "item-1", - expectedRevision: 1, - queue, - persistImage: async () => imageMetadata, - applySnapshot: () => {}, - }); - - expect(result).toEqual({ status: "conflict" }); - expect(queue.state.get("agent")).toHaveLength(1); - }); -}); - -describe("durable queue mutations", () => { - const snapshots: AgentQueueSnapshot[] = []; - const applySnapshot = (snapshot: AgentQueueSnapshot) => snapshots.push(snapshot); - - it("deletes with the revision the caller saw", async () => { - const client = createFakeQueueClient(); - - const result = await deleteQueuedComposerMessage({ - client, - agentId: "agent", - messageId: "item-1", - expectedRevision: 4, - applySnapshot, - }); - - expect(result).toEqual({ status: "applied" }); - expect(client.removed).toEqual([["agent", "item-1", 4]]); - }); - - it("surfaces a stale revision as a conflict, not a failure", async () => { - const client = createFakeQueueClient({ - deleteQueuedAgentMessage: async () => { - throw new Error("queue_revision_conflict"); - }, - }); - - const result = await deleteQueuedComposerMessage({ - client, - agentId: "agent", - messageId: "item-1", - expectedRevision: 1, - applySnapshot, - }); - - expect(result).toEqual({ status: "conflict" }); - }); - - it("reorders with the full id list and the caller's revision", async () => { - const ordered: Array<{ agentId: string; itemIds: string[]; expectedRevision: number }> = []; - const client = createFakeQueueClient({ - reorderQueuedAgentMessages: async (agentId, itemIds, expectedRevision) => { - ordered.push({ agentId, itemIds, expectedRevision }); - return { agentId, revision: 5, items: [] }; - }, - }); - - const result = await reorderQueuedComposerMessages({ - client, - agentId: "agent", - itemIds: ["b", "a"], - expectedRevision: 4, - applySnapshot, - }); - - expect(result).toEqual({ status: "applied" }); - expect(ordered).toEqual([{ agentId: "agent", itemIds: ["b", "a"], expectedRevision: 4 }]); - }); - - it("retries an uncertain or failed item through the explicit retry path", async () => { - const retried: Array<{ agentId: string; itemId: string; expectedRevision: number }> = []; - const client = createFakeQueueClient({ - retryQueuedAgentMessage: async (agentId, itemId, expectedRevision) => { - retried.push({ agentId, itemId, expectedRevision }); - return { - agentId, - revision: 6, - items: [ - { - id: itemId, - text: "hello", - intent: "queue", - deliveryState: "pending", - attempts: 0, - createdAt: "2026-01-01T00:00:00.000Z", - }, - ], - }; - }, - }); - - const result = await retryQueuedComposerMessage({ - client, - agentId: "agent", - messageId: "item-1", - expectedRevision: 5, - applySnapshot, - }); - - expect(result).toEqual({ status: "applied" }); - expect(retried).toEqual([{ agentId: "agent", itemId: "item-1", expectedRevision: 5 }]); - }); - - it("reports other mutation failures with the daemon's message", async () => { - const client = createFakeQueueClient({ - retryQueuedAgentMessage: async () => { - throw new Error("queue_item_dispatching"); - }, - }); - - const result = await retryQueuedComposerMessage({ - client, - agentId: "agent", - messageId: "item-1", - expectedRevision: 5, - applySnapshot, - }); - - expect(result).toEqual({ status: "failed", errorMessage: "queue_item_dispatching" }); - }); - - it("recognizes the revision-conflict code the daemon puts on the error field", () => { - expect(isQueueRevisionConflictError(new Error("queue_revision_conflict"))).toBe(true); - expect(isQueueRevisionConflictError(new Error("queue_item_dispatching"))).toBe(false); - expect(isQueueRevisionConflictError("queue_revision_conflict")).toBe(false); - }); -}); - describe("file upload preparation", () => { it("waits for file bytes and daemon acknowledgement before returning the attachment", async () => { let resolveRead!: (bytes: Uint8Array) => void; diff --git a/packages/app/src/composer/actions.ts b/packages/app/src/composer/actions.ts index 061a32ceae7..f810ef19c6d 100644 --- a/packages/app/src/composer/actions.ts +++ b/packages/app/src/composer/actions.ts @@ -2,12 +2,6 @@ import type { SelectedFile } from "@/attachments/selected-file"; import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit"; import type { ForgeSearchItem } from "@getpaseo/protocol/messages"; import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages"; -import type { - AgentQueueSnapshot, - QueuedAgentDeliveryIntent, - QueuedAgentMessageDeliveryState, - QueuedComposerAttachment, -} from "@getpaseo/protocol/messages"; import type { AttachmentMetadata, ComposerAttachment, @@ -21,7 +15,6 @@ import { splitComposerAttachmentsForSubmit, type ComposerAttachmentSubmitFormat, } from "@/composer/attachments/submit"; -import { toQueuedComposerAttachments } from "@/composer/queue-sync"; import { createUserMessage, generateMessageId, type UserMessageItem } from "@/types/stream"; import type { MessageSubmissionRejectionOutcome } from "@/composer/submission/model"; import type { PickedImageAttachmentInput } from "@/hooks/image-attachment-picker"; @@ -31,18 +24,6 @@ export interface QueuedComposerMessage { id: string; text: string; attachments: ComposerAttachment[]; - /** - * Durable queue state, present only on rows mirrored from a daemon snapshot. - * Local-only rows (old hosts) never set it, which is how the queue track - * tells the two apart. - */ - deliveryState?: QueuedAgentMessageDeliveryState; - lastError?: string | null; - /** - * Outbox mirror state: `pending` while the enqueue is un-acked, `failed` - * once it exhausted its retries without ever reaching the daemon. - */ - syncState?: "pending" | "failed"; } export interface AttachmentPersister { @@ -455,348 +436,3 @@ export function isAttachmentSelectedForForgeItem( attachment.item.number === item.number, ); } - -// ============================================================================ -// Daemon-owned queue — see docs/queue-mirroring.md. -// Only reachable behind server_info.features.durableAgentQueueV1; without the -// flag the composer keeps its local queue, which never leaves this device. -// ============================================================================ - -export interface ComposerQueueClient { - enqueueAgentMessage: (input: { - agentId: string; - itemId: string; - text: string; - intent: QueuedAgentDeliveryIntent; - images?: Array<{ data: string; mimeType: string }>; - attachments?: ReturnType["attachments"]; - composerAttachments?: QueuedComposerAttachment[]; - }) => Promise; - updateQueuedAgentMessage: (input: { - agentId: string; - itemId: string; - text: string; - expectedRevision: number; - images?: Array<{ data: string; mimeType: string }>; - attachments?: ReturnType["attachments"]; - composerAttachments?: QueuedComposerAttachment[]; - }) => Promise; - reorderQueuedAgentMessages: ( - agentId: string, - itemIds: string[], - expectedRevision: number, - ) => Promise; - deleteQueuedAgentMessage: ( - agentId: string, - itemId: string, - expectedRevision: number, - ) => Promise; - retryQueuedAgentMessage: ( - agentId: string, - itemId: string, - expectedRevision: number, - ) => Promise; - getQueuedAgentMessageImages: ( - agentId: string, - itemId: string, - ) => Promise>; -} - -/** - * Durable copy of an enqueue until the daemon acknowledges it. Backed by the - * queue outbox store; actions only see this narrow writer so they stay pure. - */ -export interface QueueOutboxWriter { - add: (entry: { - agentId: string; - itemId: string; - text: string; - intent: QueuedAgentDeliveryIntent; - images: Array<{ data: string; mimeType: string }>; - attachments: ReturnType["attachments"]; - composerAttachments: QueuedComposerAttachment[]; - }) => void; - remove: (itemId: string) => void; -} - -export interface QueueComposerMessageOnServerInput { - client: ComposerQueueClient; - agentId: string; - text: string; - attachments: ComposerAttachment[]; - attachmentSubmitFormat?: ComposerAttachmentSubmitFormat; - encodeImages: ( - images: AttachmentMetadata[], - ) => Promise | undefined>; - queue: QueueWriter; - applySnapshot: (snapshot: AgentQueueSnapshot) => void; - outbox?: QueueOutboxWriter; -} - -/** - * Queues a message on the daemon. The local row appears immediately and is - * replaced by the daemon's snapshot. - * - * With an outbox, the wire payload is written durably before the request goes - * out: a send the daemon never acknowledged — relay stall, app suspended - * mid-request — is retried on the next reconnect instead of being lost, so the - * optimistic row stays. Without one, failure rolls the row back and surfaces - * the error, as before. - * - * Admission only ever appends to the queue writer. No submission writer is - * involved, so nothing puts a row in the timeline before the daemon has - * delivered the prompt; the accepted delivery creates the one canonical user - * row through the normal submission identity system. - */ -export async function queueComposerMessageOnServer( - input: QueueComposerMessageOnServerInput, -): Promise { - const optimistic = queueComposerMessage({ - agentId: input.agentId, - text: input.text, - attachments: input.attachments, - queue: input.queue, - }); - if (!optimistic.queued) { - return optimistic; - } - - const rollBack = (error: unknown): QueueComposerMessageResult & { error?: string } => { - removeQueuedComposerMessageLocally({ - agentId: input.agentId, - messageId: optimistic.queued!.id, - queue: input.queue, - }); - return { - queued: null, - error: error instanceof Error ? error.message : i18n.t("composer.errors.failedToSend"), - }; - }; - - const wirePayload = splitComposerAttachmentsForSubmit(input.attachments, { - format: input.attachmentSubmitFormat, - }); - let images: Array<{ data: string; mimeType: string }> | undefined; - try { - images = await input.encodeImages(wirePayload.images); - } catch (error) { - // Encoding is local; its failure is real and retrying would not help. - return rollBack(error); - } - - const enqueueInput = { - agentId: input.agentId, - itemId: optimistic.queued.id, - text: optimistic.queued.text, - intent: "queue" as const, - images: images ?? [], - attachments: wirePayload.attachments, - composerAttachments: toQueuedComposerAttachments(input.attachments), - }; - input.outbox?.add(enqueueInput); - try { - const snapshot = await input.client.enqueueAgentMessage(enqueueInput); - input.outbox?.remove(enqueueInput.itemId); - input.applySnapshot(snapshot); - return optimistic; - } catch (error) { - if (input.outbox) { - // The durable entry retries on reconnect; keep the row so the message - // still reads as queued on this device. - return optimistic; - } - return rollBack(error); - } -} - -export function removeQueuedComposerMessageLocally(input: { - agentId: string; - messageId: string; - queue: QueueWriter; -}): QueuedComposerMessage | null { - const item = input.queue.read(input.agentId).find((q) => q.id === input.messageId); - if (!item) return null; - input.queue.write((prev) => { - const next = new Map(prev); - next.set( - input.agentId, - (prev.get(input.agentId) ?? []).filter((q) => q.id !== input.messageId), - ); - return next; - }); - return item; -} - -export interface TakeQueuedComposerMessageInput { - client: ComposerQueueClient; - agentId: string; - messageId: string; - expectedRevision: number; - queue: QueueWriter; - persistImage: (input: { - dataUrl: string; - mimeType: string; - fileName: string | null; - }) => Promise; - applySnapshot: (snapshot: AgentQueueSnapshot) => void; -} - -export type TakeQueuedComposerMessageResult = - | { status: "missing" } - | { status: "taken"; text: string; attachments: UserComposerAttachment[] } - | { status: "conflict" } - | { status: "failed"; errorMessage: string }; - -/** - * Removes a queued message from the daemon and hands its content back for the - * composer. Images are fetched and re-persisted locally because only the device - * that queued them has the bytes. - */ -export async function takeQueuedComposerMessage( - input: TakeQueuedComposerMessageInput, -): Promise { - const item = input.queue.read(input.agentId).find((q) => q.id === input.messageId); - if (!item) return { status: "missing" }; - - try { - const images = await input.client.getQueuedAgentMessageImages(input.agentId, input.messageId); - const snapshot = await input.client.deleteQueuedAgentMessage( - input.agentId, - input.messageId, - input.expectedRevision, - ); - input.applySnapshot(snapshot); - const restoredImages = await Promise.all( - images.map(async (image) => ({ - kind: "image" as const, - metadata: await input.persistImage({ - dataUrl: `data:${image.mimeType};base64,${image.data}`, - mimeType: image.mimeType, - fileName: image.fileName ?? null, - }), - })), - ); - return { - status: "taken", - text: item.text, - attachments: [...userAttachmentsOnly(item.attachments), ...restoredImages], - }; - } catch (error) { - if (isQueueRevisionConflictError(error)) { - return { status: "conflict" }; - } - return { - status: "failed", - errorMessage: error instanceof Error ? error.message : i18n.t("composer.errors.failedToSend"), - }; - } -} - -/** A mutation the daemon rejected because another device changed the queue first. */ -export type QueuedMutationResult = - | { status: "applied" } - | { status: "conflict" } - | { status: "failed"; errorMessage: string }; - -/** - * The daemon answers mutation failures with a machine-readable code on the - * response `error` field (see `agentQueueErrorText` in the session dispatch); - * the client throws it as the error message. - */ -export function isQueueRevisionConflictError(error: unknown): boolean { - return error instanceof Error && error.message === "queue_revision_conflict"; -} - -function queuedMutationResult(error: unknown): QueuedMutationResult { - if (isQueueRevisionConflictError(error)) { - return { status: "conflict" }; - } - return { - status: "failed", - errorMessage: error instanceof Error ? error.message : i18n.t("composer.errors.failedToSend"), - }; -} - -export interface DeleteQueuedComposerMessageInput { - client: ComposerQueueClient; - agentId: string; - messageId: string; - expectedRevision: number; - applySnapshot: (snapshot: AgentQueueSnapshot) => void; -} - -/** - * Discards one durable item after an explicit user decision. The snapshot from - * the daemon is authoritative; the local map is never edited directly here. - */ -export async function deleteQueuedComposerMessage( - input: DeleteQueuedComposerMessageInput, -): Promise { - try { - input.applySnapshot( - await input.client.deleteQueuedAgentMessage( - input.agentId, - input.messageId, - input.expectedRevision, - ), - ); - return { status: "applied" }; - } catch (error) { - return queuedMutationResult(error); - } -} - -export interface ReorderQueuedComposerMessagesInput { - client: ComposerQueueClient; - agentId: string; - /** Full id list in the desired order, as the reorder wire contract expects. */ - itemIds: string[]; - expectedRevision: number; - applySnapshot: (snapshot: AgentQueueSnapshot) => void; -} - -export async function reorderQueuedComposerMessages( - input: ReorderQueuedComposerMessagesInput, -): Promise { - try { - input.applySnapshot( - await input.client.reorderQueuedAgentMessages( - input.agentId, - input.itemIds, - input.expectedRevision, - ), - ); - return { status: "applied" }; - } catch (error) { - return queuedMutationResult(error); - } -} - -export interface RetryQueuedComposerMessageInput { - client: ComposerQueueClient; - agentId: string; - messageId: string; - expectedRevision: number; - applySnapshot: (snapshot: AgentQueueSnapshot) => void; -} - -/** - * The only path that resends an item whose provider acceptance is unknown or - * whose attempts ran out. Never called automatically; the user pressed retry. - */ -export async function retryQueuedComposerMessage( - input: RetryQueuedComposerMessageInput, -): Promise { - try { - input.applySnapshot( - await input.client.retryQueuedAgentMessage( - input.agentId, - input.messageId, - input.expectedRevision, - ), - ); - return { status: "applied" }; - } catch (error) { - return queuedMutationResult(error); - } -} diff --git a/packages/app/src/composer/index.tsx b/packages/app/src/composer/index.tsx index b093b2c7fdc..4b31c4e0c6a 100644 --- a/packages/app/src/composer/index.tsx +++ b/packages/app/src/composer/index.tsx @@ -47,14 +47,8 @@ import { usePointerCapabilities } from "@/hooks/pointer-capabilities"; import { useShallow } from "zustand/shallow"; import { ArrowUp, - ChevronDown, - ChevronUp, - MoreVertical, - RotateCcw, Square, Pencil, - Trash2, - X, AudioLines, CircleDot, FileText, @@ -93,7 +87,6 @@ import { encodeImages } from "@/utils/encode-images"; import { focusWithRetries } from "@/utils/web-focus"; import { cancelComposerAgent, - deleteQueuedComposerMessage, dispatchComposerAgentMessage, editQueuedComposerMessage, findForgeItemByOption, @@ -101,32 +94,14 @@ import { openComposerAttachment, pickAndPersistImages, queueComposerMessage, - queueComposerMessageOnServer, removeComposerAttachmentAtIndex, - removeQueuedComposerMessageLocally, - reorderQueuedComposerMessages, - retryQueuedComposerMessage, sendQueuedComposerMessageNow, - takeQueuedComposerMessage, toggleForgeAttachmentFromPicker, uploadFileAttachments, type AttachmentPersister, - type QueueOutboxWriter, type QueueWriter, type QueuedComposerMessage, - type QueuedMutationResult, } from "@/composer/actions"; -import { toComposerAttachments } from "@/composer/queue-sync"; -import { retryFailedOutboxEntry, useQueueOutboxStore } from "@/stores/queue-outbox-store"; -import { StatusBadge } from "@/components/ui/status-badge"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuSeparator, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; -import { confirmDialog } from "@/utils/confirm-dialog"; import { useVoiceOptional } from "@/contexts/voice-context"; import { useToast } from "@/contexts/toast-context"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; @@ -414,47 +389,21 @@ function renderAttachmentTray(args: RenderAttachmentTrayArgs): ReactElement | nu ); } -interface QueuedRowActionLabels { - menu: string; - moveUp: string; - moveDown: string; - remove: string; - retry: string; - discard: string; -} - interface RenderQueueTrackArgs { queuedMessages: readonly QueuedMessage[]; handleEditQueuedMessage: (id: string) => void; handleSendQueuedNow: (id: string) => Promise; editLabel: string; sendNowLabel: string; - /** Durable-queue controls; absent on old hosts, whose rows stay exactly as before. */ - durable?: { - onDelete: (id: string) => void; - onMove: (id: string, direction: -1 | 1) => void; - onRetry: (id: string) => void; - onDiscard: (id: string) => void; - labels: QueuedRowActionLabels; - sendingLabel: string; - unconfirmedLabel: string; - failedLabel: string; - }; } function renderQueueTrack(args: RenderQueueTrackArgs): ReactElement | null { - const { - queuedMessages, - handleEditQueuedMessage, - handleSendQueuedNow, - editLabel, - sendNowLabel, - durable, - } = args; + const { queuedMessages, handleEditQueuedMessage, handleSendQueuedNow, editLabel, sendNowLabel } = + args; if (queuedMessages.length === 0) return null; return ( - {queuedMessages.map((item, index) => ( + {queuedMessages.map((item) => ( ))} @@ -739,28 +685,6 @@ interface QueuedMessageRowProps { onSendNow: (id: string) => void; editLabel: string; sendNowLabel: string; - isFirst: boolean; - isLast: boolean; - durable?: RenderQueueTrackArgs["durable"]; -} - -type QueuedRowState = "queued" | "sending" | "unconfirmed" | "failed"; - -function resolveQueueRowState(item: QueuedMessage): QueuedRowState { - if (item.syncState === "failed" || item.deliveryState === "failed") return "failed"; - if (item.deliveryState === "uncertain") return "unconfirmed"; - if (item.deliveryState === "dispatching") return "sending"; - return "queued"; -} - -function resolveQueueStateBadge( - state: QueuedRowState, - labels: { sendingLabel: string; unconfirmedLabel: string; failedLabel: string }, -): { variant: "muted" | "warning" | "error"; label: string } | null { - if (state === "failed") return { variant: "error", label: labels.failedLabel }; - if (state === "unconfirmed") return { variant: "warning", label: labels.unconfirmedLabel }; - if (state === "sending") return { variant: "muted", label: labels.sendingLabel }; - return null; } function QueuedMessageRow({ @@ -769,9 +693,6 @@ function QueuedMessageRow({ onSendNow, editLabel, sendNowLabel, - isFirst, - isLast, - durable, }: QueuedMessageRowProps) { const handleEdit = useCallback(() => { onEdit(item.id); @@ -779,137 +700,28 @@ function QueuedMessageRow({ const handleSendNow = useCallback(() => { onSendNow(item.id); }, [onSendNow, item.id]); - const state = resolveQueueRowState(item); - const needsAttention = state === "failed" || state === "unconfirmed"; - const handleDelete = useCallback(() => { - durable?.onDelete(item.id); - }, [durable, item.id]); - const handleMoveUp = useCallback(() => { - durable?.onMove(item.id, -1); - }, [durable, item.id]); - const handleMoveDown = useCallback(() => { - durable?.onMove(item.id, 1); - }, [durable, item.id]); - const handleRetry = useCallback(() => { - durable?.onRetry(item.id); - }, [durable, item.id]); - const handleDiscard = useCallback(() => { - durable?.onDiscard(item.id); - }, [durable, item.id]); - - const badge = durable ? resolveQueueStateBadge(state, durable) : null; - const menuIcons = useMemo( - () => ({ - moveUp: , - moveDown: , - remove: , - }), - [], - ); - - const stateBadge = badge ? ( - - ) : null; - return ( - - - {item.text} - - {stateBadge !== null || item.lastError ? ( - - {stateBadge} - {item.lastError && needsAttention ? ( - - {item.lastError} - - ) : null} - - ) : null} - + + {item.text} + - {durable && needsAttention ? ( - <> - - - - - - - - ) : ( - <> - {!item.deliveryState || item.deliveryState === "pending" ? ( - <> - - - - - - - - ) : null} - {durable ? ( - - - {({ hovered, open }) => ( - - )} - - - - {durable.labels.moveUp} - - - {durable.labels.moveDown} - - - - {durable.labels.remove} - - - - ) : null} - - )} + + + + + + ); @@ -1347,15 +1159,9 @@ function offersVoiceMode(input: { isVoiceModeForAgent: boolean; hasAgent: boolean; isAgentRunning: boolean; - supportsVoiceConcurrentInput: boolean; showVoice: boolean; }): boolean { - return ( - input.showVoice && - !input.isVoiceModeForAgent && - input.hasAgent && - (!input.isAgentRunning || input.supportsVoiceConcurrentInput) - ); + return input.showVoice && !input.isVoiceModeForAgent && input.hasAgent && !input.isAgentRunning; } function ComposerVoiceModeButton({ @@ -1561,23 +1367,6 @@ function ComposerContentImpl({ const supportsForgeSearch = useSessionStore( (state) => state.sessions[serverId]?.serverInfo?.features?.forgeSearch === true, ); - // COMPAT(durableAgentQueue): added in v0.11.0-beta.3+custom (TM-02). Older - // daemons have no durable queue, so this client keeps its local in-memory - // queue against those hosts with today's meaning: session-scoped, this - // device only, never resumable. - const supportsDurableQueue = useSessionStore( - (state) => state.sessions[serverId]?.serverInfo?.features?.durableAgentQueueV1 === true, - ); - const applyAgentQueueSnapshot = useSessionStore((state) => state.applyAgentQueueSnapshot); - const failedOutboxEntries = useQueueOutboxStore( - useShallow((state) => - state.entriesForAgent(serverId, agentId).filter((entry) => entry.failedAt !== undefined), - ), - ); - // COMPAT(durableVoiceInputV1): fork feature (TM-04), added on 2026-10-08; keep while stock peers are supported. - const supportsVoiceConcurrentInput = useSessionStore( - (state) => state.sessions[serverId]?.serverInfo?.features?.durableVoiceInputV1 === true, - ); const forgeAutoAttachRef = useRef>(null); const [isForgeResolving, setIsForgeResolving] = useState(false); const forgeConfiguration = useMemo( @@ -1955,87 +1744,8 @@ function ComposerContentImpl({ [serverId, setQueuedMessages], ); - const queueOutbox = useMemo( - () => ({ - add: (entry) => useQueueOutboxStore.getState().add({ ...entry, serverId }), - remove: (itemId) => useQueueOutboxStore.getState().remove(itemId), - }), - [serverId], - ); - - const refreshQueuedMessages = useCallback(async () => { - if (!supportsDurableQueue || !client) { - return; - } - try { - const snapshot = await client.listQueuedAgentMessages(agentId); - applyAgentQueueSnapshot(serverId, snapshot); - } catch { - // A queue we cannot read is not worth interrupting the composer for; the - // next broadcast refreshes it. - } - }, [agentId, applyAgentQueueSnapshot, client, serverId, supportsDurableQueue]); - - useEffect(() => { - void refreshQueuedMessages(); - }, [refreshQueuedMessages]); - - const getAppliedQueueRevision = useCallback( - () => useSessionStore.getState().sessions[serverId]?.queuedMessageRevisions.get(agentId) ?? 0, - [agentId, serverId], - ); - - const handleQueuedMutationResult = useCallback( - (result: QueuedMutationResult): boolean => { - if (result.status === "conflict") { - // A stale revision must read as a visible conflict, never as a silent - // overwrite of another device's edit. The refresh shows the queue as it - // now stands. - setSendError(t("composer.queued.changedOnAnotherDevice")); - void refreshQueuedMessages(); - return false; - } - if (result.status === "failed") { - setSendError(result.errorMessage); - return false; - } - return true; - }, - [refreshQueuedMessages, t], - ); - const queueMessage = useCallback( (queuedMessage: string, queuedAttachments: ComposerAttachment[]) => { - const clearComposer = () => { - setUserInput(""); - setSelectedAttachments([]); - resetSuppression(); - clearSentAttachments(queuedAttachments); - }; - - if (supportsDurableQueue && client) { - void (async () => { - const result = await queueComposerMessageOnServer({ - client, - agentId, - text: queuedMessage, - attachments: queuedAttachments, - attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({ - supportsForgeAttachments: supportsForgeSearch, - }), - encodeImages, - queue: queueWriter, - applySnapshot: (snapshot) => applyAgentQueueSnapshot(serverId, snapshot), - outbox: queueOutbox, - }); - if (result.error) { - setSendError(result.error); - } - })(); - clearComposer(); - return; - } - const result = queueComposerMessage({ agentId, text: queuedMessage, @@ -2044,21 +1754,18 @@ function ComposerContentImpl({ }); if (!result.queued) return; - clearComposer(); + replaceUserInput(""); + setSelectedAttachments([]); + resetSuppression(); + clearSentAttachments(queuedAttachments); }, [ agentId, - applyAgentQueueSnapshot, clearSentAttachments, - client, - queueOutbox, queueWriter, resetSuppression, - serverId, setSelectedAttachments, - setUserInput, - supportsDurableQueue, - supportsForgeSearch, + replaceUserInput, ], ); @@ -2343,33 +2050,6 @@ function ComposerContentImpl({ const handleEditQueuedMessage = useCallback( (id: string) => { - if (supportsDurableQueue && client) { - void (async () => { - const result = await takeQueuedComposerMessage({ - client, - agentId, - messageId: id, - expectedRevision: getAppliedQueueRevision(), - queue: queueWriter, - persistImage: persistAttachmentFromDataUrl, - applySnapshot: (snapshot) => applyAgentQueueSnapshot(serverId, snapshot), - }); - if (result.status === "failed") { - setSendError(result.errorMessage); - return; - } - if (result.status === "conflict") { - handleQueuedMutationResult({ status: "conflict" }); - return; - } - if (result.status === "taken") { - replaceUserInput(result.text); - setSelectedAttachments(result.attachments); - } - })(); - return; - } - const result = editQueuedComposerMessage({ agentId, messageId: id, @@ -2379,70 +2059,12 @@ function ComposerContentImpl({ replaceUserInput(result.text); setSelectedAttachments(result.attachments); }, - [ - agentId, - applyAgentQueueSnapshot, - client, - getAppliedQueueRevision, - handleQueuedMutationResult, - queueWriter, - replaceUserInput, - serverId, - setSelectedAttachments, - supportsDurableQueue, - ], + [agentId, queueWriter, replaceUserInput, setSelectedAttachments], ); const handleSendQueuedNow = useCallback( async (id: string) => { if (!sendAgentMessageRef.current && !onSubmitMessageRef.current) return; - - if (supportsDurableQueue && client) { - // Take the message off the daemon queue first. The daemon drains the same - // queue, so leaving it there while we send would risk sending it twice. - const taken = await takeQueuedComposerMessage({ - client, - agentId, - messageId: id, - expectedRevision: getAppliedQueueRevision(), - queue: queueWriter, - persistImage: persistAttachmentFromDataUrl, - applySnapshot: (snapshot) => applyAgentQueueSnapshot(serverId, snapshot), - }); - if (taken.status === "failed") { - setSendError(taken.errorMessage); - return; - } - if (taken.status === "conflict") { - handleQueuedMutationResult({ status: "conflict" }); - return; - } - if (taken.status === "missing") { - return; - } - try { - await submitMessage(taken.text, taken.attachments); - } catch (error) { - setSendError(error instanceof Error ? error.message : t("composer.errors.failedToSend")); - // Requeue so the message is not lost. It lands at the end rather than - // where it was, because the daemon queue has no insert-at-position. - await queueComposerMessageOnServer({ - client, - agentId, - text: taken.text, - attachments: taken.attachments, - attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({ - supportsForgeAttachments: supportsForgeSearch, - }), - encodeImages, - queue: queueWriter, - applySnapshot: (snapshot) => applyAgentQueueSnapshot(serverId, snapshot), - outbox: queueOutbox, - }); - } - return; - } - // Reuse the regular send path; server-side send atomically interrupts any active run. const result = await sendQueuedComposerMessageNow({ agentId, @@ -2456,152 +2078,7 @@ function ComposerContentImpl({ setSendError(result.errorMessage); } }, - [ - agentId, - applyAgentQueueSnapshot, - client, - getAppliedQueueRevision, - handleQueuedMutationResult, - queueOutbox, - queueWriter, - serverId, - submitMessage, - supportsDurableQueue, - supportsForgeSearch, - t, - ], - ); - - const handleDeleteQueuedMessage = useCallback( - (id: string) => { - if (!(supportsDurableQueue && client)) return; - void (async () => { - const confirmed = await confirmDialog({ - title: t("composer.queued.deleteTitle"), - message: t("composer.queued.deleteMessage"), - confirmLabel: t("composer.queued.delete"), - cancelLabel: t("common.actions.cancel"), - destructive: true, - }); - if (!confirmed) return; - handleQueuedMutationResult( - await deleteQueuedComposerMessage({ - client, - agentId, - messageId: id, - expectedRevision: getAppliedQueueRevision(), - applySnapshot: (snapshot) => applyAgentQueueSnapshot(serverId, snapshot), - }), - ); - })(); - }, - [ - agentId, - applyAgentQueueSnapshot, - client, - getAppliedQueueRevision, - handleQueuedMutationResult, - serverId, - supportsDurableQueue, - t, - ], - ); - - const handleMoveQueuedMessage = useCallback( - (id: string, direction: -1 | 1) => { - if (!(supportsDurableQueue && client)) return; - const rows = queueWriter.read(agentId); - const index = rows.findIndex((row) => row.id === id); - const target = index + direction; - if (index === -1 || target < 0 || target >= rows.length) return; - const itemIds = rows.map((row) => row.id); - itemIds.splice(target, 0, ...itemIds.splice(index, 1)); - void (async () => { - handleQueuedMutationResult( - await reorderQueuedComposerMessages({ - client, - agentId, - itemIds, - expectedRevision: getAppliedQueueRevision(), - applySnapshot: (snapshot) => applyAgentQueueSnapshot(serverId, snapshot), - }), - ); - })(); - }, - [ - agentId, - applyAgentQueueSnapshot, - client, - getAppliedQueueRevision, - handleQueuedMutationResult, - queueWriter, - serverId, - supportsDurableQueue, - ], - ); - - const handleRetryQueuedMessage = useCallback( - (id: string) => { - if (failedOutboxEntries.some((entry) => entry.itemId === id)) { - // The daemon never accepted this enqueue: retry re-sends the original - // payload rather than mutating a durable item. - if (!client) return; - void retryFailedOutboxEntry({ - itemId: id, - client, - applySnapshot: (snapshot) => applyAgentQueueSnapshot(serverId, snapshot), - }); - return; - } - if (!(supportsDurableQueue && client)) return; - void (async () => { - handleQueuedMutationResult( - await retryQueuedComposerMessage({ - client, - agentId, - messageId: id, - expectedRevision: getAppliedQueueRevision(), - applySnapshot: (snapshot) => applyAgentQueueSnapshot(serverId, snapshot), - }), - ); - })(); - }, - [ - agentId, - applyAgentQueueSnapshot, - client, - failedOutboxEntries, - getAppliedQueueRevision, - handleQueuedMutationResult, - serverId, - supportsDurableQueue, - ], - ); - - const handleDiscardQueuedMessage = useCallback( - (id: string) => { - if (failedOutboxEntries.some((entry) => entry.itemId === id)) { - void (async () => { - const confirmed = await confirmDialog({ - title: t("composer.queued.deleteTitle"), - message: t("composer.queued.deleteMessage"), - confirmLabel: t("composer.queued.discard"), - cancelLabel: t("common.actions.cancel"), - destructive: true, - }); - if (!confirmed) return; - useQueueOutboxStore.getState().remove(id); - removeQueuedComposerMessageLocally({ - agentId, - messageId: id, - queue: queueWriter, - }); - })(); - return; - } - handleDeleteQueuedMessage(id); - }, - [agentId, failedOutboxEntries, handleDeleteQueuedMessage, queueWriter, t], + [agentId, queueWriter, submitMessage, t], ); const handleQueue = useCallback( @@ -2690,7 +2167,6 @@ function ComposerContentImpl({ isVoiceModeForAgent, hasAgent, isAgentRunning, - supportsVoiceConcurrentInput, showVoice: mode.showVoice, }) ? ( @@ -2715,7 +2191,6 @@ function ComposerContentImpl({ isVoiceSwitching, mode.showVoice, realtimeVoiceButtonStyle, - supportsVoiceConcurrentInput, t, voiceToggleKeys, ], @@ -2998,71 +2473,17 @@ function ComposerContentImpl({ ], ); - // Failed outbox entries annotate their optimistic rows (and append rows this - // device lost, e.g. after a restart) so an enqueue that exhausted its retries - // stays visible with explicit retry/discard instead of dropping. - const queueRows = useMemo(() => { - if (!supportsDurableQueue || failedOutboxEntries.length === 0) { - return queuedMessages; - } - const failedIds = new Set(failedOutboxEntries.map((entry) => entry.itemId)); - const annotated = queuedMessages.map( - (row): QueuedMessage => - failedIds.has(row.id) && row.syncState !== "failed" ? { ...row, syncState: "failed" } : row, - ); - const present = new Set(annotated.map((row) => row.id)); - const missing = failedOutboxEntries - .filter((entry) => !present.has(entry.itemId)) - .map( - (entry): QueuedMessage => ({ - id: entry.itemId, - text: entry.text, - attachments: toComposerAttachments(entry.composerAttachments), - syncState: "failed", - }), - ); - return missing.length === 0 ? annotated : [...annotated, ...missing]; - }, [failedOutboxEntries, queuedMessages, supportsDurableQueue]); - - const queueList = useMemo(() => { - const durable = supportsDurableQueue - ? { - onDelete: handleDeleteQueuedMessage, - onMove: handleMoveQueuedMessage, - onRetry: handleRetryQueuedMessage, - onDiscard: handleDiscardQueuedMessage, - labels: { - menu: t("composer.queued.menu"), - moveUp: t("composer.queued.moveUp"), - moveDown: t("composer.queued.moveDown"), - remove: t("composer.queued.delete"), - retry: t("composer.queued.retry"), - discard: t("composer.queued.discard"), - }, - sendingLabel: t("composer.queued.sending"), - unconfirmedLabel: t("composer.queued.unconfirmed"), - failedLabel: t("composer.queued.failed"), - } - : undefined; - return renderQueueTrack({ - queuedMessages: queueRows, - handleEditQueuedMessage, - handleSendQueuedNow, - editLabel: t("composer.attachments.editQueuedMessage"), - sendNowLabel: t("composer.attachments.sendQueuedMessageNow"), - durable, - }); - }, [ - handleDeleteQueuedMessage, - handleDiscardQueuedMessage, - handleEditQueuedMessage, - handleMoveQueuedMessage, - handleRetryQueuedMessage, - handleSendQueuedNow, - queueRows, - supportsDurableQueue, - t, - ]); + const queueList = useMemo( + () => + renderQueueTrack({ + queuedMessages, + handleEditQueuedMessage, + handleSendQueuedNow, + editLabel: t("composer.attachments.editQueuedMessage"), + sendNowLabel: t("composer.attachments.sendQueuedMessageNow"), + }), + [handleEditQueuedMessage, handleSendQueuedNow, queuedMessages, t], + ); const autocompleteConfiguration = useMemo( () => ({ @@ -3196,9 +2617,6 @@ function ComposerContentImpl({ voiceServerId={serverId} voiceAgentId={agentId} isAgentRunning={isAgentRunning} - supportsVoiceConcurrentInput={supportsVoiceConcurrentInput} - isCancellingAgent={isCancellingAgent} - onCancelAgent={handleCancelAgent} defaultSendBehavior={activeSendBehavior} sendShortcut={appSettings.sendShortcut} onQueue={handleQueue} @@ -3383,21 +2801,6 @@ const styles = StyleSheet.create((theme: Theme) => ({ color: theme.colors.foreground, fontSize: theme.fontSize.base, }, - queueItemContent: { - flex: 1, - flexDirection: "column", - gap: theme.spacing[1], - }, - queueItemState: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - }, - queueErrorText: { - flexShrink: 1, - color: theme.colors.palette.red[300], - fontSize: theme.fontSize.sm, - }, queueActions: { flexDirection: "row", alignItems: "center", @@ -3423,12 +2826,6 @@ const styles = StyleSheet.create((theme: Theme) => ({ const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner); const ThemedPencil = withUnistyles(Pencil); const ThemedArrowUp = withUnistyles(ArrowUp); -const ThemedChevronUp = withUnistyles(ChevronUp); -const ThemedChevronDown = withUnistyles(ChevronDown); -const ThemedMoreVertical = withUnistyles(MoreVertical); -const ThemedRotateCcw = withUnistyles(RotateCcw); -const ThemedX = withUnistyles(X); -const ThemedTrash2 = withUnistyles(Trash2); const ThemedGitPullRequest = withUnistyles(GitPullRequest); const ThemedCircleDot = withUnistyles(CircleDot); const ThemedAudioLines = withUnistyles(AudioLines); diff --git a/packages/app/src/composer/input/input.tsx b/packages/app/src/composer/input/input.tsx index 7b53775e7f7..a3ae8652ae8 100644 --- a/packages/app/src/composer/input/input.tsx +++ b/packages/app/src/composer/input/input.tsx @@ -193,12 +193,6 @@ export interface MessageInputProps { voiceAgentId?: string; /** When true and there's sendable content, calls onQueue instead of onSubmit */ isAgentRunning?: boolean; - /** Daemon supports voice attached while the agent works; voice may start mid-turn. */ - supportsVoiceConcurrentInput?: boolean; - /** True while the agent cancellation issued from the voice overlay is in flight. */ - isCancellingAgent?: boolean; - /** Explicit interrupt for the running agent, surfaced separately from Stop voice. */ - onCancelAgent?: () => void; /** Controls what the default send action (Enter, send button, dictation) does when the agent is * running. "interrupt" and "steer" send immediately, "queue" queues. Required so the default * lives only in DEFAULT_CLIENT_SETTINGS. */ @@ -629,9 +623,6 @@ function MessageInputOverlay({ onRetryFailedRecording, onDiscardFailedRecording, onRealtimeVoiceStop, - isAgentRunning, - isCancellingAgent, - onCancelAgent, }: { showDictationOverlay: boolean; showRealtimeOverlay: boolean; @@ -639,8 +630,6 @@ function MessageInputOverlay({ | { isMuted: boolean; isVoiceSwitching: boolean; - failure: import("@/voice/voice-failure").VoiceFailureKind | null; - lastInputStatus: import("@/voice/voice-runtime").VoiceInputStatus | null; toggleMute: () => void; } | null @@ -657,9 +646,6 @@ function MessageInputOverlay({ onRetryFailedRecording: () => void; onDiscardFailedRecording: () => void; onRealtimeVoiceStop: () => void; - isAgentRunning?: boolean; - isCancellingAgent?: boolean; - onCancelAgent?: () => void; }) { if (showDictationOverlay) { return ( @@ -683,13 +669,8 @@ function MessageInputOverlay({ ); } @@ -972,7 +953,6 @@ interface ToggleRealtimeVoiceContext { isConnected: boolean; disabled: boolean; isAgentRunning: boolean; - supportsVoiceConcurrentInput: boolean; handleStopRealtimeVoice: () => Promise | void; toast: { error: (msg: string) => void }; interruptBeforeVoiceMessage: string; @@ -988,7 +968,7 @@ function toggleRealtimeVoiceImpl(ctx: ToggleRealtimeVoiceContext): void { void ctx.handleStopRealtimeVoice(); return; } - if (ctx.isAgentRunning && !ctx.supportsVoiceConcurrentInput) { + if (ctx.isAgentRunning) { ctx.toast.error(ctx.interruptBeforeVoiceMessage); return; } @@ -1212,9 +1192,6 @@ interface ResolvedMessageInputProps { voiceServerId: string | undefined; voiceAgentId: string | undefined; isAgentRunning: boolean; - supportsVoiceConcurrentInput: boolean; - isCancellingAgent: boolean | undefined; - onCancelAgent: (() => void) | undefined; defaultSendBehavior: "interrupt" | "steer" | "queue"; sendShortcut: SendShortcut; onQueue: ((payload: MessagePayload) => void) | undefined; @@ -1263,9 +1240,6 @@ function resolveMessageInputProps(props: MessageInputProps): ResolvedMessageInpu voiceServerId: props.voiceServerId, voiceAgentId: props.voiceAgentId, isAgentRunning: props.isAgentRunning ?? false, - supportsVoiceConcurrentInput: props.supportsVoiceConcurrentInput ?? false, - isCancellingAgent: props.isCancellingAgent, - onCancelAgent: props.onCancelAgent, defaultSendBehavior: props.defaultSendBehavior, sendShortcut: props.sendShortcut, onQueue: props.onQueue, @@ -1348,9 +1322,6 @@ export const MessageInput = forwardRef( voiceServerId, voiceAgentId, isAgentRunning, - supportsVoiceConcurrentInput, - isCancellingAgent, - onCancelAgent, defaultSendBehavior, sendShortcut, onQueue, @@ -1739,6 +1710,9 @@ export const MessageInput = forwardRef( await stopRealtimeVoice({ voice, isRealtimeVoiceForCurrentAgent, + isAgentRunning, + client, + voiceAgentId, }); } catch (error) { console.error("[MessageInput] Failed to stop realtime voice", error); @@ -1747,7 +1721,7 @@ export const MessageInput = forwardRef( toast.error(message); } } - }, [isRealtimeVoiceForCurrentAgent, toast, voice]); + }, [client, isAgentRunning, isRealtimeVoiceForCurrentAgent, toast, voice, voiceAgentId]); const handleToggleRealtimeVoiceShortcut = useCallback(() => { toggleRealtimeVoiceImpl({ @@ -1757,7 +1731,6 @@ export const MessageInput = forwardRef( isConnected, disabled, isAgentRunning, - supportsVoiceConcurrentInput, handleStopRealtimeVoice, toast, interruptBeforeVoiceMessage: t("composer.voice.interruptBeforeVoice"), @@ -1769,7 +1742,6 @@ export const MessageInput = forwardRef( exitFullscreen, isAgentRunning, isConnected, - supportsVoiceConcurrentInput, t, toast, voice, @@ -2325,9 +2297,6 @@ export const MessageInput = forwardRef( onRetryFailedRecording={handleRetryFailedRecording} onDiscardFailedRecording={handleDiscardFailedRecording} onRealtimeVoiceStop={handleRealtimeVoiceStop} - isAgentRunning={isAgentRunning} - isCancellingAgent={isCancellingAgent} - onCancelAgent={onCancelAgent} /> ), @@ -2349,9 +2318,6 @@ export const MessageInput = forwardRef( handleRetryFailedRecording, handleDiscardFailedRecording, handleRealtimeVoiceStop, - isAgentRunning, - isCancellingAgent, - onCancelAgent, ], ); return ( diff --git a/packages/app/src/composer/input/state.test.ts b/packages/app/src/composer/input/state.test.ts index 6cf1e13bde3..ad492976b30 100644 --- a/packages/app/src/composer/input/state.test.ts +++ b/packages/app/src/composer/input/state.test.ts @@ -529,17 +529,44 @@ describe("resolveMessageInputEnterAction", () => { }); describe("stopRealtimeVoice", () => { - it("stops voice mode without cancelling the running agent", async () => { - const cancelAgent = vi.fn().mockResolvedValue(undefined); + it("keeps voice mode active when the running agent refuses cancellation", async () => { + const cancellationError = new Error("active run cancellation was not acknowledged"); + const cancelAgent = vi.fn().mockRejectedValue(cancellationError); const stopVoice = vi.fn().mockResolvedValue(undefined); + await expect( + stopRealtimeVoice({ + voice: { stopVoice }, + isRealtimeVoiceForCurrentAgent: true, + isAgentRunning: true, + client: { cancelAgent }, + voiceAgentId: "agent-1", + }), + ).rejects.toBe(cancellationError); + + expect(stopVoice).not.toHaveBeenCalled(); + }); + + it("stops voice mode after the running agent acknowledges cancellation", async () => { + const calls: string[] = []; + await stopRealtimeVoice({ - voice: { stopVoice }, + voice: { + stopVoice: async () => { + calls.push("stop voice"); + }, + }, isRealtimeVoiceForCurrentAgent: true, + isAgentRunning: true, + client: { + cancelAgent: async () => { + calls.push("cancel agent"); + }, + }, + voiceAgentId: "agent-1", }); - expect(stopVoice).toHaveBeenCalled(); - expect(cancelAgent).not.toHaveBeenCalled(); + expect(calls).toEqual(["cancel agent", "stop voice"]); }); }); diff --git a/packages/app/src/composer/input/state.ts b/packages/app/src/composer/input/state.ts index 2e9b368961b..67c80307451 100644 --- a/packages/app/src/composer/input/state.ts +++ b/packages/app/src/composer/input/state.ts @@ -42,6 +42,9 @@ export function resolveComposerSurfacePresentation( interface StopRealtimeVoiceContext { voice: { stopVoice: () => Promise } | null | undefined; isRealtimeVoiceForCurrentAgent: boolean; + isAgentRunning: boolean; + client: { cancelAgent: (agentId: string) => Promise } | null; + voiceAgentId: string | undefined; } interface SendActionContext { @@ -220,9 +223,13 @@ export function runMessageInputKeyboardAction( export async function stopRealtimeVoice(ctx: StopRealtimeVoiceContext): Promise { if (!ctx.voice || !ctx.isRealtimeVoiceForCurrentAgent) return; - // Stop voice detaches the microphone and playback only. The agent, its pending - // permissions, and its children keep running; interruption is the overlay's - // explicit Interrupt agent control. + if (ctx.isAgentRunning) { + if (!ctx.client || !ctx.voiceAgentId) { + throw new Error("Cannot stop the running voice agent while the host is unavailable"); + } + await ctx.client.cancelAgent(ctx.voiceAgentId); + } + await ctx.voice.stopVoice(); } diff --git a/packages/app/src/composer/queue-sync.test.ts b/packages/app/src/composer/queue-sync.test.ts deleted file mode 100644 index 0962a02ee1f..00000000000 --- a/packages/app/src/composer/queue-sync.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { describe, expect, it } from "vitest"; -import type { AgentQueueSnapshot, ForgeSearchItem } from "@getpaseo/protocol/messages"; - -import type { AttachmentMetadata } from "@/attachments/types"; -import type { PendingQueueEnqueue } from "@/stores/queue-outbox-store/model"; -import { - appendPendingQueueRows, - shouldApplyAgentQueueSnapshot, - toQueuedComposerAttachments, - toQueuedComposerMessages, -} from "./queue-sync"; - -const issueItem: ForgeSearchItem = { - kind: "issue", - number: 7, - title: "Mirror the queue", - url: "https://example.test/issues/7", - state: "open", - body: null, - labels: [], - baseRefName: null, - headRefName: null, -}; - -const imageMetadata: AttachmentMetadata = { - id: "img-1", - mimeType: "image/png", - storageType: "web-indexeddb", - storageKey: "img-1", - createdAt: 1, -}; - -function snapshot(overrides: Partial = {}): AgentQueueSnapshot { - return { - agentId: "agent", - revision: 1, - items: [ - { - id: "item-1", - text: "first", - intent: "queue", - deliveryState: "pending", - attempts: 0, - createdAt: "2026-01-01T00:00:00.000Z", - }, - ], - ...overrides, - }; -} - -describe("shouldApplyAgentQueueSnapshot", () => { - it("applies the first snapshot it sees", () => { - expect(shouldApplyAgentQueueSnapshot({ incomingRevision: 4, appliedRevision: undefined })).toBe( - true, - ); - }); - - it("applies a newer revision", () => { - expect(shouldApplyAgentQueueSnapshot({ incomingRevision: 5, appliedRevision: 4 })).toBe(true); - }); - - it("drops a snapshot that raced behind one already applied", () => { - expect(shouldApplyAgentQueueSnapshot({ incomingRevision: 3, appliedRevision: 4 })).toBe(false); - }); - - it("drops a repeat of the revision already applied", () => { - expect(shouldApplyAgentQueueSnapshot({ incomingRevision: 4, appliedRevision: 4 })).toBe(false); - }); -}); - -describe("toQueuedComposerMessages", () => { - it("keeps the composer-side attachments so any device can edit the message", () => { - const items = toQueuedComposerMessages( - snapshot({ - items: [ - { - id: "item-1", - text: "look at this", - intent: "queue", - deliveryState: "pending", - attempts: 0, - createdAt: "2026-01-01T00:00:00.000Z", - composerAttachments: [{ kind: "forge_issue", item: issueItem }], - images: [{ id: "srv-1", mimeType: "image/png", byteSize: 3 }], - }, - ], - }), - ); - - expect(items).toEqual([ - { - id: "item-1", - text: "look at this", - attachments: [{ kind: "forge_issue", item: issueItem }], - deliveryState: "pending", - lastError: undefined, - }, - ]); - }); - - it("carries the delivery state and last error so the queue track can show them", () => { - const items = toQueuedComposerMessages( - snapshot({ - items: [ - { - id: "item-1", - text: "first", - intent: "queue", - deliveryState: "uncertain", - attempts: 3, - lastError: "agent_request_outcome_unknown", - createdAt: "2026-01-01T00:00:00.000Z", - }, - ], - }), - ); - - expect(items).toEqual([ - { - id: "item-1", - text: "first", - attachments: [], - deliveryState: "uncertain", - lastError: "agent_request_outcome_unknown", - }, - ]); - }); - - it("returns an empty attachment list when the item has none", () => { - expect(toQueuedComposerMessages(snapshot())).toEqual([ - { - id: "item-1", - text: "first", - attachments: [], - deliveryState: "pending", - lastError: undefined, - }, - ]); - }); -}); - -describe("appendPendingQueueRows", () => { - function pending(overrides: Partial = {}): PendingQueueEnqueue { - return { - serverId: "server", - agentId: "agent", - itemId: "pending-1", - text: "not acked yet", - intent: "queue", - images: [], - attachments: [], - composerAttachments: [], - createdAt: 1, - attempts: 0, - ...overrides, - }; - } - - it("re-appends un-acked rows a snapshot would otherwise erase", () => { - const rows = appendPendingQueueRows(toQueuedComposerMessages(snapshot()), [pending()]); - expect(rows.map((row) => row.id)).toEqual(["item-1", "pending-1"]); - expect(rows[1]?.syncState).toBe("pending"); - }); - - it("marks a re-appended row failed when its entry exhausted the retries", () => { - const rows = appendPendingQueueRows(toQueuedComposerMessages(snapshot()), [ - pending({ itemId: "pending-2", failedAt: 5 }), - ]); - expect(rows.map((row) => row.id)).toEqual(["item-1", "pending-2"]); - expect(rows[1]?.syncState).toBe("failed"); - }); - - it("drops a pending row the snapshot already contains", () => { - const rows = appendPendingQueueRows(toQueuedComposerMessages(snapshot()), [ - pending({ itemId: "item-1" }), - ]); - expect(rows.map((row) => row.id)).toEqual(["item-1"]); - expect(rows[0]?.syncState).toBeUndefined(); - }); - - it("returns the input list unchanged when nothing is pending", () => { - const rows = toQueuedComposerMessages(snapshot()); - expect(appendPendingQueueRows(rows, [])).toBe(rows); - }); -}); - -describe("toQueuedComposerAttachments", () => { - it("drops images, which travel as bytes instead", () => { - expect( - toQueuedComposerAttachments([ - { kind: "image", metadata: imageMetadata }, - { kind: "forge_issue", item: issueItem }, - ]), - ).toEqual([{ kind: "forge_issue", item: issueItem }]); - }); - - it("keeps workspace file references, which resolve the same on any device", () => { - expect( - toQueuedComposerAttachments([ - { kind: "workspace_file", path: "src/main.ts", selection: { kind: "whole_file" } }, - ]), - ).toEqual([{ kind: "workspace_file", path: "src/main.ts", selection: { kind: "whole_file" } }]); - }); -}); diff --git a/packages/app/src/composer/queue-sync.ts b/packages/app/src/composer/queue-sync.ts deleted file mode 100644 index 75608bc2523..00000000000 --- a/packages/app/src/composer/queue-sync.ts +++ /dev/null @@ -1,101 +0,0 @@ -import type { - AgentQueueSnapshot, - QueuedAgentMessage, - QueuedComposerAttachment, -} from "@getpaseo/protocol/messages"; - -import type { ComposerAttachment, UserComposerAttachment } from "@/attachments/types"; -import { userAttachmentsOnly } from "@/attachments/workspace-attachment-utils"; -import type { QueuedComposerMessage } from "@/composer/actions"; -import type { PendingQueueEnqueue } from "@/stores/queue-outbox-store/model"; - -/** - * Reconciliation between the daemon-owned queue and the local optimistic copy. - * See docs/queue-mirroring.md — the server is authoritative and snapshots replace - * the local list wholesale. - */ - -/** - * Composer attachments a queued message can carry across devices. Images are - * absent: their bytes live on the daemon and are fetched on demand. - */ -export function toComposerAttachments( - attachments: readonly QueuedComposerAttachment[] | undefined, -): UserComposerAttachment[] { - return [...(attachments ?? [])]; -} - -/** The inverse, for the enqueue payload. Image attachments are sent as bytes instead. */ -export function toQueuedComposerAttachments( - attachments: readonly ComposerAttachment[], -): QueuedComposerAttachment[] { - const result: QueuedComposerAttachment[] = []; - for (const attachment of userAttachmentsOnly(attachments)) { - if (attachment.kind === "image") { - continue; - } - // Plugin resources are not part of the daemon queue wire schema; their bytes - // live in the plugin, so they are dropped from the queued payload. - if (attachment.kind === "plugin_resource") { - continue; - } - result.push(attachment); - } - return result; -} - -export function toQueuedComposerMessage(item: QueuedAgentMessage): QueuedComposerMessage { - return { - id: item.id, - text: item.text, - attachments: toComposerAttachments(item.composerAttachments), - deliveryState: item.deliveryState, - lastError: item.lastError, - }; -} - -export function toQueuedComposerMessages(snapshot: AgentQueueSnapshot): QueuedComposerMessage[] { - return snapshot.items.map(toQueuedComposerMessage); -} - -export function queuedMessageHasImages(item: QueuedAgentMessage): boolean { - return (item.images?.length ?? 0) > 0; -} - -/** - * Decides whether a snapshot should replace what the client is showing. Local - * optimistic writes never bump the revision, so a snapshot that is newer than the - * last one applied always wins, and an older one that raced past a local write is - * dropped rather than briefly erasing it. - */ -export function shouldApplyAgentQueueSnapshot(input: { - incomingRevision: number; - appliedRevision: number | undefined; -}): boolean { - return input.appliedRevision === undefined || input.incomingRevision > input.appliedRevision; -} - -/** - * The one exception to snapshots-replace-wholesale: an un-acked enqueue is a - * write the server does not know about yet, so a snapshot cannot be allowed to - * erase its row. Entries the snapshot already contains are dropped — the ack - * raced the broadcast — and the rest are re-appended in enqueue order, marked - * with their outbox state so the queue track can show a failed entry (one that - * exhausted its retries without a daemon acknowledgement) instead of dropping - * it. - */ -export function appendPendingQueueRows( - items: QueuedComposerMessage[], - pending: readonly PendingQueueEnqueue[], -): QueuedComposerMessage[] { - const present = new Set(items.map((item) => item.id)); - const rows = pending - .filter((entry) => !present.has(entry.itemId)) - .map((entry) => ({ - id: entry.itemId, - text: entry.text, - attachments: toComposerAttachments(entry.composerAttachments), - syncState: entry.failedAt === undefined ? ("pending" as const) : ("failed" as const), - })); - return rows.length === 0 ? items : [...items, ...rows]; -} diff --git a/packages/app/src/contexts/session-context.tsx b/packages/app/src/contexts/session-context.tsx index 8932cf8abc3..183b4ef479d 100644 --- a/packages/app/src/contexts/session-context.tsx +++ b/packages/app/src/contexts/session-context.tsx @@ -17,7 +17,6 @@ import { requestTimelineReplacement } from "@/timeline/timeline-replacement"; import { type ViewedTimelineOwner } from "@/timeline/viewed-timeline-sync"; import type { SessionOutboundMessage } from "@getpaseo/protocol/messages"; import { parseServerInfoStatusPayload } from "@getpaseo/protocol/messages"; -import { flushQueueOutboxForServer } from "@/stores/queue-outbox-store"; import { buildAgentAttentionNotificationPayload, type AgentAttentionReason, @@ -313,33 +312,29 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider useEffect(() => { const unregister = voiceRuntime?.registerSession({ serverId, - setVoiceMode: async (enabled, agentId, input) => { + setVoiceMode: async (enabled, agentId) => { if (!client) { throw new Error(t("common.errors.daemonUnavailable")); } - return client.setVoiceMode(enabled, agentId, input); + await client.setVoiceMode(enabled, agentId); }, - sendVoiceAudioChunk: async (audioData, mimeType, transport) => { + sendVoiceAudioChunk: async (audioData, mimeType) => { if (!client) { throw new Error(t("common.errors.daemonUnavailable")); } - await client.sendVoiceAudioChunk(audioData, mimeType, false, transport); + await client.sendVoiceAudioChunk(audioData, mimeType); }, - audioPlayed: async (chunkId, error, transport) => { + audioPlayed: async (chunkId) => { if (!client) { throw new Error(t("common.errors.daemonUnavailable")); } - await client.audioPlayed(chunkId, error, transport); + await client.audioPlayed(chunkId); }, - readVoiceInputReceipts: async (input) => { - if (!client) throw new Error(t("common.errors.daemonUnavailable")); - return client.readVoiceInputReceipts(input); - }, - abortRequest: async (transport) => { + abortRequest: async () => { if (!client) { throw new Error(t("common.errors.daemonUnavailable")); } - await client.abortRequest(transport); + await client.abortRequest(); }, setAssistantAudioPlaying: (isPlaying) => { setIsPlayingAudio(serverId, isPlaying); @@ -352,44 +347,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider voiceRuntime?.updateSessionConnection(serverId, isConnected); }, [isConnected, serverId, voiceRuntime]); - useEffect(() => { - if (!voiceRuntime) return; - const runtime = voiceRuntime; - let release = () => {}; - let observing = false; - function synchronizeVoiceQueueObservation() { - const snapshot = runtime.getSnapshot(); - const active = - snapshot.isVoiceMode && - snapshot.activeServerId === serverId && - useSessionStore.getState().sessions[serverId]?.serverInfo?.features?.durableVoiceInputV1 === - true; - if (active === observing) return; - observing = active; - release(); - if (!active) return; - const observation = client.observeEvents(["agent.queue.update"]); - const unsubscribe = observation.subscribe({ - snapshot: () => {}, - update: (message) => { - if (message.type === "agent.queue.update") { - runtime.onQueueChanged(serverId, message.payload.agentId); - } - }, - }); - release = () => { - unsubscribe(); - void observation.release(); - }; - } - synchronizeVoiceQueueObservation(); - const unsubscribe = voiceRuntime.subscribe(synchronizeVoiceQueueObservation); - return () => { - unsubscribe(); - release(); - }; - }, [client, serverId, voiceRuntime]); - // If the client drops mid-initialization, clear pending flags useEffect(() => { if (!isConnected) { @@ -522,9 +479,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider // features.sideConversationEvents, so a shared list stays honest across versions. "agent.side_conversation.update", "agent.side_conversation.removed", - // The client drops this one against a host that does not advertise - // features.durableAgentQueueV1, for the same reason. - "agent.queue.update", "checkout_status_update", "status.server_info", ], @@ -559,11 +513,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider }, }); - const unsubAgentQueueUpdate = client.on("agent.queue.update", (message) => { - if (message.type !== "agent.queue.update") return; - useSessionStore.getState().applyAgentQueueSnapshot(serverId, message.payload); - }); - const unsubSideConversationUpdate = client.on("agent.side_conversation.update", (message) => { if (message.type !== "agent.side_conversation.update") return; useSideConversationStore.getState().applySnapshot(serverId, message.payload); @@ -587,20 +536,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider const serverInfo = parseServerInfoStatusPayload(message.payload); if (serverInfo) { updateSessionServerInfo(serverId, toDaemonServerInfo(serverInfo)); - // COMPAT(durableAgentQueue): added in v0.11.0-beta.3+custom (TM-02/TM-03). - // Server info arrives on every (re)connect, which is exactly when an - // enqueue the daemon never acknowledged should be retried. Hosts without - // the flag keep the local queue path and their outbox entries wait; the - // local queue is in-memory and session-scoped, so nothing durable is - // implied about it either way. - if (serverInfo.features?.durableAgentQueueV1 === true) { - void flushQueueOutboxForServer({ - serverId, - client, - applySnapshot: (snapshot) => - useSessionStore.getState().applyAgentQueueSnapshot(serverId, snapshot), - }); - } return; } }); @@ -718,18 +653,11 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider if (message.type !== "transcription_result") return; const transcriptText = message.payload.text.trim(); - voiceRuntime?.onTranscriptionResult(serverId, transcriptText, message.payload); + voiceRuntime?.onTranscriptionResult(serverId, transcriptText); }); const unsubVoiceInputState = client.on("voice_input_state", (message) => { if (message.type !== "voice_input_state") return; - if (voiceRuntime && !voiceRuntime.acceptsVoiceTransport(serverId, message.payload)) return; - if (message.payload.error) { - voiceRuntime?.onInputError(serverId, message.payload.error); - } - if (message.payload.recognitionIssue) { - voiceRuntime?.onRecognitionIssue(serverId, message.payload.recognitionIssue); - } voiceRuntime?.onServerSpeechStateChanged(serverId, message.payload.isSpeaking); }); @@ -759,7 +687,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider .release() .catch((error) => console.warn("[Session] Failed to release feeds", error)); unsubProviderSubagentUpdate(); - unsubAgentQueueUpdate(); unsubSideConversationUpdate(); unsubSideConversationRemoved(); unsubAgentAttention(); diff --git a/packages/app/src/contexts/session-queue-resume.test.tsx b/packages/app/src/contexts/session-queue-resume.test.tsx deleted file mode 100644 index 248b260d0cf..00000000000 --- a/packages/app/src/contexts/session-queue-resume.test.tsx +++ /dev/null @@ -1,248 +0,0 @@ -/** - * @vitest-environment jsdom - * - * Exercises the registered status handler, not the flush function directly: the provider's - * server-info feed is what decides whether a reconnect resumes the durable queue outbox, so the - * cases drive that handler through absent, capable and downgraded hosts. - */ -import React from "react"; -import { act } from "@testing-library/react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { QueueOutboxFlushClient } from "@/stores/queue-outbox-store/model"; - -const harness = vi.hoisted(() => ({ - feedHandlers: new Map void>(), - enqueueAgentMessage: vi.fn(async () => ({ - agentId: "agent-1", - revision: 1, - items: [], - })), -})); - -vi.mock("react-i18next", () => ({ - useTranslation: () => ({ t: (key: string) => key }), - initReactI18next: { type: "3rdParty", init: () => undefined }, -})); -vi.mock("@tanstack/react-query", async (importOriginal) => ({ - ...(await importOriginal()), - useQueryClient: () => ({}), -})); -vi.mock("@/contexts/voice-context", () => ({ - useVoiceRuntimeOptional: () => null, - useVoiceAudioEngineOptional: () => null, -})); -vi.mock("@/contexts/toast-context", () => ({ - useToast: () => ({ error: vi.fn(), show: vi.fn(), copied: vi.fn() }), -})); -vi.mock("@/runtime/host-runtime", () => ({ - useHostRuntimeIsConnected: () => true, - getHostRuntimeStore: () => ({ - prepareWorkspaceRoute: vi.fn(async () => undefined), - prepareAgentTimeline: vi.fn(async () => undefined), - runProbeCycleNow: vi.fn(), - fetchAgentTimeline: vi.fn(async () => undefined), - acquireScriptStatusDemand: vi.fn(() => () => {}), - createViewedTimelineOwner: () => ({ - replaceVisibleAgentIds: vi.fn(), - replaceOpenTabAgentIds: vi.fn(), - enqueueStreamEvent: vi.fn(), - setConnected: vi.fn(), - setActive: vi.fn(), - dispose: vi.fn(), - }), - }), -})); -vi.mock("@/hooks/use-client-activity", () => ({ useClientActivity: () => undefined })); -vi.mock("@/hooks/use-app-visible", () => ({ useAppVisible: () => true })); -vi.mock("@/push-notifications", () => ({ startPushNotifications: () => () => {} })); -vi.mock("@/utils/os-notifications", () => ({ sendOsNotification: vi.fn() })); -vi.mock("@/utils/app-visibility", () => ({ - getIsAppActivelyVisible: () => true, - getIsAppVisible: () => true, -})); - -import { SessionProvider } from "./session-context"; -import { useQueueOutboxStore } from "@/stores/queue-outbox-store"; -import * as queueOutbox from "@/stores/queue-outbox-store"; - -function createFakeClient() { - const feedHandlers = harness.feedHandlers; - feedHandlers.clear(); - return { - observeEvents: () => ({ - subscribe: (observer: { snapshot: () => void; update: (message: unknown) => void }) => { - const key = `feed-${feedHandlers.size}`; - feedHandlers.set(key, observer.update); - observer.snapshot(); - return () => feedHandlers.delete(key); - }, - dispose: () => undefined, - release: async () => undefined, - }), - on: (type: string, handler: (message: unknown) => void) => { - feedHandlers.set(`on-${type}`, handler); - return () => feedHandlers.delete(`on-${type}`); - }, - observeTimeline: () => ({ - subscribe: () => () => undefined, - release: async () => undefined, - }), - enqueueAgentMessage: harness.enqueueAgentMessage, - }; -} - -/** Delivers a server-info status through whichever registered feed handles it. */ -function deliverServerInfo(features: Record): void { - const message = { - type: "status", - payload: { - status: "server_info", - serverId: "server-1", - hostname: null, - version: null, - features, - }, - }; - for (const handler of harness.feedHandlers.values()) { - handler(message); - } -} - -describe("session queue resume", () => { - let root: Root | null = null; - let container: HTMLElement | null = null; - - beforeEach(() => { - // The app's JSX compiles to the classic runtime here, and the provider does not import React. - vi.stubGlobal("React", React); - harness.enqueueAgentMessage.mockClear(); - useQueueOutboxStore.setState({ entries: {} }); - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => { - root?.render( - - {null} - , - ); - }); - }); - - afterEach(() => { - act(() => { - root?.unmount(); - }); - root = null; - container?.remove(); - container = null; - vi.unstubAllGlobals(); - vi.restoreAllMocks(); - }); - - it("holds a pending outbox entry when the host lacks the durable queue", async () => { - useQueueOutboxStore.getState().add({ - images: [], - attachments: [], - composerAttachments: [], - serverId: "server-1", - agentId: "agent-1", - itemId: "item-1", - text: "queued while offline", - intent: "queue", - }); - - await act(async () => { - deliverServerInfo({ ownedSubscriptions: true }); - }); - - expect(harness.enqueueAgentMessage).not.toHaveBeenCalled(); - expect(useQueueOutboxStore.getState().entriesForServer("server-1")).toHaveLength(1); - }); - - it("resumes the pending outbox once the host advertises the durable queue", async () => { - useQueueOutboxStore.getState().add({ - images: [], - attachments: [], - composerAttachments: [], - serverId: "server-1", - agentId: "agent-1", - itemId: "item-1", - text: "queued while offline", - intent: "queue", - }); - - await act(async () => { - deliverServerInfo({ ownedSubscriptions: true, durableAgentQueueV1: true }); - }); - - expect(harness.enqueueAgentMessage).toHaveBeenCalledTimes(1); - expect(harness.enqueueAgentMessage.mock.calls[0]?.[0]).toMatchObject({ - agentId: "agent-1", - itemId: "item-1", - text: "queued while offline", - intent: "queue", - }); - }); - - it("stops resuming after a downgrade back to a host without the flag", async () => { - const flush = vi.spyOn(queueOutbox, "flushQueueOutboxForServer"); - useQueueOutboxStore.getState().add({ - images: [], - attachments: [], - composerAttachments: [], - serverId: "server-1", - agentId: "agent-1", - itemId: "item-1", - text: "queued while offline", - intent: "queue", - }); - - await act(async () => { - deliverServerInfo({ ownedSubscriptions: true, durableAgentQueueV1: true }); - }); - expect(harness.enqueueAgentMessage).toHaveBeenCalledTimes(1); - - // Await the real flush through its finally block before testing the capability gate. - expect(flush).toHaveBeenCalledTimes(1); - await flush.mock.results[0]!.value; - expect(useQueueOutboxStore.getState().entriesForServer("server-1")).toEqual([]); - - harness.enqueueAgentMessage.mockClear(); - useQueueOutboxStore.getState().add({ - images: [], - attachments: [], - composerAttachments: [], - serverId: "server-1", - agentId: "agent-1", - itemId: "item-2", - text: "queued again", - intent: "queue", - }); - const pending = structuredClone(useQueueOutboxStore.getState().entriesForServer("server-1")); - expect(pending).toEqual([ - expect.objectContaining({ itemId: "item-2", text: "queued again", attempts: 0 }), - ]); - await act(async () => { - deliverServerInfo({ ownedSubscriptions: true }); - }); - - expect(harness.enqueueAgentMessage).not.toHaveBeenCalled(); - expect(useQueueOutboxStore.getState().entriesForServer("server-1")).toEqual(pending); - - await act(async () => { - deliverServerInfo({ ownedSubscriptions: true, durableAgentQueueV1: true }); - }); - expect(flush).toHaveBeenCalledTimes(2); - await flush.mock.results[1]!.value; - expect(harness.enqueueAgentMessage).toHaveBeenCalledTimes(1); - expect(harness.enqueueAgentMessage.mock.calls[0]?.[0]).toMatchObject({ - agentId: "agent-1", - itemId: "item-2", - text: "queued again", - intent: "queue", - }); - expect(useQueueOutboxStore.getState().entriesForServer("server-1")).toEqual([]); - }); -}); diff --git a/packages/app/src/contexts/voice-context.tsx b/packages/app/src/contexts/voice-context.tsx index 54bf40ccf91..4c8d04e2f1b 100644 --- a/packages/app/src/contexts/voice-context.tsx +++ b/packages/app/src/contexts/voice-context.tsx @@ -8,8 +8,6 @@ import { type ReactNode, } from "react"; import { activateKeepAwakeAsync, deactivateKeepAwake } from "expo-keep-awake"; -import { useTranslation } from "react-i18next"; -import { useToast } from "@/contexts/toast-context"; import { useSessionStore } from "@/stores/session-store"; import { createAudioEngine } from "@/audio"; import type { AudioEngine } from "@/audio"; @@ -32,8 +30,6 @@ const EMPTY_SNAPSHOT: VoiceRuntimeSnapshot = { isVoiceMode: false, isVoiceSwitching: false, isMuted: false, - failure: null, - lastInputStatus: null, activeServerId: null, activeAgentId: null, }; @@ -119,14 +115,6 @@ interface VoiceProviderProps { export function VoiceProvider({ children }: VoiceProviderProps) { const engineRef = useRef(null); const runtimeRef = useRef(null); - const { t } = useTranslation(); - const toast = useToast(); - // Voice stops after the microphone is lost, taking the voice panel with it, so the - // visible notice for that case is a toast. - const notifyMicrophoneLostRef = useRef(() => {}); - notifyMicrophoneLostRef.current = () => { - toast.error(t("realtimeVoice.failure.microphone-lost")); - }; if (!engineRef.current) { let runtime: VoiceRuntime | null = null; @@ -138,9 +126,7 @@ export function VoiceProvider({ children }: VoiceProviderProps) { runtime?.handleCaptureVolume(level); }, onInterruption: () => { - if (!runtime?.getSnapshot().isVoiceMode) return; - notifyMicrophoneLostRef.current(); - void runtime.handleMicrophoneLost().catch((error) => { + void runtime?.stopVoice().catch((error) => { console.error("[VoiceEngine] Failed to stop after audio interruption:", error); }); }, diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index b4c7b29d340..7f43be81288 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -18,7 +18,6 @@ export const ar: TranslationResources = { title: "بحث", placeholder: "بحث في اللوحة", - updateHost: "حدّث المضيف لاستخدام البحث", close: "إغلاق البحث", matches: "نتائج البحث", previous: "التطابق السابق", @@ -190,7 +189,7 @@ export const ar: TranslationResources = { unmuteVoice: "إلغاء كتم الصوت", muteVoice: "كتم الصوت", dictation: "الإملاء", - interruptBeforeVoice: "حدّث المضيف لاستخدام الصوت أثناء عمل الوكيل", + interruptBeforeVoice: "قم بمقاطعة الوكيل قبل بدء الوضع الصوتي", }, attachments: { addImage: "أضف صورة", @@ -224,20 +223,6 @@ export const ar: TranslationResources = { pasteImageFailed: "تعذر لصق الصورة", fileTooLarge: "{{fileName}} is too large (max {{size}})", }, - queued: { - menu: "خيارات الرسالة المنتظرة", - moveUp: "نقل لأعلى", - moveDown: "نقل لأسفل", - delete: "حذف", - discard: "تجاهل", - retry: "إعادة المحاولة", - sending: "جارٍ الإرسال...", - unconfirmed: "غير مؤكد", - failed: "فشل", - changedOnAnotherDevice: "تغيّرت هذه الرسالة المنتظرة على جهاز آخر", - deleteTitle: "حذف الرسالة المنتظرة؟", - deleteMessage: "ستُزال من كل الأجهزة المتصلة بهذا الوكيل", - }, clientCommands: { archiveAgent: "أرشفة الوكيل الحالي", freshDraft: "أرشفة هذا الوكيل وابدأ مسودة جديدة", @@ -313,75 +298,6 @@ export const ar: TranslationResources = { }, }, agentPanel: { - stream: { - tab: "الموجز", - title: "بجانب هذه المحادثة", - description: "الأسئلة والقرارات والردود والملفات، الأحدث أولاً.", - updateHost: "حدّث المضيف لاستخدام الموجز", - updateHostDescription: "تتطلب الأسئلة والردود مضيفاً أحدث. ملفاتك أدناه.", - offline: "جارٍ إعادة الاتصال. تظل العناصر المحفوظة متاحة؛ قد تكون الحالات قديمة.", - showAll: "عرض الكل", - pending: "بحاجة إلى رد ({{count}})", - noPending: "لا شيء ينتظر الرد", - noPendingDescription: "تظل الأسئلة والنتائج السابقة في الموجز الكامل.", - emptyTitle: "موجز يرافق محادثتك", - emptyDescription: "ستظهر الأسئلة والموافقات والردود النهائية هنا أثناء عمل الوكيل.", - backToChat: "العودة إلى المحادثة", - retention: - "آخر 50 حدثاً والملفات المجمّعة. يبدأ التسجيل بعد تحديث المضيف؛ يبقى السياق الكامل في المحادثة.", - question: "سؤال", - decision: "قرار", - permission: "طلب إذن", - open: "بانتظار الرد", - reply_sent: "أُرسل الرد · القرار غير متحقق منه", - pendingStatus: "بانتظار ردك", - allowed: "قُبل الرد", - denied: "رُفض", - expired: "لم يعد معلّقاً", - completed: "انتهت الجولة", - failed: "فشلت الجولة", - canceled: "تمت المقاطعة", - outcomeDescription: "تصف الحالة جولة التنفيذ ولا تؤكد إنجاز المهمة.", - excerpt: "مقتطف. السياق الكامل في المحادثة.", - showLess: "عرض أقل", - read: "قراءة", - replyInChat: "الرد في المحادثة", - viewStream: "عرض الموجز", - mutationFailed: "تعذّر حفظ التغيير", - queueTab: "قائمة الانتظار", - pinnedTab: "دبابيس التدفق", - filterAll: "الكل", - filterQuestions: "الأسئلة", - filterQAndA: "سؤال وجواب", - filterFeatures: "الميزات", - filterDecisions: "القرارات", - filterOutcomes: "النتائج", - notePlaceholder: "اكتب ملاحظة أو رابطًا…", - addNote: "إضافة ملاحظة", - answerLabel: "الإجابة:", - unpin: "إلغاء التثبيت", - showAllAction: "عرض الكل", - showOpenOnlyAction: "عرض المفتوح فقط", - noPinnedItems: "لا توجد عناصر مثبتة بعد", - noItemsFound: "لا توجد عناصر", - featureRequest: "طلب ميزة", - streamPin: "دبوس تدفق", - qAndA: "سؤال وجواب", - statusOpen: "مفتوح", - statusReviewed: "تمت المراجعة", - statusDone: "تم", - }, - artifacts: { - chatTab: "الدردشة", - tab: "الملفات ({{count}})", - emptyTitle: "لا توجد ملفات بعد", - emptyDescription: "ستظهر هنا الملفات التي ينشئها هذا الوكيل.", - updateHostTitle: "حدّث المضيف لاستخدام الملفات", - updateHostDescription: "لا يدعم هذا المضيف ملفات الدردشة بعد.", - previewMissing: "Preview unavailable", - open: "فتح {{name}}", - openLabel: "فتح", - }, states: { notFound: "لم يتم العثور على Agent", failedToLoad: "فشل تحميل الوكيل", @@ -810,9 +726,7 @@ export const ar: TranslationResources = { reloadAgent: "إعادة تحميل الوكيل", reloadAgentTooltip: "قم بإعادة تحميل الوكيل لتحديث المهارات أو MCPs أو حالة تسجيل الدخول.", close: "يغلق", - findInChat: "بحث في الدردشة", renameTerminal: "إعادة تسمية المحطة", - viewArtifacts: "عرض الملفات المنتَجة", renameAgent: "إعادة تسمية الوكيل", }, actions: { @@ -2151,25 +2065,10 @@ export const ar: TranslationResources = { }, }, realtimeVoice: { - listening: "الميكروفون يعمل", - notListening: "لا يستمع", - failure: { - "nothing-recognized": "لم أفهم ذلك. قلها مرة أخرى.", - "recognition-stalled": "توقف التعرف على الكلام عن الاستجابة. أوقف الصوت وابدأه من جديد.", - "recognition-failed": "فشل التعرف على الكلام. أوقف الصوت وابدأه من جديد.", - "recognition-unavailable": "التعرف على الكلام غير متاح على المضيف.", - "host-disconnected": "انقطع الاتصال بالمضيف. إدخال الميكروفون متوقف مؤقتًا حتى يعود الاتصال.", - "microphone-lost": "فُقد الميكروفون. توقف الصوت.", - }, - inputQueued: "تمت إضافة الكلام إلى قائمة انتظار الوكيل", - inputSent: "أُرسل الكلام إلى الوكيل", - inputRemoved: "أُزيل الكلام من قائمة الانتظار", - inputUnknown: "حالة تسليم الكلام غير مؤكدة", actions: { - interruptAgent: "مقاطعة الوكيل", mute: "كتم صوت الوقت الحقيقي", unmute: "إلغاء كتم صوت الوقت الحقيقي", - stop: "إيقاف الصوت في الوقت الحقيقي", + stop: "إيقاف الصوت في الوقت الحقيقي ومقاطعة الدوران", }, }, rewind: { diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index f4fa02fa228..2d650b83e67 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -14,7 +14,6 @@ export const en = { retry: "Retry", title: "Find", placeholder: "Find in pane", - updateHost: "Update the host to use Find", close: "Close Find", matches: "Find matches", previous: "Previous match", @@ -186,7 +185,7 @@ export const en = { unmuteVoice: "Unmute voice", muteVoice: "Mute voice", dictation: "Dictation", - interruptBeforeVoice: "Update the host to use voice while the agent works", + interruptBeforeVoice: "Interrupt the agent before starting voice mode", }, attachments: { addImage: "Add image", @@ -220,20 +219,6 @@ export const en = { pasteImageFailed: "Failed to paste image", fileTooLarge: "{{fileName}} is too large (max {{size}})", }, - queued: { - menu: "Queued message options", - moveUp: "Move up", - moveDown: "Move down", - delete: "Delete", - discard: "Discard", - retry: "Retry", - sending: "Sending...", - unconfirmed: "Unconfirmed", - failed: "Failed", - changedOnAnotherDevice: "This queued message changed on another device", - deleteTitle: "Delete queued message?", - deleteMessage: "It will be removed for every device connected to this agent", - }, clientCommands: { archiveAgent: "Archive the current agent", freshDraft: "Archive this agent and start a fresh draft", @@ -311,77 +296,6 @@ export const en = { }, }, agentPanel: { - stream: { - tab: "Stream", - title: "Alongside this chat", - description: "Questions, decisions, responses and files. Latest first.", - updateHost: "Update the host to use Stream", - updateHostDescription: - "Questions and responses need a newer host. Your file artifacts are below.", - offline: "Reconnecting. Saved items remain available; pending status may be out of date.", - showAll: "Show all items", - pending: "Needs a reply ({{count}})", - noPending: "Nothing waiting for a reply", - noPendingDescription: "Past questions and outcomes are still in the full stream.", - emptyTitle: "Your chat’s companion stream", - emptyDescription: - "Questions, approvals and final responses will appear here as the agent works.", - backToChat: "Back to chat", - retention: - "Recent 50 moments and collected files. Capture begins with the host update; full context stays in Chat.", - question: "Question", - decision: "Decision", - permission: "Permission request", - open: "Awaiting a reply", - reply_sent: "Reply sent · decision not verified", - pendingStatus: "Awaiting your response", - allowed: "Response accepted", - denied: "Declined", - expired: "No longer pending", - completed: "Turn ended", - failed: "Turn failed", - canceled: "Interrupted", - outcomeDescription: "Run status describes the turn, not verification of the task.", - excerpt: "Excerpt. Full context is in Chat.", - showLess: "Show less", - read: "Read", - replyInChat: "Reply in chat", - viewStream: "View stream", - mutationFailed: "Couldn't save that change", - queueTab: "Queue", - pinnedTab: "Stream pins", - filterAll: "All", - filterQuestions: "Questions", - filterQAndA: "Q&A", - filterFeatures: "Features", - filterDecisions: "Decisions", - filterOutcomes: "Outcomes", - notePlaceholder: "Type a note or link…", - addNote: "Add note", - answerLabel: "Answer:", - unpin: "Unpin", - showAllAction: "Show All", - showOpenOnlyAction: "Show Open Only", - noPinnedItems: "No Stream pins yet", - noItemsFound: "No items found", - featureRequest: "Feature request", - streamPin: "Stream pin", - qAndA: "Q&A", - statusOpen: "Open", - statusReviewed: "Reviewed", - statusDone: "Done", - }, - artifacts: { - chatTab: "Chat", - tab: "Artifacts ({{count}})", - emptyTitle: "No artifacts yet", - emptyDescription: "Files this agent creates will appear here.", - updateHostTitle: "Update the host to use artifacts", - updateHostDescription: "This host does not support per-chat artifact feeds yet.", - previewMissing: "Preview unavailable", - open: "Open {{name}}", - openLabel: "Open", - }, states: { notFound: "Agent not found", failedToLoad: "Failed to load agent", @@ -811,9 +725,7 @@ export const en = { reloadAgent: "Reload agent", reloadAgentTooltip: "Reload agent to update skills, MCPs or login status.", close: "Close", - findInChat: "Find in chat", renameTerminal: "Rename terminal", - viewArtifacts: "View artifacts", renameAgent: "Rename agent", }, actions: { @@ -2181,25 +2093,10 @@ export const en = { }, }, realtimeVoice: { - listening: "Microphone on", - notListening: "Not listening", - failure: { - "nothing-recognized": "Didn't catch that. Say it again.", - "recognition-stalled": "Speech recognition stopped responding. Stop and restart voice.", - "recognition-failed": "Speech recognition failed. Stop and restart voice.", - "recognition-unavailable": "Speech recognition is unavailable on the host.", - "host-disconnected": "Host disconnected. Microphone input is paused until it reconnects.", - "microphone-lost": "Microphone lost. Voice stopped.", - }, - inputQueued: "Speech queued for agent", - inputSent: "Speech sent to agent", - inputRemoved: "Speech removed from queue", - inputUnknown: "Speech delivery uncertain", actions: { - interruptAgent: "Interrupt agent", mute: "Mute realtime voice", unmute: "Unmute realtime voice", - stop: "Stop realtime voice", + stop: "Stop realtime voice and interrupt turn", }, }, rewind: { diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index f37c9aae395..e237a487d16 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -19,7 +19,6 @@ export const es: TranslationResources = { title: "Buscar", placeholder: "Buscar en el panel", - updateHost: "Actualiza el host para usar Buscar", close: "Cerrar búsqueda", matches: "Coincidencias", previous: "Coincidencia anterior", @@ -192,7 +191,7 @@ export const es: TranslationResources = { unmuteVoice: "Activar voz", muteVoice: "voz muda", dictation: "Dictado", - interruptBeforeVoice: "Actualiza el host para usar la voz mientras el agente trabaja", + interruptBeforeVoice: "Interrumpir al agente antes de iniciar el modo de voz.", }, attachments: { addImage: "Agregar imagen", @@ -227,20 +226,6 @@ export const es: TranslationResources = { pasteImageFailed: "No se pudo pegar la imagen", fileTooLarge: "{{fileName}} is too large (max {{size}})", }, - queued: { - menu: "Opciones del mensaje en cola", - moveUp: "Subir", - moveDown: "Bajar", - delete: "Eliminar", - discard: "Descartar", - retry: "Reintentar", - sending: "Enviando...", - unconfirmed: "Sin confirmar", - failed: "Falló", - changedOnAnotherDevice: "Este mensaje en cola cambió en otro dispositivo", - deleteTitle: "¿Eliminar el mensaje en cola?", - deleteMessage: "Se eliminará en todos los dispositivos conectados a este agente", - }, clientCommands: { archiveAgent: "Archivar el agente actual", freshDraft: "Archive este agente y comience un nuevo borrador", @@ -316,78 +301,6 @@ export const es: TranslationResources = { }, }, agentPanel: { - stream: { - tab: "Flujo", - title: "Junto a este chat", - description: "Preguntas, decisiones, respuestas y archivos. Lo más reciente primero.", - updateHost: "Actualiza el host para usar Flujo", - updateHostDescription: - "Las preguntas y respuestas requieren un host más reciente. Tus archivos están abajo.", - offline: - "Reconectando. Los elementos guardados siguen disponibles; el estado puede estar desactualizado.", - showAll: "Mostrar todo", - pending: "Necesita respuesta ({{count}})", - noPending: "No hay respuestas pendientes", - noPendingDescription: "Las preguntas y resultados anteriores siguen en el flujo completo.", - emptyTitle: "El flujo que acompaña tu chat", - emptyDescription: - "Aquí aparecerán preguntas, aprobaciones y respuestas finales mientras trabaja el agente.", - backToChat: "Volver al chat", - retention: - "Los últimos 50 momentos y archivos recopilados. Se registra desde la actualización del host; el contexto completo está en Chat.", - question: "Pregunta", - decision: "Decisión", - permission: "Solicitud de permiso", - open: "Esperando respuesta", - reply_sent: "Respuesta enviada · decisión sin verificar", - pendingStatus: "Esperando tu respuesta", - allowed: "Respuesta aceptada", - denied: "Rechazada", - expired: "Ya no está pendiente", - completed: "Turno terminado", - failed: "Turno fallido", - canceled: "Interrumpido", - outcomeDescription: "El estado describe el turno, no verifica la tarea.", - excerpt: "Extracto. El contexto completo está en Chat.", - showLess: "Mostrar menos", - read: "Leer", - replyInChat: "Responder en el chat", - viewStream: "Ver flujo", - mutationFailed: "No se pudo guardar el cambio", - queueTab: "Cola", - pinnedTab: "Pines del flujo", - filterAll: "Todo", - filterQuestions: "Preguntas", - filterQAndA: "Preguntas y respuestas", - filterFeatures: "Funciones", - filterDecisions: "Decisiones", - filterOutcomes: "Resultados", - notePlaceholder: "Escribe una nota o un enlace…", - addNote: "Añadir nota", - answerLabel: "Respuesta:", - unpin: "Desfijar", - showAllAction: "Mostrar todo", - showOpenOnlyAction: "Mostrar solo abiertos", - noPinnedItems: "Aún no hay pines del flujo", - noItemsFound: "No se encontraron elementos", - featureRequest: "Solicitud de función", - streamPin: "Pin del flujo", - qAndA: "Preguntas y respuestas", - statusOpen: "Abierto", - statusReviewed: "Revisado", - statusDone: "Hecho", - }, - artifacts: { - chatTab: "Chat", - tab: "Artefactos ({{count}})", - emptyTitle: "Aún no hay artefactos", - emptyDescription: "Los archivos que cree este agente aparecerán aquí.", - updateHostTitle: "Actualiza el host para usar artefactos", - updateHostDescription: "Este host aún no admite artefactos por chat.", - previewMissing: "Preview unavailable", - open: "Abrir {{name}}", - openLabel: "Abrir", - }, states: { notFound: "Agentno encontrado", failedToLoad: "No se pudo cargar el agente", @@ -822,9 +735,7 @@ export const es: TranslationResources = { reloadAgentTooltip: "Vuelva a cargar el agente para actualizar habilidades, MCP o estado de inicio de sesión.", close: "Cerrar", - findInChat: "Buscar en el chat", renameTerminal: "Cambiar nombre de terminal", - viewArtifacts: "Ver artefactos", renameAgent: "Cambiar nombre del agente", }, actions: { @@ -2205,26 +2116,10 @@ export const es: TranslationResources = { }, }, realtimeVoice: { - listening: "Micrófono activado", - notListening: "No escucha", - failure: { - "nothing-recognized": "No lo entendí. Dilo otra vez.", - "recognition-stalled": "El reconocimiento de voz dejó de responder. Detén y reinicia la voz.", - "recognition-failed": "Falló el reconocimiento de voz. Detén y reinicia la voz.", - "recognition-unavailable": "El reconocimiento de voz no está disponible en el host.", - "host-disconnected": - "Host desconectado. La entrada del micrófono está en pausa hasta que se reconecte.", - "microphone-lost": "Se perdió el micrófono. La voz se detuvo.", - }, - inputQueued: "Voz en cola para el agente", - inputSent: "Voz enviada al agente", - inputRemoved: "Voz eliminada de la cola", - inputUnknown: "Entrega de voz incierta", actions: { - interruptAgent: "Interrumpir al agente", mute: "Silenciar voz en tiempo real", unmute: "Activar voz en tiempo real", - stop: "Detener la voz en tiempo real", + stop: "Detener la voz en tiempo real e interrumpir el turno.", }, }, rewind: { diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 4a28e89cba2..f4c9c071141 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -19,7 +19,6 @@ export const fr: TranslationResources = { title: "Rechercher", placeholder: "Rechercher dans le panneau", - updateHost: "Mettez à jour l’hôte pour utiliser la recherche", close: "Fermer la recherche", matches: "Résultats de recherche", previous: "Résultat précédent", @@ -192,8 +191,7 @@ export const fr: TranslationResources = { unmuteVoice: "Réactiver le micro", muteVoice: "Couper le micro", dictation: "Dictée", - interruptBeforeVoice: - "Mettez à jour l’hôte pour utiliser la voix pendant que l’agent travaille", + interruptBeforeVoice: "Interrompez l’agent avant de démarrer le mode vocal", }, attachments: { addImage: "Ajouter une image", @@ -228,20 +226,6 @@ export const fr: TranslationResources = { pasteImageFailed: "Impossible de coller l’image", fileTooLarge: "{{fileName}} est trop volumineux (maximum {{size}})", }, - queued: { - menu: "Options du message en file", - moveUp: "Monter", - moveDown: "Descendre", - delete: "Supprimer", - discard: "Abandonner", - retry: "Réessayer", - sending: "Envoi...", - unconfirmed: "Non confirmé", - failed: "Échec", - changedOnAnotherDevice: "Ce message en file a été modifié sur un autre appareil", - deleteTitle: "Supprimer le message en file ?", - deleteMessage: "Il sera supprimé sur tous les appareils connectés à cet agent", - }, clientCommands: { archiveAgent: "Archiver l’agent actuel", freshDraft: "Archiver cet agent et démarrer un nouveau brouillon", @@ -317,78 +301,6 @@ export const fr: TranslationResources = { }, }, agentPanel: { - stream: { - tab: "Fil", - title: "Au fil de ce chat", - description: "Questions, décisions, réponses et fichiers. Les plus récents en premier.", - updateHost: "Mettez l’hôte à jour pour utiliser le fil", - updateHostDescription: - "Les questions et réponses nécessitent un hôte plus récent. Vos fichiers sont ci-dessous.", - offline: - "Reconnexion. Les éléments enregistrés restent disponibles ; les états peuvent être périmés.", - showAll: "Tout afficher", - pending: "Réponse attendue ({{count}})", - noPending: "Aucune réponse attendue", - noPendingDescription: "Les anciennes questions et les résultats restent dans le fil complet.", - emptyTitle: "Le fil qui accompagne votre chat", - emptyDescription: - "Questions, autorisations et réponses finales apparaîtront ici pendant le travail de l’agent.", - backToChat: "Retour au chat", - retention: - "Les 50 derniers moments et les fichiers collectés. La capture commence avec la mise à jour de l’hôte ; le contexte complet reste dans Chat.", - question: "Question", - decision: "Décision", - permission: "Demande d’autorisation", - open: "En attente de réponse", - reply_sent: "Réponse envoyée · décision non vérifiée", - pendingStatus: "En attente de votre réponse", - allowed: "Réponse acceptée", - denied: "Refusée", - expired: "Plus en attente", - completed: "Tour terminé", - failed: "Échec du tour", - canceled: "Interrompu", - outcomeDescription: "L’état décrit le tour, sans vérifier la réussite de la tâche.", - excerpt: "Extrait. Le contexte complet est dans Chat.", - showLess: "Réduire", - read: "Lire", - replyInChat: "Répondre dans le chat", - viewStream: "Voir le fil", - mutationFailed: "Impossible d'enregistrer cette modification", - queueTab: "File", - pinnedTab: "Pins de flux", - filterAll: "Tout", - filterQuestions: "Questions", - filterQAndA: "Questions-réponses", - filterFeatures: "Fonctionnalités", - filterDecisions: "Décisions", - filterOutcomes: "Résultats", - notePlaceholder: "Saisir une note ou un lien…", - addNote: "Ajouter une note", - answerLabel: "Réponse :", - unpin: "Désépingler", - showAllAction: "Tout afficher", - showOpenOnlyAction: "Afficher uniquement les ouverts", - noPinnedItems: "Aucun pin de flux pour le moment", - noItemsFound: "Aucun élément trouvé", - featureRequest: "Demande de fonctionnalité", - streamPin: "Pin de flux", - qAndA: "Questions/Réponses", - statusOpen: "Ouvert", - statusReviewed: "Examiné", - statusDone: "Terminé", - }, - artifacts: { - chatTab: "Discussion", - tab: "Artefacts ({{count}})", - emptyTitle: "Aucun artefact", - emptyDescription: "Les fichiers créés par cet agent apparaîtront ici.", - updateHostTitle: "Mettez à jour l’hôte pour utiliser les artefacts", - updateHostDescription: "Cet hôte ne prend pas encore en charge les artefacts par discussion.", - previewMissing: "Preview unavailable", - open: "Ouvrir {{name}}", - openLabel: "Ouvrir", - }, states: { notFound: "Agent introuvable", failedToLoad: "Impossible de charger l’agent", @@ -822,9 +734,7 @@ export const fr: TranslationResources = { reloadAgentTooltip: "Rechargez l’agent pour mettre à jour les skills, les MCP ou l’état de connexion.", close: "Fermer", - findInChat: "Rechercher dans la discussion", renameTerminal: "Renommer le terminal", - viewArtifacts: "Voir les artefacts", renameAgent: "Renommer l’agent", }, actions: { @@ -2204,27 +2114,10 @@ export const fr: TranslationResources = { }, }, realtimeVoice: { - listening: "Micro activé", - notListening: "N’écoute pas", - failure: { - "nothing-recognized": "Je n’ai pas compris. Répétez.", - "recognition-stalled": - "La reconnaissance vocale ne répond plus. Arrêtez et relancez la voix.", - "recognition-failed": "La reconnaissance vocale a échoué. Arrêtez et relancez la voix.", - "recognition-unavailable": "La reconnaissance vocale n’est pas disponible sur l’hôte.", - "host-disconnected": - "Hôte déconnecté. L’entrée du micro est suspendue jusqu’à la reconnexion.", - "microphone-lost": "Micro perdu. La session vocale s’est arrêtée.", - }, - inputQueued: "Parole en attente pour l’agent", - inputSent: "Parole envoyée à l’agent", - inputRemoved: "Parole retirée de la file", - inputUnknown: "Envoi de la parole incertain", actions: { - interruptAgent: "Interrompre l’agent", mute: "Couper la voix en temps réel", unmute: "Réactiver la voix en temps réel", - stop: "Arrêter la voix en temps réel", + stop: "Arrêter la voix en temps réel et interrompre le tour", }, }, rewind: { diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 22ff7fb33fc..472c9b040f8 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -19,7 +19,6 @@ export const ja: TranslationResources = { title: "検索", placeholder: "ペイン内を検索", - updateHost: "検索を使うにはホストを更新してください", close: "検索を閉じる", matches: "検索結果", previous: "前の一致", @@ -192,7 +191,7 @@ export const ja: TranslationResources = { unmuteVoice: "音声のミュートを解除", muteVoice: "音声をミュート", dictation: "音声入力", - interruptBeforeVoice: "エージェントの作業中に音声を使うにはホストを更新してください", + interruptBeforeVoice: "音声モードを開始する前にエージェントを中断してください", }, attachments: { addImage: "画像を追加", @@ -227,20 +226,6 @@ export const ja: TranslationResources = { pasteImageFailed: "画像を貼り付けられませんでした", fileTooLarge: "{{fileName}}が大きすぎます(最大{{size}})", }, - queued: { - menu: "キュー済みメッセージの操作", - moveUp: "上へ移動", - moveDown: "下へ移動", - delete: "削除", - discard: "破棄", - retry: "再試行", - sending: "送信中...", - unconfirmed: "未確認", - failed: "失敗", - changedOnAnotherDevice: "このキュー済みメッセージは別のデバイスで変更されました", - deleteTitle: "キュー済みメッセージを削除しますか?", - deleteMessage: "このエージェントに接続しているすべてのデバイスから削除されます", - }, clientCommands: { archiveAgent: "現在のエージェントをアーカイブ", freshDraft: "このエージェントをアーカイブして新しい下書きを開始", @@ -316,75 +301,6 @@ export const ja: TranslationResources = { }, }, agentPanel: { - stream: { - tab: "ストリーム", - title: "このチャットとともに", - description: "質問、判断、回答、ファイルを新しい順に表示します。", - updateHost: "ストリームを使うにはホストを更新", - updateHostDescription: "質問と回答には新しいホストが必要です。ファイルは下に表示されます。", - offline: "再接続中。保存済みの項目は閲覧できますが、保留状態は古い可能性があります。", - showAll: "すべて表示", - pending: "返信が必要({{count}})", - noPending: "返信待ちはありません", - noPendingDescription: "過去の質問と結果はストリーム全体で確認できます。", - emptyTitle: "チャットに寄り添うストリーム", - emptyDescription: "エージェントの作業中に質問、承認、最終回答がここに表示されます。", - backToChat: "チャットに戻る", - retention: - "直近50件と収集されたファイル。ホスト更新後から記録されます。全文はチャットで確認できます。", - question: "質問", - decision: "判断", - permission: "許可のリクエスト", - open: "返信待ち", - reply_sent: "返信済み・判断は未確認", - pendingStatus: "あなたの回答待ち", - allowed: "回答を受け付けました", - denied: "拒否済み", - expired: "保留ではありません", - completed: "ターン終了", - failed: "ターン失敗", - canceled: "中断", - outcomeDescription: "実行状態はターンの状態であり、タスクの達成を保証しません。", - excerpt: "抜粋です。全文はチャットで確認できます。", - showLess: "閉じる", - read: "読む", - replyInChat: "チャットで返信", - viewStream: "ストリームを表示", - mutationFailed: "変更を保存できませんでした", - queueTab: "キュー", - pinnedTab: "ストリームピン", - filterAll: "すべて", - filterQuestions: "質問", - filterQAndA: "Q&A", - filterFeatures: "機能", - filterDecisions: "決定", - filterOutcomes: "結果", - notePlaceholder: "メモまたはリンクを入力…", - addNote: "メモを追加", - answerLabel: "回答:", - unpin: "ピン留めを解除", - showAllAction: "すべて表示", - showOpenOnlyAction: "未返信のみ表示", - noPinnedItems: "ストリームピンはまだありません", - noItemsFound: "項目が見つかりません", - featureRequest: "機能リクエスト", - streamPin: "ストリームピン", - qAndA: "Q&A", - statusOpen: "未処理", - statusReviewed: "確認済み", - statusDone: "完了", - }, - artifacts: { - chatTab: "チャット", - tab: "成果物 ({{count}})", - emptyTitle: "成果物はまだありません", - emptyDescription: "このエージェントが作成したファイルがここに表示されます。", - updateHostTitle: "成果物を使うにはホストを更新してください", - updateHostDescription: "このホストはチャットごとの成果物にまだ対応していません。", - previewMissing: "Preview unavailable", - open: "{{name}}を開く", - openLabel: "開く", - }, states: { notFound: "エージェントが見つかりません", failedToLoad: "エージェントの読み込みに失敗しました", @@ -818,9 +734,7 @@ export const ja: TranslationResources = { reloadAgentTooltip: "スキル、MCP、ログイン状態を更新するためにエージェントを再読み込みします。", close: "閉じる", - findInChat: "チャット内を検索", renameTerminal: "ターミナルの名前を変更", - viewArtifacts: "アーティファクトを表示", renameAgent: "エージェントの名前を変更", }, actions: { @@ -2174,25 +2088,10 @@ export const ja: TranslationResources = { }, }, realtimeVoice: { - listening: "マイクはオン", - notListening: "聞き取り停止中", - failure: { - "nothing-recognized": "聞き取れませんでした。もう一度話してください。", - "recognition-stalled": "音声認識が応答しなくなりました。音声を停止して再開してください。", - "recognition-failed": "音声認識に失敗しました。音声を停止して再開してください。", - "recognition-unavailable": "ホストで音声認識を利用できません。", - "host-disconnected": "ホストとの接続が切れました。再接続までマイク入力は一時停止します。", - "microphone-lost": "マイクが使えなくなりました。音声を停止しました。", - }, - inputQueued: "発話をエージェントのキューに追加しました", - inputSent: "発話をエージェントに送信しました", - inputRemoved: "発話をキューから削除しました", - inputUnknown: "発話の送信状態を確認できません", actions: { - interruptAgent: "エージェントを中断", mute: "リアルタイム音声をミュート", unmute: "リアルタイム音声のミュートを解除", - stop: "リアルタイム音声を停止", + stop: "リアルタイム音声を停止してターンを中断", }, }, rewind: { diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index ef02273338a..8f575970bed 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -18,7 +18,6 @@ export const ko: TranslationResources = { title: "찾기", placeholder: "패널에서 찾기", - updateHost: "찾기를 사용하려면 호스트를 업데이트하세요", close: "찾기 닫기", matches: "검색 결과", previous: "이전 일치 항목", @@ -190,7 +189,7 @@ export const ko: TranslationResources = { unmuteVoice: "음성 음소거 해제", muteVoice: "음성 음소거", dictation: "받아쓰기", - interruptBeforeVoice: "에이전트 작업 중 음성을 사용하려면 호스트를 업데이트하세요", + interruptBeforeVoice: "음성 모드를 시작하기 전에 에이전트를 중단하세요", }, attachments: { addImage: "이미지 추가", @@ -224,20 +223,6 @@ export const ko: TranslationResources = { pasteImageFailed: "이미지를 붙여넣지 못했습니다.", fileTooLarge: "{{fileName}}이(가) 너무 큽니다 (최대 {{size}})", }, - queued: { - menu: "대기 중 메시지 옵션", - moveUp: "위로 이동", - moveDown: "아래로 이동", - delete: "삭제", - discard: "버리기", - retry: "다시 시도", - sending: "보내는 중...", - unconfirmed: "확인 안 됨", - failed: "실패", - changedOnAnotherDevice: "이 대기 중 메시지는 다른 기기에서 변경되었습니다", - deleteTitle: "대기 중 메시지를 삭제할까요?", - deleteMessage: "이 에이전트에 연결된 모든 기기에서 제거됩니다", - }, clientCommands: { archiveAgent: "현재 에이전트 보관", freshDraft: "이 에이전트를 보관하고 새 초안을 시작합니다", @@ -313,77 +298,6 @@ export const ko: TranslationResources = { }, }, agentPanel: { - stream: { - tab: "스트림", - title: "이 대화와 함께", - description: "질문, 결정, 응답 및 파일. 최신 항목이 먼저 표시됩니다.", - updateHost: "스트림을 사용하려면 호스트를 업데이트하세요", - updateHostDescription: - "질문과 응답에는 최신 호스트가 필요합니다. 파일 아티팩트는 아래에 있습니다.", - offline: - "다시 연결 중입니다. 저장된 항목은 계속 사용할 수 있으며, 대기 중인 상태는 오래되었을 수 있습니다.", - showAll: "모든 항목 표시", - pending: "답변 대기 ({{count}})", - noPending: "답변을 기다리는 항목이 없습니다", - noPendingDescription: "이전 질문과 결과는 전체 스트림에 그대로 남아 있습니다.", - emptyTitle: "이 대화의 컴패니언 스트림", - emptyDescription: "에이전트가 작업하는 동안 질문, 승인 및 최종 응답이 여기에 표시됩니다.", - backToChat: "대화로 돌아가기", - retention: - "최근 50개 순간과 수집된 파일. 캡처는 호스트 업데이트부터 시작되며, 전체 맥락은 대화에 유지됩니다.", - question: "질문", - decision: "결정", - permission: "권한 요청", - open: "답변 대기 중", - reply_sent: "답변 전송됨 · 결정 확인 안 됨", - pendingStatus: "응답 대기 중", - allowed: "응답 수락됨", - denied: "거절됨", - expired: "더 이상 대기 중이 아님", - completed: "턴 종료", - failed: "턴 실패", - canceled: "중단됨", - outcomeDescription: "실행 상태는 턴을 설명할 뿐, 작업의 검증을 의미하지 않습니다.", - excerpt: "발췌본. 전체 맥락은 대화에 있습니다.", - showLess: "간략히", - read: "읽기", - replyInChat: "대화에서 답장", - viewStream: "스트림 보기", - mutationFailed: "변경을 저장하지 못했습니다", - queueTab: "큐", - pinnedTab: "스트림 고정", - filterAll: "전체", - filterQuestions: "질문", - filterQAndA: "Q&A", - filterFeatures: "기능 제안", - filterDecisions: "결정", - filterOutcomes: "결과", - notePlaceholder: "메모나 링크를 입력하세요…", - addNote: "메모 추가", - answerLabel: "답변:", - unpin: "고정 해제", - showAllAction: "전체 표시", - showOpenOnlyAction: "대기 중만 표시", - noPinnedItems: "아직 스트림 고정이 없습니다", - noItemsFound: "항목이 없습니다", - featureRequest: "기능 제안", - streamPin: "스트림 고정", - qAndA: "Q&A", - statusOpen: "대기", - statusReviewed: "확인함", - statusDone: "완료", - }, - artifacts: { - chatTab: "대화", - tab: "아티팩트 ({{count}})", - emptyTitle: "아직 아티팩트가 없습니다", - emptyDescription: "이 에이전트가 만드는 파일이 여기에 표시됩니다.", - updateHostTitle: "아티팩트를 사용하려면 호스트를 업데이트하세요", - updateHostDescription: "이 호스트는 아직 대화별 아티팩트 피드를 지원하지 않습니다.", - previewMissing: "미리보기 사용 불가", - open: "{{name}} 열기", - openLabel: "열기", - }, states: { notFound: "에이전트를 찾을 수 없습니다", failedToLoad: "에이전트를 불러오지 못했습니다", @@ -814,9 +728,7 @@ export const ko: TranslationResources = { reloadAgentTooltip: "스킬, MCP 또는 로그인 상태를 업데이트하려면 에이전트를 다시 로드하세요.", close: "닫기", - findInChat: "채팅에서 찾기", renameTerminal: "터미널 이름 변경", - viewArtifacts: "아티팩트 보기", renameAgent: "에이전트 이름 변경", }, actions: { @@ -2164,26 +2076,10 @@ export const ko: TranslationResources = { }, }, realtimeVoice: { - listening: "마이크 켜짐", - notListening: "듣지 않는 중", - failure: { - "nothing-recognized": "알아듣지 못했습니다. 다시 말해 주세요.", - "recognition-stalled": "음성 인식이 응답하지 않습니다. 음성을 중지했다가 다시 시작하세요.", - "recognition-failed": "음성 인식에 실패했습니다. 음성을 중지했다가 다시 시작하세요.", - "recognition-unavailable": "호스트에서 음성 인식을 사용할 수 없습니다.", - "host-disconnected": - "호스트 연결이 끊어졌습니다. 다시 연결될 때까지 마이크 입력이 일시 중지됩니다.", - "microphone-lost": "마이크를 사용할 수 없습니다. 음성이 중지되었습니다.", - }, - inputQueued: "음성이 에이전트 대기열에 추가됨", - inputSent: "음성이 에이전트에 전송됨", - inputRemoved: "음성이 대기열에서 제거됨", - inputUnknown: "음성 전달 상태를 확인할 수 없음", actions: { - interruptAgent: "에이전트 중단", mute: "실시간 음성 음소거", unmute: "실시간 음성 음소거 해제", - stop: "실시간 음성 중지", + stop: "실시간 음성 중지 및 턴 중단", }, }, rewind: { diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 87c0dc9e4e1..31d09387f9f 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -19,7 +19,6 @@ export const ptBR: TranslationResources = { title: "Buscar", placeholder: "Buscar no painel", - updateHost: "Atualize o host para usar Localizar", close: "Fechar busca", matches: "Correspondências", previous: "Correspondência anterior", @@ -191,7 +190,7 @@ export const ptBR: TranslationResources = { unmuteVoice: "Ativar som da voz", muteVoice: "Silenciar voz", dictation: "Ditado", - interruptBeforeVoice: "Atualize o host para usar voz enquanto o agente trabalha", + interruptBeforeVoice: "Interrompa o agente antes de iniciar o modo de voz", }, attachments: { addImage: "Adicionar imagem", @@ -225,20 +224,6 @@ export const ptBR: TranslationResources = { pasteImageFailed: "Falha ao colar a imagem", fileTooLarge: "{{fileName}} é grande demais (máximo {{size}})", }, - queued: { - menu: "Opções da mensagem na fila", - moveUp: "Mover para cima", - moveDown: "Mover para baixo", - delete: "Excluir", - discard: "Descartar", - retry: "Tentar novamente", - sending: "Enviando...", - unconfirmed: "Não confirmada", - failed: "Falhou", - changedOnAnotherDevice: "Esta mensagem na fila foi alterada em outro dispositivo", - deleteTitle: "Excluir a mensagem na fila?", - deleteMessage: "Ela será removida em todos os dispositivos conectados a este agente", - }, clientCommands: { archiveAgent: "Arquivar o agente atual", freshDraft: "Arquivar este agente e iniciar um novo rascunho", @@ -314,78 +299,6 @@ export const ptBR: TranslationResources = { }, }, agentPanel: { - stream: { - tab: "Fluxo", - title: "Ao lado desta conversa", - description: "Perguntas, decisões, respostas e arquivos. Mais recentes primeiro.", - updateHost: "Atualize o host para usar o Fluxo", - updateHostDescription: - "Perguntas e respostas exigem um host mais recente. Seus arquivos estão abaixo.", - offline: - "Reconectando. Os itens salvos continuam disponíveis; os estados podem estar desatualizados.", - showAll: "Mostrar tudo", - pending: "Precisa de resposta ({{count}})", - noPending: "Nenhuma resposta pendente", - noPendingDescription: "Perguntas e resultados anteriores continuam no fluxo completo.", - emptyTitle: "O fluxo que acompanha sua conversa", - emptyDescription: - "Perguntas, aprovações e respostas finais aparecerão aqui enquanto o agente trabalha.", - backToChat: "Voltar à conversa", - retention: - "Os últimos 50 momentos e arquivos coletados. O registro começa com a atualização do host; o contexto completo fica no Chat.", - question: "Pergunta", - decision: "Decisão", - permission: "Pedido de permissão", - open: "Aguardando resposta", - reply_sent: "Resposta enviada · decisão não verificada", - pendingStatus: "Aguardando sua resposta", - allowed: "Resposta aceita", - denied: "Recusada", - expired: "Não está mais pendente", - completed: "Turno encerrado", - failed: "Falha no turno", - canceled: "Interrompido", - outcomeDescription: "O estado descreve o turno, sem verificar a conclusão da tarefa.", - excerpt: "Trecho. O contexto completo está no Chat.", - showLess: "Mostrar menos", - read: "Ler", - replyInChat: "Responder na conversa", - viewStream: "Ver fluxo", - mutationFailed: "Não foi possível salvar a alteração", - queueTab: "Fila", - pinnedTab: "Pins do fluxo", - filterAll: "Tudo", - filterQuestions: "Perguntas", - filterQAndA: "Perguntas e respostas", - filterFeatures: "Funcionalidades", - filterDecisions: "Decisões", - filterOutcomes: "Resultados", - notePlaceholder: "Digite uma nota ou um link…", - addNote: "Adicionar nota", - answerLabel: "Resposta:", - unpin: "Desafixar", - showAllAction: "Mostrar tudo", - showOpenOnlyAction: "Mostrar apenas abertos", - noPinnedItems: "Ainda não há pins do fluxo", - noItemsFound: "Nenhum item encontrado", - featureRequest: "Solicitação de recurso", - streamPin: "Pin do fluxo", - qAndA: "Perguntas e respostas", - statusOpen: "Aberto", - statusReviewed: "Revisado", - statusDone: "Concluído", - }, - artifacts: { - chatTab: "Chat", - tab: "Artefatos ({{count}})", - emptyTitle: "Nenhum artefato ainda", - emptyDescription: "Os arquivos criados por este agente aparecerão aqui.", - updateHostTitle: "Atualize o host para usar artefatos", - updateHostDescription: "Este host ainda não oferece artefatos por chat.", - previewMissing: "Preview unavailable", - open: "Abrir {{name}}", - openLabel: "Abrir", - }, states: { notFound: "Agente não encontrado", failedToLoad: "Falha ao carregar agente", @@ -819,9 +732,7 @@ export const ptBR: TranslationResources = { reloadAgent: "Recarregar agente", reloadAgentTooltip: "Recarregue o agente para atualizar skills, MCPs ou status de login.", close: "Fechar", - findInChat: "Localizar no chat", renameTerminal: "Renomear terminal", - viewArtifacts: "Ver artefatos", renameAgent: "Renomear agente", }, actions: { @@ -2189,25 +2100,10 @@ export const ptBR: TranslationResources = { }, }, realtimeVoice: { - listening: "Microfone ligado", - notListening: "Não está ouvindo", - failure: { - "nothing-recognized": "Não entendi. Diga de novo.", - "recognition-stalled": "O reconhecimento de voz parou de responder. Pare e reinicie a voz.", - "recognition-failed": "O reconhecimento de voz falhou. Pare e reinicie a voz.", - "recognition-unavailable": "O reconhecimento de voz não está disponível no host.", - "host-disconnected": "Host desconectado. A entrada do microfone está pausada até reconectar.", - "microphone-lost": "Microfone perdido. A voz foi interrompida.", - }, - inputQueued: "Fala na fila do agente", - inputSent: "Fala enviada ao agente", - inputRemoved: "Fala removida da fila", - inputUnknown: "Entrega da fala incerta", actions: { - interruptAgent: "Interromper agente", mute: "Silenciar voz em tempo real", unmute: "Ativar voz em tempo real", - stop: "Parar voz em tempo real", + stop: "Parar voz em tempo real e interromper a resposta", }, }, rewind: { diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 6467b545300..6e87cd82c97 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -19,7 +19,6 @@ export const ru: TranslationResources = { title: "Найти", placeholder: "Найти в панели", - updateHost: "Обновите хост, чтобы использовать поиск", close: "Закрыть поиск", matches: "Совпадения", previous: "Предыдущее совпадение", @@ -191,7 +190,7 @@ export const ru: TranslationResources = { unmuteVoice: "Включить звук", muteVoice: "Отключить голос", dictation: "Диктовка", - interruptBeforeVoice: "Обновите хост, чтобы использовать голос, пока агент работает", + interruptBeforeVoice: "Остановите агента перед запуском голосового режима", }, attachments: { addImage: "Добавить изображение", @@ -226,20 +225,6 @@ export const ru: TranslationResources = { pasteImageFailed: "Не удалось вставить изображение", fileTooLarge: "Файл {{fileName}} слишком большой (максимальный размер: {{size}})", }, - queued: { - menu: "Действия с сообщением в очереди", - moveUp: "Вверх", - moveDown: "Вниз", - delete: "Удалить", - discard: "Отменить", - retry: "Повторить", - sending: "Отправка...", - unconfirmed: "Не подтверждено", - failed: "Ошибка", - changedOnAnotherDevice: "Это сообщение в очереди изменено на другом устройстве", - deleteTitle: "Удалить сообщение из очереди?", - deleteMessage: "Оно будет удалено на всех устройствах, подключенных к этому агенту", - }, clientCommands: { archiveAgent: "Архивировать текущего агента", freshDraft: "Архивировать этого агента и создать новый черновик", @@ -315,75 +300,6 @@ export const ru: TranslationResources = { }, }, agentPanel: { - stream: { - tab: "Лента", - title: "Рядом с этим чатом", - description: "Вопросы, решения, ответы и файлы. Сначала новые.", - updateHost: "Обновите хост для работы с лентой", - updateHostDescription: "Для вопросов и ответов нужен новый хост. Ваши файлы показаны ниже.", - offline: "Переподключение. Сохранённые записи доступны, но статусы могут устареть.", - showAll: "Показать всё", - pending: "Ожидают ответа ({{count}})", - noPending: "Нет вопросов без ответа", - noPendingDescription: "Предыдущие вопросы и результаты доступны в полной ленте.", - emptyTitle: "Лента вашего чата", - emptyDescription: "Здесь появятся вопросы, запросы разрешений и итоговые ответы агента.", - backToChat: "Вернуться в чат", - retention: - "Последние 50 событий и собранные файлы. Запись начинается после обновления хоста; полный контекст остаётся в чате.", - question: "Вопрос", - decision: "Решение", - permission: "Запрос разрешения", - open: "Ожидает ответа", - reply_sent: "Ответ отправлен · решение не проверено", - pendingStatus: "Ожидается ваш ответ", - allowed: "Ответ принят", - denied: "Отклонено", - expired: "Больше не ожидает ответа", - completed: "Ход завершён", - failed: "Ошибка выполнения", - canceled: "Прервано", - outcomeDescription: "Статус описывает ход выполнения, а не подтверждает результат задачи.", - excerpt: "Отрывок. Полный контекст — в чате.", - showLess: "Свернуть", - read: "Читать", - replyInChat: "Ответить в чате", - viewStream: "Открыть ленту", - mutationFailed: "Не удалось сохранить изменение", - queueTab: "Очередь", - pinnedTab: "Пины потока", - filterAll: "Все", - filterQuestions: "Вопросы", - filterQAndA: "Вопросы и ответы", - filterFeatures: "Функции", - filterDecisions: "Решения", - filterOutcomes: "Итоги", - notePlaceholder: "Введите заметку или ссылку…", - addNote: "Добавить заметку", - answerLabel: "Ответ:", - unpin: "Открепить", - showAllAction: "Показать все", - showOpenOnlyAction: "Показать только открытые", - noPinnedItems: "Пинов потока пока нет", - noItemsFound: "Ничего не найдено", - featureRequest: "Запрос функции", - streamPin: "Пин потока", - qAndA: "Вопросы и ответы", - statusOpen: "Открыт", - statusReviewed: "Рассмотрено", - statusDone: "Готово", - }, - artifacts: { - chatTab: "Чат", - tab: "Артефакты ({{count}})", - emptyTitle: "Артефактов пока нет", - emptyDescription: "Созданные агентом файлы появятся здесь.", - updateHostTitle: "Обновите хост для работы с артефактами", - updateHostDescription: "Этот хост пока не поддерживает артефакты чата.", - previewMissing: "Preview unavailable", - open: "Открыть {{name}}", - openLabel: "Открыть", - }, states: { notFound: "Агент не найден", failedToLoad: "Не удалось загрузить агента", @@ -817,9 +733,7 @@ export const ru: TranslationResources = { reloadAgent: "Перезагрузить агента", reloadAgentTooltip: "Перезагрузите агента, чтобы обновить навыки, MCP или статус входа.", close: "Закрыть", - findInChat: "Найти в чате", renameTerminal: "Переименовать терминал", - viewArtifacts: "Открыть артефакты", renameAgent: "Переименовать агента", }, actions: { @@ -2185,26 +2099,10 @@ export const ru: TranslationResources = { }, }, realtimeVoice: { - listening: "Микрофон включён", - notListening: "Не слушает", - failure: { - "nothing-recognized": "Не расслышал. Повторите.", - "recognition-stalled": - "Распознавание речи перестало отвечать. Остановите и снова запустите голос.", - "recognition-failed": "Ошибка распознавания речи. Остановите и снова запустите голос.", - "recognition-unavailable": "Распознавание речи недоступно на хосте.", - "host-disconnected": "Хост отключён. Ввод с микрофона приостановлен до переподключения.", - "microphone-lost": "Микрофон потерян. Голосовой режим остановлен.", - }, - inputQueued: "Речь добавлена в очередь агента", - inputSent: "Речь отправлена агенту", - inputRemoved: "Речь удалена из очереди", - inputUnknown: "Статус доставки речи неизвестен", actions: { - interruptAgent: "Прервать агента", mute: "Отключить микрофон в голосовом режиме реального времени", unmute: "Включить микрофон в голосовом режиме реального времени", - stop: "Остановить голосовой режим реального времени", + stop: "Остановить голосовой режим реального времени и прервать текущий ответ", }, }, rewind: { diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 3f406f3a7cf..27c2f992372 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -18,7 +18,6 @@ export const zhCN: TranslationResources = { title: "查找", placeholder: "在窗格中查找", - updateHost: "更新主机以使用查找", close: "关闭查找", matches: "查找结果", previous: "上一个匹配项", @@ -190,7 +189,7 @@ export const zhCN: TranslationResources = { unmuteVoice: "取消静音", muteVoice: "静音", dictation: "听写", - interruptBeforeVoice: "更新主机以在 Agent 工作时使用语音", + interruptBeforeVoice: "启动语音模式前请先中断 Agent", }, attachments: { addImage: "添加图片", @@ -224,20 +223,6 @@ export const zhCN: TranslationResources = { pasteImageFailed: "无法粘贴图片", fileTooLarge: "{{fileName}} is too large (max {{size}})", }, - queued: { - menu: "队列消息操作", - moveUp: "上移", - moveDown: "下移", - delete: "删除", - discard: "丢弃", - retry: "重试", - sending: "发送中...", - unconfirmed: "未确认", - failed: "失败", - changedOnAnotherDevice: "此队列消息已在另一台设备上更改", - deleteTitle: "删除队列消息?", - deleteMessage: "它将从连接此代理的所有设备上移除", - }, clientCommands: { archiveAgent: "归档当前 Agent", freshDraft: "归档此 Agent 并开始新的草稿", @@ -313,74 +298,6 @@ export const zhCN: TranslationResources = { }, }, agentPanel: { - stream: { - tab: "动态", - title: "伴随此聊天", - description: "问题、决策、回复和文件,最新内容在前。", - updateHost: "更新主机以使用动态", - updateHostDescription: "问题和回复需要更新的主机。文件产物仍在下方。", - offline: "正在重连。已保存的内容仍可查看;待处理状态可能已过时。", - showAll: "显示全部", - pending: "需要回复({{count}})", - noPending: "没有待回复的内容", - noPendingDescription: "之前的问题和结果仍在完整动态中。", - emptyTitle: "此聊天的伴随动态", - emptyDescription: "智能体工作时,问题、审批和最终回复会出现在这里。", - backToChat: "返回聊天", - retention: "最近50条记录和收集的文件。主机更新后开始记录;完整上下文保留在聊天中。", - question: "问题", - decision: "决策", - permission: "权限请求", - open: "等待回复", - reply_sent: "已发送回复 · 决策尚未验证", - pendingStatus: "等待你的回复", - allowed: "回复已接受", - denied: "已拒绝", - expired: "不再待处理", - completed: "回合结束", - failed: "回合失败", - canceled: "已中断", - outcomeDescription: "运行状态描述回合状态,并不代表任务已验证完成。", - excerpt: "内容摘录。完整上下文在聊天中。", - showLess: "收起", - read: "阅读", - replyInChat: "在聊天中回复", - viewStream: "查看动态", - mutationFailed: "无法保存该更改", - queueTab: "队列", - pinnedTab: "流固定项", - filterAll: "全部", - filterQuestions: "问题", - filterQAndA: "问答", - filterFeatures: "功能", - filterDecisions: "决定", - filterOutcomes: "结果", - notePlaceholder: "输入备注或链接…", - addNote: "添加备注", - answerLabel: "回答:", - unpin: "取消固定", - showAllAction: "显示全部", - showOpenOnlyAction: "仅显示待回复", - noPinnedItems: "还没有流固定项", - noItemsFound: "未找到任何项目", - featureRequest: "功能请求", - streamPin: "流固定项", - qAndA: "问答", - statusOpen: "待处理", - statusReviewed: "已查看", - statusDone: "已完成", - }, - artifacts: { - chatTab: "聊天", - tab: "产物 ({{count}})", - emptyTitle: "暂无产物", - emptyDescription: "此 Agent 创建的文件将显示在这里。", - updateHostTitle: "更新 Host 以使用产物", - updateHostDescription: "此 Host 尚不支持每个聊天的产物。", - previewMissing: "Preview unavailable", - open: "打开 {{name}}", - openLabel: "打开", - }, states: { notFound: "未找到 Agent", failedToLoad: "加载 Agent 失败", @@ -808,9 +725,7 @@ export const zhCN: TranslationResources = { reloadAgent: "重新加载 Agent", reloadAgentTooltip: "重新加载 Agent 以更新 skills、MCPs 或登录状态。", close: "关闭", - findInChat: "在聊天中查找", renameTerminal: "重命名 Terminal", - viewArtifacts: "查看产出文件", renameAgent: "重命名 Agent", }, actions: { @@ -2126,25 +2041,10 @@ export const zhCN: TranslationResources = { }, }, realtimeVoice: { - listening: "麦克风已开启", - notListening: "未在收听", - failure: { - "nothing-recognized": "没听清,请再说一遍。", - "recognition-stalled": "语音识别无响应。请停止并重新开始语音。", - "recognition-failed": "语音识别失败。请停止并重新开始语音。", - "recognition-unavailable": "主机上的语音识别不可用。", - "host-disconnected": "主机已断开连接。重新连接前麦克风输入已暂停。", - "microphone-lost": "麦克风已丢失。语音已停止。", - }, - inputQueued: "语音已加入智能体队列", - inputSent: "语音已发送给智能体", - inputRemoved: "语音已从队列移除", - inputUnknown: "语音送达状态未知", actions: { - interruptAgent: "中断智能体", mute: "静音 realtime voice", unmute: "取消静音 realtime voice", - stop: "停止 realtime voice", + stop: "停止 realtime voice 并中断 turn", }, }, rewind: { diff --git a/packages/app/src/panels/agent-panel.tsx b/packages/app/src/panels/agent-panel.tsx index ae2bd1f67ad..cf582a99f50 100644 --- a/packages/app/src/panels/agent-panel.tsx +++ b/packages/app/src/panels/agent-panel.tsx @@ -23,17 +23,10 @@ import { useStoreWithEqualityFn } from "zustand/traditional"; import { useAgentStreamTail } from "@/agent-stream/use-agent-stream-tail"; import { AgentStreamView, type AgentStreamViewHandle } from "@/agent-stream/view"; import { ArchivedAgentCallout } from "@/components/archived-agent-callout"; -import { CompanionFeed } from "@/companion-stream/feed"; -import type { CompanionEntry } from "@getpaseo/protocol/companion-stream"; import { ComposerDock } from "@/composer/dock"; import { FileDropZone } from "@/components/file-drop/file-drop-zone"; -import { - RetainedPanel, - RetainedPanelActivity, - useRetainedPanelActive, -} from "@/components/retained-panel"; +import { useRetainedPanelActive } from "@/components/retained-panel"; import { RetainedChatContent } from "./retained-chat-content"; -import { AgentViewSwitcher } from "@/components/agent-view-switcher"; import { Composer } from "@/composer"; import { AgentCommandsProvider } from "@/agent-commands"; import { @@ -73,7 +66,6 @@ import { PaneSubtitle } from "@/panels/pane-subtitle"; import { definePanel } from "@/panels/panel-registry"; import { RenderProfile } from "@/utils/render-profiler"; import { buildDraftPanelDescriptor } from "@/panels/draft-panel-descriptor"; -import { useHostFeature } from "@/runtime/host-features"; import { type HostRuntimeConnectionStatus, useHostRuntimeClient, @@ -91,7 +83,6 @@ import { type DraftConversation, useDraftTimeline } from "@/composer/draft/timel import { AgentTracks } from "@/panels/agent-tracks"; import { OverlayDismissalScope } from "@/components/ui/overlay-dismissal"; import { ParentAgentCallout, useParentAgentId } from "@/subagents/parent"; -import { useAgentViewStore } from "@/stores/agent-view-store"; import { useCreateFlowStore } from "@/stores/create-flow-store"; import { buildDraftStoreKey, generateDraftId } from "@/stores/draft-keys"; import { @@ -129,8 +120,6 @@ interface ChatAgentStateShape { options?: Agent["options"]; controls?: Agent["controls"]; lastError?: Agent["lastError"] | null; - artifacts?: Agent["artifacts"]; - companionEntries?: Agent["companionEntries"]; } interface ChatAgentSelectedState extends ChatAgentStateShape { @@ -191,8 +180,6 @@ function selectChatAgentState( options: agent.options, controls: agent.controls, lastError: agent.lastError ?? null, - artifacts: agent.artifacts, - companionEntries: agent.companionEntries, archivedAt: agent.archivedAt ?? null, requiresAttention: agent.requiresAttention ?? false, attentionReason: agent.attentionReason ?? null, @@ -1049,8 +1036,6 @@ function ChatAgentContent({ ); } -const EMPTY_COMPANION_ENTRIES: readonly CompanionEntry[] = []; - const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ serverId, workspaceId, @@ -1109,34 +1094,13 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ onAttentionPromptSend: () => void; onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void; }) { + const { t } = useTranslation(); // The workspace sheet is for looking; Open as tab brings the agent back with its composer. const paneHost = usePaneContext().host; const showsComposer = draft !== null || paneHost !== "sheet"; // The dock lays out fullscreen for the same session the composer edits in. const composerEditingSession = useComposerEditingSession("chat"); const isComposerFullscreen = useComposerFullscreen(composerEditingSession); - const selectedView = useAgentViewStore( - (state) => state.selectedViews[`${serverId}:${agentId}`] || "chat", - ); - const setSelectedView = useAgentViewStore((state) => state.setSelectedView); - const isChatVisible = selectedView !== "artifacts"; - const handleSetSelectedView = useCallback( - (view: "chat" | "artifacts") => { - setSelectedView(serverId, agentId, view); - }, - [serverId, agentId, setSelectedView], - ); - const handleReturnToChat = useCallback(() => { - handleSetSelectedView("chat"); - }, [handleSetSelectedView]); - const handleReplyInChat = useCallback(() => { - handleReturnToChat(); - streamViewRef.current?.scrollToBottom("jump-to-bottom"); - }, [handleReturnToChat, streamViewRef]); - // COMPAT(companionStreamPortV1): added in v0.11.0-beta.3-fork, remove after 2027-04-01. - // Gate companion controls and mutations once. Supplied file snapshots remain - // readable on older hosts without reconstructing a companion stream. - const companionStreamSupported = useHostFeature(serverId, "companionStreamPortV1"); const hasActiveComposer = !agentState.archivedAt && !isArchivingCurrentAgent; const parentAgentId = useParentAgentId(serverId, agentId); // With a composer the parent is a pill above it; without one, the box takes the composer's place. @@ -1195,7 +1159,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ - - {showsComposer ? null : } - - - - {hasActiveComposer && !draft ? ( - - ) : null} - - + + {showsComposer ? null : } + + + + {hasActiveComposer && !draft ? ( + + ) : null} + ); const dockContent = ( - + {streamContent} - + + {showHistorySyncError ? ( + + ) : null} + ); const dockOverlay = ( - - ); + <> + {showHistorySyncOverlay ? ( + + + + ) : null} - const composerSlot = ( - - - {composerSection} - - + + ); const dock = ( {dockContent} - {composerSlot} + {composerSection} {dockOverlay} ); @@ -1327,7 +1264,14 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ > {dock} - + + {isArchivingCurrentAgent ? ( + + + {t("agentPanel.states.archivingTitle")} + {t("agentPanel.states.archivingSubtitle")} + + ) : null} ); @@ -1340,106 +1284,6 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ }); }); -function computeInitialHistoryLoading( - routeBottomAnchorRequest: RouteBottomAnchorRequest, - hasCachedHistory: boolean, - showHistorySyncError: boolean, -): boolean { - return ( - routeBottomAnchorRequest?.reason === "initial-entry" && - !hasCachedHistory && - !showHistorySyncError - ); -} - -const ChatAgentDockContent = memo(function ChatAgentDockContent({ - selectedView, - onSelectView, - children, - isChatVisible, - serverId, - agentId, - cwd, - companionEntries, - artifacts, - companionStreamSupported, - onOpenWorkspaceFile, - onReturnToChat, - onReplyInChat, - toast, - showHistorySyncError, - isRetryingHistorySync, - retryTimelineSync, -}: { - selectedView: React.ComponentProps["value"]; - onSelectView: React.ComponentProps["onValueChange"]; - children: ReactNode; - isChatVisible: boolean; - serverId: string; - agentId: string; - cwd: string; - companionEntries?: readonly CompanionEntry[]; - artifacts?: React.ComponentProps["artifacts"]; - companionStreamSupported: boolean; - onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void; - onReturnToChat: () => void; - onReplyInChat: () => void; - toast: ToastApi; - showHistorySyncError: boolean; - isRetryingHistorySync: boolean; - retryTimelineSync: () => void; -}) { - return ( - - - {children} - {isChatVisible ? null : ( - - )} - {showHistorySyncError && isChatVisible ? ( - - ) : null} - - ); -}); - -const ChatAgentDockOverlay = memo(function ChatAgentDockOverlay({ - isChatVisible, - showHistorySyncOverlay, - timelineSync, - toast, - dismiss, -}: { - isChatVisible: boolean; - showHistorySyncOverlay: boolean; - timelineSync: AgentScreenReadySyncState | null; - toast: ToastState | null; - dismiss: () => void; -}) { - return ( - <> - {showHistorySyncOverlay && isChatVisible ? ( - - - - ) : null} - - - - ); -}); - function wrapAgentCommandProvider({ enabled, serverId, @@ -1465,20 +1309,6 @@ function wrapAgentCommandProvider({ ); } -function ArchivingOverlay({ isArchivingCurrentAgent }: { isArchivingCurrentAgent: boolean }) { - const { t } = useTranslation(); - if (!isArchivingCurrentAgent) { - return null; - } - return ( - - - {t("agentPanel.states.archivingTitle")} - {t("agentPanel.states.archivingSubtitle")} - - ); -} - function ChatSurface({ children, disabled, @@ -1983,8 +1813,6 @@ const styles = StyleSheet.create((theme) => ({ overflow: "hidden", ...(isWeb ? { userSelect: "none" as const } : {}), }, - fullscreenComposer: { flex: 1, minHeight: 0 }, - hiddenPane: { display: "none" }, timelineSyncCalloutRail: { width: "100%", alignItems: "center", diff --git a/packages/app/src/runtime/host-features.test.ts b/packages/app/src/runtime/host-features.test.ts deleted file mode 100644 index c4186816309..00000000000 --- a/packages/app/src/runtime/host-features.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { selectHostFeature, type HostFeatureSessionState } from "./host-features"; - -function stateWith(serverId: string, features: Record | undefined) { - return { - sessions: { - [serverId]: { serverInfo: features === undefined ? null : { features } }, - }, - } as unknown as HostFeatureSessionState; -} - -describe("selectHostFeature", () => { - it("reports companionStreamPortV1 as supported when the daemon advertises it", () => { - const state = stateWith("srv", { companionStreamPortV1: true }); - expect(selectHostFeature(state, "srv", "companionStreamPortV1")).toBe(true); - }); - - it("reports the feature as absent on an older daemon without it", () => { - // Old daemons never send the flag, and unknown feature keys must not - // read as supported: the Stream panel shows its update-host notice. - const state = stateWith("srv", { providerUsageList: true }); - expect(selectHostFeature(state, "srv", "companionStreamPortV1")).toBe(false); - }); - - it("is absent before the session has server info", () => { - expect(selectHostFeature(stateWith("srv", undefined), "srv", "companionStreamPortV1")).toBe( - false, - ); - expect(selectHostFeature(stateWith("srv", undefined), "missing", "companionStreamPortV1")).toBe( - false, - ); - }); -}); diff --git a/packages/app/src/runtime/host-runtime.ts b/packages/app/src/runtime/host-runtime.ts index babce5975bf..15a86b7bb4c 100644 --- a/packages/app/src/runtime/host-runtime.ts +++ b/packages/app/src/runtime/host-runtime.ts @@ -576,8 +576,6 @@ function createDefaultDeps( : undefined; const appCapabilities = { ...browserAutomationCapabilities, - // COMPAT(companionStreamPortV1): added in v0.11.0-beta.3-fork, remove after 2027-04-01. - [CLIENT_CAPS.companionStreamPortV1]: true, }; return { diff --git a/packages/app/src/runtime/replica-cache/index.ts b/packages/app/src/runtime/replica-cache/index.ts index 7ea2519516e..e5bee785d3c 100644 --- a/packages/app/src/runtime/replica-cache/index.ts +++ b/packages/app/src/runtime/replica-cache/index.ts @@ -6,8 +6,6 @@ import { WorkspaceGitHubRuntimePayloadSchema, } from "@getpaseo/protocol/messages"; import { AgentProviderSchema } from "@getpaseo/protocol/provider-manifest"; -import { CompanionEntrySchema } from "@getpaseo/protocol/companion-stream"; -import { AgentArtifactSchema } from "@getpaseo/protocol/messages"; import type { PluginTimelineData } from "@getpaseo/plugin"; import { normalizeProjectDescriptor, @@ -259,8 +257,6 @@ const StoredAgentSnapshotSchema = z.strictObject({ attentionReason: z.enum(["finished", "error", "permission"]).nullable().optional(), attentionTimestamp: IsoDateSchema.nullable().optional(), archivedAt: IsoDateSchema.nullable().optional(), - artifacts: z.array(AgentArtifactSchema).optional(), - companionEntries: z.array(CompanionEntrySchema).optional(), }); const StoredAgentSchema = z.strictObject({ @@ -665,15 +661,6 @@ function serializeAgentCapabilities( }; } -function serializeStreamStateFields( - agent: Agent, -): Pick { - return { - ...(agent.artifacts ? { artifacts: agent.artifacts } : {}), - ...(agent.companionEntries ? { companionEntries: agent.companionEntries } : {}), - }; -} - function serializeAgent(agent: Agent): StoredAgent { const snapshot = { id: agent.id, @@ -708,7 +695,6 @@ function serializeAgent(agent: Agent): StoredAgent { attentionReason: agent.attentionReason ?? null, attentionTimestamp: agent.attentionTimestamp?.toISOString() ?? null, archivedAt: agent.archivedAt?.toISOString() ?? null, - ...serializeStreamStateFields(agent), }; return { snapshot, diff --git a/packages/app/src/screens/workspace/compact-workspace-header/tab-switcher.tsx b/packages/app/src/screens/workspace/compact-workspace-header/tab-switcher.tsx index de5610103b1..d8fd63f5d80 100644 --- a/packages/app/src/screens/workspace/compact-workspace-header/tab-switcher.tsx +++ b/packages/app/src/screens/workspace/compact-workspace-header/tab-switcher.tsx @@ -147,8 +147,6 @@ interface MobileWorkspaceTabSwitcherProps { onCloseTabsAbove: (tabId: string) => Promise | void; onCloseTabsBelow: (tabId: string) => Promise | void; onCloseOtherTabs: (tabId: string) => Promise | void; - onViewArtifacts: (agentId: string) => void; - onFindInChat: (agentId: string) => void; } function MobileWorkspaceTabOption({ @@ -170,8 +168,6 @@ function MobileWorkspaceTabOption({ onCloseTabsAbove, onCloseTabsBelow, onCloseOtherTabs, - onViewArtifacts, - onFindInChat, }: { tab: WorkspaceTabDescriptor; tabIndex: number; @@ -191,8 +187,6 @@ function MobileWorkspaceTabOption({ onCloseTabsAbove: (tabId: string) => Promise | void; onCloseTabsBelow: (tabId: string) => Promise | void; onCloseOtherTabs: (tabId: string) => Promise | void; - onViewArtifacts: (agentId: string) => void; - onFindInChat: (agentId: string) => void; }) { const { t } = useTranslation(); const startSideConversation = useStartSideConversation({ @@ -215,8 +209,6 @@ function MobileWorkspaceTabOption({ reloadAgentTooltip: t("workspace.tabs.menu.reloadAgentTooltip"), newSideConversation: t("sideConversations.actions.new"), close: t("workspace.tabs.menu.close"), - viewArtifacts: t("workspace.tabs.menu.viewArtifacts", { defaultValue: "View artifacts" }), - findInChat: t("workspace.tabs.menu.findInChat"), }), [t], ); @@ -238,8 +230,6 @@ function MobileWorkspaceTabOption({ onCloseTabsBefore: onCloseTabsAbove, onCloseTabsAfter: onCloseTabsBelow, onCloseOtherTabs, - onViewArtifacts, - onFindInChat, labels: tabMenuLabels, }); @@ -318,8 +308,6 @@ export const MobileWorkspaceTabSwitcher = memo(function MobileWorkspaceTabSwitch onCloseTabsAbove, onCloseTabsBelow, onCloseOtherTabs, - onViewArtifacts, - onFindInChat, }: MobileWorkspaceTabSwitcherProps) { const { t } = useTranslation(); const tabFallbackLabels = useMemo( @@ -442,8 +430,6 @@ export const MobileWorkspaceTabSwitcher = memo(function MobileWorkspaceTabSwitch onCloseTabsAbove={onCloseTabsAbove} onCloseTabsBelow={onCloseTabsBelow} onCloseOtherTabs={onCloseOtherTabs} - onViewArtifacts={onViewArtifacts} - onFindInChat={onFindInChat} /> ); }, @@ -463,8 +449,6 @@ export const MobileWorkspaceTabSwitcher = memo(function MobileWorkspaceTabSwitch onCloseTabsAbove, onCloseTabsBelow, onCloseOtherTabs, - onViewArtifacts, - onFindInChat, ], ); diff --git a/packages/app/src/screens/workspace/workspace-desktop-tabs-row.tsx b/packages/app/src/screens/workspace/workspace-desktop-tabs-row.tsx index 1391c62670d..25ba966baa6 100644 --- a/packages/app/src/screens/workspace/workspace-desktop-tabs-row.tsx +++ b/packages/app/src/screens/workspace/workspace-desktop-tabs-row.tsx @@ -21,7 +21,6 @@ import { Copy, History, MessageCirclePlus, - Search, Pencil, RotateCw, Columns2, @@ -133,7 +132,6 @@ const AGENT_TOOLTIP_TITLE_MAX_LENGTH = 80; const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); const ThemedX = withUnistyles(X); -const ThemedSearch = withUnistyles(Search); const ThemedCopy = withUnistyles(Copy); const ThemedRotateCw = withUnistyles(RotateCw); @@ -469,8 +467,6 @@ function TabContextMenuItem({ return ; case "x": return ; - case "search": - return ; default: return undefined; } @@ -1216,8 +1212,6 @@ function ResolvedWorkspaceDesktopTabsRow({ reloadAgentTooltip: t("workspace.tabs.menu.reloadAgentTooltip"), newSideConversation: t("sideConversations.actions.new"), close: t("workspace.tabs.menu.close"), - viewArtifacts: t("workspace.tabs.menu.viewArtifacts", { defaultValue: "View artifacts" }), - findInChat: t("workspace.tabs.menu.findInChat"), }), [t], ); diff --git a/packages/app/src/screens/workspace/workspace-screen.tsx b/packages/app/src/screens/workspace/workspace-screen.tsx index 4d1954ec9f9..0cd3958da2f 100644 --- a/packages/app/src/screens/workspace/workspace-screen.tsx +++ b/packages/app/src/screens/workspace/workspace-screen.tsx @@ -147,7 +147,6 @@ import { createWorkspaceBrowser, useBrowserStore } from "@/desktop/browser/store import { getDesktopHost } from "@/desktop/host"; import { buildProviderCommand } from "@/utils/provider-command-templates"; import { generateDraftId } from "@/stores/draft-keys"; -import { useAgentViewStore } from "@/stores/agent-view-store"; import { resolveWorkspaceRouteId } from "@/utils/workspace-identity"; import { useOpenAgentTabLabels } from "@/subagents/use-open-agent-tab-labels"; import { WorkspaceTabPresentationResolver } from "@/screens/workspace/workspace-tab-presentation"; @@ -2198,42 +2197,6 @@ function WorkspaceScreenContent({ [toast, t], ); - const setFindOpen = useAgentViewStore((state) => state.setFindOpen); - const handleFindInChat = useCallback( - (agentId: string) => { - setFindOpen(normalizedServerId, agentId, true); - if (persistenceKey) { - const tabTarget = { kind: "agent", agentId } as WorkspaceTabTarget; - const tabId = openWorkspaceTabFocused(persistenceKey, tabTarget); - if (tabId) { - navigateToTabId(tabId); - } - } - }, - [normalizedServerId, persistenceKey, openWorkspaceTabFocused, navigateToTabId, setFindOpen], - ); - - const setAgentSelectedView = useAgentViewStore((state) => state.setSelectedView); - const handleViewArtifacts = useCallback( - (agentId: string) => { - setAgentSelectedView(normalizedServerId, agentId, "artifacts"); - if (persistenceKey) { - const tabTarget = { kind: "agent", agentId } as WorkspaceTabTarget; - const tabId = openWorkspaceTabFocused(persistenceKey, tabTarget); - if (tabId) { - navigateToTabId(tabId); - } - } - }, - [ - normalizedServerId, - persistenceKey, - openWorkspaceTabFocused, - navigateToTabId, - setAgentSelectedView, - ], - ); - const handleCopyFilePath = useCallback( async (path: string) => { if (!path) return; @@ -3522,8 +3485,6 @@ function WorkspaceScreenContent({ onCloseTabsAbove={actions.closeAbove} onCloseTabsBelow={actions.closeBelow} onCloseOtherTabs={actions.closeOthers} - onViewArtifacts={handleViewArtifacts} - onFindInChat={handleFindInChat} /> ); }, @@ -3541,8 +3502,6 @@ function WorkspaceScreenContent({ handleReloadAgent, handleRenameTab, handleCloseTabById, - handleViewArtifacts, - handleFindInChat, ], ); // Without a pane's tabs (above a split) the header carries workspace controls only: split panes diff --git a/packages/app/src/screens/workspace/workspace-tab-menu.ts b/packages/app/src/screens/workspace/workspace-tab-menu.ts index 0c908066fa0..8cb0d15421b 100644 --- a/packages/app/src/screens/workspace/workspace-tab-menu.ts +++ b/packages/app/src/screens/workspace/workspace-tab-menu.ts @@ -20,8 +20,6 @@ export interface WorkspaceTabMenuLabels { reloadAgentTooltip: string; newSideConversation: string; close: string; - viewArtifacts: string; - findInChat: string; } export const DEFAULT_WORKSPACE_TAB_MENU_LABELS: WorkspaceTabMenuLabels = { @@ -39,8 +37,6 @@ export const DEFAULT_WORKSPACE_TAB_MENU_LABELS: WorkspaceTabMenuLabels = { reloadAgentTooltip: i18n.t("workspace.tabs.menu.reloadAgentTooltip"), newSideConversation: i18n.t("sideConversations.actions.new"), close: i18n.t("workspace.tabs.menu.close"), - viewArtifacts: i18n.t("workspace.tabs.menu.viewArtifacts", { defaultValue: "View artifacts" }), - findInChat: i18n.t("workspace.tabs.menu.findInChat", { defaultValue: "Find in chat" }), }; export type WorkspaceTabMenuEntry = @@ -56,9 +52,7 @@ export type WorkspaceTabMenuEntry = | "copy-x" | "pencil" | "message-circle-plus" - | "file-code-2" - | "x" - | "search"; + | "x"; hint?: string; tooltip?: string; disabled?: boolean; @@ -97,8 +91,6 @@ interface BuildWorkspaceTabMenuEntriesInput { onCloseTabsBefore: (tabId: string) => Promise | void; onCloseTabsAfter: (tabId: string) => Promise | void; onCloseOtherTabs: (tabId: string) => Promise | void; - onViewArtifacts?: (agentId: string) => void; - onFindInChat?: (agentId: string) => void; labels?: WorkspaceTabMenuLabels; } @@ -233,43 +225,6 @@ export function buildWorkspaceTabMenuEntries( if (tab.target.kind === "agent") { const { agentId } = tab.target; - if (surface === "mobile" && input.onViewArtifacts) { - entries.push({ - kind: "item", - key: "view-artifacts", - label: labels.viewArtifacts, - icon: "file-code-2", - testID: `${menuTestIDBase}-view-artifacts`, - onSelect: () => { - input.onViewArtifacts?.(agentId); - }, - }); - if (!input.onFindInChat) { - entries.push({ - kind: "separator", - key: "view-artifacts-separator", - }); - } - } - - // Native has no Cmd+F equivalent, so the tab menu is how Find is reached. - // Web opens it from the keyboard shortcut in `chat-find/index.web.tsx`. - if (surface === "mobile" && input.onFindInChat) { - entries.push({ - kind: "item", - key: "find-in-chat", - label: labels.findInChat, - icon: "search", - testID: `${menuTestIDBase}-find-in-chat`, - onSelect: () => { - input.onFindInChat?.(agentId); - }, - }); - entries.push({ - kind: "separator", - key: "find-in-chat-separator", - }); - } entries.push({ kind: "item", key: "copy-resume-command", diff --git a/packages/app/src/screens/workspace/workspace-tab-trailing-accessory.test.tsx b/packages/app/src/screens/workspace/workspace-tab-trailing-accessory.test.tsx index 3fd395195dc..9851125cc81 100644 --- a/packages/app/src/screens/workspace/workspace-tab-trailing-accessory.test.tsx +++ b/packages/app/src/screens/workspace/workspace-tab-trailing-accessory.test.tsx @@ -40,7 +40,6 @@ vi.mock("lucide-react-native", () => { MessageCirclePlus: StubIcon, Pencil: StubIcon, RotateCw: StubIcon, - Search: StubIcon, X: StubIcon, }; }); diff --git a/packages/app/src/screens/workspace/workspace-tab-trailing-accessory.tsx b/packages/app/src/screens/workspace/workspace-tab-trailing-accessory.tsx index 872c1f87d2e..8a8cfab3144 100644 --- a/packages/app/src/screens/workspace/workspace-tab-trailing-accessory.tsx +++ b/packages/app/src/screens/workspace/workspace-tab-trailing-accessory.tsx @@ -11,7 +11,6 @@ import { MessageCirclePlus, Pencil, RotateCw, - Search, X, } from "lucide-react-native"; import { @@ -34,7 +33,6 @@ const ThemedCopyX = withUnistyles(CopyX); const ThemedMessageCirclePlus = withUnistyles(MessageCirclePlus); const ThemedPencil = withUnistyles(Pencil); const ThemedX = withUnistyles(X); -const ThemedSearch = withUnistyles(Search); const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); @@ -68,8 +66,6 @@ function MobileTabDropdownMenuItem({ return ; case "x": return ; - case "search": - return ; default: return undefined; } diff --git a/packages/app/src/stores/agent-view-store.ts b/packages/app/src/stores/agent-view-store.ts deleted file mode 100644 index 2d839da4fab..00000000000 --- a/packages/app/src/stores/agent-view-store.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { create } from "zustand"; - -type AgentView = "chat" | "artifacts"; - -interface AgentViewStoreState { - selectedViews: Record; - setSelectedView: (serverId: string, agentId: string, view: AgentView) => void; - getSelectedView: (serverId: string, agentId: string) => AgentView; - /** - * Find is an overlay on Chat, not a sibling view, so it is tracked separately. - * Keyed by `${serverId}:${agentId}` because the tab menu opens it for an agent - * the panel may not be mounted for yet. - */ - findOpen: Record; - setFindOpen: (serverId: string, agentId: string, open: boolean) => void; -} - -// Find state and the Chat/Artifacts selection have separate lifetimes and keys. -export const useAgentViewStore = create()((set, get) => ({ - selectedViews: {}, - setSelectedView: (serverId, agentId, view) => { - set((state) => ({ - selectedViews: { - ...state.selectedViews, - [`${serverId}:${agentId}`]: view, - }, - })); - }, - getSelectedView: (serverId, agentId) => { - return get().selectedViews[`${serverId}:${agentId}`] || "chat"; - }, - findOpen: {}, - setFindOpen: (serverId, agentId, open) => { - set((state) => ({ - findOpen: { - ...state.findOpen, - [`${serverId}:${agentId}`]: open, - }, - })); - }, -})); diff --git a/packages/app/src/stores/queue-outbox-store/index.ts b/packages/app/src/stores/queue-outbox-store/index.ts deleted file mode 100644 index f6529a56d4a..00000000000 --- a/packages/app/src/stores/queue-outbox-store/index.ts +++ /dev/null @@ -1,210 +0,0 @@ -import { create } from "zustand"; -import { persist } from "zustand/middleware"; -import AsyncStorage from "@react-native-async-storage/async-storage"; -import { z } from "zod"; -import type { AgentQueueSnapshot } from "@getpaseo/protocol/messages"; - -import { createValidatedPersistStorage } from "@/storage/validated-persist-storage"; -import { - flushQueueOutbox, - PendingQueueEnqueueSchema, - type PendingQueueEnqueue, - type QueueOutboxFlushClient, -} from "./model"; - -export { - QUEUE_OUTBOX_MAX_ATTEMPTS, - type PendingQueueEnqueue, - type QueueOutboxFlushClient, -} from "./model"; - -const PersistedQueueOutboxSchema = z.object({ - entries: z.record(z.string(), PendingQueueEnqueueSchema), -}); - -type PersistedQueueOutbox = z.infer; - -interface QueueOutboxActions { - add: (entry: Omit) => void; - remove: (itemId: string) => void; - bumpAttempts: (itemId: string) => void; - /** Parks an exhausted entry in the visible failed state. */ - markFailed: (itemId: string) => void; - /** Explicit retry: clears the failed state and the attempt streak. */ - retryEntry: (itemId: string) => void; - entriesForServer: (serverId: string) => PendingQueueEnqueue[]; - entriesForAgent: (serverId: string, agentId: string) => PendingQueueEnqueue[]; -} - -type QueueOutboxStore = PersistedQueueOutbox & QueueOutboxActions; - -function sortByCreation(entries: PendingQueueEnqueue[]): PendingQueueEnqueue[] { - return entries.sort((a, b) => a.createdAt - b.createdAt); -} - -/** - * The durable outbox for daemon-owned queue writes. Entries are keyed by item - * id (unique across servers by construction) and survive app restarts, so an - * enqueue that never reached the daemon is retried instead of lost. - */ -export const useQueueOutboxStore = create()( - persist( - (set, get) => ({ - entries: {}, - - add: (entry) => { - set((state) => ({ - entries: { - ...state.entries, - [entry.itemId]: { ...entry, createdAt: Date.now(), attempts: 0 }, - }, - })); - }, - - remove: (itemId) => { - set((state) => { - if (!(itemId in state.entries)) { - return state; - } - const entries = { ...state.entries }; - delete entries[itemId]; - return { entries }; - }); - }, - - bumpAttempts: (itemId) => { - set((state) => { - const entry = state.entries[itemId]; - if (!entry) { - return state; - } - return { - entries: { - ...state.entries, - [itemId]: { ...entry, attempts: entry.attempts + 1 }, - }, - }; - }); - }, - - markFailed: (itemId) => { - set((state) => { - const entry = state.entries[itemId]; - if (!entry) { - return state; - } - return { - entries: { - ...state.entries, - [itemId]: { ...entry, failedAt: Date.now() }, - }, - }; - }); - }, - - retryEntry: (itemId) => { - set((state) => { - const entry = state.entries[itemId]; - if (!entry) { - return state; - } - return { - entries: { - ...state.entries, - [itemId]: { ...entry, attempts: 0, failedAt: undefined }, - }, - }; - }); - }, - - entriesForServer: (serverId) => - sortByCreation(Object.values(get().entries).filter((entry) => entry.serverId === serverId)), - - entriesForAgent: (serverId, agentId) => - sortByCreation( - Object.values(get().entries).filter( - (entry) => entry.serverId === serverId && entry.agentId === agentId, - ), - ), - }), - { - name: "paseo-queue-outbox", - version: 1, - storage: createValidatedPersistStorage(AsyncStorage, PersistedQueueOutboxSchema), - partialize: ({ entries }) => ({ entries }), - }, - ), -); - -/** - * Retries one failed entry — the explicit user action — without touching any - * other pending entry for the server. - */ -export async function retryFailedOutboxEntry(input: { - itemId: string; - client: QueueOutboxFlushClient; - applySnapshot: (snapshot: AgentQueueSnapshot) => void; -}): Promise { - const store = useQueueOutboxStore.getState(); - const entry = store.entries[input.itemId]; - if (!entry || entry.failedAt === undefined) { - return; - } - store.retryEntry(input.itemId); - await flushQueueOutbox({ - serverId: entry.serverId, - outbox: { - list: () => { - const current = useQueueOutboxStore.getState().entries[input.itemId]; - return current && current.failedAt === undefined ? [current] : []; - }, - remove: store.remove, - bumpAttempts: store.bumpAttempts, - markFailed: store.markFailed, - }, - client: input.client, - applySnapshot: input.applySnapshot, - }); -} - -const flushesInFlight = new Set(); - -/** - * Flushes this store's un-acked enqueues for one server. Called on every - * (re)connect that advertises the durable queue feature; concurrent calls for - * the same server coalesce so a burst of status messages cannot double-send. - * Failed entries are skipped: retrying one is an explicit user decision, never - * an automatic side effect of a reconnect. - */ -export async function flushQueueOutboxForServer(input: { - serverId: string; - client: QueueOutboxFlushClient; - applySnapshot: (snapshot: AgentQueueSnapshot) => void; - onEntryExhausted?: (entry: PendingQueueEnqueue) => void; -}): Promise { - if (flushesInFlight.has(input.serverId)) { - return; - } - flushesInFlight.add(input.serverId); - try { - const store = useQueueOutboxStore.getState(); - await flushQueueOutbox({ - serverId: input.serverId, - outbox: { - list: (serverId) => - useQueueOutboxStore - .getState() - .entriesForServer(serverId) - .filter((entry) => entry.failedAt === undefined), - remove: store.remove, - bumpAttempts: store.bumpAttempts, - markFailed: store.markFailed, - }, - client: input.client, - applySnapshot: input.applySnapshot, - ...(input.onEntryExhausted ? { onEntryExhausted: input.onEntryExhausted } : {}), - }); - } finally { - flushesInFlight.delete(input.serverId); - } -} diff --git a/packages/app/src/stores/queue-outbox-store/model.test.ts b/packages/app/src/stores/queue-outbox-store/model.test.ts deleted file mode 100644 index 534e55972c7..00000000000 --- a/packages/app/src/stores/queue-outbox-store/model.test.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { describe, expect, test } from "vitest"; - -import type { AgentQueueSnapshot } from "@getpaseo/protocol/messages"; - -import { - flushQueueOutbox, - QUEUE_OUTBOX_MAX_ATTEMPTS, - type PendingQueueEnqueue, - type QueueOutboxAccess, -} from "./model"; - -function pendingEntry(overrides: Partial = {}): PendingQueueEnqueue { - return { - serverId: "server-1", - agentId: "agent-1", - itemId: "item-1", - text: "hello", - intent: "queue", - images: [], - attachments: [], - composerAttachments: [], - createdAt: 1, - attempts: 0, - ...overrides, - }; -} - -function snapshotWith(...itemIds: string[]): AgentQueueSnapshot { - return { - agentId: "agent-1", - revision: 1, - items: itemIds.map((id) => ({ - id, - text: "hello", - intent: "queue", - deliveryState: "pending", - attempts: 0, - createdAt: "2026-01-01T00:00:00Z", - })), - }; -} - -interface Harness { - outbox: QueueOutboxAccess; - entries: Map; - bumped: string[]; - markedFailed: string[]; -} - -function createOutbox(initial: PendingQueueEnqueue[]): Harness { - const entries = new Map(initial.map((entry) => [entry.itemId, entry])); - const bumped: string[] = []; - const markedFailed: string[] = []; - return { - entries, - bumped, - markedFailed, - outbox: { - list: (serverId) => - [...entries.values()] - .filter((entry) => entry.serverId === serverId) - .sort((a, b) => a.createdAt - b.createdAt), - remove: (itemId) => { - entries.delete(itemId); - }, - bumpAttempts: (itemId) => { - bumped.push(itemId); - const entry = entries.get(itemId); - if (entry) { - entries.set(itemId, { ...entry, attempts: entry.attempts + 1 }); - } - }, - markFailed: (itemId) => { - markedFailed.push(itemId); - const entry = entries.get(itemId); - if (entry) { - entries.set(itemId, { ...entry, failedAt: 1 }); - } - }, - }, - }; -} - -describe("flushQueueOutbox", () => { - test("re-sends entries oldest first and clears them on ack", async () => { - const harness = createOutbox([ - pendingEntry({ itemId: "item-2", createdAt: 2 }), - pendingEntry({ itemId: "item-1", createdAt: 1 }), - ]); - const sent: string[] = []; - const applied: AgentQueueSnapshot[] = []; - - await flushQueueOutbox({ - serverId: "server-1", - outbox: harness.outbox, - client: { - enqueueAgentMessage: async (input) => { - sent.push(input.itemId); - return snapshotWith(input.itemId); - }, - }, - applySnapshot: (snapshot) => applied.push(snapshot), - }); - - expect(sent).toEqual(["item-1", "item-2"]); - expect(harness.entries.size).toBe(0); - expect(applied).toHaveLength(2); - }); - - test("only flushes entries for the requested server", async () => { - const harness = createOutbox([ - pendingEntry({ itemId: "item-1", serverId: "server-1" }), - pendingEntry({ itemId: "item-2", serverId: "server-2" }), - ]); - const sent: string[] = []; - - await flushQueueOutbox({ - serverId: "server-1", - outbox: harness.outbox, - client: { - enqueueAgentMessage: async (input) => { - sent.push(input.itemId); - return snapshotWith(input.itemId); - }, - }, - applySnapshot: () => {}, - }); - - expect(sent).toEqual(["item-1"]); - expect([...harness.entries.keys()]).toEqual(["item-2"]); - }); - - test("re-sends the entry verbatim, including its admission intent", async () => { - const harness = createOutbox([pendingEntry({ intent: "steer_strict" })]); - const sent: Array<{ itemId: string; intent: string; text: string }> = []; - - await flushQueueOutbox({ - serverId: "server-1", - outbox: harness.outbox, - client: { - enqueueAgentMessage: async (input) => { - sent.push({ itemId: input.itemId, intent: input.intent, text: input.text }); - return snapshotWith(input.itemId); - }, - }, - applySnapshot: () => {}, - }); - - expect(sent).toEqual([{ itemId: "item-1", intent: "steer_strict", text: "hello" }]); - }); - - test("a failed send keeps the entry and bumps its attempt count", async () => { - const harness = createOutbox([pendingEntry()]); - - await flushQueueOutbox({ - serverId: "server-1", - outbox: harness.outbox, - client: { - enqueueAgentMessage: async () => { - throw new Error("transport not connected"); - }, - }, - applySnapshot: () => {}, - }); - - expect(harness.bumped).toEqual(["item-1"]); - expect(harness.entries.get("item-1")?.attempts).toBe(1); - }); - - test("an entry that exhausts its attempts stays visible as failed and is reported", async () => { - const harness = createOutbox([pendingEntry({ attempts: QUEUE_OUTBOX_MAX_ATTEMPTS - 1 })]); - const exhausted: string[] = []; - - await flushQueueOutbox({ - serverId: "server-1", - outbox: harness.outbox, - client: { - enqueueAgentMessage: async () => { - throw new Error("still broken"); - }, - }, - applySnapshot: () => {}, - onEntryExhausted: (entry) => exhausted.push(entry.itemId), - }); - - // An undelivered prompt is never dropped silently: the entry stays with its - // full payload until an explicit retry or discard. - expect(harness.entries.size).toBe(1); - expect(harness.entries.get("item-1")?.failedAt).toBeDefined(); - expect(exhausted).toEqual(["item-1"]); - }); - - test("a failed entry is not re-flushed by later flushes", async () => { - const harness = createOutbox([ - pendingEntry({ failedAt: 1, attempts: QUEUE_OUTBOX_MAX_ATTEMPTS }), - ]); - const sent: string[] = []; - - await flushQueueOutbox({ - serverId: "server-1", - outbox: { - ...harness.outbox, - list: (serverId) => - harness.outbox.list(serverId).filter((entry) => entry.failedAt === undefined), - }, - client: { - enqueueAgentMessage: async (input) => { - sent.push(input.itemId); - return snapshotWith(input.itemId); - }, - }, - applySnapshot: () => {}, - }); - - expect(sent).toEqual([]); - expect(harness.entries.size).toBe(1); - }); - - test("an entry that succeeds on a later flush is removed", async () => { - const harness = createOutbox([pendingEntry({ attempts: QUEUE_OUTBOX_MAX_ATTEMPTS - 2 })]); - let calls = 0; - const flush = () => - flushQueueOutbox({ - serverId: "server-1", - outbox: harness.outbox, - client: { - enqueueAgentMessage: async (input) => { - calls += 1; - if (calls === 1) { - throw new Error("transient"); - } - return snapshotWith(input.itemId); - }, - }, - applySnapshot: () => {}, - }); - - await flush(); - expect(harness.entries.get("item-1")?.attempts).toBe(QUEUE_OUTBOX_MAX_ATTEMPTS - 1); - - await flush(); - expect(harness.entries.size).toBe(0); - }); -}); diff --git a/packages/app/src/stores/queue-outbox-store/model.ts b/packages/app/src/stores/queue-outbox-store/model.ts deleted file mode 100644 index 9e636fd3513..00000000000 --- a/packages/app/src/stores/queue-outbox-store/model.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { z } from "zod"; -import { - AgentAttachmentWireSchema, - QueuedAgentDeliveryIntentSchema, - QueuedComposerAttachmentSchema, - type AgentQueueSnapshot, - type QueuedAgentDeliveryIntent, -} from "@getpaseo/protocol/messages"; - -/** - * A queue enqueue the daemon has not acknowledged yet. The entry is the durable - * copy: it carries the full wire payload (image bytes included) so it can be - * re-sent verbatim after a reconnect or a fresh app launch, even though the - * optimistic composer row it mirrors lives only in memory. - * - * Re-sending is safe because the daemon treats an enqueue with a known item id — - * queued or already drained — as a retry and does nothing. - * See docs/queue-mirroring.md, "The un-acked window". - */ -export const PendingQueueEnqueueSchema = z.object({ - serverId: z.string(), - agentId: z.string(), - itemId: z.string(), - text: z.string(), - intent: QueuedAgentDeliveryIntentSchema, - images: z.array(z.object({ data: z.string(), mimeType: z.string() })), - attachments: z.array(AgentAttachmentWireSchema), - composerAttachments: z.array(QueuedComposerAttachmentSchema), - createdAt: z.number(), - attempts: z.number().int().nonnegative(), - /** - * Set when the attempts ran out without a daemon acknowledgement. The entry - * stays visible as a failed row with explicit retry/discard instead of being - * dropped — an undelivered prompt is never deleted silently. - */ - failedAt: z.number().optional(), -}); - -export type PendingQueueEnqueue = z.infer; - -/** - * A retry cap, not a timeout: attempts only accrue on reconnects that fail, so - * a healthy daemon clears the outbox on the first flush and a poisoned entry - * (one the daemon keeps rejecting) cannot retry forever. Unlike the source, - * exhaustion parks the entry in a visible failed state; only an explicit - * retry or discard removes it. - */ -export const QUEUE_OUTBOX_MAX_ATTEMPTS = 8; - -export interface QueueOutboxAccess { - list: (serverId: string) => PendingQueueEnqueue[]; - remove: (itemId: string) => void; - bumpAttempts: (itemId: string) => void; - markFailed: (itemId: string) => void; -} - -export interface QueueOutboxFlushClient { - enqueueAgentMessage: (input: { - agentId: string; - itemId: string; - text: string; - intent: QueuedAgentDeliveryIntent; - images?: Array<{ data: string; mimeType: string }>; - attachments?: PendingQueueEnqueue["attachments"]; - composerAttachments?: PendingQueueEnqueue["composerAttachments"]; - }) => Promise; -} - -export interface FlushQueueOutboxInput { - serverId: string; - outbox: QueueOutboxAccess; - client: QueueOutboxFlushClient; - applySnapshot: (snapshot: AgentQueueSnapshot) => void; - /** - * Called when an entry exhausts its attempts. The entry stays in the outbox, - * visible as failed; this only tells the UI the state changed. - */ - onEntryExhausted?: (entry: PendingQueueEnqueue) => void; -} - -/** - * Re-sends every un-acked enqueue for one server, oldest first so queue order - * survives the retry. Success removes the entry; failure bumps its attempt - * count and parks it in the visible failed state once the cap is reached. - */ -export async function flushQueueOutbox(input: FlushQueueOutboxInput): Promise { - for (const entry of input.outbox.list(input.serverId)) { - try { - const snapshot = await input.client.enqueueAgentMessage({ - agentId: entry.agentId, - itemId: entry.itemId, - text: entry.text, - intent: entry.intent, - images: entry.images, - attachments: entry.attachments, - composerAttachments: entry.composerAttachments, - }); - input.outbox.remove(entry.itemId); - input.applySnapshot(snapshot); - } catch { - if (entry.attempts + 1 >= QUEUE_OUTBOX_MAX_ATTEMPTS) { - input.outbox.markFailed(entry.itemId); - input.onEntryExhausted?.(entry); - } else { - input.outbox.bumpAttempts(entry.itemId); - } - } - } -} diff --git a/packages/app/src/stores/session-store.test.ts b/packages/app/src/stores/session-store.test.ts index 56f2130d8ef..1b9052c4c12 100644 --- a/packages/app/src/stores/session-store.test.ts +++ b/packages/app/src/stores/session-store.test.ts @@ -1,23 +1,7 @@ -import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; - -vi.mock("@react-native-async-storage/async-storage", () => { - const storage = new Map(); - return { - default: { - getItem: vi.fn(async (key: string) => storage.get(key) ?? null), - setItem: vi.fn(async (key: string, value: string) => { - storage.set(key, value); - }), - removeItem: vi.fn(async (key: string) => { - storage.delete(key); - }), - }, - }; -}); +import { afterEach, describe, expect, it } from "vitest"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; -import type { AgentQueueSnapshot, WorkspaceDescriptorPayload } from "@getpaseo/protocol/messages"; -import { useQueueOutboxStore } from "./queue-outbox-store"; +import type { WorkspaceDescriptorPayload } from "@getpaseo/protocol/messages"; import { normalizeWorkspaceDescriptor, @@ -865,130 +849,3 @@ describe("removeWorkspace", () => { expect(after.workspaces).toBe(before.workspaces); }); }); - -describe("durable agent queue snapshots", () => { - const agentId = "agent-1"; - - function queueSnapshot(overrides: Partial = {}): AgentQueueSnapshot { - return { - agentId, - revision: 1, - items: [ - { - id: "item-1", - text: "first", - intent: "queue", - deliveryState: "pending", - attempts: 0, - createdAt: "2026-01-01T00:00:00.000Z", - }, - ], - ...overrides, - }; - } - - function seedOutboxEntry(itemId: string): void { - useQueueOutboxStore.getState().add({ - serverId: "test-server", - agentId, - itemId, - text: "not acked yet", - intent: "queue", - images: [], - attachments: [], - composerAttachments: [], - }); - } - - beforeAll(async () => { - // Persist rehydration resolves after import and would otherwise replace - // entries added before it landed. - await useQueueOutboxStore.persist.rehydrate(); - }); - - afterEach(() => { - for (const itemId of Object.keys(useQueueOutboxStore.getState().entries)) { - useQueueOutboxStore.getState().remove(itemId); - } - }); - - it("applies a snapshot as queue rows and records the revision", () => { - initializeTestSession(); - - useSessionStore.getState().applyAgentQueueSnapshot("test-server", queueSnapshot()); - - const session = useSessionStore.getState().sessions["test-server"]; - expect(session?.queuedMessageRevisions.get(agentId)).toBe(1); - expect(session?.queuedMessages.get(agentId)).toEqual([ - { - id: "item-1", - text: "first", - attachments: [], - deliveryState: "pending", - lastError: undefined, - }, - ]); - }); - - it("re-appends an un-acked outbox row a snapshot would erase", () => { - initializeTestSession(); - seedOutboxEntry("pending-1"); - - useSessionStore.getState().applyAgentQueueSnapshot("test-server", queueSnapshot()); - - const rows = useSessionStore.getState().sessions["test-server"]?.queuedMessages.get(agentId); - expect(rows?.map((row) => [row.id, row.syncState])).toEqual([ - ["item-1", undefined], - ["pending-1", "pending"], - ]); - }); - - it("marks a re-appended row failed when its entry exhausted the retries", () => { - initializeTestSession(); - seedOutboxEntry("pending-1"); - useQueueOutboxStore.getState().bumpAttempts("pending-1"); - useQueueOutboxStore.getState().markFailed("pending-1"); - - useSessionStore.getState().applyAgentQueueSnapshot("test-server", queueSnapshot()); - - const rows = useSessionStore.getState().sessions["test-server"]?.queuedMessages.get(agentId); - expect(rows?.at(-1)).toMatchObject({ id: "pending-1", syncState: "failed" }); - }); - - it("drops a snapshot that is older than the applied revision", () => { - initializeTestSession(); - - useSessionStore - .getState() - .applyAgentQueueSnapshot("test-server", queueSnapshot({ revision: 4 })); - useSessionStore - .getState() - .applyAgentQueueSnapshot("test-server", queueSnapshot({ revision: 3 })); - - const session = useSessionStore.getState().sessions["test-server"]; - expect(session?.queuedMessageRevisions.get(agentId)).toBe(4); - expect(session?.queuedMessages.get(agentId)?.[0]?.id).toBe("item-1"); - }); - - it("never creates a submitted timeline row: snapshots only touch the queue", () => { - initializeTestSession(); - - useSessionStore.getState().applyAgentQueueSnapshot("test-server", queueSnapshot()); - - const timeline = selectAgentTimelineState( - useSessionStore.getState().sessions["test-server"], - agentId, - ); - expect(timeline.status).toBe("cold"); - expect( - useSessionStore.getState().sessions["test-server"]?.agentStreamTail.get(agentId), - ).toBeUndefined(); - }); - - it("is a no-op without a session, leaving local queues to their own meaning", () => { - useSessionStore.getState().applyAgentQueueSnapshot("test-server", queueSnapshot()); - - expect(useSessionStore.getState().sessions["test-server"]).toBeUndefined(); - expect(Object.keys(useQueueOutboxStore.getState().entries).length).toBe(0); - }); -}); diff --git a/packages/app/src/stores/session-store.ts b/packages/app/src/stores/session-store.ts index 796c8caa05c..625c3d8c2f0 100644 --- a/packages/app/src/stores/session-store.ts +++ b/packages/app/src/stores/session-store.ts @@ -22,8 +22,8 @@ import { type MessageSubmissionRejectionOutcome, } from "@/composer/submission/model"; import type { PendingPermission } from "@/types/shared"; +import type { ComposerAttachment } from "@/attachments/types"; import type { AgentLifecycleStatus } from "@getpaseo/protocol/agent-lifecycle"; -import type { CompanionEntry } from "@getpaseo/protocol/companion-stream"; import type { AgentPermissionRequest, AgentOptionControl, @@ -33,7 +33,6 @@ import type { AgentMode, AgentCapabilityFlags, AgentUsage, - AgentArtifact, AgentPersistenceHandle, } from "@getpaseo/protocol/agent-types"; import type { @@ -42,20 +41,12 @@ import type { ServerCapabilities, WorkspaceDescriptorPayload, WorkspaceProjectDescriptorPayload, - AgentQueueSnapshot, } from "@getpaseo/protocol/messages"; import { normalizeWorkspaceOpaqueId, normalizeWorkspacePath, resolveWorkspaceMapKeyByIdentity, } from "@/utils/workspace-identity"; -import type { QueuedComposerMessage } from "@/composer/actions"; -import { - appendPendingQueueRows, - shouldApplyAgentQueueSnapshot, - toQueuedComposerMessages, -} from "@/composer/queue-sync"; -import { useQueueOutboxStore } from "@/stores/queue-outbox-store"; import { createAgentLastActivityCoalescer, type AgentLastActivityCommitter, @@ -119,8 +110,6 @@ export interface Agent { labels: Record; metadata?: Record; projectPlacement?: ProjectPlacementPayload | null; - artifacts?: AgentArtifact[]; - companionEntries?: CompanionEntry[]; } export interface WorkspaceDescriptor { @@ -527,12 +516,10 @@ export interface SessionState { fileExplorer: Map; // Queued messages - queuedMessages: Map; - /** - * Last daemon queue revision applied per agent, so an out-of-order broadcast - * cannot erase a newer state. See docs/queue-mirroring.md. - */ - queuedMessageRevisions: Map; + queuedMessages: Map< + string, + Array<{ id: string; text: string; attachments: ComposerAttachment[] }> + >; } // Global store state @@ -713,11 +700,11 @@ interface SessionStoreActions { setQueuedMessages: ( serverId: string, value: - | Map - | ((prev: Map) => Map), + | Map> + | (( + prev: Map>, + ) => Map>), ) => void; - /** Applies a daemon queue snapshot, dropping it if it is older than what is shown. */ - applyAgentQueueSnapshot: (serverId: string, snapshot: AgentQueueSnapshot) => void; // Hydration setHasHydratedAgents: (serverId: string, hydrated: boolean) => void; @@ -772,7 +759,6 @@ function createInitialSessionState( pendingPermissions: new Map(), fileExplorer: new Map(), queuedMessages: new Map(), - queuedMessageRevisions: new Map(), }; } @@ -1943,40 +1929,6 @@ export const useSessionStore = create()( }); }, - applyAgentQueueSnapshot: (serverId, snapshot) => { - set((prev) => { - const session = prev.sessions[serverId]; - if (!session) { - return prev; - } - if ( - !shouldApplyAgentQueueSnapshot({ - incomingRevision: snapshot.revision, - appliedRevision: session.queuedMessageRevisions.get(snapshot.agentId), - }) - ) { - return prev; - } - const queuedMessages = new Map(session.queuedMessages); - queuedMessages.set( - snapshot.agentId, - appendPendingQueueRows( - toQueuedComposerMessages(snapshot), - useQueueOutboxStore.getState().entriesForAgent(serverId, snapshot.agentId), - ), - ); - const queuedMessageRevisions = new Map(session.queuedMessageRevisions); - queuedMessageRevisions.set(snapshot.agentId, snapshot.revision); - return { - ...prev, - sessions: { - ...prev.sessions, - [serverId]: { ...session, queuedMessages, queuedMessageRevisions }, - }, - }; - }); - }, - // Hydration setHasHydratedAgents: (serverId, hydrated) => { set((prev) => { diff --git a/packages/app/src/utils/agent-snapshots.ts b/packages/app/src/utils/agent-snapshots.ts index c3eea36d79f..86da628bdfb 100644 --- a/packages/app/src/utils/agent-snapshots.ts +++ b/packages/app/src/utils/agent-snapshots.ts @@ -145,7 +145,5 @@ export function normalizeAgentSnapshot(snapshot: AgentSnapshotPayload, serverId: parentAgentId, labels: snapshot.labels, metadata: snapshot.metadata, - artifacts: snapshot.artifacts, - companionEntries: snapshot.companionEntries, }; } diff --git a/packages/app/src/voice/input-receipt-cue.ts b/packages/app/src/voice/input-receipt-cue.ts deleted file mode 100644 index 50a01ce4f10..00000000000 --- a/packages/app/src/voice/input-receipt-cue.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { AudioPlaybackSource } from "@/audio"; - -/** Short local cues distinguish durable admission from provider submission. */ -export function createInputReceiptCue(state: "queued" | "sent"): AudioPlaybackSource { - const sampleRate = 24000; - const frequencies = state === "queued" ? [523] : [740, 988]; - const noteSamples = Math.round(sampleRate * 0.075); - const pcm = new Uint8Array(noteSamples * frequencies.length * 2); - const view = new DataView(pcm.buffer); - frequencies.forEach((frequency, note) => { - for (let i = 0; i < noteSamples; i++) { - const envelope = Math.sin((Math.PI * i) / noteSamples) ** 2; - const sample = Math.sin((2 * Math.PI * frequency * i) / sampleRate); - view.setInt16((note * noteSamples + i) * 2, Math.round(sample * envelope * 5500), true); - } - }); - return { - size: pcm.byteLength, - type: "audio/pcm;rate=24000;bits=16", - async arrayBuffer() { - return pcm.buffer; - }, - }; -} diff --git a/packages/app/src/voice/voice-failure-cue.ts b/packages/app/src/voice/voice-failure-cue.ts deleted file mode 100644 index e546d90ce40..00000000000 --- a/packages/app/src/voice/voice-failure-cue.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { Buffer } from "buffer"; -import type { AudioPlaybackSource } from "@/audio"; -import type { VoiceFailureKind } from "./voice-failure"; -import { - VOICE_FAILURE_PHRASE_MULAW_BASE64, - VOICE_FAILURE_PHRASE_SAMPLE_RATE, -} from "./voice-failure-phrases.mulaw"; - -const SAMPLE_RATE = VOICE_FAILURE_PHRASE_SAMPLE_RATE; -const BUZZ_MS = 360; -const BUZZ_START_HZ = 311; -const BUZZ_END_HZ = 208; -const BUZZ_HARMONICS = 6; -const GAP_MS = 120; - -function samplesFor(ms: number): number { - return Math.round((SAMPLE_RATE * ms) / 1000); -} - -/** - * The failure earcon: one buzzy tone gliding down over a third of a second. Every other - * voice earcon (mute, unmute, speech rate) is a short run of pure sine notes, so the - * harmonic timbre, the continuous glide, and the length each set this one apart. - */ -function writeBuzz(view: DataView, offsetSamples: number): void { - const total = samplesFor(BUZZ_MS); - const attack = samplesFor(10); - const release = samplesFor(80); - let normalization = 0; - for (let h = 1; h <= BUZZ_HARMONICS; h++) normalization += 1 / h; - let phase = 0; - for (let i = 0; i < total; i++) { - const progress = i / total; - const frequency = BUZZ_START_HZ * (BUZZ_END_HZ / BUZZ_START_HZ) ** progress; - phase += (2 * Math.PI * frequency) / SAMPLE_RATE; - let sample = 0; - for (let h = 1; h <= BUZZ_HARMONICS; h++) sample += Math.sin(phase * h) / h; - const envelope = Math.min(1, i / attack, (total - i) / release); - view.setInt16( - (offsetSamples + i) * 2, - Math.round((sample / normalization) * envelope * 9000), - true, - ); - } -} - -// G.711 mu-law expansion; the phrases ship compressed to half the size of PCM16. -function decodeMuLaw(byte: number): number { - const value = ~byte & 0xff; - const sign = value & 0x80; - const exponent = (value >> 4) & 0x07; - const mantissa = value & 0x0f; - const magnitude = (((mantissa << 3) + 0x84) << exponent) - 0x84; - return sign ? -magnitude : magnitude; -} - -type PhraseKey = keyof typeof VOICE_FAILURE_PHRASE_MULAW_BASE64; - -function toSource(pcm: Uint8Array): AudioPlaybackSource { - return { - size: pcm.byteLength, - type: `audio/pcm;rate=${SAMPLE_RATE};bits=16`, - async arrayBuffer() { - return pcm.buffer.slice(pcm.byteOffset, pcm.byteOffset + pcm.byteLength) as ArrayBuffer; - }, - }; -} - -function buildCue(phrase: PhraseKey, withBuzz: boolean): AudioPlaybackSource { - const encoded = Buffer.from(VOICE_FAILURE_PHRASE_MULAW_BASE64[phrase], "base64"); - const prefixSamples = withBuzz ? samplesFor(BUZZ_MS) + samplesFor(GAP_MS) : 0; - const pcm = new Uint8Array((prefixSamples + encoded.length) * 2); - const view = new DataView(pcm.buffer); - if (withBuzz) writeBuzz(view, 0); - for (let i = 0; i < encoded.length; i++) { - view.setInt16((prefixSamples + i) * 2, decodeMuLaw(encoded[i]), true); - } - return toSource(pcm); -} - -/** The failure earcon followed by a spoken name for the failure. Played on the device. */ -export function createVoiceFailureCue(kind: VoiceFailureKind): AudioPlaybackSource { - return buildCue(kind, true); -} - -/** Spoken once the host is back after a disconnect that was announced. */ -export function createVoiceReconnectedCue(): AudioPlaybackSource { - return buildCue("reconnected", false); -} diff --git a/packages/app/src/voice/voice-failure-phrases.mulaw.ts b/packages/app/src/voice/voice-failure-phrases.mulaw.ts deleted file mode 100644 index 9c056e7ccc1..00000000000 --- a/packages/app/src/voice/voice-failure-phrases.mulaw.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Generated by scripts/generate-voice-failure-phrases.mjs. Do not edit by hand. -// Kokoro (Apache-2.0) voice 9, G.711 mu-law mono 12000 Hz, base64. - -export const VOICE_FAILURE_PHRASE_SAMPLE_RATE = 12000; - -export const VOICE_FAILURE_PHRASE_MULAW_BASE64 = { - // "Didn't catch that." (987 ms) - "nothing-recognized": - "X19eXl5eXV1dXV1dXV1dXV1dXV1eXl5fX2BiY2VmaGlrbW9zd3z9+PPv7Orn5OLg3t3c29rZ2djX1tbV1dTT09LS0tLS0tLT09TU1dbX2Nna3N3e4OPn6u3v9ft9eHNvbGpnZWNhX15dXVxbW1taWlpZWVlYWFhXV1dWVlVVVVRUVFRTU1NTU1NTU1NUVFVWWFlaXF1fYmZqbnV+9+/q5eHe3NnY1tTS0dDPz87Ozs7Ozs7Ozs7Ozs7Oz8/P0NHS09TV19ja293f4uXp7PH5fndxbWlmY2BeXVxbWVlYV1ZWVVRTU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9xp9uRu2OFg2t/z51/f22Fp6Gj3clvb6WxaXXh69ltdb+xgV+39anX77XB6321u4Xhe/G/1Zvh3eed4+Gzn929+ae7j83f7e3d8eenpZnb+82d1++Zod3Z17fhn8u5ofHHv7/Lm8npva/pte2R2b25ldnZwaXZudnnzYWZpcW9tefFp/P50+Ot9bH3y8/3i6PN6833v4/ptcXxv9et/av54bO3r9ezq6vnk6+Ly33treP5m9PBw//xr9/Xj9HR26fj23ffp9vXo3+rnanH8ZXR7dvJydvdufff0/Pf0+2pm6vBz+n5seW/9cWpqfmht+nlrZnj6ePd5YHb++Q==", - // "Recognition stalled." (1286 ms) - "recognition-stalled": - "X15eXVxcXFxcXV1eXl9hZGdrb3Z++fHt6eXh3tza2NbV09LR0M/Pz8/Ozs3Nzc7P0NPW2dzh6flwZVxWT0xIREJAPz4+Pj09PT09Pj4/QURHS09VXGd47N/X0MzJxcPAv769vby7urm5ubm5urq7vLy9vb6+wcXL0d3val1TTEdBPjs4NTIvLi4tLS4uLi4vLzAyNDc5PUFITlhkfeXXzsjEv768urm4t7a1tbW0tLSzs7O0tLW2tre3uLi5urq6u7y+wcbLz9jhel5PR0A7NzMvLSwrKikpKCgoKCgpKistLjAzNzo+Q0pUZujVy8bBvry6uLa1s7GwsLCwsLCvr6+vr6+wsbGxsrO0tbW1tbe4u77Dx8zQ2fBgUEc/OzYxLSspKCclJSMjIiMjJCUmJykrLS8zNzs+Rk9n4dDIwr67uLazsrCvrq2srKysq6yrrKysra2ur6+vr66tra+xtrq/w8THytHdaE9AOTItKScmJCQjIiEgHx8fICIkJykrLS80Njo8QU5r0Mi9vbu8vLm2sK6sq6ysraytra2tra2trq+wsrOvraqpqq2xur7Au7i0tbvHaEU1LiooKCcnJyQgHRsaGRsdISUoKSkpKi0xO0h4zsO+vsDHysvBurGurK6xtru6urWyr6+vr7GwsbGwraqloqChpKerq6uoqKmss8B+PzQsKiclIyEeHBoYFxcZHB8jJSYnKCwyQG7Hvbq+ws/U1tDHvru6vc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v6PRf2mXo/HLpdv3jaO759O/99/fsbObvce3rbej7+/795Gnu9XXs/HN56nV7dPlzfmzxcmrva296dHVo/HVnfHJtemt+bm//bnV3b350d3V0929+fnn9/P179v/4+Pv58P3w9vjz8/T48fD67fb18PX19fD4+fP4+/n6/PR8/fd8//l3+Xp9fH14/nd7e3Z9d3p5eHt4d3x4eXh5e3h5e3p6e315fHx7fH56ff19fn3+/f1++/x+/Pr/+/r6/vf6/Pn4/ff+9/z4+/v4+vn+9X/4/fv5/vv7/P39/f39//1//n9/fv1+fn3/fn19fn19fH18fXx8fnt8fXx9fXx+fH58fXx+fX1/fX5/fv5+fv7///7//v7+/f/+/f3+/P7//P7+/v79f/7+f//+f/7/fn9+/35+f319fn59fn19fn19fX19fH19fH1+fH18fXx+fH59fXx/fX59fv9+f/9//X///f79/fz9/P37/Pz8+/v7/Pz7/P37/Pz9/fz9/f39/v3+/v7+//7+/3//f35//319fn19fn58fX19fX19fH19fXx9fHx9fH19fX19fX59fn1/fn5+//9+f/9///5+/n//fv7/fn7/f37/fv5+f33///15/f18ff3+f/7//ft9fvv9fP37fv77/v/++v/9+39+/ft+f/v7e3z6+nr+evf4enr+83x2+/r9f/58/Pl8dHbt+nx3cPD0dWzv+3d1+H5u8vX5fvZ0+3n4/Hl97etqfOx48W775357cu/9b/na+Vbw8Wncem9+a9ttTu/Q501b0e1Pd9FfX+xt5+/72mxr6Gbu5ux462/ib2xq2m9w5+ztVcpoXNhv7ddfcNNqaf3raePPVFDO3lZsce/uVVXR4Ujv8fhS3vlPZNh3UGdtaPNa7O3panje5XLK5Wj01NdueOH83uR63+LUbWnPfmR24t5VZepkXV3kW1tlaVFXbHFPaGd1XFPo3l5o2tl5T9raYenI2+rZzdbqz8XL2dLPzuHS0eb87VRbSUxLTj8+PDo8QT48QUdCRj9GSEpZVk5K38W9urq6t767squpqay0u729vbe3veJJPDs5PD89NzEvLSwsMz0+OjU2Njg9R0dGPTk3O0NKSEM/QVpa/8aspaanq6mpqqSgn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0tOTExPT09MRkJESEpKTEpGQ0RGS09KSEZDQ0RHS0pJSEVHTFJYXFxZVVJYXmZnY1xaWmFnbXRuWFhdXWFpaGheWV1bX/7vdmhhXGF55+Ln8Xb+6dzW0tfc3OPe1dHMzdTX1dPPzsrKz9XRz83KysrNztPb0c3O0dbX3N/c1Nra1t7s4t/g4+Th7//z937p6n/9/Xn9eP76cG5vbXJ+eW5tcGpjZ25qaGppXlxgZF5gYVtZWlpbXV5aWFtaXF5eW1dXVlVZW11cXltbXV5eYWVkYWJfXWBpaWZxfXRtcXBxeXp2eX7+e3737e7w8u/u9fLp5+vt7enu7Ono4+Hg39/f4+Df29vc4Obm4uPf3Nzd5Onn5eDe3d/l7O3l4N4=", - // "Recognition failed." (1238 ms) - "recognition-failed": - "W1hVUk9OTUxMS0tLS0tMTU9SVltfaHX26d/b1tLPzcvJx8XEw8LBwMDAwMHBwsPExMXGyMrN09vtcFxSS0ZBPjw6ODY1MzIxMDAwMTI0NTg7PUFHTVZj/OHWzsjDv727ube2trW0s7OysrKysrO0tba3uLq7vb7Aw8bJzdLe+l9SSkQ+Ozg1Mi8uLSwrKikpKSkpKSorLC4vMjY5PUNKVGjq1svFv7y5t7SysK+urq6ura2tra2urq6vr7CxsrS2uLq8vb/CxsnLzc3Oz9Pa63FaT0hDPTs3NDAuLSspJyYlJCMjIiMjJCYnKSssLzI3PERPZN7NxL26trOwrq2sqqqpqKioqKeoqKipqaqrrK2urrGytLO0tLW3urzBx8/acl1NRD46NTAtKiclIiAfHh4eHh8fHyAiIyUnKSwuMzc+Rld218vDvLqysq6urayrqqiop6inp6eoqKmpqqurra6vrqyrqamrrbO5vr/CyMbOztxlSzcvJyIeHh4eHh4dHBwbGxsbHR8jKCwwNTg6PEBLeM6+uLSysrKxr66trKurqqmpqaqsrq6vr7Gvrqqlop+goqesrq6tqaepqa+520k0LCclJCMiHx0aGBUUFRcZHB4gIyUnKSwyPFXZvby1ubvAw8C7trCvsbS5u727uLa0s7Sys6+vr66sp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X39/j7/v7+/f5+fnx8eXh5eXl4dnRzc3J1dHRxb25ub3BvcHFvb25vcnRzdHJycXV2eXp7enp7fv/8+/z9/v37+fj3+Pj39/b28/P09PT08/Ly8fHx8/Tz8vLz8/P09PT19fX19/j4+fj5+vv7/Pz8/f79/35+fnx7fHx7eXl4eHh3dnZ1dHR0dHR0dHRyc3R0c3R0dHV0dXV2dnd2d3d4eHl6ent6e3x7fX5+/v7+//78/Pv6+vr7+fn4+ff4+Pj5+Pf39/f4+Pj49/j4+fn6+vr7+/r8+/z7+/39/f7+f///f359fXx8fHx7e3t7enp6ent7enp6e3t7fHt8e3x8fXx9fn1+fn5/f/////7+/v39/f39/Pz9/Pv7/Pz7+/z8+/v7/Pz8/Pz8/Pz9/f39/f7+/f7+/v7+f35+fn19fX18fHx9fHx8e3t7e3t7e3x7e3t7e3t7fHx7e3x8fHx8fX19fX1+fn5//////v7+/v79/f39/Pz9/Pz8/Pz8/Pz8+/z8+/z8/Pz9/Pz8/f39/f3+/f3+/v7//v///35/fn5+fn59fn19fX19fH19fX18fHx8fX19fX19fX19fX1+fX5+fn5////////+///+/v7+/v79/f39/f79/Pz9/fz9/f39/f39/f3+/f79/v7+/v7+/v7/f///f39/fn9+fn5+fn59fn5+fn19fn19fX59fX19fn1+fn5+fn5+fn5+f35+f3//fv////////7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v////////9/f39/fn5/fn5+fn5+fn5+fn5+fn5+fn5+fn5+fn5+fn5+fn9+fn5+f39//39/f///f/////////7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+//7+///+//////////9/f///f3//fn9/f35+fn5+fn5+fn5+fn5+fn5+fn5+fn5+f35+fn9/f39/f39/f3////9//////////////////////////v7///7/////f///////////////f/9/f/9//39/f39/fn9/f35/fn5/fn5+fn5+fn5/f39+f39/fn9//39/f39/f///f3//f3///////////////////////3//////////////////////////f///////f3///39/////f39/f39/f39/f39/f39/f39/f39/f39/f39/f39+f39/f39/f39/f39/f39/f39/f39//39/fv9/f39/f3//f///f3//f////39/////f/////9/////f/////////////////9//3///3//f39/f///f39/f39//3///39/f39//39/f39/f39//39/f39/f39/f/9/f39/f3//f3///////////////3///////3///3///3////////9/f/9/f/9/f39/f39/f39///9//39/f3//f39/f////39//39/f3//f39//39/f39/f39/f39/f/9/f3//f39//39//3//f/9/f39/f///f39//39/f39//39/f3///3//f39/f39/f3//f3///39//3////9//3//////f39///9//////3///3//////f3//f///f39/f39/f39/f39/f///f3//f39/f39/f3///3//f39/f39/f39/f39/f39/////f3//f/9//3///39//3///3//f///////////f////3//f3//f3//f39/f39/f39/f///fn9//39/f39/f3//f39/f39/f39/f3////9/f39/f39/f39/f39///9///9/f/9/f39/f///////////f/////9//39/////f////3//f39/f3///39/f39//39/////f////39//3//////f/9/f39/f///f39//3//////f/9//3//f39//3//f/9/f/9//39/f/9/f39/f3//f3///39///9/f39/f3///39//39/f39/f3//f3//f39/f39//39/f39/f3//f39/f39/f/9/f3//f39//39/fn9/f39//39/f39/f/9/f/9/f3///39/f3//f39//3//f39/f39/f3//f39/////f3//f///f3//f////3//f3//f39//3///39/f39/f/9/f39//39/f39/f3///39/f39/f39/f39/f39/f3///39/f3//f3///3///////3//f3//////f///////f3////9///9//////////3//f39/f/9/f39/f39/f39/f/9/f39//39/f39/f3//f///f3//f3//f///////f///f////3//f/9//3//f3//f39/f39/f/9/f39/f3//f3///39///9/f////3//f3//////f/9/f39/f///f3//f37///9+/39+fX5+fX7+/v5//v99f35+//7+/v7+fX5///79/f7+/n59fv5//vz8/nz9f3n+f/7+//l9fvx+fX7+/H/8/f7+fn98fX58/n59/v98fXz8fH35ff/+e3x3ent6/n37+3v8fHd8dvxu7+n76On5fmX9amPn7e3q5uRqcPNpcPDm7/3rfWNkbm546eTo6fJ8Ymtzbfbq8ft7aV9gcG145+12cHhmZvv18Pbc6m399nHs39TW3dp5W1pcZXXc1Nrd72NWWFxmft7a3epyWU5JS05WduXc1+H1alZYVVZp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llXltcW1hVU1RST09PTkxMTEtJSUlKSUlKSkpLS0xMTU1NTk9QUFFVVlZYW11eYmZobW5xcnBxdXV9eXr58PLt5+Xg3tzb2tnY2dnY2NjZ19bW1dXT09TU0tHT1dTV1dbX1dbX19fX1dfZ2tvb3+Lg3uTp6urq6/Dz8/R9dXJ8fXNwbm5ua2ppZ2ZhXl5fXlxbW1tZWFlaWVdWV1hYWFdYWFlYWFpaW1pbXF1dXV5f", -} as const; diff --git a/packages/app/src/voice/voice-failure.test.ts b/packages/app/src/voice/voice-failure.test.ts deleted file mode 100644 index 5e43aac90cd..00000000000 --- a/packages/app/src/voice/voice-failure.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { - createVoiceFailureTracker, - voiceFailureFromRecognitionIssue, - type VoiceFailureKind, -} from "@/voice/voice-failure"; -import { createVoiceFailureCue, createVoiceReconnectedCue } from "@/voice/voice-failure-cue"; - -function createClock() { - let now = 0; - return { - now: () => now, - advance(ms: number) { - now += ms; - }, - }; -} - -describe("voice failure tracker", () => { - it("speaks a repeating failure once per episode", () => { - const clock = createClock(); - const tracker = createVoiceFailureTracker(clock.now); - expect(tracker.report("recognition-failed")).toBe(true); - for (let i = 0; i < 50; i++) { - clock.advance(200); - expect(tracker.report("recognition-failed")).toBe(false); - } - expect(tracker.current()).toBe("recognition-failed"); - }); - - it("bounds a flapping connection to one disconnect and one recovery per window", () => { - const clock = createClock(); - const tracker = createVoiceFailureTracker(clock.now); - const spoken: string[] = []; - for (let i = 0; i < 20; i++) { - if (tracker.report("host-disconnected")) spoken.push("disconnected"); - clock.advance(300); - if (tracker.clear(["host-disconnected"]).length > 0) spoken.push("reconnected"); - clock.advance(300); - } - expect(spoken).toEqual(["disconnected", "reconnected"]); - - clock.advance(30_000); - expect(tracker.report("host-disconnected")).toBe(true); - }); - - it("names a new kind of failure, unless it follows another within the cascade window", () => { - const clock = createClock(); - const tracker = createVoiceFailureTracker(clock.now); - expect(tracker.report("host-disconnected")).toBe(true); - clock.advance(1_000); - expect(tracker.report("recognition-failed")).toBe(false); - expect(tracker.current()).toBe("recognition-failed"); - clock.advance(5_000); - expect(tracker.report("microphone-lost")).toBe(true); - }); - - it("repeats a miss only after recognition worked in between", () => { - const clock = createClock(); - const tracker = createVoiceFailureTracker(clock.now); - expect(tracker.report("nothing-recognized")).toBe(true); - clock.advance(15_000); - expect(tracker.report("nothing-recognized")).toBe(false); - expect(tracker.clear(["nothing-recognized"])).toEqual(["nothing-recognized"]); - expect(tracker.current()).toBeNull(); - clock.advance(1_000); - expect(tracker.report("nothing-recognized")).toBe(true); - }); - - it("maps host recognition issues and ignores values it does not know", () => { - expect(voiceFailureFromRecognitionIssue("nothing_recognized")).toBe("nothing-recognized"); - expect(voiceFailureFromRecognitionIssue("timed_out")).toBe("recognition-stalled"); - expect(voiceFailureFromRecognitionIssue("failed")).toBe("recognition-failed"); - expect(voiceFailureFromRecognitionIssue("something_new")).toBeNull(); - }); - - it("builds a separate spoken cue for every failure, each led by the failure earcon", async () => { - const kinds: VoiceFailureKind[] = [ - "nothing-recognized", - "recognition-stalled", - "recognition-failed", - "recognition-unavailable", - "host-disconnected", - "microphone-lost", - ]; - const sizes = new Set(kinds.map((kind) => createVoiceFailureCue(kind).size)); - sizes.add(createVoiceReconnectedCue().size); - expect(sizes.size).toBe(kinds.length + 1); - - const cue = createVoiceFailureCue("recognition-failed"); - expect(cue.type).toBe("audio/pcm;rate=12000;bits=16"); - const samples = new Int16Array(await cue.arrayBuffer()); - // 360 ms of earcon at 12 kHz, then a 120 ms gap before the phrase. - const earcon = samples.subarray(0, 4320); - expect(Math.max(...earcon.map(Math.abs))).toBeGreaterThan(5000); - expect(Math.max(...samples.subarray(4320, 5760).map(Math.abs))).toBe(0); - }); -}); diff --git a/packages/app/src/voice/voice-failure.ts b/packages/app/src/voice/voice-failure.ts deleted file mode 100644 index b98b2b391cc..00000000000 --- a/packages/app/src/voice/voice-failure.ts +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Voice input problems the user can act on. Each kind has its own spoken phrase and panel - * text, because each calls for a different response: repeat yourself, restart voice, check - * the host, or check the microphone. - */ -export type VoiceFailureKind = - /** A long utterance produced an empty transcript. Repeat it. */ - | "nothing-recognized" - /** The recognizer returned no result before the host's deadline. Restart voice. */ - | "recognition-stalled" - /** The host's recognizer errored. Restart voice. */ - | "recognition-failed" - /** The host could not start local speech recognition, for example its model did not load. */ - | "recognition-unavailable" - /** The connection to the host dropped. Input is paused until it reconnects. */ - | "host-disconnected" - /** The device stopped delivering microphone audio. Voice stops. */ - | "microphone-lost"; - -/** Failures after which nothing the user says reaches the agent. */ -export function isVoiceFailureBlocking(kind: VoiceFailureKind): boolean { - return kind !== "nothing-recognized"; -} - -/** Host `voice_input_state.recognitionIssue` values. Unknown values are ignored. */ -export function voiceFailureFromRecognitionIssue(issue: string): VoiceFailureKind | null { - switch (issue) { - case "nothing_recognized": - return "nothing-recognized"; - case "timed_out": - return "recognition-stalled"; - case "failed": - return "recognition-failed"; - default: - return null; - } -} - -/** - * The same kind stays quiet this long after it was spoken, even if it cleared in between. - * This bounds a flapping connection to one "Host disconnected" and one "Reconnected" per - * window. A miss repeats sooner because each one follows a separate attempt by the user. - */ -const REANNOUNCE_AFTER_MS: Record = { - "nothing-recognized": 10_000, - "recognition-stalled": 30_000, - "recognition-failed": 30_000, - "recognition-unavailable": 30_000, - "host-disconnected": 30_000, - "microphone-lost": 30_000, -}; - -/** A different kind this soon after an announcement is usually a consequence of it. */ -const CASCADE_WINDOW_MS = 3_000; - -interface Episode { - kind: VoiceFailureKind; - announced: boolean; -} - -export interface VoiceFailureTracker { - /** Records a failure. Returns true when it should be spoken now. */ - report(kind: VoiceFailureKind): boolean; - /** Ends episodes. Returns the kinds whose episode had been spoken, for a recovery cue. */ - clear(kinds: readonly VoiceFailureKind[]): VoiceFailureKind[]; - /** The most recently reported failure that has not cleared. */ - current(): VoiceFailureKind | null; - reset(): void; -} - -/** - * Speaks a failure once per episode. A repeat of an active kind stays silent until the - * episode clears, so a failure repeating every few hundred milliseconds is announced once. - */ -export function createVoiceFailureTracker(now: () => number = Date.now): VoiceFailureTracker { - // Insertion order is report order; the last entry is the one the panel shows. - const episodes = new Map(); - const lastAnnouncedAt = new Map(); - let lastAnyAnnouncedAt = Number.NEGATIVE_INFINITY; - - return { - report(kind) { - const existing = episodes.get(kind); - if (existing) { - episodes.delete(kind); - episodes.set(kind, existing); - return false; - } - const at = now(); - const announce = - at - (lastAnnouncedAt.get(kind) ?? Number.NEGATIVE_INFINITY) >= REANNOUNCE_AFTER_MS[kind] && - at - lastAnyAnnouncedAt >= CASCADE_WINDOW_MS; - episodes.set(kind, { kind, announced: announce }); - if (announce) { - lastAnnouncedAt.set(kind, at); - lastAnyAnnouncedAt = at; - } - return announce; - }, - - clear(kinds) { - const recovered: VoiceFailureKind[] = []; - for (const kind of kinds) { - const episode = episodes.get(kind); - if (!episode) continue; - episodes.delete(kind); - if (episode.announced) recovered.push(kind); - } - return recovered; - }, - - current() { - let latest: VoiceFailureKind | null = null; - for (const kind of episodes.keys()) latest = kind; - return latest; - }, - - reset() { - episodes.clear(); - lastAnnouncedAt.clear(); - lastAnyAnnouncedAt = Number.NEGATIVE_INFINITY; - }, - }; -} diff --git a/packages/app/src/voice/voice-runtime.test.ts b/packages/app/src/voice/voice-runtime.test.ts index 98e111a28a3..189140c7f65 100644 --- a/packages/app/src/voice/voice-runtime.test.ts +++ b/packages/app/src/voice/voice-runtime.test.ts @@ -3,8 +3,6 @@ import type { DaemonServerInfo } from "@/stores/session-store"; import type { AudioEngine } from "@/audio"; import { createVoiceRuntime, type VoiceSessionAdapter } from "@/voice/voice-runtime"; import { REALTIME_VOICE_VAD_CONFIG } from "@/voice/realtime-voice-config"; -import type { VoiceFailureKind } from "@/voice/voice-failure"; -import { createVoiceFailureCue, createVoiceReconnectedCue } from "@/voice/voice-failure-cue"; const CUE_MIME_TYPE = "audio/pcm;rate=16000;bits=16"; const THINKING_TONE_MIN_SILENCE_MS = 1500; @@ -28,10 +26,9 @@ function createAudioEngineMock(): AudioEngine { function createSessionAdapter(serverId = "server-1"): VoiceSessionAdapter { return { serverId, - setVoiceMode: vi.fn(async () => ({})), + setVoiceMode: vi.fn().mockResolvedValue(undefined), sendVoiceAudioChunk: vi.fn().mockResolvedValue(undefined), audioPlayed: vi.fn().mockResolvedValue(undefined), - readVoiceInputReceipts: vi.fn().mockResolvedValue({ items: [], nextCursor: null }), abortRequest: vi.fn().mockResolvedValue(undefined), setAssistantAudioPlaying: vi.fn(), }; @@ -538,394 +535,4 @@ describe("voice runtime", () => { expect(listener).not.toHaveBeenCalled(); unsubscribe(); }); - - it("reports playback failure instead of acknowledging success and plays the next reply", async () => { - const adapter = createSessionAdapter(); - const engine = createAudioEngineMock(); - vi.mocked(engine.play).mockRejectedValueOnce(new Error("audio output unavailable")); - const { runtime } = createRuntime({ engine }); - runtime.registerSession(adapter); - await runtime.startVoice("server-1", "agent-1"); - - runtime.handleAudioOutput( - "server-1", - createAudioPayload({ - id: "failed", - groupId: "failed-group", - chunkIndex: 0, - isLastChunk: true, - }), - ); - await vi.waitFor(() => - expect(adapter.audioPlayed).toHaveBeenCalledWith("failed", "audio output unavailable"), - ); - runtime.handleAudioOutput( - "server-1", - createAudioPayload({ - id: "recovered", - groupId: "recovered-group", - chunkIndex: 0, - isLastChunk: true, - }), - ); - await vi.waitFor(() => expect(adapter.audioPlayed).toHaveBeenCalledWith("recovered")); - expect(runtime.getSnapshot().phase).toBe("listening"); - await runtime.destroy(); - }); - - it("times out a stalled player, reports failure, and consumes the next reply", async () => { - const adapter = createSessionAdapter(); - const engine = createAudioEngineMock(); - vi.mocked(engine.play).mockImplementationOnce(() => new Promise(() => {})); - const { runtime } = createRuntime({ engine }); - runtime.registerSession(adapter); - await runtime.startVoice("server-1", "agent-1"); - runtime.handleAudioOutput( - "server-1", - createAudioPayload({ - id: "stalled", - groupId: "stalled-group", - chunkIndex: 0, - isLastChunk: true, - }), - ); - await vi.advanceTimersByTimeAsync(90_000); - expect(adapter.audioPlayed).toHaveBeenCalledWith("stalled", "Audio playback timed out"); - expect(engine.stop).toHaveBeenCalled(); - expect(engine.clearQueue).toHaveBeenCalled(); - runtime.handleAudioOutput( - "server-1", - createAudioPayload({ - id: "next", - groupId: "next-group", - chunkIndex: 0, - isLastChunk: true, - }), - ); - await vi.waitFor(() => expect(adapter.audioPlayed).toHaveBeenCalledWith("next")); - await runtime.destroy(); - }); - - it("drops stalled playback on reconnect so new audio can play", async () => { - const adapter = createSessionAdapter(); - const engine = createAudioEngineMock(); - let finishOldPlayback!: (duration: number) => void; - vi.mocked(engine.play).mockImplementationOnce( - () => - new Promise((resolve) => { - finishOldPlayback = resolve; - }), - ); - const { runtime } = createRuntime({ engine }); - runtime.registerSession(adapter); - await runtime.startVoice("server-1", "agent-1"); - runtime.handleAudioOutput( - "server-1", - createAudioPayload({ - id: "stale", - groupId: "stale-group", - chunkIndex: 0, - isLastChunk: false, - }), - ); - expect(engine.play).toHaveBeenCalledOnce(); - - runtime.updateSessionConnection("server-1", false); - runtime.updateSessionConnection("server-1", true); - await vi.waitFor(() => expect(runtime.getSnapshot().isVoiceSwitching).toBe(false)); - runtime.handleAudioOutput( - "server-1", - createAudioPayload({ - id: "fresh", - groupId: "fresh-group", - chunkIndex: 0, - isLastChunk: true, - }), - ); - await vi.waitFor(() => expect(adapter.audioPlayed).toHaveBeenCalledWith("fresh")); - finishOldPlayback(1); - await vi.advanceTimersByTimeAsync(0); - expect(adapter.audioPlayed).toHaveBeenCalledTimes(1); - expect(engine.stop).toHaveBeenCalled(); - expect(engine.clearQueue).toHaveBeenCalled(); - expect(engine.initialize).toHaveBeenCalledTimes(2); - await runtime.destroy(); - }); - - it("a stopped delayed start never restarts microphone capture", async () => { - const adapter = createSessionAdapter(); - let acknowledge!: () => void; - const acknowledgement = new Promise((resolve) => { - acknowledge = resolve; - }); - vi.mocked(adapter.setVoiceMode).mockImplementation(async (enabled, _agentId, input) => { - if (enabled) await acknowledgement; - return { attachmentId: input?.attachmentId, generation: "g1" }; - }); - const { runtime, engine } = createRuntime({ - getServerInfo: () => ({ ...createServerInfo(), features: { durableVoiceInputV1: true } }), - }); - runtime.registerSession(adapter); - const start = runtime.startVoice("server-1", "agent-1"); - await vi.waitFor(() => expect(adapter.setVoiceMode).toHaveBeenCalledTimes(1)); - const stop = runtime.stopVoice(); - acknowledge(); - await Promise.all([start, stop]); - expect(engine.startCapture).not.toHaveBeenCalled(); - expect(runtime.getSnapshot().isVoiceMode).toBe(false); - expect(adapter.setVoiceMode).toHaveBeenLastCalledWith(false, undefined, { - attachmentId: expect.any(String), - generation: "g1", - }); - }); - - it("an old host gets no durable attachment, so no receipts are read", async () => { - const adapter = createSessionAdapter(); - const { runtime, engine } = createRuntime({ - // No durableVoiceInputV1: the host predates the fork's receipt flow. - getServerInfo: () => ({ ...createServerInfo(), features: {} }), - }); - runtime.registerSession(adapter); - - await runtime.startVoice("server-1", "agent-1"); - - expect(engine.startCapture).toHaveBeenCalled(); - // An incapable host gets no durable transport options or receipt reads. - expect(adapter.setVoiceMode).toHaveBeenCalledExactlyOnceWith(true, "agent-1"); - expect(adapter.readVoiceInputReceipts).not.toHaveBeenCalled(); - await runtime.destroy(); - }); - - it("uses one logical attachment across reconnect and ignores stale transport output", async () => { - const adapter = createSessionAdapter(); - let generation = "g1"; - vi.mocked(adapter.setVoiceMode).mockImplementation(async (_enabled, _agentId, input) => ({ - attachmentId: input?.attachmentId, - generation, - })); - const { runtime, engine } = createRuntime({ - getServerInfo: () => ({ ...createServerInfo(), features: { durableVoiceInputV1: true } }), - }); - runtime.registerSession(adapter); - await runtime.startVoice("server-1", "agent-1"); - const firstStart = vi.mocked(adapter.setVoiceMode).mock.calls[0]; - const attachmentId = firstStart?.[2]?.attachmentId; - expect(attachmentId).toEqual(expect.any(String)); - runtime.handleCapturePcm(new Uint8Array([1, 2])); - expect(adapter.sendVoiceAudioChunk).toHaveBeenCalledWith( - expect.any(String), - expect.any(String), - { - attachmentId, - generation: "g1", - }, - ); - - runtime.onTranscriptionResult("server-1", "follow up", { - attachmentId, - generation: "g1", - queued: true, - messageId: `${attachmentId}:one`, - }); - expect(runtime.getSnapshot()).toMatchObject({ phase: "listening", lastInputStatus: "queued" }); - generation = "g2"; - runtime.updateSessionConnection("server-1", false); - vi.mocked(engine.play).mockClear(); - runtime.handleAudioOutput("server-1", { - ...createAudioPayload({ id: "in-gap", groupId: "in-gap", chunkIndex: 0, isLastChunk: true }), - attachmentId, - generation: "g1", - }); - expect(engine.play).not.toHaveBeenCalled(); - runtime.updateSessionConnection("server-1", true); - await vi.waitFor(() => expect(adapter.setVoiceMode).toHaveBeenCalledTimes(2)); - expect(vi.mocked(adapter.setVoiceMode).mock.calls[1]?.[2]?.attachmentId).toBe(attachmentId); - expect(runtime.acceptsVoiceTransport("server-1", { attachmentId, generation: "g1" })).toBe( - false, - ); - expect(runtime.acceptsVoiceTransport("server-1", { attachmentId, generation: "g2" })).toBe( - true, - ); - vi.mocked(engine.play).mockClear(); - runtime.handleAudioOutput("server-1", { - ...createAudioPayload({ id: "old", groupId: "old", chunkIndex: 0, isLastChunk: true }), - attachmentId, - generation: "g1", - }); - expect(engine.play).not.toHaveBeenCalled(); - await runtime.stopVoice(); - }); - - it("reconciles queued and submitted speech by message id without replaying admission", async () => { - const adapter = createSessionAdapter(); - vi.mocked(adapter.setVoiceMode).mockImplementation(async (_enabled, _agentId, input) => ({ - attachmentId: input?.attachmentId, - generation: "g1", - })); - const { runtime } = createRuntime({ - getServerInfo: () => ({ ...createServerInfo(), features: { durableVoiceInputV1: true } }), - }); - runtime.registerSession(adapter); - await runtime.startVoice("server-1", "agent-1"); - const attachmentId = vi.mocked(adapter.setVoiceMode).mock.calls[0]?.[2]?.attachmentId ?? ""; - vi.mocked(adapter.readVoiceInputReceipts).mockResolvedValue({ - items: [ - { messageId: `${attachmentId}:one`, state: "queued", createdAt: "2026-10-02T12:00:00Z" }, - ], - nextCursor: null, - }); - runtime.onQueueChanged("server-1", "agent-1"); - await vi.waitFor(() => expect(runtime.getSnapshot().lastInputStatus).toBe("queued")); - vi.mocked(adapter.readVoiceInputReceipts).mockResolvedValue({ - items: [ - { messageId: `${attachmentId}:one`, state: "submitted", createdAt: "2026-10-02T12:00:00Z" }, - ], - nextCursor: null, - }); - runtime.onQueueChanged("server-1", "agent-1"); - await vi.waitFor(() => expect(runtime.getSnapshot().lastInputStatus).toBe("sent")); - // A replayed transcript for an already-submitted id neither re-queues nor regresses. - runtime.onTranscriptionResult("server-1", "follow up", { - attachmentId, - generation: "g1", - queued: true, - messageId: `${attachmentId}:one`, - }); - expect(runtime.getSnapshot().lastInputStatus).toBe("sent"); - await runtime.stopVoice(); - }); -}); - -describe("voice failure reporting", () => { - beforeEach(() => { - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - /** Names of the local failure cues the engine was asked to play, in order. */ - function spokenFailureCues(engine: AudioEngine): string[] { - const kinds: VoiceFailureKind[] = [ - "nothing-recognized", - "recognition-stalled", - "recognition-failed", - "recognition-unavailable", - "host-disconnected", - "microphone-lost", - ]; - const bySize = new Map([[createVoiceReconnectedCue().size, "reconnected"]]); - for (const kind of kinds) bySize.set(createVoiceFailureCue(kind).size, kind); - return vi.mocked(engine.play).mock.calls.flatMap(([source]) => { - const name = source.type.includes("rate=12000") ? bySize.get(source.size) : undefined; - return name ? [name] : []; - }); - } - - function createCommandRuntime() { - const adapter = createSessionAdapter(); - vi.mocked(adapter.setVoiceMode).mockResolvedValue({}); - const { runtime, engine } = createRuntime(); - runtime.registerSession(adapter); - return { runtime, adapter, engine }; - } - - it("says and shows recognition failure and stops uploads instead of failing silently", async () => { - const { runtime, adapter, engine } = createCommandRuntime(); - await runtime.startVoice("server-1", "agent-1"); - for (let i = 0; i < 5; i++) { - runtime.onInputError( - "server-1", - "Speech recognition failed. Stop and restart voice to reconnect.", - ); - runtime.onRecognitionIssue("server-1", "failed"); - } - runtime.handleCapturePcm(new Uint8Array([1, 2])); - expect(adapter.sendVoiceAudioChunk).not.toHaveBeenCalled(); - expect(runtime.getSnapshot()).toMatchObject({ failure: "recognition-failed" }); - expect(spokenFailureCues(engine)).toEqual(["recognition-failed"]); - await runtime.destroy(); - }); - - it("says a host disconnect once through flapping and says when it is back", async () => { - const { runtime, engine } = createCommandRuntime(); - await runtime.startVoice("server-1", "agent-1"); - runtime.onRecognitionIssue("server-1", "nothing_recognized"); - await vi.advanceTimersByTimeAsync(5_000); - runtime.updateSessionConnection("server-1", false); - expect(runtime.getSnapshot().failure).toBe("host-disconnected"); - runtime.updateSessionConnection("server-1", true); - await vi.advanceTimersByTimeAsync(0); - expect(runtime.getSnapshot().failure).toBeNull(); - for (let i = 0; i < 10; i++) { - runtime.updateSessionConnection("server-1", false); - await vi.advanceTimersByTimeAsync(200); - runtime.updateSessionConnection("server-1", true); - await vi.advanceTimersByTimeAsync(200); - } - expect(spokenFailureCues(engine)).toEqual([ - "nothing-recognized", - "host-disconnected", - "reconnected", - ]); - await runtime.destroy(); - }); - - it("says a missed utterance once and shows it until recognition works again", async () => { - const { runtime, engine } = createCommandRuntime(); - await runtime.startVoice("server-1", "agent-1"); - runtime.onTranscriptionResult("server-1", ""); - runtime.onRecognitionIssue("server-1", "nothing_recognized"); - runtime.onRecognitionIssue("server-1", "nothing_recognized"); - expect(runtime.getSnapshot()).toMatchObject({ - phase: "listening", - failure: "nothing-recognized", - }); - runtime.onTranscriptionResult("server-1", "run the tests"); - expect(runtime.getSnapshot().failure).toBeNull(); - // A repeat inside the re-announce floor stays quiet; an unknown issue is ignored. - await vi.advanceTimersByTimeAsync(5_000); - runtime.onRecognitionIssue("server-1", "nothing_recognized"); - runtime.onRecognitionIssue("server-1", "a_future_issue"); - expect(runtime.getSnapshot().failure).toBe("nothing-recognized"); - expect(spokenFailureCues(engine)).toEqual(["nothing-recognized"]); - await runtime.destroy(); - }); - - it("reports an unknown recognition issue kind without speaking it", async () => { - const { runtime, engine } = createCommandRuntime(); - await runtime.startVoice("server-1", "agent-1"); - runtime.onRecognitionIssue("server-1", "a_future_issue"); - expect(runtime.getSnapshot().failure).toBeNull(); - expect(spokenFailureCues(engine)).toEqual([]); - await runtime.destroy(); - }); - - it("says the microphone was lost before stopping voice, even if the player never settles", async () => { - const { runtime, engine, adapter } = createCommandRuntime(); - await runtime.startVoice("server-1", "agent-1"); - vi.mocked(engine.play).mockReturnValue(new Promise(() => {})); - const stopped = runtime.handleMicrophoneLost(); - await vi.advanceTimersByTimeAsync(0); - expect(spokenFailureCues(engine)).toEqual(["microphone-lost"]); - expect(engine.stopCapture).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(4_000); - await stopped; - expect(engine.stopCapture).toHaveBeenCalled(); - expect(adapter.setVoiceMode).toHaveBeenLastCalledWith(false); - expect(runtime.getSnapshot()).toMatchObject({ isVoiceMode: false, failure: null }); - await runtime.destroy(); - }); - - it("says recognition is unavailable when the host cannot start it", async () => { - const { runtime, engine, adapter } = createCommandRuntime(); - vi.mocked(adapter.setVoiceMode).mockRejectedValueOnce( - new Error("Local speech models are still downloading (stt_unavailable)"), - ); - await expect(runtime.startVoice("server-1", "agent-1")).rejects.toThrow("downloading"); - expect(spokenFailureCues(engine)).toEqual(["recognition-unavailable"]); - expect(runtime.getSnapshot()).toMatchObject({ isVoiceMode: false, failure: null }); - await runtime.destroy(); - }); }); diff --git a/packages/app/src/voice/voice-runtime.ts b/packages/app/src/voice/voice-runtime.ts index bda08c4f3aa..3b7843e2f74 100644 --- a/packages/app/src/voice/voice-runtime.ts +++ b/packages/app/src/voice/voice-runtime.ts @@ -2,14 +2,7 @@ import { Buffer } from "buffer"; import type { AgentStreamEventPayload, SessionOutboundMessage } from "@getpaseo/protocol/messages"; import { resolveVoiceUnavailableMessage } from "@/utils/server-info-capabilities"; import type { DaemonServerInfo } from "@/stores/session-store"; -import { createInputReceiptCue } from "@/voice/input-receipt-cue"; -import { - createVoiceFailureTracker, - voiceFailureFromRecognitionIssue, - type VoiceFailureKind, -} from "@/voice/voice-failure"; -import { createVoiceFailureCue, createVoiceReconnectedCue } from "@/voice/voice-failure-cue"; -import type { AudioEngine, AudioPlaybackSource } from "@/audio"; +import type { AudioEngine } from "@/audio"; import { THINKING_TONE_NATIVE_PCM_BASE64, THINKING_TONE_NATIVE_PCM_DURATION_MS, @@ -25,12 +18,6 @@ const THINKING_TONE_REPEAT_GAP_MS = 350; * silence has outlasted those gaps. */ const THINKING_TONE_MIN_SILENCE_MS = 1500; -// TTS emits bounded text segments. Recover locally before the daemon's 120s -// acknowledgement deadline, even if a platform player never settles play(). -const PLAYBACK_TIMEOUT_MS = 90_000; -// Before voice stops over a failure, give its spoken cue this long to finish. A player that -// never settles, such as one blocked by a phone call, must not hold the stop. -const FAILURE_CUE_BEFORE_STOP_MAX_MS = 4_000; const DISPLAY_VOLUME_PUBLISH_INTERVAL_MS = 120; const DISPLAY_VOLUME_CHANGE_EPSILON = 0.02; const DISPLAY_VOLUME_ATTACK = 0.35; @@ -50,17 +37,11 @@ export type VoiceRuntimePhase = | "playing" | "stopping"; -export type VoiceInputStatus = "queued" | "sent" | "removed" | "unknown"; - export interface VoiceRuntimeSnapshot { phase: VoiceRuntimePhase; isVoiceMode: boolean; isVoiceSwitching: boolean; isMuted: boolean; - /** The input problem to show in the voice panel; also spoken when it begins. */ - failure: VoiceFailureKind | null; - /** Delivery state of the most recent spoken follow-up, from daemon receipts. */ - lastInputStatus: VoiceInputStatus | null; activeServerId: string | null; activeAgentId: string | null; } @@ -71,38 +52,12 @@ export interface VoiceRuntimeTelemetrySnapshot { segmentDuration: number; } -/** Identifies the voice attachment a voice message belongs to. */ -export interface VoiceTransport { - attachmentId: string; - generation: string; -} - export interface VoiceSessionAdapter { serverId: string; - setVoiceMode( - enabled: boolean, - agentId?: string, - input?: { attachmentId?: string; generation?: string }, - ): Promise<{ attachmentId?: string; generation?: string }>; - sendVoiceAudioChunk( - audioData: string, - mimeType: string, - transport?: VoiceTransport, - ): Promise; - audioPlayed(chunkId: string, error?: string, transport?: VoiceTransport): Promise; - readVoiceInputReceipts(input: { - agentId: string; - attachmentId: string; - generation: string; - after?: string; - limit?: number; - }): Promise< - Pick< - Extract["payload"], - "items" | "nextCursor" - > - >; - abortRequest(transport?: VoiceTransport): Promise; + setVoiceMode(enabled: boolean, agentId?: string): Promise; + sendVoiceAudioChunk(audioData: string, mimeType: string): Promise; + audioPlayed(chunkId: string): Promise; + abortRequest(): Promise; setAssistantAudioPlaying(isPlaying: boolean): void; } @@ -130,9 +85,6 @@ interface RuntimeState { serverSpeechDetected: boolean; transportReady: boolean; generation: number; - /** Logical attachment across reconnects; the transport generation changes each reclaim. */ - attachmentId: string | null; - transportGeneration: string | null; segmentDurationTimer: ReturnType | null; lastDisplayVolumePublishMs: number; serverSpeechStartedAt: number | null; @@ -175,8 +127,6 @@ const INITIAL_SNAPSHOT: VoiceRuntimeSnapshot = { isVoiceMode: false, isVoiceSwitching: false, isMuted: false, - failure: null, - lastInputStatus: null, activeServerId: null, activeAgentId: null, }; @@ -195,8 +145,6 @@ function snapshotsEqual(left: VoiceRuntimeSnapshot, right: VoiceRuntimeSnapshot) left.isVoiceMode === right.isVoiceMode && left.isVoiceSwitching === right.isVoiceSwitching && left.isMuted === right.isMuted && - left.failure === right.failure && - left.lastInputStatus === right.lastInputStatus && left.activeServerId === right.activeServerId && left.activeAgentId === right.activeAgentId ); @@ -231,28 +179,8 @@ export interface VoiceRuntime { shouldPlayVoiceAudio(serverId: string): boolean; onAssistantAudioStarted(serverId: string): void; onAssistantAudioFinished(serverId: string): void; - onTranscriptionResult( - serverId: string, - text: string, - payload?: { - attachmentId?: string; - generation?: string; - queued?: boolean; - messageId?: string; - }, - ): void; - /** True when a voice message belongs to the current attachment incarnation. */ - acceptsVoiceTransport( - serverId: string, - payload: { attachmentId?: string; generation?: string }, - ): boolean; - /** A queue snapshot changed on the host; re-read this attachment's receipts. */ - onQueueChanged(serverId: string, agentId: string): void; + onTranscriptionResult(serverId: string, text: string): void; onServerSpeechStateChanged(serverId: string, isSpeaking: boolean): void; - onInputError(serverId: string, error: string): void; - onRecognitionIssue(serverId: string, issue: string): void; - /** The device stopped delivering microphone audio. Announces it, then stops voice. */ - handleMicrophoneLost(): Promise; onTurnEvent(serverId: string, agentId: string, eventType: TurnEventType): void; } @@ -268,8 +196,6 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { serverSpeechDetected: false, transportReady: false, generation: 0, - attachmentId: null, - transportGeneration: null, segmentDurationTimer: null, lastDisplayVolumePublishMs: 0, serverSpeechStartedAt: null, @@ -285,10 +211,6 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { controller: null, timeout: null, }; - const failures = createVoiceFailureTracker(); - const inputStatuses = new Map(); - let receiptReadTail: Promise = Promise.resolve(); - let voiceLifecycleTail: Promise = Promise.resolve(); const cuePcm16 = Uint8Array.from(Buffer.from(THINKING_TONE_NATIVE_PCM_BASE64, "base64")); const cueSource = { size: cuePcm16.byteLength, @@ -403,15 +325,12 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { } } - async function acknowledgeChunk(chunkId: string, error?: string): Promise { + async function acknowledgeChunk(chunkId: string): Promise { const activeSession = getActiveSession(); if (!activeSession) { return; } - const transport = voiceTransport(); - if (transport) await activeSession.adapter.audioPlayed(chunkId, error, transport); - else if (error === undefined) await activeSession.adapter.audioPlayed(chunkId); - else await activeSession.adapter.audioPlayed(chunkId, error); + await activeSession.adapter.audioPlayed(chunkId); } async function processPlaybackQueue(serverId: string): Promise { @@ -452,27 +371,15 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { api.onAssistantAudioStarted(serverId); } - let playbackError: string | undefined; - let playbackTimeout: ReturnType | undefined; try { if (group.shouldPlay) { - const timeout = new Promise((_resolve, reject) => { - playbackTimeout = setTimeout(() => { - reject(new Error("Audio playback timed out")); - }, PLAYBACK_TIMEOUT_MS); - }); - await Promise.race([deps.engine.play(nextChunk.source), timeout]); + await deps.engine.play(nextChunk.source); } } catch (error) { if (generation !== playback.generation) { return; } console.error(`[VoiceRuntime] play error chunk=${group.nextChunkToPlay}:`, error); - playbackError = error instanceof Error ? error.message : String(error); - deps.engine.stop(); - deps.engine.clearQueue(); - } finally { - clearTimeout(playbackTimeout); } if (generation !== playback.generation) { @@ -481,7 +388,7 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { if (!group.ackedChunkIds.has(nextChunk.id)) { group.ackedChunkIds.add(nextChunk.id); - void acknowledgeChunk(nextChunk.id, playbackError).catch((error) => { + void acknowledgeChunk(nextChunk.id).catch((error) => { console.warn("[VoiceRuntime] Failed to confirm audio playback:", error); }); } @@ -582,44 +489,6 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { cue.timeout = setTimeout(playNext, THINKING_TONE_MIN_SILENCE_MS); } - function playLocalCue(source: AudioPlaybackSource, label: string): Promise { - return deps.engine.play(source).then( - () => undefined, - (error) => { - console.warn(`[VoiceRuntime#${instanceId}] ${label} cue failed:`, error); - }, - ); - } - - /** Shows the failure, and speaks it when it starts a new episode. */ - function reportFailure(kind: VoiceFailureKind): Promise { - const announce = failures.report(kind); - patchSnapshot({ failure: failures.current() }); - if (!announce) { - return Promise.resolve(); - } - // The thinking tone would otherwise suggest the agent is still working on what was said. - stopCue(); - return playLocalCue(createVoiceFailureCue(kind), "Failure"); - } - - function clearFailures(kinds: readonly VoiceFailureKind[]): VoiceFailureKind[] { - const recovered = failures.clear(kinds); - patchSnapshot({ failure: failures.current() }); - return recovered; - } - - async function reportFailureBeforeStopping(kind: VoiceFailureKind): Promise { - let timeout: ReturnType | undefined; - await Promise.race([ - reportFailure(kind), - new Promise((resolve) => { - timeout = setTimeout(resolve, FAILURE_CUE_BEFORE_STOP_MAX_MS); - }), - ]); - clearTimeout(timeout); - } - const uploader: ContinuousVoiceUploader = { reset() {}, pushPcmChunk(chunk) { @@ -635,37 +504,14 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { const base64 = Buffer.from(chunk).toString("base64"); - const transport = voiceTransport(); - const upload = transport - ? activeSession.adapter.sendVoiceAudioChunk(base64, PCM_MIME_TYPE, transport) - : activeSession.adapter.sendVoiceAudioChunk(base64, PCM_MIME_TYPE); - void upload.catch((error) => { + void activeSession.adapter.sendVoiceAudioChunk(base64, PCM_MIME_TYPE).catch((error) => { console.error(`[VoiceRuntime#${instanceId}] Failed to send audio chunk:`, error); }); }, }; - function disableVoice( - adapter: VoiceSessionAdapter, - transport?: { attachmentId: string; generation: string }, - ): Promise { - return transport - ? adapter.setVoiceMode(false, undefined, transport) - : adapter.setVoiceMode(false); - } - - function voiceTransport(): VoiceTransport | undefined { - return state.attachmentId && state.transportGeneration - ? { attachmentId: state.attachmentId, generation: state.transportGeneration } - : undefined; - } - function resetToDisabledState(): void { - failures.reset(); - inputStatuses.clear(); state.transportReady = false; - state.attachmentId = null; - state.transportGeneration = null; state.turnInProgress = false; state.serverSpeechDetected = false; state.lastDisplayVolumePublishMs = 0; @@ -674,61 +520,6 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { patchSnapshot({ ...INITIAL_SNAPSHOT }); } - function applyInputStatus(messageId: string, status: VoiceInputStatus, playCue: boolean): void { - const previous = inputStatuses.get(messageId); - if ( - previous === "sent" || - previous === "removed" || - (previous === "unknown" && status === "queued") - ) - return; - if (previous === status) return; - inputStatuses.set(messageId, status); - patchSnapshot({ lastInputStatus: status }); - if (playCue && (status === "queued" || status === "sent")) { - void playLocalCue( - createInputReceiptCue(status), - status === "queued" ? "Queued" : "Sent to agent", - ); - } - } - - function reconcileInputReceipts(playCue: boolean): void { - receiptReadTail = receiptReadTail - .catch(() => undefined) - .then(async () => { - const active = getActiveSession(); - const agentId = state.snapshot.activeAgentId; - const attachmentId = state.attachmentId; - const generation = state.transportGeneration; - if (!active || !agentId || !attachmentId || !generation || !state.transportReady) return; - let after: string | undefined; - do { - const page = await active.adapter.readVoiceInputReceipts({ - agentId, - attachmentId, - generation, - ...(after ? { after } : {}), - limit: 100, - }); - if (generation !== state.transportGeneration || attachmentId !== state.attachmentId) - return; - for (const item of page.items) { - applyInputStatus( - item.messageId, - item.state === "submitted" ? "sent" : item.state, - playCue, - ); - } - after = page.nextCursor ?? undefined; - } while (after); - return undefined; - }) - .catch((error) => { - console.warn(`[VoiceRuntime#${instanceId}] Could not reconcile voice receipts:`, error); - }); - } - function publishDisplayVolume(level: number, nowMs: number): void { const previousVolume = state.telemetry.volume; const smoothing = level >= previousVolume ? DISPLAY_VOLUME_ATTACK : DISPLAY_VOLUME_RELEASE; @@ -763,8 +554,6 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { resetToDisabledState(); } - // The reconnect transition keeps its generation checks and failure cleanup together. - // oxlint-disable-next-line complexity async function resyncVoiceMode(serverId: string): Promise { if ( !state.snapshot.isVoiceMode || @@ -779,50 +568,12 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { return; } - const generation = state.generation; patchSnapshot((prev) => ({ ...prev, isVoiceSwitching: true })); try { - await deps.engine.initialize(); - if (generation !== state.generation) return; - const options = state.attachmentId ? { attachmentId: state.attachmentId } : undefined; - const response = options - ? await activeSession.adapter.setVoiceMode(true, state.snapshot.activeAgentId, options) - : await activeSession.adapter.setVoiceMode(true, state.snapshot.activeAgentId); - if (generation !== state.generation) { - if (response.attachmentId && response.generation) - await activeSession.adapter.setVoiceMode(false, undefined, { - attachmentId: response.attachmentId, - generation: response.generation, - }); - return; - } - if ( - state.attachmentId && - (response.attachmentId !== state.attachmentId || !response.generation) - ) - throw new Error("Host did not acknowledge this voice attachment"); + await activeSession.adapter.setVoiceMode(true, state.snapshot.activeAgentId); state.transportReady = true; - state.transportGeneration = response.generation ?? null; - reconcileInputReceipts(false); - // The host re-created its recognizer, so every earlier failure is stale. - const recovered = clearFailures([ - "host-disconnected", - "recognition-unavailable", - "recognition-failed", - "recognition-stalled", - "nothing-recognized", - ]); - if (recovered.includes("host-disconnected")) { - void playLocalCue(createVoiceReconnectedCue(), "Reconnected"); - } - } catch (error) { - if (generation !== state.generation) return; - console.warn(`[VoiceRuntime#${instanceId}] Voice reconnect failed:`, error); - void reportFailure("host-disconnected"); } finally { - if (generation === state.generation) { - patchSnapshot((prev) => ({ ...prev, isVoiceSwitching: false })); - } + patchSnapshot((prev) => ({ ...prev, isVoiceSwitching: false })); } } @@ -875,18 +626,6 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { } if (!connected) { state.transportReady = false; - state.transportGeneration = null; - if (!state.snapshot.isVoiceMode) return; - state.generation += 1; - state.turnInProgress = false; - state.serverSpeechDetected = false; - resetCaptureTelemetry(); - resetPlaybackState(); - stopCue(); - deps.engine.stop(); - deps.engine.clearQueue(); - session.adapter.setAssistantAudioPlaying(false); - void reportFailure("host-disconnected"); return; } void resyncVoiceMode(serverId); @@ -928,7 +667,6 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { ) { return; } - if (!api.acceptsVoiceTransport(serverId, payload)) return; const groupId = payload.groupId ?? payload.id; const chunkIndex = payload.chunkIndex ?? 0; @@ -965,162 +703,111 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { void processPlaybackQueue(serverId); }, - // Capture admission, generation checks, and rollback are one transition. - // oxlint-disable-next-line complexity async startVoice(serverId, agentId) { - const requestedGeneration = ++state.generation; - const operation = voiceLifecycleTail - .catch(() => undefined) - // Capture admission and rollback must remain in the same serialized transition. - // oxlint-disable-next-line complexity - .then(async () => { - if (requestedGeneration !== state.generation) return undefined; - const session = sessions.get(serverId); - if (!session) { - throw new Error(`Voice runtime is not ready for host ${serverId}`); - } - if (!session.connected) { - throw new Error(`Host ${serverId} is not connected`); - } + const session = sessions.get(serverId); + if (!session) { + throw new Error(`Voice runtime is not ready for host ${serverId}`); + } + if (!session.connected) { + throw new Error(`Host ${serverId} is not connected`); + } - const serverInfo = deps.getServerInfo(serverId); - const unavailableMessage = resolveVoiceUnavailableMessage({ - serverInfo, - mode: "voice", - }); - if (unavailableMessage) { - throw new Error(unavailableMessage); - } + const serverInfo = deps.getServerInfo(serverId); + const unavailableMessage = resolveVoiceUnavailableMessage({ + serverInfo, + mode: "voice", + }); + if (unavailableMessage) { + throw new Error(unavailableMessage); + } - const previousTransport = voiceTransport(); - const previousServerId = state.snapshot.activeServerId; - const previousAgentId = state.snapshot.activeAgentId; - const generation = requestedGeneration; - let enabledCurrentVoiceMode = false; - state.generation = generation; - inputStatuses.clear(); - state.attachmentId = - serverInfo?.features?.durableVoiceInputV1 === true ? crypto.randomUUID() : null; - state.transportGeneration = null; - state.transportReady = false; - patchSnapshot((prev) => ({ - ...prev, - isVoiceSwitching: true, - phase: "starting", - activeServerId: serverId, - activeAgentId: agentId, - })); - - try { - if ( - state.snapshot.isVoiceMode && - previousServerId && - (previousServerId !== serverId || previousAgentId !== agentId) - ) { - const previousSession = sessions.get(previousServerId); - if (previousSession) { - previousSession.adapter.setAssistantAudioPlaying(false); - await disableVoice(previousSession.adapter, previousTransport); - } - } - - await deps.activateKeepAwake(KEEP_AWAKE_TAG).catch((error) => { - console.warn("[VoiceRuntime] Failed to activate keep-awake:", error); - }); - - await deps.engine.initialize(); - if (generation !== state.generation) return undefined; - let response: { attachmentId?: string; generation?: string }; - try { - response = state.attachmentId - ? await session.adapter.setVoiceMode(true, agentId, { - attachmentId: state.attachmentId, - }) - : await session.adapter.setVoiceMode(true, agentId); - } catch (error) { - // The host starts its recognizer while enabling voice mode, so a rejection with the - // host still connected means recognition could not start there. - await reportFailureBeforeStopping( - session.connected ? "recognition-unavailable" : "host-disconnected", - ); - throw error; - } - enabledCurrentVoiceMode = true; - state.transportGeneration = response.generation ?? null; - if (generation !== state.generation) { - await disableVoice(session.adapter, voiceTransport()); - return undefined; - } - if ( - state.attachmentId && - (response.attachmentId !== state.attachmentId || !response.generation) - ) - throw new Error("Host did not acknowledge this voice attachment"); - await deps.engine.startCapture(); - if (state.generation !== generation) { - return undefined; - } - - state.transportReady = true; - state.turnInProgress = false; - uploader.reset(); - resetCaptureTelemetry(); - reconcileInputReceipts(false); - patchSnapshot((prev) => ({ - ...prev, - isVoiceMode: true, - isVoiceSwitching: false, - phase: "listening", - isMuted: deps.engine.isMuted(), - failure: null, - })); - } catch (error) { - if (enabledCurrentVoiceMode) { - await disableVoice(session.adapter, voiceTransport()).catch(() => undefined); - } - await performLocalStop(); - throw error; + const previousServerId = state.snapshot.activeServerId; + const previousAgentId = state.snapshot.activeAgentId; + const generation = state.generation + 1; + let enabledCurrentVoiceMode = false; + state.generation = generation; + state.transportReady = false; + patchSnapshot((prev) => ({ + ...prev, + isVoiceSwitching: true, + phase: "starting", + activeServerId: serverId, + activeAgentId: agentId, + })); + + try { + if ( + state.snapshot.isVoiceMode && + previousServerId && + (previousServerId !== serverId || previousAgentId !== agentId) + ) { + const previousSession = sessions.get(previousServerId); + if (previousSession) { + previousSession.adapter.setAssistantAudioPlaying(false); + await previousSession.adapter.setVoiceMode(false); } - return undefined; + } + + await deps.activateKeepAwake(KEEP_AWAKE_TAG).catch((error) => { + console.warn("[VoiceRuntime] Failed to activate keep-awake:", error); }); - voiceLifecycleTail = operation; - return operation as Promise; - }, - async stopVoice() { - const requestedGeneration = ++state.generation; - const stopCurrentVoice = async () => { - const activeSession = getActiveSession(); - const generation = requestedGeneration; + await deps.engine.initialize(); + await session.adapter.setVoiceMode(true, agentId); + enabledCurrentVoiceMode = true; + await deps.engine.startCapture(); + if (state.generation !== generation) { + return; + } + + state.transportReady = true; + state.turnInProgress = false; + uploader.reset(); + resetCaptureTelemetry(); patchSnapshot((prev) => ({ ...prev, - isVoiceSwitching: true, - phase: "stopping", + isVoiceMode: true, + isVoiceSwitching: false, + phase: "listening", + isMuted: deps.engine.isMuted(), })); + } catch (error) { + if (enabledCurrentVoiceMode) { + await session.adapter.setVoiceMode(false).catch(() => undefined); + } + await performLocalStop(); + throw error; + } + }, - try { - stopCue(); - uploader.reset(); - state.transportReady = false; - resetPlaybackState(); - deps.engine.stop(); - deps.engine.clearQueue(); - activeSession?.adapter.setAssistantAudioPlaying(false); - if (activeSession) { - await disableVoice(activeSession.adapter, voiceTransport()); - } - } finally { - await deps.engine.stopCapture().catch(() => undefined); - await deps.deactivateKeepAwake(KEEP_AWAKE_TAG).catch(() => undefined); - if (state.generation === generation) { - resetToDisabledState(); - } + async stopVoice() { + const activeSession = getActiveSession(); + const generation = state.generation + 1; + state.generation = generation; + patchSnapshot((prev) => ({ + ...prev, + isVoiceSwitching: true, + phase: "stopping", + })); + + try { + stopCue(); + uploader.reset(); + state.transportReady = false; + resetPlaybackState(); + deps.engine.stop(); + deps.engine.clearQueue(); + activeSession?.adapter.setAssistantAudioPlaying(false); + if (activeSession) { + await activeSession.adapter.setVoiceMode(false); } - return undefined; - }; - const operation = voiceLifecycleTail.catch(() => undefined).then(stopCurrentVoice); - voiceLifecycleTail = operation; - return operation as Promise; + await deps.engine.stopCapture(); + await deps.deactivateKeepAwake(KEEP_AWAKE_TAG).catch(() => undefined); + } finally { + if (state.generation === generation) { + resetToDisabledState(); + } + } }, async destroy() { @@ -1193,40 +880,12 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { reconcileCue(); }, - acceptsVoiceTransport(serverId, payload) { - if (serverId !== state.snapshot.activeServerId) return false; - if (!state.attachmentId) return true; - return ( - !!state.transportGeneration && - payload.generation === state.transportGeneration && - payload.attachmentId === state.attachmentId - ); - }, - - onTranscriptionResult(serverId, text, payload) { - if ( - serverId !== state.snapshot.activeServerId || - !state.snapshot.isVoiceMode || - !api.acceptsVoiceTransport(serverId, payload ?? {}) - ) { + onTranscriptionResult(serverId, text) { + if (serverId !== state.snapshot.activeServerId || !state.snapshot.isVoiceMode) { return; } - if (state.transportGeneration && text.trim() && payload?.queued !== true) return; - - if (payload?.messageId && payload.queued) { - applyInputStatus(payload.messageId, "queued", true); - } if (text.trim()) { - // Recognition works again, so the next miss or stall is a new episode. - clearFailures(["nothing-recognized", "recognition-stalled", "recognition-failed"]); - if (state.attachmentId) { - // Admission is durable; the queue snapshot drives the follow-up's phase. - state.turnInProgress = false; - patchSnapshot((prev) => ({ ...prev, phase: "listening" })); - stopCue(); - return; - } state.turnInProgress = true; patchSnapshot((prev) => ({ ...prev, phase: "waiting" })); reconcileCue(); @@ -1238,12 +897,6 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { stopCue(); }, - onQueueChanged(serverId, agentId) { - if (state.snapshot.activeServerId === serverId && state.snapshot.activeAgentId === agentId) { - reconcileInputReceipts(true); - } - }, - onServerSpeechStateChanged(serverId, isSpeaking) { if (serverId !== state.snapshot.activeServerId || !state.snapshot.isVoiceMode) { return; @@ -1270,27 +923,6 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { reconcileCue(); }, - onInputError(serverId, error) { - if (serverId !== state.snapshot.activeServerId || !state.snapshot.isVoiceMode) return; - console.warn(`[VoiceRuntime#${instanceId}] Host input error: ${error}`); - state.transportReady = false; - void reportFailure("recognition-failed"); - }, - - onRecognitionIssue(serverId, issue) { - if (serverId !== state.snapshot.activeServerId || !state.snapshot.isVoiceMode) return; - const kind = voiceFailureFromRecognitionIssue(issue); - // Muted capture uploads nothing; a miss while muted is not news. - if (!kind || (kind === "nothing-recognized" && state.snapshot.isMuted)) return; - void reportFailure(kind); - }, - - async handleMicrophoneLost() { - if (!state.snapshot.isVoiceMode) return; - await reportFailureBeforeStopping("microphone-lost"); - await api.stopVoice(); - }, - onTurnEvent(serverId, agentId, eventType) { if ( !state.snapshot.isVoiceMode || @@ -1301,7 +933,6 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime { } if (eventType === "turn_started") { - reconcileInputReceipts(true); state.turnInProgress = true; if (state.snapshot.phase !== "playing") { patchSnapshot((prev) => ({ ...prev, phase: "waiting" })); diff --git a/packages/app/test-stubs/lucide-react-native.ts b/packages/app/test-stubs/lucide-react-native.ts index dededa4f4cc..72199773f95 100644 --- a/packages/app/test-stubs/lucide-react-native.ts +++ b/packages/app/test-stubs/lucide-react-native.ts @@ -68,7 +68,6 @@ export const MessageSquare = StubIcon; export const MessageSquarePlus = StubIcon; export const Mic = StubIcon; export const MicOff = StubIcon; -export const PhoneOff = StubIcon; export const Monitor = StubIcon; export const Moon = StubIcon; export const MoreHorizontal = StubIcon; diff --git a/packages/cli/src/commands/agent/artifacts-scan.ts b/packages/cli/src/commands/agent/artifacts-scan.ts deleted file mode 100644 index 4d75d3928cf..00000000000 --- a/packages/cli/src/commands/agent/artifacts-scan.ts +++ /dev/null @@ -1,96 +0,0 @@ -import type { Command } from "commander"; -import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; -import { connectToDaemon, getDaemonHost, resolveAgentId } from "../../utils/client.js"; -import { selectDaemonTarget } from "../../utils/daemon-target.js"; -import type { - CommandError, - CommandOptions, - OutputSchema, - SingleResult, -} from "../../output/index.js"; - -interface AgentArtifactsScanResult { - agentId: string; - addedOrUpdated: number; - total: number; -} - -const artifactsScanSchema: OutputSchema = { - idField: "agentId", - columns: [ - { header: "AGENT ID", field: "agentId" }, - { header: "ADDED/UPDATED", field: "addedOrUpdated" }, - { header: "TOTAL", field: "total" }, - ], -}; - -export interface ArtifactsScanOptions extends CommandOptions { - limit?: string; -} - -export function addArtifactsScanOptions(command: Command): Command { - return command.option( - "--limit ", - "Maximum artifacts to retain, newest first (default: daemon default)", - ); -} - -/** - * Backfills an agent's artifact feed from files already on disk. - * - * Artifacts are normally collected per turn, so an agent that did its work - * before the feature existed shows an empty feed no matter how much it - * produced. This scans its working directory once and records what it finds. - */ -export async function runArtifactsScanCommand( - agentIdArg: string, - options: ArtifactsScanOptions, - _command: Command, -): Promise> { - let limit: number | undefined; - if (options.limit !== undefined) { - const parsed = Number.parseInt(options.limit, 10); - if (!Number.isFinite(parsed) || parsed <= 0) { - throw { - code: "INVALID_ARGUMENT", - message: `--limit must be a positive integer, got: ${options.limit}`, - } satisfies CommandError; - } - limit = parsed; - } - - const daemonTarget = selectDaemonTarget(options); - const host = getDaemonHost({ target: daemonTarget }); - let client: DaemonClient; - try { - client = await connectToDaemon({ target: daemonTarget }); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - throw { - code: "DAEMON_NOT_RUNNING", - message: `Cannot connect to daemon at ${host}: ${message}`, - } satisfies CommandError; - } - - try { - const payload = await client.fetchAgents({ filter: { includeArchived: true } }); - const agentId = resolveAgentId( - agentIdArg, - payload.entries.map((entry) => entry.agent), - ); - if (!agentId) { - throw { - code: "AGENT_NOT_FOUND", - message: `Agent not found: ${agentIdArg}`, - } satisfies CommandError; - } - const result = await client.scanAgentArtifacts(agentId, limit !== undefined ? { limit } : {}); - return { - type: "single", - data: { agentId, addedOrUpdated: result.addedOrUpdated, total: result.total }, - schema: artifactsScanSchema, - }; - } finally { - await client.close().catch(() => undefined); - } -} diff --git a/packages/cli/src/commands/agent/index.ts b/packages/cli/src/commands/agent/index.ts index 345565ef09e..e15f2b5a088 100644 --- a/packages/cli/src/commands/agent/index.ts +++ b/packages/cli/src/commands/agent/index.ts @@ -11,7 +11,6 @@ import { addInspectOptions, runInspectCommand } from "./inspect.js"; import { addWaitOptions, runWaitCommand } from "./wait.js"; import { addAttachOptions, runAttachCommand } from "./attach.js"; import { addReloadOptions, runReloadCommand } from "./reload.js"; -import { addArtifactsScanOptions, runArtifactsScanCommand } from "./artifacts-scan.js"; import { addImportOptions, runImportCommand } from "./import.js"; import { runUpdateCommand } from "./update.js"; import { runDetachCommand } from "./detach.js"; @@ -88,15 +87,6 @@ export function createAgentCommand(): Command { withOutput(runReloadCommand), ); - addJsonAndDaemonHostOptions( - addArtifactsScanOptions( - agent - .command("artifacts-scan") - .description("Backfill an agent's artifact feed from files already on disk") - .argument("", "Agent ID, prefix, or name"), - ), - ).action(withOutput(runArtifactsScanCommand)); - addJsonAndDaemonHostOptions( agent .command("detach") diff --git a/packages/client/src/connection/index.ts b/packages/client/src/connection/index.ts index 626edf6f0fc..32bf6029780 100644 --- a/packages/client/src/connection/index.ts +++ b/packages/client/src/connection/index.ts @@ -152,11 +152,7 @@ export const DEFAULT_CLIENT_CAPABILITIES = { [CLIENT_CAPS.workspaceSetupObservation]: true, [CLIENT_CAPS.pluginBinaryPayloads]: true, [CLIENT_CAPS.backgroundAgents]: true, - [CLIENT_CAPS.durableAgentQueue]: true, - [CLIENT_CAPS.durableVoiceInputV1]: true, [CLIENT_CAPS.explicitEventSubscriptions]: true, - // COMPAT(companionStreamPortV1): added in v0.11.0-beta.3-fork, remove after 2027-04-01. - [CLIENT_CAPS.companionStreamPortV1]: true, } satisfies Record, true>; /** Calling releases demand; ready waits for membership, or local attachment on broadcast hosts. */ diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index df3d8120b0f..236d1f8dc21 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -1143,9 +1143,6 @@ test("advertises client capabilities in hello", async () => { terminal_reflowable_snapshot: true, terminal_chunked_replay: true, timeline_notifications: true, - companion_stream_port_v1: true, - durable_agent_queue: true, - durable_voice_input_v1: true, plugin_timeline_items: true, plugin_binary_payloads: true, workspace_setup_blocked: true, @@ -9012,67 +9009,6 @@ test("sendMessage preserves explicit skill selection and null clears on the wire await omitted; }); -test("the queue selector follows the host capability across one client's reconnects", async () => { - const capable = createMockTransport(); - const incapable = createMockTransport(); - const capableAgain = createMockTransport(); - const transports = [capable, incapable, capableAgain]; - let transportIndex = 0; - const client = new DaemonClient({ - url: "ws://test", - clientId: "queue_selector_unit_test", - reconnect: { enabled: true, baseDelayMs: 1, maxDelayMs: 1 }, - transportFactory: () => { - const transport = transports[transportIndex]; - if (!transport) throw new Error("unexpected extra reconnect"); - transportIndex += 1; - return transport.transport; - }, - }); - clients.push(client); - - const subscriptionSelectors = (mock: ReturnType) => - mock.sent - .map((frame) => parseSentFrame(frame)) - .filter((message) => message.type === "session.events.set_subscription.request") - .map((message) => message.events as string[]); - - const initialConnect = client.connect(); - capable.triggerOpen({ features: { ownedSubscriptions: true, durableAgentQueueV1: true } }); - await initialConnect; - - client.observeEvents(["agent.queue.update", "status.server_info"]); - expect(subscriptionSelectors(capable).at(-1)).toEqual([ - "agent.queue.update", - "status.server_info", - ]); - - // Downgrade: the same client reconnects to a host that never saw the fork flag. - capable.triggerClose({ code: 1001, reason: "daemon restarted" }); - client.ensureConnected(); - incapable.triggerOpen({ features: { ownedSubscriptions: true } }); - await vi.waitFor(() => - expect(subscriptionSelectors(incapable).at(-1)).toEqual(["status.server_info"]), - ); - for (const selectors of subscriptionSelectors(incapable)) { - expect(selectors).not.toContain("agent.queue.update"); - } - - // Restore: the flag returns with the next handshake, so the selector comes back. - incapable.triggerClose({ code: 1001, reason: "daemon upgraded" }); - client.ensureConnected(); - capableAgain.triggerOpen({ features: { ownedSubscriptions: true, durableAgentQueueV1: true } }); - await vi.waitFor(() => - expect(subscriptionSelectors(capableAgain).at(-1)).toEqual([ - "agent.queue.update", - "status.server_info", - ]), - ); - - // The mock daemon never answers a release, so teardown closes the client instead. - await client.close(); -}); - test("measures an outbound message in UTF-8 bytes against the daemon's message limit", async () => { const mock = createMockTransport(); const client = new DaemonClient({ diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index d186a24ea86..0d488e371c2 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -26,7 +26,7 @@ import { type TimelineSubscription, } from "./connection/index.js"; import { CreationClient } from "./creation/index.js"; -import type { AgentQueueSnapshot, CreationSnapshot } from "@getpaseo/protocol/messages"; +import type { CreationSnapshot } from "@getpaseo/protocol/messages"; import type { JsonValue } from "@getpaseo/protocol/agent-types"; import type { z } from "zod"; import type { SessionEventSubscription } from "@getpaseo/protocol/messages"; @@ -52,9 +52,6 @@ import { DaemonUpdateResponseSchema, SessionInboundMessageSchema, type ActiveTurnBehavior, - type AgentAttachmentWire, - type QueuedAgentDeliveryIntent, - type QueuedComposerAttachment, type ServerInfoStatusPayload, } from "@getpaseo/protocol/messages"; import { validateWSOutboundMessage } from "@getpaseo/protocol/validation/ws-outbound"; @@ -1377,12 +1374,6 @@ export function supportsUsageReports(features: ServerInfoStatusPayload["features return features?.usageSources === true || features?.providerUsageList === true; } -/** Identifies the voice attachment a voice message belongs to. */ -export interface VoiceTransport { - attachmentId: string; - generation: string; -} - /** * Event selectors a host only understands behind a handshake feature. Anything absent from this * map is part of the base protocol and always sent. The client drops mapped selectors the @@ -1394,9 +1385,6 @@ const EVENT_SELECTOR_FEATURES: Partial< // COMPAT(sideConversationEvents): added in 0.12.0-beta.1.fork.1. "agent.side_conversation.update": "sideConversationEvents", "agent.side_conversation.removed": "sideConversationEvents", - // COMPAT(durableAgentQueueV1): added in 0.12.0-beta.1.fork.1. An old daemon rejects the whole - // subscription request when it parses an unknown selector, so this one is dropped before send. - "agent.queue.update": "durableAgentQueueV1", }; export class TerminalKeepUnsupportedError extends Error { @@ -3750,56 +3738,6 @@ export class DaemonClient { } } - async updateCompanionEntry(input: { - agentId: string; - entryId?: string; - action: "update_status" | "add_pin" | "remove_pin" | "add_q_and_a"; - status?: "open" | "reviewed" | "done"; - text?: string; - answerText?: string; - sourceId?: string; - }): Promise { - const payload = - await this.sendNamespacedCorrelatedSessionRequest<"agent.companion.update_entry.response">({ - message: { - type: "agent.companion.update_entry.request", - agentId: input.agentId, - entryId: input.entryId, - action: input.action, - status: input.status, - text: input.text, - answerText: input.answerText, - sourceId: input.sourceId, - }, - }); - if (!payload.accepted) { - throw new Error(payload.error ?? "updateCompanionEntry rejected"); - } - } - - /** - * Backfills an agent's artifact feed from files already on disk. Needed for - * agents whose work predates the artifact feed, whose feeds are otherwise - * permanently empty. - */ - async scanAgentArtifacts( - agentId: string, - options?: { limit?: number }, - ): Promise<{ addedOrUpdated: number; total: number }> { - const payload = - await this.sendNamespacedCorrelatedSessionRequest<"agent.artifacts.scan.response">({ - message: { - type: "agent.artifacts.scan.request", - agentId, - ...(options?.limit !== undefined ? { limit: options.limit } : {}), - }, - }); - if (!payload.accepted) { - throw new Error(payload.error ?? "scanAgentArtifacts rejected"); - } - return { addedOrUpdated: payload.addedOrUpdated, total: payload.total }; - } - async renameProject( projectId: string, customName: string | null, @@ -4517,159 +4455,6 @@ export class DaemonClient { return this.sendAgentMessage(agentId, text, options); } - // ========================================================================== - // Durable agent message queue — see docs/queue-mirroring.md. - // Gated on server_info.features.durableAgentQueueV1; callers must check the - // flag before reaching any of these. Mutations are revision-checked: a stale - // expectedRevision is rejected with the `queue_revision_conflict` code - // instead of overwriting another device's edit. - // ========================================================================== - - /** - * Admits a prompt into the durable queue with an explicit delivery intent. - * `itemId` comes from the caller so an optimistic local row and the stored - * item share an id, which makes a reconnect retry of the same enqueue a - * daemon-side no-op instead of a duplicate. - */ - async enqueueAgentMessage(input: { - agentId: string; - itemId: string; - text: string; - intent: QueuedAgentDeliveryIntent; - images?: Array<{ data: string; mimeType: string }>; - attachments?: AgentAttachmentWire[]; - composerAttachments?: QueuedComposerAttachment[]; - }): Promise { - return this.requireAgentQueuePayload( - await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.enqueue.response">({ - message: { - type: "agent.queue.enqueue.request", - agentId: input.agentId, - itemId: input.itemId, - text: input.text, - intent: input.intent, - ...(input.images?.length ? { images: input.images } : {}), - ...(input.attachments?.length ? { attachments: input.attachments } : {}), - ...(input.composerAttachments?.length - ? { composerAttachments: input.composerAttachments } - : {}), - }, - }), - ); - } - - async updateQueuedAgentMessage(input: { - agentId: string; - itemId: string; - text: string; - expectedRevision: number; - images?: Array<{ data: string; mimeType: string }>; - attachments?: AgentAttachmentWire[]; - composerAttachments?: QueuedComposerAttachment[]; - }): Promise { - return this.requireAgentQueuePayload( - await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.update.response">({ - message: { - type: "agent.queue.update.request", - agentId: input.agentId, - itemId: input.itemId, - text: input.text, - expectedRevision: input.expectedRevision, - ...(input.images?.length ? { images: input.images } : {}), - ...(input.attachments?.length ? { attachments: input.attachments } : {}), - ...(input.composerAttachments?.length - ? { composerAttachments: input.composerAttachments } - : {}), - }, - }), - ); - } - - async reorderQueuedAgentMessages( - agentId: string, - itemIds: string[], - expectedRevision: number, - ): Promise { - return this.requireAgentQueuePayload( - await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.reorder.response">({ - message: { type: "agent.queue.reorder.request", agentId, itemIds, expectedRevision }, - }), - ); - } - - async deleteQueuedAgentMessage( - agentId: string, - itemId: string, - expectedRevision: number, - ): Promise { - return this.requireAgentQueuePayload( - await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.delete.response">({ - message: { type: "agent.queue.delete.request", agentId, itemId, expectedRevision }, - }), - ); - } - - async retryQueuedAgentMessage( - agentId: string, - itemId: string, - expectedRevision: number, - ): Promise { - return this.requireAgentQueuePayload( - await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.retry.response">({ - message: { type: "agent.queue.retry.request", agentId, itemId, expectedRevision }, - }), - ); - } - - async sendQueuedAgentMessageNow( - agentId: string, - itemId: string, - expectedRevision: number, - ): Promise { - return this.requireAgentQueuePayload( - await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.send_now.response">({ - message: { type: "agent.queue.send_now.request", agentId, itemId, expectedRevision }, - }), - ); - } - - async listQueuedAgentMessages(agentId: string): Promise { - return this.requireAgentQueuePayload( - await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.list.response">({ - message: { type: "agent.queue.list.request", agentId }, - }), - ); - } - - /** - * Fetches the image bytes of one queued item. A device that did not queue the - * item has no local copy, so pulling it back into the composer would - * otherwise drop the images. - */ - async getQueuedAgentMessageImages( - agentId: string, - itemId: string, - ): Promise> { - const payload = - await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.get_item_images.response">({ - message: { type: "agent.queue.get_item_images.request", agentId, itemId }, - }); - if (payload.error) { - throw new Error(payload.error); - } - return payload.images; - } - - private requireAgentQueuePayload(payload: { - queue: AgentQueueSnapshot | null; - error: string | null; - }): AgentQueueSnapshot { - if (!payload.queue) { - throw new Error(payload.error ?? "Agent queue request rejected"); - } - return payload.queue; - } - async rewindAgent( agentId: string, messageId: string, @@ -5012,23 +4797,12 @@ export class DaemonClient { // Audio / Voice // ============================================================================ - async setVoiceMode( - enabled: boolean, - agentId?: string, - input?: { - /** Voice attachment identity; the host binds its transport generation to it. */ - attachmentId?: string; - /** Supplied when an existing attachment reclaims itself after a reconnect. */ - generation?: string; - }, - ): Promise { + async setVoiceMode(enabled: boolean, agentId?: string): Promise { const requestId = this.createRequestId(); const message = SessionInboundMessageSchema.parse({ type: "set_voice_mode", enabled, ...(agentId ? { agentId } : {}), - ...(input?.attachmentId ? { attachmentId: input.attachmentId } : {}), - ...(input?.generation ? { generation: input.generation } : {}), requestId, }); const response = await this.sendRequest({ @@ -5054,42 +4828,8 @@ export class DaemonClient { return response; } - /** Reads this attachment's delivery receipts so the panel can show truthful state. */ - async readVoiceInputReceipts(input: { - agentId: string; - attachmentId: string; - generation: string; - after?: string; - limit?: number; - }): Promise< - Extract["payload"] - > { - const requestId = this.createRequestId(); - const response = await this.sendRequest({ - requestId, - message: { type: "voice.input.receipts.read.request", requestId, ...input }, - select: (msg) => - msg.type === "voice.input.receipts.read.response" && msg.payload.requestId === requestId - ? msg.payload - : null, - }); - if (response.error) throw new Error(response.error); - return response; - } - - async sendVoiceAudioChunk( - audio: string, - format: string, - isLast = false, - transport?: VoiceTransport, - ): Promise { - return this.sendSessionMessageStrict({ - type: "voice_audio_chunk", - audio, - format, - isLast, - ...transport, - }); + async sendVoiceAudioChunk(audio: string, format: string, isLast = false): Promise { + this.sendSessionMessage({ type: "voice_audio_chunk", audio, format, isLast }); } async startDictationStream(dictationId: string, format: string): Promise { @@ -5311,17 +5051,12 @@ export class DaemonClient { this.sendSessionMessageStrict({ type: "dictation_stream_cancel", dictationId }); } - async abortRequest(transport?: VoiceTransport): Promise { - this.sendSessionMessage({ type: "abort_request", ...transport }); + async abortRequest(): Promise { + this.sendSessionMessage({ type: "abort_request" }); } - async audioPlayed(id: string, error?: string, transport?: VoiceTransport): Promise { - this.sendSessionMessageStrict({ - type: "audio_played", - id, - ...(error !== undefined ? { error } : {}), - ...transport, - }); + async audioPlayed(id: string): Promise { + this.sendSessionMessage({ type: "audio_played", id }); } // ============================================================================ diff --git a/packages/protocol/src/agent-types.ts b/packages/protocol/src/agent-types.ts index d9da3cb54a5..9e603a37e7c 100644 --- a/packages/protocol/src/agent-types.ts +++ b/packages/protocol/src/agent-types.ts @@ -10,18 +10,6 @@ import type { z } from "zod"; export type AgentProvider = string; -export type AgentArtifactKind = "html" | "markdown" | "image" | "svg" | "pdf" | "diff"; - -export interface AgentArtifact { - path: string; - name: string; - kind: AgentArtifactKind; - mimeType: string; - size: number; - createdAt: string; - updatedAt: string; -} - export interface AgentMetadata { [key: string]: unknown; } diff --git a/packages/protocol/src/client-capabilities.ts b/packages/protocol/src/client-capabilities.ts index 1900945b1f5..da582a8ec73 100644 --- a/packages/protocol/src/client-capabilities.ts +++ b/packages/protocol/src/client-capabilities.ts @@ -57,20 +57,7 @@ export const CLIENT_CAPS = { // Sources without it never receive agent-level background agents in inclusive lists or // update subscriptions, because older apps auto-open a tab for every replicated root agent. backgroundAgents: "background_agents", - // COMPAT(durableAgentQueue): fork addition (TM-02). The daemon only mirrors - // `agent.queue.update` to clients that advertise this, so a client with a - // strict outbound union never receives the event. - durableAgentQueue: "durable_agent_queue", - // COMPAT(durableVoiceInputV1): fork addition (TM-04). Gate for voice - // attachment admission into the durable queue and the receipt-read RPC. - // Keep the gate while stock peers are supported. - durableVoiceInputV1: "durable_voice_input_v1", browserHost: "browser_host", - // COMPAT(companionStreamPortV1): added in v0.11.0-beta.3-fork, remove after 2027-04-01. - // Clients declaring this get the optional `artifacts` / `companionEntries` - // agent-snapshot fields. Paired with the `agent.companion.update_entry.*` - // operations; not the source fork's `companionStream` capability name. - companionStreamPortV1: "companion_stream_port_v1", } as const; export type ClientCapability = (typeof CLIENT_CAPS)[keyof typeof CLIENT_CAPS]; diff --git a/packages/protocol/src/companion-stream.ts b/packages/protocol/src/companion-stream.ts deleted file mode 100644 index f8d74575515..00000000000 --- a/packages/protocol/src/companion-stream.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { z } from "zod"; - -const common = { - id: z.string(), - timestamp: z.string(), - text: z.string(), - truncated: z.boolean(), -}; - -export const CompanionEntrySchema = z.discriminatedUnion("kind", [ - z.object({ - ...common, - kind: z.literal("question"), - status: z.enum(["open", "reviewed", "done", "reply_sent"]), - }), - z.object({ - ...common, - kind: z.literal("feature_request"), - status: z.enum(["open", "reviewed", "done"]), - }), - z.object({ - ...common, - kind: z.literal("permission"), - requestId: z.string(), - requestKind: z.enum(["tool", "plan", "question", "mode", "other"]), - status: z.enum(["pending", "allowed", "denied", "expired"]), - }), - z.object({ - ...common, - kind: z.literal("outcome"), - status: z.enum(["completed", "failed", "canceled"]), - }), - z.object({ - ...common, - kind: z.literal("pin"), - sourceId: z.string().optional(), - }), - z.object({ - ...common, - kind: z.literal("q_and_a"), - answer: z.string().optional(), - questionMessageId: z.string().optional(), - answerMessageId: z.string().optional(), - }), -]); - -export type CompanionEntry = z.infer; - -export function isCompanionEntryPending(entry: CompanionEntry): boolean { - return ( - (entry.kind === "question" && entry.status === "open") || - (entry.kind === "feature_request" && entry.status === "open") || - (entry.kind === "permission" && entry.status === "pending") - ); -} diff --git a/packages/protocol/src/messages.agent-queue.test.ts b/packages/protocol/src/messages.agent-queue.test.ts deleted file mode 100644 index eef22f0de99..00000000000 --- a/packages/protocol/src/messages.agent-queue.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { z } from "zod"; - -import { CLIENT_CAPS } from "./client-capabilities"; -import { - AgentQueueEnqueueRequestSchema, - AgentQueueMutationRequestSchema, - AgentQueueUpdateMessageSchema, - SendAgentMessageRequestSchema, - ServerInfoStatusPayloadSchema, - SessionEventSubscriptionSchema, - SessionEventsSetSubscriptionRequestSchema, - SessionInboundMessageSchema, - SessionOutboundMessageSchema, -} from "./messages"; - -/** - * A released daemon's view of the send request. It knows nothing about queue - * intent, which is exactly the mixed-version case the legacy contract protects. - */ -const ReleasedSendRequestSchema = z.object({ - type: z.literal("send_agent_message_request"), - requestId: z.string(), - agentId: z.string(), - text: z.string(), - messageId: z.string().optional(), -}); - -describe("durable agent queue wire contract", () => { - it("requires an explicit delivery intent on admission", () => { - const admitted = AgentQueueEnqueueRequestSchema.parse({ - type: "agent.queue.enqueue.request", - requestId: "req-1", - agentId: "agent-1", - itemId: "item-1", - text: "follow-up", - intent: "steer_strict", - }); - expect(admitted.intent).toBe("steer_strict"); - - // Omitting the intent is a parse failure, not a silent "queue" default: - // admission is never inferred from a message the daemon did not classify. - expect(() => - AgentQueueEnqueueRequestSchema.parse({ - type: "agent.queue.enqueue.request", - requestId: "req-2", - agentId: "agent-1", - itemId: "item-2", - text: "follow-up", - }), - ).toThrow(); - }); - - it("registers every queue RPC on the session unions", () => { - for (const type of [ - "agent.queue.enqueue.request", - "agent.queue.update.request", - "agent.queue.reorder.request", - "agent.queue.delete.request", - "agent.queue.retry.request", - "agent.queue.send_now.request", - "agent.queue.list.request", - "agent.queue.get_item_images.request", - ]) { - expect( - SessionInboundMessageSchema.options.map((option) => option.shape.type.value), - ).toContain(type); - } - for (const type of [ - "agent.queue.enqueue.response", - "agent.queue.update.response", - "agent.queue.reorder.response", - "agent.queue.delete.response", - "agent.queue.retry.response", - "agent.queue.send_now.response", - "agent.queue.list.response", - "agent.queue.get_item_images.response", - "agent.queue.update", - ]) { - expect( - SessionOutboundMessageSchema.options.map((option) => option.shape.type.value), - ).toContain(type); - } - }); - - it("lets a queue-aware client subscribe to the queue broadcast", () => { - // A client cannot mirror the queue without subscribing to it, and the - // daemon only delivers the event to durableAgentQueue-capable clients. - expect(SessionEventSubscriptionSchema.options).toContain("agent.queue.update"); - expect(() => - SessionEventsSetSubscriptionRequestSchema.parse({ - type: "session.events.set_subscription.request", - requestId: "req-1", - events: ["agent.queue.update"], - }), - ).not.toThrow(); - }); - - it("never sends image bytes in a queue snapshot", () => { - const broadcast = AgentQueueUpdateMessageSchema.parse({ - type: "agent.queue.update", - payload: { - agentId: "agent-1", - revision: 3, - items: [ - { - id: "item-1", - text: "look at this", - intent: "queue", - deliveryState: "uncertain", - attempts: 1, - lastError: "agent_request_outcome_unknown", - images: [{ id: "image-1", mimeType: "image/png", byteSize: 3 }], - createdAt: "2026-01-01T00:00:00.000Z", - }, - ], - }, - }); - expect(broadcast.payload.items[0]?.deliveryState).toBe("uncertain"); - expect(JSON.stringify(broadcast)).not.toContain("data:"); - }); - - it("carries the expected revision on queue mutations", () => { - const base = { - type: "agent.queue.delete.request", - requestId: "req-1", - agentId: "agent-1", - expectedRevision: 7, - }; - expect(() => AgentQueueMutationRequestSchema.parse(base)).not.toThrow(); - expect(() => - AgentQueueMutationRequestSchema.parse({ ...base, expectedRevision: -1 }), - ).toThrow(); - }); -}); - -describe("mixed-version send compatibility", () => { - it("keeps a legacy send request on the legacy shape with no queue intent", () => { - const legacyRequest = ReleasedSendRequestSchema.parse({ - type: "send_agent_message_request", - requestId: "req-old-client", - agentId: "agent-1", - text: "keep working", - }); - expect(legacyRequest).toEqual({ - type: "send_agent_message_request", - requestId: "req-old-client", - agentId: "agent-1", - text: "keep working", - }); - }); - - it("never lets queue intent ride along on the legacy send request", () => { - const parsed = SendAgentMessageRequestSchema.parse({ - type: "send_agent_message_request", - requestId: "req-new-client", - agentId: "agent-1", - text: "replace the turn", - activeTurnBehavior: "steer", - }); - const legacyView = ReleasedSendRequestSchema.parse(parsed); - expect("activeTurnBehavior" in legacyView).toBe(false); - expect(Object.keys(legacyView)).not.toContain("intent"); - }); - - it("gates the queue on an optional feature flag an old daemon never sets", () => { - const oldDaemon = ServerInfoStatusPayloadSchema.parse({ - status: "server_info", - protocolVersion: 1, - serverId: "server-1", - }); - expect(oldDaemon.features?.durableAgentQueueV1).toBeUndefined(); - - const newDaemon = ServerInfoStatusPayloadSchema.parse({ - status: "server_info", - protocolVersion: 1, - serverId: "server-1", - features: { durableAgentQueueV1: true }, - }); - expect(newDaemon.features?.durableAgentQueueV1).toBe(true); - // A daemon without the flag must never receive the new enum, so a client - // that sees it absent must not send any agent.queue.* message at all. - expect(oldDaemon.features?.durableAgentQueueV1 === true).toBe(false); - }); - - it("gates the queue broadcast on a client capability old clients do not send", () => { - expect(CLIENT_CAPS.durableAgentQueue).toBe("durable_agent_queue"); - }); -}); diff --git a/packages/protocol/src/messages.artifacts.test.ts b/packages/protocol/src/messages.artifacts.test.ts deleted file mode 100644 index 4e055a88b01..00000000000 --- a/packages/protocol/src/messages.artifacts.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { AgentSnapshotPayloadSchema } from "./messages.js"; - -describe("agent artifact snapshots", () => { - it("accepts additive per-agent artifacts", () => { - const snapshot = AgentSnapshotPayloadSchema.parse({ - id: "agent-1", - provider: "codex", - cwd: "/tmp/project", - model: null, - createdAt: "2026-07-22T00:00:00.000Z", - updatedAt: "2026-07-22T00:01:00.000Z", - lastUserMessageAt: null, - status: "idle", - capabilities: { - supportsStreaming: true, - supportsSessionPersistence: true, - supportsDynamicModes: true, - supportsMcpServers: true, - supportsReasoningStream: true, - supportsToolInvocations: true, - }, - currentModeId: null, - availableModes: [], - pendingPermissions: [], - persistence: null, - title: "Artifacts", - labels: {}, - artifacts: [ - { - path: "report.html", - name: "report.html", - kind: "html", - mimeType: "text/html", - size: 42, - createdAt: "2026-07-22T00:00:30.000Z", - updatedAt: "2026-07-22T00:00:30.000Z", - }, - ], - }); - - expect(snapshot.artifacts?.[0]?.path).toBe("report.html"); - expect(snapshot.companionEntries).toBeUndefined(); - const upgraded = { - ...snapshot, - companionEntries: [ - { - id: "turn:one", - kind: "outcome", - status: "completed", - text: "Report is ready", - timestamp: "2026-09-21T12:00:00.000Z", - truncated: false, - }, - ], - }; - expect(AgentSnapshotPayloadSchema.parse(upgraded).companionEntries).toEqual( - upgraded.companionEntries, - ); - // The previous wire shape ignores the additive field and still parses the snapshot. - expect(AgentSnapshotPayloadSchema.omit({ companionEntries: true }).parse(upgraded)).toEqual( - snapshot, - ); - }); -}); diff --git a/packages/protocol/src/messages.companion-update-entry.test.ts b/packages/protocol/src/messages.companion-update-entry.test.ts deleted file mode 100644 index 216ddb1b8c5..00000000000 --- a/packages/protocol/src/messages.companion-update-entry.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { - AgentCompanionUpdateEntryRequestMessageSchema, - AgentCompanionUpdateEntryResponseMessageSchema, - ServerInfoStatusPayloadSchema, - SessionInboundMessageSchema, - SessionOutboundMessageSchema, -} from "./messages.js"; - -const baseRequest = { - type: "agent.companion.update_entry.request" as const, - agentId: "agent-1", - action: "add_pin" as const, - text: "note", - requestId: "req-1", -}; - -describe("agent.companion.update_entry wire contract", () => { - it("parses the renamed request through the session inbound union", () => { - const parsed = SessionInboundMessageSchema.parse(baseRequest); - expect(parsed.type).toBe("agent.companion.update_entry.request"); - }); - - it("parses status, remove_pin, and add_q_and_a variants", () => { - expect( - AgentCompanionUpdateEntryRequestMessageSchema.parse({ - type: "agent.companion.update_entry.request", - agentId: "agent-1", - entryId: "question:1", - action: "update_status", - status: "reviewed", - requestId: "req-2", - }).action, - ).toBe("update_status"); - expect( - AgentCompanionUpdateEntryRequestMessageSchema.parse({ - type: "agent.companion.update_entry.request", - agentId: "agent-1", - entryId: "pin:1", - action: "remove_pin", - requestId: "req-3", - }).entryId, - ).toBe("pin:1"); - expect( - AgentCompanionUpdateEntryRequestMessageSchema.parse({ - type: "agent.companion.update_entry.request", - agentId: "agent-1", - action: "add_q_and_a", - text: "q", - answerText: "a", - requestId: "req-4", - }).answerText, - ).toBe("a"); - }); - - it("rejects the source fork's flat update_companion_entry_request", () => { - // The source fork's operation name must stay distinct: a source-built client - // that sees the fork's `companionStream` capability would send this shape. - const result = SessionInboundMessageSchema.safeParse({ - type: "update_companion_entry_request", - agentId: "agent-1", - action: "add_pin", - text: "note", - requestId: "req-5", - }); - expect(result.success).toBe(false); - }); - - it("parses the correlated success and failure responses", () => { - const success = AgentCompanionUpdateEntryResponseMessageSchema.parse({ - type: "agent.companion.update_entry.response", - payload: { requestId: "req-1", agentId: "agent-1", accepted: true, error: null }, - }); - expect(success.payload.accepted).toBe(true); - const failure = SessionOutboundMessageSchema.parse({ - type: "agent.companion.update_entry.response", - payload: { requestId: "req-1", agentId: "agent-1", accepted: false, error: "not found" }, - }); - expect(failure.type).toBe("agent.companion.update_entry.response"); - }); - - it("advertises companionStreamPortV1 and not the source fork's feature names", () => { - const info = ServerInfoStatusPayloadSchema.parse({ - status: "server_info", - serverId: "server-1", - version: "0.11.0-beta.3-fork", - features: { companionStreamPortV1: true }, - }); - expect(info.features?.companionStreamPortV1).toBe(true); - expect( - ServerInfoStatusPayloadSchema.safeParse({ features: { companionStream: true } }).success, - ).toBe(false); - expect( - ServerInfoStatusPayloadSchema.safeParse({ features: { artifactFeed: true } }).success, - ).toBe(false); - }); -}); diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 8fc48613767..7b1018e4818 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -39,7 +39,6 @@ export { import { TerminalProfileSchema } from "./terminal-profile.js"; export { TerminalProfileSchema, type TerminalProfile } from "./terminal-profile.js"; import { z } from "zod"; -import { CompanionEntrySchema } from "./companion-stream.js"; import { TerminalActivitySchema } from "./terminal-activity.js"; import { CLIENT_CAPS } from "./client-capabilities.js"; import { AGENT_LIFECYCLE_STATUSES } from "./agent-lifecycle.js"; @@ -911,18 +910,6 @@ const AgentActiveTurnPayloadSchema = z.object({ startedAt: z.string().nullable(), }); -export const AgentArtifactSchema = z.object({ - path: z.string(), - name: z.string(), - kind: z.enum(["html", "markdown", "image", "svg", "pdf", "diff"]), - mimeType: z.string(), - size: z.number().int().nonnegative(), - createdAt: z.string(), - updatedAt: z.string(), -}); - -export type AgentArtifactPayload = z.infer; - export const AgentSnapshotPayloadSchema = z.object({ id: z.string(), provider: AgentProviderSchema, @@ -965,8 +952,6 @@ export const AgentSnapshotPayloadSchema = z.object({ // Background agent: hidden from default discovery, tabs, tracks and notifications. // Fixed at creation. Effective background also includes the workspace's flag. background: z.boolean().optional(), - artifacts: z.array(AgentArtifactSchema).optional(), - companionEntries: z.array(CompanionEntrySchema).optional(), }); export type AgentSnapshotPayload = z.infer; @@ -1018,10 +1003,6 @@ export type RecentProviderSessionDescriptorPayload = z.infer< export const VoiceAudioChunkMessageSchema = z.object({ type: z.literal("voice_audio_chunk"), - /** Voice attachment identity. Absent in legacy clients without attachments. */ - attachmentId: z.string().optional(), - /** Transport generation handed out by the host for this attachment. */ - generation: z.string().optional(), audio: z.string(), // base64 encoded format: z.string(), isLast: z.boolean(), @@ -1029,45 +1010,11 @@ export const VoiceAudioChunkMessageSchema = z.object({ export const AbortRequestMessageSchema = z.object({ type: z.literal("abort_request"), - attachmentId: z.string().optional(), - generation: z.string().optional(), }); export const AudioPlayedMessageSchema = z.object({ type: z.literal("audio_played"), - attachmentId: z.string().optional(), - generation: z.string().optional(), id: z.string(), - /** Set when the client failed to play the clip; the speech caller sees the failure. */ - error: z.string().optional(), -}); - -export const VoiceInputReceiptsReadRequestSchema = z.object({ - type: z.literal("voice.input.receipts.read.request"), - requestId: z.string(), - agentId: z.string(), - attachmentId: z.string(), - generation: z.string(), - after: z.string().optional(), - limit: z.number().int().min(1).max(100).optional(), -}); - -export const VoiceInputReceiptsReadResponseSchema = z.object({ - type: z.literal("voice.input.receipts.read.response"), - payload: z.object({ - requestId: z.string(), - agentId: z.string(), - attachmentId: z.string(), - items: z.array( - z.object({ - messageId: z.string(), - state: z.enum(["queued", "submitted", "removed", "unknown"]), - createdAt: z.string(), - }), - ), - nextCursor: z.string().nullable(), - error: z.string().nullable(), - }), }); const AgentDirectoryFilterSchema = z.object({ @@ -1109,53 +1056,6 @@ export const UpdateAgentRequestMessageSchema = z.object({ requestId: z.string(), }); -// COMPAT(companionStreamPortV1): added in v0.11.0-beta.3-fork, remove after 2027-04-01. -// Ported from the source fork's flat `update_companion_entry_request`; renamed to the -// dotted namespace so the two contracts stay distinct on the wire. -export const AgentCompanionUpdateEntryRequestMessageSchema = z.object({ - type: z.literal("agent.companion.update_entry.request"), - agentId: z.string(), - entryId: z.string().optional(), - action: z.enum(["update_status", "add_pin", "remove_pin", "add_q_and_a"]), - status: z.enum(["open", "reviewed", "done"]).optional(), - text: z.string().optional(), - answerText: z.string().optional(), - sourceId: z.string().optional(), - requestId: z.string(), -}); - -export const AgentCompanionUpdateEntryResponseMessageSchema = z.object({ - type: z.literal("agent.companion.update_entry.response"), - payload: z.object({ - requestId: z.string(), - agentId: z.string(), - accepted: z.boolean(), - error: z.string().nullable(), - }), -}); - -export const AgentArtifactsScanRequestMessageSchema = z.object({ - type: z.literal("agent.artifacts.scan.request"), - agentId: z.string(), - requestId: z.string(), - /** Overrides the daemon's default retention ceiling for this scan. */ - limit: z.number().int().positive().optional(), -}); - -export const AgentArtifactsScanResponseMessageSchema = z.object({ - type: z.literal("agent.artifacts.scan.response"), - payload: z.object({ - requestId: z.string(), - agentId: z.string(), - accepted: z.boolean(), - error: z.string().nullable(), - /** Files newly recorded or refreshed by this scan. */ - addedOrUpdated: z.number().int().nonnegative(), - /** Size of the agent's artifact list after the scan. */ - total: z.number().int().nonnegative(), - }), -}); - // The daemon accepts only image bytes chosen or acquired by the client. It must // never fetch a user-provided URL on the host's network. export const ProjectIconSourceSchema = z.discriminatedUnion("type", [ @@ -1290,10 +1190,6 @@ export const WorkspaceArchiveUndoRequestSchema = z.object({ export const SetVoiceModeMessageSchema = z.object({ type: z.literal("set_voice_mode"), - /** Voice attachment identity; the host binds its generation to it. */ - attachmentId: z.string().optional(), - /** Supplied when an existing attachment reclaims itself after a reconnect. */ - generation: z.string().optional(), enabled: z.boolean(), agentId: z.string().optional(), requestId: z.string().optional(), @@ -1359,21 +1255,19 @@ export const ExternalResourceAttachmentMetadataSchema = z.object({ url: z.string(), }); -export const TextAttachmentWireSchema = z.object({ - type: z.literal("text"), - mimeType: z.literal("text/plain"), - contextKind: z.string().optional(), - title: z.string().nullable().optional(), - text: z.string(), - externalResource: ExternalResourceAttachmentMetadataSchema.optional(), -}); - -export const TextAttachmentSchema = TextAttachmentWireSchema.transform( - ({ contextKind, ...attachment }) => ({ +export const TextAttachmentSchema = z + .object({ + type: z.literal("text"), + mimeType: z.literal("text/plain"), + contextKind: z.string().optional(), + title: z.string().nullable().optional(), + text: z.string(), + externalResource: ExternalResourceAttachmentMetadataSchema.optional(), + }) + .transform(({ contextKind, ...attachment }) => ({ ...attachment, ...(contextKind === "chat_history" ? { contextKind } : {}), - }), -); + })); export const ReviewAttachmentContextLineSchema = z.object({ oldLineNumber: z.number().int().positive().nullable(), @@ -1422,21 +1316,6 @@ export const AgentAttachmentSchema = z.discriminatedUnion("type", [ UploadedFileAttachmentSchema, ]); -/** - * Same shape as AgentAttachmentSchema without the text-attachment transform, so - * attachments can appear in outbound messages. Message schemas stay pure — see - * docs/protocol-validation.md. - */ -export const AgentAttachmentWireSchema = z.discriminatedUnion("type", [ - ForgeChangeRequestAttachmentSchema, - ForgeIssueAttachmentSchema, - GitHubPrAttachmentSchema, - GitHubIssueAttachmentSchema, - TextAttachmentWireSchema, - ReviewAttachmentSchema, - UploadedFileAttachmentSchema, -]); - function normalizeAgentAttachments(input: unknown): AgentAttachment[] { if (!Array.isArray(input)) { return []; @@ -2555,9 +2434,6 @@ export const SetVoiceModeResponseMessageSchema = z.object({ reasonCode: z.string().optional(), retryable: z.boolean().optional(), missingModelIds: z.array(z.string()).optional(), - /** Echoed attachment identity plus the host's fresh transport generation. */ - attachmentId: z.string().optional(), - generation: z.string().optional(), }), }); @@ -2933,250 +2809,6 @@ export const ForgeSearchKindSchema = z.enum([ export const GitHubSearchKindSchema = ForgeSearchKindSchema; -// --------------------------------------------------------------------------- -// Durable agent message queue. Removal group: Queue (TM-02). -// -// Admission through these RPCs is opt-in. `send_agent_message_request` without -// queue intent keeps the legacy receipt-backed interrupt path and never reaches -// the queue, so every message in this block is new to an old daemon: gate a -// client on `server_info.features.durableAgentQueueV1` before sending any of it, -// and never send the new `intent` values to a daemon that lacks the flag. The -// daemon only broadcasts `agent.queue.update` to clients advertising -// CLIENT_CAPS.durableAgentQueue, so an old client never sees an unknown event. -// --------------------------------------------------------------------------- - -/** - * How the daemon delivers a queued item. `queue` waits for a free agent; - * `steer_strict` asks the provider to steer the running turn and never - * interrupts or replaces it. Both values postdate every released daemon, which - * is why the feature flag gates the whole block. - */ -export const QueuedAgentDeliveryIntentSchema = z.enum(["queue", "steer_strict"]); -export type QueuedAgentDeliveryIntent = z.infer; - -/** - * Where a queued item stands in the claim/dispatch/receipt/removal cycle. - * - * - `pending`: accepted and never handed to a provider; safe to resume. - * - `dispatching`: claimed, dispatch in flight. - * - `uncertain`: the provider may or may not have accepted it. Visible for - * reconciliation; the daemon never resends it on its own. - * - `failed`: repeated known failures (see the daemon's attempt limit). Visible - * with an explicit retry or discard. - */ -export const QueuedAgentMessageDeliveryStateSchema = z.enum([ - "pending", - "dispatching", - "uncertain", - "failed", -]); -export type QueuedAgentMessageDeliveryState = z.infer; - -/** - * Queued images are described, never shipped. The bytes live on the daemon, so a - * queue holding a photo does not push megabytes of base64 at every connected - * client on every queue change. - */ -export const QueuedAgentMessageImageSchema = z.object({ - id: z.string(), - mimeType: z.string(), - fileName: z.string().nullable().optional(), - byteSize: z.number().int().nonnegative().optional(), -}); - -/** - * The composer-side view of an attachment, kept alongside the agent-side one so - * any device can pull a queued message back into its composer with the same - * pills the author saw. Images are excluded: their bytes are stored separately - * and fetched with agent.queue.get_item_images.request. - */ -export const QueuedComposerAttachmentSchema = z.discriminatedUnion("kind", [ - z.object({ kind: z.literal("file"), attachment: UploadedFileAttachmentSchema }), - z.object({ - kind: z.literal("workspace_file"), - path: z.string(), - selection: z.discriminatedUnion("kind", [ - z.object({ kind: z.literal("whole_file") }), - z.object({ - kind: z.literal("line_range"), - startLine: z.number().int().positive(), - endLine: z.number().int().positive(), - }), - ]), - }), - z.object({ kind: z.literal("forge_issue"), item: ForgeSearchItemSchema }), - z.object({ kind: z.literal("forge_change_request"), item: ForgeSearchItemSchema }), - z.object({ kind: z.literal("github_issue"), item: ForgeSearchItemSchema }), - z.object({ kind: z.literal("github_pr"), item: ForgeSearchItemSchema }), -]); - -export const QueuedAgentMessageSchema = z.object({ - id: z.string(), - text: z.string(), - /** Set when the item was admitted as spoken input rather than typed or tool-created. */ - origin: z.literal("voice").optional(), - intent: QueuedAgentDeliveryIntentSchema, - deliveryState: QueuedAgentMessageDeliveryStateSchema, - attempts: z.number().int().nonnegative(), - lastError: z.string().nullable().optional(), - attachments: z.array(AgentAttachmentWireSchema).optional(), - composerAttachments: z.array(QueuedComposerAttachmentSchema).optional(), - images: z.array(QueuedAgentMessageImageSchema).optional(), - createdAt: z.string(), -}); - -export const AgentQueueSnapshotSchema = z.object({ - agentId: z.string(), - /** Increments on every mutation so clients can drop a stale broadcast. */ - revision: z.number().int().nonnegative(), - items: z.array(QueuedAgentMessageSchema), -}); - -export const AgentQueueEnqueueRequestSchema = z.object({ - type: z.literal("agent.queue.enqueue.request"), - requestId: z.string(), - agentId: z.string(), - /** Client-generated so the optimistic local item and the stored item share an id. */ - itemId: z.string(), - text: z.string(), - intent: QueuedAgentDeliveryIntentSchema, - images: z.array(ImageAttachmentSchema).optional(), - attachments: z.array(AgentAttachmentWireSchema).optional(), - composerAttachments: z.array(QueuedComposerAttachmentSchema).optional(), -}); - -/** - * The revision the client last saw. A stale device is rejected with - * `queue_revision_conflict` instead of overwriting another device's edit, so - * edits, reorders and deletions are governed by queue revisions. - */ -export const AgentQueueMutationRequestSchema = z.object({ - type: z.string(), - requestId: z.string(), - agentId: z.string(), - expectedRevision: z.number().int().nonnegative(), -}); - -export const AgentQueueUpdateRequestSchema = AgentQueueMutationRequestSchema.extend({ - type: z.literal("agent.queue.update.request"), - itemId: z.string(), - text: z.string(), - images: z.array(ImageAttachmentSchema).optional(), - attachments: z.array(AgentAttachmentWireSchema).optional(), - composerAttachments: z.array(QueuedComposerAttachmentSchema).optional(), -}); - -export const AgentQueueReorderRequestSchema = AgentQueueMutationRequestSchema.extend({ - type: z.literal("agent.queue.reorder.request"), - /** Full id list in the desired order. Unknown ids are ignored, omitted ids keep their relative order at the end. */ - itemIds: z.array(z.string()), -}); - -export const AgentQueueDeleteRequestSchema = AgentQueueMutationRequestSchema.extend({ - type: z.literal("agent.queue.delete.request"), - itemId: z.string(), -}); - -/** Returns a failed or uncertain item to the drain loop after an explicit user decision. */ -export const AgentQueueRetryRequestSchema = AgentQueueMutationRequestSchema.extend({ - type: z.literal("agent.queue.retry.request"), - itemId: z.string(), -}); - -/** - * Attempts delivery of one item now instead of waiting for the queue to reach - * the head. The response carries the queue after the attempt, so a client can - * tell a delivered item from one the admission fence refused. - */ -export const AgentQueueSendNowRequestSchema = AgentQueueMutationRequestSchema.extend({ - type: z.literal("agent.queue.send_now.request"), - itemId: z.string(), -}); - -export const AgentQueueListRequestSchema = z.object({ - type: z.literal("agent.queue.list.request"), - requestId: z.string(), - agentId: z.string(), -}); - -/** - * Fetches the image bytes of one queued item. A device that did not queue the - * item has no local copy, so editing it there would otherwise drop the images. - */ -export const AgentQueueGetItemImagesRequestSchema = z.object({ - type: z.literal("agent.queue.get_item_images.request"), - requestId: z.string(), - agentId: z.string(), - itemId: z.string(), -}); - -export const AgentQueueGetItemImagesResponseSchema = z.object({ - type: z.literal("agent.queue.get_item_images.response"), - payload: z.object({ - requestId: z.string(), - agentId: z.string(), - itemId: z.string(), - images: z.array( - z.object({ - id: z.string(), - mimeType: z.string(), - fileName: z.string().nullable().optional(), - data: z.string(), - }), - ), - error: z.string().nullable(), - }), -}); - -export const AgentQueueResponsePayloadSchema = z.object({ - requestId: z.string(), - agentId: z.string(), - queue: AgentQueueSnapshotSchema.nullable(), - /** Machine-readable on mutation failures, e.g. `queue_revision_conflict`. */ - error: z.string().nullable(), -}); - -export const AgentQueueEnqueueResponseSchema = z.object({ - type: z.literal("agent.queue.enqueue.response"), - payload: AgentQueueResponsePayloadSchema, -}); - -export const AgentQueueUpdateResponseSchema = z.object({ - type: z.literal("agent.queue.update.response"), - payload: AgentQueueResponsePayloadSchema, -}); - -export const AgentQueueReorderResponseSchema = z.object({ - type: z.literal("agent.queue.reorder.response"), - payload: AgentQueueResponsePayloadSchema, -}); - -export const AgentQueueDeleteResponseSchema = z.object({ - type: z.literal("agent.queue.delete.response"), - payload: AgentQueueResponsePayloadSchema, -}); - -export const AgentQueueRetryResponseSchema = z.object({ - type: z.literal("agent.queue.retry.response"), - payload: AgentQueueResponsePayloadSchema, -}); - -export const AgentQueueSendNowResponseSchema = z.object({ - type: z.literal("agent.queue.send_now.response"), - payload: AgentQueueResponsePayloadSchema, -}); - -export const AgentQueueListResponseSchema = z.object({ - type: z.literal("agent.queue.list.response"), - payload: AgentQueueResponsePayloadSchema, -}); - -/** Unsolicited full-queue broadcast, only to clients advertising CLIENT_CAPS.durableAgentQueue. */ -export const AgentQueueUpdateMessageSchema = z.object({ - type: z.literal("agent.queue.update"), - payload: AgentQueueSnapshotSchema, -}); - export const ForgeSearchRequestSchema = z.object({ type: z.literal("forge.search.request"), cwd: z.string(), @@ -3891,10 +3523,6 @@ export const SessionEventSubscriptionSchema = z.enum([ "agent.background_work.update", "agent.side_conversation.update", "agent.side_conversation.removed", - // COMPAT(durableAgentQueue): fork addition (TM-02). Only sent by clients that - // saw features.durableAgentQueueV1; an old daemon parsing this enum rejects - // the subscription request, which is why the client gates before subscribing. - "agent.queue.update", "terminal_attention_required", "status.server_info", "status.daemon_config_changed", @@ -3969,8 +3597,6 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ ArchiveAgentRequestMessageSchema, CloseItemsRequestMessageSchema, UpdateAgentRequestMessageSchema, - AgentCompanionUpdateEntryRequestMessageSchema, - AgentArtifactsScanRequestMessageSchema, ProjectRenameRequestSchema, ProjectIconSetRequestSchema, ProjectRemoveRequestSchema, @@ -3988,7 +3614,6 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ WorkspaceRecoveryRestoreRequestSchema, WorkspaceArchiveUndoRequestSchema, SetVoiceModeMessageSchema, - VoiceInputReceiptsReadRequestSchema, SendAgentMessageRequestSchema, WaitForFinishRequestSchema, DaemonGetStatusRequestSchema, @@ -4057,14 +3682,6 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ SideConversationAskRequestMessageSchema, SideConversationTimelineGetRequestMessageSchema, SideConversationListRequestMessageSchema, - AgentQueueEnqueueRequestSchema, - AgentQueueUpdateRequestSchema, - AgentQueueReorderRequestSchema, - AgentQueueDeleteRequestSchema, - AgentQueueRetryRequestSchema, - AgentQueueSendNowRequestSchema, - AgentQueueListRequestSchema, - AgentQueueGetItemImagesRequestSchema, SetAgentTimelineSubscriptionRequestMessageSchema, AgentForkContextRequestMessageSchema, SetAgentModeRequestMessageSchema, @@ -4220,8 +3837,6 @@ export const AudioOutputMessageSchema = z.object({ audio: z.string(), // base64 encoded format: z.string(), id: z.string(), - attachmentId: z.string().optional(), - generation: z.string().optional(), isVoiceMode: z.boolean(), // Mode when audio was generated (for drift protection) groupId: z.string().optional(), // Logical utterance id chunkIndex: z.number().int().nonnegative().optional(), @@ -4236,11 +3851,6 @@ export const TranscriptionResultMessageSchema = z.object({ language: z.string().optional(), duration: z.number().optional(), requestId: z.string(), // Echoed back from request for tracking - attachmentId: z.string().optional(), - generation: z.string().optional(), - /** Queue item id of the admitted utterance; present only when it was queued. */ - messageId: z.string().optional(), - queued: z.boolean().optional(), avgLogprob: z.number().optional(), isLowConfidence: z.boolean().optional(), byteLength: z.number().optional(), @@ -4253,13 +3863,6 @@ export const VoiceInputStateMessageSchema = z.object({ type: z.literal("voice_input_state"), payload: z.object({ isSpeaking: z.boolean(), - /** Input problem text, e.g. a transcript that could not be queued. */ - error: z.string().optional(), - attachmentId: z.string().optional(), - generation: z.string().optional(), - // "nothing_recognized" | "timed_out" | "failed". A string so later hosts can add - // values that older clients ignore instead of rejecting the message. - recognitionIssue: z.string().optional(), }), }); @@ -4481,15 +4084,6 @@ export const ServerInfoStatusPayloadSchema = z agentTimelinePromptIndex: z.boolean().optional(), // COMPAT(agentHistorySearch): added in v0.3.0, remove gate after 2027-02-07. agentHistorySearch: z.boolean().optional(), - // COMPAT(durableAgentQueue): fork addition (TM-02). Gates the whole - // agent.queue.* block, including the delivery-intent enum that no - // released daemon understands. Remove the gate after 2027-10-01 once - // the supported daemon floor is past every 0.11.x host. - durableAgentQueueV1: z.boolean().optional(), - // COMPAT(durableVoiceInputV1): fork addition (TM-04). Gates voice - // attachment admission into the durable agent queue; an old daemon - // never answers voice.input.receipts.read requests. - durableVoiceInputV1: z.boolean().optional(), // COMPAT(checkoutRefresh): added in v0.1.86, remove gate after 2026-11-29. checkoutRefresh: z.boolean().optional(), // COMPAT(workspaceMultiplicity): added in v0.1.97, drop the gate when floor >= v0.1.97 @@ -4508,11 +4102,6 @@ export const ServerInfoStatusPayloadSchema = z workspaceFileEditing: z.boolean().optional(), // COMPAT(fileByteWrites): added in v0.13.0, remove gate after 2027-04-20. fileByteWrites: z.boolean().optional(), - // COMPAT(companionStreamPortV1): added in v0.11.0-beta.3-fork, remove after 2027-04-01. - // Deliberately not the source fork's `companionStream`/`artifactFeed` flags: a client - // that saw those names would expect the source's flat companion RPC, which this - // daemon does not accept. - companionStreamPortV1: z.boolean().optional(), // COMPAT(providerUsageList): added in v0.1.98, drop the gate when daemon floor >= v0.1.98. providerUsageList: z.boolean().optional(), // COMPAT(agentDetach): added in v0.1.98, remove gate after 2026-12-19 once daemon floor >= v0.1.98. @@ -7982,9 +7571,6 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ HostsRouteOpenResponseSchema, HostsRouteFrameSchema, HostsRouteClosedSchema, - - AgentCompanionUpdateEntryResponseMessageSchema, - AgentArtifactsScanResponseMessageSchema, BrowserHostRegisterResponseSchema, SubscriptionReleaseResponseSchema, SessionEventsSetSubscriptionResponseSchema, @@ -8083,15 +7669,6 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ SideConversationUpdateMessageSchema, SideConversationListResponseMessageSchema, SideConversationRemovedMessageSchema, - AgentQueueEnqueueResponseSchema, - AgentQueueUpdateResponseSchema, - AgentQueueReorderResponseSchema, - AgentQueueDeleteResponseSchema, - AgentQueueRetryResponseSchema, - AgentQueueSendNowResponseSchema, - AgentQueueListResponseSchema, - AgentQueueGetItemImagesResponseSchema, - AgentQueueUpdateMessageSchema, SetAgentTimelineSubscriptionResponseMessageSchema, AgentAttentionRequiredMessageSchema, AgentForkContextResponseMessageSchema, @@ -8106,7 +7683,6 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ WorkspaceMarkUnreadResponseSchema, SendAgentMessageResponseMessageSchema, SetVoiceModeResponseMessageSchema, - VoiceInputReceiptsReadResponseSchema, DaemonGetStatusResponseSchema, DaemonGetPairingOfferResponseSchema, DaemonConfigReloadResponseSchema, @@ -8451,20 +8027,6 @@ export type DictationStreamFinishMessage = z.infer; export type CreateAgentRequestMessage = z.infer; export type AgentAttachment = z.infer; -export type AgentAttachmentWire = z.infer; -export type QueuedAgentMessage = z.infer; -export type QueuedAgentMessageImage = z.infer; -export type QueuedComposerAttachment = z.infer; -export type AgentQueueSnapshot = z.infer; -export type AgentQueueEnqueueRequest = z.infer; -export type AgentQueueUpdateRequest = z.infer; -export type AgentQueueReorderRequest = z.infer; -export type AgentQueueDeleteRequest = z.infer; -export type AgentQueueRetryRequest = z.infer; -export type AgentQueueSendNowRequest = z.infer; -export type AgentQueueListRequest = z.infer; -export type AgentQueueGetItemImagesRequest = z.infer; -export type AgentQueueUpdateMessage = z.infer; export type ForgeChangeRequestAttachment = z.infer; export type ForgeIssueAttachment = z.infer; export type UploadedFileAttachment = z.infer; @@ -8519,18 +8081,6 @@ export type LoopStopRequest = z.infer; export type ResumeAgentRequestMessage = z.infer; export type DeleteAgentRequestMessage = z.infer; export type UpdateAgentRequestMessage = z.infer; -export type AgentCompanionUpdateEntryRequestMessage = z.infer< - typeof AgentCompanionUpdateEntryRequestMessageSchema ->; -export type AgentCompanionUpdateEntryResponseMessage = z.infer< - typeof AgentCompanionUpdateEntryResponseMessageSchema ->; -export type AgentArtifactsScanRequestMessage = z.infer< - typeof AgentArtifactsScanRequestMessageSchema ->; -export type AgentArtifactsScanResponseMessage = z.infer< - typeof AgentArtifactsScanResponseMessageSchema ->; export type ProjectIconSource = z.infer; export type ProjectRenameRequest = z.infer; export type ProjectIconSetRequest = z.infer; diff --git a/packages/protocol/src/messages.voice-flow.test.ts b/packages/protocol/src/messages.voice-flow.test.ts deleted file mode 100644 index 63e82ca2b1d..00000000000 --- a/packages/protocol/src/messages.voice-flow.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - ServerInfoStatusPayloadSchema, - SessionInboundMessageSchema, - SessionOutboundMessageSchema, -} from "./messages"; - -describe("voice attachment and failure wire contract", () => { - it("continues accepting legacy voice frames without attachment fields", () => { - expect( - SessionInboundMessageSchema.parse({ - type: "voice_audio_chunk", - audio: "AA==", - format: "pcm", - isLast: false, - }), - ).toEqual({ type: "voice_audio_chunk", audio: "AA==", format: "pcm", isLast: false }); - expect(SessionInboundMessageSchema.parse({ type: "abort_request" })).toEqual({ - type: "abort_request", - }); - expect(SessionInboundMessageSchema.parse({ type: "audio_played", id: "clip" })).toEqual({ - type: "audio_played", - id: "clip", - }); - expect(SessionInboundMessageSchema.parse({ type: "set_voice_mode", enabled: true })).toEqual({ - type: "set_voice_mode", - enabled: true, - }); - }); - - it("accepts attachment identity and transport generations on voice frames", () => { - const chunk = { - type: "voice_audio_chunk", - audio: "AA==", - format: "pcm", - isLast: false, - attachmentId: "attachment", - generation: "g2", - }; - expect(SessionInboundMessageSchema.parse(chunk)).toEqual(chunk); - expect( - SessionInboundMessageSchema.parse({ - type: "audio_played", - id: "clip", - error: "Audio playback timed out", - attachmentId: "attachment", - generation: "g2", - }), - ).toEqual({ - type: "audio_played", - id: "clip", - error: "Audio playback timed out", - attachmentId: "attachment", - generation: "g2", - }); - }); - - it("registers the voice receipt read RPC on the session unions", () => { - const request = { - type: "voice.input.receipts.read.request", - requestId: "r", - agentId: "agent-1", - attachmentId: "attachment", - generation: "g2", - }; - expect(SessionInboundMessageSchema.parse(request)).toEqual(request); - }); - - it("keeps recognition issues a plain string so later hosts can extend them", () => { - const issue = { - type: "voice_input_state", - payload: { isSpeaking: false, recognitionIssue: "timed_out" }, - }; - expect(SessionOutboundMessageSchema.parse(issue)).toEqual(issue); - // A value a later host adds must not make an older client reject the message. - expect( - SessionOutboundMessageSchema.parse({ - type: "voice_input_state", - payload: { isSpeaking: false, recognitionIssue: "a_later_issue" }, - }).payload.recognitionIssue, - ).toBe("a_later_issue"); - }); - - it("advertises the voice concurrent input feature as optional", () => { - const status = ServerInfoStatusPayloadSchema.parse({ - status: "server_info", - serverId: "daemon-1", - features: { durableVoiceInputV1: true }, - }); - expect(status.features?.durableVoiceInputV1).toBe(true); - expect( - ServerInfoStatusPayloadSchema.parse({ - status: "server_info", - serverId: "daemon-1", - features: {}, - }).features?.durableVoiceInputV1, - ).toBeUndefined(); - }); -}); diff --git a/packages/server/src/server/agent-queue/send-or-queue.test.ts b/packages/server/src/server/agent-queue/send-or-queue.test.ts deleted file mode 100644 index 58bcb93eee5..00000000000 --- a/packages/server/src/server/agent-queue/send-or-queue.test.ts +++ /dev/null @@ -1,268 +0,0 @@ -import { mkdtemp, rm } from "node:fs/promises"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; -import { afterEach, beforeEach, describe, expect, test } from "vitest"; - -import { createTestLogger } from "../../test-utils/test-logger.js"; -import type { AgentManager } from "../agent/agent-manager.js"; -import type { AgentStorage } from "../agent/agent-storage.js"; -import { AgentQueueService } from "./service.js"; -import { AgentQueueStore } from "./store.js"; -import { sendOrQueuePromptToAgent, type SendOrQueuePromptParams } from "./send-or-queue.js"; - -const AGENT_ID = "agent-1"; - -interface FakeManagerState { - inFlight: boolean; - outOfBandAccepts: boolean; - modeChanges: string[]; -} - -function createFakeManager(state: FakeManagerState): AgentManager { - return { - hasInFlightRun: () => state.inFlight, - tryRunOutOfBand: () => state.outOfBandAccepts, - setAgentMode: async (_agentId: string, mode: string) => { - state.modeChanges.push(mode); - }, - subscribe: () => () => {}, - // The queue's own drain must see the same busy state the policy saw, or it - // would deliver the queued item immediately and the tests would race it. - getAgent: (agentId: string) => ({ - id: agentId, - lifecycle: state.inFlight ? "running" : "idle", - }), - } as unknown as AgentManager; -} - -describe("sendOrQueuePromptToAgent", () => { - let dir: string; - let services: AgentQueueService[]; - - beforeEach(async () => { - dir = await mkdtemp(join(tmpdir(), "send-or-queue-")); - services = []; - }); - - afterEach(async () => { - for (const service of services) { - await service.flushDrains(); - service.stop(); - } - await rm(dir, { recursive: true, force: true }); - }); - - function createHarness(state: FakeManagerState) { - const manager = createFakeManager(state); - const service = new AgentQueueService({ - store: new AgentQueueStore(join(dir, "queues")), - agentManager: manager, - agentStorage: { get: async () => undefined } as unknown as AgentStorage, - logger: createTestLogger(), - // Drains never fire in these tests (no lifecycle events), but the send - // is stubbed anyway so a drain could not reach a real agent. - sendPrompt: async () => {}, - }); - services.push(service); - const sends: SendOrQueuePromptParams[] = []; - const send = (async (params: unknown) => { - sends.push(params as SendOrQueuePromptParams); - return { outOfBand: false }; - }) as NonNullable; - return { manager, service, sends, send }; - } - - test("queues the message when an explicit intent targets a busy agent", async () => { - const state: FakeManagerState = { inFlight: true, outOfBandAccepts: false, modeChanges: [] }; - const harness = createHarness(state); - - const result = await sendOrQueuePromptToAgent({ - agentManager: harness.manager, - agentStorage: {} as AgentStorage, - queueService: harness.service, - agentId: AGENT_ID, - text: "follow-up while busy", - intent: "queue", - messageId: "msg-1", - logger: createTestLogger(), - send: harness.send, - }); - - expect(result).toEqual({ queued: true, outOfBand: false }); - expect(harness.sends).toHaveLength(0); - const snapshot = await harness.service.list(AGENT_ID); - expect(snapshot.items.map((item) => item.id)).toEqual(["msg-1"]); - expect(snapshot.items[0]?.text).toBe("follow-up while busy"); - }); - - test("a busy agent without queue intent keeps the legacy direct send", async () => { - const state: FakeManagerState = { inFlight: true, outOfBandAccepts: false, modeChanges: [] }; - const harness = createHarness(state); - - const result = await sendOrQueuePromptToAgent({ - agentManager: harness.manager, - agentStorage: {} as AgentStorage, - queueService: harness.service, - agentId: AGENT_ID, - text: "legacy busy send", - messageId: "msg-1", - logger: createTestLogger(), - send: harness.send, - }); - - // Admission is explicit: no intent, no queue. This is the seam that keeps - // the legacy send path on its released behavior. - expect(result).toEqual({ queued: false, outOfBand: false }); - expect(harness.sends).toHaveLength(1); - expect((await harness.service.list(AGENT_ID)).items).toHaveLength(0); - }); - - test("interrupt: true bypasses the queue and sends immediately", async () => { - const state: FakeManagerState = { inFlight: true, outOfBandAccepts: false, modeChanges: [] }; - const harness = createHarness(state); - - const result = await sendOrQueuePromptToAgent({ - agentManager: harness.manager, - agentStorage: {} as AgentStorage, - queueService: harness.service, - agentId: AGENT_ID, - text: "explicit interruption", - intent: "queue", - interrupt: true, - logger: createTestLogger(), - send: harness.send, - }); - - expect(result).toEqual({ queued: false, outOfBand: false }); - expect(harness.sends).toHaveLength(1); - expect((await harness.service.list(AGENT_ID)).items).toHaveLength(0); - }); - - test("sends immediately when the agent is idle", async () => { - const state: FakeManagerState = { inFlight: false, outOfBandAccepts: false, modeChanges: [] }; - const harness = createHarness(state); - - const result = await sendOrQueuePromptToAgent({ - agentManager: harness.manager, - agentStorage: {} as AgentStorage, - queueService: harness.service, - agentId: AGENT_ID, - text: "normal send", - intent: "queue", - logger: createTestLogger(), - send: harness.send, - }); - - expect(result).toEqual({ queued: false, outOfBand: false }); - expect(harness.sends).toHaveLength(1); - expect((await harness.service.list(AGENT_ID)).items).toHaveLength(0); - }); - - test("out-of-band commands run mid-turn instead of queueing", async () => { - const state: FakeManagerState = { inFlight: true, outOfBandAccepts: true, modeChanges: [] }; - const harness = createHarness(state); - - const result = await sendOrQueuePromptToAgent({ - agentManager: harness.manager, - agentStorage: {} as AgentStorage, - queueService: harness.service, - agentId: AGENT_ID, - text: "/goal pause", - intent: "queue", - logger: createTestLogger(), - send: harness.send, - }); - - expect(result).toEqual({ queued: false, outOfBand: true }); - expect(harness.sends).toHaveLength(0); - expect((await harness.service.list(AGENT_ID)).items).toHaveLength(0); - }); - - test("applies a requested mode change even while the prompt queues", async () => { - const state: FakeManagerState = { inFlight: true, outOfBandAccepts: false, modeChanges: [] }; - const harness = createHarness(state); - - const result = await sendOrQueuePromptToAgent({ - agentManager: harness.manager, - agentStorage: {} as AgentStorage, - queueService: harness.service, - agentId: AGENT_ID, - text: "queued with mode", - intent: "steer_strict", - sessionMode: "plan", - logger: createTestLogger(), - send: harness.send, - }); - - expect(result.queued).toBe(true); - expect(state.modeChanges).toEqual(["plan"]); - }); - - test("falls back to a direct send when no queue service is available", async () => { - const state: FakeManagerState = { inFlight: true, outOfBandAccepts: false, modeChanges: [] }; - const harness = createHarness(state); - - const result = await sendOrQueuePromptToAgent({ - agentManager: harness.manager, - agentStorage: {} as AgentStorage, - queueService: null, - agentId: AGENT_ID, - text: "no queue configured", - intent: "queue", - logger: createTestLogger(), - send: harness.send, - }); - - expect(result).toEqual({ queued: false, outOfBand: false }); - expect(harness.sends).toHaveLength(1); - }); - - test("spoken input queues even when the agent is idle and never rides out-of-band", async () => { - // Out-of-band would accept here; speech must not take that path. - const state: FakeManagerState = { inFlight: false, outOfBandAccepts: true, modeChanges: [] }; - const harness = createHarness(state); - - const result = await sendOrQueuePromptToAgent({ - agentManager: harness.manager, - agentStorage: {} as AgentStorage, - queueService: harness.service, - agentId: AGENT_ID, - text: "spoken follow-up", - intent: "queue", - origin: "voice", - voiceOwner: "owner-1", - messageId: "attachment:gen:utt", - logger: createTestLogger(), - send: harness.send, - }); - - expect(result).toEqual({ queued: true, outOfBand: false }); - expect(harness.sends).toHaveLength(0); - const snapshot = await harness.service.list(AGENT_ID); - expect(snapshot.items.map((item) => item.id)).toEqual(["attachment:gen:utt"]); - }); - - test("spoken input queues on a busy agent even when out-of-band would accept", async () => { - const state: FakeManagerState = { inFlight: true, outOfBandAccepts: true, modeChanges: [] }; - const harness = createHarness(state); - - const result = await sendOrQueuePromptToAgent({ - agentManager: harness.manager, - agentStorage: {} as AgentStorage, - queueService: harness.service, - agentId: AGENT_ID, - text: "spoken while busy", - intent: "queue", - origin: "voice", - voiceOwner: "owner-1", - logger: createTestLogger(), - send: harness.send, - }); - - expect(result).toEqual({ queued: true, outOfBand: false }); - expect(harness.sends).toHaveLength(0); - expect((await harness.service.list(AGENT_ID)).items.map((item) => item.text)).toEqual([ - "spoken while busy", - ]); - }); -}); diff --git a/packages/server/src/server/agent-queue/send-or-queue.ts b/packages/server/src/server/agent-queue/send-or-queue.ts deleted file mode 100644 index 8ccea02ce6a..00000000000 --- a/packages/server/src/server/agent-queue/send-or-queue.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { Logger } from "pino"; - -import type { AgentAttachment, QueuedAgentDeliveryIntent } from "@getpaseo/protocol/messages"; - -import { sendPromptToAgent } from "../agent/agent-prompt.js"; -import type { AgentManager } from "../agent/agent-manager.js"; -import type { AgentRunOptions } from "../agent/agent-sdk-types.js"; -import type { AgentStorage } from "../agent/agent-storage.js"; -import { buildAgentPrompt } from "../agent/prompt-attachments.js"; -import type { AgentQueueService } from "./service.js"; - -export interface SendOrQueuePromptParams { - agentManager: AgentManager; - agentStorage: AgentStorage; - queueService: AgentQueueService | null; - agentId: string; - text: string; - /** - * Explicit queue admission. Without it this helper is a plain send: a busy - * agent keeps the platform's receipt-backed interrupt semantics, and no - * prompt is ever queued because a surface forgot to decide. - */ - intent?: QueuedAgentDeliveryIntent; - /** Set when the prompt is spoken input; speech always queues, idle or busy. */ - origin?: "voice"; - /** The principal/client pair that spoke the prompt. Required with origin. */ - voiceOwner?: string; - images?: Array<{ data: string; mimeType: string }>; - attachments?: AgentAttachment[]; - messageId?: string; - /** True cancels an in-flight turn (the old replace behavior). */ - interrupt?: boolean; - runOptions?: AgentRunOptions; - sessionMode?: string; - unarchive?: boolean; - logger: Logger; - /** - * Injected so tests can substitute the send without module mocks; defaults - * to the same sendPromptToAgent every prompt surface uses. - */ - send?: typeof sendPromptToAgent; -} - -export interface SendOrQueueResult { - queued: boolean; - outOfBand: boolean; -} - -/** - * The busy policy for prompt surfaces that opt into the durable queue. A prompt - * with an explicit `intent` aimed at an agent with an in-flight turn is queued - * and delivered when the turn completes, because interrupting the turn aborts - * its in-flight tool calls — including running provider subagents. - * `interrupt: true` is the explicit opt-in for the old cancel-and-replace - * behavior. Out-of-band commands (e.g. /goal pause) still run immediately; they - * never touch the active turn. - * - * The legacy `send_agent_message_request` handler does NOT route through here: - * it keeps its own receipt-backed path so old clients see exactly the released - * behavior. - */ -// Busy policy, spoken admission, and the out-of-band escape are one decision. -// oxlint-disable-next-line complexity -export async function sendOrQueuePromptToAgent( - params: SendOrQueuePromptParams, -): Promise { - const { queueService } = params; - // Spoken input always takes the durable queue, idle or busy: one admission - // boundary, one identity, one truthful queued/sent story. It never rides an - // out-of-band run, because speech follows the turn it follows up on. Typed - // prompts keep the TM-02 busy precondition and its out-of-band escape. - const spoken = params.origin === "voice"; - const busy = params.agentManager.hasInFlightRun(params.agentId); - if (!params.interrupt && params.intent && queueService && (spoken || busy)) { - if (!spoken && busy) { - const prompt = buildAgentPrompt(params.text, params.images, params.attachments); - if (await params.agentManager.tryRunOutOfBand(params.agentId, prompt, params.runOptions)) { - return { queued: false, outOfBand: true }; - } - } - if (params.sessionMode) { - // Mode changes apply to the next turn anyway, so setting it now keeps - // the queued prompt's intent even though delivery happens later. - await params.agentManager.setAgentMode(params.agentId, params.sessionMode); - } - await queueService.enqueue({ - agentId: params.agentId, - itemId: params.messageId ?? randomUUID(), - text: params.text, - intent: params.intent, - ...(spoken ? { origin: params.origin, voiceOwner: params.voiceOwner } : {}), - ...(params.images?.length ? { images: params.images } : {}), - ...(params.attachments?.length ? { attachments: params.attachments } : {}), - }); - return { queued: true, outOfBand: false }; - } - - const send = params.send ?? sendPromptToAgent; - const result = await send({ - agentManager: params.agentManager, - agentStorage: params.agentStorage, - agentId: params.agentId, - prompt: buildAgentPrompt(params.text, params.images, params.attachments), - ...(params.messageId ? { messageId: params.messageId } : {}), - ...(params.runOptions ? { runOptions: params.runOptions } : {}), - ...(params.sessionMode ? { sessionMode: params.sessionMode } : {}), - ...(params.unarchive !== undefined ? { unarchive: params.unarchive } : {}), - logger: params.logger, - }); - return { queued: false, outOfBand: result.disposition === "out_of_band" }; -} diff --git a/packages/server/src/server/agent-queue/service.test.ts b/packages/server/src/server/agent-queue/service.test.ts deleted file mode 100644 index 37e257828db..00000000000 --- a/packages/server/src/server/agent-queue/service.test.ts +++ /dev/null @@ -1,1225 +0,0 @@ -import { mkdtemp, rm } from "node:fs/promises"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; -import { afterEach, beforeEach, describe, expect, test } from "vitest"; - -import type { AgentQueueSnapshot } from "@getpaseo/protocol/messages"; -import type { AgentLifecycleStatus } from "@getpaseo/protocol/agent-lifecycle"; - -import { createTestLogger } from "../../test-utils/test-logger.js"; -import type { SteerResult } from "../agent/agent-sdk-types.js"; -import { MessageReceipts } from "../message-receipts/index.js"; -import type { AgentManagerEvent, ManagedAgent } from "../agent/agent-manager.js"; -import type { AgentStorage } from "../agent/agent-storage.js"; -import { - AgentQueueService, - DELIVERY_ATTEMPT_LIMIT, - QueueImagePayloadTooLargeError, - QueueItemDispatchingError, - QueueItemUncertainError, - type AgentQueueAgentController, - type SendQueuedPromptInput, -} from "./service.js"; -import { AgentQueueStore } from "./store.js"; -import { wrapSpokenInput } from "../voice-config.js"; - -const AGENT_ID = "agent-1"; - -/** - * Stands in for the shared AgentManager: the queue service needs the state - * subscription, the lifecycle of the agent it is draining for, the strict-steer - * admission, and the run-start wait. - */ -class FakeAgentController implements AgentQueueAgentController { - lifecycle: AgentLifecycleStatus = "idle"; - pendingPermissions = 0; - steerResult: SteerResult = { status: "unavailable" }; - steerPrompts: unknown[] = []; - private readonly subscribers = new Set<(event: AgentManagerEvent) => void>(); - - subscribe = ((callback: (event: AgentManagerEvent) => void) => { - this.subscribers.add(callback); - return () => { - this.subscribers.delete(callback); - }; - }) as AgentQueueAgentController["subscribe"]; - - getAgent = ((agentId: string) => - ({ - id: agentId, - lifecycle: this.lifecycle, - }) as ManagedAgent) as AgentQueueAgentController["getAgent"]; - - getPendingPermissions = (() => - Array.from({ length: this.pendingPermissions }, (_, index) => ({ - id: `permission-${index}`, - }))) as NonNullable; - - steerAgentRun = (async (_agentId: string, prompt: unknown) => { - this.steerPrompts.push(prompt); - return this.steerResult; - }) as AgentQueueAgentController["steerAgentRun"]; - - waitForAgentRunStart = (async () => {}) as AgentQueueAgentController["waitForAgentRunStart"]; - - emitLifecycle(lifecycle: AgentLifecycleStatus, agentId = AGENT_ID): void { - this.lifecycle = lifecycle; - for (const subscriber of this.subscribers) { - subscriber({ type: "agent_state", agent: { id: agentId, lifecycle } as ManagedAgent }); - } - } - - resolvePermission(agentId = AGENT_ID): void { - this.pendingPermissions = 0; - for (const subscriber of this.subscribers) { - subscriber({ - type: "agent_stream", - agentId, - event: { - type: "permission_resolved", - requestId: "permission-0", - resolution: { behavior: "allow" }, - provider: "codex", - }, - } as unknown as AgentManagerEvent); - } - } -} - -interface Harness { - service: AgentQueueService; - store: AgentQueueStore; - agents: FakeAgentController; - /** Every send the service attempted, including the ones that threw. */ - attempts: SendQueuedPromptInput[]; - sent: SendQueuedPromptInput[]; - broadcasts: AgentQueueSnapshot[]; - failSends: (error: Error | null) => void; -} - -describe("AgentQueueService", () => { - let dir: string; - let harness: Harness; - - function createHarness(): Harness { - const agents = new FakeAgentController(); - const attempts: SendQueuedPromptInput[] = []; - const sent: SendQueuedPromptInput[] = []; - const broadcasts: AgentQueueSnapshot[] = []; - let sendError: Error | null = null; - - const store = new AgentQueueStore(join(dir, "queues")); - const service = new AgentQueueService({ - store, - agentManager: agents, - agentStorage: { get: async () => undefined } as unknown as AgentStorage, - logger: createTestLogger(), - sendPrompt: async (input) => { - attempts.push(input); - if (sendError) { - throw sendError; - } - sent.push(input); - // A real send starts a turn, so the agent is no longer free to drain. - agents.lifecycle = "running"; - }, - }); - service.subscribeToMutations((snapshot) => broadcasts.push(snapshot)); - - return { - service, - store, - agents, - attempts, - sent, - broadcasts, - failSends: (error) => { - sendError = error; - }, - }; - } - - beforeEach(async () => { - dir = await mkdtemp(join(tmpdir(), "paseo-agent-queue-")); - harness = createHarness(); - harness.service.start(); - }); - - afterEach(async () => { - await harness.service.flushDrains(); - harness.service.stop(); - await rm(dir, { recursive: true, force: true }); - }); - - test("broadcasts the queue to subscribers when an item is enqueued while the agent is busy", async () => { - harness.agents.lifecycle = "running"; - - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - - expect(harness.sent).toEqual([]); - expect(harness.broadcasts).toHaveLength(1); - expect(harness.broadcasts[0]?.items.map((item) => item.text)).toEqual(["first"]); - // Delivery bookkeeping rides on every snapshot an enqueuing client sees. - expect(harness.broadcasts[0]?.items[0]).toMatchObject({ - intent: "queue", - deliveryState: "pending", - attempts: 0, - }); - }); - - test("a second client reads the same queue the first client wrote", async () => { - harness.agents.lifecycle = "running"; - - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "from the phone", - intent: "queue", - }); - - const asSeenElsewhere = await harness.service.list(AGENT_ID); - expect(asSeenElsewhere.items.map((item) => item.text)).toEqual(["from the phone"]); - }); - - test("queue survives a service restart", async () => { - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "persisted", - intent: "queue", - }); - - harness.service.stop(); - const restarted = createHarness(); - restarted.agents.lifecycle = "running"; - try { - const snapshot = await restarted.service.list(AGENT_ID); - expect(snapshot.items.map((item) => item.text)).toEqual(["persisted"]); - } finally { - restarted.service.stop(); - } - }); - - test("drains the head when the agent stops running, with no client involved", async () => { - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-2", - text: "second", - intent: "queue", - }); - - harness.agents.emitLifecycle("running"); - harness.agents.emitLifecycle("idle"); - await harness.service.flushDrains(); - - expect(harness.sent.map((input) => input.messageId)).toEqual(["item-1"]); - expect((await harness.service.list(AGENT_ID)).items.map((item) => item.id)).toEqual(["item-2"]); - }); - - test("sends immediately when the agent is already idle", async () => { - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "now", - intent: "queue", - }); - await harness.service.flushDrains(); - - expect(harness.sent.map((input) => input.messageId)).toEqual(["item-1"]); - expect((await harness.service.list(AGENT_ID)).items).toEqual([]); - }); - - test("receipt-backed voice and typed messages preserve FIFO and equal spoken utterances", async () => { - const receipts = new MessageReceipts(join(dir, "agent-requests")); - harness.service.setMessageReceipts(receipts); - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "attachment:a", - text: "same", - intent: "queue", - origin: "voice", - voiceOwner: "owner-1", - }); - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "attachment:b", - text: "same", - intent: "queue", - origin: "voice", - voiceOwner: "owner-1", - }); - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "typed-1", - text: "typed", - intent: "queue", - }); - for (let index = 0; index < 3; index++) { - harness.agents.emitLifecycle("running"); - harness.agents.emitLifecycle("idle"); - await harness.service.flushDrains(); - } - expect(harness.sent.map((item) => item.messageId)).toEqual([ - "attachment:a", - "attachment:b", - "typed-1", - ]); - expect(harness.sent.map((item) => item.prompt)).toEqual([ - wrapSpokenInput("same"), - wrapSpokenInput("same"), - "typed", - ]); - expect(await receipts.outcome(AGENT_ID, "attachment:a#1")).toBe("completed"); - expect((await harness.service.list(AGENT_ID)).items).toEqual([]); - }); - - test("a permission wait holds the head until the keyed resolution", async () => { - harness.service.setMessageReceipts(new MessageReceipts(join(dir, "agent-requests"))); - harness.agents.pendingPermissions = 1; - harness.agents.emitLifecycle("idle"); - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "attachment:a", - text: "yes", - intent: "queue", - origin: "voice", - voiceOwner: "owner-1", - }); - await harness.service.flushDrains(); - expect(harness.sent).toEqual([]); - await expect( - harness.service.waitForPendingDispatch(AGENT_ID, new AbortController().signal), - ).resolves.toBeUndefined(); - expect(harness.agents.pendingPermissions).toBe(1); - expect((await harness.service.list(AGENT_ID)).items.map((item) => item.id)).toEqual([ - "attachment:a", - ]); - harness.agents.resolvePermission(); - await harness.service.flushDrains(); - expect(harness.sent.map((item) => item.messageId)).toEqual(["attachment:a"]); - }); - - test("permission state resolution without a stream event wakes an idle queue", async () => { - harness.agents.pendingPermissions = 1; - harness.agents.emitLifecycle("idle"); - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "yes", - text: "yes", - intent: "queue", - }); - await harness.service.flushDrains(); - expect(harness.sent).toEqual([]); - harness.agents.pendingPermissions = 0; - harness.agents.emitLifecycle("idle"); - await harness.service.flushDrains(); - expect(harness.sent.map((item) => item.messageId)).toEqual(["yes"]); - }); - - test("removing admitted speech records an outcome that survives a later retry", async () => { - harness.service.setMessageReceipts(new MessageReceipts(join(dir, "agent-requests"))); - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "attachment:removed", - text: "cancel this", - intent: "queue", - origin: "voice", - voiceOwner: "owner-1", - }); - const snapshot = await harness.service.list(AGENT_ID); - await harness.service.remove(AGENT_ID, "attachment:removed", snapshot.revision); - const receipts = new MessageReceipts(join(dir, "agent-requests")); - expect(await receipts.outcome(AGENT_ID, "attachment:removed")).toBe("removed"); - expect((await harness.service.list(AGENT_ID)).items).toEqual([]); - // A reconnect retry of the same utterance id must not resurrect deleted speech. - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "attachment:removed", - text: "cancel this", - intent: "queue", - origin: "voice", - voiceOwner: "owner-1", - }); - expect((await harness.service.list(AGENT_ID)).items).toEqual([]); - expect(harness.sent).toEqual([]); - }); - - test("refused speech deletions never write a removed receipt", async () => { - const receipts = new MessageReceipts(join(dir, "agent-requests")); - harness.service.setMessageReceipts(receipts); - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "attachment:protected", - text: "keep this", - intent: "queue", - origin: "voice", - voiceOwner: "owner-1", - }); - const snapshot = await harness.service.list(AGENT_ID); - await expect( - harness.service.remove(AGENT_ID, "attachment:protected", snapshot.revision - 1), - ).rejects.toMatchObject({ code: "queue_revision_conflict" }); - expect(await receipts.outcome(AGENT_ID, "attachment:protected")).toBeNull(); - const [item] = (await harness.store.get(AGENT_ID)).items; - if (!item) throw new Error("Expected queued speech"); - const dispatchingItems = [{ ...item, deliveryState: "dispatching" as const }]; - await harness.store.mutate(AGENT_ID, (current) => ({ - ...current, - items: dispatchingItems, - })); - const claimed = await harness.service.list(AGENT_ID); - await expect( - harness.service.remove(AGENT_ID, "attachment:protected", claimed.revision), - ).rejects.toBeInstanceOf(QueueItemDispatchingError); - expect(await receipts.outcome(AGENT_ID, "attachment:protected")).toBeNull(); - expect((await harness.service.list(AGENT_ID)).items).toHaveLength(1); - }); - - test("a dispatch observer reports an unknown outcome without retrying it", async () => { - harness.service.setMessageReceipts(new MessageReceipts(join(dir, "agent-requests"))); - harness.failSends(new Error("provider accepted, connection lost")); - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "uncertain", - text: "once", - intent: "queue", - }); - await harness.service.flushDrains(); - await expect( - harness.service.waitForPendingDispatch(AGENT_ID, new AbortController().signal), - ).rejects.toThrow("not been confirmed submitted"); - expect(harness.attempts).toHaveLength(1); - expect((await harness.service.list(AGENT_ID)).items.map((item) => item.id)).toEqual([ - "uncertain", - ]); - }); - - test("a competing run retains the head and clears only its pre-provider receipt", async () => { - harness.service.setMessageReceipts(new MessageReceipts(join(dir, "agent-requests"))); - harness.failSends(Object.assign(new Error("Agent busy"), { code: "AGENT_RUN_BUSY" })); - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "race", - text: "follow up", - intent: "queue", - }); - await harness.service.flushDrains(); - expect((await harness.service.list(AGENT_ID)).items.map((item) => item.id)).toEqual(["race"]); - expect( - await new MessageReceipts(join(dir, "agent-requests")).outcome(AGENT_ID, "race#1"), - ).toBeNull(); - harness.failSends(null); - harness.agents.emitLifecycle("running"); - harness.agents.emitLifecycle("idle"); - await harness.service.flushDrains(); - expect(harness.sent.map((item) => item.messageId)).toEqual(["race"]); - }); - - test("a send that fails leaves the message pending at the front of the queue", async () => { - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-2", - text: "second", - intent: "queue", - }); - - harness.failSends(new Error("provider exploded")); - harness.agents.emitLifecycle("running"); - harness.agents.emitLifecycle("idle"); - await harness.service.flushDrains(); - - expect(harness.sent).toEqual([]); - expect(harness.attempts.length).toBeGreaterThan(0); - const items = (await harness.service.list(AGENT_ID)).items; - expect(items.map((item) => item.id)).toEqual(["item-1", "item-2"]); - expect(items[0]).toMatchObject({ deliveryState: "pending", lastError: "provider exploded" }); - }); - - test("removing an item broadcasts the shorter queue", async () => { - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - const second = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-2", - text: "second", - intent: "queue", - }); - harness.broadcasts.length = 0; - - await harness.service.remove(AGENT_ID, "item-1", second.revision); - - expect(harness.broadcasts).toHaveLength(1); - expect(harness.broadcasts[0]?.items.map((item) => item.id)).toEqual(["item-2"]); - }); - - test("removing an unknown item changes nothing and broadcasts nothing", async () => { - harness.agents.lifecycle = "running"; - const first = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - harness.broadcasts.length = 0; - - const snapshot = await harness.service.remove(AGENT_ID, "does-not-exist", first.revision); - - expect(snapshot.items.map((item) => item.id)).toEqual(["item-1"]); - expect(harness.broadcasts).toEqual([]); - }); - - test("a mutation carrying a stale revision is rejected, not applied", async () => { - harness.agents.lifecycle = "running"; - const first = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - - // Another device adds its own item; the first device's view is now stale. - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-2", - text: "from the other device", - intent: "queue", - }); - harness.broadcasts.length = 0; - - await expect(harness.service.remove(AGENT_ID, "item-1", first.revision)).rejects.toMatchObject({ - code: "queue_revision_conflict", - }); - - expect((await harness.service.list(AGENT_ID)).items.map((item) => item.id)).toEqual([ - "item-1", - "item-2", - ]); - expect(harness.broadcasts).toEqual([]); - }); - - test("revision increases monotonically across mutations", async () => { - harness.agents.lifecycle = "running"; - const first = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - const second = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-2", - text: "second", - intent: "queue", - }); - const afterRemovingBoth = await harness.service.remove(AGENT_ID, "item-1", second.revision); - const emptied = await harness.service.remove(AGENT_ID, "item-2", afterRemovingBoth.revision); - const refilled = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-3", - text: "third", - intent: "queue", - }); - - expect(emptied.items).toEqual([]); - expect([ - first.revision, - second.revision, - afterRemovingBoth.revision, - emptied.revision, - refilled.revision, - ]).toEqual([1, 2, 3, 4, 5]); - }); - - test("reorder moves an item to the front and leaves unmentioned ids at the end", async () => { - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - const second = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-2", - text: "second", - intent: "queue", - }); - const third = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-3", - text: "third", - intent: "queue", - }); - - const snapshot = await harness.service.reorder(AGENT_ID, ["item-3", "item-1"], third.revision); - - expect(snapshot.items.map((item) => item.id)).toEqual(["item-3", "item-1", "item-2"]); - expect(second.revision).toBe(2); - }); - - test("image bytes are stored but never broadcast", async () => { - harness.agents.lifecycle = "running"; - - const snapshot = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "look at this", - intent: "queue", - images: [{ data: "AAAA", mimeType: "image/png" }], - }); - - const image = snapshot.items[0]?.images?.[0]; - expect(image).toMatchObject({ mimeType: "image/png", byteSize: 3 }); - expect(JSON.stringify(snapshot)).not.toContain("AAAA"); - }); - - test("queued images reach the agent as prompt image blocks on drain and round-trip on demand", async () => { - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "look at this", - intent: "queue", - images: [{ data: "AAAA", mimeType: "image/png" }], - }); - - // A different device can pull the exact bytes back for its composer. - const images = await harness.service.getItemImages(AGENT_ID, "item-1"); - expect(images.map((image) => image.data)).toEqual(["AAAA"]); - - harness.agents.emitLifecycle("running"); - harness.agents.emitLifecycle("idle"); - await harness.service.flushDrains(); - - expect(harness.sent[0]?.prompt).toEqual([ - { type: "text", text: "look at this" }, - { type: "image", data: "AAAA", mimeType: "image/png" }, - ]); - await expect(harness.service.getItemImages(AGENT_ID, "item-1")).rejects.toThrow( - /no longer queued/, - ); - }); - - test("rejects an empty message", async () => { - await expect( - harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: " ", - intent: "queue", - }), - ).rejects.toThrow(/empty/i); - }); - - test("rejects an enqueue past the queue length bound", async () => { - harness.agents.lifecycle = "running"; - let revision = 0; - for (let index = 0; index < 50; index += 1) { - const snapshot = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: `item-${index}`, - text: `message ${index}`, - intent: "queue", - }); - revision = snapshot.revision; - } - expect(revision).toBe(50); - - await expect( - harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-over", - text: "one too many", - intent: "queue", - }), - ).rejects.toMatchObject({ code: "queue_full", limit: 50 }); - expect((await harness.service.list(AGENT_ID)).items).toHaveLength(50); - }); - - test("rejects an item whose images exceed the payload bound", async () => { - harness.agents.lifecycle = "running"; - const oversized = "A".repeat(16 * 1024 * 1024 + 1); - - await expect( - harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "with a huge image", - intent: "queue", - images: [{ data: oversized, mimeType: "image/png" }], - }), - ).rejects.toBeInstanceOf(QueueImagePayloadTooLargeError); - expect((await harness.service.list(AGENT_ID)).items).toEqual([]); - }); - - test("re-enqueueing the same id is a retry, not a duplicate", async () => { - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - const snapshot = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - - expect(snapshot.items.map((item) => item.id)).toEqual(["item-1"]); - }); - - test("an enqueue retry that lands after the item drained does not resend it", async () => { - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "once", - intent: "queue", - }); - await harness.service.flushDrains(); - expect(harness.sent.map((input) => input.messageId)).toEqual(["item-1"]); - - // The client never saw the ack (e.g. relay dropped mid-request) and retries - // after reconnect. The daemon already delivered the item. - harness.agents.lifecycle = "idle"; - const snapshot = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "once", - intent: "queue", - }); - await harness.service.flushDrains(); - - expect(snapshot.items).toEqual([]); - expect(harness.sent.map((input) => input.messageId)).toEqual(["item-1"]); - }); - - test("a failed delivery retries on the next wakeup and delivers once", async () => { - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "flaky", - intent: "queue", - }); - - harness.failSends(new Error("provider exploded")); - harness.agents.emitLifecycle("running"); - harness.agents.emitLifecycle("idle"); - await harness.service.flushDrains(); - expect(harness.sent).toEqual([]); - - harness.failSends(null); - harness.agents.emitLifecycle("running"); - harness.agents.emitLifecycle("idle"); - await harness.service.flushDrains(); - - expect(harness.sent.map((input) => input.messageId)).toEqual(["item-1"]); - expect((await harness.service.list(AGENT_ID)).items).toEqual([]); - }); - - test("repeated known failures end in a visible failed state at the attempt limit", async () => { - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "doomed", - intent: "queue", - }); - - harness.failSends(new Error("provider exploded")); - for (let attempt = 0; attempt < DELIVERY_ATTEMPT_LIMIT; attempt += 1) { - harness.agents.emitLifecycle("running"); - harness.agents.emitLifecycle("idle"); - await harness.service.flushDrains(); - } - - const items = (await harness.service.list(AGENT_ID)).items; - expect(items).toHaveLength(1); - expect(items[0]).toMatchObject({ - deliveryState: "failed", - attempts: DELIVERY_ATTEMPT_LIMIT, - lastError: "provider exploded", - }); - expect(harness.attempts).toHaveLength(DELIVERY_ATTEMPT_LIMIT); - - // An explicit retry is the only way back to deliverable. - harness.failSends(null); - const revision = (await harness.service.list(AGENT_ID)).revision; - const snapshot = await harness.service.retry(AGENT_ID, "item-1", revision); - expect(snapshot.items[0]).toMatchObject({ deliveryState: "pending", attempts: 0 }); - await harness.service.flushDrains(); - expect(harness.sent.map((input) => input.messageId)).toEqual(["item-1"]); - }); - - test("editing an item replaces its content and resets its delivery state", async () => { - harness.agents.lifecycle = "running"; - const enqueued = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "before the edit", - intent: "queue", - }); - - const snapshot = await harness.service.update(AGENT_ID, "item-1", enqueued.revision, { - text: "after the edit", - images: [{ data: "BBBB", mimeType: "image/jpeg" }], - }); - - expect(snapshot.items[0]).toMatchObject({ - text: "after the edit", - deliveryState: "pending", - attempts: 0, - }); - expect(snapshot.items[0]?.images?.[0]?.byteSize).toBe(3); - - harness.agents.emitLifecycle("running"); - harness.agents.emitLifecycle("idle"); - await harness.service.flushDrains(); - expect(harness.sent[0]?.prompt).toEqual([ - { type: "text", text: "after the edit" }, - { type: "image", data: "BBBB", mimeType: "image/jpeg" }, - ]); - }); - - test("editing refuses a dispatching item and demands a decision on an uncertain item", async () => { - harness.agents.lifecycle = "running"; - const now = new Date().toISOString(); - await harness.store.mutate(AGENT_ID, (current) => ({ - ...current, - items: [ - { - id: "item-1", - text: "in flight", - intent: "queue", - deliveryState: "dispatching", - attempts: 1, - attemptSeq: 1, - createdAt: now, - }, - { - id: "item-2", - text: "ambiguous", - intent: "queue", - deliveryState: "uncertain", - attempts: 1, - attemptSeq: 1, - lastError: "agent_request_outcome_unknown", - createdAt: now, - }, - ], - })); - const revision = (await harness.service.list(AGENT_ID)).revision; - - await expect( - harness.service.update(AGENT_ID, "item-1", revision, { text: "edited mid-flight" }), - ).rejects.toBeInstanceOf(QueueItemDispatchingError); - await expect( - harness.service.update(AGENT_ID, "item-2", revision, { text: "edited while uncertain" }), - ).rejects.toBeInstanceOf(QueueItemUncertainError); - // Deletion of an in-flight item is refused too; the ambiguous one is - // deletable — that is the explicit discard. - await expect(harness.service.remove(AGENT_ID, "item-1", revision)).rejects.toBeInstanceOf( - QueueItemDispatchingError, - ); - const discarded = await harness.service.remove(AGENT_ID, "item-2", revision); - expect(discarded.items.map((item) => item.id)).toEqual(["item-1"]); - }); - - test("deleting an agent drops its queue", async () => { - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - - await harness.service.deleteForAgent(AGENT_ID); - - expect((await harness.service.list(AGENT_ID)).items).toEqual([]); - }); - - test("send_now delivers a pending item from a free agent and reports the post-attempt queue", async () => { - harness.agents.lifecycle = "running"; - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "first", - intent: "queue", - }); - const second = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-2", - text: "urgent second", - intent: "queue", - }); - - // An explicit send-now may deliver a later item to a free agent: the - // response shows it gone while the head remains queued. The enqueues armed - // drain attempts that were refused while busy, so settle them first. - await harness.service.flushDrains(); - harness.agents.lifecycle = "idle"; - const snapshot = await harness.service.sendNow(AGENT_ID, "item-2", second.revision); - expect(snapshot.items.map((item) => item.id)).toEqual(["item-1"]); - expect(harness.sent.map((input) => input.messageId)).toEqual(["item-2"]); - }); - - test("send_now on a busy agent refuses without touching the queue", async () => { - harness.agents.lifecycle = "running"; - const enqueued = await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "wait your turn", - intent: "queue", - }); - harness.broadcasts.length = 0; - - const snapshot = await harness.service.sendNow(AGENT_ID, "item-1", enqueued.revision); - - expect(snapshot.items.map((item) => item.id)).toEqual(["item-1"]); - expect(snapshot.items[0]).toMatchObject({ deliveryState: "pending" }); - expect(harness.sent).toEqual([]); - expect(harness.broadcasts).toEqual([]); - }); - - test("a refused strict steer leaves the turn running, the item pending, and burns no attempt", async () => { - harness.agents.lifecycle = "running"; - harness.agents.steerResult = { status: "unavailable" }; - - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "steer this", - intent: "steer_strict", - }); - await harness.service.flushDrains(); - - // The admission was asked once, refused, and nothing was interrupted. - expect(harness.agents.steerPrompts).toHaveLength(1); - expect(harness.agents.lifecycle).toBe("running"); - expect(harness.sent).toEqual([]); - const items = (await harness.service.list(AGENT_ID)).items; - expect(items[0]).toMatchObject({ deliveryState: "pending", attempts: 0 }); - - // When the turn later ends, the item is delivered as a normal run — the - // fallback that never interrupts anything. - harness.agents.emitLifecycle("running"); - harness.agents.emitLifecycle("idle"); - await harness.service.flushDrains(); - expect(harness.sent.map((input) => input.messageId)).toEqual(["item-1"]); - expect((await harness.service.list(AGENT_ID)).items).toEqual([]); - }); - - test("an accepted strict steer delivers into the running turn", async () => { - harness.agents.lifecycle = "running"; - harness.agents.steerResult = { status: "accepted" }; - - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "steer this", - intent: "steer_strict", - }); - await harness.service.flushDrains(); - - expect(harness.agents.steerPrompts).toHaveLength(1); - expect((await harness.service.list(AGENT_ID)).items).toEqual([]); - expect(harness.sent).toEqual([]); - }); - - test("a steer_strict item on an idle agent is delivered as a normal run", async () => { - await harness.service.enqueue({ - agentId: AGENT_ID, - itemId: "item-1", - text: "arrived after the turn ended", - intent: "steer_strict", - }); - await harness.service.flushDrains(); - - expect(harness.sent.map((input) => input.messageId)).toEqual(["item-1"]); - expect((await harness.service.list(AGENT_ID)).items).toEqual([]); - }); -}); - -describe("AgentQueueService startup recovery", () => { - let dir: string; - - beforeEach(async () => { - dir = await mkdtemp(join(tmpdir(), "paseo-agent-queue-recovery-")); - }); - - afterEach(async () => { - await rm(dir, { recursive: true, force: true }); - }); - - interface RecoveryHarness { - service: AgentQueueService; - agents: FakeAgentController; - store: AgentQueueStore; - receipts: MessageReceipts; - sent: SendQueuedPromptInput[]; - } - - async function createRecoveryHarness(): Promise { - const agents = new FakeAgentController(); - const receipts = new MessageReceipts(join(dir, "agent-requests")); - const store = new AgentQueueStore(join(dir, "queues")); - const sent: SendQueuedPromptInput[] = []; - const service = new AgentQueueService({ - store, - agentManager: agents, - agentStorage: { get: async () => undefined } as unknown as AgentStorage, - logger: createTestLogger(), - receipts, - sendPrompt: async (input) => { - sent.push(input); - agents.lifecycle = "running"; - }, - }); - return { service, agents, store, receipts, sent }; - } - - test("activates without dispatching, then resumes only never-dispatched items", async () => { - const first = await createRecoveryHarness(); - first.agents.lifecycle = "running"; - await first.service.start(); - await first.service.enqueue({ - agentId: "agent-a", - itemId: "kept", - text: "queued before the restart", - intent: "queue", - }); - await first.service.enqueue({ - agentId: "agent-a", - itemId: "removed", - text: "deleted before the restart", - intent: "queue", - }); - const before = await first.service.list("agent-a"); - await first.service.remove("agent-a", "removed", before.revision); - await first.service.stop(); - - // A restarted daemon loads the queue without dispatching: construction and - // activation are separate, and agents that are not loaded stay untouched. - const second = await createRecoveryHarness(); - expect((await second.service.list("agent-a")).items.map((item) => item.id)).toEqual(["kept"]); - expect(second.sent).toEqual([]); - - // The agent is loaded and idle at activation time, so the never-dispatched - // item resumes exactly once. - second.agents.lifecycle = "idle"; - await second.service.activate(); - expect(second.sent.map((input) => input.messageId)).toEqual(["kept"]); - expect((await second.service.list("agent-a")).items).toEqual([]); - await second.service.stop(); - }); - - test("a claim whose receipt completed is delivered, not resent", async () => { - const harness = await createRecoveryHarness(); - const prompt = [{ type: "text", text: "crashed mid-dispatch" }]; - // Simulate a crash after the provider took the prompt: the attempt's - // receipt reached `completed` but the queue still holds the claim. - await harness.receipts.send({ - agentId: "agent-a", - messageId: "claimed#1", - request: { prompt, intent: "queue" }, - send: async () => {}, - }); - await harness.store.mutate("agent-a", (current) => ({ - ...current, - items: [ - { - id: "claimed", - text: "crashed mid-dispatch", - intent: "queue", - deliveryState: "dispatching", - attempts: 1, - attemptSeq: 1, - createdAt: new Date().toISOString(), - }, - ], - })); - - await harness.service.activate(); - - expect((await harness.service.list("agent-a")).items).toEqual([]); - expect(harness.sent).toEqual([]); - await harness.service.stop(); - }); - - test("a claim whose receipt is pending holds as uncertain and is never auto-resent", async () => { - const harness = await createRecoveryHarness(); - const prompt = [{ type: "text", text: "crashed before the receipt" }]; - // The receipt was committed but the send never completed: the provider may - // or may not have the prompt. The simulated crash rejects the send. - await harness.receipts - .send({ - agentId: "agent-a", - messageId: "claimed#1", - request: { prompt, intent: "queue" }, - send: async () => { - throw new Error("daemon restarted mid-send"); - }, - }) - .catch(() => undefined); - await harness.store.mutate("agent-a", (current) => ({ - ...current, - items: [ - { - id: "claimed", - text: "crashed before the receipt", - intent: "queue", - deliveryState: "dispatching", - attempts: 1, - attemptSeq: 1, - createdAt: new Date().toISOString(), - }, - ], - })); - - await harness.service.activate(); - await harness.service.flushDrains(); - - const items = (await harness.service.list("agent-a")).items; - expect(items[0]).toMatchObject({ - deliveryState: "uncertain", - lastError: "agent_request_outcome_unknown", - }); - expect(harness.sent).toEqual([]); - - // The explicit user decision is the only path that resends it. - const snapshot = await harness.service.retry( - "agent-a", - "claimed", - (await harness.service.list("agent-a")).revision, - ); - expect(snapshot.items[0]).toMatchObject({ deliveryState: "pending", attempts: 0 }); - await harness.service.flushDrains(); - expect(harness.sent.map((input) => input.messageId)).toEqual(["claimed"]); - await harness.service.stop(); - }); - - test("a queue-intent claim with no receipt resumes as never dispatched", async () => { - const harness = await createRecoveryHarness(); - // Crash between claim and dispatch: the receipt layer saw nothing, so the - // prompt never reached the provider. - await harness.store.mutate("agent-a", (current) => ({ - ...current, - items: [ - { - id: "claimed", - text: "claimed but never sent", - intent: "queue", - deliveryState: "dispatching", - attempts: 1, - attemptSeq: 1, - createdAt: new Date().toISOString(), - }, - ], - })); - - // Recovery returns the claim to `pending` instead of holding it, and the - // activation then delivers it exactly once to the loaded, idle agent. - await harness.service.activate(); - - expect(harness.sent.map((input) => input.messageId)).toEqual(["claimed"]); - expect((await harness.service.list("agent-a")).items).toEqual([]); - await harness.service.stop(); - }); - - test("a steer_strict claim with no receipt holds as uncertain", async () => { - const harness = await createRecoveryHarness(); - await harness.store.mutate("agent-a", (current) => ({ - ...current, - items: [ - { - id: "steered-maybe", - text: "steer interrupted by a crash", - intent: "steer_strict", - deliveryState: "dispatching", - attempts: 1, - attemptSeq: 1, - createdAt: new Date().toISOString(), - }, - ], - })); - - await harness.service.activate(); - await harness.service.flushDrains(); - - expect((await harness.service.list("agent-a")).items[0]).toMatchObject({ - deliveryState: "uncertain", - lastError: "queue_claim_interrupted", - }); - expect(harness.sent).toEqual([]); - await harness.service.stop(); - }); - - test("an archived agent keeps its queue and never auto-runs it", async () => { - const records = new Map([ - ["agent-archived", { archivedAt: "2026-01-01T00:00:00.000Z" }], - ]); - const agents = new FakeAgentController(); - const sent: SendQueuedPromptInput[] = []; - const service = new AgentQueueService({ - store: new AgentQueueStore(join(dir, "queues")), - agentManager: agents, - agentStorage: { - get: async (agentId: string) => records.get(agentId), - } as unknown as AgentStorage, - logger: createTestLogger(), - sendPrompt: async (input) => { - sent.push(input); - agents.lifecycle = "running"; - }, - }); - - await service.enqueue({ - agentId: "agent-archived", - itemId: "item-1", - text: "waiting for a restored agent", - intent: "queue", - }); - await service.flushDrains(); - - agents.lifecycle = "idle"; - agents.emitLifecycle("running"); - agents.emitLifecycle("idle"); - await service.activate(); - await service.flushDrains(); - - expect(sent).toEqual([]); - expect((await service.list("agent-archived")).items.map((item) => item.id)).toEqual(["item-1"]); - await service.stop(); - }); -}); diff --git a/packages/server/src/server/agent-queue/service.ts b/packages/server/src/server/agent-queue/service.ts deleted file mode 100644 index afbc6928dbf..00000000000 --- a/packages/server/src/server/agent-queue/service.ts +++ /dev/null @@ -1,993 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { Logger } from "pino"; - -import type { - AgentAttachment, - AgentQueueSnapshot, - QueuedAgentDeliveryIntent, - QueuedComposerAttachment, -} from "@getpaseo/protocol/messages"; -import type { AgentLifecycleStatus } from "@getpaseo/protocol/agent-lifecycle"; - -import type { AgentManager } from "../agent/agent-manager.js"; -import type { AgentPromptInput } from "../agent/agent-sdk-types.js"; -import type { AgentStorage } from "../agent/agent-storage.js"; -import { buildAgentPrompt } from "../agent/prompt-attachments.js"; -import { sendPromptToAgent, waitForAgentRunStartWithTimeout } from "../agent/agent-prompt.js"; -import { wrapSpokenInput } from "../voice-config.js"; -import type { MessageReceipts } from "../message-receipts/index.js"; -import { - QueueRevisionConflictError, - recordDrainedId, - toAgentQueueSnapshot, - type AgentQueueMutationResult, - type AgentQueueStore, - type StoredQueuedImage, - type StoredQueuedMessage, -} from "./store.js"; - -/** - * A dispatch that fails with a known pre-start error is retried on the next - * wakeup until the limit; the attempt that passes the limit leaves the item in - * the visible `failed` state with an explicit retry or discard. - */ -export const DELIVERY_ATTEMPT_LIMIT = 8; - -/** - * Admission bounds. A queue is a holding area for follow-ups, not an archive: - * past these limits the client gets a machine-readable rejection instead of an - * unbounded record. - */ -export const MAX_ITEMS_PER_QUEUE = 50; -export const MAX_ITEM_IMAGE_BASE64_CHARS = 16 * 1024 * 1024; - -export class QueueFullError extends Error { - readonly code = "queue_full"; - - constructor(readonly limit: number) { - super(`Agent queue holds at most ${limit} items`); - this.name = "QueueFullError"; - } -} - -export class QueueImagePayloadTooLargeError extends Error { - readonly code = "image_payload_too_large"; - - constructor(readonly limit: number) { - super(`Queued images exceed ${limit} base64 characters per item`); - this.name = "QueueImagePayloadTooLargeError"; - } -} - -export class QueueItemDispatchingError extends Error { - readonly code = "queue_item_dispatching"; - - constructor(itemId: string) { - super(`Queued message ${itemId} is being dispatched`); - this.name = "QueueItemDispatchingError"; - } -} - -export class QueueItemUncertainError extends Error { - readonly code = "queue_item_uncertain"; - - constructor(itemId: string) { - super(`Queued message ${itemId} needs an explicit retry or discard first`); - this.name = "QueueItemUncertainError"; - } -} - -/** A strict steer the provider would not absorb. Never interrupts the turn. */ -class QueueSteerRefusedError extends Error { - constructor(itemId: string) { - super(`Queued message ${itemId} was not steered into the active turn`); - this.name = "QueueSteerRefusedError"; - } -} - -export type AgentQueueMutationListener = (snapshot: AgentQueueSnapshot) => void; - -export interface EnqueueAgentMessageInput { - agentId: string; - itemId: string; - text: string; - /** Admission is explicit: the daemon never infers a delivery intent. */ - intent: QueuedAgentDeliveryIntent; - /** Set when the item is spoken input; wraps the prompt and keys receipt reads. */ - origin?: "voice"; - /** The principal/client pair that spoke the item. Required when origin is set. */ - voiceOwner?: string; - images?: Array<{ data: string; mimeType: string }>; - attachments?: AgentAttachment[]; - composerAttachments?: QueuedComposerAttachment[]; -} - -export interface UpdateQueuedMessageInput { - text: string; - images?: Array<{ data: string; mimeType: string }>; - attachments?: AgentAttachment[]; - composerAttachments?: QueuedComposerAttachment[]; -} - -export interface SendQueuedPromptInput { - agentId: string; - prompt: AgentPromptInput; - messageId: string; -} - -/** The queue drains through the same receipt service the legacy send path uses. */ -export type AgentQueueReceiptController = Pick< - MessageReceipts, - "send" | "outcome" | "listForAttachment" | "recordRemoved" ->; - -export interface AgentQueueServiceOptions { - store: AgentQueueStore; - agentManager: AgentQueueAgentController; - agentStorage: AgentStorage; - logger: Logger; - /** Correlates dispatch attempts across restarts. Absent only in unit tests. */ - receipts?: AgentQueueReceiptController | null; - /** - * Injected so tests can substitute the send without module mocks; defaults to - * the same sendPromptToAgent the send_agent_message_request handler uses. - */ - sendPrompt?: (input: SendQueuedPromptInput) => Promise; -} - -export type AgentQueueAgentController = Pick< - AgentManager, - "subscribe" | "getAgent" | "steerAgentRun" | "waitForAgentRunStart" -> & - Partial>; - -/** - * The receipt key of one dispatch attempt. Attempts are keyed individually so a - * retry after a known failure is not blocked by the previous attempt's receipt. - */ -function attemptReceiptId(itemId: string, attempt: number): string { - return `${itemId}#${attempt}`; -} - -/** - * Owns the per-agent message queue for the whole daemon: one instance, shared by - * every connected session, so the queue mirrors across devices and drains even - * when nothing is connected. - * - * Delivery is claim -> provider dispatch -> correlated receipt -> removal. A - * claimed item stays in the queue in the `dispatching` state, so a crash leaves - * the state on disk for startup recovery instead of silently dropping or - * resending the prompt. - */ -export class AgentQueueService { - private readonly store: AgentQueueStore; - private readonly agentManager: AgentQueueAgentController; - private readonly agentStorage: AgentStorage; - private readonly logger: Logger; - private readonly receiptsOption: AgentQueueReceiptController | null; - private receipts: AgentQueueReceiptController | null; - private readonly sendPrompt: (input: SendQueuedPromptInput) => Promise; - - private readonly listeners = new Set(); - private readonly lastLifecycle = new Map(); - private readonly lastPermissionCount = new Map(); - private readonly drainTails = new Map>(); - private unsubscribeAgentEvents: (() => void) | null = null; - - constructor(options: AgentQueueServiceOptions) { - this.store = options.store; - this.agentManager = options.agentManager; - this.agentStorage = options.agentStorage; - this.logger = options.logger.child({ module: "agent", component: "agent-queue" }); - this.receiptsOption = options.receipts ?? null; - this.receipts = this.receiptsOption; - this.sendPrompt = - options.sendPrompt ?? - ((input) => - sendPromptToAgent({ - agentManager: this.agentManager as AgentManager, - agentStorage: this.agentStorage, - agentId: input.agentId, - prompt: input.prompt, - messageId: input.messageId, - // A queued follow-up must never cancel and replace a turn that - // started after the claim; losing the race is a failed attempt. - replaceRunning: false, - // And it waits behind a permission wait: answering it is the user's - // decision, never the queued prompt's. - blockPendingPermissions: true, - unarchive: false, - logger: this.logger, - })); - } - - /** - * Reuse the daemon's direct-send receipt owner once the WebSocket server - * constructs it. Unit tests may instead inject one through the options. - */ - setMessageReceipts(receipts: AgentQueueReceiptController): void { - if (this.receiptsOption) { - throw new Error("Agent queue receipts were already provided at construction"); - } - this.receipts = receipts; - } - - /** - * Startup recovery: resolve claims left in `dispatching` state, then start - * lifecycle delivery. Items whose provider acceptance is unknown become - * `uncertain` and are never dispatched again without an explicit retry. - * - * Call once after agents and providers are ready — never during daemon - * initialization, so loading state and deciding outcomes stay separate. - */ - async activate(): Promise { - for (const agentId of await this.store.ids()) { - const recovered = await this.recoverDispatchingClaims(agentId); - if (recovered.changed) { - this.publish(recovered); - } - } - this.start(); - // Wake agents that are already loaded and idle so never-dispatched items - // resume. Agents that load on demand later drain through their own - // running-to-idle transition instead of being loaded here. - for (const agentId of await this.store.ids()) { - if (this.agentManager.getAgent(agentId)?.lifecycle === "idle") { - this.scheduleDrain(agentId); - } - } - await this.flushDrains(); - } - - /** - * Resolves one agent's `dispatching` claims against the receipt record: - * completed means the provider took the prompt (remove the item), pending - * means the attempt may have landed (hold as `uncertain`), and no receipt - * means the attempt never dispatched for `queue` intent — while a strict - * steer may have reached the provider mid-admission, so it holds as - * `uncertain` too. - */ - private async recoverDispatchingClaims(agentId: string): Promise { - const queue = await this.store.get(agentId); - const claimed = queue.items.filter((item) => item.deliveryState === "dispatching"); - if (claimed.length === 0) { - return { queue, changed: false }; - } - const outcomes = new Map(); - for (const item of claimed) { - outcomes.set( - item.id, - this.receipts - ? await this.receipts.outcome(agentId, attemptReceiptId(item.id, item.attemptSeq)) - : null, - ); - } - return this.store.mutate(agentId, (current) => { - const items: StoredQueuedMessage[] = []; - let drainedIds = current.drainedIds; - let changed = false; - for (const item of current.items) { - if (item.deliveryState !== "dispatching") { - items.push(item); - continue; - } - changed = true; - const outcome = outcomes.get(item.id); - if (outcome === "completed") { - drainedIds = recordDrainedId(drainedIds, item.id); - continue; - } - if (outcome === "pending") { - items.push({ - ...item, - deliveryState: "uncertain", - lastError: "agent_request_outcome_unknown", - }); - continue; - } - // No receipt for the in-flight attempt: the send never happened for - // queue intent, while a strict steer may have reached the provider - // mid-admission, so only the steer holds as uncertain. - if (item.intent === "steer_strict") { - items.push({ - ...item, - deliveryState: "uncertain", - lastError: "queue_claim_interrupted", - }); - continue; - } - items.push({ ...item, deliveryState: "pending" }); - } - if (!changed) { - return current; - } - return { ...current, items, drainedIds }; - }); - } - - start(): void { - if (this.unsubscribeAgentEvents) { - return; - } - this.unsubscribeAgentEvents = this.agentManager.subscribe((event) => { - // A keyed permission resolution is itself a drain wakeup: the head was - // held only because of the wait, and the run it follows up on may end - // without another lifecycle transition. - if (event.type === "agent_stream" && event.event.type === "permission_resolved") { - this.scheduleDrain(event.agentId); - return; - } - if (event.type !== "agent_state") { - return; - } - const permissionCount = this.pendingPermissionCount(event.agent.id, event.agent); - const previousCount = this.lastPermissionCount.get(event.agent.id) ?? 0; - this.lastPermissionCount.set(event.agent.id, permissionCount); - if (previousCount > 0 && permissionCount === 0) this.scheduleDrain(event.agent.id); - this.handleAgentState(event.agent.id, event.agent.lifecycle); - }); - } - - stop(): void { - this.unsubscribeAgentEvents?.(); - this.unsubscribeAgentEvents = null; - this.listeners.clear(); - this.lastLifecycle.clear(); - this.lastPermissionCount.clear(); - } - - subscribeToMutations(listener: AgentQueueMutationListener): () => void { - this.listeners.add(listener); - return () => { - this.listeners.delete(listener); - }; - } - - async list(agentId: string): Promise { - return toAgentQueueSnapshot(await this.store.get(agentId)); - } - - /** - * This attachment's spoken items still in the queue. Receipt reads merge this - * with the durable receipt records, so the speaking device sees queued and - * submitted state that survives its own reconnects. - */ - async listVoiceInputs( - agentId: string, - attachmentId: string, - voiceOwner?: string, - ): Promise { - const queue = await this.store.get(agentId); - return queue.items.filter( - (item) => - item.origin === "voice" && - item.voiceOwner === voiceOwner && - item.id.startsWith(`${attachmentId}:`), - ); - } - - async enqueue(input: EnqueueAgentMessageInput): Promise { - const text = input.text.trim(); - const attachments = input.attachments ?? []; - const images = input.images ?? []; - if (!text && attachments.length === 0 && images.length === 0) { - throw new Error("Cannot queue an empty message"); - } - this.assertImagePayloadWithinLimit(images); - - const item: StoredQueuedMessage = { - id: input.itemId, - text, - ...(input.origin ? { origin: input.origin, voiceOwner: input.voiceOwner } : {}), - intent: input.intent, - deliveryState: "pending", - attempts: 0, - attemptSeq: 0, - createdAt: new Date().toISOString(), - ...(attachments.length ? { attachments } : {}), - ...(input.composerAttachments?.length - ? { composerAttachments: input.composerAttachments } - : {}), - ...(images.length - ? { - images: images.map((image) => ({ - id: randomUUID(), - mimeType: image.mimeType, - fileName: null, - data: image.data, - })), - } - : {}), - }; - - const result = await this.store.mutate(input.agentId, async (current) => { - // Re-enqueueing the same id is a retry, not a duplicate — including a - // retry that lands after the item was already drained and delivered. - if (current.items.some((existing) => existing.id === item.id)) { - return current; - } - // The receipt record outlives the bounded drained-id window: a delivered - // or user-deleted item's id must never admit again. - if (this.receipts) { - const outcome = await this.receipts.outcome(input.agentId, item.id); - if (outcome === "completed" || outcome === "removed") return current; - } - if (current.drainedIds?.includes(item.id)) { - return current; - } - if (current.items.length >= MAX_ITEMS_PER_QUEUE) { - throw new QueueFullError(MAX_ITEMS_PER_QUEUE); - } - return { ...current, items: [...current.items, item] }; - }); - this.publish(result); - this.scheduleDrain(input.agentId); - return toAgentQueueSnapshot(result.queue); - } - - /** - * Replaces one item's content. The replacement is a new admission of the same - * identity: attempts reset, and a `failed` item becomes deliverable again. - * A `dispatching` item refuses the edit (the dispatch is in flight) and an - * `uncertain` item demands an explicit retry or discard first, because - * rewriting the content cannot tell the user whether the old one arrived. - */ - async update( - agentId: string, - itemId: string, - expectedRevision: number, - patch: UpdateQueuedMessageInput, - ): Promise { - const text = patch.text.trim(); - const attachments = patch.attachments ?? []; - const images = patch.images ?? []; - if (!text && attachments.length === 0 && images.length === 0) { - throw new Error("Cannot queue an empty message"); - } - this.assertImagePayloadWithinLimit(images); - - const result = await this.store.mutateWithExpectedRevision( - agentId, - expectedRevision, - (current) => { - if (!current.items.some((item) => item.id === itemId)) { - throw new Error(`Queued message ${itemId} is no longer queued`); - } - return { - ...current, - items: current.items.map((item) => { - if (item.id !== itemId) { - return item; - } - if (item.deliveryState === "dispatching") { - throw new QueueItemDispatchingError(itemId); - } - if (item.deliveryState === "uncertain") { - throw new QueueItemUncertainError(itemId); - } - return { - ...item, - text, - deliveryState: "pending", - attempts: 0, - // Re-admission with new content: the sequence keeps increasing - // so the new dispatch never reuses an old attempt's receipt key. - attemptSeq: item.attemptSeq + 1, - lastError: undefined, - ...(attachments.length ? { attachments } : { attachments: undefined }), - ...(images.length - ? { - images: images.map((image) => ({ - id: randomUUID(), - mimeType: image.mimeType, - fileName: null, - data: image.data, - })), - } - : { images: undefined }), - ...(patch.composerAttachments?.length - ? { composerAttachments: patch.composerAttachments } - : { composerAttachments: undefined }), - }; - }), - }; - }, - ); - this.publish(result); - this.scheduleDrain(agentId); - return toAgentQueueSnapshot(result.queue); - } - - /** - * Deletes one item. A `dispatching` item refuses deletion because the provider - * dispatch is in flight; `uncertain` and `failed` items are deletable — that - * is the explicit discard. - */ - async remove( - agentId: string, - itemId: string, - expectedRevision: number, - ): Promise { - const result = await this.store.mutateWithExpectedRevision( - agentId, - expectedRevision, - async (current) => { - const item = current.items.find((candidate) => candidate.id === itemId); - if (!item) { - return current; - } - if (item.deliveryState === "dispatching") { - throw new QueueItemDispatchingError(itemId); - } - // Validate under the queue lock before writing the durable tombstone. - // A refused stale edit or in-flight deletion cannot change its outcome. - if (item.origin === "voice" && this.receipts) { - await this.receipts.recordRemoved({ - agentId, - messageId: itemId, - attachmentId: itemId.split(":", 1)[0], - voiceOwner: item.voiceOwner, - createdAt: item.createdAt, - }); - } - return { ...current, items: current.items.filter((candidate) => candidate.id !== itemId) }; - }, - ); - this.publish(result); - return toAgentQueueSnapshot(result.queue); - } - - async reorder( - agentId: string, - itemIds: string[], - expectedRevision: number, - ): Promise { - const result = await this.store.mutateWithExpectedRevision( - agentId, - expectedRevision, - (current) => { - const byId = new Map(current.items.map((item) => [item.id, item])); - const ordered: StoredQueuedMessage[] = []; - for (const id of itemIds) { - const item = byId.get(id); - if (item) { - ordered.push(item); - byId.delete(id); - } - } - // Ids the caller did not mention keep their relative order at the end. - ordered.push(...current.items.filter((item) => byId.has(item.id))); - const unchanged = ordered.every((item, index) => current.items[index]?.id === item.id); - return unchanged ? current : { ...current, items: ordered }; - }, - ); - this.publish(result); - return toAgentQueueSnapshot(result.queue); - } - - /** - * Explicit user decision to attempt an `uncertain` or `failed` item again — - * the only path that resends an item whose provider acceptance is unknown. - */ - async retry( - agentId: string, - itemId: string, - expectedRevision: number, - ): Promise { - const result = await this.store.mutateWithExpectedRevision( - agentId, - expectedRevision, - (current) => ({ - ...current, - items: current.items.map((item) => - item.id === itemId && - (item.deliveryState === "failed" || item.deliveryState === "uncertain") - ? { ...item, deliveryState: "pending", attempts: 0, lastError: undefined } - : item, - ), - }), - ); - this.publish(result); - this.scheduleDrain(agentId); - return toAgentQueueSnapshot(result.queue); - } - - /** - * Attempts delivery of one item now instead of waiting for it to reach the - * head. The response carries the queue after the attempt, so the client can - * tell a delivered item from one the admission fence refused: a busy or - * archived agent, or an item that is not `pending`, leaves the queue - * unchanged. - */ - async sendNow( - agentId: string, - itemId: string, - expectedRevision: number, - ): Promise { - const current = await this.store.get(agentId); - if (current.revision !== expectedRevision) { - throw new QueueRevisionConflictError(expectedRevision, current.revision); - } - const item = current.items.find((candidate) => candidate.id === itemId); - if (!item || item.deliveryState !== "pending") { - return toAgentQueueSnapshot(current); - } - // Dispatch work is serialized per agent with the drain loop, so a send-now - // cannot interleave with an in-flight drain dispatch; awaiting the tail is - // what lets the response describe the queue after the attempt. - await this.runOnAgentTail(agentId, () => this.dispatchPendingItem(agentId, itemId)); - return this.list(agentId); - } - - /** - * Returns the stored image bytes for one queued item. Only the device that - * queued an image has a local copy, so any other device has to ask for it - * before it can pull the item back into its composer. - */ - async getItemImages(agentId: string, itemId: string): Promise { - const queue = await this.store.get(agentId); - const item = queue.items.find((candidate) => candidate.id === itemId); - if (!item) { - throw new Error(`Queued message ${itemId} is no longer queued`); - } - return item.images ?? []; - } - - async deleteForAgent(agentId: string): Promise { - await this.store.delete(agentId); - this.lastLifecycle.delete(agentId); - this.lastPermissionCount.delete(agentId); - } - - private assertImagePayloadWithinLimit(images: Array<{ data: string; mimeType: string }>): void { - const total = images.reduce((sum, image) => sum + image.data.length, 0); - if (total > MAX_ITEM_IMAGE_BASE64_CHARS) { - throw new QueueImagePayloadTooLargeError(MAX_ITEM_IMAGE_BASE64_CHARS); - } - } - - private async isArchived(agentId: string): Promise { - const record = await this.agentStorage.get(agentId); - return record?.archivedAt != null; - } - - private handleAgentState(agentId: string, lifecycle: AgentLifecycleStatus): void { - const previous = this.lastLifecycle.get(agentId); - this.lastLifecycle.set(agentId, lifecycle); - if (previous === "running" && lifecycle === "idle") { - this.scheduleDrain(agentId); - } - } - - /** - * Follow-ups wait behind a permission the agent is blocked on: answering it - * is the user's decision, and the queued prompt must never answer for them. - */ - private pendingPermissionCount( - agentId: string, - agent?: { pendingPermissions?: { size: number } }, - ): number { - if (agent) { - return ( - agent.pendingPermissions?.size ?? - this.agentManager.getPendingPermissions?.(agentId).length ?? - 0 - ); - } - return this.agentManager.getPendingPermissions?.(agentId).length ?? 0; - } - - private hasBlockingPermission(agentId: string): boolean { - const agent = this.agentManager.getAgent(agentId); - return this.pendingPermissionCount(agentId, agent ?? undefined) > 0; - } - - /** - * Drains run one at a time per agent. Chaining rather than dropping the request - * matters: a wakeup that arrives while a drain is in flight is the wakeup for - * the next item, and dropping it strands the rest of the queue. - */ - private scheduleDrain(agentId: string): void { - void this.runOnAgentTail(agentId, () => this.drain(agentId)).catch((error) => { - this.logger.warn({ err: error, agentId }, "Failed to drain queued agent message"); - }); - } - - /** Runs one work item on the per-agent tail, serialized with drains. */ - private async runOnAgentTail(agentId: string, work: () => Promise): Promise { - const previous = this.drainTails.get(agentId) ?? Promise.resolve(); - const next = previous.catch(() => undefined).then(work); - const tail = next.catch(() => undefined); - this.drainTails.set(agentId, tail as Promise); - try { - return await next; - } finally { - if (this.drainTails.get(agentId) === tail) { - this.drainTails.delete(agentId); - } - } - } - - /** Awaits in-flight drains. Tests and shutdown use it; nothing else should need it. */ - async flushDrains(): Promise { - while (this.drainTails.size > 0) { - await Promise.all(Array.from(this.drainTails.values())); - await Promise.resolve(); - } - } - - /** - * Bridge durable admission to the provider run observed by wait-for-finish. - * Waiters observe the dispatch; they can never cancel it — aborting ends the - * observation only, and an unresolved queued outcome returns an error instead - * of a false idle result. - */ - async waitForPendingDispatch(agentId: string, signal: AbortSignal): Promise { - const aborted = () => new DOMException("Queue dispatch wait aborted", "AbortError"); - while (true) { - if (signal.aborted) throw aborted(); - const pending = this.drainTails.get(agentId); - if (pending) { - await new Promise((resolve, reject) => { - const onAbort = () => { - signal.removeEventListener("abort", onAbort); - reject(aborted()); - }; - signal.addEventListener("abort", onAbort, { once: true }); - void pending.then(() => { - signal.removeEventListener("abort", onAbort); - resolve(); - return; - }); - }); - continue; - } - const queue = await this.store.get(agentId); - if (this.drainTails.has(agentId)) continue; - if (signal.aborted) throw aborted(); - const agent = this.agentManager.getAgent(agentId); - if ( - queue.items.length > 0 && - (!agent || agent.lifecycle === "idle" || agent.lifecycle === "closed") && - !this.agentManager.hasInFlightRun?.(agentId) && - !this.hasBlockingPermission(agentId) - ) { - // An uncertain or failed dispatch is still queued; it is not completion. - throw new Error( - "Queued input has not been confirmed submitted; inspect its delivery outcome", - ); - } - return; - } - } - - /** - * Sends the head of the queue when the agent is free. Serialized per agent so a - * burst of state events cannot send the same item twice. - * - * The queue is strictly FIFO: an item that is not `pending` (dispatching, - * uncertain, failed) holds the line — later items must not silently overtake - * the message they follow up on. - */ - private async drain(agentId: string): Promise { - if (await this.isArchived(agentId)) { - // Archived agents keep their queue but never auto-run. - return; - } - const agent = this.agentManager.getAgent(agentId); - if (!agent) { - return; - } - if (this.hasBlockingPermission(agentId)) { - return; - } - if (this.agentManager.hasInFlightRun?.(agentId)) { - return; - } - const queue = await this.store.get(agentId); - const head = queue.items[0]; - if (!head || head.deliveryState !== "pending") { - return; - } - if (head.intent === "queue" && agent.lifecycle !== "idle" && agent.lifecycle !== "closed") { - return; - } - await this.dispatchPendingItem(agentId, head.id); - } - - /** - * One delivery attempt for a `pending` item: claim, dispatch through the - * receipt service, then remove on success or record the outcome on failure. - * Callers reach this only through the per-agent work tail, so two attempts on - * one agent never overlap. - */ - private async dispatchPendingItem(agentId: string, itemId: string): Promise { - if (await this.isArchived(agentId)) { - return; - } - const agent = this.agentManager.getAgent(agentId); - if (!agent) { - return; - } - if (this.hasBlockingPermission(agentId)) { - return; - } - const queue = await this.store.get(agentId); - const item = queue.items.find((candidate) => candidate.id === itemId); - if (!item || item.deliveryState !== "pending") { - return; - } - // A queue-intent dispatch needs a free agent; this also refuses a send-now - // aimed at a busy agent instead of replacing the turn that won the race. - if (item.intent === "queue" && agent.lifecycle !== "idle" && agent.lifecycle !== "closed") { - return; - } - - // Claim before sending so a concurrent drain cannot send the item twice. - // The claim persists `dispatching`, so a crash here is a recoverable state, - // not a lost or duplicated prompt. - const claimed = await this.store.mutate(agentId, (current) => { - const target = current.items.find((candidate) => candidate.id === itemId); - if (!target || target.deliveryState !== "pending") { - return current; - } - return { - ...current, - items: current.items.map((candidate) => - candidate.id === itemId - ? { - ...candidate, - deliveryState: "dispatching", - attempts: candidate.attempts + 1, - attemptSeq: candidate.attemptSeq + 1, - } - : candidate, - ), - }; - }); - if (!claimed.changed) { - return; - } - this.publish(claimed); - const claimedItem = claimed.queue.items.find((candidate) => candidate.id === itemId); - if (!claimedItem) { - return; - } - - const prompt = buildAgentPrompt( - claimedItem.origin === "voice" ? wrapSpokenInput(claimedItem.text) : claimedItem.text, - claimedItem.images?.map(({ data, mimeType }) => ({ data, mimeType })), - claimedItem.attachments as AgentAttachment[] | undefined, - ); - - try { - if (claimedItem.intent === "steer_strict" && agent.lifecycle === "running") { - await this.deliverStrictSteer(agentId, claimedItem, prompt); - } else { - await this.deliverAsRun(agentId, claimedItem, prompt); - } - } catch (error) { - if (error instanceof QueueSteerRefusedError) { - // The provider would not absorb the prompt and the turn kept running: - // not a dispatch attempt. Un-claim without burning an attempt; the next - // wakeup tries again, and a later turn end delivers it as a new run. - const reverted = await this.store.mutate(agentId, (current) => ({ - ...current, - items: current.items.map((candidate) => - candidate.id === itemId && candidate.deliveryState === "dispatching" - ? { ...candidate, deliveryState: "pending", attempts: candidate.attempts - 1 } - : candidate, - ), - })); - this.publish(reverted); - return; - } - const message = error instanceof Error ? error.message : String(error); - this.logger.warn({ err: error, agentId, itemId }, "Queued agent message failed to send"); - const failed = await this.store.mutate(agentId, (current) => ({ - ...current, - items: current.items.map((candidate) => { - if (candidate.id !== itemId || candidate.deliveryState !== "dispatching") { - return candidate; - } - if (candidate.attempts >= DELIVERY_ATTEMPT_LIMIT) { - return { ...candidate, deliveryState: "failed", lastError: message }; - } - return { ...candidate, deliveryState: "pending", lastError: message }; - }), - })); - this.publish(failed); - return; - } - - const delivered = await this.store.mutate(agentId, (current) => { - if (!current.items.some((candidate) => candidate.id === itemId)) { - return current; - } - return { - ...current, - items: current.items.filter((candidate) => candidate.id !== itemId), - drainedIds: recordDrainedId(current.drainedIds, itemId), - }; - }); - this.publish(delivered); - } - - /** - * Normal run delivery for a free agent. A run that was reported started but - * never confirmed within the start budget is `uncertain`, not failed: the - * provider may still be working on the prompt. - */ - private async deliverAsRun( - agentId: string, - item: StoredQueuedMessage, - prompt: AgentPromptInput, - ): Promise { - const send = async () => { - const result = (await this.sendPrompt({ - agentId, - prompt, - messageId: item.id, - })) as { disposition?: string } | undefined; - if (result?.disposition === "turn_started") { - await waitForAgentRunStartWithTimeout(this.agentManager as AgentManager, agentId); - } - }; - if (this.receipts) { - await this.receipts.send({ - agentId, - messageId: attemptReceiptId(item.id, item.attemptSeq), - request: { prompt, intent: item.intent }, - ...(item.origin === "voice" - ? { - attachment: { - messageId: item.id, - attachmentId: item.id.split(":", 1)[0], - voiceOwner: item.voiceOwner, - createdAt: item.createdAt, - }, - } - : {}), - send, - }); - return; - } - await send(); - } - - /** - * Strict steering for a running agent: the active turn is asked to absorb the - * prompt through the shared admission, and refusal leaves the turn untouched. - * Steer attempts write no receipt — a refused attempt un-claims instead, so - * only the ambiguous crash window lands in recovery as `uncertain`. - */ - private async deliverStrictSteer( - agentId: string, - item: StoredQueuedMessage, - prompt: AgentPromptInput, - ): Promise { - const result = await this.agentManager.steerAgentRun(agentId, prompt, { - clientMessageId: item.id, - }); - if (result.status !== "accepted") { - throw new QueueSteerRefusedError(item.id); - } - } - - private publish(result: AgentQueueMutationResult): void { - if (!result.changed) { - return; - } - const snapshot = toAgentQueueSnapshot(result.queue); - for (const listener of this.listeners) { - try { - listener(snapshot); - } catch (error) { - this.logger.warn( - { err: error, agentId: result.queue.agentId }, - "Agent queue listener failed", - ); - } - } - } -} diff --git a/packages/server/src/server/agent-queue/store.test.ts b/packages/server/src/server/agent-queue/store.test.ts deleted file mode 100644 index 6bede3e54e9..00000000000 --- a/packages/server/src/server/agent-queue/store.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { mkdtemp, readFile, rm, stat } from "node:fs/promises"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; -import { expect, test } from "vitest"; - -import { AgentQueueStore, type AgentQueueJournalEntry, type StoredQueuedMessage } from "./store.js"; - -function storedItem(id: string, text = "keep this message"): StoredQueuedMessage { - return { - id, - text, - intent: "queue", - deliveryState: "pending", - attempts: 0, - attemptSeq: 0, - createdAt: new Date().toISOString(), - }; -} - -test("journals complete queue states before they can be replaced", async () => { - const dir = await mkdtemp(join(tmpdir(), "paseo-queue-journal-")); - const store = new AgentQueueStore(dir); - try { - await store.mutate("agent-1", (current) => ({ - ...current, - items: [storedItem("message-1")], - })); - await store.mutate("agent-1", (current) => ({ ...current, items: [] })); - - const journalPath = join(dir, "agent-1.journal.jsonl"); - const entries = (await readFile(journalPath, "utf8")) - .trim() - .split("\n") - .map((line) => JSON.parse(line) as AgentQueueJournalEntry); - expect(entries).toHaveLength(2); - expect(entries[0]?.after.items[0]?.text).toBe("keep this message"); - expect(entries[1]?.before.items[0]?.text).toBe("keep this message"); - expect(entries[1]?.after.items).toEqual([]); - expect((await store.get("agent-1")).items).toEqual([]); - // Windows reports synthesized POSIX mode bits; this assertion is meaningful - // only where the 0600 mode used when opening the journal is enforced. - if (process.platform !== "win32") { - expect((await stat(journalPath)).mode & 0o077).toBe(0); - } - } finally { - await rm(dir, { recursive: true, force: true }); - } -}); - -test("keeps a previous journal when the current journal reaches its size limit", async () => { - const dir = await mkdtemp(join(tmpdir(), "paseo-queue-journal-rotate-")); - const store = new AgentQueueStore(dir, 200); - try { - await store.mutate("agent-1", (current) => ({ - ...current, - items: [storedItem("message-1", "original")], - })); - await store.mutate("agent-1", (current) => ({ ...current, items: [] })); - const previous = await readFile(join(dir, "agent-1.journal.previous.jsonl"), "utf8"); - const current = await readFile(join(dir, "agent-1.journal.jsonl"), "utf8"); - expect(JSON.parse(previous.trim()).after.items[0].text).toBe("original"); - expect(JSON.parse(current.trim()).before.items[0].text).toBe("original"); - } finally { - await rm(dir, { recursive: true, force: true }); - } -}); - -test("journal entries describe image bytes instead of copying them", async () => { - const dir = await mkdtemp(join(tmpdir(), "paseo-queue-journal-image-")); - const store = new AgentQueueStore(dir); - try { - await store.mutate("agent-1", (current) => ({ - ...current, - items: [ - { - ...storedItem("message-1"), - images: [{ id: "img-1", mimeType: "image/png", fileName: null, data: "QUFBQQ==" }], - }, - ], - })); - - const journal = await readFile(join(dir, "agent-1.journal.jsonl"), "utf8"); - expect(journal).not.toContain("QUFBQQ=="); - // The queue file still holds the payload: delivery and get_item_images need it. - expect(await readFile(join(dir, "agent-1.json"), "utf8")).toContain("QUFBQQ=="); - } finally { - await rm(dir, { recursive: true, force: true }); - } -}); - -test("the queue file is written atomically with 0600 permissions", async () => { - const dir = await mkdtemp(join(tmpdir(), "paseo-queue-perms-")); - const store = new AgentQueueStore(dir); - try { - await store.mutate("agent-1", (current) => ({ - ...current, - items: [storedItem("message-1")], - })); - await store.mutate("agent-1", (current) => ({ ...current, items: [] })); - - // The empty rewrite must not reset permissions either. - if (process.platform !== "win32") { - expect((await stat(join(dir, "agent-1.json"))).mode & 0o077).toBe(0); - } - } finally { - await rm(dir, { recursive: true, force: true }); - } -}); - -test("a mutation naming a stale revision is rejected and changes nothing", async () => { - const dir = await mkdtemp(join(tmpdir(), "paseo-queue-revision-")); - const store = new AgentQueueStore(dir); - try { - const first = await store.mutate("agent-1", (current) => ({ - ...current, - items: [storedItem("message-1")], - })); - const staleRevision = first.queue.revision - 1; - - await expect( - store.mutateWithExpectedRevision("agent-1", staleRevision, (current) => ({ - ...current, - items: [storedItem("message-2")], - })), - ).rejects.toMatchObject({ - code: "queue_revision_conflict", - expectedRevision: staleRevision, - actualRevision: first.queue.revision, - }); - - // The rejected write must not land or bump the revision. - const after = await store.get("agent-1"); - expect(after.revision).toBe(first.queue.revision); - expect(after.items.map((item) => item.id)).toEqual(["message-1"]); - } finally { - await rm(dir, { recursive: true, force: true }); - } -}); - -test("a mutation naming the current revision applies and bumps the revision", async () => { - const dir = await mkdtemp(join(tmpdir(), "paseo-queue-revision-ok-")); - const store = new AgentQueueStore(dir); - try { - const first = await store.mutate("agent-1", (current) => ({ - ...current, - items: [storedItem("message-1")], - })); - - const second = await store.mutateWithExpectedRevision( - "agent-1", - first.queue.revision, - (current) => ({ ...current, items: [] }), - ); - - expect(second.changed).toBe(true); - expect(second.queue.revision).toBe(first.queue.revision + 1); - expect(second.queue.items).toEqual([]); - } finally { - await rm(dir, { recursive: true, force: true }); - } -}); - -test("ids lists the agents with persisted queues and delete removes the journal", async () => { - const dir = await mkdtemp(join(tmpdir(), "paseo-queue-ids-")); - const store = new AgentQueueStore(dir); - try { - await store.mutate("agent-1", (current) => ({ ...current, items: [storedItem("m-1")] })); - await store.mutate("agent-2", (current) => ({ ...current, items: [storedItem("m-2")] })); - - expect(await store.ids()).toEqual(["agent-1", "agent-2"]); - - await store.delete("agent-1"); - expect(await store.ids()).toEqual(["agent-2"]); - await expect(stat(join(dir, "agent-1.journal.jsonl"))).rejects.toMatchObject({ - code: "ENOENT", - }); - } finally { - await rm(dir, { recursive: true, force: true }); - } -}); - -test("an unknown agent parses as an empty queue at revision 0", async () => { - const dir = await mkdtemp(join(tmpdir(), "paseo-queue-empty-")); - const store = new AgentQueueStore(dir); - try { - expect(await store.get("agent-unknown")).toEqual({ - agentId: "agent-unknown", - revision: 0, - items: [], - }); - } finally { - await rm(dir, { recursive: true, force: true }); - } -}); diff --git a/packages/server/src/server/agent-queue/store.ts b/packages/server/src/server/agent-queue/store.ts deleted file mode 100644 index a32667166c0..00000000000 --- a/packages/server/src/server/agent-queue/store.ts +++ /dev/null @@ -1,341 +0,0 @@ -import { mkdir, open, readdir, readFile, rename, rm, stat } from "node:fs/promises"; -import { join } from "node:path"; -import { z } from "zod"; - -import { - AgentAttachmentWireSchema, - QueuedAgentDeliveryIntentSchema, - QueuedAgentMessageDeliveryStateSchema, - QueuedComposerAttachmentSchema, - type AgentQueueSnapshot, -} from "@getpaseo/protocol/messages"; -import { writeJsonFileAtomic } from "../atomic-file.js"; - -/** - * Image bytes are held here and never broadcast. See docs/queue-mirroring.md for - * why a queued image cannot mirror by reference. - */ -const StoredQueuedImageSchema = z.object({ - id: z.string(), - mimeType: z.string(), - fileName: z.string().nullable().optional(), - data: z.string(), -}); - -const StoredQueuedMessageSchema = z.object({ - id: z.string(), - text: z.string(), - /** Set when the item was admitted as spoken input; drives wrapping and receipt reads. */ - origin: z.literal("voice").optional(), - /** The principal/client pair that spoke the item; only it may read the receipts. */ - voiceOwner: z.string().optional(), - // TM-02 adaptation: delivery bookkeeping is part of the durable record, so a - // restart can tell a never-dispatched item from an ambiguous one. The source - // store did not track it; every item this daemon writes carries all of these. - // `attempts` is the user-visible streak and resets on retry; `attemptSeq` - // never resets, so each dispatch gets its own receipt key and a retry can - // never collide with the previous attempt's receipt. - intent: QueuedAgentDeliveryIntentSchema, - deliveryState: QueuedAgentMessageDeliveryStateSchema, - attempts: z.number().int().nonnegative(), - attemptSeq: z.number().int().nonnegative(), - lastError: z.string().nullable().optional(), - attachments: z.array(AgentAttachmentWireSchema).optional(), - composerAttachments: z.array(QueuedComposerAttachmentSchema).optional(), - images: z.array(StoredQueuedImageSchema).optional(), - createdAt: z.string(), -}); - -const StoredAgentQueueSchema = z.object({ - agentId: z.string(), - revision: z.number().int().nonnegative(), - items: z.array(StoredQueuedMessageSchema), - // Ids of items that have already been drained. An enqueue retry (same id) that - // arrives after its item was delivered must be a no-op, not a resend. - drainedIds: z.array(z.string()).optional(), -}); - -export type StoredQueuedImage = z.infer; -export type StoredQueuedMessage = z.infer; -export type StoredAgentQueue = z.infer; - -export function emptyAgentQueue(agentId: string): StoredAgentQueue { - return { agentId, revision: 0, items: [] }; -} - -/** - * The window only has to outlast a client's retry horizon, not history: a - * retry always targets a recent item, so a small bound is plenty and keeps the - * queue file from growing forever. - */ -export const MAX_REMEMBERED_DRAINED_IDS = 100; - -export function recordDrainedId(ids: readonly string[] | undefined, id: string): string[] { - const next = [...(ids ?? []).filter((existing) => existing !== id), id]; - return next.slice(-MAX_REMEMBERED_DRAINED_IDS); -} - -/** - * Thrown by {@link AgentQueueStore.mutateWithExpectedRevision} when a client - * mutation names a revision it has not seen. The queue is left untouched so a - * stale device can never overwrite another device's edit. - */ -export class QueueRevisionConflictError extends Error { - readonly code = "queue_revision_conflict"; - - constructor( - readonly expectedRevision: number, - readonly actualRevision: number, - ) { - super(`Queue revision conflict: expected ${expectedRevision}, current ${actualRevision}`); - this.name = "QueueRevisionConflictError"; - } -} - -/** Projects the stored queue onto the wire, replacing image bytes with descriptors. */ -export function toAgentQueueSnapshot(queue: StoredAgentQueue): AgentQueueSnapshot { - return { - agentId: queue.agentId, - revision: queue.revision, - items: queue.items.map((item) => ({ - id: item.id, - text: item.text, - ...(item.origin ? { origin: item.origin } : {}), - intent: item.intent, - deliveryState: item.deliveryState, - attempts: item.attempts, - ...(item.lastError !== undefined ? { lastError: item.lastError } : {}), - createdAt: item.createdAt, - ...(item.attachments?.length ? { attachments: item.attachments } : {}), - ...(item.composerAttachments?.length - ? { composerAttachments: item.composerAttachments } - : {}), - ...(item.images?.length - ? { - images: item.images.map((image) => ({ - id: image.id, - mimeType: image.mimeType, - fileName: image.fileName ?? null, - byteSize: approximateBase64ByteSize(image.data), - })), - } - : {}), - })), - }; -} - -function approximateBase64ByteSize(data: string): number { - let padding = 0; - if (data.endsWith("==")) { - padding = 2; - } else if (data.endsWith("=")) { - padding = 1; - } - return Math.max(0, Math.floor((data.length * 3) / 4) - padding); -} - -type QueueMutator = (current: StoredAgentQueue) => StoredAgentQueue | Promise; - -export interface AgentQueueMutationResult { - queue: StoredAgentQueue; - changed: boolean; -} - -/** Each record retains both sides of a mutation for manual recovery. */ -export interface AgentQueueJournalEntry { - recordedAt: string; - before: StoredAgentQueue; - after: StoredAgentQueue; -} - -/** - * Journal entries describe images instead of copying their bytes: the queue - * file already holds the payload, and the journal is the recovery aid, not a - * second copy of user data. - */ -function elideJournalImageBytes(queue: StoredAgentQueue): StoredAgentQueue { - return { - ...queue, - items: queue.items.map((item) => - item.images?.length - ? { - ...item, - images: item.images.map(({ data, ...descriptor }) => ({ - ...descriptor, - data: ``, - })), - } - : item, - ), - }; -} - -export class AgentQueueStore { - private readonly mutations = new Map>(); - - constructor( - private readonly dir: string, - /** - * Appends stop rotating once the current journal passes this size; the - * previous generation is kept so a rotation itself cannot lose both copies. - * Queue payloads can be large, so the default stays well above any honest - * queue while still bounding disk use. - */ - private readonly maxJournalBytes = 64 * 1024 * 1024, - ) {} - - /** Every agent id that has a persisted queue file. Startup recovery walks it. */ - async ids(): Promise { - await this.ensureDir(); - const entries = await readdir(this.dir); - return entries - .filter((name) => name.endsWith(".json")) - .map((name) => name.slice(0, -".json".length)); - } - - async get(agentId: string): Promise { - await this.ensureDir(); - try { - const content = await readFile(this.filePath(agentId), "utf-8"); - return StoredAgentQueueSchema.parse(JSON.parse(content)); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - return emptyAgentQueue(agentId); - } - throw error; - } - } - - /** - * Read-modify-write under a per-agent lock. A mutator that returns its input - * unchanged does not bump `revision` and reports `changed: false`, so a no-op - * never triggers a broadcast. - * - * The record survives an empty queue because `revision` has to stay monotonic: - * deleting the file would restart it at 0 and make clients drop later updates - * as stale. - */ - async mutate(agentId: string, mutate: QueueMutator): Promise { - return this.serialize(agentId, async () => { - const current = await this.get(agentId); - // An async mutator (receipt reads during admission) still runs under the - // per-agent lock, so its decision cannot race a concurrent mutation. - return this.apply(agentId, current, await mutate(current)); - }); - } - - /** - * {@link mutate} guarded by the revision the caller last saw. Used by every - * client-facing mutation; internal queue mechanics (claim, recovery) use the - * unguarded form because they act on the state they just read. - */ - async mutateWithExpectedRevision( - agentId: string, - expectedRevision: number, - mutate: QueueMutator, - ): Promise { - return this.serialize(agentId, async () => { - const current = await this.get(agentId); - if (current.revision !== expectedRevision) { - throw new QueueRevisionConflictError(expectedRevision, current.revision); - } - return this.apply(agentId, current, await mutate(current)); - }); - } - - async delete(agentId: string): Promise { - await this.serialize(agentId, async () => { - await this.ensureDir(); - await rm(this.filePath(agentId), { force: true }); - await rm(this.journalPath(agentId), { force: true }); - await rm(this.previousJournalPath(agentId), { force: true }); - }); - } - - private async apply( - agentId: string, - current: StoredAgentQueue, - next: StoredAgentQueue, - ): Promise { - if (next === current) { - return { queue: current, changed: false }; - } - const updated = StoredAgentQueueSchema.parse({ - ...next, - agentId, - revision: current.revision + 1, - }); - // Record the recoverable state before replacing the queue file. If the - // journal cannot be written, leave the existing queue untouched. - await this.appendJournal({ - recordedAt: new Date().toISOString(), - before: current, - after: updated, - }); - await this.write(updated); - return { queue: updated, changed: true }; - } - - private filePath(agentId: string): string { - return join(this.dir, `${agentId}.json`); - } - - private journalPath(agentId: string): string { - return join(this.dir, `${agentId}.journal.jsonl`); - } - - private previousJournalPath(agentId: string): string { - return join(this.dir, `${agentId}.journal.previous.jsonl`); - } - - private async ensureDir(): Promise { - await mkdir(this.dir, { recursive: true }); - } - - private async write(queue: StoredAgentQueue): Promise { - await this.ensureDir(); - // Queue text, attachments and image payloads are user data; they get the - // same 0600 treatment as the daemon keypair and receipts. - await writeJsonFileAtomic(this.filePath(queue.agentId), queue, { mode: 0o600 }); - } - - private async appendJournal(entry: AgentQueueJournalEntry): Promise { - const journalPath = this.journalPath(entry.after.agentId); - const line = `${JSON.stringify({ - recordedAt: entry.recordedAt, - before: elideJournalImageBytes(entry.before), - after: elideJournalImageBytes(entry.after), - })}\n`; - let size = 0; - try { - size = (await stat(journalPath)).size; - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; - } - if (size > 0 && size + Buffer.byteLength(line) > this.maxJournalBytes) { - const previousPath = this.previousJournalPath(entry.after.agentId); - await rm(previousPath, { force: true }); - await rename(journalPath, previousPath); - } - const file = await open(journalPath, "a", 0o600); - try { - await file.writeFile(line); - await file.sync(); - } finally { - await file.close(); - } - } - - private async serialize(agentId: string, mutation: () => Promise): Promise { - const previous = this.mutations.get(agentId) ?? Promise.resolve(); - const next = previous.catch(() => undefined).then(mutation); - this.mutations.set(agentId, next); - try { - return await next; - } finally { - if (this.mutations.get(agentId) === next) { - this.mutations.delete(agentId); - } - } - } -} diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index a46b82ff896..ce23223b29d 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -8,14 +8,6 @@ import type { PluginLifecycle } from "../plugins/lifecycle/index.js"; import { describeHookAgent, publishAgentStream } from "../plugins/lifecycle/index.js"; import { applyRecordPatch } from "../record-patch.js"; import type { PluginSessionOpenRequest } from "@getpaseo/plugin/server"; -import type { CompanionEntry } from "@getpaseo/protocol/companion-stream"; -import { - appendManualCompanionEntry, - CompanionStreamCollector, - restoreCompanionEntries, -} from "./companion-stream.js"; -import { AgentArtifactCollector } from "./artifacts/collector.js"; -import type { AgentArtifact } from "@getpaseo/protocol/agent-types"; import { randomUUID } from "node:crypto"; import { basename, resolve } from "node:path"; import { stat } from "node:fs/promises"; @@ -119,8 +111,7 @@ import { } from "./runtime-mcp-config.js"; import { resolveCreateAgentTitles } from "./create-agent-title.js"; import type { PaseoToolCatalogFactory } from "./tools/types.js"; -import { isPaseoToolPolicyEnabled, isPaseoToolEnabled } from "./paseo-tool-policy.js"; -import { stripVoiceModeSystemPrompt, VOICE_AVAILABLE_INSTRUCTION } from "../voice-config.js"; +import { isPaseoToolPolicyEnabled } from "./paseo-tool-policy.js"; import { ProviderSubagentStore, type ProviderSubagentDescriptor, @@ -171,16 +162,6 @@ export class PeerTurnActiveError extends Error { } } -/** The run reservation rejected a competing prompt before the provider saw it. */ -export class AgentRunBusyError extends Error { - readonly code = "AGENT_RUN_BUSY"; - - constructor(agentId: string) { - super(`Agent ${agentId} already has an active run`); - this.name = "AgentRunBusyError"; - } -} - export class AgentRunCancellationError extends Error { constructor(agentId: string, action: "reload" | "replace" | "rewind" | "stop") { super( @@ -399,8 +380,6 @@ export interface CreateAgentOptions { owner?: AgentOwner; /** Background agents stay out of discovery, tabs, tracks and attention. Fixed at creation. */ background?: boolean; - artifacts?: AgentArtifact[]; - companionEntries?: CompanionEntry[]; } export interface AgentManagerOptions { @@ -488,10 +467,6 @@ function resolveInitialAttention(input: AttentionState | undefined): AttentionSt }; } -function resolveInitialArtifacts(artifacts: AgentArtifact[] | undefined): AgentArtifact[] { - return artifacts ? [...artifacts] : []; -} - interface StreamEventFlags { shouldDispatchEvent: boolean; shouldNotifyWaiters: boolean; @@ -561,8 +536,6 @@ interface ManagedAgentBase { labels: Record; /** Plugin-owned data. Paseo persists and forwards it and never reads a key. */ metadata: AgentMetadata; - artifacts: AgentArtifact[]; - companionEntries?: CompanionEntry[]; } type ManagedAgentWithSession = ManagedAgentBase & { @@ -671,7 +644,6 @@ interface AgentMetadataPatch { title?: string; labels?: AgentLabelPatch; metadata?: Record; - companionEntries?: CompanionEntry[]; } const SYSTEM_ERROR_PREFIX = "[System Error]"; @@ -931,8 +903,6 @@ export class AgentManager { private readonly rescueTimeouts: Required; private readonly beforeSteerUnavailableFallback?: AgentManagerOptions["beforeSteerUnavailableFallback"]; private acceptingAgentRegistrations = true; - private readonly artifactCollector = new AgentArtifactCollector(); - private readonly companionCollector = new CompanionStreamCollector(); constructor(options: AgentManagerOptions) { this.pluginLifecycle = options.pluginLifecycle; @@ -1708,8 +1678,6 @@ export class AgentManager { owner: record.owner, background: record.background, env: record.launchEnv, - artifacts: record.artifacts, - companionEntries: record.companionEntries, }); }), ); @@ -1782,8 +1750,6 @@ export class AgentManager { owner: options.owner, background: options.background, launchEnv: options.env ? { ...options.env } : undefined, - artifacts: options.artifacts, - companionEntries: options.companionEntries, historyPrimed: true, }); if (!agent.internal) { @@ -1817,8 +1783,6 @@ export class AgentManager { workspaceId?: string; owner?: AgentOwner; background?: boolean; - artifacts?: AgentArtifact[]; - companionEntries?: CompanionEntry[]; attention?: AttentionState; }, resumeOptions?: AgentResumeSessionOptions, @@ -1853,8 +1817,6 @@ export class AgentManager { workspaceId?: string; owner?: AgentOwner; background?: boolean; - artifacts?: AgentArtifact[]; - companionEntries?: CompanionEntry[]; attention?: AttentionState; }, resumeOptions?: AgentResumeSessionOptions, @@ -1937,8 +1899,6 @@ export class AgentManager { metadata: record.metadata, background: record.background, owner: record.owner, - artifacts: record.artifacts, - companionEntries: record.companionEntries, } : {}), workspaceId, @@ -2165,8 +2125,6 @@ export class AgentManager { historyPrimed: rehydrateFromDisk ? false : preservedHistoryPrimed, lastUsage: preservedLastUsage, lastError: preservedLastError, - artifacts: existing.artifacts, - companionEntries: existing.companionEntries, attention: preservedAttention, restoring: true, }); @@ -2674,8 +2632,6 @@ export class AgentManager { background: record.background, labels: record.labels, metadata: record.metadata, - artifacts: record.artifacts ?? [], - companionEntries: restoreCompanionEntries(record), }, }); } @@ -2966,82 +2922,12 @@ export class AgentManager { ...(patch.title ? { title: patch.title } : {}), ...(patch.labels ? { labels: applyRecordPatch(record.labels, patch.labels) } : {}), ...(patch.metadata ? { metadata: applyRecordPatch(record.metadata, patch.metadata) } : {}), - ...(patch.companionEntries ? { companionEntries: patch.companionEntries } : {}), updatedAt: this.nextStoredUpdatedAt(record), }; await registry.upsert(nextRecord); return nextRecord; } - async updateCompanionEntry(input: { - agentId: string; - entryId?: string; - action: "update_status" | "add_pin" | "remove_pin" | "add_q_and_a"; - status?: "open" | "reviewed" | "done"; - text?: string; - answerText?: string; - sourceId?: string; - }): Promise { - const liveAgent = this.getAgent(input.agentId); - let entries = liveAgent?.companionEntries; - if (!liveAgent) { - if (!this.registry) return; - const stored = await this.registry.get(input.agentId); - if (!stored) return; - entries = restoreCompanionEntries({ companionEntries: stored.companionEntries }); - } else { - entries = entries ?? []; - } - - if (!entries) return; - let next = [...entries]; - - if (input.action === "update_status" && input.entryId && input.status) { - next = next.map((e) => - e.id === input.entryId && (e.kind === "question" || e.kind === "feature_request") - ? { ...e, status: input.status as "open" | "reviewed" | "done" } - : e, - ); - } else if (input.action === "add_pin") { - const pinId = `pin:${Date.now()}:${Math.random().toString(36).slice(2)}`; - const appended = appendManualCompanionEntry(next, { - id: pinId, - kind: "pin", - timestamp: new Date().toISOString(), - text: input.text ?? "", - truncated: false, - sourceId: input.sourceId, - }); - if (appended.error) { - throw new Error(appended.error); - } - next = appended.entries; - } else if (input.action === "remove_pin" && input.entryId) { - next = next.filter((e) => !(e.id === input.entryId && e.kind === "pin")); - } else if (input.action === "add_q_and_a") { - const qnaId = `qa:${Date.now()}:${Math.random().toString(36).slice(2)}`; - const appended = appendManualCompanionEntry(next, { - id: qnaId, - kind: "q_and_a", - timestamp: new Date().toISOString(), - text: input.text ?? "", - answer: input.answerText, - truncated: false, - }); - if (appended.error) { - throw new Error(appended.error); - } - next = appended.entries; - } - - if (liveAgent) { - liveAgent.companionEntries = next; - this.emitState(liveAgent, { persist: true }); - } else { - await this.writeStoredMetadata(input.agentId, { companionEntries: next }); - } - } - async detachAgent(agentId: string): Promise<{ record: StoredAgentRecord; live: boolean; @@ -3426,9 +3312,6 @@ export class AgentManager { item = limitAgentTimelineItemContent(item); this.touchUpdatedAt(agent); const row = this.recordTimeline(agentId, item); - if (item.type === "user_message") { - this.collectCompanionEvent(agent, { type: "timeline", item, provider: agent.provider }); - } this.dispatchStream( agentId, { @@ -3504,7 +3387,6 @@ export class AgentManager { this.runs.settleForegroundRun(agentId, pendingRun.token); throw error; } - this.artifactCollector.cancelTurn(agent.id); agent.pendingReplacement = false; const errorMsg = error instanceof Error ? error.message : "Failed to start turn"; this.runs.settleForegroundStart(pendingRun, { status: "failed", error: errorMsg }); @@ -3598,11 +3480,7 @@ export class AgentManager { }, "agent.manager.stream.request", ); - if ( - existingAgent.activeForegroundTurnId || - this.runs.hasRun(agentId) || - (options?.requireNoPendingPermissions && existingAgent.pendingPermissions.size > 0) - ) { + if (existingAgent.activeForegroundTurnId || this.runs.hasRun(agentId)) { this.logger.trace( { agentId, @@ -3614,7 +3492,7 @@ export class AgentManager { }, "agent.manager.stream.reject", ); - throw new AgentRunBusyError(agentId); + throw new Error(`Agent ${agentId} already has an active run`); } const agent = existingAgent; @@ -3626,7 +3504,6 @@ export class AgentManager { const streamForwarder = async function* streamForwarder(this: AgentManager) { let turnId: string; let turnStream: ReturnType | null = null; - this.artifactCollector.beginTurn(agent.id, agent.cwd); turnId = await this.startPendingForegroundTurn({ agent, agentId, @@ -4672,8 +4549,6 @@ export class AgentManager { owner?: AgentOwner; background?: boolean; launchEnv?: Record; - artifacts?: AgentArtifact[]; - companionEntries?: CompanionEntry[]; }, ): Promise { let registered = false; @@ -4861,8 +4736,6 @@ export class AgentManager { attention?: AttentionState; persistence?: AgentPersistenceHandle; labels?: Record; - artifacts?: AgentArtifact[]; - companionEntries?: CompanionEntry[]; } | undefined; }) { @@ -4879,8 +4752,6 @@ export class AgentManager { attention: resolveInitialAttention(options?.attention), internal: config.internal ?? false, labels: options?.labels ?? {}, - artifacts: resolveInitialArtifacts(options?.artifacts), - companionEntries: restoreCompanionEntries(options), }; } @@ -4907,8 +4778,6 @@ export class AgentManager { workspaceId?: string; owner?: AgentOwner; launchEnv?: Record; - artifacts?: AgentArtifact[]; - companionEntries?: CompanionEntry[]; } | undefined; }): ActiveManagedAgent { @@ -4964,7 +4833,6 @@ export class AgentManager { agent: LiveManagedAgent, cancelReason: string, ): ManagedAgentClosed { - this.artifactCollector.cancelTurn(agent.id); this.agentStreamCoalescer.flushAndDiscard(agent.id); this.agents.delete(agent.id); this.previousStatuses.delete(agent.id); @@ -4997,8 +4865,6 @@ export class AgentManager { } private discardRetainedAgentState(agentId: string): void { - this.artifactCollector.cancelTurn(agentId); - this.companionCollector.clear(agentId); this.timelineStore.delete(agentId); this.paseoToolPolicies.delete(agentId); for (const event of this.sideConversations.deleteParent(agentId)) { @@ -5142,13 +5008,6 @@ export class AgentManager { const shouldNotifyWaiters = await this.handleStreamEvent(agent, event); - if (isTurnTerminalEvent(event)) { - // Artifact collection walks the working directory. Never hold the turn's waiters - // on it: upstream settles and notifies at the terminal event, and a steer or - // replace admitted during the walk must see the run already settled. - void this.collectArtifactsForTurn(agent); - } - if (!shouldNotifyWaiters) { return; } @@ -5534,10 +5393,6 @@ export class AgentManager { await dispatchPromise; } - if (!options?.fromHistory && event.type !== "timeline") { - this.collectCompanionEvent(agent, event); - } - if (!options?.fromHistory) { if (isTurnTerminalEvent(event)) { this.runs.settleTerminalRun(agent.id, eventTurnId); @@ -5923,81 +5778,6 @@ export class AgentManager { } } - private collectCompanionEvent(agent: ManagedAgent, event: AgentStreamEvent): void { - const previous = agent.companionEntries ?? []; - const next = this.companionCollector.observe( - agent.id, - previous, - event, - new Date().toISOString(), - ); - if (next !== previous) { - agent.companionEntries = next; - this.emitState(agent); - } - } - - /** - * Backfills an agent's artifact feed from what is already on disk. - * - * Turn-scoped collection cannot see work an agent did before this feature - * existed, so without this every pre-existing agent shows an empty feed - * forever. Explicit rather than automatic: a full walk of a large working - * directory is not something to do on every agent load. - */ - async scanAgentArtifacts( - agentId: string, - options?: { limit?: number }, - ): Promise<{ addedOrUpdated: number; total: number }> { - const agent = this.agents.get(agentId); - if (!agent) { - throw new Error(`Agent ${agentId} not found`); - } - const collection = await this.artifactCollector.scanExisting( - agent.cwd, - agent.artifacts, - options?.limit !== undefined ? { limit: options.limit } : {}, - ); - if (!collection) { - return { addedOrUpdated: 0, total: agent.artifacts?.length ?? 0 }; - } - agent.artifacts = collection.artifacts; - this.touchUpdatedAt(agent); - this.emitState(agent); - this.logger.info( - { - agentId, - cwd: agent.cwd, - addedOrUpdated: collection.addedOrUpdated, - artifactCount: collection.artifacts.length, - }, - "Backfilled agent artifacts", - ); - return { addedOrUpdated: collection.addedOrUpdated, total: collection.artifacts.length }; - } - - private async collectArtifactsForTurn(agent: ActiveManagedAgent): Promise { - try { - const collection = await this.artifactCollector.finishTurn(agent.id, agent.artifacts); - if (!collection) { - return; - } - agent.artifacts = collection.artifacts; - this.touchUpdatedAt(agent); - this.emitState(agent); - this.logger.info( - { - agentId: agent.id, - addedOrUpdated: collection.addedOrUpdated, - artifactCount: collection.artifacts.length, - }, - "Collected agent artifacts", - ); - } catch (error) { - this.logger.warn({ err: error, agentId: agent.id }, "Failed to collect agent artifacts"); - } - } - private onStreamTurnStarted(params: { agent: ActiveManagedAgent; eventTurnId: string | undefined; @@ -6005,7 +5785,6 @@ export class AgentManager { flags: StreamEventFlags; }): void { const { agent, eventTurnId, isForegroundEvent, flags } = params; - this.artifactCollector.beginTurn(agent.id, agent.cwd); this.logger.trace( { agentId: agent.id, @@ -6093,9 +5872,6 @@ export class AgentManager { turnId?: string, options?: { providerMessageId?: string }, ): AgentStreamEvent { - if (item.type === "tool_call") { - this.artifactCollector.observeToolCall(agentId, item); - } const row = this.recordTimeline(agentId, item, { ...options, turnId }); const event: AgentStreamEvent = { type: "timeline", @@ -6103,8 +5879,6 @@ export class AgentManager { provider, ...(turnId !== undefined ? { turnId } : {}), }; - const timelineAgent = this.agents.get(agentId); - if (timelineAgent) this.collectCompanionEvent(timelineAgent, event); this.dispatchStream(agentId, event, { seq: row.seq, epoch: this.timelineStore.getEpoch(agentId), @@ -6725,11 +6499,6 @@ export class AgentManager { purpose: options.purpose, resolveDefaultModel: options.resolveDefaultModel, }); - // Older voice toggles persisted a speech-only prompt block. Remove it only - // when a provider is naturally created or resumed. - const systemPrompt = stripVoiceModeSystemPrompt(storedConfig.systemPrompt); - if (systemPrompt) storedConfig.systemPrompt = systemPrompt; - else delete storedConfig.systemPrompt; const paseoToolPolicy = this.paseoToolsEnabled ? this.resolvePaseoToolPolicy(storedConfig.provider) : { enabled: false }; @@ -6744,22 +6513,6 @@ export class AgentManager { mcpAuthToken: this.mcpAuthToken, }), ); - const capabilities = this.clients.get(storedConfig.provider)?.capabilities; - const hasSpeakTransport = - (capabilities?.supportsNativePaseoTools && !!this.paseoToolCatalogFactory) || - (capabilities?.supportsMcpServers && !!this.mcpBaseUrl); - if ( - hasSpeakTransport && - this.paseoToolsEnabled && - isPaseoToolEnabled(paseoToolPolicy, "speak") - ) { - launchConfig.daemonAppendSystemPrompt = [ - launchConfig.daemonAppendSystemPrompt, - VOICE_AVAILABLE_INSTRUCTION, - ] - .filter(Boolean) - .join("\n\n"); - } return { storedConfig, launchConfig, paseoToolPolicy }; } diff --git a/packages/server/src/server/agent/agent-projections.test.ts b/packages/server/src/server/agent/agent-projections.test.ts index 49fa372c9e4..745ab449ebe 100644 --- a/packages/server/src/server/agent/agent-projections.test.ts +++ b/packages/server/src/server/agent/agent-projections.test.ts @@ -452,27 +452,6 @@ describe("toAgentPayload", () => { unrelated: { retained: true }, }, }, - artifacts: [ - { - path: "/tmp/report.md", - name: "report.md", - kind: "markdown", - mimeType: "text/markdown", - size: 12, - createdAt: "2025-01-01T00:00:00.000Z", - updatedAt: "2025-01-01T00:00:00.000Z", - }, - ], - companionEntries: [ - { - id: "question:retained", - kind: "question", - text: "Keep this question?", - status: "open", - timestamp: "2025-01-01T00:00:00.000Z", - truncated: false, - }, - ], }); const originalPersistence = structuredClone(agent.persistence); const record = toStoredAgentRecord(agent); @@ -496,12 +475,6 @@ describe("toAgentPayload", () => { }, ]); expect(storedPayload.pendingPermissions).toEqual([]); - expect(payload.artifacts).toEqual(agent.artifacts); - expect(storedPayload.artifacts).toEqual(agent.artifacts); - expect(payload.companionEntries).toEqual(agent.companionEntries); - expect(storedPayload.companionEntries).toEqual(agent.companionEntries); - expect(record.artifacts).toEqual(agent.artifacts); - expect(record.companionEntries).toEqual(agent.companionEntries); expect(agent.persistence).toEqual(originalPersistence); expect(record).toEqual(originalRecord); payload.persistence!.metadata!.conversationId = "wire-mutation"; diff --git a/packages/server/src/server/agent/agent-projections.ts b/packages/server/src/server/agent/agent-projections.ts index 0f2a12ab555..5db6bcc31e1 100644 --- a/packages/server/src/server/agent/agent-projections.ts +++ b/packages/server/src/server/agent/agent-projections.ts @@ -27,7 +27,6 @@ import { resolveStoredAgentUpdatedAt, toAgentPersistenceHandle, } from "../persistence-hooks.js"; -import { restoreCompanionEntries } from "./companion-stream.js"; export type { ManagedAgent }; interface ProjectionOptions { @@ -112,8 +111,6 @@ export function toStoredAgentRecord( internal: options?.internal, ...(agent.background ? { background: true } : {}), owner: agent.owner, - artifacts: agent.artifacts ?? [], - companionEntries: agent.companionEntries ?? [], } satisfies StoredAgentRecord; } @@ -169,8 +166,6 @@ export function toAgentPayload( metadata: agent.metadata, archivedAt: options?.archivedAt ?? null, ...visibilityFlags(agent), - artifacts: agent.artifacts ?? [], - companionEntries: agent.companionEntries ?? [], }; const usageScopeKey = projectUsageScopeKey(agent); @@ -265,16 +260,6 @@ function buildStoredOptionControls( }; } -/** Stream facts a stored record carries: artifacts always, companion entries when present. */ -function buildStoredStreamFacts( - record: StoredAgentRecord, -): Pick { - return { - artifacts: record.artifacts ?? [], - companionEntries: restoreCompanionEntries(record), - }; -} - export function buildStoredAgentPayload( record: StoredAgentRecord, validProviders: Iterable, @@ -334,7 +319,6 @@ export function buildStoredAgentPayload( labels: normalizeLabels(record.labels), metadata: record.metadata, ...(typeof record.lastError === "string" ? { lastError: record.lastError } : {}), - ...buildStoredStreamFacts(record), ...(providerAvailable ? {} : { providerUnavailable: true }), }; } diff --git a/packages/server/src/server/agent/agent-prompt.test.ts b/packages/server/src/server/agent/agent-prompt.test.ts index 112060e2b97..734921dfb7c 100644 --- a/packages/server/src/server/agent/agent-prompt.test.ts +++ b/packages/server/src/server/agent/agent-prompt.test.ts @@ -16,11 +16,7 @@ import { join } from "node:path"; import { createTestLogger } from "../../test-utils/test-logger.js"; import { AgentManager } from "./agent-manager.js"; import { AgentStorage } from "./agent-storage.js"; -import { - sendPromptToAgent, - setupFinishNotification, - waitForAgentRunStartWithTimeout, -} from "./agent-prompt.js"; +import { setupFinishNotification, waitForAgentRunStartWithTimeout } from "./agent-prompt.js"; import type { AgentManagerEvent, ManagedAgent } from "./agent-manager.js"; import type { AgentClient, @@ -973,96 +969,3 @@ test("schedule trigger identity survives the provider assigning a message ID", ( projectAgentMessages({ type: "user_message", text, messageId: "provider-message" }), ); }); - -test("queue acceptance waits on its own reserved provider run", async () => { - const workdir = mkdtempSync(join(tmpdir(), "queued-run-acceptance-")); - const client = new SlowStartAgentClient(null); - const manager = new AgentManager({ clients: { codex: client }, logger: createTestLogger() }); - const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { - workspaceId: undefined, - }); - try { - // The queue's delivery: dispatch without replacement, then wait for the - // reserved run to actually start before the receipt completes. - const dispatch = sendPromptToAgent({ - agentManager: manager, - agentStorage: { get: async () => undefined } as unknown as AgentStorage, - agentId: agent.id, - prompt: "one", - replaceRunning: false, - logger: createTestLogger(), - }).then(async (result) => { - expect(result.disposition).toBe("turn_started"); - await waitForAgentRunStartWithTimeout(manager, agent.id); - return true; - }); - await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(true)); - await expect( - sendPromptToAgent({ - agentManager: manager, - agentStorage: { get: async () => undefined } as unknown as AgentStorage, - agentId: agent.id, - prompt: "competing", - replaceRunning: false, - logger: createTestLogger(), - }), - ).rejects.toMatchObject({ code: "AGENT_RUN_BUSY" }); - client.sessions[0].release(); - await expect(dispatch).resolves.toBe(true); - } finally { - await manager.closeAgent(agent.id).catch(() => undefined); - for (const session of client.sessions) session.release(); - rmSync(workdir, { recursive: true, force: true }); - } -}); - -test("queue reservation preserves a pending permission without a foreground run", async () => { - const workdir = mkdtempSync(join(tmpdir(), "queued-permission-reservation-")); - const client = new SlowStartAgentClient(null); - const manager = new AgentManager({ clients: { codex: client }, logger: createTestLogger() }); - const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { - workspaceId: undefined, - }); - try { - client.sessions[0].pushEvent({ - type: "permission_requested", - provider: "codex", - request: { - id: "approval-key", - provider: "codex", - kind: "tool", - name: "shell", - input: { command: "controlled" }, - }, - }); - await vi.waitFor(() => expect(manager.getPendingPermissions(agent.id)).toHaveLength(1)); - expect(manager.hasInFlightRun(agent.id)).toBe(false); - expect(() => - manager.streamAgent(agent.id, "yes", { requireNoPendingPermissions: true }), - ).toThrow(/active run/); - expect(manager.getPendingPermissions(agent.id).map((request) => request.id)).toEqual([ - "approval-key", - ]); - await manager.respondToPermission(agent.id, "approval-key", { behavior: "deny" }); - expect(manager.getPendingPermissions(agent.id)).toEqual([]); - } finally { - await manager.closeAgent(agent.id).catch(() => undefined); - rmSync(workdir, { recursive: true, force: true }); - } -}); - -test("queued dispatch cannot claim a turn when an agent became archived", async () => { - const streamAgent = vi.fn(); - await expect( - sendPromptToAgent({ - agentId: "archived", - prompt: "queued speech", - replaceRunning: false, - unarchive: false, - agentManager: { streamAgent } as unknown as AgentManager, - agentStorage: { get: async () => ({ archivedAt: "2026-10-08" }) } as unknown as AgentStorage, - logger: createTestLogger(), - }), - ).rejects.toMatchObject({ code: "AGENT_PROMPT_NOT_SUBMITTED" }); - expect(streamAgent).not.toHaveBeenCalled(); -}); diff --git a/packages/server/src/server/agent/agent-prompt.ts b/packages/server/src/server/agent/agent-prompt.ts index b58fb382db4..c0c094d5a90 100644 --- a/packages/server/src/server/agent/agent-prompt.ts +++ b/packages/server/src/server/agent/agent-prompt.ts @@ -79,25 +79,9 @@ async function startOrReplaceRun( replaced: boolean; }> { const replaced = Boolean(options?.replaceRunning && agentManager.hasInFlightRun(agentId)); - let iterator: AsyncGenerator; - if (replaced) { - iterator = await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions); - } else { - try { - iterator = agentManager.streamAgent(agentId, prompt, options?.runOptions); - } catch (cause) { - // streamAgent reserves synchronously; an exception here preceded startTurn. - if ( - options?.replaceRunning === false && - !(cause instanceof Error && "code" in cause && cause.code === "AGENT_RUN_BUSY") - ) { - throw Object.assign(new Error("Agent run reservation failed", { cause }), { - code: "AGENT_PROMPT_NOT_SUBMITTED", - }); - } - throw cause; - } - } + const iterator = replaced + ? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions) + : agentManager.streamAgent(agentId, prompt, options?.runOptions); return { iterator, replaced }; } @@ -140,9 +124,7 @@ export async function startAgentRun( await agentManager.reloadStalePluginSession(agentId); return await startAgentRunInner(agentManager, agentId, prompt, logger, options); } catch (error) { - // A queue attempt must fail as not-submitted instead of silently reloading - // and retrying: the caller owns whether the prompt is attempted again. - if (options?.replaceRunning === false || !isStaleProviderSessionError(error)) throw error; + if (!isStaleProviderSessionError(error)) throw error; logger.info({ agentId, err: error }, "Provider session went stale; reopening from persistence"); // The live session belongs to a retired plugin runtime. Reload swaps in a // fresh session on the current runtime while preserving history and labels. @@ -253,14 +235,6 @@ export interface SendPromptToAgentParams { unarchive?: boolean; /** See {@link StartAgentRunOptions.clearPendingPermissions}. */ clearPendingPermissions?: boolean; - /** - * Default true: an explicit send replaces an in-flight turn. Queue delivery - * passes false, so losing a busy race fails the attempt instead of - * interrupting the turn that won it. - */ - replaceRunning?: boolean; - /** Queue delivery waits while a provider permission request is pending. */ - blockPendingPermissions?: boolean; logger: Logger; } @@ -358,63 +332,42 @@ export async function sendPreparedPromptToAgent( ): Promise<{ disposition: PromptDispatchDisposition }> { const unarchive = params.unarchive ?? true; - try { - const record = await params.agentStorage.get(params.agentId); - let archivedAtToRestore: string | null = null; - if (record?.archivedAt) { - if (!unarchive) { - if (params.replaceRunning === false) throw new Error("Queued agent is archived"); - return { disposition: "turn_started" }; - } - if (await unarchiveAgentState(params.agentStorage, params.agentManager, params.agentId)) { - archivedAtToRestore = record.archivedAt; - } + const record = await params.agentStorage.get(params.agentId); + let archivedAtToRestore: string | null = null; + if (record?.archivedAt) { + if (!unarchive) { + return { disposition: "turn_started" }; } - try { - await ensureAgentLoaded(params.agentId, { - agentManager: params.agentManager, - agentStorage: params.agentStorage, - logger: params.logger, - }); - } catch (error) { - // Restore an archive cleared by a send whose provider failed to load. - if (archivedAtToRestore) { - await params.agentManager.archiveSnapshot(params.agentId, archivedAtToRestore); - } - throw error; - } - - if (params.sessionMode) { - await params.agentManager.setAgentMode(params.agentId, params.sessionMode); + if (await unarchiveAgentState(params.agentStorage, params.agentManager, params.agentId)) { + archivedAtToRestore = record.archivedAt; } + } - if ( - params.blockPendingPermissions && - params.agentManager.getPendingPermissions(params.agentId).length - ) { - const error = new Error(`Agent ${params.agentId} is waiting for permission`); - Object.assign(error, { code: "AGENT_RUN_BUSY" }); - throw error; + try { + await ensureAgentLoaded(params.agentId, { + agentManager: params.agentManager, + agentStorage: params.agentStorage, + logger: params.logger, + }); + } catch (error) { + // A send that could not load the agent leaves it where it was: still archived. + // Concurrent sends share this load, so none of them holds a live session. + if (archivedAtToRestore) { + await params.agentManager.archiveSnapshot(params.agentId, archivedAtToRestore); } - } catch (cause) { - // No prompt dispatch has happened; a queue can safely retain and retry this head. - if (params.replaceRunning === false) - throw Object.assign(new Error("Agent prompt preparation failed", { cause }), { - code: "AGENT_PROMPT_NOT_SUBMITTED", - }); - throw cause; + throw error; } - const runOptions = params.runOptions; + if (params.sessionMode) { + await params.agentManager.setAgentMode(params.agentId, params.sessionMode); + } return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, { - replaceRunning: params.replaceRunning ?? true, + replaceRunning: true, onDispatch: params.onDispatch, activeTurnBehavior: params.activeTurnBehavior, clearPendingPermissions: params.clearPendingPermissions, - runOptions: params.blockPendingPermissions - ? { ...runOptions, requireNoPendingPermissions: true } - : runOptions, + runOptions: params.runOptions, }); } diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index 3eece8988d4..83fd202ccfb 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -200,8 +200,6 @@ export type AgentPromptContentBlock = export type AgentPromptInput = string | AgentPromptContentBlock[]; export interface AgentRunOptions { - /** Manager admission guard, checked synchronously with the run reservation. */ - requireNoPendingPermissions?: boolean; outputSchema?: unknown; resumeFrom?: AgentPersistenceHandle; maxThinkingTokens?: number; diff --git a/packages/server/src/server/agent/agent-storage.test.ts b/packages/server/src/server/agent/agent-storage.test.ts index 1acad6b090a..2534a093123 100644 --- a/packages/server/src/server/agent/agent-storage.test.ts +++ b/packages/server/src/server/agent/agent-storage.test.ts @@ -320,26 +320,6 @@ describe("AgentStorage", () => { metadata, }, }); - agent.artifacts = [ - { - path: "/tmp/report.md", - name: "report.md", - kind: "markdown", - mimeType: "text/markdown", - size: 12, - createdAt: "2025-01-01T00:00:00.000Z", - updatedAt: "2025-01-01T00:00:00.000Z", - }, - ]; - agent.companionEntries = [ - { - id: "pin:disk", - kind: "pin", - text: "Retained context", - truncated: false, - timestamp: "2025-01-01T00:00:00.000Z", - }, - ]; await storage.applySnapshot(agent); const file = path.join(storagePath, "tmp-project", "disk-resume.json"); const originalBytes = await fs.readFile(file, "utf8"); @@ -356,8 +336,6 @@ describe("AgentStorage", () => { nativeHandle: "native-disk", metadata: { conversationId: "disk-conversation" }, }); - expect(payload.artifacts).toEqual(agent.artifacts); - expect(payload.companionEntries).toEqual(agent.companionEntries); expect(record.persistence).toEqual(agent.persistence); const secondReload = new AgentStorage(storagePath, logger); diff --git a/packages/server/src/server/agent/agent-storage.ts b/packages/server/src/server/agent/agent-storage.ts index 86614292bda..5e2a8816e46 100644 --- a/packages/server/src/server/agent/agent-storage.ts +++ b/packages/server/src/server/agent/agent-storage.ts @@ -5,13 +5,7 @@ import type { Logger } from "pino"; import type { JsonValue } from "@getpaseo/protocol/agent-types"; import { writeJsonFileAtomic } from "../atomic-file.js"; -import { CompanionEntrySchema } from "@getpaseo/protocol/companion-stream"; -import { - AgentArtifactSchema, - AgentFeatureSchema, - AgentOptionControlSchema, - AgentStatusSchema, -} from "../messages.js"; +import { AgentFeatureSchema, AgentOptionControlSchema, AgentStatusSchema } from "../messages.js"; import { toStoredAgentRecord } from "./agent-projections.js"; import type { ManagedAgent } from "./agent-manager.js"; import type { AgentSessionConfig } from "./agent-sdk-types.js"; @@ -91,8 +85,6 @@ const RAW_STORED_AGENT_SCHEMA = z.object({ background: z.boolean().optional(), archivedAt: z.string().nullable().optional(), owner: AgentOwnerSchema.optional(), - artifacts: z.array(AgentArtifactSchema).optional(), - companionEntries: z.array(CompanionEntrySchema).optional(), }); export type SerializableAgentConfig = Pick< diff --git a/packages/server/src/server/agent/artifacts/backfill.test.ts b/packages/server/src/server/agent/artifacts/backfill.test.ts deleted file mode 100644 index b5d2751da7a..00000000000 --- a/packages/server/src/server/agent/artifacts/backfill.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { mkdtemp, mkdir, writeFile, utimes } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import path from "node:path"; -import { describe, expect, it } from "vitest"; -import { AgentArtifactCollector } from "./collector.js"; - -async function makeWorkspace(): Promise { - const root = await mkdtemp(path.join(tmpdir(), "paseo-artifact-backfill-")); - await writeFile(path.join(root, "report.html"), "

report

"); - await writeFile(path.join(root, "notes.md"), "# notes"); - await writeFile(path.join(root, "diagram.svg"), ""); - await writeFile(path.join(root, "main.ts"), "export const x = 1;"); - - await mkdir(path.join(root, "node_modules", "pkg"), { recursive: true }); - await writeFile(path.join(root, "node_modules", "pkg", "readme.md"), "# vendored"); - - await mkdir(path.join(root, ".git"), { recursive: true }); - await writeFile(path.join(root, ".git", "COMMIT_EDITMSG.md"), "# internal"); - - return root; -} - -describe("artifact backfill", () => { - it("finds pre-existing files that no turn ever observed", async () => { - const cwd = await makeWorkspace(); - const collector = new AgentArtifactCollector(); - - // No beginTurn/finishTurn: this is the case the turn-scoped collector - // cannot see at all. - const result = await collector.scanExisting(cwd, []); - - expect(result).not.toBeNull(); - const paths = result?.artifacts.map((artifact) => artifact.path).sort(); - expect(paths).toEqual(["diagram.svg", "notes.md", "report.html"]); - expect(result?.addedOrUpdated).toBe(3); - }); - - it("skips vendored and VCS directories", async () => { - const cwd = await makeWorkspace(); - const result = await new AgentArtifactCollector().scanExisting(cwd, []); - - const paths = result?.artifacts.map((artifact) => artifact.path) ?? []; - expect(paths.some((p) => p.includes("node_modules"))).toBe(false); - expect(paths.some((p) => p.includes(".git"))).toBe(false); - }); - - it("classifies each artifact by extension", async () => { - const cwd = await makeWorkspace(); - const result = await new AgentArtifactCollector().scanExisting(cwd, []); - - const byPath = new Map(result?.artifacts.map((a) => [a.path, a]) ?? []); - expect(byPath.get("report.html")?.kind).toBe("html"); - expect(byPath.get("report.html")?.mimeType).toBe("text/html"); - expect(byPath.get("notes.md")?.kind).toBe("markdown"); - expect(byPath.get("diagram.svg")?.kind).toBe("svg"); - expect(byPath.get("report.html")?.size).toBeGreaterThan(0); - }); - - it("keeps the newest when the limit is smaller than the match count", async () => { - const cwd = await makeWorkspace(); - // Age report.html so it is unambiguously the oldest of the three. - const old = new Date(Date.now() - 1000 * 60 * 60 * 24); - await utimes(path.join(cwd, "report.html"), old, old); - - const result = await new AgentArtifactCollector().scanExisting(cwd, [], { limit: 2 }); - - expect(result?.artifacts).toHaveLength(2); - expect(result?.artifacts.map((a) => a.path)).not.toContain("report.html"); - }); - - it("reports nothing to do when every artifact is already recorded", async () => { - const cwd = await makeWorkspace(); - const collector = new AgentArtifactCollector(); - const first = await collector.scanExisting(cwd, []); - expect(first).not.toBeNull(); - - const second = await collector.scanExisting(cwd, first?.artifacts ?? []); - - // A second pass over unchanged files must not churn the agent record. - expect(second).toBeNull(); - }); -}); diff --git a/packages/server/src/server/agent/artifacts/collector.test.ts b/packages/server/src/server/agent/artifacts/collector.test.ts deleted file mode 100644 index 55b2a92600a..00000000000 --- a/packages/server/src/server/agent/artifacts/collector.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; -import os from "node:os"; -import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; -import { AgentArtifactCollector } from "./collector.js"; - -const temporaryDirectories: string[] = []; - -afterEach(async () => { - await Promise.all( - temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true })), - ); -}); - -describe("AgentArtifactCollector", () => { - it("collects supported files created by shell-style writes during a turn", async () => { - const cwd = await mkdtemp(path.join(os.tmpdir(), "paseo-artifacts-")); - temporaryDirectories.push(cwd); - await mkdir(path.join(cwd, "reports")); - const collector = new AgentArtifactCollector(); - - collector.beginTurn("agent-1", cwd); - await writeFile(path.join(cwd, "reports", "summary.html"), "

Summary

"); - await writeFile(path.join(cwd, "chart.png"), Buffer.from([137, 80, 78, 71])); - await writeFile(path.join(cwd, "notes.txt"), "not an artifact"); - - const collection = await collector.finishTurn("agent-1", []); - - expect(collection?.addedOrUpdated).toBe(2); - expect(collection?.artifacts.map((artifact) => artifact.path).sort()).toEqual([ - "chart.png", - "reports/summary.html", - ]); - expect(collection?.artifacts.find((artifact) => artifact.path === "chart.png")?.kind).toBe( - "image", - ); - }); - - it("caps the retained artifact list at the per-agent ceiling during a turn", async () => { - const cwd = await mkdtemp(path.join(os.tmpdir(), "paseo-artifacts-")); - temporaryDirectories.push(cwd); - await mkdir(path.join(cwd, "out")); - const collector = new AgentArtifactCollector(); - collector.beginTurn("agent-3", cwd); - const total = 210; - for (let index = 0; index < total; index += 1) { - await writeFile(path.join(cwd, "out", `page-${String(index).padStart(3, "0")}.html`), "

"); - } - - const collection = await collector.finishTurn("agent-3", []); - - expect(collection?.artifacts).toHaveLength(200); - // The kept set is the most recently modified, so the oldest pages drop. - expect(collection?.artifacts.every((artifact) => artifact.path > "out/page-009.html")).toBe( - true, - ); - }); - - it("uses completed write tool calls when the recursive watcher is unavailable", async () => { - const cwd = await mkdtemp(path.join(os.tmpdir(), "paseo-artifacts-")); - temporaryDirectories.push(cwd); - const collector = new AgentArtifactCollector(); - collector.beginTurn("agent-2", cwd); - await writeFile(path.join(cwd, "report.md"), "# Report"); - collector.observeToolCall("agent-2", { - type: "tool_call", - callId: "write-1", - name: "Write", - status: "completed", - error: null, - detail: { type: "write", filePath: "report.md" }, - }); - - const collection = await collector.finishTurn("agent-2", []); - - expect(collection?.artifacts).toEqual([ - expect.objectContaining({ path: "report.md", kind: "markdown" }), - ]); - }); -}); diff --git a/packages/server/src/server/agent/artifacts/collector.ts b/packages/server/src/server/agent/artifacts/collector.ts deleted file mode 100644 index 98ef672d605..00000000000 --- a/packages/server/src/server/agent/artifacts/collector.ts +++ /dev/null @@ -1,272 +0,0 @@ -import { readdir, stat } from "node:fs/promises"; -import path from "node:path"; -import type { - AgentArtifact, - AgentArtifactKind, - ToolCallTimelineItem, -} from "@getpaseo/protocol/agent-types"; - -const IGNORED_DIRECTORIES = new Set([ - ".git", - ".expo", - ".next", - ".paseo", - ".turbo", - "coverage", - "node_modules", -]); -const MAX_SCANNED_ENTRIES = 20_000; -/** - * Explicit per-agent ceiling on retained artifact metadata. A repo with - * committed build output can match thousands of files; each retained entry - * lives in the persisted agent record, so the list itself must stay bounded. - */ -const MAX_RETAINED_ARTIFACTS = 200; - -interface ArtifactFormat { - kind: AgentArtifactKind; - mimeType: string; -} - -const ARTIFACT_FORMATS: Record = { - ".diff": { kind: "diff", mimeType: "text/x-diff" }, - ".gif": { kind: "image", mimeType: "image/gif" }, - ".htm": { kind: "html", mimeType: "text/html" }, - ".html": { kind: "html", mimeType: "text/html" }, - ".jpeg": { kind: "image", mimeType: "image/jpeg" }, - ".jpg": { kind: "image", mimeType: "image/jpeg" }, - ".md": { kind: "markdown", mimeType: "text/markdown" }, - ".mdx": { kind: "markdown", mimeType: "text/markdown" }, - ".patch": { kind: "diff", mimeType: "text/x-diff" }, - ".pdf": { kind: "pdf", mimeType: "application/pdf" }, - ".png": { kind: "image", mimeType: "image/png" }, - ".svg": { kind: "svg", mimeType: "image/svg+xml" }, - ".webp": { kind: "image", mimeType: "image/webp" }, -}; - -interface ActiveTurn { - cwd: string; - startedAt: number; - candidates: Set; -} - -export interface ArtifactCollectionResult { - artifacts: AgentArtifact[]; - addedOrUpdated: number; -} - -export class AgentArtifactCollector { - private readonly activeTurns = new Map(); - - beginTurn(agentId: string, cwd: string): void { - if (this.activeTurns.has(agentId)) { - return; - } - const turn: ActiveTurn = { - cwd: path.resolve(cwd), - startedAt: Date.now(), - candidates: new Set(), - }; - // No live watcher: tool-call paths plus the end-of-turn mtime scan already find every - // file the turn touched, and a raw recursive fs.watch is what docs/file-observation.md - // forbids on Linux (Node walks the tree in JS and throws an uncaught ENOENT when a - // directory vanishes mid-scan, which upstream's hub tests do while deleting temp repos). - this.activeTurns.set(agentId, turn); - } - - observeToolCall(agentId: string, item: ToolCallTimelineItem): void { - if (item.status !== "completed") { - return; - } - if (item.detail.type !== "write" && item.detail.type !== "edit") { - return; - } - const turn = this.activeTurns.get(agentId); - if (turn) { - this.addCandidate(turn, item.detail.filePath); - } - } - - async finishTurn( - agentId: string, - existingArtifacts: readonly AgentArtifact[], - ): Promise { - const turn = this.activeTurns.get(agentId); - if (!turn) { - return null; - } - this.activeTurns.delete(agentId); - - const recentPaths = await findRecentlyModifiedArtifacts(turn.cwd, turn.startedAt); - for (const recentPath of recentPaths) { - turn.candidates.add(recentPath); - } - - return mergeArtifactCandidates( - turn.cwd, - turn.candidates, - existingArtifacts, - MAX_RETAINED_ARTIFACTS, - ); - } - - /** - * Collects artifacts that already exist under `cwd`, whatever their age. - * - * Turn-scoped collection only ever sees files touched while a turn was - * running, so an agent whose work predates this feature — or predates the - * daemon build that carries it — shows an empty feed forever. This is the - * backfill for that case, and it is deliberately explicit rather than - * automatic: a full walk of a large working directory is not something to run - * behind the user's back on every agent load. - */ - async scanExisting( - cwd: string, - existingArtifacts: readonly AgentArtifact[], - options?: { limit?: number }, - ): Promise { - // A zero cutoff makes the recency filter match everything. - const candidates = await findRecentlyModifiedArtifacts(cwd, 0); - const limit = options?.limit ?? MAX_RETAINED_ARTIFACTS; - return mergeArtifactCandidates(cwd, candidates, existingArtifacts, limit); - } - - cancelTurn(agentId: string): void { - this.activeTurns.delete(agentId); - } - - private addCandidate(turn: ActiveTurn, filePath: string): void { - const relativePath = resolveRelativeArtifactPath(turn.cwd, filePath); - if (relativePath && getArtifactFormat(relativePath)) { - turn.candidates.add(relativePath); - } - } -} - -/** - * Merges freshly inspected candidates into an agent's existing artifact list. - * - * `limit` caps the retained list, keeping the most recently modified — a - * backfill over a repo with a committed build directory can otherwise bury the - * handful of files the user actually cares about. `null` keeps everything, - * which is right for a single turn's output. - */ -async function mergeArtifactCandidates( - cwd: string, - candidates: Iterable, - existingArtifacts: readonly AgentArtifact[], - limit: number | null, -): Promise { - const artifactsByPath = new Map(existingArtifacts.map((artifact) => [artifact.path, artifact])); - let addedOrUpdated = 0; - for (const candidate of candidates) { - const artifact = await inspectArtifact(cwd, candidate, artifactsByPath.get(candidate)); - if (!artifact) { - continue; - } - const previous = artifactsByPath.get(candidate); - if (!previous || previous.updatedAt !== artifact.updatedAt || previous.size !== artifact.size) { - artifactsByPath.set(candidate, artifact); - addedOrUpdated += 1; - } - } - if (addedOrUpdated === 0) { - return null; - } - - let artifacts = Array.from(artifactsByPath.values()); - artifacts.sort((left, right) => Date.parse(left.updatedAt) - Date.parse(right.updatedAt)); - if (limit !== null && artifacts.length > limit) { - artifacts = artifacts.slice(artifacts.length - limit); - } - return { artifacts, addedOrUpdated }; -} - -async function findRecentlyModifiedArtifacts(cwd: string, startedAt: number): Promise { - const matches: string[] = []; - const pending = [cwd]; - let scannedEntries = 0; - while (pending.length > 0 && scannedEntries < MAX_SCANNED_ENTRIES) { - const directory = pending.pop(); - if (!directory) { - break; - } - let entries; - try { - entries = await readdir(directory, { withFileTypes: true }); - } catch { - continue; - } - for (const entry of entries) { - scannedEntries += 1; - if (scannedEntries > MAX_SCANNED_ENTRIES) { - break; - } - const absolutePath = path.join(directory, entry.name); - if (entry.isDirectory()) { - if (!IGNORED_DIRECTORIES.has(entry.name)) { - pending.push(absolutePath); - } - continue; - } - if (!entry.isFile() || !getArtifactFormat(entry.name)) { - continue; - } - try { - const fileStat = await stat(absolutePath); - if (fileStat.mtimeMs >= startedAt - 100) { - matches.push(toPortableRelativePath(cwd, absolutePath)); - } - } catch { - continue; - } - } - } - return matches; -} - -async function inspectArtifact( - cwd: string, - relativePath: string, - previous: AgentArtifact | undefined, -): Promise { - const format = getArtifactFormat(relativePath); - if (!format) { - return null; - } - try { - const fileStat = await stat(path.join(cwd, relativePath)); - if (!fileStat.isFile()) { - return null; - } - const updatedAt = fileStat.mtime.toISOString(); - return { - path: relativePath, - name: path.basename(relativePath), - kind: format.kind, - mimeType: format.mimeType, - size: fileStat.size, - createdAt: previous?.createdAt ?? updatedAt, - updatedAt, - }; - } catch { - return null; - } -} - -function resolveRelativeArtifactPath(cwd: string, filePath: string): string | null { - const absolutePath = path.resolve(cwd, filePath); - const relativePath = path.relative(cwd, absolutePath); - if (!relativePath || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath)) { - return null; - } - return relativePath.split(path.sep).join("/"); -} - -function toPortableRelativePath(cwd: string, absolutePath: string): string { - return path.relative(cwd, absolutePath).split(path.sep).join("/"); -} - -function getArtifactFormat(filePath: string): ArtifactFormat | null { - return ARTIFACT_FORMATS[path.extname(filePath).toLowerCase()] ?? null; -} diff --git a/packages/server/src/server/agent/companion-stream.test.ts b/packages/server/src/server/agent/companion-stream.test.ts deleted file mode 100644 index e8dcf06b3f5..00000000000 --- a/packages/server/src/server/agent/companion-stream.test.ts +++ /dev/null @@ -1,399 +0,0 @@ -import { describe, expect, it } from "vitest"; -import type { CompanionEntry } from "@getpaseo/protocol/companion-stream"; -import { - appendManualCompanionEntry, - CompanionStreamCollector, - restoreCompanionEntries, - COMPANION_ENTRY_LIMIT, - COMPANION_MANUAL_ENTRY_LIMIT, - COMPANION_TEXT_LIMIT, -} from "./companion-stream.js"; - -describe("conversation companion stream", () => { - it("returns the same entries reference when an event changes nothing", () => { - const collector = new CompanionStreamCollector(); - const timestamp = "2026-09-21T12:00:00.000Z"; - const settled: CompanionEntry[] = [ - { - id: "turn:t0:question", - kind: "question", - timestamp, - text: "Ship it?", - truncated: false, - status: "reply_sent", - }, - ]; - // A user message only moves open questions to reply_sent; with none open, the - // agent manager must not emit a fresh agent state for it. - const afterUserMessage = collector.observe( - "agent", - settled, - { - type: "timeline", - provider: "codex", - turnId: "t1", - item: { type: "user_message", id: "u1", messageId: "u1", text: "go", timestamp }, - } as never, - timestamp, - ); - expect(afterUserMessage).toBe(settled); - const afterUnrelatedResolution = collector.observe( - "agent", - settled, - { - type: "permission_resolved", - provider: "codex", - requestId: "not-tracked", - resolution: { behavior: "allow" }, - } as never, - timestamp, - ); - expect(afterUnrelatedResolution).toBe(settled); - }); - - it("never evicts pins or tracked Q&A when captured moments churn", () => { - const collector = new CompanionStreamCollector(); - const timestamp = "2026-09-21T12:00:00.000Z"; - const pin: CompanionEntry = { - id: "pin:keep", - kind: "pin", - timestamp, - text: "user note", - truncated: false, - }; - let entries: CompanionEntry[] = [pin]; - for (let turn = 0; turn < COMPANION_ENTRY_LIMIT + 5; turn += 1) { - entries = collector.observe( - "agent", - entries, - { - type: "turn_completed", - provider: "codex", - turnId: `t${turn}`, - } as never, - timestamp, - ); - } - expect(entries).toContain(pin); - expect(entries.filter((entry) => entry.kind === "outcome").length).toBeLessThanOrEqual( - COMPANION_ENTRY_LIMIT, - ); - }); - - it("clips manual entry text to the shared excerpt limit", () => { - const appended = appendManualCompanionEntry([], { - id: "pin:long", - kind: "pin", - timestamp: "2026-09-21T12:00:00.000Z", - text: "x".repeat(COMPANION_TEXT_LIMIT + 1), - truncated: false, - }); - expect(appended.error).toBeUndefined(); - expect(appended.entries[0]?.text).toHaveLength(COMPANION_TEXT_LIMIT); - expect(appended.entries[0]?.truncated).toBe(true); - }); - - it("clips a manual Q&A answer and refuses appends past the manual ceiling", () => { - const timestamp = "2026-09-21T12:00:00.000Z"; - const appended = appendManualCompanionEntry([], { - id: "qa:long", - kind: "q_and_a", - timestamp, - text: "q", - answer: "a".repeat(COMPANION_TEXT_LIMIT + 1), - truncated: false, - }); - expect(appended.entries[0]).toMatchObject({ answer: "a".repeat(COMPANION_TEXT_LIMIT) }); - - const full: CompanionEntry[] = Array.from( - { length: COMPANION_MANUAL_ENTRY_LIMIT }, - (_, index): CompanionEntry => ({ - id: `pin:${index}`, - kind: "pin", - timestamp, - text: `note ${index}`, - truncated: false, - }), - ); - const refused = appendManualCompanionEntry(full, { - id: "pin:one-too-many", - kind: "pin", - timestamp, - text: "overflow", - truncated: false, - }); - expect(refused.error).toBeTruthy(); - expect(refused.entries).toBe(full); - }); - - it("keeps a question open until the provider resolves its permission request", () => { - const collector = new CompanionStreamCollector(); - const timestamp = "2026-09-21T12:00:00.000Z"; - const pending = collector.observe( - "agent", - [], - { - type: "permission_requested", - provider: "codex", - request: { - id: "q1", - provider: "codex", - name: "request_user_input", - kind: "question", - input: { questions: [{ question: "Which database should we use?" }] }, - }, - }, - timestamp, - ); - expect(pending).toEqual([ - { - id: "permission:q1", - kind: "permission", - requestId: "q1", - requestKind: "question", - text: "Which database should we use?", - timestamp, - status: "pending", - truncated: false, - }, - ]); - expect( - collector.observe( - "agent", - pending, - { - type: "permission_resolved", - provider: "codex", - requestId: "q1", - resolution: { behavior: "allow" }, - }, - timestamp, - ), - ).toEqual([{ ...pending[0], status: "allowed" }]); - }); -}); - -const timestamp = "2026-09-21T12:00:00.000Z"; - -it("collects only the final response, merges chunks, and keeps other agents separate", () => { - const collector = new CompanionStreamCollector(); - const output = (agentId: string, text: string) => - collector.observe( - agentId, - [], - { - type: "timeline", - provider: "codex", - turnId: "run", - item: { type: "assistant_message", text }, - }, - timestamp, - ); - expect(output("one", "I will inspect the files")).toEqual([]); - collector.observe( - "one", - [], - { - type: "timeline", - provider: "codex", - turnId: "run", - item: { - type: "tool_call", - callId: "read", - name: "read", - status: "completed", - error: null, - detail: { type: "read", filePath: "README.md" }, - }, - }, - timestamp, - ); - output("one", "Implemented "); - output("two", "Unrelated result"); - output("one", "the feature."); - const result = collector.observe( - "one", - [], - { type: "turn_completed", provider: "codex", turnId: "run" }, - timestamp, - ); - expect(result).toEqual([ - { - id: "turn:run", - kind: "outcome", - timestamp, - text: "Implemented the feature.", - truncated: false, - status: "completed", - }, - ]); - expect( - collector.observe( - "one", - result, - { type: "turn_completed", provider: "codex", turnId: "run" }, - timestamp, - ), - ).toEqual(result); -}); - -it("tracks prose questions without claiming a reply resolved a decision", () => { - const collector = new CompanionStreamCollector(); - collector.observe( - "a", - [], - { - type: "timeline", - provider: "codex", - turnId: "q", - item: { type: "assistant_message", text: "Use SQLite or Postgres?" }, - }, - timestamp, - ); - const result = collector.observe( - "a", - [], - { type: "turn_completed", provider: "codex", turnId: "q" }, - timestamp, - ); - expect(result).toEqual([ - { - id: "turn:q:question", - kind: "question", - timestamp, - text: "Use SQLite or Postgres?", - truncated: false, - status: "open", - }, - { id: "turn:q", kind: "outcome", timestamp, text: "", truncated: false, status: "completed" }, - ]); - expect( - collector.observe( - "a", - result, - { - type: "timeline", - provider: "codex", - item: { type: "user_message", text: "What do you recommend?" }, - }, - timestamp, - ), - ).toEqual([{ ...result[0], status: "reply_sent" }, result[1]]); -}); - -it.each(["Example: `ready?`", "Example:\n```js\nready?\n```", "See https://example.com/?"])( - "does not turn code or URLs into open questions: %s", - (text) => { - const collector = new CompanionStreamCollector(); - collector.observe( - "a", - [], - { - type: "timeline", - provider: "codex", - turnId: "r", - item: { type: "assistant_message", text }, - }, - timestamp, - ); - expect( - collector - .observe("a", [], { type: "turn_completed", provider: "codex", turnId: "r" }, timestamp) - .map((entry) => entry.kind), - ).toEqual(["outcome"]); - }, -); - -it("retains structured questions after unrelated user messages and expires them on interruption", () => { - const collector = new CompanionStreamCollector(); - const entries = collector.observe( - "a", - [], - { - type: "permission_requested", - provider: "codex", - request: { - id: "p", - name: "approval", - kind: "plan", - provider: "codex", - detail: { type: "plan", text: "Migrate the database" }, - }, - }, - timestamp, - ); - expect( - collector.observe( - "a", - entries, - { type: "timeline", provider: "codex", item: { type: "user_message", text: "Wait" } }, - timestamp, - ), - ).toEqual(entries); - expect( - collector.observe( - "a", - entries, - { type: "turn_canceled", provider: "codex", turnId: "r", reason: "Stopped by user" }, - timestamp, - ), - ).toEqual([ - { ...entries[0], status: "expired" }, - { - id: "turn:r", - kind: "outcome", - timestamp, - text: "Stopped by user", - truncated: false, - status: "canceled", - }, - ]); - expect(restoreCompanionEntries({ companionEntries: entries })).toEqual([ - { ...entries[0], status: "expired" }, - ]); -}); - -it("bounds stored output and records failure independently of an assistant success claim", () => { - const collector = new CompanionStreamCollector(); - collector.observe( - "a", - [], - { - type: "timeline", - provider: "codex", - turnId: "r", - item: { type: "assistant_message", text: "Succeeded!" }, - }, - timestamp, - ); - const error = "x".repeat(COMPANION_TEXT_LIMIT + 100); - expect( - collector.observe( - "a", - [], - { type: "turn_failed", provider: "codex", turnId: "r", error }, - timestamp, - ), - ).toEqual([ - { - id: "turn:r", - kind: "outcome", - timestamp, - text: error.slice(0, COMPANION_TEXT_LIMIT), - truncated: true, - status: "failed", - }, - ]); - let entries: CompanionEntry[] = []; - for (let i = 0; i < COMPANION_ENTRY_LIMIT + 2; i++) { - entries = collector.observe( - "a", - entries, - { type: "turn_completed", provider: "codex", turnId: String(i) }, - timestamp, - ); - } - expect(entries.map((entry) => entry.id)).toEqual( - Array.from({ length: COMPANION_ENTRY_LIMIT }, (_, i) => `turn:${i + 2}`), - ); -}); diff --git a/packages/server/src/server/agent/companion-stream.ts b/packages/server/src/server/agent/companion-stream.ts deleted file mode 100644 index e73093fcac7..00000000000 --- a/packages/server/src/server/agent/companion-stream.ts +++ /dev/null @@ -1,283 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { CompanionEntry } from "@getpaseo/protocol/companion-stream"; -import type { AgentPermissionRequest, AgentStreamEvent } from "./agent-sdk-types.js"; - -export const COMPANION_ENTRY_LIMIT = 50; -export const COMPANION_TEXT_LIMIT = 4000; -/** - * Explicit ceiling for user-created entries (Stream pins and tracked Q&A). - * Captured moments churn against COMPANION_ENTRY_LIMIT; manual entries are - * never evicted by that churn, so they need a bound of their own. Adding - * past the cap is refused so an old note is never silently dropped. - */ -export const COMPANION_MANUAL_ENTRY_LIMIT = 100; - -interface ResponseDraft { - text: string; - messageId: string | undefined; - truncated: boolean; -} - -function excerpt(text: string): { text: string; truncated: boolean } { - return { - text: text.slice(0, COMPANION_TEXT_LIMIT), - truncated: text.length > COMPANION_TEXT_LIMIT, - }; -} - -function requestText(request: AgentPermissionRequest): string { - const questions = request.input?.questions; - if (Array.isArray(questions)) { - const text = questions - .flatMap((question: unknown) => { - if (typeof question !== "object" || question === null || !("question" in question)) - return []; - return typeof question.question === "string" ? [question.question] : []; - }) - .join("\n\n"); - if (text) return text; - } - if (request.kind === "plan") { - if (typeof request.metadata?.planText === "string") return request.metadata.planText; - if (typeof request.input?.plan === "string") return request.input.plan; - } - if (request.detail?.type === "plain_text" && request.detail.text) return request.detail.text; - if (request.detail?.type === "plan") return request.detail.text; - if (request.detail?.type === "shell") return request.detail.command; - return request.description || request.title || request.name; -} - -export function restoreCompanionEntries(options?: { - companionEntries?: CompanionEntry[]; -}): CompanionEntry[] { - const entries = options?.companionEntries ?? []; - // Provider requests do not survive session recreation. Do not present an old approval as live. - return entries.map(expirePendingPermission); -} - -function expirePendingPermission(entry: CompanionEntry): CompanionEntry { - return entry.kind === "permission" && entry.status === "pending" - ? { ...entry, status: "expired" } - : entry; -} - -export class CompanionStreamCollector { - private readonly drafts = new Map>(); - - clear(agentId: string): void { - this.drafts.delete(agentId); - } - - observe( - agentId: string, - entries: CompanionEntry[], - event: AgentStreamEvent, - timestamp: string, - ): CompanionEntry[] { - const turnKey = "turnId" in event ? (event.turnId ?? "unscoped") : "unscoped"; - const turns = this.drafts.get(agentId) ?? new Map(); - if (event.type === "turn_started") { - turns.delete(turnKey); - this.drafts.set(agentId, turns); - } - if (event.type === "timeline") { - return this.observeTimeline(agentId, entries, event, turnKey, turns); - } - if (event.type === "permission_requested") { - const entry: CompanionEntry = { - id: `permission:${event.request.id}`, - kind: "permission", - timestamp, - requestId: event.request.id, - requestKind: event.request.kind, - status: "pending", - ...excerpt(requestText(event.request)), - }; - return upsert(entries, entry); - } - if (event.type === "permission_resolved") { - return mapChanged(entries, (entry) => - entry.kind === "permission" && entry.requestId === event.requestId - ? { ...entry, status: event.resolution.behavior === "allow" ? "allowed" : "denied" } - : entry, - ); - } - if ( - event.type !== "turn_completed" && - event.type !== "turn_failed" && - event.type !== "turn_canceled" - ) - return entries; - - const draft = turns.get(turnKey); - turns.delete(turnKey); - if (turns.size === 0) this.drafts.delete(agentId); - return collectOutcome(entries, event, timestamp, draft); - } - - private observeTimeline( - agentId: string, - entries: CompanionEntry[], - event: Extract, - turnKey: string, - turns: Map, - ): CompanionEntry[] { - const item = event.item; - if (item.type === "assistant_message") { - const previous = turns.get(turnKey); - const sameMessage = previous && previous.messageId === item.messageId; - const next = excerpt((sameMessage ? previous.text : "") + item.text); - turns.set(turnKey, { - ...next, - messageId: item.messageId, - truncated: next.truncated || Boolean(sameMessage && previous.truncated), - }); - this.drafts.set(agentId, turns); - } else if (item.type === "tool_call" || item.type === "user_message") { - // Only the final response is a review card, not intermediate tool narration. - turns.delete(turnKey); - } - if (item.type === "user_message") { - return mapChanged(entries, (entry) => - entry.kind === "question" && entry.status === "open" - ? { ...entry, status: "reply_sent" } - : entry, - ); - } - return entries; - } -} - -function collectOutcome( - entries: CompanionEntry[], - event: Extract, - timestamp: string, - draft: ResponseDraft | undefined, -): CompanionEntry[] { - const id = `turn:${event.turnId ?? randomUUID()}`; - if (entries.some((entry) => entry.id === id)) return entries; - let next = entries; - if (event.type !== "turn_completed") { - next = mapChanged(next, expirePendingPermission); - } - const text = draft?.text.trim() ?? ""; - // Plain prose questions are a hint, never a claim that a later reply resolved a decision. - const prose = text.replace(/```[\s\S]*?```|`[^`]*`|https?:\/\/\S+/g, ""); - const question = event.type === "turn_completed" && /[??]\s*$/.test(prose); - if (question) { - next = upsert(next, { - id: `${id}:question`, - kind: "question", - timestamp, - text, - truncated: draft?.truncated ?? false, - status: "open", - }); - } - let outcomeText = question ? "" : text; - let status: "completed" | "failed" | "canceled" = "completed"; - if (event.type === "turn_failed") { - outcomeText = event.error; - status = "failed"; - } else if (event.type === "turn_canceled") { - outcomeText = event.reason; - status = "canceled"; - } - return upsert(next, { - id, - kind: "outcome", - timestamp, - ...excerpt(outcomeText), - truncated: - outcomeText === text - ? (draft?.truncated ?? false) - : outcomeText.length > COMPANION_TEXT_LIMIT, - status, - }); -} - -/** - * Returns the input array itself when no element changed. The agent manager emits a - * fresh agent state whenever the entries reference changes, and an emit that carries - * no change still tells every client the agent is running before the authoritative - * turn and status messages arrive. - */ -function mapChanged( - entries: CompanionEntry[], - update: (entry: CompanionEntry) => CompanionEntry, -): CompanionEntry[] { - let changed = false; - const next = entries.map((entry) => { - const updated = update(entry); - if (updated !== entry) changed = true; - return updated; - }); - return changed ? next : entries; -} - -function isManualEntry(entry: CompanionEntry): boolean { - return entry.kind === "pin" || entry.kind === "q_and_a"; -} - -function upsert(entries: CompanionEntry[], entry: CompanionEntry): CompanionEntry[] { - const existing = entries.find((item) => item.id === entry.id); - const next = existing - ? entries.map((item) => (item.id === entry.id ? { ...entry, timestamp: item.timestamp } : item)) - : [...entries, entry]; - return evictCapturedSurplus(next); -} - -/** - * Enforces COMPANION_ENTRY_LIMIT over captured moments only. Stream pins and - * tracked Q&A are user data: moment churn trims the oldest captured entries - * and never touches them. - */ -function evictCapturedSurplus(entries: CompanionEntry[]): CompanionEntry[] { - if (entries.length <= COMPANION_ENTRY_LIMIT) { - return entries; - } - const surplus = entries.length - COMPANION_ENTRY_LIMIT; - let remaining = surplus; - const next: CompanionEntry[] = []; - for (const entry of entries) { - if (remaining > 0 && !isManualEntry(entry)) { - remaining -= 1; - continue; - } - next.push(entry); - } - return next; -} - -export interface ManualEntryAppendResult { - entries: CompanionEntry[]; - error?: string; -} - -/** - * Appends a user-created pin or Q&A under the explicit manual-entry bounds: - * the text is excerpt-clipped like captured moments, and the append is - * refused once COMPANION_MANUAL_ENTRY_LIMIT is reached. - */ -export function appendManualCompanionEntry( - entries: CompanionEntry[], - entry: CompanionEntry, -): ManualEntryAppendResult { - const manualCount = entries.filter(isManualEntry).length; - if (manualCount >= COMPANION_MANUAL_ENTRY_LIMIT) { - return { - entries, - error: `Stream pin limit reached (${COMPANION_MANUAL_ENTRY_LIMIT}). Remove one to add another.`, - }; - } - let clipped: CompanionEntry = - entry.text.length > COMPANION_TEXT_LIMIT ? { ...entry, ...excerpt(entry.text) } : entry; - if ( - clipped.kind === "q_and_a" && - clipped.answer && - clipped.answer.length > COMPANION_TEXT_LIMIT - ) { - clipped = { ...clipped, answer: clipped.answer.slice(0, COMPANION_TEXT_LIMIT) }; - } - return { entries: [...entries, clipped] }; -} diff --git a/packages/server/src/server/agent/lifecycle-command.ts b/packages/server/src/server/agent/lifecycle-command.ts index 954246bd14e..431cff0fe66 100644 --- a/packages/server/src/server/agent/lifecycle-command.ts +++ b/packages/server/src/server/agent/lifecycle-command.ts @@ -33,15 +33,6 @@ export interface LifecycleAgentManager { labels?: Record; }, ): Promise; - updateCompanionEntry(input: { - agentId: string; - entryId?: string; - action: "update_status" | "add_pin" | "remove_pin" | "add_q_and_a"; - status?: "open" | "reviewed" | "done"; - text?: string; - answerText?: string; - sourceId?: string; - }): Promise; } export interface LifecycleAgentStorage { @@ -198,29 +189,6 @@ export async function updateAgentCommand( }; } -export async function updateCompanionEntryCommand( - dependencies: Pick, - input: { - agentId: string; - entryId?: string; - action: "update_status" | "add_pin" | "remove_pin" | "add_q_and_a"; - status?: "open" | "reviewed" | "done"; - text?: string; - answerText?: string; - sourceId?: string; - }, -): Promise<{ accepted: boolean; error?: string }> { - try { - await dependencies.agentManager.updateCompanionEntry(input); - return { accepted: true }; - } catch (error) { - return { - accepted: false, - error: error instanceof Error ? error.message : "Failed to update companion entry", - }; - } -} - export interface DetachAgentResult { agentId: string; record: StoredAgentRecord; diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index e2d02a0d08c..62fb2906b41 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -23,7 +23,6 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import express from "express"; import { createServer } from "node:http"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { Readable } from "node:stream"; import { realpathSync } from "node:fs"; import { access, mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { join, resolve as resolvePath } from "node:path"; @@ -32,8 +31,6 @@ import { z } from "zod"; import { createTestLogger } from "../../test-utils/test-logger.js"; import { createAgentMcpServer as createAgentMcpServerWithDependencies } from "./mcp-server.js"; -import { createPaseoToolCatalog } from "./tools/paseo-tools.js"; -import { TTSManager } from "./tts-manager.js"; import { AgentManager, type ManagedAgent } from "./agent-manager.js"; import { AgentStorage, type StoredAgentRecord } from "./agent-storage.js"; import { createTestAgentClients } from "../test-utils/fake-agent-client.js"; @@ -56,7 +53,6 @@ import { AgentListItemPayloadSchema, AgentPermissionRequestPayloadSchema, AgentSnapshotPayloadSchema, - AudioPlayedMessageSchema, } from "@getpaseo/protocol/messages"; import { createPersistedProjectRecord, @@ -6552,126 +6548,34 @@ describe("speak MCP tool", () => { ); }); - it("returns an MCP error when the client reports failed audio playback", async () => { - const { agentManager, agentStorage } = createTestDeps(); - const tts = new TTSManager("voice-output-test", logger, { - async synthesizeSpeech() { - return { stream: Readable.from([Buffer.from("audio")]), format: "pcm" }; - }, - }); - const server = await createAgentMcpServer({ - agentManager, - agentStorage, - providerSnapshotManager: createOpenCodeManager().manager, - callerAgentId: "voice-agent-failed-output", - enableVoiceTools: true, - resolveSpeakHandler: - () => - async ({ text, signal }) => { - await tts.generateAndWaitForPlayback( - text, - (message) => { - if (message.type !== "audio_output") return; - const response = AudioPlayedMessageSchema.parse({ - type: "audio_played", - id: message.payload.id, - error: "Audio playback timed out", - }); - tts.confirmAudioPlayed(response.id, response.error); - }, - signal ?? new AbortController().signal, - true, - ); - }, - logger, - }); - const client = await connectInMemoryMcpClient(server); - try { - const result = await client.callTool({ name: "speak", arguments: { text: "Hello." } }); - expect(result.isError).toBe(true); - expect(result.content).toEqual([ - { type: "text", text: "Audio playback failed: Audio playback timed out" }, - ]); - } finally { - tts.cleanup(); - await client.close(); - await server.close(); - } - }); - - it.each([{ enabled: false }, { disabledTools: ["speak"] }])( - "keeps speak available independently of the Paseo tool policy: %j", - async (paseoToolPolicy) => { - const { agentManager, agentStorage } = createTestDeps(); - const options = { - agentManager, - agentStorage, - providerSnapshotManager: createOpenCodeManager().manager, - callerAgentId: "voice-agent", - paseoToolPolicy, - logger, - }; - const catalog = createPaseoToolCatalog(options); - expect(catalog.getTool("speak")).toBeDefined(); - const server = await createAgentMcpServer(options); - const client = await connectInMemoryMcpClient(server); - try { - expect((await client.listTools()).tools.map((tool) => tool.name)).toContain("speak"); - expect( - (await client.callTool({ name: "speak", arguments: { text: "Hello" } })) - .structuredContent, - ).toMatchObject({ ok: false }); - } finally { - await client.close(); - await server.close(); - } - }, - ); - - it("settles when no speak handler is attached", async () => { + it("fails when no speak handler exists", async () => { const { agentManager, agentStorage } = createTestDeps(); const server = await createAgentMcpServer({ agentManager, agentStorage, providerSnapshotManager: createOpenCodeManager().manager, callerAgentId: "voice-agent-2", + enableVoiceTools: true, resolveSpeakHandler: () => null, logger, }); const tool = registeredTool(server, "speak"); - const result = await tool.handler({ text: "Hello." }); - expect(result).toEqual( - expect.objectContaining({ - content: [{ type: "text", text: "Voice is not attached. Continue in the chat." }], - structuredContent: { ok: false }, - }), + await expect(tool.handler({ text: "Hello." })).rejects.toThrow( + "No speak handler registered for your session", ); }); - it("advertises speak before attachment in MCP and native agent catalogs", async () => { + it("does not register speak tool unless voice tools are enabled", async () => { const { agentManager, agentStorage } = createTestDeps(); const server = await createAgentMcpServer({ agentManager, agentStorage, providerSnapshotManager: createOpenCodeManager().manager, callerAgentId: "agent-no-voice", - resolveSpeakHandler: () => null, logger, }); const tool = lookupTool(server, "speak"); - expect(tool).toBeDefined(); - const catalog = createPaseoToolCatalog({ - agentManager, - agentStorage, - providerSnapshotManager: createOpenCodeManager().manager, - callerAgentId: "agent-no-voice", - resolveSpeakHandler: () => null, - logger, - }); - expect(catalog.getTool("speak")?.name).toBe("speak"); - expect(await catalog.executeTool("speak", { text: "Hello." })).toEqual( - expect.objectContaining({ structuredContent: { ok: false } }), - ); + expect(tool).toBeUndefined(); }); }); diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 6188fde693f..eb1f9a5c177 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -1337,12 +1337,7 @@ function createToolCatalog( type TopLevelCreateAgentArgs = z.infer; type LegacyTopLevelCreateAgentArgs = z.infer; - if ( - options.voiceOnly || - scope === "agent" || - options.enableVoiceTools || - callerContext?.enableVoiceTools - ) { + if (options.voiceOnly || options.enableVoiceTools || callerContext?.enableVoiceTools) { registerTool( "speak", { @@ -1366,23 +1361,16 @@ function createToolCatalog( } const handler = resolveSpeakHandler?.(callerAgentId) ?? null; if (!handler) { - // Voice can detach while the agent works; the tool call settles - // instead of failing so the turn keeps its visible reply in chat. - return { - content: [{ type: "text", text: "Voice is not attached. Continue in the chat." }], - structuredContent: ensureValidJson({ ok: false }), - }; + throw new Error(`No speak handler registered for your session '${callerAgentId}'`); } - const outcome = await handler({ + await handler({ text: args.text, callerAgentId, signal: context?.signal, }); return { - content: outcome - ? [{ type: "text", text: `Audio ${outcome.reason}. Continue in the chat.` }] - : [], - structuredContent: ensureValidJson({ ok: !outcome }), + content: [], + structuredContent: ensureValidJson({ ok: true }), }; }, ); diff --git a/packages/server/src/server/agent/tts-manager.test.ts b/packages/server/src/server/agent/tts-manager.test.ts index 98da7af9aa4..6dfc198306e 100644 --- a/packages/server/src/server/agent/tts-manager.test.ts +++ b/packages/server/src/server/agent/tts-manager.test.ts @@ -213,92 +213,14 @@ describe("TTSManager", () => { expect(firstChunkId).not.toBeNull(); }); - const interrupted = expect(task).rejects.toThrow("Speech playback interrupted"); abort.abort(); - await interrupted; + await task; await vi.waitFor(() => { expect(destroyed.length).toBeGreaterThanOrEqual(2); }); }); - it("rejects missing playback acknowledgements and permits a later speech call", async () => { - vi.useFakeTimers(); - try { - const manager = new TTSManager("s1", pino({ level: "silent" }), new FakeTts()); - const emitted = vi.fn(); - const task = manager.generateAndWaitForPlayback( - "hello", - emitted, - new AbortController().signal, - true, - ); - const failure = expect(task).rejects.toThrow("Audio playback confirmation timed out"); - await vi.waitFor(() => expect(emitted).toHaveBeenCalledOnce()); - await vi.advanceTimersByTimeAsync(120_000); - await failure; - - await manager.generateAndWaitForPlayback( - "recovered", - (msg) => { - if (msg.type === "audio_output") manager.confirmAudioPlayed(msg.payload.id); - }, - new AbortController().signal, - true, - ); - } finally { - vi.useRealTimers(); - } - }); - - it("propagates client playback failures to the speech caller", async () => { - const manager = new TTSManager("s1", pino({ level: "silent" }), new FakeTts()); - await expect( - manager.generateAndWaitForPlayback( - "hello", - (msg) => { - if (msg.type === "audio_output") { - manager.confirmAudioPlayed(msg.payload.id, "native output unavailable"); - } - }, - new AbortController().signal, - true, - ), - ).rejects.toThrow("Audio playback failed: native output unavailable"); - }); - - it("rejects canceled playback rather than returning speech success", async () => { - const manager = new TTSManager("s1", pino({ level: "silent" }), new FakeTts()); - await expect( - manager.generateAndWaitForPlayback( - "hello", - () => manager.cancelPendingPlaybacks("client disconnected"), - new AbortController().signal, - true, - ), - ).rejects.toThrow("Speech playback interrupted: client disconnected"); - }); - - it("rejects a disconnected output sink and releases its playback timer", async () => { - vi.useFakeTimers(); - try { - const manager = new TTSManager("s1", pino({ level: "silent" }), new FakeTts()); - await expect( - manager.generateAndWaitForPlayback( - "hello", - () => { - throw new Error("Voice output has no connected client"); - }, - new AbortController().signal, - true, - ), - ).rejects.toThrow("Voice output has no connected client"); - expect(vi.getTimerCount()).toBe(0); - } finally { - vi.useRealTimers(); - } - }); - it("does not emit unhandled rejections when stream iteration fails", async () => { const unhandled: unknown[] = []; const onUnhandled = (reason: unknown) => { diff --git a/packages/server/src/server/agent/tts-manager.ts b/packages/server/src/server/agent/tts-manager.ts index 37b1af9f084..ee6c7470199 100644 --- a/packages/server/src/server/agent/tts-manager.ts +++ b/packages/server/src/server/agent/tts-manager.ts @@ -30,17 +30,6 @@ type PreparedSegmentResult = const MAX_TTS_SEGMENT_CHARS = 260; const TTS_PREFETCH_SEGMENTS = 2; const CLOSED_AUDIO_ID_TTL_MS = 10_000; -const PLAYBACK_CONFIRMATION_TIMEOUT_MS = 120_000; - -export class AudioPlaybackError extends Error { - constructor( - public readonly reason: "interrupted" | "timeout" | "client_error", - message: string, - ) { - super(message); - this.name = "AudioPlaybackError"; - } -} function splitOversizedFragment(fragment: string, maxChars: number): string[] { const trimmed = fragment.trim(); @@ -203,7 +192,8 @@ export class TTSManager { try { for (const segment of segments) { if (abortSignal.aborted) { - throw new AudioPlaybackError("interrupted", "Speech playback interrupted"); + this.logger.debug("Aborted before emitting segmented audio"); + return; } const synthWaitStart = Date.now(); @@ -213,7 +203,7 @@ export class TTSManager { scheduleNextSegments(); if (result.kind === "aborted") { - throw new AudioPlaybackError("interrupted", "Speech playback interrupted"); + return; } if (result.kind === "error") { @@ -369,9 +359,6 @@ export class TTSManager { playbackResolve = resolve; playbackReject = reject; }); - // Cancellation/cleanup can reject while we are still collecting the stream. - // The rejection is rethrown by the await below once collection finishes. - void playbackPromise.catch(() => undefined); const pendingPlayback: PendingPlayback = { resolve: playbackResolve, @@ -383,7 +370,6 @@ export class TTSManager { this.pendingPlaybacks.set(audioId, pendingPlayback); let onAbort: (() => void) | undefined; - let playbackTimeout: ReturnType | undefined; onAbort = () => { this.logger.debug("Aborted while waiting for playback"); @@ -391,12 +377,11 @@ export class TTSManager { pendingPlayback.pendingChunks = 0; this.pendingPlaybacks.delete(audioId); this.rememberClosedAudioId(audioId); - playbackReject(new AudioPlaybackError("interrupted", "Speech playback interrupted")); + playbackResolve(); this.destroySpeechStream(stream); }; abortSignal.addEventListener("abort", onAbort, { once: true }); - if (abortSignal.aborted) onAbort(); try { const buffers: Buffer[] = []; @@ -412,18 +397,6 @@ export class TTSManager { const fullBuffer = Buffer.concat(buffers); const chunkId = `${audioId}:0`; pendingPlayback.pendingChunks = 1; - playbackTimeout = setTimeout(() => { - playbackReject( - new AudioPlaybackError( - "timeout", - "Audio playback confirmation timed out; the client did not confirm audio output", - ), - ); - }, PLAYBACK_CONFIRMATION_TIMEOUT_MS); - this.logger.info( - { audioId, chunkId, audioBytes: fullBuffer.length, format }, - "Emitting TTS audio; waiting for playback confirmation", - ); emitMessage({ type: "audio_output", @@ -450,20 +423,23 @@ export class TTSManager { await playbackPromise; } catch (error) { if (abortSignal.aborted) { - throw new AudioPlaybackError("interrupted", "Speech playback interrupted"); + this.logger.debug("Audio stream closed after abort"); + } else { + this.logger.error({ err: error }, "Error streaming audio"); + this.pendingPlaybacks.delete(audioId); + throw error; } - this.logger.error({ err: error, audioId }, "Audio output failed"); - throw error; } finally { - clearTimeout(playbackTimeout); - this.pendingPlaybacks.delete(audioId); - this.rememberClosedAudioId(audioId); if (onAbort) { abortSignal.removeEventListener("abort", onAbort); } this.destroySpeechStream(stream); } + if (abortSignal.aborted) { + return; + } + this.logger.debug({ audioId, textLength: text.length }, "Audio playback confirmed"); } @@ -471,7 +447,7 @@ export class TTSManager { * Called when client confirms audio playback completed * Resolves the corresponding promise */ - public confirmAudioPlayed(chunkId: string, error?: string): void { + public confirmAudioPlayed(chunkId: string): void { const [audioId] = chunkId.includes(":") ? chunkId.split(":") : [chunkId]; const pending = this.pendingPlaybacks.get(audioId); @@ -487,13 +463,6 @@ export class TTSManager { return; } - if (error !== undefined) { - pending.reject(new AudioPlaybackError("client_error", `Audio playback failed: ${error}`)); - this.pendingPlaybacks.delete(audioId); - this.rememberClosedAudioId(audioId); - return; - } - pending.pendingChunks = Math.max(0, pending.pendingChunks - 1); if (pending.pendingChunks === 0 && pending.streamEnded) { @@ -517,9 +486,7 @@ export class TTSManager { ); for (const [audioId, pending] of this.pendingPlaybacks.entries()) { - pending.reject( - new AudioPlaybackError("interrupted", `Speech playback interrupted: ${reason}`), - ); + pending.resolve(); this.pendingPlaybacks.delete(audioId); this.rememberClosedAudioId(audioId); this.logger.debug({ audioId }, "Cleared pending playback"); diff --git a/packages/server/src/server/authorization/operation-permissions.ts b/packages/server/src/server/authorization/operation-permissions.ts index 7c7656e0e5e..ea6f94ac1e5 100644 --- a/packages/server/src/server/authorization/operation-permissions.ts +++ b/packages/server/src/server/authorization/operation-permissions.ts @@ -16,7 +16,6 @@ const INBOUND_PERMISSION = { "hosts.route.frame.request": null, "hosts.route.close.request": null, abort_request: "workspace.write", - "agent.artifacts.scan.request": "workspace.read", "agent.config.apply.request": ["workspace.write", "hub.execute"], "agent.detach.request": "workspace.write", "agent.provider.detach.request": "workspace.write", @@ -25,14 +24,6 @@ const INBOUND_PERMISSION = { "agent.background_work.list.request": "workspace.read", "agent.background_work.stop.request": ["workspace.write", "hub.execute"], "agent.provider_subagents.timeline.get.request": "workspace.read", - "agent.queue.delete.request": "workspace.write", - "agent.queue.enqueue.request": "workspace.write", - "agent.queue.get_item_images.request": "workspace.read", - "agent.queue.list.request": "workspace.read", - "agent.queue.reorder.request": "workspace.write", - "agent.queue.retry.request": "workspace.write", - "agent.queue.send_now.request": "workspace.write", - "agent.queue.update.request": "workspace.write", "agent.rewind.request": "workspace.write", "agent.side_conversation.ask.request": "workspace.write", "agent.side_conversation.list.request": "workspace.read", @@ -223,10 +214,7 @@ const INBOUND_PERMISSION = { unsubscribe_terminal_request: "workspace.read", unsubscribe_terminals_request: "workspace.read", update_agent_request: "workspace.write", - // COMPAT(companionStreamPortV1): added in v0.11.0-beta.3-fork, remove after 2027-04-01. - "agent.companion.update_entry.request": "workspace.write", validate_branch_request: "workspace.read", - "voice.input.receipts.read.request": "workspace.read", voice_audio_chunk: "workspace.write", wait_for_finish_request: "workspace.read", "workspace.clear_attention.request": "workspace.write", @@ -265,9 +253,6 @@ const OUTBOUND_PERMISSION = { "hosts.route.open.response": null, "hosts.route.frame": null, "hosts.route.closed": null, - // COMPAT(companionStreamPortV1): added in v0.11.0-beta.3-fork, remove after 2027-04-01. - "agent.companion.update_entry.response": "workspace.write", - "agent.artifacts.scan.response": "workspace.read", "agent.create.response": ["workspace.write", "hub.execute"], "agent.create.update": ["workspace.write", "hub.execute"], "workspace.create.update": "workspace.manage", @@ -283,15 +268,6 @@ const OUTBOUND_PERMISSION = { "agent.background_work.list.response": "workspace.read", "agent.background_work.stop.response": ["workspace.write", "hub.execute"], "agent.background_work.update": "workspace.read", - "agent.queue.delete.response": "workspace.write", - "agent.queue.enqueue.response": "workspace.write", - "agent.queue.get_item_images.response": "workspace.read", - "agent.queue.list.response": "workspace.read", - "agent.queue.reorder.response": "workspace.write", - "agent.queue.retry.response": "workspace.write", - "agent.queue.send_now.response": "workspace.write", - "agent.queue.update": "workspace.read", - "agent.queue.update.response": "workspace.write", "agent.rewind.response": "workspace.write", "agent.side_conversation.ask.response": "workspace.write", "agent.side_conversation.list.response": "workspace.read", @@ -480,7 +456,6 @@ const OUTBOUND_PERMISSION = { "speech.local_models.download.response": "daemon.manage", "speech.local_models.delete.response": "daemon.manage", set_voice_mode_response: "workspace.write", - "voice.input.receipts.read.response": "workspace.read", start_workspace_script_response: "workspace.write", stash_list_response: "workspace.read", stash_pop_response: "workspace.read", diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index bacf4d4b533..d9dbcc59d2e 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -162,8 +162,6 @@ import { } from "./workspace-registry.js"; import { CheckoutDiffManager } from "./checkout-diff-manager.js"; import { ScheduleService } from "./schedule/service.js"; -import { AgentQueueService } from "./agent-queue/service.js"; -import { AgentQueueStore } from "./agent-queue/store.js"; import { DaemonConfigStore, type MutableDaemonConfig } from "./daemon-config-store.js"; import { createOrchestrationSkills } from "./orchestration-skills/index.js"; import { @@ -1484,16 +1482,6 @@ export async function createPaseoDaemon( } }); logger.info({ elapsed: elapsed() }, "Schedule service initialized"); - // The durable agent message queue: constructed here so it loads persisted - // state, but activated only once the server accepts connections — loading - // and dispatching stay separate phases (AgentQueueService.activate). - const agentQueueService = new AgentQueueService({ - store: new AgentQueueStore(path.join(config.paseoHome, "queues")), - agentManager, - agentStorage, - logger, - }); - logger.info({ elapsed: elapsed() }, "Agent message queue initialized"); logger.info({ elapsed: elapsed() }, "Loading persisted agent registry"); // Startup loads persisted agent history once before restoring the registry. const persistedRecords = await agentStorage.listAll(); @@ -1923,7 +1911,6 @@ export async function createPaseoDaemon( pluginRuntime, orchestrationSkills, workspaceLabelService, - agentQueueService, ); pluginRuntime.bindPaseoSessionHost(wsServer); await pluginRuntime.start(); @@ -1932,7 +1919,6 @@ export async function createPaseoDaemon( await finishSubscriptions.start(); wsServer.beginAcceptingConnections(); const relaySecurityLogger = logger.child({ module: "relay-security" }); - await agentQueueService.activate(); relayRuntime = createRelayRuntime({ config: { enabled: relayEnabled, @@ -2051,7 +2037,6 @@ export async function createPaseoDaemon( } await speechService.stop(); await scheduleService.stop().catch(() => undefined); - agentQueueService.stop(); await relayRuntime?.stop().catch(() => undefined); if (wsServer) { await wsServer.close(); diff --git a/packages/server/src/server/daemon-e2e/agent-queue-mirroring.e2e.test.ts b/packages/server/src/server/daemon-e2e/agent-queue-mirroring.e2e.test.ts deleted file mode 100644 index 5b7a2bd26fd..00000000000 --- a/packages/server/src/server/daemon-e2e/agent-queue-mirroring.e2e.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { describe, test, expect, beforeEach, afterEach } from "vitest"; -import type { AgentQueueSnapshot, SessionOutboundMessage } from "@getpaseo/protocol/messages"; -import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js"; -import { DaemonClient } from "../test-utils/daemon-client.js"; -import { createMessageCollector, type MessageCollector } from "../test-utils/message-collector.js"; - -/** - * Two independent clients against one daemon queue, on the fake provider - * harness (no real provider credentials). Covers the composer-facing contract - * from docs/queue-mirroring.md: cross-client mirroring of enqueue, update, - * reorder and delete, durability across a client reconnect, and receipt-driven - * delivery that leaves exactly one canonical user row. - * - * The agent is parked mid-turn on a fake permission request, which is what - * keeps a queue item pending while both clients mutate it. - */ - -const CODEX_TEST_MODEL = "gpt-5.4-mini"; -const CODEX_TEST_THINKING_OPTION_ID = "low"; - -async function waitFor( - poll: () => T | undefined, - description: string, - timeoutMs = 15000, -): Promise { - const deadline = Date.now() + timeoutMs; - for (;;) { - const result = poll(); - if (result !== undefined) { - return result; - } - if (Date.now() > deadline) { - throw new Error(`Timed out waiting for ${description}`); - } - await new Promise((resolve) => setTimeout(resolve, 50)); - } -} - -function queueEvents(collector: MessageCollector, agentId: string): AgentQueueSnapshot[] { - return collector.messages - .filter( - (message): message is Extract => - message.type === "agent.queue.update" && message.payload.agentId === agentId, - ) - .map((message) => message.payload); -} - -function permissionRequestFrom(collector: MessageCollector, agentId: string) { - const message = collector.messages.find( - (candidate) => - candidate.type === "agent_permission_request" && candidate.payload.agentId === agentId, - ); - return message?.type === "agent_permission_request" ? message.payload.request : undefined; -} - -function snapshotWithItemCount(collector: MessageCollector, agentId: string, count: number) { - return queueEvents(collector, agentId).find((snapshot) => snapshot.items.length === count); -} - -function snapshotAtOrPastRevision( - collector: MessageCollector, - agentId: string, - revision: number, - itemCount: number, -) { - return queueEvents(collector, agentId).find( - (snapshot) => snapshot.revision >= revision && snapshot.items.length === itemCount, - ); -} - -function snapshotWithItemOrder( - collector: MessageCollector, - agentId: string, - revision: number, - itemIds: string[], -) { - const expected = itemIds.join(","); - return queueEvents(collector, agentId).find( - (snapshot) => - snapshot.revision >= revision && snapshot.items.map((item) => item.id).join(",") === expected, - ); -} - -async function waitForEmptyQueue( - collector: MessageCollector, - agentId: string, - afterRevision: number, -): Promise { - return await waitFor( - () => - queueEvents(collector, agentId).find( - (snapshot) => snapshot.items.length === 0 && snapshot.revision > afterRevision, - ), - `an empty queue snapshot for ${agentId} past revision ${afterRevision}`, - ); -} - -describe("agent queue mirroring e2e", () => { - let ctx: DaemonTestContext; - let clientB: DaemonClient; - let collectorA: MessageCollector; - let collectorB: MessageCollector; - let feedsA: ReturnType; - let feedsB: ReturnType; - - beforeEach(async () => { - ctx = await createDaemonTestContext(); - clientB = new DaemonClient({ - url: `ws://127.0.0.1:${ctx.daemon.port}/ws`, - appVersion: "0.1.70", - }); - await clientB.connect(); - await clientB.fetchAgents({ subscribe: {} }); - collectorA = createMessageCollector(ctx.client); - collectorB = createMessageCollector(clientB); - // Subscribable events: permission requests park the fake turn, and queue - // snapshots broadcast to subscribed capable clients — the app's session - // context subscribes to exactly these two feeds. - feedsA = ctx.client.observeEvents(["agent_permission_request", "agent.queue.update"], { - notifications: true, - }); - feedsB = clientB.observeEvents(["agent_permission_request", "agent.queue.update"], { - notifications: true, - }); - await Promise.all([feedsA.ready, feedsB.ready]); - }); - - afterEach(async () => { - await Promise.all([feedsA.release(), feedsB.release()]); - collectorA.unsubscribe(); - collectorB.unsubscribe(); - await ctx.cleanup(); - }, 60000); - - test("mirrors enqueue, update, reorder and delete between two clients and drains to one canonical row", async () => { - const agent = await ctx.client.createAgent({ - provider: "codex", - model: CODEX_TEST_MODEL, - thinkingOptionId: CODEX_TEST_THINKING_OPTION_ID, - cwd: "/tmp", - title: "Queue mirroring", - }); - - // Park the turn on a permission request so the queue item stays pending. - await ctx.client.sendMessage(agent.id, 'printf "ok" > permission.txt'); - const permissionRequest = await waitFor( - () => permissionRequestFrom(collectorA, agent.id), - "the fake permission request", - ); - - // Client B admits a prompt into the daemon queue while the agent is busy. - const enqueued = await clientB.enqueueAgentMessage({ - agentId: agent.id, - itemId: "item-1", - text: "first", - intent: "queue", - }); - expect(enqueued.items.map((item) => item.id)).toEqual(["item-1"]); - expect(enqueued.items[0]?.deliveryState).toBe("pending"); - - // Client A, which never sent anything, sees the same queue. - const mirrored = await waitFor( - () => snapshotAtOrPastRevision(collectorA, agent.id, enqueued.revision, 1), - "client A to mirror the enqueue", - ); - expect(mirrored.items[0]?.text).toBe("first"); - - // Client B edits the item in place; both devices converge on the new text. - const updated = await clientB.updateQueuedAgentMessage({ - agentId: agent.id, - itemId: "item-1", - text: "first (edited)", - expectedRevision: mirrored.revision, - }); - expect(updated.items[0]?.text).toBe("first (edited)"); - - // A second item from client A, then a reorder from client B. - await ctx.client.enqueueAgentMessage({ - agentId: agent.id, - itemId: "item-2", - text: "second", - intent: "queue", - }); - const withTwo = await waitFor( - () => snapshotWithItemCount(collectorB, agent.id, 2), - "client B to mirror the second item", - ); - const reordered = await clientB.reorderQueuedAgentMessages( - agent.id, - ["item-2", "item-1"], - withTwo.revision, - ); - expect(reordered.items.map((item) => item.id)).toEqual(["item-2", "item-1"]); - - const mirroredOrder = await waitFor( - () => snapshotWithItemOrder(collectorA, agent.id, reordered.revision, ["item-2", "item-1"]), - "client A to mirror the reorder", - ); - - // A reconnecting client reads the same durable queue, then stays connected - // so the drain below can be observed on a client that never queued anything. - await ctx.client.close(); - const reconnected = new DaemonClient({ - url: `ws://127.0.0.1:${ctx.daemon.port}/ws`, - appVersion: "0.1.70", - }); - let reconnectedCollector: MessageCollector | null = null; - try { - await reconnected.connect(); - await reconnected.fetchAgents({ subscribe: {} }); - const reconnectedFeeds = reconnected.observeEvents( - ["agent_permission_request", "agent.queue.update"], - { notifications: true }, - ); - await reconnectedFeeds.ready; - reconnectedCollector = createMessageCollector(reconnected); - const listed = await reconnected.listQueuedAgentMessages(agent.id); - expect(listed.items.map((item) => item.id)).toEqual(["item-2", "item-1"]); - expect(listed.items[1]?.text).toBe("first (edited)"); - - // Discard the second item; the first drains when the parked turn ends. - const afterDelete = await clientB.deleteQueuedAgentMessage( - agent.id, - "item-2", - mirroredOrder.revision, - ); - expect(afterDelete.items.map((item) => item.id)).toEqual(["item-1"]); - - clientB.respondToPermission(agent.id, permissionRequest.id, { - behavior: "allow", - }); - await clientB.waitForFinish(agent.id, 60000); - - // The delivered item is gone from the queue on both live clients. - await waitForEmptyQueue(collectorB, agent.id, afterDelete.revision); - const drainedElsewhere = await waitForEmptyQueue( - reconnectedCollector, - agent.id, - afterDelete.revision, - ); - expect(drainedElsewhere.items).toEqual([]); - - // Delivery created exactly one canonical user row, carrying the edited - // text — not the original admission, and not a duplicate per device. - const timeline = await reconnected.fetchAgentTimeline(agent.id, { - projection: "canonical", - }); - const userRows = timeline.entries.filter( - (entry) => entry.item.type === "user_message" && entry.item.text.includes("(edited)"), - ); - expect(userRows).toHaveLength(1); - } finally { - reconnectedCollector?.unsubscribe(); - await reconnected.close(); - } - }, 120000); - - test("rejects a stale revision with queue_revision_conflict instead of overwriting", async () => { - const agent = await ctx.client.createAgent({ - provider: "codex", - model: CODEX_TEST_MODEL, - thinkingOptionId: CODEX_TEST_THINKING_OPTION_ID, - cwd: "/tmp", - title: "Queue conflicts", - }); - - await ctx.client.sendMessage(agent.id, 'printf "ok" > permission.txt'); - await waitFor(() => permissionRequestFrom(collectorA, agent.id), "the fake permission request"); - - const enqueued = await clientB.enqueueAgentMessage({ - agentId: agent.id, - itemId: "item-1", - text: "original", - intent: "queue", - }); - - // Client A mutates first; client B's write still carries the older revision. - await ctx.client.updateQueuedAgentMessage({ - agentId: agent.id, - itemId: "item-1", - text: "edited elsewhere", - expectedRevision: enqueued.revision, - }); - - await expect( - clientB.updateQueuedAgentMessage({ - agentId: agent.id, - itemId: "item-1", - text: "stale overwrite", - expectedRevision: enqueued.revision, - }), - ).rejects.toThrow("queue_revision_conflict"); - - const listed = await clientB.listQueuedAgentMessages(agent.id); - expect(listed.items[0]?.text).toBe("edited elsewhere"); - }, 120000); -}); diff --git a/packages/server/src/server/hub/daemon-executions.test.ts b/packages/server/src/server/hub/daemon-executions.test.ts index ff8ff742aa1..65c2a9617bd 100644 --- a/packages/server/src/server/hub/daemon-executions.test.ts +++ b/packages/server/src/server/hub/daemon-executions.test.ts @@ -260,9 +260,7 @@ test("a failed Hub create removes its auto-created worktree", async () => { test("failed Hub creates release their lifecycle subscriptions", async () => { const hub = await launchRelationship(); - // Closed setup clients may expire during the test. Track the new lifecycle - // subscriptions directly so unrelated WebSocket cleanup cannot hide a leak. - const activeNewSubscriptions = hub.trackNewAgentSubscriptions(); + const subscriptionBaseline = hub.agentSubscriptionCount(); hub.failProviderPromptStart(); hub.beginOwnedCreate("failed-prompt-create-1", "failed-prompt-execution-1", { @@ -277,7 +275,7 @@ test("failed Hub creates release their lifecycle subscriptions", async () => { expect(hub.activeOwnedAgentIds()).toEqual([]); expect(await hub.durableOwnedAgentIds()).toEqual([]); expect(await hub.listedWorktrees()).toHaveLength(1); - expect(activeNewSubscriptions()).toBe(0); + expect(hub.agentSubscriptionCount()).toBe(subscriptionBaseline); hub.failProviderPromptStart(); hub.beginOwnedCreate("failed-prompt-create-2", "failed-prompt-execution-2"); @@ -290,7 +288,7 @@ test("failed Hub creates release their lifecycle subscriptions", async () => { expect(hub.activeOwnedAgentIds()).toEqual([]); expect(await hub.durableOwnedAgentIds()).toEqual([]); expect(await hub.listedWorktrees()).toHaveLength(1); - expect(activeNewSubscriptions()).toBe(0); + expect(hub.agentSubscriptionCount()).toBe(subscriptionBaseline); }); test("failed Hub create cleans durable state when provider close rejects", async () => { diff --git a/packages/server/src/server/hub/test-utils/relationship-harness.ts b/packages/server/src/server/hub/test-utils/relationship-harness.ts index 892d493e298..a0c02bbb12a 100644 --- a/packages/server/src/server/hub/test-utils/relationship-harness.ts +++ b/packages/server/src/server/hub/test-utils/relationship-harness.ts @@ -911,20 +911,8 @@ export class HubRelationshipHarness { return this.daemon!.agentManager.getAgent(agentId) !== null && !record?.archivedAt; } - trackNewAgentSubscriptions(): () => number { - const manager = this.daemon!.agentManager; - const subscribe = manager.subscribe.bind(manager); - const active = new Set(); - manager.subscribe = (listener, options) => { - const token = {}; - active.add(token); - const release = subscribe(listener, options); - return () => { - active.delete(token); - release(); - }; - }; - return () => active.size; + agentSubscriptionCount(): number { + return this.daemon!.agentManager.subscriptionCount(); } async hubExecutionIntentFiles(): Promise { diff --git a/packages/server/src/server/message-receipts/index.test.ts b/packages/server/src/server/message-receipts/index.test.ts index 44390941c16..10c1615a6a0 100644 --- a/packages/server/src/server/message-receipts/index.test.ts +++ b/packages/server/src/server/message-receipts/index.test.ts @@ -75,175 +75,3 @@ test("failed local message preparation does not leave an ambiguous receipt", asy await requests.send(input); expect(sends).toBe(1); }); - -test("voice receipts remain readable after more than 100 later deliveries", async () => { - const { requests, directory } = await fixture(); - const input = { - agentId: "agent", - messageId: "attachment:first#1", - attachment: { - messageId: "attachment:first", - attachmentId: "attachment", - voiceOwner: "owner", - createdAt: "2026-10-02T12:00:00.000Z", - }, - request: { text: "first" }, - send: async () => {}, - }; - await requests.send(input); - for (let index = 0; index < 101; index++) { - await requests.send({ - ...input, - messageId: `other:${index}#1`, - attachment: undefined, - request: { text: `${index}` }, - }); - } - const reopened = new MessageReceipts(directory); - expect(await reopened.outcome("agent", "attachment:first#1")).toBe("completed"); - expect(await reopened.outcome("agent", "attachment:first")).toBe("completed"); - const outcomes = await reopened.listForAttachment({ - agentId: "agent", - attachmentId: "attachment", - voiceOwner: "owner", - }); - // Later non-attachment deliveries never enter this attachment's records. - expect(outcomes).toHaveLength(1); - expect(outcomes[0]).toMatchObject({ messageId: "attachment:first", state: "completed" }); -}); - -test("known reservation loss clears the pending receipt but provider ambiguity does not", async () => { - const { requests, directory } = await fixture(); - const busy = Object.assign(new Error("busy"), { code: "AGENT_RUN_BUSY" }); - const input = { - agentId: "agent", - messageId: "retryable#1", - request: { text: "follow up" }, - send: async () => { - throw busy; - }, - }; - await expect(requests.send(input)).rejects.toThrow("busy"); - expect(await new MessageReceipts(directory).outcome("agent", "retryable#1")).toBeNull(); - await requests.send({ ...input, send: async () => {} }); - expect(await requests.outcome("agent", "retryable#1")).toBe("completed"); -}); - -test("attachment receipts retain client authority across owner reconstruction", async () => { - const { requests, directory } = await fixture(); - await requests.send({ - agentId: "agent", - messageId: "attachment:one#1", - attachment: { - messageId: "attachment:one", - attachmentId: "attachment", - voiceOwner: "principal/client-a", - }, - request: {}, - send: async () => {}, - }); - const reopened = new MessageReceipts(directory); - expect( - await reopened.listForAttachment({ - agentId: "agent", - attachmentId: "attachment", - voiceOwner: "principal/client-b", - }), - ).toEqual([]); - expect( - await reopened.listForAttachment({ - agentId: "agent", - attachmentId: "attachment", - voiceOwner: "principal/client-a", - }), - ).toHaveLength(1); -}); - -test("in-flight dispatch is reported as sending, and removal waits for it", async () => { - const { requests } = await fixture(); - const input = { - agentId: "agent", - messageId: "attachment:one#1", - attachment: { messageId: "attachment:one", attachmentId: "attachment" }, - request: {}, - }; - let release!: () => void; - let entered!: () => void; - const started = new Promise((resolve) => { - entered = resolve; - }); - const barrier = new Promise((resolve) => { - release = resolve; - }); - const pending = requests.send({ - ...input, - send: async () => { - entered(); - await barrier; - }, - }); - await started; - expect( - (await requests.listForAttachment({ agentId: "agent", attachmentId: "attachment" }))[0]?.state, - ).toBe("sending"); - release(); - await pending; - expect( - (await requests.listForAttachment({ agentId: "agent", attachmentId: "attachment" }))[0]?.state, - ).toBe("completed"); -}); - -test("a removed marker makes re-admitting the same speech id a no-op", async () => { - const { requests, directory } = await fixture(); - expect( - await requests.recordRemoved({ - agentId: "agent", - messageId: "attachment:gone", - attachmentId: "attachment", - voiceOwner: "owner", - createdAt: "2026-10-02T12:00:00.000Z", - }), - ).toBe(true); - const reopened = new MessageReceipts(directory); - expect(await reopened.outcome("agent", "attachment:gone")).toBe("removed"); - expect( - await reopened.recordRemoved({ - agentId: "agent", - messageId: "attachment:gone", - attachmentId: "attachment", - voiceOwner: "owner", - }), - ).toBe(true); - const outcomes = await reopened.listForAttachment({ - agentId: "agent", - attachmentId: "attachment", - voiceOwner: "owner", - }); - expect(outcomes).toHaveLength(1); - expect(outcomes[0]).toMatchObject({ messageId: "attachment:gone", state: "removed" }); -}); - -test("completed logical speech wins over an older ambiguous attempt", async () => { - const { requests, directory } = await fixture(); - const input = { - agentId: "agent", - messageId: "speech#1", - request: {}, - attachment: { messageId: "speech", attachmentId: "attachment", voiceOwner: "owner" }, - send: async () => { - throw new Error("unknown provider outcome"); - }, - }; - await expect(requests.send(input)).rejects.toThrow("unknown provider outcome"); - // Represents a user's explicit reconciliation and retry, not an automatic replay. - await requests.send({ ...input, messageId: "speech#2", send: async () => {} }); - const reopened = new MessageReceipts(directory); - expect(await reopened.outcome("agent", "speech")).toBe("completed"); - expect( - await reopened.listForAttachment({ - agentId: "agent", - attachmentId: "attachment", - voiceOwner: "owner", - }), - ).toEqual([expect.objectContaining({ messageId: "speech", state: "completed" })]); -}); diff --git a/packages/server/src/server/message-receipts/index.ts b/packages/server/src/server/message-receipts/index.ts index c5d7c29122b..6103160b12d 100644 --- a/packages/server/src/server/message-receipts/index.ts +++ b/packages/server/src/server/message-receipts/index.ts @@ -1,36 +1,18 @@ import { createHash } from "node:crypto"; -import { readFile, readdir, rm } from "node:fs/promises"; +import { readFile } from "node:fs/promises"; import path from "node:path"; import { z } from "zod"; import { writeJsonFileAtomic } from "../atomic-file.js"; const ReceiptSchema = z.object({ fingerprint: z.string(), - state: z.enum(["pending", "completed", "removed"]), + state: z.enum(["pending", "completed"]), agentId: z.string(), - /** Queue item id a voice receipt belongs to; absent on legacy direct-send receipts. */ - messageId: z.string().optional(), - attachmentId: z.string().optional(), - voiceOwner: z.string().optional(), - createdAt: z.string().optional(), }); -interface VoiceInputReceipt { - messageId: string; - state: "pending" | "sending" | "completed" | "removed"; - createdAt: string; -} - interface SendMessageInput { agentId: string; messageId: string; request: unknown; - /** Voice delivery metadata recorded on the receipt for attachment reads. */ - attachment?: { - messageId: string; - attachmentId: string; - voiceOwner?: string; - createdAt?: string; - }; send: () => Promise; prepare?: () => Promise; } @@ -38,8 +20,6 @@ interface SendMessageInput { /** Owns message delivery receipts; creation is owned by CreationService. */ export class MessageReceipts { private readonly pending = new Map>(); - /** Logical message ids with a dispatch in flight, for attachment read state. */ - private readonly sending = new Set(); constructor(private readonly directory: string) {} send(input: SendMessageInput): Promise { @@ -50,177 +30,28 @@ export class MessageReceipts { this.sendOnce(key, input), ); this.pending.set(key, result); - if (input.attachment) this.sending.add(`${input.agentId}\u0000${input.attachment.messageId}`); void result .finally(() => { if (this.pending.get(key) === result) this.pending.delete(key); - if (input.attachment) - this.sending.delete(`${input.agentId}\u0000${input.attachment.messageId}`); }) .catch(() => undefined); return result; } - /** - * The persisted outcome of a send, without sending: `null` when no receipt - * exists. Startup recovery for queued dispatch claims reads this to tell a - * never-dispatched attempt from one whose provider acceptance is unknown. - * `removed` marks speech the user deleted; re-admitting its id is a no-op. - */ - async outcome( - agentId: string, - messageId: string, - ): Promise<"pending" | "completed" | "removed" | null> { - const key = digest(["send", agentId, messageId]); - const file = path.join(this.directory, `${key}.json`); - try { - const existing = await readReceipt(file); - return existing?.state ?? null; - } catch { - // An unreadable receipt is no evidence; the caller holds the claim as - // ambiguous instead of resending. - return null; - } - } - - /** - * Delivery records for one voice attachment, newest-context per message. Only - * receipts carrying the attachment metadata answer; legacy direct sends and - * typed queue attempts are invisible here. - */ - async listForAttachment(input: { - agentId: string; - attachmentId: string; - voiceOwner?: string; - }): Promise { - const files = await readdir(this.directory).catch((error: unknown) => { - if (error instanceof Error && "code" in error && error.code === "ENOENT") return []; - throw error; - }); - const records = await Promise.all( - files - .filter((name) => name.endsWith(".json")) - .map((name) => readReceipt(path.join(this.directory, name))), - ); - const byId = new Map(); - const priority = { pending: 0, sending: 1, completed: 2, removed: 3 }; - for (const record of records) { - if ( - !record || - record.agentId !== input.agentId || - record.attachmentId !== input.attachmentId || - record.voiceOwner !== input.voiceOwner || - !record.messageId - ) - continue; - const state = - record.state === "pending" && this.sending.has(`${record.agentId}\u0000${record.messageId}`) - ? "sending" - : record.state; - const previous = byId.get(record.messageId); - if (previous && priority[previous.state] >= priority[state]) continue; - byId.set(record.messageId, { - messageId: record.messageId, - state, - createdAt: record.createdAt ?? "", - }); - } - return [...byId.values()]; - } - - /** - * Records that one queued item was deleted before delivery, so a later - * admission of the same speech id stays removed. Refuses while a dispatch is - * in flight — the outcome is not the user's to declare yet. - */ - async recordRemoved(input: { - agentId: string; - messageId: string; - attachmentId?: string; - voiceOwner?: string; - createdAt?: string; - }): Promise { - const key = digest(["send", input.agentId, input.messageId]); - const previous = this.pending.get(key); - const result = (previous ? previous.catch(() => undefined) : Promise.resolve()).then( - async () => { - const file = path.join(this.directory, `${key}.json`); - const existing = await readReceipt(file); - if (existing) { - return existing.state === "removed"; - } - await writeJsonFileAtomic(file, { - fingerprint: digest({ removed: true }), - state: "removed", - agentId: input.agentId, - messageId: input.messageId, - ...(input.attachmentId - ? { attachmentId: input.attachmentId, voiceOwner: input.voiceOwner } - : {}), - createdAt: input.createdAt ?? new Date().toISOString(), - }); - return true; - }, - ); - const tracked = result.then(() => undefined); - void tracked.catch(() => undefined); - this.pending.set(key, tracked); - try { - return await result; - } finally { - if (this.pending.get(key) === tracked) this.pending.delete(key); - } - } - private async sendOnce(key: string, input: SendMessageInput): Promise { const file = path.join(this.directory, `${key}.json`); const fingerprint = digest(input.request); const existing = await readReceipt(file); if (existing) { if (existing.fingerprint !== fingerprint) throw new Error("agent_request_key_conflict"); - if (existing.state === "completed" || existing.state === "removed") return; + if (existing.state === "completed") return; // A provider may have accepted the message before its receipt was committed. throw new Error("agent_request_outcome_unknown"); } await input.prepare?.(); - const receipt = { - fingerprint, - agentId: input.agentId, - ...(input.attachment - ? { - messageId: input.attachment.messageId, - attachmentId: input.attachment.attachmentId, - ...(input.attachment.voiceOwner ? { voiceOwner: input.attachment.voiceOwner } : {}), - createdAt: input.attachment.createdAt ?? new Date().toISOString(), - } - : {}), - }; + const receipt = { fingerprint, agentId: input.agentId }; await writeJsonFileAtomic(file, { ...receipt, state: "pending" }); - try { - await input.send(); - } catch (error) { - // A competing run rejected the synchronous reservation before provider - // dispatch. This is the only post-receipt error safe to retry: the - // receipt would otherwise make the next attempt look ambiguous. - if ( - error instanceof Error && - "code" in error && - (error.code === "AGENT_RUN_BUSY" || error.code === "AGENT_PROMPT_NOT_SUBMITTED") - ) { - await rm(file, { force: true }); - } - throw error; - } - if (input.attachment && input.attachment.messageId !== input.messageId) { - // Keep the logical speech identity after the queue's bounded drained-id - // window expires. Write this before completing the attempt so a crash - // cannot drain the queue without retaining the logical identity. - const logicalKey = digest(["send", input.agentId, input.attachment.messageId]); - await writeJsonFileAtomic(path.join(this.directory, `${logicalKey}.json`), { - ...receipt, - state: "completed", - }); - } + await input.send(); await writeJsonFileAtomic(file, { ...receipt, state: "completed" }); } } diff --git a/packages/server/src/server/persistence-hooks.ts b/packages/server/src/server/persistence-hooks.ts index 0e0d47ed585..9d60d9e249d 100644 --- a/packages/server/src/server/persistence-hooks.ts +++ b/packages/server/src/server/persistence-hooks.ts @@ -141,8 +141,6 @@ export function extractTimestamps(record: StoredAgentRecord): { workspaceId?: string; owner?: StoredAgentRecord["owner"]; background?: boolean; - artifacts?: StoredAgentRecord["artifacts"]; - companionEntries?: StoredAgentRecord["companionEntries"]; } { return { createdAt: new Date(record.createdAt), @@ -153,8 +151,6 @@ export function extractTimestamps(record: StoredAgentRecord): { workspaceId: record.workspaceId, owner: record.owner, background: record.background, - artifacts: record.artifacts, - companionEntries: record.companionEntries, }; } diff --git a/packages/server/src/server/session.test.ts b/packages/server/src/server/session.test.ts index 22716485006..14625dd00f1 100644 --- a/packages/server/src/server/session.test.ts +++ b/packages/server/src/server/session.test.ts @@ -7,7 +7,6 @@ import { createMessageReceiptsStub, createTestCreationService, } from "./test-utils/session-stubs.js"; -import { EventEmitter } from "node:events"; import { execSync } from "child_process"; import { existsSync, @@ -42,11 +41,7 @@ import { terminalWorkerDirectory, writeTerminalCleanupRecord, } from "../terminal/terminal-worker-record.js"; -import { - OWNER_PERMISSIONS, - SessionAuthorization, - type DaemonPermission, -} from "./authorization/index.js"; +import { OWNER_PERMISSIONS, type DaemonPermission } from "./authorization/index.js"; import { DownloadTokenStore } from "./file-download/token-store.js"; import { StructuredAgentFallbackError } from "./agent/agent-response-loop.js"; import type { StoredAgentRecord } from "./agent/agent-storage.js"; @@ -232,161 +227,15 @@ test("side conversation ask reports archived agents unavailable without loading ]); }); -test("voice attach, abort, transport loss and detach never touch the agent", async () => { - const agentId = "11111111-1111-4111-8111-111111111111"; - const messages: SessionOutboundMessage[] = []; - const mutating = { - cancelAgentRun: vi.fn(), - streamAgent: vi.fn(), - steerOrReplaceActiveTurn: vi.fn(), - replaceAgentRun: vi.fn(), - respondToPermission: vi.fn(), - askSideQuestion: vi.fn(), - }; - const session = createSessionForTest({ - messages, - agentManager: { - getAgent: vi.fn(() => ({ id: agentId, provider: "codex", lifecycle: "running" })), - ...mutating, - }, - }); - - // Attach fails cleanly here (the test session has no speech providers), which - // is itself part of the contract: a failed attach must not disturb the run. - await session.handleMessage({ type: "set_voice_mode", enabled: true, agentId, requestId: "v1" }); - await session.handleMessage({ - type: "voice_audio_chunk", - audio: "AA==", - format: "audio/pcm;rate=16000;bits=16", - isLast: false, - }); - await session.handleMessage({ type: "abort_request" }); - await session.handleMessage({ type: "set_voice_mode", enabled: false, requestId: "v2" }); - - for (const [name, fn] of Object.entries(mutating)) { - expect(fn, name).not.toHaveBeenCalled(); - } - // The stop still acknowledges so the client's detach completes. - expect(messages).toContainEqual( - expect.objectContaining({ - type: "set_voice_mode_response", - payload: expect.objectContaining({ requestId: "v2", enabled: false, accepted: true }), - }), - ); -}); - -test("successful voice attach, STT failure and transport loss preserve work and scope receipts", async () => { - class SpeechStream extends EventEmitter { - requiredSampleRate = 16000; - async connect() {} - appendPcm16() {} - commit() {} - clear() {} - close() { - this.removeAllListeners(); - } - flush() {} - reset() {} - } - const agentId = "11111111-1111-4111-8111-111111111111"; - const permission = { id: "pending-permission" }; - const child = { id: "child", lifecycle: "running" }; - const sideConversation = { threadId: "side-thread", messages: ["independent question"] }; - const agent = { - id: agentId, - provider: "codex", - lifecycle: "running", - activeForegroundTurnId: "running-turn", - config: {}, - pendingPermissions: new Map([[permission.id, permission]]), - }; - const mutations = { - cancelAgentRun: vi.fn(), - reloadAgentSession: vi.fn(), - replaceAgentRun: vi.fn(), - respondToPermission: vi.fn(), - askSideQuestion: vi.fn(), - archiveAgent: vi.fn(), - clearAgentHistory: vi.fn(), - streamAgent: vi.fn(), - }; - const recognizer = new SpeechStream(); - const detector = new SpeechStream(); - const messages: SessionOutboundMessage[] = []; - const listForAttachment = vi.fn(async () => []); - const session = createSessionForTest({ - messages, - voiceOwner: "principal/client", - messageReceipts: { send: (input) => input.send(), listForAttachment }, - agentManager: { - getAgent: vi.fn((id: string) => (id === child.id ? child : agent)), - listAgents: vi.fn(() => [agent, child]), - waitForAgentClose: vi.fn(async () => {}), - ...mutations, - }, - stt: { id: "local", createSession: () => recognizer }, - voice: { turnDetection: { id: "local", createSession: () => detector } }, - voiceBridge: { registerVoiceSpeakHandler: () => "generation" }, - }); - const source = {}; - session.updateClientCapabilities({ [CLIENT_CAPS.ownedSubscriptions]: true }, source); - const attach = { - type: "set_voice_mode" as const, - enabled: true, - agentId, - attachmentId: "attachment", - requestId: "attach", - }; - await session.handleMessage(attach, source); - expect(messages).toContainEqual( - expect.objectContaining({ - type: "set_voice_mode_response", - payload: expect.objectContaining({ accepted: true, generation: "generation" }), - }), - ); - await session.handleMessage( - { - type: "voice.input.receipts.read.request", - agentId, - attachmentId: "attachment", - generation: "generation", - requestId: "receipts", - }, - source, - ); - expect(listForAttachment).toHaveBeenCalledWith({ - agentId, - attachmentId: "attachment", - voiceOwner: "principal/client", - }); - recognizer.emit("error", new Error("recognizer failed")); - await session.handleMessage( - { type: "abort_request", attachmentId: "attachment", generation: "generation" }, - source, - ); - await session.handleMessage({ ...attach, enabled: false, generation: "generation" }, source); - await session.handleMessage(attach, source); - session.clearAgentTimelineSubscription(source); - await vi.waitFor(() => expect(recognizer.listenerCount("transcript")).toBe(0)); - expect(agent.activeForegroundTurnId).toBe("running-turn"); - expect([...agent.pendingPermissions.values()]).toEqual([permission]); - expect(child).toEqual({ id: "child", lifecycle: "running" }); - expect(sideConversation.messages).toEqual(["independent question"]); - for (const method of Object.values(mutations)) expect(method).not.toHaveBeenCalled(); - await session.cleanup(); -}); - function captureAgentManagerEvents(): { subscribe: ReturnType; dispatch: (event: AgentManagerEvent) => void; - activeCount: () => number; } { - const callbacks = new Set<(event: AgentManagerEvent) => void>(); + const callbacks: Array<(event: AgentManagerEvent) => void> = []; return { - activeCount: () => callbacks.size, subscribe: vi.fn((callback: (event: AgentManagerEvent) => void) => { - callbacks.add(callback); - return () => callbacks.delete(callback); + callbacks.push(callback); + return () => {}; }), dispatch: (event) => { for (const callback of callbacks) callback(event); @@ -501,7 +350,6 @@ test("side conversation updates and removals reach a subscribed modern source", { [CLIENT_CAPS.ownedSubscriptions]: true, [CLIENT_CAPS.sideConversations]: true }, socket, ); - expect(events.activeCount()).toBe(0); await session.handleMessage( { type: "session.events.set_subscription.request", @@ -510,7 +358,6 @@ test("side conversation updates and removals reach a subscribed modern source", }, socket, ); - expect(events.activeCount()).toBe(1); targetedMessages.length = 0; events.dispatch({ @@ -546,17 +393,6 @@ test("side conversation updates and removals reach a subscribed modern source", } // The proof-carrying lane replaces the legacy broadcast for modern sources. expect(messages).toEqual([]); - const subscriptionId = targetedMessages[0]!.message.payload.subscriptionId; - await session.handleMessage( - { - type: "subscription.release.request", - requestId: "release-side-conversation-events", - subscriptionId, - }, - socket, - ); - expect(events.activeCount()).toBe(0); - await session.cleanup(); }); test("side conversation removals skip a subscribed modern source without the capability", async () => { @@ -681,115 +517,6 @@ test("a released side conversation subscription stops receiving removals", async expect(targetedMessages).toEqual([]); }); -test.each([true, false])( - "side conversation delivery respects each source capability (capable source last: %s)", - async (capableLast) => { - const messages: SessionOutboundMessage[] = []; - const targetedMessages: Array<{ source: object; message: SessionOutboundMessage }> = []; - const events = captureAgentManagerEvents(); - const session = createSessionForTest({ - messages, - targetedMessages, - agentManager: { subscribe: events.subscribe }, - }); - const capableSource = {}; - const otherCapableSource = {}; - const incapableSource = {}; - const sources = capableLast - ? [incapableSource, capableSource, otherCapableSource] - : [capableSource, otherCapableSource, incapableSource]; - for (const source of sources) { - session.updateClientCapabilities( - { - [CLIENT_CAPS.ownedSubscriptions]: true, - [CLIENT_CAPS.sideConversations]: source !== incapableSource, - }, - source, - ); - } - // The modern lane is capability plus subscription. Every source subscribes here, including the - // incapable one, so the case proves capability decides rather than the subscription alone. - for (const [index, source] of sources.entries()) { - await session.handleMessage( - { - type: "session.events.set_subscription.request", - requestId: `side-conversation-capability-${index}`, - events: ["agent.side_conversation.update", "agent.side_conversation.removed"], - }, - source, - ); - } - // The subscription responses are not what this case asserts. - targetedMessages.length = 0; - - events.dispatch({ - type: "side_conversation", - event: { type: "update", record: SIDE_CONVERSATION_RECORD }, - }); - expect(messages).toEqual([]); - expect(targetedMessages).toEqual( - [capableSource, otherCapableSource].map((source) => ({ - source, - message: { - type: "agent.side_conversation.update", - payload: { ...SIDE_CONVERSATION_SNAPSHOT, subscriptionId: expect.any(String) }, - }, - })), - ); - - // Release, not capability: detaching the first capable source drops its subscriptions, and only - // the second one still hears about the removal. - session.clearAgentTimelineSubscription(capableSource); - targetedMessages.length = 0; - events.dispatch({ - type: "side_conversation", - event: { - type: "remove", - parentAgentId: SIDE_CONVERSATION_RECORD.parentAgentId, - threadId: SIDE_CONVERSATION_RECORD.threadId, - }, - }); - expect(targetedMessages).toEqual([ - { - source: otherCapableSource, - message: { - type: "agent.side_conversation.removed", - payload: { - parentAgentId: SIDE_CONVERSATION_RECORD.parentAgentId, - threadId: SIDE_CONVERSATION_RECORD.threadId, - subscriptionId: expect.any(String), - }, - }, - }, - ]); - session.clearAgentTimelineSubscription(otherCapableSource); - session.clearAgentTimelineSubscription(incapableSource); - targetedMessages.length = 0; - events.dispatch({ - type: "side_conversation", - event: { type: "update", record: SIDE_CONVERSATION_RECORD }, - }); - expect(messages).toEqual([]); - expect(targetedMessages).toEqual([]); - await session.cleanup(); - }, -); - -test("side conversation events stop when the client removes its capability", async () => { - const messages: SessionOutboundMessage[] = []; - const events = captureAgentManagerEvents(); - const session = createSessionForTest({ messages, agentManager: { subscribe: events.subscribe } }); - session.updateClientCapabilities({ [CLIENT_CAPS.sideConversations]: true }); - session.updateClientCapabilities({}); - - events.dispatch({ - type: "side_conversation", - event: { type: "update", record: SIDE_CONVERSATION_RECORD }, - }); - expect(messages).toEqual([]); - await session.cleanup(); -}); - test("side conversation ask leaves the update broadcast to the manager", async () => { const agentId = SIDE_CONVERSATION_RECORD.parentAgentId; const messages: SessionOutboundMessage[] = []; @@ -1027,12 +754,7 @@ interface SessionForTestOptions { workspaceRuntimeStore?: WorkspaceRuntimeStore; sendToSource?: SessionOptions["onMessageToSource"]; clientId?: string; - voiceOwner?: SessionOptions["voiceOwner"]; - voiceBridge?: SessionOptions["voiceBridge"]; - messageReceipts?: SessionOptions["messageReceipts"]; - clientCapabilities?: Record; permissions?: readonly DaemonPermission[]; - agentQueueService?: SessionOptions["agentQueueService"]; agentManager?: { [K in keyof SessionOptions["agentManager"]]?: unknown }; agentStorage?: { [K in keyof SessionOptions["agentStorage"]]?: unknown }; github?: Partial; @@ -1111,14 +833,10 @@ function createSessionForTest(options: SessionForTestOptions = {}): Session { const sessionOptions: SessionOptions = { workspaceRuntimeStore: options.workspaceRuntimeStore ?? createWorkspaceRuntimeStore(), - messageReceipts: options.messageReceipts ?? createMessageReceiptsStub(), + messageReceipts: createMessageReceiptsStub(), agentMessages: createAgentMessageDeliveryStub(), creationService: createTestCreationService(), clientId: options.clientId ?? "test-client", - voiceOwner: options.voiceOwner, - voiceBridge: options.voiceBridge, - clientCapabilities: options.clientCapabilities, - agentQueueService: options.agentQueueService, onMessage: (message) => messages.push(message), ...(options.targetedMessages ? { @@ -1130,6 +848,7 @@ function createSessionForTest(options: SessionForTestOptions = {}): Session { messages.push(message), }), onBinaryMessage: createBinaryMessageHandler(options.binaryMessages), + clientCapabilities: options.clientCapabilities, logger, downloadTokenStore: options.downloadTokenStore ?? asDownloadTokenStore(), pushNotifications: options.pushNotifications ?? asPushNotifications(), @@ -1689,30 +1408,6 @@ describe("session authorization permissions", () => { ]); }); - test("rejects a base-ref change without workspace.write", async () => { - const messages: SessionOutboundMessage[] = []; - const session = createSessionForTest({ permissions: ["hub.execute"], messages }); - - await session.handleMessage({ - type: "checkout.base_ref.set.request", - requestId: "base-ref-denied", - cwd: "/tmp/repo", - baseRef: "origin/main", - }); - - expect(messages).toEqual([ - { - type: "rpc_error", - payload: { - requestId: "base-ref-denied", - requestType: "checkout.base_ref.set.request", - error: "Session is not authorized for checkout.base_ref.set.request", - code: "access_denied", - }, - }, - ]); - }); - test("replaces a session's permissions without reconstructing the session", async () => { const messages: SessionOutboundMessage[] = []; const session = createSessionForTest({ permissions: ["hub.execute"], messages }); @@ -7104,472 +6799,3 @@ test("does not publish internal agents' background work to subscribed clients", }); expect(messages.some((message) => message.type === "agent.background_work.update")).toBe(false); }); - -test("a legacy send_agent_message_request never reaches the queue service", async () => { - const agentId = "11111111-1111-4111-8111-111111111111"; - const messages: SessionOutboundMessage[] = []; - const { AgentQueueService } = await import("./agent-queue/service.js"); - const { AgentQueueStore } = await import("./agent-queue/store.js"); - const queueDir = mkdtempSync(join(tmpdir(), "session-legacy-send-queue-")); - try { - const queueService = new AgentQueueService({ - store: new AgentQueueStore(queueDir), - agentManager: asAgentManager({}), - agentStorage: asAgentStorage({ - get: vi.fn().mockResolvedValue(undefined), - }), - logger: pino({ level: "silent" }), - sendPrompt: vi.fn(async () => ({})), - }); - const session = createSessionForTest({ - messages, - agentQueueService: queueService, - agentManager: { - listAgents: vi.fn(() => [{ id: agentId }]), - getAgent: vi.fn(() => ({ - id: agentId, - provider: "codex", - lifecycle: "idle", - pendingPermissions: new Set(), - })), - hasInFlightRun: vi.fn(() => false), - tryRunOutOfBand: vi.fn(() => false), - streamAgent: vi.fn(() => (async function* () {})()), - waitForAgentRunStart: vi.fn(async () => {}), - waitForAgentClose: vi.fn(async () => {}), - reloadStalePluginSession: vi.fn(async () => {}), - }, - agentStorage: { - get: vi.fn().mockResolvedValue({ id: agentId, provider: "codex", cwd: "/tmp/x" }), - list: vi.fn().mockResolvedValue([{ id: agentId, provider: "codex", cwd: "/tmp/x" }]), - }, - }); - - await session.handleMessage({ - type: "send_agent_message_request", - requestId: "legacy-1", - agentId, - text: "keep working", - messageId: "legacy-msg-1", - }); - - // The released response shape, produced by the receipt-backed legacy path. - expect(messages).toEqual([ - { - type: "send_agent_message_response", - payload: { requestId: "legacy-1", agentId, accepted: true, error: null }, - }, - ]); - // Queue admission never happened and nothing was stored. - expect((await queueService.list(agentId)).items).toEqual([]); - } finally { - rmSync(queueDir, { recursive: true, force: true }); - } -}); - -test("agent.queue.enqueue.request admits through the queue service and mirrors the update on the subscribed lane", async () => { - const agentId = "11111111-1111-4111-8111-111111111111"; - const messages: SessionOutboundMessage[] = []; - const targetedMessages: Array<{ source: object; message: SessionOutboundMessage }> = []; - const { AgentQueueService } = await import("./agent-queue/service.js"); - const { AgentQueueStore } = await import("./agent-queue/store.js"); - const queueDir = mkdtempSync(join(tmpdir(), "session-queue-rpc-")); - try { - const queueService = new AgentQueueService({ - store: new AgentQueueStore(queueDir), - agentManager: asAgentManager({}), - agentStorage: asAgentStorage({ get: vi.fn().mockResolvedValue(undefined) }), - logger: pino({ level: "silent" }), - sendPrompt: vi.fn(async () => ({})), - }); - const session = createSessionForTest({ - messages, - targetedMessages, - agentQueueService: queueService, - clientCapabilities: { [CLIENT_CAPS.durableAgentQueue]: true }, - agentManager: { - listAgents: vi.fn(() => [{ id: agentId }]), - // Proven handler dependency: without it the enqueue request answers with - // `rpc_error: Request failed: createStub: "getAgent" was called but not stubbed`, so the - // case never reaches its response. - getAgent: vi.fn(() => ({ - id: agentId, - provider: "codex", - lifecycle: "idle", - pendingPermissions: new Set(), - })), - }, - agentStorage: { - get: vi.fn().mockResolvedValue(undefined), - list: vi.fn().mockResolvedValue([{ id: agentId, provider: "codex", cwd: "/tmp/x" }]), - }, - }); - // The shipped client advertises owned subscriptions and asks for the queue selector, so the - // response is correlated back to it and the update travels on the same proof-carrying lane. - const socket = {}; - session.updateClientCapabilities( - { [CLIENT_CAPS.ownedSubscriptions]: true, [CLIENT_CAPS.durableAgentQueue]: true }, - socket, - ); - await session.handleMessage( - { - type: "session.events.set_subscription.request", - requestId: "queue-subscription", - events: ["agent.queue.update"], - }, - socket, - ); - targetedMessages.length = 0; - - await session.handleMessage( - { - type: "agent.queue.enqueue.request", - requestId: "q-1", - agentId, - itemId: "item-1", - text: "queued from the phone", - intent: "queue", - }, - socket, - ); - - const delivered = targetedMessages - .filter(({ source }) => source === socket) - .map(({ message }) => message); - const response = delivered.find( - (message) => message.type === "agent.queue.enqueue.response", - ) as Extract; - expect(response.payload.requestId).toBe("q-1"); - expect(response.payload.error).toBeNull(); - expect(response.payload.queue?.items[0]).toMatchObject({ - id: "item-1", - text: "queued from the phone", - intent: "queue", - deliveryState: "pending", - }); - - // The update is the subscribed, proof-carrying copy, asserted independently of the response. - const update = delivered.find((message) => message.type === "agent.queue.update") as Extract< - SessionOutboundMessage, - { type: "agent.queue.update" } - >; - expect(update.payload.items.map((item) => item.id)).toEqual(["item-1"]); - expect(update.payload.subscriptionId).toEqual(expect.any(String)); - } finally { - rmSync(queueDir, { recursive: true, force: true }); - } -}); - -test("agent.queue.update reaches only the capable sources that subscribed", async () => { - const agentId = "11111111-1111-4111-8111-111111111111"; - const messages: SessionOutboundMessage[] = []; - const targetedMessages: Array<{ source: object; message: SessionOutboundMessage }> = []; - const { AgentQueueService } = await import("./agent-queue/service.js"); - const { AgentQueueStore } = await import("./agent-queue/store.js"); - const queueDir = mkdtempSync(join(tmpdir(), "session-queue-subscription-")); - try { - const queueService = new AgentQueueService({ - store: new AgentQueueStore(queueDir), - agentManager: asAgentManager({}), - agentStorage: asAgentStorage({ get: vi.fn().mockResolvedValue(undefined) }), - logger: pino({ level: "silent" }), - sendPrompt: vi.fn(async () => ({})), - }); - const session = createSessionForTest({ - messages, - targetedMessages, - agentQueueService: queueService, - agentManager: { - listAgents: vi.fn(() => [{ id: agentId }]), - // Proven dependency for every enqueue path: without it the request answers with - // `rpc_error: createStub: "getAgent" was called but not stubbed` and no update is emitted. - getAgent: vi.fn(() => ({ - id: agentId, - provider: "codex", - lifecycle: "idle", - pendingPermissions: new Set(), - })), - }, - agentStorage: { - get: vi.fn().mockResolvedValue(undefined), - list: vi.fn().mockResolvedValue([{ id: agentId, provider: "codex", cwd: "/tmp/x" }]), - }, - }); - - const subscribed = {}; - const unsubscribed = {}; - const incapable = {}; - const later = {}; - for (const [index, source] of [subscribed, unsubscribed, incapable].entries()) { - session.updateClientCapabilities( - { - [CLIENT_CAPS.ownedSubscriptions]: true, - [CLIENT_CAPS.durableAgentQueue]: source !== incapable, - }, - source, - ); - if (source !== unsubscribed) { - await session.handleMessage( - { - type: "session.events.set_subscription.request", - requestId: `queue-subscription-${index}`, - events: ["agent.queue.update"], - }, - source, - ); - } - } - - const enqueue = (requestId: string) => - session.handleMessage({ - type: "agent.queue.enqueue.request", - requestId, - agentId, - itemId: `item-${requestId}`, - text: `queued ${requestId}`, - intent: "queue", - }); - const queueUpdates = () => - targetedMessages.filter(({ message }) => message.type === "agent.queue.update"); - // Read the subscribe acknowledgement before the list is cleared for the delivery assertions. - const acknowledgement = targetedMessages.find( - ({ source: owner, message }) => - owner === subscribed && - message.type === "session.events.set_subscription.response" && - message.payload.requestId === "queue-subscription-0", - )?.message; - if (acknowledgement?.type !== "session.events.set_subscription.response") { - throw new Error("Missing queue-subscription-0 acknowledgement"); - } - const subscribedSubscriptionId = acknowledgement.payload.subscriptionId; - - // The owner principal is permitted to have these delivered; the queue update is not a - // privileged message that a narrower principal would be denied. - expect( - new SessionAuthorization(OWNER_PERMISSIONS).allowsOutbound({ - type: "agent.queue.update", - } as SessionOutboundMessage), - ).toBe(true); - - targetedMessages.length = 0; - await enqueue("q-1"); - // Capability is not enough: only the source that asked for the selector hears the update, and - // neither the unsubscribed nor the incapable source does. - expect(queueUpdates().map(({ source }) => source)).toEqual([subscribed]); - const initialUpdate = queueUpdates().find(({ source }) => source === subscribed)?.message; - if (initialUpdate?.type !== "agent.queue.update") { - throw new Error("Missing emitted queue update for subscribed source"); - } - expect(session.delivery.permits(subscribed, initialUpdate)).toBe(true); - expect(session.delivery.permits(unsubscribed, initialUpdate)).toBe(false); - expect(session.delivery.permits(incapable, initialUpdate)).toBe(false); - - // Explicit release through the protocol, distinct from detaching a source: the subscription id - // from the subscribe response stops delivery while the source keeps its capability. - await session.handleMessage( - { - type: "subscription.release.request", - requestId: "queue-release", - subscriptionId: subscribedSubscriptionId, - }, - subscribed, - ); - targetedMessages.length = 0; - await enqueue("q-2"); - expect(queueUpdates()).toEqual([]); - expect(session.delivery.permits(subscribed, initialUpdate)).toBe(false); - - // A later source that subscribes joins without disturbing anyone else. - session.updateClientCapabilities( - { [CLIENT_CAPS.ownedSubscriptions]: true, [CLIENT_CAPS.durableAgentQueue]: true }, - later, - ); - await session.handleMessage( - { - type: "session.events.set_subscription.request", - requestId: "queue-subscription-later", - events: ["agent.queue.update"], - }, - later, - ); - targetedMessages.length = 0; - await enqueue("q-3"); - expect(queueUpdates().map(({ source }) => source)).toEqual([later]); - - // Downgrade: dropping the capability stops delivery, restoring it resumes. - session.updateClientCapabilities({ [CLIENT_CAPS.ownedSubscriptions]: true }, later); - targetedMessages.length = 0; - await enqueue("q-4"); - expect(queueUpdates()).toEqual([]); - session.updateClientCapabilities( - { [CLIENT_CAPS.ownedSubscriptions]: true, [CLIENT_CAPS.durableAgentQueue]: true }, - later, - ); - targetedMessages.length = 0; - await enqueue("q-5"); - expect(queueUpdates().map(({ source }) => source)).toEqual([later]); - } finally { - rmSync(queueDir, { recursive: true, force: true }); - } -}); - -test("a legacy client receives the queue update through its capability alone", async () => { - const agentId = "11111111-1111-4111-8111-111111111111"; - const messages: SessionOutboundMessage[] = []; - const targetedMessages: Array<{ source: object; message: SessionOutboundMessage }> = []; - const { AgentQueueService } = await import("./agent-queue/service.js"); - const { AgentQueueStore } = await import("./agent-queue/store.js"); - const queueDir = mkdtempSync(join(tmpdir(), "session-queue-legacy-")); - try { - const queueService = new AgentQueueService({ - store: new AgentQueueStore(queueDir), - agentManager: asAgentManager({}), - agentStorage: asAgentStorage({ get: vi.fn().mockResolvedValue(undefined) }), - logger: pino({ level: "silent" }), - sendPrompt: vi.fn(async () => ({})), - }); - const session = createSessionForTest({ - messages, - targetedMessages, - agentQueueService: queueService, - agentManager: { - listAgents: vi.fn(() => [{ id: agentId }]), - // Same proven dependency as the subscribed case: the enqueue path resolves the agent. - getAgent: vi.fn(() => ({ - id: agentId, - provider: "codex", - lifecycle: "idle", - pendingPermissions: new Set(), - })), - }, - agentStorage: { - get: vi.fn().mockResolvedValue(undefined), - list: vi.fn().mockResolvedValue([{ id: agentId, provider: "codex", cwd: "/tmp/x" }]), - }, - }); - // No ownedSubscriptions: this is the pre-owned-subscription client shape, so the update - // reaches it through the capability-gated broadcast lane instead of a subscription. - const legacyCapable = {}; - const legacyIncapable = {}; - session.updateClientCapabilities({ [CLIENT_CAPS.durableAgentQueue]: true }, legacyCapable); - session.updateClientCapabilities({}, legacyIncapable); - - await session.handleMessage( - { - type: "agent.queue.enqueue.request", - requestId: "q-legacy", - agentId, - itemId: "item-legacy", - text: "queued from a legacy client", - intent: "queue", - }, - legacyCapable, - ); - - const updates = targetedMessages.filter(({ message }) => message.type === "agent.queue.update"); - expect(updates.map(({ source }) => source)).toEqual([legacyCapable]); - expect(updates[0]?.message).toMatchObject({ - payload: { items: [expect.objectContaining({ id: "item-legacy" })] }, - }); - } finally { - rmSync(queueDir, { recursive: true, force: true }); - } -}); - -test("a client without the durableAgentQueue capability never sees the queue broadcast", async () => { - const agentId = "11111111-1111-4111-8111-111111111111"; - const messages: SessionOutboundMessage[] = []; - const { AgentQueueService } = await import("./agent-queue/service.js"); - const { AgentQueueStore } = await import("./agent-queue/store.js"); - const queueDir = mkdtempSync(join(tmpdir(), "session-queue-gate-")); - try { - const queueService = new AgentQueueService({ - store: new AgentQueueStore(queueDir), - agentManager: asAgentManager({}), - agentStorage: asAgentStorage({ get: vi.fn().mockResolvedValue(undefined) }), - logger: pino({ level: "silent" }), - sendPrompt: vi.fn(async () => ({})), - }); - const session = createSessionForTest({ - messages, - agentQueueService: queueService, - agentManager: { - listAgents: vi.fn(() => [{ id: agentId }]), - // Proven dependency for the enqueue path, as in the subscribed case. - getAgent: vi.fn(() => ({ - id: agentId, - provider: "codex", - lifecycle: "idle", - pendingPermissions: new Set(), - })), - }, - agentStorage: { - get: vi.fn().mockResolvedValue(undefined), - list: vi.fn().mockResolvedValue([{ id: agentId, provider: "codex", cwd: "/tmp/x" }]), - }, - }); - - await session.handleMessage({ - type: "agent.queue.enqueue.request", - requestId: "q-1", - agentId, - itemId: "item-1", - text: "hidden from old clients", - intent: "queue", - }); - - expect(messages.some((message) => message.type === "agent.queue.update")).toBe(false); - expect(messages.some((message) => message.type === "agent.queue.enqueue.response")).toBe(true); - } finally { - rmSync(queueDir, { recursive: true, force: true }); - } -}); - -test("delete_agent_request removes the agent's queue through the lifecycle", async () => { - const agentId = "11111111-1111-4111-8111-111111111111"; - const messages: SessionOutboundMessage[] = []; - const { AgentQueueService } = await import("./agent-queue/service.js"); - const { AgentQueueStore } = await import("./agent-queue/store.js"); - const queueDir = mkdtempSync(join(tmpdir(), "session-queue-delete-")); - try { - const queueService = new AgentQueueService({ - store: new AgentQueueStore(queueDir), - agentManager: asAgentManager({}), - agentStorage: asAgentStorage({ get: vi.fn().mockResolvedValue(undefined) }), - logger: pino({ level: "silent" }), - sendPrompt: vi.fn(async () => ({})), - }); - await queueService.enqueue({ - agentId, - itemId: "item-1", - text: "queued", - intent: "queue", - }); - const session = createSessionForTest({ - messages, - agentQueueService: queueService, - agentManager: { - listAgents: vi.fn(() => []), - getAgent: vi.fn(() => null), - deleteAgentState: vi.fn(async () => {}), - flush: vi.fn(async () => {}), - }, - agentStorage: { - get: vi.fn().mockResolvedValue({ id: agentId, provider: "codex", cwd: "/tmp/x" }), - list: vi.fn().mockResolvedValue([]), - remove: vi.fn(async () => {}), - }, - }); - - await session.handleMessage({ - type: "delete_agent_request", - agentId, - requestId: "del-1", - }); - - expect(messages.some((message) => message.type === "agent_deleted")).toBe(true); - expect((await queueService.list(agentId)).items).toEqual([]); - } finally { - rmSync(queueDir, { recursive: true, force: true }); - } -}); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index d35c56e1159..606a00c1776 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -15,11 +15,9 @@ import { searchTimeline } from "./agent/chat-search/index.js"; import type { BrowserToolsBroker } from "./browser-tools/broker.js"; import { BrowserAutomationHostCapabilitySchema } from "@getpaseo/protocol/browser-automation/capabilities"; import type { - AgentCompanionUpdateEntryRequestMessage, SessionEventSubscription, UsageReportEntry, ProviderUsage, - AgentQueueSnapshot, } from "@getpaseo/protocol/messages"; import { relative } from "node:path"; import { isAbsolute } from "node:path"; @@ -39,6 +37,7 @@ import { formatPluginSourceReference } from "@getpaseo/protocol/plugin-source-re import { serializeAgentStreamEvent, type AgentSnapshotPayload, + type AgentAttachment, type FirstAgentContext, type SessionInboundMessage, type SessionOutboundMessage, @@ -83,7 +82,6 @@ import { waitForAgentRunStartWithTimeout, unarchiveAgentState, } from "./agent/agent-prompt.js"; -import { sendOrQueuePromptToAgent } from "./agent-queue/send-or-queue.js"; import { resolveCreateAgentTitles, resolveFirstAgentPromptTitle, @@ -122,7 +120,6 @@ import { } from "./workspace-labels/index.js"; import { AgentManager, AgentRunCancellationError } from "./agent/agent-manager.js"; -import type { AgentQueueService } from "./agent-queue/service.js"; import { buildTimelinePromptIndex } from "./agent/timeline-prompt-index.js"; import { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js"; import type { @@ -148,7 +145,6 @@ import { detachAgentCommand, setAgentModeCommand, updateAgentCommand, - updateCompanionEntryCommand, } from "./agent/lifecycle-command.js"; import { buildStoredAgentPayload, toAgentPayload } from "./agent/agent-projections.js"; import { assertPluginTimelineDataSize } from "./agent/agent-timeline-content.js"; @@ -160,6 +156,7 @@ import { getAgentStreamEventTurnId, type AgentPersistenceHandle, type AgentPermissionResponse, + type AgentRunOptions, type AgentSessionConfig, } from "./agent/agent-sdk-types.js"; import type { StoredAgentRecord } from "./agent/agent-storage.js"; @@ -188,6 +185,7 @@ import { type WorkspaceMutation, type WorkspaceRegistry, } from "./workspace-registry.js"; +import { wrapSpokenInput } from "./voice-config.js"; import { isVoicePermissionAllowed } from "./voice-permission-policy.js"; import { ProjectIconReader, @@ -478,34 +476,12 @@ const nodeSessionFileSystem: SessionFileSystem = { // Stub types for features under development (modules not yet available) type AgentMcpTransportFactory = () => Promise; -/** Collapses an optional injected subsystem to its settled nullable form. */ -function nullable(value?: T | null): T | null { - return value ?? null; -} - -const AGENT_QUEUE_RESPONSE_TYPES = { - "agent.queue.enqueue.request": "agent.queue.enqueue.response", - "agent.queue.update.request": "agent.queue.update.response", - "agent.queue.reorder.request": "agent.queue.reorder.response", - "agent.queue.delete.request": "agent.queue.delete.response", - "agent.queue.retry.request": "agent.queue.retry.response", - "agent.queue.send_now.request": "agent.queue.send_now.response", - "agent.queue.list.request": "agent.queue.list.response", -} as const; - -type AgentQueueRequestMessage = Extract< - SessionInboundMessage, - { type: keyof typeof AGENT_QUEUE_RESPONSE_TYPES } ->; - export interface SessionOptions { connectedHosts?: ConnectedHosts; sourceId?: string; routed?: boolean; browserToolsBroker?: BrowserToolsBroker | null; clientId: string; - /** Principal/client pair that owns this session's spoken input and its receipts. */ - voiceOwner?: string; permissions: readonly DaemonPermission[]; appVersion?: string | null; clientCapabilities?: Record | null; @@ -525,9 +501,7 @@ export interface SessionOptions { worktreesRoot?: string; agentManager: AgentManager; agentStorage: AgentStorage; - /** Absent when the daemon runs without the durable queue (pre-fork peer). */ - agentQueueService?: AgentQueueService | null; - messageReceipts: Pick; + messageReceipts: Pick; agentMessages: AgentMessageDelivery; creationService: Pick; projectRegistry: ProjectRegistry; @@ -624,21 +598,10 @@ export interface SessionOptions { turnDetection?: Resolvable; }; voiceBridge?: { - registerVoiceSpeakHandler?: ( - agentId: string, - attachmentId: string, - handler: VoiceSpeakHandler, - revoke: () => void, - ) => string; - unregisterVoiceSpeakHandler?: (agentId: string, generation: string) => void; - registerVoiceCallerContext?: ( - agentId: string, - generation: string, - context: VoiceCallerContext, - ) => void; - unregisterVoiceCallerContext?: (agentId: string, generation: string) => void; - isCurrent?: (agentId: string, generation: string) => boolean; - hasSpokenInTurn?: (agentId: string, turnId: string) => boolean; + registerVoiceSpeakHandler?: (agentId: string, handler: VoiceSpeakHandler) => void; + unregisterVoiceSpeakHandler?: (agentId: string) => void; + registerVoiceCallerContext?: (agentId: string, context: VoiceCallerContext) => void; + unregisterVoiceCallerContext?: (agentId: string) => void; }; dictation?: { finalTimeoutMs?: number; @@ -822,11 +785,8 @@ export class Session { private readonly browserToolsBroker: SessionOptions["browserToolsBroker"]; private readonly clientId: string; private readonly authorization: SessionAuthorization; - private readonly agentQueueService: AgentQueueService | null; - private unsubscribeAgentQueue: (() => void) | null = null; private appVersion: string | null; private clientCapabilities: ReadonlySet; - private sideConversationDemandWithoutSource = false; private readonly sessionId: string; private readonly onMessage: (msg: SessionOutboundMessage) => void; private readonly onMessageToSource: @@ -868,6 +828,7 @@ export class Session { private readonly pluginRuntime: SessionOptions["pluginRuntime"]; private readonly orchestrationSkills: SessionOptions["orchestrationSkills"]; private unsubscribeAgentEvents: (() => void) | null = null; + private sideConversationDemandWithoutSource = false; private unsubscribeProjectMutations: (() => void) | null = null; private unsubscribePluginChanges: (() => void) | null = null; private unsubscribeWorkspaceMutations: (() => void) | null = null; @@ -929,8 +890,7 @@ export class Session { private readonly daemonSession: DaemonSession; private readonly hubExecutionController: HubExecutionController | null; private readonly workspaceScripts: WorkspaceScriptsService; - private readonly voiceOwner?: string; - private readonly messageReceipts: Pick; + private readonly messageReceipts: Pick; agentMessages: AgentMessageDelivery; private readonly createAgentLifecycleDispatch: CreateAgentLifecycleDispatch; private readonly creationService: Pick; @@ -997,7 +957,6 @@ export class Session { } = options; this.browserToolsBroker = options.browserToolsBroker; this.clientId = clientId; - this.voiceOwner = options.voiceOwner; this.authorization = new SessionAuthorization(permissions); this.appVersion = appVersion ?? null; @@ -1042,8 +1001,6 @@ export class Session { }); this.agentManager = agentManager; this.agentStorage = agentStorage; - this.agentQueueService = nullable(options.agentQueueService); - this.unsubscribeAgentQueue = this.subscribeToAgentQueueMutations(); this.projectRegistry = projectRegistry; this.workspaceRegistry = workspaceRegistry; this.directorySync = resolveDirectorySync(directorySync); @@ -1396,24 +1353,21 @@ export class Session { agentStorage: this.agentStorage, logger: this.sessionLogger, }), - sendSpokenInput: async (agentId, text, messageId) => { - // Speech always takes the durable queue (idle or busy) so its - // acceptance is one identity with truthful receipts. Detaching - // voice never withdraws what was already admitted. - if (!this.agentQueueService) throw new Error("Agent message queue is unavailable"); - await sendOrQueuePromptToAgent({ - agentManager: this.agentManager, - agentStorage: this.agentStorage, - queueService: this.agentQueueService, - logger: this.sessionLogger, + reloadAgentSession: (agentId, overrides) => + this.agentManager.reloadAgentSession(agentId, overrides), + sendSpokenInput: async (agentId, text) => { + await this.handleSendAgentMessage( agentId, - messageId, text, - intent: "queue", - origin: "voice", - voiceOwner: options.voiceOwner, - }); + undefined, + undefined, + undefined, + undefined, + { spokenInput: true }, + ); }, + interruptAgentIfRunning: (agentId) => this.interruptAgentIfRunning(agentId), + hasActiveAgentRun: (agentId) => this.hasActiveAgentRun(agentId), }, logger: this.sessionLogger, sessionId: this.sessionId, @@ -1456,6 +1410,7 @@ export class Session { activity: this.clientSources.get(source)?.activity ?? null, pushToken: this.clientSources.get(source)?.pushToken ?? null, }); + this.refreshObservationProducers(); // COMPAT(ownedSubscriptions): added in v0.8.0, remove capability-driven legacy host registration after 2027-03-09. if ( !this.delivery.isModern(source) && @@ -1477,7 +1432,6 @@ export class Session { } } } - this.refreshObservationProducers(); } clearAgentTimelineSubscription(source: object): void { @@ -1884,6 +1838,13 @@ export class Session { } } + private hasActiveAgentRun(agentId: string | null): boolean { + if (!agentId) { + return false; + } + return this.agentManager.hasInFlightRun(agentId); + } + private handleAgentRunError(agentId: string, error: unknown, context: string): void { const message = errorToFriendlyMessage(error); this.sessionLogger.error({ err: error, agentId, context }, `${context} for agent ${agentId}`); @@ -2306,10 +2267,6 @@ export class Session { return; } - // Attached voice reads the live turn for fallback playback; it observes - // events without owning or disturbing them. - this.voiceSessions.handleAgentEvent(event.agentId, event.event, event); - if ( this.voiceSessions.isActiveForAgent(event.agentId) && event.event.type === "permission_requested" && @@ -3309,10 +3266,6 @@ export class Session { } private dispatchAgentLifecycleMessage(msg: SessionInboundMessage): Promise | undefined { - return this.dispatchAgentQueueMessage(msg) ?? this.dispatchAgentLifecycleOperation(msg); - } - - private dispatchAgentLifecycleOperation(msg: SessionInboundMessage): Promise | undefined { switch (msg.type) { case "fetch_agents_request": return this.handleFetchAgents(msg); @@ -3679,12 +3632,6 @@ export class Session { private async dispatchMiscMessage(msg: SessionInboundMessage): Promise { switch (msg.type) { - case "agent.companion.update_entry.request": - await this.handleCompanionUpdateEntryRequest(msg); - return; - case "agent.artifacts.scan.request": - await this.handleAgentArtifactsScanRequest(msg.agentId, msg.requestId, msg.limit); - return; case "list_commands_request": await this.handleListCommandsRequest(msg); return; @@ -3841,9 +3788,6 @@ export class Session { try { await this.agentStorage.remove(agentId); await this.agentManager.deleteAgentState(agentId); - // Deleting an agent removes its queue through the normal lifecycle; a - // re-created agent with the same id starts from an empty queue. - await this.agentQueueService?.deleteForAgent(agentId); // Directory removal is daemon-wide; agent_deleted below stays a source-scoped RPC reply. if (knownAgent) this.agentManager.notifyAgentRemoved(knownAgent); } catch (error) { @@ -4043,102 +3987,6 @@ export class Session { }; } - private async handleAgentArtifactsScanRequest( - agentId: string, - requestId: string, - limit: number | undefined, - ): Promise { - this.sessionLogger.info( - { agentId, requestId, limit }, - "Scanning agent working dir for artifacts", - ); - try { - // Backfill targets are usually closed agents, which are not resident in - // the manager until something loads them. - await ensureAgentLoaded(agentId, { - agentManager: this.agentManager, - agentStorage: this.agentStorage, - logger: this.sessionLogger, - }); - const result = await this.agentManager.scanAgentArtifacts( - agentId, - limit !== undefined ? { limit } : {}, - ); - this.emit({ - type: "agent.artifacts.scan.response", - payload: { - requestId, - agentId, - accepted: true, - error: null, - addedOrUpdated: result.addedOrUpdated, - total: result.total, - }, - }); - } catch (error) { - this.emit({ - type: "agent.artifacts.scan.response", - payload: { - requestId, - agentId, - accepted: false, - error: error instanceof Error ? error.message : String(error), - addedOrUpdated: 0, - total: 0, - }, - }); - } - } - - // COMPAT(companionStreamPortV1): added in v0.11.0-beta.3-fork, remove after 2027-04-01. - private async handleCompanionUpdateEntryRequest( - msg: AgentCompanionUpdateEntryRequestMessage, - ): Promise { - this.sessionLogger.info( - { - agentId: msg.agentId, - requestId: msg.requestId, - action: msg.action, - }, - "session: agent.companion.update_entry.request", - ); - - let accepted = true; - let error: string | null = null; - try { - const result = await updateCompanionEntryCommand( - { agentManager: this.agentManager }, - { - agentId: msg.agentId, - entryId: msg.entryId, - action: msg.action, - status: msg.status, - text: msg.text, - answerText: msg.answerText, - sourceId: msg.sourceId, - }, - ); - if (!result.accepted) { - accepted = false; - error = result.error ?? "Failed to update companion entry"; - this.sessionLogger.warn({ error }, "Failed to update companion entry"); - } - } catch (err) { - accepted = false; - error = err instanceof Error ? err.message : String(err); - this.sessionLogger.error({ err }, "session: agent.companion.update_entry.request error"); - } - this.emit({ - type: "agent.companion.update_entry.response", - payload: { - requestId: msg.requestId, - agentId: msg.agentId, - accepted, - error, - }, - }); - } - private async handleUpdateAgentRequest( agentId: string, name: string | undefined, @@ -4718,6 +4566,60 @@ export class Session { } } + /** + * Handle text message to agent (with optional image attachments) + */ + private async handleSendAgentMessage( + agentId: string, + text: string, + messageId?: string, + images?: Array<{ data: string; mimeType: string }>, + attachments?: AgentAttachment[], + runOptions?: AgentRunOptions, + options?: { spokenInput?: boolean }, + ): Promise<{ ok: true } | { ok: false; error: string }> { + this.sessionLogger.info( + { + agentId, + textPreview: text.substring(0, 50), + imageCount: images?.length ?? 0, + attachmentCount: attachments?.length ?? 0, + }, + `Sending text to agent ${agentId}${ + images && images.length > 0 ? ` with ${images.length} image attachment(s)` : "" + }${ + attachments && attachments.length > 0 + ? ` and ${attachments.length} structured attachment(s)` + : "" + }`, + ); + + const promptText = options?.spokenInput ? wrapSpokenInput(text) : text; + const prompt = buildAgentPrompt(promptText, images, attachments); + + try { + await sendPromptToAgent({ + agentManager: this.agentManager, + agentStorage: this.agentStorage, + agentId, + prompt, + messageId, + runOptions, + // A typed or spoken message from the human answers any permission the + // agent is blocked on. + clearPendingPermissions: true, + logger: this.sessionLogger, + }); + return { ok: true }; + } catch (error) { + this.handleAgentRunError(agentId, error, "Failed to send agent message"); + return { + ok: false, + error: error instanceof Error ? error.message : String(error), + }; + } + } + /** * Handle create agent request */ @@ -9355,285 +9257,6 @@ export class Session { } } - /** - * Mirrors queue mutations to this session's clients. Delivery is gated per - * source on the durableAgentQueue capability, so a client whose outbound - * union predates the fork never sees an event type it cannot parse. - */ - private subscribeToAgentQueueMutations(): (() => void) | null { - const service = this.agentQueueService; - if (!service) { - return null; - } - return service.subscribeToMutations((snapshot) => { - this.emit({ type: "agent.queue.update", payload: snapshot }); - }); - } - - private dispatchAgentQueueMessage(msg: SessionInboundMessage): Promise | undefined { - if (msg.type === "voice.input.receipts.read.request") { - return this.handleVoiceInputReceiptsRead(msg); - } - if (msg.type === "agent.queue.get_item_images.request") { - return this.handleAgentQueueGetItemImagesRequest(msg); - } - if ((AGENT_QUEUE_RESPONSE_TYPES as Record)[msg.type]) { - return this.handleAgentQueueRequest(msg as AgentQueueRequestMessage); - } - return undefined; - } - - /** - * Answers one voice attachment's delivery receipts: queue presence means - * queued, the receipt record means submitted or removed. The read is scoped - * to the attachment this connection still owns, so a stale device cannot - * poll another device's speech. - */ - private async handleVoiceInputReceiptsRead( - msg: Extract, - ): Promise { - const respond = ( - items: Array<{ - messageId: string; - state: "queued" | "submitted" | "removed" | "unknown"; - createdAt: string; - }>, - nextCursor: string | null, - error: string | null, - ) => - this.emit({ - type: "voice.input.receipts.read.response", - payload: { - requestId: msg.requestId, - agentId: msg.agentId, - attachmentId: msg.attachmentId, - items, - nextCursor, - error, - }, - }); - const resolved = await this.resolveAgentIdentifier(msg.agentId); - if (!resolved.ok) { - respond([], null, resolved.error); - return; - } - if ( - !this.voiceSessions.ownsAttachment( - this.delivery.currentSource, - resolved.agentId, - msg.attachmentId, - msg.generation, - ) - ) { - respond([], null, "Voice attachment is no longer owned by this connection."); - return; - } - try { - const [queue, receipts] = await Promise.all([ - this.agentQueueService?.listVoiceInputs( - resolved.agentId, - msg.attachmentId, - this.voiceOwner, - ), - this.messageReceipts.listForAttachment({ - agentId: resolved.agentId, - attachmentId: msg.attachmentId, - voiceOwner: this.voiceOwner, - }), - ]); - const byId = new Map< - string, - { - messageId: string; - state: "queued" | "submitted" | "removed" | "unknown"; - createdAt: string; - } - >(); - for (const item of queue ?? []) { - const state = - item.deliveryState === "failed" || item.deliveryState === "uncertain" - ? "unknown" - : "queued"; - byId.set(item.id, { messageId: item.id, state, createdAt: item.createdAt }); - } - for (const receipt of receipts) { - let state: "queued" | "submitted" | "removed" | "unknown" = "unknown"; - if (receipt.state === "sending") state = "queued"; - else if (receipt.state === "completed") state = "submitted"; - else if (receipt.state === "removed") state = "removed"; - byId.set(receipt.messageId, { - messageId: receipt.messageId, - state, - createdAt: receipt.createdAt, - }); - } - const all = [...byId.values()].sort( - (a, b) => a.createdAt.localeCompare(b.createdAt) || a.messageId.localeCompare(b.messageId), - ); - const offset = msg.after - ? Math.max(0, all.findIndex((item) => item.messageId === msg.after) + 1) - : 0; - const limit = msg.limit ?? 50; - const page = all.slice(offset, offset + limit); - respond(page, all[offset + limit] ? (page.at(-1)?.messageId ?? null) : null, null); - } catch (error) { - respond([], null, errorToFriendlyMessage(error)); - } - } - - /** - * Queue errors carry a machine-readable code on the response (`error` field) - * so clients can branch on revision conflicts without parsing prose. - */ - private agentQueueErrorText(error: unknown): string { - if (error instanceof Error && "code" in error && typeof error.code === "string") { - return error.code; - } - return errorToFriendlyMessage(error); - } - - private async handleAgentQueueRequest(msg: AgentQueueRequestMessage): Promise { - const responseType = AGENT_QUEUE_RESPONSE_TYPES[msg.type]; - const service = this.agentQueueService; - if (!service) { - this.emit({ - type: responseType, - payload: { - requestId: msg.requestId, - agentId: msg.agentId, - queue: null, - error: "This daemon does not support the durable agent message queue.", - }, - }); - return; - } - - const resolved = await this.resolveAgentIdentifier(msg.agentId); - if (!resolved.ok) { - this.emit({ - type: responseType, - payload: { - requestId: msg.requestId, - agentId: msg.agentId, - queue: null, - error: resolved.error, - }, - }); - return; - } - - const agentId = resolved.agentId; - try { - const queue = await this.applyAgentQueueRequest(service, agentId, msg); - this.emit({ - type: responseType, - payload: { requestId: msg.requestId, agentId, queue, error: null }, - }); - } catch (error) { - this.sessionLogger.warn( - { err: error, agentId, type: msg.type }, - "Agent queue request failed", - ); - this.emit({ - type: responseType, - payload: { - requestId: msg.requestId, - agentId, - queue: null, - error: this.agentQueueErrorText(error), - }, - }); - } - } - - private applyAgentQueueRequest( - service: AgentQueueService, - agentId: string, - msg: AgentQueueRequestMessage, - ): Promise { - switch (msg.type) { - case "agent.queue.enqueue.request": - return service.enqueue({ - agentId, - itemId: msg.itemId, - text: msg.text, - intent: msg.intent, - images: msg.images, - attachments: msg.attachments, - composerAttachments: msg.composerAttachments, - }); - case "agent.queue.update.request": - return service.update(agentId, msg.itemId, msg.expectedRevision, { - text: msg.text, - images: msg.images, - attachments: msg.attachments, - composerAttachments: msg.composerAttachments, - }); - case "agent.queue.reorder.request": - return service.reorder(agentId, msg.itemIds, msg.expectedRevision); - case "agent.queue.delete.request": - return service.remove(agentId, msg.itemId, msg.expectedRevision); - case "agent.queue.retry.request": - return service.retry(agentId, msg.itemId, msg.expectedRevision); - case "agent.queue.send_now.request": - return service.sendNow(agentId, msg.itemId, msg.expectedRevision); - case "agent.queue.list.request": - return service.list(agentId); - } - } - - private async handleAgentQueueGetItemImagesRequest( - msg: Extract, - ): Promise { - const emitError = (agentId: string, error: string) => { - this.emit({ - type: "agent.queue.get_item_images.response", - payload: { - requestId: msg.requestId, - agentId, - itemId: msg.itemId, - images: [], - error, - }, - }); - }; - - const service = this.agentQueueService; - if (!service) { - emitError(msg.agentId, "This daemon does not support the durable agent message queue."); - return; - } - const resolved = await this.resolveAgentIdentifier(msg.agentId); - if (!resolved.ok) { - emitError(msg.agentId, resolved.error); - return; - } - - try { - const images = await service.getItemImages(resolved.agentId, msg.itemId); - this.emit({ - type: "agent.queue.get_item_images.response", - payload: { - requestId: msg.requestId, - agentId: resolved.agentId, - itemId: msg.itemId, - images, - error: null, - }, - }); - } catch (error) { - emitError(resolved.agentId, this.agentQueueErrorText(error)); - } - } - - /** Admitted input counts as live: a queued follow-up must not read as "not found". */ - private async hasLiveOrQueuedAgent(agentId: string): Promise { - return ( - Boolean(this.agentManager.getAgent(agentId)) || - Boolean((await this.agentQueueService?.list(agentId))?.items.length) - ); - } - /** Answer a wait with the settled record, or a not-found error. */ private async emitUnavailableFinishResponse(agentId: string, requestId: string): Promise { const settled = await this.readSettledAgent(agentId); @@ -9690,6 +9313,7 @@ export class Session { } const agentId = resolved.agentId; + const abortController = new AbortController(); const hasTimeout = typeof timeoutMs === "number" && timeoutMs > 0; const timeoutHandle = hasTimeout @@ -9700,18 +9324,17 @@ export class Session { try { const signal = AbortSignal.any([abortController.signal, sourceSignal]); - // Wait for both accepted message delivery and durable queue admission before observing the run. + // Wait for accepted message delivery before observing the run. await this.agentMessages.waitForDispatch(agentId, signal); - await this.agentQueueService?.waitForPendingDispatch(agentId, signal); const live = this.agentManager.getAgent(agentId); - if (!live && !(await this.hasLiveOrQueuedAgent(agentId))) { + if (!live) { await this.emitUnavailableFinishResponse(agentId, requestId); return; } let result = await this.agentManager.waitForAgentEvent(agentId, { - signal, + signal: AbortSignal.any([abortController.signal, sourceSignal]), waitForActive: true, }); let final = await this.getAgentPayloadById(agentId); @@ -9829,23 +9452,6 @@ export class Session { if (shouldNotify) notified.add(subscription.owner.source); } - /** - * COMPAT(durableAgentQueue): fork addition. Only clients advertising the - * capability may receive the queue broadcast, so a client whose outbound - * union predates the fork never sees an event type it cannot parse. - */ - private canDeliverEventToSource( - message: SessionOutboundMessage, - source: object | undefined, - ): boolean { - if (message.type !== "agent.queue.update") { - return true; - } - return source - ? this.supportsForSource(CLIENT_CAPS.durableAgentQueue, source) - : this.supports(CLIENT_CAPS.durableAgentQueue); - } - private emitSubscribedEvent(message: SessionOutboundMessage, onlySource?: object): boolean { const event = sessionEventCategory(message); if (!event) return false; @@ -9860,43 +9466,25 @@ export class Session { CLIENT_CAPS.workspaceSetupObservation, subscription.owner.source, )) || - (onlySource && subscription.owner.source !== onlySource) || - !this.canDeliverEventToSource(message, subscription.owner.source) + (onlySource && subscription.owner.source !== onlySource) ) continue; this.emitEventToOwner(subscription, message, notified); delivered.add(subscription.owner.source); } - this.emitImplicitLegacyEvent(message, event, onlySource, delivered); - return true; - } - - // COMPAT(ownedSubscriptions): added in v0.8.0, remove implicit event delivery after 2027-03-09. - private emitImplicitLegacyEvent( - message: SessionOutboundMessage, - event: SessionEventSubscription, - onlySource: object | undefined, - delivered: Set, - ): void { + // COMPAT(ownedSubscriptions): added in v0.8.0, remove implicit event delivery after 2027-03-09. if (this.onMessageToSource && this.clientSources.size > 0) { for (const source of this.clientSources.keys()) { if ( (!onlySource || source === onlySource) && !delivered.has(source) && !this.delivery.isModern(source) && - this.wantsEvent(event, source) && - this.canDeliverEventToSource(message, source) + this.wantsEvent(event, source) ) this.onMessageToSource(source, this.workspaceSetupMessageForClient(message, source)); } - return; - } - if ( - delivered.size === 0 && - this.wantsEvent(event) && - this.canDeliverEventToSource(message, undefined) - ) - this.onMessage(message); + } else if (delivered.size === 0 && this.wantsEvent(event)) this.onMessage(message); + return true; } private emit(msg: SessionOutboundMessage): void { @@ -10021,8 +9609,6 @@ export class Session { this.unsubscribePluginChanges = null; this.unsubscribeWorkspaceMutations?.(); this.unsubscribeWorkspaceMutations = null; - this.unsubscribeAgentQueue?.(); - this.unsubscribeAgentQueue = null; this.agentUpdates.dispose(); await this.hubExecutionController?.cleanup(); if (this.unsubscribeTerminalWorkspaceContributionEvents) { @@ -10097,28 +9683,9 @@ const SIDE_CONVERSATION_EVENT_TYPES: ReadonlySet = new Set([ "agent.side_conversation.removed", ]); -/** Outbound types whose subscription category is the type itself. */ -const DIRECT_EVENT_CATEGORIES: ReadonlySet = new Set([ - "project.update", - "providers_snapshot_update", - "agent_attention_required", - "agent_permission_request", - "agent_permission_resolved", - "checkout_status_update", - "script_status_update", - "workspace_setup_progress", - "agent.provider_subagents.update", - "agent.queue.update", - "terminal_attention_required", - "activity_log", - "hub.execution.agent.update", - "hub.execution.agent.stream", -]); - function sessionEventCategory(message: SessionOutboundMessage): SessionEventSubscription | null { if (SIDE_CONVERSATION_EVENT_TYPES.has(message.type)) return message.type as SessionEventSubscription; - if (DIRECT_EVENT_CATEGORIES.has(message.type)) return message.type as SessionEventSubscription; switch (message.type) { case "project.update": case "providers_snapshot_update": diff --git a/packages/server/src/server/session.voice-mcp-config.test.ts b/packages/server/src/server/session.voice-mcp-config.test.ts index 3ead2469027..98b1d41020a 100644 --- a/packages/server/src/server/session.voice-mcp-config.test.ts +++ b/packages/server/src/server/session.voice-mcp-config.test.ts @@ -2,8 +2,8 @@ import { describe, expect, test } from "vitest"; import { buildVoiceAgentMcpServerConfig, + buildVoiceModeSystemPrompt, stripVoiceModeSystemPrompt, - wrapSpokenInput, } from "./voice-config.js"; describe("voice MCP stdio config", () => { @@ -32,7 +32,34 @@ describe("voice MCP stdio config", () => { }); }); -describe("voice prompt instructions", () => { +describe("voice mode prompt instructions", () => { + test("builds enabled voice instructions and preserves base prompt", () => { + const prompt = buildVoiceModeSystemPrompt("Base system prompt", true); + + expect(prompt).toContain("Base system prompt"); + expect(prompt).toContain(""); + expect(prompt).toContain("Paseo voice mode is now on."); + expect(prompt).toContain("Always use the speak tool for all user-facing communication."); + expect(prompt).toContain(""); + }); + + test("builds disabled voice instructions and supersedes previous voice block", () => { + const existing = [ + "Base system prompt", + "", + "legacy voice instruction", + "", + ].join("\n\n"); + + const prompt = buildVoiceModeSystemPrompt(existing, false); + + expect(prompt).toContain("Base system prompt"); + expect(prompt).toContain("Paseo voice mode is now off."); + expect(prompt).toContain("Ignore any earlier Paseo voice mode instructions in this thread."); + expect(prompt.match(//g)?.length ?? 0).toBe(1); + expect(prompt).not.toContain("legacy voice instruction"); + }); + test("strips voice blocks from persisted prompt", () => { const existing = [ "Base system prompt", @@ -48,12 +75,4 @@ describe("voice prompt instructions", () => { ), ).toBeUndefined(); }); - - test("wraps spoken input without telling the agent to abandon chat replies", () => { - const wrapped = wrapSpokenInput("run the tests"); - expect(wrapped).toContain(""); - expect(wrapped).toContain("run the tests"); - expect(wrapped).toContain("keep a readable reply in the chat"); - expect(wrapped).not.toContain("speak tool only"); - }); }); diff --git a/packages/server/src/server/session/voice/index.test.ts b/packages/server/src/server/session/voice/index.test.ts index 7556529bce5..043b759d1ef 100644 --- a/packages/server/src/server/session/voice/index.test.ts +++ b/packages/server/src/server/session/voice/index.test.ts @@ -29,9 +29,14 @@ test("a failed speech close reports the failure without retaining observation de async loadAgent() { throw new Error("Unexpected agent load"); }, + async reloadAgentSession() { + throw new Error("Unexpected agent reload"); + }, async sendSpokenInput() { throw new Error("Unexpected spoken input"); }, + async interruptAgentIfRunning() {}, + hasActiveAgentRun: () => false, }, stt: null, tts: null, diff --git a/packages/server/src/server/session/voice/index.ts b/packages/server/src/server/session/voice/index.ts index bdbb8f2c40d..1832da1c650 100644 --- a/packages/server/src/server/session/voice/index.ts +++ b/packages/server/src/server/session/voice/index.ts @@ -1,5 +1,4 @@ import type { SessionInboundMessage, SessionOutboundMessage } from "../../messages.js"; -import type { AgentStreamEvent } from "../../agent/agent-sdk-types.js"; import type { OwnedOperation, SessionDelivery } from "../owned-subscriptions/index.js"; import { VoiceSession, type VoiceSessionOptions } from "./voice-session.js"; @@ -22,7 +21,6 @@ interface ActiveVoiceSource { voice: VoiceSession; owner: OwnedOperation; pending: Set>; - lifecycleTail: Promise; closing: boolean; } @@ -46,50 +44,15 @@ export class VoiceSessions { ); } - /** Whether this source still owns the named voice attachment incarnation. */ - ownsAttachment( - source: object | undefined, - agentId: string, - attachmentId: string, - generation: string, - ): boolean { - const active = source ? this.sources.get(source) : undefined; - return ( - !!active && - !active.closing && - active.voice.isActiveForAgent(agentId) && - active.voice.acceptsInput(attachmentId, generation) - ); - } - - /** Forwards observed agent events to every live attachment on the agent. */ - handleAgentEvent( - agentId: string, - event: AgentStreamEvent, - metadata: { seq?: number; epoch?: string } = {}, - ): void { - for (const source of this.sources.values()) { - if (!source.closing && source.voice.isActiveForAgent(agentId)) { - source.voice.handleAgentEvent(event, metadata); - } - } - } - handleMessage(message: VoiceMessage): Promise { const source = this.delivery.currentSource; if (!source) throw new Error("Voice request has no source"); const existing = this.sources.get(source); if (existing?.closing) return existing.owner.release().then(() => this.handleMessage(message)); const active = existing ?? this.startSource(source); - // Attach and detach serialize: a stop that lands behind a start must see - // the attachment the start created, not race it. - const before = message.type === "set_voice_mode" ? active.lifecycleTail : Promise.resolve(); - const pending = before - .catch(() => undefined) - .then(() => { - return active.closing ? undefined : this.dispatch(active.voice, message); - }); - if (message.type === "set_voice_mode") active.lifecycleTail = pending; + const pending = Promise.resolve().then(() => { + return active.closing ? undefined : this.dispatch(active.voice, message); + }); active.pending.add(pending); const finished = () => { active.pending.delete(pending); @@ -104,7 +67,7 @@ export class VoiceSessions { const owner = this.delivery.operation(isVoiceOutput, async () => { active.closing = true; this.demandChanged(); - // Cancel input immediately; release audio resources after bootstrap has settled. + // Cancel input immediately; restore agent configuration after bootstrap has settled. try { active.voice.cancel(); } finally { @@ -116,7 +79,6 @@ export class VoiceSessions { const active: ActiveVoiceSource = { owner, pending: new Set(), - lifecycleTail: Promise.resolve(), closing: false, voice: new VoiceSession({ ...this.options, @@ -141,23 +103,13 @@ export class VoiceSessions { private async dispatch(voice: VoiceSession, message: VoiceMessage): Promise { switch (message.type) { case "voice_audio_chunk": - return voice.acceptsInput(message.attachmentId, message.generation) - ? voice.handleAudioChunk(message) - : Promise.resolve(); + return voice.handleAudioChunk(message); case "abort_request": - return voice.acceptsInput(message.attachmentId, message.generation) - ? voice.handleAbort() - : Promise.resolve(); + return voice.handleAbort(); case "audio_played": - if (voice.acceptsInput(message.attachmentId, message.generation)) { - voice.handleAudioPlayed(message.id, message.error); - } - return Promise.resolve(); + return voice.handleAudioPlayed(message.id); case "set_voice_mode": - return voice.handleSetVoiceMode(message.enabled, message.agentId, message.requestId, { - attachmentId: message.attachmentId, - generation: message.generation, - }); + return voice.handleSetVoiceMode(message.enabled, message.agentId, message.requestId); case "dictation_stream_start": return voice.handleDictationStreamStart(message); case "dictation_stream_chunk": diff --git a/packages/server/src/server/session/voice/voice-recognition-issue.test.ts b/packages/server/src/server/session/voice/voice-recognition-issue.test.ts deleted file mode 100644 index f322ed67ce1..00000000000 --- a/packages/server/src/server/session/voice/voice-recognition-issue.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { - NOTHING_RECOGNIZED_MIN_SPEECH_MS, - resolveVoiceRecognitionIssue, -} from "./voice-recognition-issue.js"; - -describe("resolveVoiceRecognitionIssue", () => { - const long = NOTHING_RECOGNIZED_MIN_SPEECH_MS; - - it("reports a long utterance that produced no text", () => { - expect( - resolveVoiceRecognitionIssue({ - transcript: "", - speechMs: long, - timedOut: false, - inputMuted: false, - }), - ).toBe("nothing_recognized"); - }); - - it("stays quiet for short noise and for recognized speech", () => { - expect( - resolveVoiceRecognitionIssue({ - transcript: "", - speechMs: long - 1, - timedOut: false, - inputMuted: false, - }), - ).toBeNull(); - expect( - resolveVoiceRecognitionIssue({ - transcript: "hello", - speechMs: long, - timedOut: true, - inputMuted: false, - }), - ).toBeNull(); - }); - - it("does not report discarded speech while muted", () => { - expect( - resolveVoiceRecognitionIssue({ - transcript: "", - speechMs: long, - timedOut: false, - inputMuted: true, - }), - ).toBeNull(); - }); - - it("reports a recognizer that never answered, muted or not", () => { - for (const inputMuted of [false, true]) { - expect( - resolveVoiceRecognitionIssue({ transcript: "", speechMs: 0, timedOut: true, inputMuted }), - ).toBe("timed_out"); - } - }); -}); diff --git a/packages/server/src/server/session/voice/voice-recognition-issue.ts b/packages/server/src/server/session/voice/voice-recognition-issue.ts deleted file mode 100644 index 708121068a1..00000000000 --- a/packages/server/src/server/session/voice/voice-recognition-issue.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Why a finished utterance produced no text, when the user should hear about it. Sent as - * `voice_input_state.recognitionIssue`; the app speaks and shows each one. - */ -export type VoiceRecognitionIssue = "nothing_recognized" | "timed_out" | "failed"; - -/** - * Detector time from speech start to speech stop. The local detector confirms speech 800 ms - * after onset and ends it after 1 s of silence, so this is about 1.3 s of actual speech. - * Shorter utterances that transcribe to nothing are usually coughs, clicks, or noise. - */ -export const NOTHING_RECOGNIZED_MIN_SPEECH_MS = 1500; - -export function resolveVoiceRecognitionIssue(input: { - transcript: string; - speechMs: number; - timedOut: boolean; - inputMuted: boolean; -}): VoiceRecognitionIssue | null { - if (input.transcript.length > 0) return null; - // A recognizer that does not answer also cannot hear "unmute microphone", so report it muted too. - if (input.timedOut) return "timed_out"; - if (input.inputMuted || input.speechMs < NOTHING_RECOGNIZED_MIN_SPEECH_MS) return null; - return "nothing_recognized"; -} diff --git a/packages/server/src/server/session/voice/voice-session.test.ts b/packages/server/src/server/session/voice/voice-session.test.ts index c7c3d0049e3..1511d6f2fd8 100644 --- a/packages/server/src/server/session/voice/voice-session.test.ts +++ b/packages/server/src/server/session/voice/voice-session.test.ts @@ -6,7 +6,6 @@ import { describe, expect, test, vi } from "vitest"; import { VoiceSession, type VoiceSessionHost } from "./voice-session.js"; import type { ManagedAgent } from "../../agent/agent-manager.js"; -import type { AgentStreamEvent } from "../../agent/agent-sdk-types.js"; import type { SessionOutboundMessage } from "../../messages.js"; import type { SpeechToTextProvider, @@ -58,35 +57,28 @@ class FakeVoiceSttSession extends EventEmitter implements StreamingTranscription } } -/** Stands in for the agent's live run so tests can prove voice never touches it. */ -interface FakeWorker { - turnId: string; - childHeartbeat: number; - running: boolean; -} - interface FakeVoiceHost extends VoiceSessionHost { readonly emitted: SessionOutboundMessage[]; - readonly spokenInput: Array<{ agentId: string; text: string; messageId: string }>; - readonly worker: FakeWorker; + readonly spokenInput: Array<{ agentId: string; text: string }>; } function createFakeHost(): FakeVoiceHost { const emitted: SessionOutboundMessage[] = []; - const spokenInput: Array<{ agentId: string; text: string; messageId: string }> = []; - const worker: FakeWorker = { turnId: "active-turn", childHeartbeat: 1, running: true }; + const spokenInput: Array<{ agentId: string; text: string }> = []; return { emitted, spokenInput, - worker, emit: (msg) => { emitted.push(msg); }, loadAgent: async (agentId) => ({ id: agentId, config: { systemPrompt: undefined } }) as unknown as ManagedAgent, - sendSpokenInput: async (agentId, text, messageId) => { - spokenInput.push({ agentId, text, messageId }); + reloadAgentSession: async (agentId) => ({ id: agentId }) as unknown as ManagedAgent, + sendSpokenInput: async (agentId, text) => { + spokenInput.push({ agentId, text }); }, + interruptAgentIfRunning: async () => {}, + hasActiveAgentRun: () => false, }; } @@ -110,9 +102,8 @@ function createVoiceSession(tts: TextToSpeechProvider | null = null) { sttLanguage: "en", tts, voiceBridge: { - registerVoiceSpeakHandler: (_id, _attachmentId, handler) => { + registerVoiceSpeakHandler: (_id, handler) => { speakHandler = handler; - return "test-generation"; }, }, stt, @@ -145,189 +136,30 @@ async function settle(): Promise { } describe("VoiceSession streaming transcription", () => { - test("a negotiated attachment rejects missing tokens and stale mute/stop requests", async () => { - const { voiceSession, host } = createVoiceSession(); - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "start", { - attachmentId: "attachment", - }); - expect(voiceSession.acceptsInput()).toBe(false); - expect(voiceSession.acceptsInput("attachment", "test-generation")).toBe(true); - await voiceSession.handleSetVoiceMode(false, VOICE_AGENT_ID, "stale-stop", { - attachmentId: "old", - generation: "old", - }); - expect(voiceSession.isActiveForAgent(VOICE_AGENT_ID)).toBe(true); - expect(host.emitted).toContainEqual( - expect.objectContaining({ - type: "set_voice_mode_response", - payload: expect.objectContaining({ accepted: false, error: expect.any(String) }), - }), - ); - await voiceSession.cleanup(); - }); - - test("stopping aborts synthesis before it can emit into a later attachment", async () => { - let release!: () => void; - let started!: () => void; - const start = new Promise((resolve) => { - started = resolve; - }); - const barrier = new Promise((resolve) => { - release = resolve; - }); - const tts: TextToSpeechProvider = { - async synthesizeSpeech() { - started(); - await barrier; - return { stream: Readable.from([Buffer.from("audio")]), format: "pcm;rate=24000" }; - }, - }; - const { voiceSession, host, speak } = createVoiceSession(tts); - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID); - const pending = speak({ text: "old attachment", callerAgentId: VOICE_AGENT_ID }); - await start; - await voiceSession.handleSetVoiceMode(false, VOICE_AGENT_ID); - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID); - release(); - await pending.catch(() => undefined); - expect(host.emitted.filter(isAudioOutput)).toEqual([]); - await voiceSession.cleanup(); - }); - - test("reads new visible assistant text at turn end for a live session without speak", async () => { - const tts: TextToSpeechProvider = { - async synthesizeSpeech() { - return { stream: Readable.from([Buffer.from("audio")]), format: "pcm;rate=24000" }; - }, - }; - const { voiceSession, host } = createVoiceSession(tts); - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID); - voiceSession.handleAgentEvent({ type: "turn_started", turnId: "turn" } as AgentStreamEvent); - voiceSession.handleAgentEvent( - { - type: "timeline", - item: { type: "assistant_message", text: "Visible answer." }, - turnId: "turn", - } as AgentStreamEvent, - { seq: 1, epoch: "epoch" }, - ); - voiceSession.handleAgentEvent({ type: "turn_completed", turnId: "turn" } as AgentStreamEvent); - try { - await waitForAudioOutput(host); - const audio = host.emitted.find((message) => message.type === "audio_output"); - if (audio?.type !== "audio_output") throw new Error("Missing fallback playback"); - voiceSession.handleAudioPlayed(audio.payload.id); - await settle(); - expect(host.emitted.filter(isAudioOutput)).toHaveLength(1); - } finally { - await voiceSession.cleanup(); - } - }); - - test("fallback excludes other turns, reasoning, tool text and duplicate timeline delivery", async () => { - const read: string[] = []; - const tts: TextToSpeechProvider = { - async synthesizeSpeech(text) { - read.push(text); - return { stream: Readable.from([Buffer.from("audio")]), format: "pcm;rate=24000" }; - }, - }; - const { voiceSession, host } = createVoiceSession(tts); - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID); - voiceSession.handleAgentEvent({ type: "turn_started", provider: "codex", turnId: "current" }); - for (const item of [ - { type: "reasoning", text: "PRIVATE REASONING" }, - { type: "tool_call", name: "shell", input: { text: "PRIVATE TOOL" } }, - ]) - voiceSession.handleAgentEvent( - { type: "timeline", provider: "codex", turnId: "current", item } as AgentStreamEvent, - { seq: 1, epoch: "e" }, - ); - voiceSession.handleAgentEvent( - { - type: "timeline", - provider: "codex", - turnId: "old", - item: { type: "assistant_message", text: "PRIVATE OLD TURN" }, - }, - { seq: 2, epoch: "e" }, - ); - const visible = { - type: "timeline", - provider: "codex", - turnId: "current", - item: { type: "assistant_message", text: "Visible." }, - } as const; - voiceSession.handleAgentEvent(visible as AgentStreamEvent, { seq: 3, epoch: "e" }); - voiceSession.handleAgentEvent(visible as AgentStreamEvent, { seq: 3, epoch: "e" }); - voiceSession.handleAgentEvent({ type: "turn_completed", provider: "codex", turnId: "old" }); - expect(read).toEqual([]); - voiceSession.handleAgentEvent({ type: "turn_completed", provider: "codex", turnId: "current" }); - await waitForAudioOutput(host); - expect(read).toEqual(["Visible."]); - await voiceSession.cleanup(); - }); - - test("an interrupted speak suppresses fallback for that same turn", async () => { - const tts: TextToSpeechProvider = { - async synthesizeSpeech() { - return { stream: Readable.from([Buffer.from("audio")]), format: "pcm;rate=24000" }; - }, - }; - const { voiceSession, host, speak } = createVoiceSession(tts); - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID); - voiceSession.handleAgentEvent({ type: "turn_started", provider: "codex", turnId: "turn" }); - const playback = speak({ text: "Already attempted", callerAgentId: VOICE_AGENT_ID }); - await waitForAudioOutput(host); - await voiceSession.handleAbort(); - expect(await playback).toEqual({ ok: false, reason: "interrupted" }); - // A duplicate start event must not reset the invocation marker. - voiceSession.handleAgentEvent({ type: "turn_started", provider: "codex", turnId: "turn" }); - voiceSession.handleAgentEvent( - { - type: "timeline", - provider: "codex", - turnId: "turn", - item: { type: "assistant_message", text: "Already attempted" }, - }, - { seq: 1, epoch: "e" }, - ); - voiceSession.handleAgentEvent({ type: "turn_completed", provider: "codex", turnId: "turn" }); - await settle(); - expect(host.emitted.filter(isAudioOutput)).toHaveLength(1); - await voiceSession.cleanup(); - }); - - test("barge-in stops playback while the active turn and child keep working", async () => { + test("interrupts playback and the agent on speech detection without partial transcripts", async () => { const tts: TextToSpeechProvider = { async synthesizeSpeech() { return { stream: Readable.from([Buffer.from("audio")]), format: "pcm;rate=24000" }; }, }; const { voiceSession, detector, host, speak } = createVoiceSession(tts); - const worker = host.worker; + const interrupted: string[] = []; + async function recordInterruption(agentId: string) { + interrupted.push(agentId); + } + host.interruptAgentIfRunning = recordInterruption; await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID); const playback = speak({ text: "A spoken response." }); try { await waitForAudioOutput(host); detector.emit("speech_started"); await settle(); - expect(host.emitted).toContainEqual( - expect.objectContaining({ - type: "voice_input_state", - payload: expect.objectContaining({ isSpeaking: true }), - }), - ); - // The agent and its child are the same objects, still running, untouched. - expect(host.worker).toBe(worker); - expect(host.worker).toEqual({ turnId: "active-turn", childHeartbeat: 1, running: true }); + expect(host.emitted).toContainEqual({ + type: "voice_input_state", + payload: { isSpeaking: true }, + }); + expect(interrupted).toEqual([VOICE_AGENT_ID]); await playback; - const nextPlayback = speak({ text: "The next response still plays." }); - await vi.waitFor(() => expect(host.emitted.filter(isAudioOutput)).toHaveLength(2)); - const latest = host.emitted.findLast((message) => message.type === "audio_output"); - if (latest?.type !== "audio_output") throw new Error("Missing next audio output"); - voiceSession.handleAudioPlayed(latest.payload.id); - await nextPlayback; } finally { await voiceSession.cleanup(); await playback.catch(() => {}); @@ -369,28 +201,29 @@ describe("VoiceSession streaming transcription", () => { } }); - test("abort leaves the worker and its child alive", async () => { + test("surfaces a refused voice-mode agent interruption", async () => { const { voiceSession, host } = createVoiceSession(); - const worker = host.worker; + host.interruptAgentIfRunning = vi.fn(async () => { + throw new Error("active run cancellation was not acknowledged"); + }); + await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID); - await voiceSession.handleAbort(); - expect(host.worker).toBe(worker); - expect(host.worker.running).toBe(true); - expect(host.worker.childHeartbeat).toBe(1); - await voiceSession.cleanup(); - }); + await expect(voiceSession.handleAbort()).rejects.toThrow( + "active run cancellation was not acknowledged", + ); + expect(host.interruptAgentIfRunning).toHaveBeenCalledWith(VOICE_AGENT_ID); + expect(host.emitted).toContainEqual( + expect.objectContaining({ + type: "activity_log", + payload: expect.objectContaining({ + type: "error", + content: "Voice interruption failed: active run cancellation was not acknowledged", + metadata: { voiceAbortFailed: true }, + }), + }), + ); - test("stopping and restarting voice preserves the provider turn and child", async () => { - const { voiceSession, host } = createVoiceSession(); - const worker = host.worker; - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "start"); - await voiceSession.handleSetVoiceMode(false, VOICE_AGENT_ID, "stop"); - expect(host.worker).toBe(worker); - expect(host.worker.running).toBe(true); - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "restart"); - expect(host.worker.turnId).toBe("active-turn"); - expect(host.worker.childHeartbeat).toBe(1); await voiceSession.cleanup(); }); @@ -415,11 +248,7 @@ describe("VoiceSession streaming transcription", () => { expect(sttSession.commitCount).toBe(1); expect(host.spokenInput).toEqual([ - expect.objectContaining({ - agentId: VOICE_AGENT_ID, - text: "ship the streaming final", - messageId: expect.any(String), - }), + { agentId: VOICE_AGENT_ID, text: "ship the streaming final" }, ]); expect(host.emitted).toContainEqual( expect.objectContaining({ @@ -428,8 +257,6 @@ describe("VoiceSession streaming transcription", () => { text: "ship the streaming final", language: "en", avgLogprob: -0.1, - queued: true, - messageId: expect.any(String), }), }), ); @@ -453,57 +280,12 @@ describe("VoiceSession streaming transcription", () => { await settle(); expect(host.spokenInput).toEqual([]); - const transcriptIndex = host.emitted.findIndex( - (message) => message.type === "transcription_result" && message.payload.text === "", - ); - const issueIndex = host.emitted.findIndex( - (message) => - message.type === "voice_input_state" && message.payload.recognitionIssue === "timed_out", + expect(host.emitted).toContainEqual( + expect.objectContaining({ + type: "transcription_result", + payload: expect.objectContaining({ text: "" }), + }), ); - expect(transcriptIndex).toBeGreaterThanOrEqual(0); - // The issue follows the empty transcript, which is what returns the app to listening. - expect(issueIndex).toBeGreaterThan(transcriptIndex); - - await voiceSession.cleanup(); - } finally { - vi.useRealTimers(); - } - }); - - test("reports a long utterance that recognized nothing, but not a short noise", async () => { - vi.useFakeTimers(); - try { - const { voiceSession, detector, sttSession, host } = createVoiceSession(); - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "start"); - async function utterance(segmentId: string, speechMs: number) { - detector.emit("speech_started"); - await settle(); - await vi.advanceTimersByTimeAsync(speechMs); - detector.emit("speech_stopped"); - await settle(); - sttSession.emitCommitted({ segmentId, previousSegmentId: null }); - sttSession.emitTranscript({ - segmentId, - transcript: "", - isFinal: true, - isLowConfidence: true, - }); - await settle(); - await settle(); - } - function issues() { - return host.emitted.flatMap((message) => - message.type === "voice_input_state" && message.payload.recognitionIssue - ? [message.payload.recognitionIssue] - : [], - ); - } - - await utterance("cough", 1_100); - expect(issues()).toEqual([]); - await utterance("mumble", 2_500); - expect(issues()).toEqual(["nothing_recognized"]); - expect(host.spokenInput).toEqual([]); await voiceSession.cleanup(); } finally { @@ -511,22 +293,6 @@ describe("VoiceSession streaming transcription", () => { } }); - test("reports a recognizer error", async () => { - const { voiceSession, sttSession, host } = createVoiceSession(); - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID); - - sttSession.emit("error", new Error("speech worker exited")); - await settle(); - - expect(host.emitted).toContainEqual( - expect.objectContaining({ - type: "voice_input_state", - payload: expect.objectContaining({ isSpeaking: false, recognitionIssue: "failed" }), - }), - ); - await voiceSession.cleanup(); - }); - test("filters a low-confidence streaming final without submitting to the agent", async () => { const { voiceSession, detector, sttSession, host } = createVoiceSession(); @@ -559,78 +325,4 @@ describe("VoiceSession streaming transcription", () => { await voiceSession.cleanup(); }); - - test("admission completing during detach never acknowledges on the released attachment", async () => { - const { voiceSession, detector, sttSession, host } = createVoiceSession(); - let finish!: () => void; - const admission = vi.fn( - () => - new Promise((resolve) => { - finish = resolve; - }), - ); - host.sendSpokenInput = admission; - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "first", { attachmentId: "first" }); - detector.emit("speech_started"); - await settle(); - detector.emit("speech_stopped"); - await settle(); - sttSession.emitCommitted({ segmentId: "segment-1", previousSegmentId: null }); - sttSession.emitTranscript({ - segmentId: "segment-1", - transcript: "original speech", - isFinal: true, - }); - await vi.waitFor(() => expect(admission).toHaveBeenCalledOnce()); - const detached = voiceSession.handleSetVoiceMode(false, VOICE_AGENT_ID, "stop", { - attachmentId: "first", - generation: "test-generation", - }); - await settle(); - host.emitted.length = 0; - finish(); - await detached; - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "replacement", { - attachmentId: "second", - }); - await settle(); - expect(host.emitted.some((message) => message.type === "transcription_result")).toBe(false); - await voiceSession.cleanup(); - }); - - test("a queued-speech failure is reported instead of acknowledged as heard", async () => { - const { voiceSession, detector, sttSession, host } = createVoiceSession(); - const failingHost = host as FakeVoiceHost & { - sendSpokenInput: (agentId: string, text: string, messageId: string) => Promise; - }; - failingHost.sendSpokenInput = async () => { - throw new Error("Agent message queue is unavailable"); - }; - - await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID); - detector.emit("speech_started"); - await settle(); - detector.emit("speech_stopped"); - await settle(); - sttSession.emitCommitted({ segmentId: "segment-1", previousSegmentId: null }); - sttSession.emitTranscript({ - segmentId: "segment-1", - transcript: "reach the agent", - isFinal: true, - }); - await settle(); - - expect(host.emitted).toContainEqual( - expect.objectContaining({ - type: "voice_input_state", - payload: expect.objectContaining({ - isSpeaking: false, - error: expect.stringContaining("Could not queue speech"), - }), - }), - ); - expect(host.emitted.some((message) => message.type === "transcription_result")).toBe(false); - - await voiceSession.cleanup(); - }); }); diff --git a/packages/server/src/server/session/voice/voice-session.ts b/packages/server/src/server/session/voice/voice-session.ts index b129ec1a06c..95537dd021e 100644 --- a/packages/server/src/server/session/voice/voice-session.ts +++ b/packages/server/src/server/session/voice/voice-session.ts @@ -3,7 +3,7 @@ import { z } from "zod"; import type pino from "pino"; import { getErrorMessage } from "@getpaseo/protocol/error-utils"; import type { SessionInboundMessage, SessionOutboundMessage } from "../../messages.js"; -import { TTSManager, AudioPlaybackError } from "../../agent/tts-manager.js"; +import { TTSManager } from "../../agent/tts-manager.js"; import { STTManager } from "../../agent/stt-manager.js"; import type { SpeechToTextProvider, TextToSpeechProvider } from "../../speech/speech-provider.js"; import type { TurnDetectionProvider } from "../../speech/turn-detection-provider.js"; @@ -14,16 +14,13 @@ import { type DictationStreamOutboundMessage, } from "../../dictation/dictation-stream-manager.js"; import { createVoiceTurnController, type VoiceTurnController } from "./voice-turn-controller.js"; +import { buildVoiceModeSystemPrompt, stripVoiceModeSystemPrompt } from "../../voice-config.js"; import type { VoiceCallerContext, VoiceSpeakHandler } from "../../voice-types.js"; import type { ManagedAgent } from "../../agent/agent-manager.js"; -import type { AgentStreamEvent } from "../../agent/agent-sdk-types.js"; +import type { AgentSessionConfig } from "../../agent/agent-sdk-types.js"; import type { LocalSpeechModelId } from "../../speech/providers/local/models.js"; import { toResolver, type Resolvable } from "../../speech/provider-resolver.js"; import type { SpeechReadinessSnapshot, SpeechReadinessState } from "../../speech/speech-runtime.js"; -import { - resolveVoiceRecognitionIssue, - type VoiceRecognitionIssue, -} from "./voice-recognition-issue.js"; const PCM_SAMPLE_RATE = 16000; const PCM_CHANNELS = 1; @@ -37,6 +34,10 @@ const AgentIdSchema = z.guid(); type ProcessingPhase = "idle" | "transcribing"; +interface VoiceModeBaseConfig { + systemPrompt?: string; +} + interface AudioBufferState { chunks: Buffer[]; format: string; @@ -116,12 +117,18 @@ function convertPCMToWavBuffer( * The agent-facing operations VoiceSession needs from the session that owns it. * VoiceSession owns all voice/audio state; it reaches back through this narrow * seam only to deliver transcripts to the agent, drive TTS playback, and - * manage the audio attachment. Agent work has a separate lifetime. + * abort/inspect the active agent run. */ export interface VoiceSessionHost { emit(msg: SessionOutboundMessage): void; loadAgent(agentId: string): Promise; - sendSpokenInput(agentId: string, text: string, messageId: string): Promise; + reloadAgentSession( + agentId: string, + overrides: Partial, + ): Promise; + sendSpokenInput(agentId: string, text: string): Promise; + interruptAgentIfRunning(agentId: string): Promise; + hasActiveAgentRun(agentId: string | null): boolean; } export interface VoiceSessionOptions { @@ -136,21 +143,10 @@ export interface VoiceSessionOptions { turnDetection?: Resolvable; }; voiceBridge?: { - registerVoiceSpeakHandler?: ( - agentId: string, - attachmentId: string, - handler: VoiceSpeakHandler, - revoke: () => void, - ) => string; - unregisterVoiceSpeakHandler?: (agentId: string, generation: string) => void; - registerVoiceCallerContext?: ( - agentId: string, - generation: string, - context: VoiceCallerContext, - ) => void; - unregisterVoiceCallerContext?: (agentId: string, generation: string) => void; - isCurrent?: (agentId: string, generation: string) => boolean; - hasSpokenInTurn?: (agentId: string, turnId: string) => boolean; + registerVoiceSpeakHandler?: (agentId: string, handler: VoiceSpeakHandler) => void; + unregisterVoiceSpeakHandler?: (agentId: string) => void; + registerVoiceCallerContext?: (agentId: string, context: VoiceCallerContext) => void; + unregisterVoiceCallerContext?: (agentId: string) => void; }; dictation?: { finalTimeoutMs?: number; @@ -180,14 +176,6 @@ export class VoiceSession { private isVoiceMode = false; private speechInProgress = false; - // Fallback playback bookkeeping for the currently observed turn. - private spokeThisTurn = false; - private fallbackTurnId: string | null = null; - private fallbackEpoch: string | null = null; - private fallbackSeq = -1; - // Set once a client negotiates an attachment; tokenless frames are legacy. - private requiresTransportToken = false; - private visibleReply = ""; private readonly dictationStreamManager: DictationStreamManager; private readonly resolveVoiceTurnDetection: () => TurnDetectionProvider | null; @@ -209,24 +197,18 @@ export class VoiceSession { private readonly registerVoiceSpeakHandler?: ( agentId: string, - attachmentId: string, handler: VoiceSpeakHandler, - revoke: () => void, - ) => string; - private readonly unregisterVoiceSpeakHandler?: (agentId: string, generation: string) => void; + ) => void; + private readonly unregisterVoiceSpeakHandler?: (agentId: string) => void; private readonly registerVoiceCallerContext?: ( agentId: string, - generation: string, context: VoiceCallerContext, ) => void; - private readonly unregisterVoiceCallerContext?: (agentId: string, generation: string) => void; - private readonly hasSpokenInTurn?: (agentId: string, turnId: string) => boolean; - private readonly isCurrent?: (agentId: string, generation: string) => boolean; + private readonly unregisterVoiceCallerContext?: (agentId: string) => void; private readonly getSpeechReadiness?: () => SpeechReadinessSnapshot; private voiceModeAgentId: string | null = null; - private voiceModeAttachmentId: string | null = null; - private voiceModeGeneration: string | null = null; + private voiceModeBaseConfig: VoiceModeBaseConfig | null = null; constructor(options: VoiceSessionOptions) { const { host, logger, sessionId, sttLanguage, tts, stt, voice, voiceBridge, dictation } = @@ -243,8 +225,6 @@ export class VoiceSession { this.unregisterVoiceSpeakHandler = voiceBridge?.unregisterVoiceSpeakHandler; this.registerVoiceCallerContext = voiceBridge?.registerVoiceCallerContext; this.unregisterVoiceCallerContext = voiceBridge?.unregisterVoiceCallerContext; - this.isCurrent = voiceBridge?.isCurrent; - this.hasSpokenInTurn = voiceBridge?.hasSpokenInTurn; this.getSpeechReadiness = dictation?.getSpeechReadiness; this.ttsManager = new TTSManager(this.sessionId, this.sessionLogger, tts); @@ -272,102 +252,6 @@ export class VoiceSession { ); } - /** - * Whether a voice message belongs to this attachment incarnation. Tokenless - * frames are a legacy client that never negotiated an attachment; they keep - * working while the session is open. - */ - // COMPAT(durableVoiceInputV1): tokenless legacy attachments, remove after 2027-03-29. - acceptsInput(attachmentId?: string, generation?: string): boolean { - if (!this.requiresTransportToken && !attachmentId && !generation) return !this.closed; - return ( - this.currentAttachment() && - attachmentId === this.voiceModeAttachmentId && - generation === this.voiceModeGeneration - ); - } - - /** - * Observed turn events drive fallback playback only: when the agent did not - * use the speak tool during a turn, the attached session reads the visible - * final assistant text so the answer is not silent. Reasoning, tool payloads - * and other turns are never read. - */ - handleAgentEvent(event: AgentStreamEvent, metadata: { seq?: number; epoch?: string } = {}): void { - if (!this.currentAttachment()) return; - if (event.type === "turn_started" && event.turnId && event.turnId !== this.fallbackTurnId) { - this.fallbackTurnId = event.turnId; - this.spokeThisTurn = false; - this.visibleReply = ""; - } else if (event.type === "timeline" && event.item.type === "assistant_message") { - this.collectVisibleReply(event, metadata); - } else if ( - (event.type === "turn_completed" || - event.type === "turn_failed" || - event.type === "turn_canceled") && - event.turnId && - event.turnId === this.fallbackTurnId - ) { - const reply = this.visibleReply.trim(); - if ( - event.type === "turn_completed" && - reply && - !this.spokeThisTurn && - !this.hasSpokenInTurn?.(this.voiceModeAgentId!, event.turnId) - ) { - this.spokeThisTurn = true; - void this.speakFallback(reply); - } - this.visibleReply = ""; - this.fallbackTurnId = null; - } - } - - private collectVisibleReply( - event: Extract, - metadata: { seq?: number; epoch?: string }, - ): void { - if (event.item.type !== "assistant_message") return; - if ( - !event.turnId || - event.turnId !== this.fallbackTurnId || - metadata.seq === undefined || - !metadata.epoch - ) - return; - if (this.fallbackEpoch && metadata.epoch !== this.fallbackEpoch) { - this.visibleReply = ""; - this.fallbackSeq = -1; - } - if (metadata.seq <= this.fallbackSeq) return; - this.fallbackEpoch = metadata.epoch; - this.fallbackSeq = metadata.seq; - this.visibleReply = (this.visibleReply + event.item.text).slice(0, 4000); - } - - private async speakFallback(text: string): Promise { - try { - await this.ttsManager.generateAndWaitForPlayback( - text, - (message) => this.emit(message), - this.abortController.signal, - true, - ); - } catch (error) { - this.sessionLogger.warn({ err: error }, "Voice fallback playback failed"); - } - } - - private currentAttachment(): boolean { - return ( - !this.closed && - this.isVoiceMode && - !!this.voiceModeAgentId && - !!this.voiceModeGeneration && - (this.isCurrent?.(this.voiceModeAgentId, this.voiceModeGeneration) ?? true) - ); - } - isActiveForAgent(agentId: string): boolean { return this.isVoiceMode && this.voiceModeAgentId === agentId; } @@ -467,29 +351,13 @@ export class VoiceSession { /** * Handle voice mode toggle */ - // Attachment ownership and controller startup must share one failure cleanup path. - // oxlint-disable-next-line complexity - async handleSetVoiceMode( - enabled: boolean, - agentId?: string, - requestId?: string, - input: { attachmentId?: string; generation?: string } = {}, - ): Promise { + async handleSetVoiceMode(enabled: boolean, agentId?: string, requestId?: string): Promise { const startedAt = Date.now(); try { this.sessionLogger.info( { enabled, requestedAgentId: agentId ?? null, requestId: requestId ?? null }, "set_voice_mode started", ); - // A stop or reclaim from a stale transport incarnation must not tear down - // the attachment a live connection owns. - if ( - !enabled && - this.voiceModeAgentId && - !this.acceptsInput(input.attachmentId, input.generation) - ) { - throw new Error("Voice attachment is no longer owned by this request."); - } if (enabled) { const unavailable = this.resolveVoiceFeatureUnavailableContext("voice_mode"); if (unavailable) { @@ -501,8 +369,7 @@ export class VoiceSession { if ( this.isVoiceMode && this.voiceModeAgentId && - (this.voiceModeAgentId !== normalizedAgentId || - (input.attachmentId && input.attachmentId !== this.voiceModeAttachmentId)) + this.voiceModeAgentId !== normalizedAgentId ) { this.sessionLogger.info( { @@ -512,14 +379,10 @@ export class VoiceSession { }, "set_voice_mode disabling previous active voice agent", ); - await this.disableVoiceModeForActiveAgent(); - this.isVoiceMode = false; + await this.disableVoiceModeForActiveAgent(true); } if (!this.isVoiceMode || this.voiceModeAgentId !== normalizedAgentId) { - this.requiresTransportToken = !!input.attachmentId; - this.voiceModeAttachmentId = input.attachmentId ?? uuidv4(); - this.createAbortController(); this.sessionLogger.info( { agentId: normalizedAgentId, elapsedMs: Date.now() - startedAt }, "set_voice_mode enabling voice for agent", @@ -527,7 +390,7 @@ export class VoiceSession { const refreshedAgentId = await this.enableVoiceModeForAgent(normalizedAgentId); this.voiceModeAgentId = refreshedAgentId; if (this.closed) { - await this.disableVoiceModeForActiveAgent(); + await this.disableVoiceModeForActiveAgent(true); return; } this.sessionLogger.info( @@ -545,10 +408,6 @@ export class VoiceSession { { agentId: this.voiceModeAgentId, elapsedMs: Date.now() - startedAt }, "set_voice_mode voice turn controller started", ); - if (this.closed) { - await this.disableVoiceModeForActiveAgent(); - return; - } this.isVoiceMode = !this.closed; this.sessionLogger.info( { @@ -564,8 +423,6 @@ export class VoiceSession { requestId, enabled: true, agentId: this.voiceModeAgentId, - ...(this.voiceModeAttachmentId ? { attachmentId: this.voiceModeAttachmentId } : {}), - ...(this.voiceModeGeneration ? { generation: this.voiceModeGeneration } : {}), accepted: true, error: null, }, @@ -578,7 +435,7 @@ export class VoiceSession { { agentId: this.voiceModeAgentId, elapsedMs: Date.now() - startedAt }, "set_voice_mode disabling active voice mode", ); - await this.disableVoiceModeForActiveAgent(); + await this.disableVoiceModeForActiveAgent(true); this.isVoiceMode = false; this.sessionLogger.info({ elapsedMs: Date.now() - startedAt }, "Voice mode disabled"); if (requestId) { @@ -594,9 +451,6 @@ export class VoiceSession { }); } } catch (error) { - if (!this.isVoiceMode && this.voiceModeAgentId) { - await this.disableVoiceModeForActiveAgent(); - } const errorMessage = error instanceof Error ? error.message : "Failed to set voice mode"; const unavailable = this.getVoiceFeatureUnavailableResponseMetadata(error); this.sessionLogger.error( @@ -645,33 +499,61 @@ export class VoiceSession { ); this.registerVoiceBridgeForAgent(agentId); - // A turn that was already running when voice attached keeps its identity: - // attach/detach never restarts, replaces, or interrupts it. - this.fallbackTurnId = existing.activeForegroundTurnId ?? null; - return existing.id; + + const baseConfig: VoiceModeBaseConfig = { + systemPrompt: stripVoiceModeSystemPrompt(existing.config.systemPrompt), + }; + this.voiceModeBaseConfig = baseConfig; + const refreshOverrides: Partial = { + systemPrompt: buildVoiceModeSystemPrompt(baseConfig.systemPrompt, true), + }; + + try { + this.sessionLogger.info( + { agentId, elapsedMs: Date.now() - startedAt }, + "enableVoiceModeForAgent.reloadAgentSession.start", + ); + const refreshed = await this.host.reloadAgentSession(agentId, refreshOverrides); + this.sessionLogger.info( + { agentId, refreshedAgentId: refreshed.id, elapsedMs: Date.now() - startedAt }, + "enableVoiceModeForAgent.reloadAgentSession.done", + ); + return refreshed.id; + } catch (error) { + this.unregisterVoiceSpeakHandler?.(agentId); + this.unregisterVoiceCallerContext?.(agentId); + this.voiceModeBaseConfig = null; + throw error; + } } - private async disableVoiceModeForActiveAgent(): Promise { - this.isVoiceMode = false; - this.abortController.abort(); - this.visibleReply = ""; - this.fallbackTurnId = null; - this.spokeThisTurn = false; - this.fallbackEpoch = null; - this.fallbackSeq = -1; + private async disableVoiceModeForActiveAgent(restoreAgentConfig: boolean): Promise { await this.stopVoiceTurnController(); - this.ttsManager.cancelPendingPlaybacks("voice mode disabled"); const agentId = this.voiceModeAgentId; - if (!agentId) return; + if (!agentId) { + this.voiceModeBaseConfig = null; + return; + } - if (this.voiceModeGeneration) { - this.unregisterVoiceSpeakHandler?.(agentId, this.voiceModeGeneration); - this.unregisterVoiceCallerContext?.(agentId, this.voiceModeGeneration); + if (restoreAgentConfig && this.voiceModeBaseConfig) { + const baseConfig = this.voiceModeBaseConfig; + try { + await this.host.reloadAgentSession(agentId, { + systemPrompt: buildVoiceModeSystemPrompt(baseConfig.systemPrompt, false), + }); + } catch (error) { + this.sessionLogger.warn( + { err: error, agentId }, + "Failed to restore agent config while disabling voice mode", + ); + } } + + this.unregisterVoiceSpeakHandler?.(agentId); + this.unregisterVoiceCallerContext?.(agentId); + this.voiceModeBaseConfig = null; this.voiceModeAgentId = null; - this.voiceModeAttachmentId = null; - this.voiceModeGeneration = null; } private handleDictationManagerMessage(msg: DictationStreamOutboundMessage): void { @@ -698,9 +580,6 @@ export class VoiceSession { "startVoiceTurnController creating controller", ); - const controllerGeneration = this.voiceModeGeneration; - const isCurrentController = () => - this.currentAttachment() && controllerGeneration === this.voiceModeGeneration; const controller = createVoiceTurnController({ logger: this.sessionLogger.child({ component: "voice-turn-controller" }), turnDetection, @@ -708,7 +587,6 @@ export class VoiceSession { sttLanguage: this.sttLanguage, callbacks: { onSpeechStarted: async () => { - if (!isCurrentController()) return; // Voice STT providers return final transcripts only. Use the detector's // confirmed speech event so interruption does not wait for transcription. this.sessionLogger.debug("Voice VAD speech_started"); @@ -727,7 +605,6 @@ export class VoiceSession { ); }, onSpeechStopped: async () => { - if (!isCurrentController()) return; this.handleVoiceSpeechStopped(); this.setPhase("transcribing"); this.emit({ @@ -741,23 +618,14 @@ export class VoiceSession { }); }, onFinalTranscript: async ({ - utteranceId, transcript, language, durationMs, - speechMs, - timedOut, avgLogprob, isLowConfidence, }) => { - if (!isCurrentController()) return; - const requestId = `${controllerGeneration}:${utteranceId}`; + const requestId = uuidv4(); const transcriptText = isLowConfidence ? "" : transcript.trim(); - const recognitionIssue = this.resolveRecognitionIssue({ - transcript: transcriptText, - speechMs, - timedOut, - }); if (isLowConfidence) { this.sessionLogger.debug( { text: transcript, avgLogprob }, @@ -781,19 +649,9 @@ export class VoiceSession { ...(avgLogprob !== undefined ? { avgLogprob } : {}), ...(isLowConfidence !== undefined ? { isLowConfidence } : {}), }); - // After the transcript delivery, which is what returns the app to listening. - this.emitRecognitionIssue(recognitionIssue); }, onError: (error) => { - if (!isCurrentController()) return; this.sessionLogger.error({ err: error }, "Voice turn controller failed"); - this.emit({ - type: "voice_input_state", - payload: { - isSpeaking: false, - recognitionIssue: "failed", - }, - }); }, }, }); @@ -815,29 +673,6 @@ export class VoiceSession { await controller.stop(); } - private resolveRecognitionIssue(input: { - transcript: string; - speechMs: number; - timedOut: boolean; - }): VoiceRecognitionIssue | null { - const recognitionIssue = resolveVoiceRecognitionIssue({ - ...input, - inputMuted: false, - }); - if (recognitionIssue) { - this.sessionLogger.warn( - { recognitionIssue, speechMs: input.speechMs, timedOut: input.timedOut }, - "Voice utterance produced no text", - ); - } - return recognitionIssue; - } - - private emitRecognitionIssue(recognitionIssue: VoiceRecognitionIssue | null): void { - if (!recognitionIssue) return; - this.emit({ type: "voice_input_state", payload: { isSpeaking: false, recognitionIssue } }); - } - private handleVoiceSpeechStopped(): void { this.sessionLogger.info("voice_input_state emitting isSpeaking=false"); this.emit({ @@ -1131,27 +966,24 @@ export class VoiceSession { ): Promise { const transcriptText = result.text.trim(); - const emitTranscript = (messageId?: string) => - this.emit({ - type: "transcription_result", - payload: { - text: result.text, - ...(result.language ? { language: result.language } : {}), - ...(result.duration !== undefined ? { duration: result.duration } : {}), - requestId: result.requestId, - ...(messageId ? { messageId, queued: true } : {}), - ...(result.avgLogprob !== undefined ? { avgLogprob: result.avgLogprob } : {}), - ...(result.isLowConfidence !== undefined - ? { isLowConfidence: result.isLowConfidence } - : {}), - ...(result.byteLength !== undefined ? { byteLength: result.byteLength } : {}), - ...(result.format ? { format: result.format } : {}), - ...(result.debugRecordingPath ? { debugRecordingPath: result.debugRecordingPath } : {}), - }, - }); + this.emit({ + type: "transcription_result", + payload: { + text: result.text, + ...(result.language ? { language: result.language } : {}), + ...(result.duration !== undefined ? { duration: result.duration } : {}), + requestId: result.requestId, + ...(result.avgLogprob !== undefined ? { avgLogprob: result.avgLogprob } : {}), + ...(result.isLowConfidence !== undefined + ? { isLowConfidence: result.isLowConfidence } + : {}), + ...(result.byteLength !== undefined ? { byteLength: result.byteLength } : {}), + ...(result.format ? { format: result.format } : {}), + ...(result.debugRecordingPath ? { debugRecordingPath: result.debugRecordingPath } : {}), + }, + }); if (!transcriptText) { - emitTranscript(); this.sessionLogger.debug("Empty transcription (false positive), not aborting"); this.setPhase("idle"); this.clearSpeechInProgress("empty transcription"); @@ -1179,6 +1011,20 @@ export class VoiceSession { }); } + this.emit({ + type: "activity_log", + payload: { + id: uuidv4(), + timestamp: new Date(), + type: "transcript", + content: result.text, + metadata: { + ...(result.language ? { language: result.language } : {}), + ...(result.duration !== undefined ? { duration: result.duration } : {}), + }, + }, + }); + this.clearSpeechInProgress("transcription complete"); this.setPhase("idle"); if (!this.isVoiceMode) { @@ -1200,60 +1046,12 @@ export class VoiceSession { return; } - if (!this.currentAttachment()) return; - // The transcript is acknowledged only after its queue write succeeds, and - // it carries the item id the receipts will answer under. - const generation = this.voiceModeGeneration; - const attachmentId = this.voiceModeAttachmentId; - const messageId = `${attachmentId}:${result.requestId}`; - try { - await this.host.sendSpokenInput(agentId, result.text, messageId); - } catch (error) { - if ( - !this.currentAttachment() || - generation !== this.voiceModeGeneration || - attachmentId !== this.voiceModeAttachmentId - ) - return; - this.emit({ - type: "voice_input_state", - payload: { isSpeaking: false, error: `Could not queue speech: ${getErrorMessage(error)}` }, - }); - return; - } - if ( - !this.currentAttachment() || - generation !== this.voiceModeGeneration || - attachmentId !== this.voiceModeAttachmentId - ) - return; - emitTranscript(messageId); - this.emit({ - type: "activity_log", - payload: { - id: uuidv4(), - timestamp: new Date(), - type: "transcript", - content: result.text, - metadata: { messageId }, - }, - }); + await this.host.sendSpokenInput(agentId, result.text); await this.flushPendingAudioSegments("transcription complete"); } private registerVoiceBridgeForAgent(agentId: string): void { - const attachmentId = this.voiceModeAttachmentId; - let handlerGeneration: string | null = null; - const handler: VoiceSpeakHandler = async ({ text, signal }) => { - // A speak call from a superseded incarnation must not play into a - // different attachment than the one the agent heard the request from. - if ( - !this.currentAttachment() || - attachmentId !== this.voiceModeAttachmentId || - handlerGeneration !== this.voiceModeGeneration - ) - return { ok: false, reason: "unavailable" }; - this.spokeThisTurn = true; + this.registerVoiceSpeakHandler?.(agentId, async ({ text, signal }) => { this.sessionLogger.info( { agentId, @@ -1265,22 +1063,12 @@ export class VoiceSession { const abortSignal = signal ? AbortSignal.any([signal, this.abortController.signal]) : this.abortController.signal; - try { - await this.ttsManager.generateAndWaitForPlayback( - text, - (msg) => this.emit(msg), - abortSignal, - true, - ); - } catch (error) { - // Interrupted audio is an outcome, not a failure: report it so a - // fallback reading is suppressed for this turn instead of doubled. - if (error instanceof AudioPlaybackError && error.reason === "interrupted") { - this.sessionLogger.info({ agentId }, "Voice speak tool call interrupted"); - return { ok: false, reason: "interrupted" }; - } - throw error; - } + await this.ttsManager.generateAndWaitForPlayback( + text, + (msg) => this.emit(msg), + abortSignal, + true, + ); this.sessionLogger.info( { agentId, textLength: text.length }, "Voice speak tool call finished playback", @@ -1294,22 +1082,9 @@ export class VoiceSession { content: text, }, }); - }; - - this.voiceModeGeneration = - this.registerVoiceSpeakHandler?.( - agentId, - this.voiceModeAttachmentId ?? uuidv4(), - handler, - () => { - void this.cleanup().catch((error) => - this.sessionLogger.warn({ err: error }, "Failed to revoke old voice attachment"), - ); - }, - ) ?? uuidv4(); - handlerGeneration = this.voiceModeGeneration; + }); - this.registerVoiceCallerContext?.(agentId, this.voiceModeGeneration, { + this.registerVoiceCallerContext?.(agentId, { childAgentDefaultLabels: {}, allowCustomCwd: false, enableVoiceTools: true, @@ -1317,9 +1092,7 @@ export class VoiceSession { } /** - * Handle abort request from client. Abort stops the agent's audible output - * and this session's capture; the agent run itself is never touched — an - * explicit interrupt command from the user is the only path that cancels it. + * Handle abort request from client */ async handleAbort(): Promise { this.sessionLogger.info( @@ -1329,7 +1102,26 @@ export class VoiceSession { this.abortController.abort(); this.ttsManager.cancelPendingPlaybacks("abort request"); - this.createAbortController(); + + // Voice abort should always interrupt active agent output immediately. + if (this.isVoiceMode && this.voiceModeAgentId) { + try { + await this.host.interruptAgentIfRunning(this.voiceModeAgentId); + } catch (error) { + const message = `Voice interruption failed: ${getErrorMessage(error)}`; + this.emit({ + type: "activity_log", + payload: { + id: uuidv4(), + timestamp: new Date(), + type: "error", + content: message, + metadata: { voiceAbortFailed: true }, + }, + }); + throw error; + } + } if (this.processingPhase === "transcribing") { // Still in STT phase - we'll buffer the next audio @@ -1347,12 +1139,12 @@ export class VoiceSession { /** * Handle audio playback confirmation from client */ - handleAudioPlayed(id: string, error?: string): void { - this.ttsManager.confirmAudioPlayed(id, error); + handleAudioPlayed(id: string): void { + this.ttsManager.confirmAudioPlayed(id); } /** - * Mark speech detection start and stop only active playback. + * Mark speech detection start and abort any active playback/agent run. */ private async handleVoiceSpeechStart(): Promise { if (this.speechInProgress) { @@ -1361,9 +1153,10 @@ export class VoiceSession { const chunkReceivedAt = Date.now(); const phaseBeforeAbort = this.processingPhase; + const hadActiveStream = this.host.hasActiveAgentRun(this.voiceModeAgentId); this.speechInProgress = true; - this.sessionLogger.debug("Voice speech detected – aborting playback"); + this.sessionLogger.debug("Voice speech detected – aborting playback and active agent run"); if (this.pendingAudioSegments.length > 0) { this.sessionLogger.debug( @@ -1385,12 +1178,13 @@ export class VoiceSession { this.clearBufferTimeout(); + this.abortController.abort(); await this.handleAbort(); const latencyMs = Date.now() - chunkReceivedAt; this.sessionLogger.debug( - { latencyMs, phaseBeforeAbort }, - "[Telemetry] barge_in.audio_abort_latency", + { latencyMs, phaseBeforeAbort, hadActiveStream }, + "[Telemetry] barge_in.llm_abort_latency", ); } @@ -1518,22 +1312,6 @@ export class VoiceSession { } } } - if ( - msg.type === "audio_output" || - msg.type === "transcription_result" || - msg.type === "voice_input_state" - ) { - if (!this.currentAttachment()) return; - this.host.emit({ - ...msg, - payload: { - ...msg.payload, - attachmentId: this.voiceModeAttachmentId ?? undefined, - generation: this.voiceModeGeneration ?? undefined, - }, - } as SessionOutboundMessage); - return; - } this.host.emit(msg); } @@ -1560,7 +1338,7 @@ export class VoiceSession { if (failures.length) throw new AggregateError(failures, "Voice input cleanup failed"); } - /** Release audio resources after in-flight requests settle. */ + /** Restore the agent only after the caller has drained its in-flight requests. */ async cleanup(): Promise { try { this.cancel(); @@ -1568,7 +1346,7 @@ export class VoiceSession { try { await this.stopVoiceTurnController(); } finally { - await this.disableVoiceModeForActiveAgent(); + await this.disableVoiceModeForActiveAgent(true); this.isVoiceMode = false; } } diff --git a/packages/server/src/server/session/voice/voice-turn-controller.test.ts b/packages/server/src/server/session/voice/voice-turn-controller.test.ts index e3badb663dc..4f2a7e96cfd 100644 --- a/packages/server/src/server/session/voice/voice-turn-controller.test.ts +++ b/packages/server/src/server/session/voice/voice-turn-controller.test.ts @@ -433,7 +433,6 @@ describe("voice turn controller", () => { expect.objectContaining({ segmentId: "segment-1", transcript: "hello", - timedOut: true, }), ); } finally { @@ -441,34 +440,6 @@ describe("voice turn controller", () => { } }); - it("reports the detector's speech duration apart from recognition latency", async () => { - vi.useFakeTimers(); - try { - const harness = createControllerHarness(); - - await harness.controller.start(); - harness.detector.emit("speech_started"); - await settleSerialQueue(); - await vi.advanceTimersByTimeAsync(2_000); - harness.detector.emit("speech_stopped"); - await settleSerialQueue(); - await vi.advanceTimersByTimeAsync(700); - harness.sttSessions[0]?.emitCommitted({ segmentId: "segment-1", previousSegmentId: null }); - harness.sttSessions[0]?.emitTranscript({ - segmentId: "segment-1", - transcript: "hello", - isFinal: true, - }); - await settleSerialQueue(); - - expect(harness.onFinalTranscript).toHaveBeenCalledWith( - expect.objectContaining({ speechMs: 2_000, durationMs: 2_700, timedOut: false }), - ); - } finally { - vi.useRealTimers(); - } - }); - it("does not include stale uncommitted finals once committed segments are known", async () => { vi.useFakeTimers(); try { diff --git a/packages/server/src/server/session/voice/voice-turn-controller.ts b/packages/server/src/server/session/voice/voice-turn-controller.ts index 8d588e17ad3..20e2b4ba1f3 100644 --- a/packages/server/src/server/session/voice/voice-turn-controller.ts +++ b/packages/server/src/server/session/voice/voice-turn-controller.ts @@ -71,24 +71,17 @@ interface TranscriptSegmentMeta { } interface VoiceFinalTranscript { - /** Controller-owned identity survives provider segment reuse and finalization retries. */ - utteranceId: string; segmentId: string; transcript: string; language?: string; avgLogprob?: number; isLowConfidence?: boolean; durationMs: number; - /** Time between the detector's speech start and speech stop, excluding recognition latency. */ - speechMs: number; - /** The recognizer returned no final result before the deadline, so the transcript is partial or empty. */ - timedOut: boolean; } interface FinalizingVoiceTurn { turnId: string; startedAt: number; - speechMs: number; committedSegmentIds: string[]; transcriptsBySegmentId: Map; finalTranscriptSegmentIds: Set; @@ -172,10 +165,7 @@ export function createVoiceTurnController(params: { ); } - function assembleFinalTranscript( - turn: FinalizingVoiceTurn, - reason: "complete" | "timeout", - ): VoiceFinalTranscript { + function assembleFinalTranscript(turn: FinalizingVoiceTurn): VoiceFinalTranscript { const orderedFinalSegmentIds = getOrderedFinalSegmentIds(turn); const transcript = orderedFinalSegmentIds .map((segmentId) => turn.transcriptsBySegmentId.get(segmentId)?.trim() ?? "") @@ -192,7 +182,6 @@ export function createVoiceTurnController(params: { orderedFinalMeta.every((meta) => meta.isLowConfidence === true); return { - utteranceId: turn.turnId, segmentId: turn.committedSegmentIds[0] ?? orderedFinalSegmentIds[0] ?? turn.turnId, transcript, ...(language ? { language } : {}), @@ -201,8 +190,6 @@ export function createVoiceTurnController(params: { : {}), ...(allLowConfidence ? { isLowConfidence: true } : {}), durationMs: Math.max(0, Date.now() - turn.startedAt), - speechMs: turn.speechMs, - timedOut: reason === "timeout", }; } @@ -215,7 +202,7 @@ export function createVoiceTurnController(params: { clearTimeout(turn.timeout); currentFinalizingTurn = null; - const finalTranscript = assembleFinalTranscript(turn, reason); + const finalTranscript = assembleFinalTranscript(turn); if (reason === "timeout") { params.logger.warn( { @@ -451,7 +438,6 @@ export function createVoiceTurnController(params: { const finalizingTurn: FinalizingVoiceTurn = { turnId, startedAt, - speechMs: Math.max(0, endedAt - startedAt), committedSegmentIds: [], transcriptsBySegmentId: new Map(), finalTranscriptSegmentIds: new Set(), diff --git a/packages/server/src/server/test-utils/session-stubs.ts b/packages/server/src/server/test-utils/session-stubs.ts index 3ba82f330b4..6ded439a573 100644 --- a/packages/server/src/server/test-utils/session-stubs.ts +++ b/packages/server/src/server/test-utils/session-stubs.ts @@ -318,7 +318,6 @@ export function createProviderSnapshotManagerStub(): { export function createMessageReceiptsStub(): SessionOptions["messageReceipts"] { return { send: (input) => input.send(), - listForAttachment: async () => [], }; } diff --git a/packages/server/src/server/voice-config.ts b/packages/server/src/server/voice-config.ts index 00a17607f06..d8cb1992f4f 100644 --- a/packages/server/src/server/voice-config.ts +++ b/packages/server/src/server/voice-config.ts @@ -1,13 +1,23 @@ const VOICE_PROMPT_BLOCK_START = ""; const VOICE_PROMPT_BLOCK_END = ""; -/** - * Applied only when an agent is naturally created or resumed with Paseo tools. - * Voice attachment no longer rewrites the running session: the agent keeps its - * prompt, and speak is simply available whenever audio is attached. - */ -export const VOICE_AVAILABLE_INSTRUCTION = - "When Paseo voice is attached, speak can read a concise response aloud. Keep the answer visible in chat too. Voice can attach or detach while you work; continue the current turn and tool calls without changing course."; +const VOICE_AGENT_SYSTEM_INSTRUCTION = [ + "Paseo voice mode is now on.", + "You are the Paseo voice assistant.", + "The user cannot see your chat messages or tool calls.", + "Always use the speak tool for all user-facing communication.", + "Before calling any non-speak tool, first call speak with a short acknowledgement of what you heard and what you will do next.", + "For long-running work, use speak to provide progress updates before and during execution.", + "Treat the user input as transcribed speech.", + "If the user intent is clear, proceed without extra confirmation.", + "If the transcription seems incomplete, cut off, ambiguous, or may contain a non-obvious mistake or misspelling, ask a clarifying question via speak before taking action.", + "Use concise plain language suitable for speech output.", +].join(" "); + +const VOICE_AGENT_DISABLED_INSTRUCTION = [ + "Paseo voice mode is now off.", + "Ignore any earlier Paseo voice mode instructions in this thread.", +].join(" "); function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); @@ -29,8 +39,22 @@ export function stripVoiceModeSystemPrompt(existing?: string): string | undefine return stripped.length > 0 ? stripped : undefined; } +export function buildVoiceModeSystemPrompt(existing: string | undefined, enabled: boolean): string { + const basePrompt = stripVoiceModeSystemPrompt(existing); + const voiceInstruction = enabled + ? VOICE_AGENT_SYSTEM_INSTRUCTION + : VOICE_AGENT_DISABLED_INSTRUCTION; + const voiceBlock = [VOICE_PROMPT_BLOCK_START, voiceInstruction, VOICE_PROMPT_BLOCK_END].join( + "\n", + ); + + return [basePrompt, voiceBlock] + .filter((entry): entry is string => typeof entry === "string" && entry.length > 0) + .join("\n\n"); +} + export function wrapSpokenInput(text: string): string { - return `\n${text}\n\nThis message was spoken by the user. The user may not be looking at the chat; use speak when audio is attached, and keep a readable reply in the chat.`; + return `\n${text}\n\nThis message was spoken by the user. Respond using the speak tool only, not normal messages, because the user may not be looking at the chat.`; } export function buildVoiceAgentMcpServerConfig(params: { diff --git a/packages/server/src/server/voice-types.ts b/packages/server/src/server/voice-types.ts index 8d74af62588..9533b10c38e 100644 --- a/packages/server/src/server/voice-types.ts +++ b/packages/server/src/server/voice-types.ts @@ -2,7 +2,7 @@ export type VoiceSpeakHandler = (params: { text: string; callerAgentId: string; signal?: AbortSignal; -}) => Promise; +}) => Promise; export interface VoiceCallerContext { childAgentDefaultLabels?: Record; diff --git a/packages/server/src/server/websocket-server.relay-reconnect.test.ts b/packages/server/src/server/websocket-server.relay-reconnect.test.ts index 5025941f2ab..06e39b77798 100644 --- a/packages/server/src/server/websocket-server.relay-reconnect.test.ts +++ b/packages/server/src/server/websocket-server.relay-reconnect.test.ts @@ -709,41 +709,6 @@ describe("relay external socket reconnect behavior", () => { await server.close(); }); - test("voice output fails while detached and uses the replacement relay socket", async () => { - const server = createServer(); - const clientId = "cid-voice-reconnect"; - const oldSocket = new MockSocket(); - await attachRelayAndHello({ server, socket: oldSocket, clientId }); - const session = sessionMock.instances[0]; - const { onMessage } = session.args; - if (typeof onMessage !== "function") throw new Error("Missing session emitter"); - const audio = { - type: "audio_output", - payload: { - id: "speech:0", - groupId: "speech", - chunkIndex: 0, - isLastChunk: true, - audio: "YQ==", - format: "pcm", - isVoiceMode: true, - }, - }; - onMessage(audio); - oldSocket.sent.length = 0; - oldSocket.emit("close", 1006, ""); - expect(() => onMessage(audio)).toThrow("Voice output has no connected client"); - - const liveSocket = new MockSocket(); - await attachRelayAndHello({ server, socket: liveSocket, clientId }); - liveSocket.sent.length = 0; - onMessage(audio); - expect(sessionMock.instances).toHaveLength(1); - expect(oldSocket.sent).toEqual([]); - expect(sentEnvelopes(liveSocket).map((envelope) => envelope.message)).toEqual([audio]); - await server.close(); - }); - test("rejects sockets attached after shutdown begins", async () => { const server = createServer(); const existingSocket = new MockSocket(); @@ -1380,3 +1345,45 @@ describe("relay external socket reconnect behavior", () => { await server.close(); }); }); + +function findRpcError(socket: MockSocket): z.infer | undefined { + return sentEnvelopes(socket).find((envelope) => envelope.message?.type === "rpc_error"); +} + +describe("legacy session RPC compatibility", () => { + test("answers a removed TMAD RPC with rpc_error instead of dropping it", async () => { + const server = createServer(); + const socket = new MockSocket(); + try { + await attachDirectAndHello({ server, socket, clientId: "legacy-rpc-client" }); + + // A 0.16.0-beta.2 app still sends this after the durable queue was removed. + socket.emit( + "message", + JSON.stringify({ + type: "session", + message: { + type: "agent.queue.enqueue.request", + requestId: "legacy-queue-1", + agentId: "agent-legacy", + text: "queued while the daemon still served the durable queue", + }, + }), + ); + + await vi.waitFor(() => + expect(findRpcError(socket)).toMatchObject({ + message: { + payload: { + requestId: "legacy-queue-1", + requestType: "agent.queue.enqueue.request", + code: "unknown_schema", + }, + }, + }), + ); + } finally { + await server.close(); + } + }); +}); diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 15c8a96ed5b..8d17a50e7ce 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -21,7 +21,6 @@ import { type WorkspaceBaseBranchService, } from "./session/workspace-base-branch/service.js"; import type { CreationSnapshot } from "@getpaseo/protocol/messages"; -import type { AgentQueueService } from "./agent-queue/service.js"; import { CreationService } from "./creation/index.js"; import { MessageReceipts } from "./message-receipts/index.js"; import { WebSocket, WebSocketServer } from "ws"; @@ -410,11 +409,6 @@ function resolveCapabilityReason(params: { return state.message; } -/** Collapses an optional injected subsystem to its settled nullable form. */ -function nullable(value?: T | null): T | null { - return value ?? null; -} - function buildServerCapabilities(params: { readiness: SpeechReadinessSnapshot | null; }): ServerCapabilities | undefined { @@ -619,18 +613,7 @@ export class VoiceAssistantWebSocketServer { private dictation!: { finalTimeoutMs?: number; } | null; - private readonly voiceSpeakHandlers = new Map< - string, - { - principalId: string; - clientId: string; - attachmentId: string; - generation: string; - handler: VoiceSpeakHandler; - revoke: () => void; - } - >(); - private readonly spokenTurns = new Map(); + private readonly voiceSpeakHandlers = new Map(); private readonly voiceCallerContexts = new Map(); private readonly workspaceSetupObservation = new WorkspaceSetupObservation(); private readonly workspaceSetupRuntime: WorkspaceSetupRuntime; @@ -666,7 +649,6 @@ export class VoiceAssistantWebSocketServer { private readonly directorySync = new DirectorySyncService(); private readonly pluginRuntime: SessionOptions["pluginRuntime"]; private readonly orchestrationSkills: SessionOptions["orchestrationSkills"]; - private readonly agentQueueService: AgentQueueService | null; private async validateCompletedCreation(snapshot: CreationSnapshot): Promise { if (snapshot.workspace && snapshot.kind === "workspace") { @@ -736,7 +718,6 @@ export class VoiceAssistantWebSocketServer { pluginRuntime?: SessionOptions["pluginRuntime"], orchestrationSkills?: SessionOptions["orchestrationSkills"], workspaceLabelService?: WorkspaceLabelService, - agentQueueService?: AgentQueueService | null, ) { this.logger = logger.child({ module: "websocket-server" }); this.workspaceSetupRuntime = workspaceSetupRuntime; @@ -754,7 +735,6 @@ export class VoiceAssistantWebSocketServer { this.hubRelationships = hubRelationships ?? null; this.pluginRuntime = pluginRuntime; this.orchestrationSkills = orchestrationSkills; - this.agentQueueService = nullable(agentQueueService); this.agentManager = agentManager; this.agentStorage = agentStorage; this.agentMessages = createAgentMessageDelivery({ @@ -783,9 +763,6 @@ export class VoiceAssistantWebSocketServer { ), }); this.messageReceipts = new MessageReceipts(join(paseoHome, "agent-requests")); - // The queue's drains and the legacy send path share one receipt owner, so a - // spoken item's acceptance is readable through the same records. - this.agentQueueService?.setMessageReceipts(this.messageReceipts); this.creationService = new CreationService( join(paseoHome, "creations"), this.logger.child({ module: "creation" }), @@ -1700,8 +1677,6 @@ export class VoiceAssistantWebSocketServer { sourceId: options.sourceId, browserToolsBroker: this.browserToolsBroker, clientId: options.clientId, - /** Voice receipt reads are scoped to the principal/client pair that spoke. */ - voiceOwner: JSON.stringify([options.principalId, options.clientId]), appVersion: options.appVersion, clientCapabilities: options.clientCapabilities, permissions: options.permissions, @@ -1726,7 +1701,6 @@ export class VoiceAssistantWebSocketServer { worktreesRoot: this.worktreesRoot, agentManager: this.agentManager, agentStorage: this.agentStorage, - agentQueueService: this.agentQueueService ?? undefined, messageReceipts: this.messageReceipts, agentMessages: this.agentMessages, creationService: this.creationService, @@ -1767,48 +1741,20 @@ export class VoiceAssistantWebSocketServer { turnDetection: () => this.speech?.resolveTurnDetection() ?? null, }, voiceBridge: { - registerVoiceSpeakHandler: (agentId, attachmentId, handler, revoke) => { - const previous = this.voiceSpeakHandlers.get(agentId); - if ( - previous && - (previous.principalId !== options.principalId || - previous.clientId !== options.clientId || - previous.attachmentId !== attachmentId) - ) - throw new Error("Voice mode is already active for this agent on another device"); - const generation = randomUUID(); - this.voiceSpeakHandlers.set(agentId, { - principalId: options.principalId, - clientId: options.clientId, - attachmentId, - generation, - handler, - revoke, - }); - previous?.revoke(); - return generation; + registerVoiceSpeakHandler: (agentId, handler) => { + if (this.voiceSpeakHandlers.has(agentId)) + throw new Error("Voice mode is already active for this agent"); + this.voiceSpeakHandlers.set(agentId, handler); }, - unregisterVoiceSpeakHandler: (agentId, generation) => { - if (this.voiceSpeakHandlers.get(agentId)?.generation === generation) { - this.voiceSpeakHandlers.delete(agentId); - } + unregisterVoiceSpeakHandler: (agentId) => { + this.voiceSpeakHandlers.delete(agentId); }, - registerVoiceCallerContext: (agentId, generation, context) => { - if (this.voiceSpeakHandlers.get(agentId)?.generation === generation) { - this.voiceCallerContexts.set(agentId, context); - } + registerVoiceCallerContext: (agentId, context) => { + this.voiceCallerContexts.set(agentId, context); }, - unregisterVoiceCallerContext: (agentId, generation) => { - if ( - !this.voiceSpeakHandlers.has(agentId) || - this.voiceSpeakHandlers.get(agentId)?.generation === generation - ) { - this.voiceCallerContexts.delete(agentId); - } + unregisterVoiceCallerContext: (agentId) => { + this.voiceCallerContexts.delete(agentId); }, - hasSpokenInTurn: (agentId, turnId) => this.spokenTurns.get(agentId) === turnId, - isCurrent: (agentId, generation) => - this.voiceSpeakHandlers.get(agentId)?.generation === generation, }, dictation: this.dictation || this.speech @@ -2203,14 +2149,6 @@ export class VoiceAssistantWebSocketServer { agentTimelinePromptIndex: true, // COMPAT(agentHistorySearch): added in v0.3.0, remove gate after 2027-02-07. agentHistorySearch: true, - // COMPAT(durableAgentQueue): added in 0.11.0-beta.3.fork.1, fork-only — - // stock peers never gain it, so the gate lasts as long as stock peers - // are supported. Gates the agent.queue.* surface end to end. - durableAgentQueueV1: true, - // COMPAT(durableVoiceInputV1): added in TM-04 on 2026-10-08. Keep - // the gate while stock peers are supported. This contract adapts source - // voiceConcurrentInput to TM-02 admission and receipt reconciliation. - durableVoiceInputV1: this.agentQueueService !== null, // COMPAT(checkoutRefresh): added in v0.1.86, remove gate after 2026-11-29. checkoutRefresh: true, // COMPAT(workspaceMultiplicity): added in v0.1.97, drop the gate when floor >= v0.1.97 @@ -2233,8 +2171,6 @@ export class VoiceAssistantWebSocketServer { workspaceFileEditing: true, // COMPAT(fileByteWrites): added in v0.13.0, remove gate after 2027-04-20. fileByteWrites: true, - // COMPAT(companionStreamPortV1): added in v0.11.0-beta.3-fork, remove after 2027-04-01. - companionStreamPortV1: true, // COMPAT(providerUsageList): added in v0.1.98, drop the gate when daemon floor >= v0.1.98. providerUsageList: true, // COMPAT(agentDetach): added in v0.1.98, remove gate after 2026-12-19 once daemon floor >= v0.1.98. @@ -2441,10 +2377,7 @@ export class VoiceAssistantWebSocketServer { } public resolveVoiceSpeakHandler(callerAgentId: string): VoiceSpeakHandler | null { - // Record actual tool invocation even while detached, so reconnect cannot read it twice. - const turnId = this.agentManager.getAgent(callerAgentId)?.activeForegroundTurnId; - if (turnId) this.spokenTurns.set(callerAgentId, turnId); - return this.voiceSpeakHandlers.get(callerAgentId)?.handler ?? null; + return this.voiceSpeakHandlers.get(callerAgentId) ?? null; } public resolveVoiceCallerContext(callerAgentId: string): VoiceCallerContext | null {