diff --git a/.oxlintrc.json b/.oxlintrc.json index ae335c0e48a..e46575d11f4 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -630,6 +630,18 @@ "paseo/no-raw-pressable": "off" } }, + // Fork raw-pressable burn-down: fork-only files predating the v0.12.0 rule. Migrate to components/ui press primitives (docs/design.md §2), then delete this block. + { + "files": [ + "packages/app/src/components/provider-account-sheet.tsx", + "packages/app/src/artifacts/feed.tsx", + "packages/app/src/screens/project-pull-requests/view.tsx", + "packages/app/src/agent-stream/pinned-prompt/pinned-prompt.web.tsx" + ], + "rules": { + "paseo/no-raw-pressable": "off" + } + }, { "files": ["**/e2e/**/fixtures.ts"], "rules": { diff --git a/CLAUDE.md b/CLAUDE.md index 48f0695d6cb..8c97b04d3f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,6 +26,8 @@ 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 de6c619ae36..f6c0c9f5bb3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -7,6 +7,8 @@ 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 new file mode 100644 index 00000000000..ed12d2f8338 Binary files /dev/null and b/docs/artifact-feed.png differ diff --git a/docs/companion-stream.md b/docs/companion-stream.md new file mode 100644 index 00000000000..8b30c31b498 --- /dev/null +++ b/docs/companion-stream.md @@ -0,0 +1,68 @@ +# 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/custom-providers.md b/docs/custom-providers.md index ef0281ec7f6..384f4ae8c67 100644 --- a/docs/custom-providers.md +++ b/docs/custom-providers.md @@ -320,6 +320,12 @@ You can create multiple entries that extend the same built-in provider. Each get "Profile" here means a provider alias, and it is not an **Agent profile** — that is a named bundle of provider, model, mode, thinking option and features, stored under `daemon.agentProfiles`. See [glossary.md](glossary.md) for all four senses of the word. +Three ways to create one, all writing the same `config.json` entry: + +- **App** — Settings > Providers, then use **Add account** on a built-in row. Use **Edit account** on the new row to change its name, ID, description, or environment. +- **CLI** — `paseo provider add claude-work --extends claude --label "Claude (Work)" --env ANTHROPIC_API_KEY=sk-ant-...`, and `paseo provider rm claude-work` to delete it. +- **By hand** — edit `config.json` as below. + Example: two different Anthropic accounts as separate profiles: ```json @@ -347,7 +353,17 @@ Example: two different Anthropic accounts as separate profiles: } ``` -Each profile appears as a separate provider in the Paseo app. You can select which one to use when launching an agent. +Each account appears immediately after its built-in provider in provider lists and usage. You can select it when launching an agent. The shared agent tools return the account as its own provider ID and include `baseProviderId` in `list_providers` and `inspect_provider` so agents can recognize the relationship. + +Usage reads credentials from the account's environment without falling back to the built-in provider's credentials: + +| Provider | Account-specific usage credentials | +| -------- | -------------------------------------------------------------------- | +| Claude | `CLAUDE_CONFIG_DIR` or `CLAUDE_HOME`, containing `.credentials.json` | +| Codex | `CODEX_HOME`, containing `auth.json` | +| Copilot | `COPILOT_TOKEN`, `GITHUB_TOKEN`, or `GITHUB_PAT` | + +An account without supported OAuth credentials still appears in usage as unavailable. API-key and custom-endpoint accounts often have no subscription quota API to report. You can also combine profiles with model overrides to pin specific models per profile: diff --git a/docs/design.md b/docs/design.md index f86565e97e1..f6d99a66b28 100644 --- a/docs/design.md +++ b/docs/design.md @@ -30,6 +30,8 @@ Before adding a new component, read `components/ui/`. The primitive usually exis Hierarchy is conveyed through weight and color, not size. Most interface text is `fontSize.base`; compact metadata and hints use `fontSize.sm`. The distinction between a row's primary line and its secondary line is `foreground` versus `foregroundMuted`. +The pinned prompt at the top of the transcript (`packages/app/src/agent-stream/pinned-prompt/pinned-prompt.web.tsx`) is the one deliberate exception. It is a 0.7 transform of the real user bubble, which puts its text, corner radius, and shadow off the token ramp. Size is doing the work there because the pin has to read as the same object as the bubble it replaces, shrunk — a restyled copy on the ramp reads as a different component. Do not take it as license elsewhere, and do not "fix" it to `fontSize.sm`. + The authored interface ramp uses a 14px base. New native installs default to 15px; web and desktop default to 14px. The Appearance **Interface size** setting is the rendered `fontSize.base` value and scales the rest of the UI ramp proportionally. Primary readable content has its own `fontSize.content`, which defaults to 16px on native and 15px on web and desktop. It owns message bodies, composer input, Markdown, and PR prose. Controls, navigation, metadata, tool chrome, code, diffs, editors, and terminals stay on their interface or code tokens. **Code size** remains independent. Weight has three tiers, applied by role: diff --git a/docs/expo-router.md b/docs/expo-router.md index f81c194ffb0..49e28506041 100644 --- a/docs/expo-router.md +++ b/docs/expo-router.md @@ -109,6 +109,22 @@ store-ready protected group so a cold host deep link can survive daemon startup. Do not collapse this topology with a catch-all, `getId`, or `dangerouslySingular` workaround. +## Navigation History + +Desktop history records resting routes and the focused workspace tab after the layout store +hydrates. Browser back and forward remain owned by the browser; the desktop bracket shortcuts +step the app history. A history step selects its index before navigating so the recorder does +not append the landing location again. +Record the `/new` route's query inputs with its path so Back restores the selected host, project, +source directory, draft, and the change request the form was seeded with. A reopened tab may select +an existing duplicate with the same target; replay uses the tab that actually gained focus when +reconciling the history entry. + +An absent workspace still navigates to its workspace route. That screen asks the daemon for +recovery state and offers Restore or Unarchive when appropriate. History does not change the +workspace or agent archive state. Reload starts a new history from the restored workspace and +the focused tab in the persisted layout. + ## Agent Targets Notifications and agent URLs name a host and agent. Both use diff --git a/docs/forge-providers.md b/docs/forge-providers.md index 2d31eaef2f5..d5ae2bd03f2 100644 --- a/docs/forge-providers.md +++ b/docs/forge-providers.md @@ -224,5 +224,8 @@ are stale, run `npm run build:server`. - GitHub PR polling owns one account-wide GraphQL budget. Coordinate retained targets per host, batch their reads, and stop until GitHub's reset time when the reserve is exhausted. Never add a per-target GitHub request to the poll - path. Resolve fork PRs through their parent repository without abandoning the - shared batch. + path. +- Check a fork's own PRs before its parent's. `gh` resolves a fork's base to + its parent, so its ordinary PR commands can miss a PR opened against the + fork itself. Keep parent lookup in the shared batch and decide the redirect + per entry per tick: sibling branches can have PRs in different repositories. diff --git a/docs/glossary.md b/docs/glossary.md index a6ff393c6ab..237683cc4c9 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -14,6 +14,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here - **Project host entry** — One row in a project for a single (project, daemon) pair, aggregating that daemon's workspaces in the project. Internal. Code: `ProjectHostEntry` (`packages/app/src/utils/projects.ts:11`). Don't introduce "Checkout" as a synonym. - **Placement** — One workspace's stable foreign-key relationship to its project plus its git checkout snapshot. Internal. An explicit creation `projectId` is authoritative when active. - **Branch** — Plain git branch. UI: "Switch branch". Code: `currentBranch` in `WorkspaceGitRuntimePayloadSchema` (`packages/protocol/src/messages.ts:2136`); `BranchSwitcher` (`packages/app/src/components/branch-switcher.tsx`). +- **Base branch** — The branch a workspace compares its changes with. UI: the right side of the branch pair in the wide workspace header and "Compared with" in Changes. The header offers a picker when the host supports `checkoutBaseRefSet`. - **Forge** — Git hosting service behind Paseo's change-request features: GitHub, GitLab, Gitea, Forgejo, or a future registered adapter. Code: `ForgeService`, `forge-registry`, `forge-resolver`. Use `forge` for internal abstraction and registry IDs; use concrete forge names only when a behavior or RPC is forge-specific. - **Change request** — Forge-neutral term for a proposed branch-to-branch code change. UI normally renders the forge noun instead: GitHub/Gitea/Forgejo "PR", GitLab "MR". Code: `forge_change_request` attachments, `checkoutSource: { kind: "change_request" }`, and PR/MR status payloads. - **MR** — GitLab merge request. UI label for GitLab change requests only; do not use MR for GitHub/Gitea/Forgejo. @@ -56,7 +57,8 @@ 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`). -- **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". +- **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". - **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 new file mode 100644 index 00000000000..b5037b21d38 --- /dev/null +++ b/docs/queue-mirroring.md @@ -0,0 +1,62 @@ +# 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/docs/service-proxy.md b/docs/service-proxy.md index cab7f427748..f37ea849fe6 100644 --- a/docs/service-proxy.md +++ b/docs/service-proxy.md @@ -28,7 +28,18 @@ Local and public routes use one combined leftmost label (`script--branch--projec ## Managing workspace scripts -Configured `paseo.json` scripts can be managed without addressing their backing terminal directly: +The run menu includes `paseo.json` commands and package.json scripts from the workspace and +nested packages. Package scripts run as regular terminal commands; declare a service in +`paseo.json` when you need a managed port and URL. The package's `packageManager` field or +lockfile selects npm, pnpm, Yarn, or Bun, with the parent package's choice inherited by nested +packages. + +Discovery runs when you open the menu or list scripts. Sidebar snapshots reuse that catalog +so rendering workspace status never recursively scans the checkout. Dependency, generated, +hidden, and symlinked directories are excluded. Reopen the menu after adding or removing a +package or script. + +Both sources can be managed without addressing their backing terminal directly: ```bash paseo script ls [--cwd | --workspace ] diff --git a/docs/terminal-activity.md b/docs/terminal-activity.md index ee1f411a7a8..c31045d4f27 100644 --- a/docs/terminal-activity.md +++ b/docs/terminal-activity.md @@ -6,7 +6,7 @@ Paseo surfaces terminal activity as a tab indicator (the same "running" dot used Terminal activity is source-agnostic plumbing. `TerminalActivityTracker` holds the current per-terminal state and emits transitions to the manager, worker protocol, websocket subscription, app buckets, dots, and notifications. -The tracker defaults to unknown (`null`). Activity production lives outside terminal stream parsing: agent hook commands report coarse activity to the daemon's local `/api/terminal-activity` endpoint. +The tracker defaults to unknown (`null`). Agent hook commands report coarse activity to the daemon's local `/api/terminal-activity` endpoint. Managed regular scripts also produce activity: the launcher marks the terminal working and shell command completion marks it idle. This applies to both `paseo.json` commands and package.json scripts; services retain their separate health checks. ## Architecture @@ -30,7 +30,7 @@ Terminal directory snapshots (`terminalsChanged`) and workspace contribution cha Each `onChange` delivers both the new snapshot and the `previous` one (`{ state, changedAt }`). The transition flows unchanged up through `TerminalSession.onActivityChange` (as `{ activity, previous }`), the worker protocol's `terminalActivityChange` event, and the manager-level `subscribeTerminalActivity(listener)` stream (`{ terminalId, name, cwd, activity, previous }`). -The daemon consumes these transitions, not snapshots. When a transition moves from `working` to `idle`, the tracker records finished attention, so the terminal shows the same green finished dot as an idle agent that needs review. The websocket layer also fires a "Terminal finished" attention notification. A terminal that exits while still working emits no turn-end notification. +The daemon consumes these transitions, not snapshots. When a transition moves from `working` to `idle`, the tracker records finished attention, so the terminal shows the same green finished dot as an idle agent that needs review. The websocket layer also fires a completion notification. Managed regular scripts include their name and exit code, distinguishing success from failure. The existing presence policy suppresses notifications while you are viewing that terminal. A terminal that exits while still working emits no turn-end notification. Terminal list visibility is `workspaceId`-scoped: a terminal belongs to the workspace that created it, and same-`cwd` sibling workspaces do not see it in their terminal lists. Terminal status routing starts from that owning workspace, uses the owning workspace's `cwd`, then fans the status bucket out to every active workspace with the same `cwd`. diff --git a/docs/terminal-worker.md b/docs/terminal-worker.md index d83dea9957e..87398341b45 100644 --- a/docs/terminal-worker.md +++ b/docs/terminal-worker.md @@ -45,7 +45,7 @@ The worker writes `$PASEO_HOME/terminal-worker/.json` (owner-only) with its Never more than two workers run. A new worker launches only when none is current, none is incompatible and fewer than two run. The count comes from the records, so an unreachable worker counts, as does one whose socket probe is inconclusive, and one a cleanup could not confirm gone. When two run, the daemon starts with no current worker, and the first terminal created after one of them exits launches it. -**The frozen envelope never changes across versions:** the frame format (4-byte length + `v8.serialize`), `hello`/`helloAck`, the `listTerminals` info fields and `shutdown`. That is what lets any daemon close any worker: a kill stop sends `shutdown` to a newer worker it cannot otherwise drive. Protocol 5 hard cuts unreleased protocols 1 through 4, including the acknowledgement-based replay contract: those workers are obsolete and close. For future versions, keep a previous-version adapter so the draining worker can still be driven, and drop the adapter for the version before that. +**The frozen envelope never changes across versions:** the frame format (4-byte length + `v8.serialize`), `hello`/`helloAck`, the `listTerminals` info fields and `shutdown`. That is what lets any daemon close any worker: a kill stop sends `shutdown` to a newer worker it cannot otherwise drive. Protocol 6 adds terminal-owned managed command dispatch. A protocol 5 worker keeps existing terminals and active scripts running through the unchanged input/replay lifecycle, but cannot accept the new command variant. Starting a script uses a current worker instead of reusing a terminal on that draining worker. Protocols 1 through 4 were unreleased and close as obsolete. Keep the previous-version adapter when bumping the protocol; drop the adapter for the version before that. Tests stand up other versions with `PASEO_TERMINAL_WORKER_PROTOCOL_OVERRIDE`, read by the worker. It is test-only. @@ -66,7 +66,7 @@ The SDK advertises `terminal_chunked_replay` only because it decodes begin/data/ A worker outlives the installation that started it. An npm or desktop update replaces that installation's files, and the next terminal the old worker creates would load node-pty's `spawn-helper` and the zsh integration from paths that no longer exist. So a built daemon does not launch the worker from its install: - `npm run build` bundles the worker with esbuild (`packages/server/scripts/build-terminal-worker.mjs`) into `dist/server/terminal-worker/` with its `shell-integration/` beside it. Only node-pty stays external. A package loaded through a module-local `createRequire` is invisible to esbuild and would be missing at run time; `terminal-worker-runtime.test.ts` fails if the bundle loads anything but built-ins and node-pty. -- Before launching, the daemon copies the bundle, the shell integration and node-pty (this platform's native build only) into `$PASEO_HOME/terminal-worker/-/` and launches from there. The hash covers the bundle and node-pty, so a local rebuild of the same version gets its own copy. +- Before launching, the daemon copies the bundle, the shell integration and node-pty (this platform's native build only) into `$PASEO_HOME/terminal-worker/-/` and launches from there. The hash covers the bundle, sorted shell-integration paths and bytes, and node-pty package metadata, so an integration-only rebuild of the same version gets its own copy. - A copy is deleted once no record names it: after a draining worker exits, after a kill cleanup, and at daemon start. The daemon and the reaper delete copies, never the worker itself, so a worker exiting cannot remove a copy a new worker is about to launch from. - Dev (`.ts` source) launches from source and copies nothing. diff --git a/fork/CHANGELOG.md b/fork/CHANGELOG.md index 76401460db9..de5ebd2828e 100644 --- a/fork/CHANGELOG.md +++ b/fork/CHANGELOG.md @@ -157,6 +157,13 @@ this stable base before publishing or deploying. Real OMP on Triton remains unverified because its selected provider has no credentials; preserve the failed receipt and verify authenticated providers during host canaries. +The stable basket retains the accepted beta.1 owner deltas. Retire duplicate +#7179 and #7169 production carries in favor of stable upstream implementations; +keep fork closed-session/mode-error guards, sourced message identity, symmetric +OMP command/ACK tests and cleanup failure reporting. Keep #6762, #7057, #7062, +#7146 and #7106 because they remain unmerged. Preserve workspace-relative file +opening and account cache invalidation through stable's replacement owners. + ## 0.12.0-beta.3 base decision — 2026-10-19 Advance from the reviewed beta.1 custom merge to upstream `v0.12.0-beta.3`. diff --git a/fork/campaign/upgrade-0.12.0.manifest.txt b/fork/campaign/upgrade-0.12.0.manifest.txt new file mode 100644 index 00000000000..d582a8ffc5a --- /dev/null +++ b/fork/campaign/upgrade-0.12.0.manifest.txt @@ -0,0 +1,7 @@ +# Base: v0.12.0 (cafe4b01c8522ff39560241c5deb01427dc8dc5b) +# custom is updated separately; this successor includes the accepted beta.1 owners. +# #7179 and #7169 production implementations now come from upstream stable. +# Preserve fork guards, sourced identity, ACK correlation and cleanup regressions. +# Retain OPEN #6762/#7057/#7062/#7146/#7106 and U2a-U2f fork-only behavior. +custom +upgrade/basket-0.12.0 diff --git a/fork/handover-beta-upgrade-u2a-2026-10-17.md b/fork/handover-beta-upgrade-u2a-2026-10-17.md new file mode 100644 index 00000000000..8d0aed6964c --- /dev/null +++ b/fork/handover-beta-upgrade-u2a-2026-10-17.md @@ -0,0 +1,162 @@ +# Beta upgrade, U2a common carries handover (2026-10-17) + +Candidate branch `fork/carries-0.12.0-beta.1` in the isolated worktree +`/home/ctaylor/repos/paseo-upgrade-carries`. The U1 branch `upgrade/custom-0.12.0-beta.1` and its +worktree were not touched. Checks ran on Neptune in the shared private candidate with pinned Node +`22.20.0` and redirected git hooks. + +## Inputs + +| Input | SHA | +| --- | --- | +| U1 head (base) | `81831be87bfad35802f0a0bf0a90fc7183c4fc1c` | +| Common carries (manifest `fork/carries-0.11.1`) | `36fdadba65369dc41feb756d5b2c6004dc2a17e8` | +| Merge | `85830573a36216889faccca17124c39f4acfe7f3` (parents `81831be87`, `36fdadba`) | +| Non-Latin coverage | `d92c42b11246955c6fbb990546b9a9ba725ceca0` | +| Capability-absent coverage | `f219e61842fb3b125d9e4065b9e9426ae39296e5` | +| Rename ordering fix | `24dddacd4315f5a3ae5e4090444a2b14c1623063` | +| Final source SHA | `05e01290fbde13058031d30775096bf950d8e042` | +| Test-only drain correction | `46e14f12226658a669ba878170bd9736c736b8fd` | + +The carry manifest line owns accounts #2785, screenshots #2237, bounded byte hydration #2664, +terminal flush #3545, structured finish reasons #3950, CJK #4101 and argument hints #3369 only. +Merge base with the carry branch is `b56d6ef3c`. The carry changed 94 paths; 40 of them were also +changed by beta. + +## Conflicts + +Fresh count is 6, confirmed before resolving by `git merge-tree --write-tree` (tree +`2e0105f32`) and by the real merge. Resolutions: + +| Path | Resolution | +| --- | --- | +| `packages/protocol/src/messages.ts` | Keep beta `hopliteProvider`; add the carry's optional `providerConfigReplace` and `providerConfigRename` | +| `packages/server/src/server/websocket-server.ts` | Keep the dynamic `hopliteProvider` advertisement; add the two carry flags as `true` | +| `packages/server/src/server/session.ts` | Import union: `AgentDirectory` plus `TIMELINE_PAGE_BYTE_BUDGET` | +| `packages/app/src/provider-selection/provider-selection.test.ts` | Import union: `resolveEffectiveComposerModeId` plus the carry's `resolveProviderIconId` | +| `packages/app/src/screens/settings/providers-section.tsx` | Keep beta's `isConfigOwnedProvider(def.id)` removal guard; add the carry's account add/edit/icon props | +| `packages/server/src/terminal/terminal.test.ts` | Keep beta's CJK round-trip test (try/finally plus continuation-cell assertions); drop the duplicate carry copy | + +## Retirements + +| Topic | Decision and evidence | +| --- | --- | +| #3369 argument hints | Retired by source equivalence. Beta `acp-agent.ts` already maps `command.input?.hint ?? ""` into `argumentHint`; the merged file holds one copy and the carry contributes no unique production code. The carry's fixture case (`input: { hint: "query" }`, expectation `"query"`) is compatible with beta production and stays as coverage. | +| #4101 CJK server and protocol | Retired by source equivalence. Beta `protocol/terminal-snapshot.ts` and `server/terminal/terminal.ts` already contain the byte-identical `cell.getWidth() === 0` continuation handling from upstream #6452. | +| #4101 CJK app emulator | Retained. The emulator contract, native grids, webview, terminal pane and runtime changes are unique to the carry and merged cleanly. | +| #3950 structured finish reasons | No carry delta. The branch carries the same code as the baseline; the baseline already owns it. | + +The carry COMPAT tags were kept as written. The stale `v0.2.X` placeholder versions are recorded +here rather than rewritten into release provenance. + +## Semantic audit of the auto-merges + +The 34 files changed by both sides that merged without a conflict were reviewed for call sites, +guards, ordering and error paths. Mechanical presence of carry-added lines was used only as an +inventory. The only carry-added lines absent from the result are the three lines of the duplicate +CJK test copy that beta's version re-expresses inside try/finally with a `dispose()`. + +- **Accounts transactions.** `daemon-config-store.ts` holds both `removeProviders` and + `replaceProviders`/`renameProviders` with the apply-and-rollback transaction and a joined + rollback error. Beta's config-owned removal restriction is preserved in the UI guard while the + account props come from the carry. +- **Rename ordering and persisted-agent migration.** `websocket-server.ts` repoints live agents + first (`renameProviderOnLiveAgents`), then broadcasts the config change, then runs + `agentStorage.renameProvider` per rename, isolating a per-rename failure and broadcasting a + second config change only when records moved. The live-agent step runs before storage so a + persistence flush cannot write the old provider id back over a migrated record. The comment on + `renameProviderOnLiveAgents` states that ordering. +- **Provider-home routing and scoped usage.** Credential-home routing lives in the usage-source + plugins (`CLAUDE_CONFIG_DIR` then `CLAUDE_HOME` then `~/.claude`, keychain routes, Codex + `codexHome`), and `plugins/index.ts` invalidates account usage sources on a `providers` config + change. The app's usage model carries per-account pins and the snapshot manager adds + `baseProviderId` for grouping and icon inheritance. +- **Capability-absent behavior.** `providers-section.tsx` reads `providerConfigReplace` and + `providerConfigRename` through `useHostFeature`; account editing is hidden without the former + and the rename control is hidden without the latter. `f219e6184` adds the negative case to the + section suite. Adding an account stays offered on a host without the flags. That is the shipped + carry behavior, recorded here rather than changed. +- **Hydration.** `TIMELINE_PAGE_BYTE_BUDGET` (4 MiB) is added to `websocket/physical-socket.ts` + and wired into the projected timeline page selection in `session.ts`. Beta never changed that + module, so the constant is carry-only. The daemon e2e suite asserts bounded projected page bytes + through real fetches, non-empty pages, cursors that strictly advance, a stall guard, and + complete coverage of 400 entries. +- **Screenshots.** `codex/tool-call-mapper.ts` materializes `_meta["codex/toolSurface"]` + screenshots out of timeline entries and keeps the explanation of the 0.6 MB inline payload. +- **Flush guard.** `agent-manager.ts` wraps the coalescer `onFlush` in try/catch and warns + instead of letting a torn-down agent's deferred flush reach the process as an uncaught throw. +- **CJK emulator.** The retained app-side changes merged without conflict; the server and protocol + sides are beta's. + +## Receipts + +All evidence paths are under +`/Users/ctaylor/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u2a/` on Neptune. + +Static gates at `f219e6184`: `build:server`, `typecheck`, `lint`, `format:check` all exit 0, tree +clean. + +Focused suites, `npx vitest run --bail=1`, run per file: + +| Suite | Result | +| --- | --- | +| server provider-snapshot-manager, daemon-config-store, acp-agent, codex tool-call-mapper, agent-manager, timeline-page-bounds, usage provider-accounts, usage provider-account-discovery, usage-session | 0 | +| server daemon-e2e timeline-byte-bound | 0 | +| protocol terminal-snapshot | 0 | +| app providers-section (with the new negative case), provider-selection, terminal-emulator-runtime, provider-account-form-model, terminal-input.native | 0 | +| app browser chat-find ranges (new wide-character case), assistant-selection-copy content (new non-Latin case) | 0 | +| server claude agent, server terminal, cli 15-provider | 1, attributed below | + +Baseline attribution at `81831be87` runs the same three files with the same commands: + +- `server/src/server/agent/providers/claude/agent.test.ts` fails on "resolves the installed + Claude Code version" with `Claude binary not found while resolving`; the binary is not + provisioned in this environment. +- `server/src/terminal/terminal.test.ts` fails one case, "loads the user's zsh prompt when the + integration dir is packaged", expecting `PASEO_CUSTOM_PROMPT> `; 41 pass and 3 skip. +- `packages/cli/tests/15-provider.test.ts` fails "provider models claude should exit 0" because + the daemon reports the claude provider unavailable. + +All three fail identically at the U1 head, so they are inherited environment failures, not carry +regressions. No assertion was weakened. + +## Rename ordering correction + +The first audit of the rename path checked ordering inside one migration and missed ordering +between migrations. Two config changes could overlap: an A to B migration that was still writing +when the B to C change ran found no B records, and the first migration then persisted B while +configuration already said C. The same change published the config captured at change time, so a +completion could republish a superseded config. + +`24dddacd4` fixes both. Each change's rename batch is queued on one promise tail, so migration +order follows config order. The stored tail is re-settled after a failure, keeping one bad batch +from wedging the ones behind it while per-rename isolation stays inside the migration. Completion +broadcasts `daemonConfigStore.get()` instead of the captured config. `close()` awaits the tail +after the config subscription is released, so a pending migration cannot write storage after +teardown. The live-agent repoint stays synchronous and first, and beta's transactional owner is +untouched. + +The regression lives in `websocket-server.provider-rename.test.ts`: a delayed first storage +migration with a second rename landing while it is blocked, asserting `provider`, +`runtimeInfo.provider` and `persistence.provider` all end at the final id and that nothing +republishes the superseded config once the final one is live; a close-drain case; and a failed +batch that leaves its record alone while the next change still migrates. Run against the pre-fix +source, the ordering and drain cases fail (2 failed, 2 passed); with the fix all four pass. + +`46e14f122` corrects the ordering test to close the server first, since close awaits the rename +tail, and only then assert the record, all three persisted references, the broadcast set and a +second read. That makes the test prove the record stays at the final id after the queue drains +instead of sampling while a migration may still run. The correction is test-only; production is +unchanged from `05e01290f`, whose `build:server`, `typecheck`, `lint` and `format:check` receipts +carry. Run again against the pre-fix production source, the ordering and drain cases still fail +(2 failed, 2 passed). + +Receipts at `05e01290f`: `build:server`, `typecheck`, `lint`, `format:check` all exit 0; the +rename suite (4 tests), `mutable-provider-config-owner.test.ts` and `daemon-config-store.test.ts` +pass. At `46e14f122` the rename suite is 4 of 4 and `format:check`, `lint` and `typecheck` are 0. + +## Gaps + +- The claude binary and a usable claude provider are absent here; provider-facing integration + checks that need them stay open. +- Physical iOS and Android, packaged Electron and nine-locale sweeps remain U7 work. diff --git a/fork/handover-beta-upgrade-u2b-2026-10-17.md b/fork/handover-beta-upgrade-u2b-2026-10-17.md new file mode 100644 index 00000000000..0abccef28fa --- /dev/null +++ b/fork/handover-beta-upgrade-u2b-2026-10-17.md @@ -0,0 +1,120 @@ +# Beta upgrade, U2b infi backend handover (2026-10-17) + +Candidate branch `fork/infi-backend-0.12.0-beta.1` in the isolated worktree +`/home/ctaylor/repos/paseo-upgrade-infi-backend`. The U1 and U2a branches and worktrees were not +touched. Checks ran on Neptune in the shared private candidate. + +## Inputs + +| Input | SHA | +| --- | --- | +| U2a head (base) | `b02d333f729c02651659b3aba757da84312704d1` | +| Adapted infi backend carry | `1dd375931a0c4de5e930abb4b2cf2dc52d9cbcc5` | +| Merge | `5b2dfb6e78a23b1a5775dc496cec80b90c22cee3` (parents `b02d333f7`, `1dd375931`) | +| Behavioral receipts | `be3197a9d3a0420a7085a9d0bc00e56624ac24aa` | +| Compact owner correction | `6677c971462ee9ccf8a0fa4b4fccb1840e32b1b9` | +| Compact page states | `707b8b23ed1a40f6f57a837da981cf4fea664b41` | +| Final source SHA | `c077a85ab434351d1bad133853f73437ed6c2dd9` | + +The carry is one adapted commit, 54 files (+2751/-320), pinned to Source-IP01 `cabbc692d`, +IP02 `637360584`, IP03 `0d4161b1c`, IP04 `1967db56b`, IP07 `06b79b7c9`, IP13 `f3a66c4be`. No +author fork and no UI layer was merged. Merge base with the carry branch is `5c922d3d2`. + +## Conflicts + +Fresh count 3, confirmed by `git merge-tree --write-tree` (tree `68d9ae84a2f33db0e1542fbf0a281098092433a2`) +and by the real merge. + +| Path | Resolution | +| --- | --- | +| `packages/app/src/screens/workspace/scripts/workspace-scripts-button.tsx` | Beta's moved component keeps its shape and its `useWorkspaceScriptActions` seam; the carry's IP-04 behavior is ported in: menu-demand discovery behind `packageJsonScripts`, search, collapsible package groups, loading, retry and empty states, package-script labels, and a sheet menu on compact | +| `packages/app/src/screens/workspace/workspace-screen.tsx` | Beta's header stays as it is, with no restored mobile ternary. The scripts button gate keeps beta's structure and additionally renders for a discovery-capable host, so IP-04 stays reachable when a workspace has no configured scripts yet | +| `packages/protocol/src/messages.wire-compat.test.ts` | Import union | + +## Compact owner correction + +Compact has no scripts button in beta's layout. Beta puts scripts on a page of the workspace header +menu (`useWorkspaceScriptsMenuPages`), and the carry's discovery only reached the desktop button, so +a compact workspace could not see package scripts at all and the carry-authored compact assertions +clicked an element that does not exist. `6677c9714` and `707b8b23e` extend beta's existing hook +with the same menu-demand discovery and the same capability gate (shared query key, rows and pages +labelled by the package script name, discovery only while the menu is open) and give the Scripts +page loading, error-with-retry and empty rows, so the row a capable host shows always targets a +real page and a discovery failure is visible. No compact button was added; beta's page grid, +grouping and search stay in the desktop button. + +## Semantic audit of the auto-merges + +30 paths are changed by both sides; 3 conflicted and 27 auto-merged. The auto-merged set was +audited for call sites, guards, ordering and error paths: + +- **U2a rename serialization intact**: `providerRenameMigration`, `enqueueProviderRenameMigration`, + the close drain, and the completion broadcast of `daemonConfigStore.get()` are unchanged. +- **U1 side-conversation delivery intact**: `forwardSideConversationUpdate`, the capability set, + `hasSideConversationEventSubscription`, and the byte-budget import all survive; the U1 session + suite passes including the new base-ref denial test. +- **IP-07 base ref**: schemas, session routing, `workspace.write` entries for request and response, + the `checkoutBaseRefSet` flag, `checkout-git` `set-base-ref`, `writePaseoWorktreeBaseRef`, and + the branch-suggestion `localRefs`/`remoteRefs` metadata are present. +- **IP-02 and IP-13**: `resolveForkLocalPullRequestView`, `pickPullRequestCandidate`, + `parseStatusCheckRollup`, optional `checks` on PR facts, and the `forgeSearchChecks` flag. +- **IP-03**: the quit path keeps `isDesktopManagedDaemonRunning()` and adds the cancelable + confirmation plus `quitSignal` and `confirmStopDaemon`; no unowned-daemon authority and no + confirmation bypass. +- **IP-01**: the link parser takes `sourceCwd`/`workspaceRoot`, reports + `outsideWorkspaceDirectory`, and the stream view resolves source locations with an inline error + surface. +- **IP-04**: `discoverPackageScripts` with quoting, exclusion of dependency, generated, hidden and + symlinked directories, package-manager inheritance, the `packageJsonScripts` flag, script status + projection, and the replica-cache script snapshot. +- **Other overlaps** (`session.ts`, `websocket-server.ts`, `daemon-client.ts`, i18n, docs) hold the + carry's additions next to beta's ownership. + +No carry hunk was retired as equivalent in this layer. The only carry text dropped is the obsolete +mobile header ternary and its ghost scripts button, which beta's compact header replaced. + +Scope ruling: compact search, grouping and the desktop grid are **not adopted**. Beta's compact +header menu is the canonical compact owner and lists scripts as pages, so those desktop surfaces +stay in the desktop button. This is a scope decision, not equivalence or coverage: the desktop +keeps its bounded list, scroll and filter, and compact keeps discovery, run, terminal navigation +and resize. + +## Behavioral receipts + +| Behaviour | Evidence | +| --- | --- | +| Compact discovery, run and navigation | Browser: `workspace-package-scripts.spec.ts` case at `126` starts compact and drives the header menu: nested package script discovered, run, sheet closes, its `terminal-surface` visible, reopening reports the row `Running` | +| Resize preservation | Browser: case at `157` starts desktop, asserts the desktop trigger, narrows to compact, then drives the same compact flow, so the resize path is asserted rather than replaced | +| Old-host no-send | `packages/client/src/daemon-client.test.ts` "refuses to set a checkout base ref when the host lacks the feature" asserts the rejection and `mock.sent` length 0; `daemon-client.ts` calls `requireCheckoutBaseRefSupport()` before building the request | +| Base-ref authorization denial | `session.test.ts` "rejects a base-ref change without workspace.write" expects `access_denied` before dispatch | +| Base-ref persistence and refresh | `checkout-session.test.ts` persists the base, refreshes git state, rejects an unsafe ref before touching the checkout, and emits an error response when persisting fails | +| Quit cancel and updater | `quit-lifecycle.test.ts` covers cancel, keep-running, OS signal and updater-started quit | +| Fork-local versus parent PR | `github-service.test.ts` covers fork-redirect when the fork has no matching PR, fork-local PR resolved without redirecting, a fork-local PR crowded out of a batch page, bounded open PR listing, and listing without checks permission | +| Scripts capability absence | `workspace-scripts-button.test.tsx` with `packageJsonScripts: false` shows no discovered rows | + +## Receipts + +All evidence paths are under +`/Users/ctaylor/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u2b/` on Neptune. + +- `build:server`, `typecheck`, `lint`, `format:check` all exit 0 at `34b55a2ec`; `typecheck`, + `lint` and `format:check` exit 0 again at `c077a85ab` after the app-only compact correction, + which leaves the server and protocol declarations untouched. +- Focused suites, `npx vitest run --bail=1`: protocol checkout-pr-schema and wire-compat; + server checkout-session, workspace-scripts-service, package-scripts, terminal-notifications, + worktree-bootstrap, checkout-git, session (159), provider-rename, mutable-provider-config-owner; + app assistant-file-links parse, scripts button (12), sidebar meta-items and service-summary; + desktop quit-lifecycle; client daemon-client (177). All exit 0 except the attribution below. +- Browser, `workspace-package-scripts.spec.ts`: 4 of 4 at `c077a85ab`, covering desktop nested + scripts and bounded search plus fresh-compact and resized-compact discovery, run and navigation. +- `github-service.test.ts` fails one case, "merges pull requests with gh using merge", with + `GitHubCliMissingError`. The same file and case fail identically at `b02d333f7` (rc 1), so this is + an inherited environment limitation, not a carry regression. +- The three known environment limitations from earlier layers (claude binary, packaged zsh prompt, + claude provider unavailable) remain open. + +## Gaps + +- The claude CLI and a usable claude provider are absent here. +- Physical iOS and Android, packaged Electron and nine-locale sweeps remain U7 work. +- The U2c infi UI layer is not started. diff --git a/fork/handover-beta-upgrade-u2c-2026-10-17.md b/fork/handover-beta-upgrade-u2c-2026-10-17.md new file mode 100644 index 00000000000..95d85d489f4 --- /dev/null +++ b/fork/handover-beta-upgrade-u2c-2026-10-17.md @@ -0,0 +1,231 @@ +# Beta upgrade, U2c infi UI handover (2026-10-17) + +Candidate branch `fork/infi-ui-0.12.0-beta.1` in the isolated worktree +`/home/ctaylor/repos/paseo-upgrade-infi-ui`. The U1, U2a and U2b branches and worktrees were not +touched. Checks ran on Neptune in the shared private candidate. + +## Inputs + +| Input | SHA | +| --- | --- | +| U2b head (base) | `d9e19ff7d5776fee993d93a354375b2a367bdafc` | +| Adapted infi UI carry | `133ff0f7e0234da8aa684a23a8da31024531242d` | +| Merge | `07e3835f2c7d6363c631a069c028bfd4e1939d6e` (parents `d9e19ff7d`, `133ff0f7e`) | +| Header dependency fix | `ed1a399176ac497f5a7ead4cd163f1a8f8945a56` | +| History route-context fix | `bcc4a49ed48b3c41040fa1db9466328d0a5b0a8a` | +| Suite rename for JSX cases | `895f1c660598cb20378c8992697e4cf6ba5ddece` | +| Handoff suite lint and JSX runtime | `31911d43611816b9843e48005e60e241949e49c0` | +| Formatter pass on the new evidence | `d372efd5aaceb36cab683beecc3188633dd32935` | +| Handoff evidence corrections | `d7f65eadbfa1186e7b85d671e5bde81be055d0a5` | +| Daemon-side handoff setup proof | `7d8d787cae45f6b326164ad591c22760d59b4ea9` | +| Pin fixture turn count | `f97f1d173ae5de6ddb261e0281b1277cec7773da` | +| E2E helper type for the thinking option | `1005bda7826c961597f9f6ebc1ae1c561f858e4c` | +| Final source SHA | `1005bda7826c961597f9f6ebc1ae1c561f858e4c` | + +Merge base with the carry branch is `5c922d3d2`. The carry covers IP-05, IP-06, IP-08, IP-09, IP-10, +IP-11 and IP-14. + +The ledger itself is a docs-only commit on top of the source head; `fork/**/*.md` is outside the +formatter's scope (`.oxfmtrc.json`), so it carries no formatter pass. + +## Footprint + +The merge touches `packages/app` and three docs only: 83 files, +5241/-99. `git diff --stat` over +`packages/server`, `packages/protocol`, `packages/client`, `packages/cli`, `packages/relay` and +`packages/desktop` is empty, so the U1 side-conversation delivery, the U2a rename serialization and +the U2b backend and capability surfaces are untouched by construction. + +## Conflicts + +Fresh count 10 from `git merge-tree --write-tree`, 11 in the real merge. Six of the eleven are the +backend carry replayed on a different base, with no UI delta, and are byte-identical to the U2b head +after resolution: + +| Path | Resolution | +| --- | --- | +| `packages/app/e2e/browser/workspace-package-scripts.spec.ts`, `packages/app/src/assistant-file-links/parse.test.ts`, `packages/app/src/screens/workspace/scripts/workspace-scripts-button.tsx`, `packages/client/src/daemon-client.ts`, `packages/client/src/daemon-client.test.ts`, `packages/protocol/src/messages.wire-compat.test.ts` | ours | + +The five UI conflicts: + +| Path | Resolution | +| --- | --- | +| `packages/app/src/components/message.tsx` | Beta's reordered imports; `AgentDeepLinkTarget` re-added next to `PlanCard` and the pin plumbing re-applied by hand (`source` on `ToolCallProps`, in the destructure, on `PlanCard`, and in `areToolCallPropsEqual`) because the conflict block was imports only while the body already carried the carry's changes | +| `packages/app/src/app/new.tsx` | Beta's `WorkspaceComposerEditingSessionsProvider`/`ComposerEditingScope` shell kept with `initialChangeRequest` passed to `NewWorkspaceScreen`; import union with `parseInitialChangeRequest` | +| `packages/app/src/components/plan-card.tsx` | Imports only; beta's set kept plus `AgentDeepLinkTarget`, `PlanCopyActions`, `PlanHandoffButton`. Beta's body already carried `source`, `PlanCopyActions` and the conditional `PlanHandoffButton` | +| `packages/app/src/agent-stream/view.tsx` | Union of beta's `destinationRoot` and the carry's `planSource` memo; beta's body already threads `source` through both `ToolCallSlot` call sites and `ToolCallSlotProps` | +| `packages/app/src/screens/workspace/workspace-screen.tsx` | Beta's extracted `WorkspaceHeaderProjectRow` module and header menu kept; the wide branch pair ported into that module (`branches` prop, `WorkspaceHeaderBranchesModel` exported there), beta's title bar extended with `baseRefName`/`workspaceDirectory`/`normalizedWorkspaceId` and the branches memo, and `baseRef` carried through the checkout-state derivation to `baseRefName` | + +## Retired carry hunks + +Three, each with evidence rather than equivalence: + +- The carry's inline `WorkspaceHeaderProjectRow` and its local `WorkspaceHeaderBranchesModel`. Beta + moved the component into `@/screens/workspace/workspace-header-project-row`, and the branch pair + was ported there. No `headerProjectRow*` style remains in `workspace-screen.tsx`. +- `{isMobile && workspaceScripts.length > 0 ? : null}` in the title + bar. Beta's title bar has neither the button nor a `workspaceScripts` prop; beta's compact header + menu owns scripts as pages, which U2b extended with menu-demand discovery (`6677c9714`, + `707b8b23e`). +- `{!isMobile && workspaceDescriptor && workspaceDescriptor.scripts.length > 0 ? ...}` in + `headerRight`. Beta's gate is `workspaceDescriptor && (workspaceDescriptor.scripts.length > 0 || + supportsPackageJsonScripts)`, a superset for the discovery-capable host and the gate U2b's carry + introduced. Restoring the carry's gate would have removed the package.json entry point. + +Compact search and grouping stay **not adopted**, per the U2b scope ruling. Beta keeps tab, header, +route and compact-menu ownership. + +## Semantic audit of the auto-merges + +Denominators, all reproducible from the merge: + +| Measure | Count | +| --- | --- | +| Paths changed by both sides versus `5c922d3d2` | 69 | +| Real conflicts | 11 | +| Both-side paths auto-merged | 59 | +| ... byte-identical on both sides | 21 | +| ... requiring a content merge | 38 | +| ... merged result byte-identical to the U2b head | 15 | +| ... genuine unions of both sides | 23 | +| ... merged result equal to the carry | 0 | +| Merge versus U2b head | 86 paths (83 under `packages/app`) | + +The preflight figure "28 files changed by both sides, 11 conflicted and 17 auto-merged" describes a +different set: 28 is the UI-layer carry delta (`1dd375931` -> `133ff0f7e`, 85 paths) intersected with +paths beta also changed, and inside that 28 it is 5 conflicted and 23 auto-merged, because six of the +eleven conflicts are backend-replay paths outside it. + +Observed blob facts for the 38 content merges: the merged blob equals the U2b head in 15 paths, +differs from both sides in 23, and equals the carry in 0. That is a statement about content, not a +preservation proof; preservation is established by the per-path ownership, guard, ordering and +cleanup audit below, and by the 21 byte-identical paths, where `ours:path` and `theirs:path` are the +same blob. + +**The 21 byte-identical paths** (backend carry replay, accepted in U2b) have `ours:path` and +`theirs:path` at the same blob, so the merged content equals both sides by construction. They are +`packages/server/**` (session, websocket-server, worktree-bootstrap, checkout-git, forge and github +services and their tests, package-scripts, workspace-scripts-service, script-status-projection, +operation-permissions, workspace-script-runtime-store, worktree-metadata, +websocket-server.terminal-notifications), `packages/desktop/src/daemon/quit-lifecycle*`, +`packages/app/e2e/support/helpers/workspace-setup.ts`, +`packages/app/src/components/sidebar/sidebar-workspace-menu.tsx`, +`packages/app/src/components/sidebar/workspace-meta-row/*`, `docs/forge-providers.md` and +`docs/terminal-activity.md`. + +**The 15 paths whose merge equals the U2b head** keep ours byte for byte, and every line the carry +added is present in ours, so the carry's change is a subset of the change U2b already adapted: +`packages/server/src/{server/session.ts,server/websocket-server.ts,server/worktree-bootstrap*.ts, +services/forge-service.ts,services/github-service*.ts,utils/checkout-git*.ts}`, +`packages/protocol/src/{messages.ts,messages.checkout-pr-schema.test.ts}`, +`packages/desktop/src/main.ts`, `docs/service-proxy.md`, +`packages/app/src/assistant-file-links/parse.ts` and `packages/app/src/runtime/replica-cache/index.ts`. + +**The 23 unions**, reviewed for ownership, guards, ordering and cleanup: + +- `app/_layout.tsx` — the carry mounts `NavigationHistoryRecorder` once, inside `ProvidersWrapper` + after `HostSessionManager` and inside the appearance and voice providers; it renders nothing and + touches no route registration, so beta's route tree is untouched. +- `navigation/history` seam — recording is an effect on (pathname, focused tab of that pathname's + workspace) rather than a raw store subscription, which keeps the torn `navigateToWorkspace` sample + invisible; replay moves the index before navigating (`store.setIndex(nextIndex)` at + `navigation/history/replay.ts:81`) so the landing location is a no-op for the recorder; `pushEntry` + drops the forward branch and caps at 100; `entriesEqual` identifies a route entry by its path, so a + distinct change request is a distinct entry. +- `keyboard/keyboard-shortcuts.ts` and `keyboard/actions.ts` — four history entries (`Cmd+[`, + `Cmd+]`, `Ctrl+[`, `Ctrl+]`), each desktop-only with `commandCenter: false` and `terminal: false` + where it applies, no duplicates; beta's shortcut table and dispatch are unchanged. +- `hooks/use-keyboard-shortcuts.ts` — `history-go` maps to `goHistory(action.delta)` and returns its + handled flag; beta's `router-back`/`router-push` cases are untouched. +- `components/sidebar-workspace-list.tsx` — the project PR shortcut renders only for a row with a + worktree target on a host whose `worktreeSupport !== "unsupported"`, behind `actionsVisible`; the + carry's `useSidebarProjectStatus`/`statusEnteredAt` plumbing sits beside beta's row content. +- `components/sidebar/project-leading-visual.tsx` and + `components/sidebar/sidebar-workspace-row-content.tsx` — `useStatusPulse` wraps the status dot and + takes the bucket's `enteredAt`. The hook cancels its animation and clears its timer on cleanup, + restores opacity, keeps the original expiry (`enteredAt + 60s`) rather than restarting it, and + returns early under reduced motion or while the retained panel is inactive. Beta's "busy is the + ring, not a dot" rule survives in the merged comment and markup. +- `hooks/sidebar-workspaces-view-model.ts` (and its suite) — `deriveProjectStatusBucket` stays as a + wrapper over the new `deriveProjectStatus`, which returns `{ bucket, enteredAt }` where `enteredAt` + is the latest timestamp among members that match the aggregated bucket; beta's bucketing is + unchanged. +- `screens/new-workspace-screen.tsx` — the seeded change request attaches exactly once behind an + `initialRequestAttached` ref, starts the form in worktree isolation + (`initialWorktree: Boolean(initialChangeRequest)`), and derives the initial picker selection with + `allowAutoPrSelection: false`, so a later user selection is not overwritten. +- `stores/workspace-layout-store.ts` — the carry adds an injectable + `storage: StateStorage = AsyncStorage` factory parameter and passes it to + `createValidatedPersistStorage`; beta's persist name, version, migrate and partialize are untouched. +- `vitest.config.ts` — `optimizeDeps.include` gains `react`, `react-dom/client` and two + react-native-web style modules for the jsdom and browser suites; beta's exclude list is intact. +- `docs/glossary.md` — union of the carry's "Base branch" term (which the ported header branch pair + and the Changes "Compared with" label depend on) and beta's forge terms. +- `e2e/browser/plan-card-markdown.spec.ts` — the carry's handoff case lands on beta's spec; this + layer extends it with the non-overwrite, setup-preservation and no-auto-send assertions. +- The nine `i18n/resources/*.ts` files — union of carry and beta keys; the locale parity suite + compares every locale's flattened key set against English and passes. + +## Behavioral receipts + +All evidence paths are under +`/Users/ctaylor/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u2c/` on Neptune. + +- `build:client`, `build:server`, `typecheck`, `format:check` exit 0 and `lint` exits 1 at + `07e3835f2` (`checks-07e3835f2.log`). The single lint error is the header memo reading + `normalizedWorkspaceId` without listing it; `ed1a39917` fixes it. +- `typecheck`, `lint` and `format:check` exit 0 at `ed1a39917` (`checks-ed1a39917.log`). +- `typecheck`, `lint` and `format:check` exit 0 at `d372efd5a` (`checks-d372efd5a.log`). +- `typecheck`, `lint` and `format:check` exit 0 at `1005bda78` (`checks-1005bda78.log`), after the + type-only e2e helper change. The layer's last product-relevant static receipt is `d372efd5a`; the + commits after it touch tests and the ledger only. +- Focused suites, `npx vitest run --bail=1`, 457 tests pass at `7d8d787ca` + (`tests-7d8d787ca.log`), including the four navigation-history suites, the handoff suite, the + pinned-prompt model suite and the locale parity suite that compares every locale's flattened key + set against English. Earlier runs: `tests-d7f65eadb.log` (81 of 81 for the four touched suites) + and `tests-895f1c660.log`. +- Browser, pinned UI only, desktop and compact: + - `project-pull-requests.spec.ts` 2 of 2 and `branch-switcher.spec.ts` 1 of 1 pass at + `d7f65eadb` (`browser-d7f65eadb.log`). + - `plan-card-markdown.spec.ts` 3 of 3 passes at `7d8d787ca` + (`browser-plan-card-7d8d787ca.log`). + - `pinned-prompt.spec.ts` 6 of 6 passes at `f97f1d173` + (`browser-pinned-prompt-f97f1d173.log`) after the fixture repair below. + +### Browser failures and the repair + +The first gate run failed four cases. Both causes are recorded here rather than waived. + +**Handoff case.** The setup assertions read the composer chrome, and the seeded mock model +(`e2e-fast-stream`) is `isSelectable: false` with no `thinkingOptions`, so no provider, model or +thinking selector renders. Replaced with daemon-side proof: the spec seeds `ten-second-stream` with +`thinkingOptionId: "high"` and asserts the created destination agent's `provider`, `model` and +`thinkingOptionId` equal the source agent's, with the source's `thinkingOptionId` pinned to `"high"` +so the effort check cannot pass vacuously. Every pre-existing assertion is unchanged. One type-only +test-infrastructure fix went with it: `seed-client.ts`'s `fetchAgents` return type now lists +`thinkingOptionId`, which the daemon payload already carries — `packages/protocol/src/agent-types.ts` +types it on the agent payload, `packages/client/src/daemon-client.ts:903` on the client's agent +record, and `packages/app/src/stores/session-store.ts:68` on the `Agent` the app reads it from. + +**Pin cases.** Quantified with a temporary diagnostic spec (uncommitted, deleted) that printed +scroll geometry: at 12 seeded turns the transcript was `scrollHeight` 1914 against a 696px +viewport, so at maximum `scrollTop` (1218) prompt 8's bubble bottom sat 25px below the transcript +top with no scroll range left, and `scrollPromptAboveFold(prompts[8])` could never reach its +precondition. Content below that row was 671px against the 696px viewport, so the row could +approach the top no closer than 25px. Prompts 6 and 7 clear the top on the same fixture, and their +tests passed. The same three cases failed identically at `07e3835f2` +(`browser-pinned-prompt-baseline-07e3835f2.log`), which attributes them to the checkpoint, not to +the later commits. The repair is fixture-only: `LOADED_TURNS` 12 -> 14, so the seeded transcript has +enough content below `prompts[8]` to fill the viewport and the helper still derives `newestPrompt` +itself. `prompts[8]` and every behavioral assertion are unchanged, no timeout moved and no product +code changed. Measured after the repair (`pin-diag-14.log`): at maximum scroll prompt 8's bubble +bottom is 273px above the transcript top, 345px of headroom. + +## Gaps + +- Coverage boundary, not a waived bug: the pin's behavior for a turn whose remaining content is + shorter than the transcript viewport is unreachable, because no scroll position can put such a + prompt above the fold. That is a precondition no fixture can satisfy, and it says nothing about + whether the pin is correct there. The repaired fixture proves the reachable case with `prompts[8]` + and 345px of headroom. +- The claude CLI and a usable claude provider are absent here. +- Physical iOS and Android, packaged Electron and nine-locale sweeps remain U7 work. diff --git a/fork/handover-beta-upgrade-u2d-2026-10-17.md b/fork/handover-beta-upgrade-u2d-2026-10-17.md new file mode 100644 index 00000000000..8e771a3a9dd --- /dev/null +++ b/fork/handover-beta-upgrade-u2d-2026-10-17.md @@ -0,0 +1,380 @@ +# Beta upgrade, U2d TMAD baseline handover (2026-10-17) + +Candidate branch `fork/tmad-baseline-0.12.0-beta.1` in the isolated worktree +`/home/ctaylor/repos/paseo-upgrade-tmad-baseline`. The U1, U2a, U2b and U2c branches and worktrees +were not touched. Checks run on Neptune in the shared private candidate. + +## Inputs + +| Input | SHA | +| --- | --- | +| U2c corrected head (base) | `84ba5a6916e9621f8975723ddee06626ca6a6546` | +| Pinned TMAD baseline carry | `139e0c81e8eb51b0f97551171b2217838c3ebab5` | +| Merge base | `94ca59a972a7842b67adfa454e6d0ba606f7cd71` | +| Merge | `27daed7df89a7a2ff06c0f6ce0194c1619034406` (parents `84ba5a691`, `139e0c81e`) | +| Client type and import fixes | `c3a78a49ad47e2e754b30fdb61ade29fa69573eb` | +| Beta-owner integration fixes | `f2ded6715ecae81680f80c53a218977ed315bf74` | + +## What the carry is + +`139e0c81e` is the head of `fork/tmad-0.11.1`, assembled on the 0.11.1 basket after `custom`, +`fork/carries`, `fork/infi-backend` and `fork/infi-ui` were merged. It therefore contains our own +earlier layers in their 0.11.1 form as well as the TMAD baseline: its own side-conversation repair, +its own wide-header branch pair, and its own copies of the pinned-prompt, plan-card and +project-pull-requests specs. That is why the overlap is 227 paths. + +## Denominators + +| Measure | Value | +| --- | --- | +| Ours versus base | 1000 paths | +| Carry versus base | 369 paths | +| Changed by both sides | 227 | +| Both-side auto-merged | 215 (121 byte-identical, 94 content-merged) | +| Conflicts (`merge-tree` and the real merge agree) | 12 (19 hunks) | +| Carry-only paths | 142 (49 `fork/plans/tmad-port`, 44 app, 32 server, 6 protocol, rest cli/client/scripts) | +| Content merges equal to the U2c head | 57 | +| Content merges that are unions | 33 | +| Content merges equal to the carry | 4 | + +## Conflicts and resolutions + +| Path | Hunks | Resolution | +| --- | --- | --- | +| `packages/protocol/src/messages.ts` | 2 | Ours' private `internal` marker and the side-conversation selectors kept; the carry's optional `artifacts`/`companionEntries` agent facts and the `agent.queue.update` selector added with its COMPAT tag | +| `packages/client/src/daemon-client.ts` | 1 | Ours' `EVENT_SELECTOR_FEATURES` map kept and `agent.queue.update` mapped to `durableAgentQueueV1`; the carry's duplicate `VoiceTransport` declaration dropped because the merged file already had it once | +| `packages/app/src/contexts/session-context.tsx` | 1 | Union of the side-conversation selectors and `agent.queue.update` | +| `packages/server/src/server/session.ts` | 2 | U1's subscription-based forwarder kept as the owner (the carry's same-named duplicate was removed); the wait path's liveness check became queue-aware so a queued-but-not-live agent is not reported missing | +| `packages/server/src/server/agent/agent-prompt.ts` | 1 | Ours' delivery/dispatch call kept and the carry's `replaceRunning: params.replaceRunning ?? true` admission control added | +| `packages/server/src/server/agent/agent-projections.ts` | 2 | Union of `internal` and the artifacts/companion facts | +| `packages/server/src/server/agent/agent-prompt.test.ts` | 2 | Import union reduced to `sendPromptToAgent` (the notification helpers moved to `agent-messages`); both test blocks kept | +| `packages/server/src/server/agent/mcp-server.test.ts` | 1 | Ours' aliased import plus the carry's tool-catalog and TTS imports | +| `packages/server/src/server/session.test.ts` | 1 | Both side-conversation test blocks kept | +| `packages/app/src/panels/agent-panel.tsx` | 2 | Beta's panel and composer hooks kept; the artifacts/chat switcher, `RetainedPanel` wrapper and `viewOptions` ported in, with beta's sheet facts row inside | +| `packages/app/src/screens/workspace/workspace-screen.tsx` | 3 | Beta's structure kept (the carry's inline switcher/menu copies retired); `handleViewArtifacts`/`handleFindInChat` restored and threaded into beta's compact tab switcher | +| `packages/app/src/components/message.tsx` | 1 | Beta's renderer kept; the import union of the icons the retained surfaces need | + +Three fixes followed the merge, each found by an exact-SHA gate: `VoiceTransport` restored in the +client, the moved notification helpers dropped from the test's union import, and the duplicate +forwarder removed. Two more came from the integration pass: the companion feed now uses beta's +`MarkdownRenderer` (no `enableHtmlish` prop) and the stored-payload builder extracts its stream facts +to stay under the complexity limit. + +Four more gate findings, each fixed without changing behavior: the client's `VoiceTransport` type was +restored, the test's union import no longer pulls helpers that moved to `agent-messages`, the +duplicate side-conversation forwarder was removed so U1's subscription lane stays the only one, and +`packages/server/src/server/session.ts`'s event-category switch moved its one-to-one cases into +`DIRECT_EVENT_CATEGORIES` to stay under the complexity limit. The composer memo at +`packages/app/src/composer/input/input.tsx` (the overlay container that renders the dictation and +realtime-voice overlays) was missing `isAgentRunning`, `isCancellingAgent` and `onCancelAgent` from +its dependency list; those are the dependencies added, not voice-overlay-only ones. + +### Sign-off recorded before the test edits + +The coordinator's sign-off authorizes, in this layer: the bounded test setup fix for the queue +enqueue case (explicit source, targeted response capture that keeps the payload expectations, and an +independent queue-update assertion), with no production reply-routing change; explicit +`delivery.permits` positive and negative proof in the queue ownership case; explicit +`subscription.release.request` coverage separate from `clearAgentTimelineSubscription`; and the +same-client capable, incapable, capable reconnect selector case. A new provider-mounting test file is +acceptable where no existing file fits, reusing the existing suites and jobs. + +Final advisor review found that the queue case had not completed the authorized explicit +`delivery.permits` requirement: its earlier receipt established destination isolation and +`SessionAuthorization.allowsOutbound`, which is authorization evidence, not delivery-owner proof. +The side-conversation tests had separate permits assertions; they do not receipt the queue case. +Before this final test-only edit, the inspected design was sent to the advisor: retain the actual +emitted queue update object, assert its owner permitted and unsubscribed/incapable sources denied, +then assert the same object's owner denied after the real release request. Existing authorization, +delivery, release, later-source and downgrade/restoration assertions remain. No proof values or +permits outcomes are synthesized. The changed case alone is rerun with required static gates. + +## Audit of all 94 content merges + +**57 equal to the U2c head.** Every line the carry added is present in the merged file for 49 of them. +The 8 with differences are all U2b/U2c-owned adaptations, each checked by hand: `docs/expo-router.md` +(the U2c sentence now names the change request), `navigation/history/{model,recorder,model.test}.ts` +(the change request is recorded and replayed), `app/new.tsx` (same line at beta's indentation), +`pinned-prompt.spec.ts` (`LOADED_TURNS` is 14 after the U2c fixture repair), +`workspace-package-scripts.spec.ts` (the U2b compact-owner flow; the carry's compact search is not +adopted by the U2b scope ruling), and `terminal.test.ts` (the carry's CJK round-trip test is present, +the differences are formatting and import order). No unique required carry content is missing. + +**33 unions**, reviewed for ownership, guards, ordering and cleanup. The load-bearing ones: +`websocket-server.ts` and `bootstrap.ts` carry the queue service and capability advertisement; +`stores/session-store.ts` carries the revision-guarded queue mirror plus artifact and companion facts; +`composer/index.tsx` and `composer/input/*` carry the queue admission semantics +(`SendBehavior = ActiveTurnBehavior | "queue"`, queue plus pending permission resolves to interrupt) +over beta's composer; `agent-stream/view.tsx` keeps U2c's pin and plan-source plumbing; +`protocol/agent-types.ts` adds only optional artifact types; `agent-manager.ts` honours +`requireNoPendingPermissions`; the nine locale files are unions whose parity suite compares every +locale's key set against English; the rest are docs and test-infrastructure unions. + +**4 equal to the carry**, each ours plus additions, verified line by line: +`workspace-desktop-tabs-row.tsx` (+6: Search icon and the `viewArtifacts`/`findInChat` labels), +`agent-sdk-types.ts` (+2 optional admission guard), `agent-storage.ts` (+4/-1 optional artifact and +companion schemas on the stored record; the record schema is not strict, so old records parse and a +downgrade strips the new keys), `operation-permissions.ts` (+25 queue, artifact and voice operations +with read/write scopes; the daemon's own suite asserts every inbound and outbound operation is +authorized). + +## The four seams the review asked about + +**Queue receipt owner before activation.** `bootstrap.ts` constructs `AgentQueueService` with its +store, agent manager, agent storage and logger before the server accepts connections — the comment +records that loading and dispatching are separate phases — and activation happens after +`beginAcceptingConnections()`. Voice input and composer queueing reach the same service through +`sendOrQueuePromptToAgent`, so one admission and receipt path serves both. + +**Selector filtering at reconnect.** The client re-evaluates `filterSupportedEventSelectors` on every +send, "including the restore after a reconnect, so a downgrade to a host without the feature never +sees the selector" (the comment at the call site). The daemon side broadcasts `agent.queue.update` +only to clients that advertise `CLIENT_CAPS.durableAgentQueue`, checked per source. + +**Old-host zero send.** The app reads `serverInfo.features.durableAgentQueueV1` before enabling the +durable queue and before flushing the outbox on each server-info arrival; without the flag the client +keeps its local in-memory queue and sends no queue RPC. The selector is dropped for the same reason, +and the queue RPC block is documented as unreachable without the flag. + +**Beta voice and Markdown owners.** The carry touches no file under `components/markdown/**`, so beta's +renderer, links, Find and native selection are untouched by construction; the companion feed now +calls beta's `MarkdownRenderer` with its supported props. The audio files take small additive carry +deltas on top of beta's files (base to ours is empty for `audio-engine.web.ts`, +`audio-engine.native.ts`, `playback.ts` and `voice-context.tsx`), so beta keeps the shared audio and +playback owner and gains cancellation-during-preparation and microphone-loss reporting. + +## Accepted-layer contracts + +Still present after the merge: U1's `forwardSideConversationUpdate` and +`hasSideConversationEventSubscription`; U2a's `providerRenameMigration` and +`enqueueProviderRenameMigration`; U2b's `useWorkspaceScriptsMenuPages` and +`supportsPackageJsonScripts`; U2c's `WorkspaceHeaderBranchesModel`, `PlanHandoffButton`, the pinned +prompt and the recorded `changeRequest`. + +## Assembly fixes + +Both are present: the session snapshot suite stubs async-storage in memory +(`packages/app/src/stores/session-store.test.ts`), and the queue service is loaded before it is +activated. The app's `pretypecheck` builds the native audio workspace first. + +## Gates + +All execution uses Neptune's exclusive private candidate, Node 22.20.0. Receipt paths below are +relative to `~/.paseo-fork/candidates/upgrade-0.12.0-beta.1/`. No build or test ran on Uranus. +The retained-file code and corrected browser contracts are committed at +`33e270f60987a29890039f1d619203e55ca27827`. The final browser adapters are +`a61591ddb285e8082591f165f66a068fdfcb86e1`; the delivery-proof test addition is +`87c8049f5985c1604ee864a78633ddb1e19dfd8e`. Neither changes product code. Later handover-only +commits do not retimestamp tests. + +The sealed manifest `evidence/u2d/receipts-87c8049f5.sha256` inventories 139 receipt files, +including original failures, final logs, traces, images, videos and wire/snapshot observations. +Its SHA-256 is `f313a88ccb2e73db7b277b1851949ac24f5cd3867630de9e8e4382c385d02bed`. +All entries verify; `evidence/u2d/receipt-integrity-87c8049f5.txt` records the check. The later +advisor receipt, independent coordinator check (`evidence/u2d/coordinator-integrity-87c8049f5.txt`) +and handover-only static receipt are separate from this sealed inventory. + +Persistent advisor `3f2c7ea5-1328-4cd7-85c3-8c3d3ddbe4ff` gave final **ACCEPT** for U2d source +and evidence at `87c8049f5985c1604ee864a78633ddb1e19dfd8e`, with no blocking finding in the +code, ownership-proof assertions or reviewed ledger draft. The exact verdict is retained in +`evidence/u2d/advisor-final-87c8049f5.txt`. Acceptance covers this bounded baseline only, with +the gaps below still open; it grants no ADVANCE or activation. + +| Gate | Executed SHA | Result and receipt | +| --- | --- | --- | +| Client/server declaration stacks | `f2ded6715ecae81680f80c53a218977ed315bf74` | Both builds exit 0, `evidence/u2d/checks-f2ded6715.log`. Later server changes are the source-reviewed mechanical category extraction and whitespace; current retained-file repair is app-only. | +| App focused baseline | `e63d7fa98085c4b9fbc5ba09464f8651daa1c6a1` | 21 files / 332 tests pass, `evidence/u2d/tests-app-e63d7fa98.log`: composer actions/state, outbox/sync/mirror, voice/audio, Find, companion model, locale parity, U2b scripts and U2c handoff/history/pin. | +| Protocol queue and old/new parsing | `e63d7fa98085c4b9fbc5ba09464f8651daa1c6a1` | 2 files / 29 tests pass, `evidence/u2d/tests-protocol-e63d7fa98.log`. | +| Protocol artifacts/companion/voice | `71dcafa6dc75b0d9735fd7043440049d33ce4f79` | 3 files / 11 tests pass, `evidence/u2d/protocol-remaining-71dcafa6d.log`. | +| Server queue/receipts/collection | `71dcafa6dc75b0d9735fd7043440049d33ce4f79` | 7 files / 87 tests pass, `evidence/u2d/server-remaining-71dcafa6d.log`. This fills the suites not reached by the earlier bailed server batch. | +| Merged prompt and MCP behavior | `71dcafa6dc75b0d9735fd7043440049d33ce4f79` | 2 files / 158 tests pass, `evidence/u2d/merged-agent-tests-71dcafa6d.log`. | +| Session ownership and queue subscription suite | `17771efb2e6d2b1c109a2b86c6e0d46221ffdd81` | 170 tests pass, `evidence/u2d/session-final.log`; later ACK discriminant guard rerun alone at `71dcafa6d`, 1 pass / 169 skipped, `evidence/u2d/static-focused-71dcafa6d.log`. The production `session.ts` delta after this receipt is whitespace-only. | +| Actual queue delivery proof | `87c8049f5985c1604ee864a78633ddb1e19dfd8e` | Changed ownership case 1 pass / 169 skipped, `evidence/u2d/queue-proof-87c8049f5.log`: actual emitted message permits its owner, rejects unsubscribed/incapable sources and rejects its owner after release. Authorization checks remain distinct. This completes the earlier missing proof; earlier session greens alone did not establish it. | +| Registered reconnect handler | `71dcafa6dc75b0d9735fd7043440049d33ce4f79` | 3 tests pass after typed-mock correction, `evidence/u2d/handler-corrected-71dcafa6d.log`. Initial 3/3 at `9ec641052f6ab92314e94a64372f12c5d57216ce` remains in `evidence/u2d/status-handler.log`. | +| Strengthened reconnect selector | `f605c8dd0e49ab6a241cc634cd5a76e93bb94361` | Selector 1 pass and handler 3 pass, `evidence/u2d/reconnect-f605c8dd0.log`. Every incapable request excludes the selector; real completed flush precedes downgrade, exact pending item survives and dispatches once on restoration. Later static findings in that log were corrected separately. | +| Old-host voice adapter | `5d9d91d4337b8e88895dd81e44ec008357bb1a7a` | Changed case 1 pass / 31 skipped, `evidence/u2d/voice-absent-5d9d91d43.log`: exactly two adapter arguments, zero receipt reads and cleanup retained. | +| Unsupported retained-file rendering | `33e270f60987a29890039f1d619203e55ca27827` | New real-feed cases 2/2 pass, `evidence/u2d/retained-files-focused-33e270f60.log`: supplied card opens through workspace-file navigation; absent files use the ordinary empty state. Both keep the upgrade notice and avoid companion mutation calls. | +| Exact retained-file static gates | `33e270f60987a29890039f1d619203e55ca27827` | Typecheck, repository lint and format check all exit 0, `evidence/u2d/static-33e270f60.log`. Advisor source-cleared this exact commit; final receipt review remains separate. | +| Exact browser-adapter static gates | `a61591ddb285e8082591f165f66a068fdfcb86e1` | Typecheck, repository lint and format check all exit 0, `evidence/u2d/static-a61591ddb.log`. Advisor source-cleared both test adapters. | +| Exact final test/code static gates | `87c8049f5985c1604ee864a78633ddb1e19dfd8e` | Typecheck, repository lint and format check all exit 0, `evidence/u2d/static-87c8049f5.log`. The only test delta after the browser receipt is the independently receipted queue proof. | +| U2a provider rename | `46e14f12226658a669ba878170bd9736c736b8fd` | Accepted 4/4 in `evidence/u2a/final-rename-owner.log`; that receipt also contains the owner/config-store cases. | +| U2a mutable owner/config store | `05e01290fbde13058031d30775096bf950d8e042` | Accepted 4/4 and 40/40, `evidence/u2a/fix-owner.log`, `evidence/u2a/fix-config-store.log`. | + +Reuse is deliberate: since `e63d7fa98`, app production changes are restricted to the three +retained-file rendering/plumbing files, now covered by the new focused cases and affected browser +flow. Protocol/client/server behavior tested above is unchanged; added or strengthened tests are +receipted separately. U2a test blobs are identical to their accepted heads, and beta's +`components/markdown/**` remains byte-identical to the U2c base. No unchanged green suite was rerun. +The earlier server batch `tests-server-e63d7fa98.log` stopped at its session failure; it is not a +green receipt for later files. The first root-config handler invocation at `71dcafa6d` failed before +collection (`__DEV__`); the app-workspace invocation above is the valid 3/3 receipt. + +### Browser evidence and classification + +| Flow | Executed SHA | Result and receipt | +| --- | --- | --- | +| Durable queue, desktop 1280 and compact 390 | `400dae50d694ab78a3571cb846f9cf1364c37a7d` | Both pass, `evidence/u2d/browser-adapters-400dae50d.log`: actual daemon/UI pending state, independent Send now and Delete items, promotion/deletion transitions and outbound capture. | +| Queue flag absent, desktop 1280 | `71dcafa6dc75b0d9735fd7043440049d33ce4f79` | Pass, `evidence/u2d/browser-71dcafa6d.log`: local queue path with no durable queue RPC or daemon item. | +| Queue flag absent, compact 390 | `400dae50d694ab78a3571cb846f9cf1364c37a7d` | Pass, `evidence/u2d/browser-adapters-400dae50d.log`, same local-path and zero-durable-RPC contract. | +| Companion flag absent, desktop 1280 | `33e270f60987a29890039f1d619203e55ca27827` | Pass, `evidence/u2d/artifacts-33e270f60.log`: delivered absent flag and supplied snapshot, upgrade notice, file card and HTML preview, exact draft retained, mutation controls absent and both feature RPC families zero throughout. | +| Supported artifacts, desktop 1280 and compact 390 | `a61591ddb285e8082591f165f66a068fdfcb86e1` | Both pass, `evidence/u2d/artifacts-a61591ddb.log`: populated all-items view, canonical entry (compact menu Find plus explicit dismissal), Chat/draft round trip, filter reselection, same card and real iframe preview, return and zero requests in both feature families. This is all-items coverage, not default file visibility or filter persistence. | +| Companion flag absent, compact 390 | `a61591ddb285e8082591f165f66a068fdfcb86e1` | Pass in the same 3/3 browser receipt: actual delivered absent flag and supplied snapshot, upgrade notice/card, no mutation controls, real preview, canonical file-sheet close and exact draft retained, both feature RPC families zero. | + +Each browser output directory retains traces, screenshots and JSON attachments beside its named +log. `browser-observations-71dcafa6d.json` and `browser-observations-400dae50d.json` summarize actual +app outbound requests; they do not substitute fixture-client requests for browser traffic. +`artifact-observations-33e270f60.json`, `artifact-observations-a61591ddb.json` and +`artifact-snapshots-a61591ddb.json` preserve the retained-file flows' actual requests and snapshots. +The four final artifact gates are the one retained desktop absent-host pass plus three affected +passes; no single run is described as 4/4. Ordinary workspace-file reads/subscriptions occur during +preview and are allowed. Zero feature RPCs does not mean zero network traffic. Desktop/compact +retained-file and both queue pending screenshots were inspected. The supported desktop trace also +records a caught post-test WebSocket send ("Test ended"); the case and runner pass, with all acceptance +assertions complete. The diagnostic remains in the trace summary. + +Superseded failures remain in `browser-71dcafa6d.log`, `browser-compact-9b5a69159.log` and +`browser-compact-5d9d91d43.log`, with their trace directories. They record the unhandled browser +confirm, compact setup expecting a desktop tab, Show All not selected, chooser/menu dismissal +interaction, and the explicitly retracted hidden-entry/no-compact-switcher expectations. The +strict two-backdrop failure is a locator ambiguity; the approved canonical locator selects the +first backdrop and retains its normal actionability and closed-state checks. + +The independent pre-repair file-loss observation is `unsupported-observe-9b5a69159.log` (desktop +observation completed, compact observation blocked in dismissal), with +`unsupported-outbound-9b5a69159.json` and `unsupported-snapshots-9b5a69159.json`. Both widths received +real file snapshots; the completed desktop flow rendered zero cards and emitted zero feature RPCs. +This product defect remains distinct from the superseded layout contract. The old-host voice +third-argument failure remains in `voice-absent-9b5a69159.log`; its corrected receipt is above. + +At `33e270f60`, the other three artifact cases failed in new test assumptions, after reaching real +cards. Both supported cases passed the first Show All/card and Chat/draft checks, then expected the +Stream filter to persist. The panel conditionally mounts `CompanionFeed`, whose local filter starts +pending-only, in both this integration and pinned `139e0c81e`; the owning doc promises Chat/draft +retention, not Stream-filter persistence. Before editing, advisor and coordinator approved checking +Show All on reentry, clicking it, checking Show Open Only and the same card, then preserving preview, +return, draft and full-flow zero-RPC checks. Classification: unsupported test assumption, separate +from the retained-file defect. + +The compact absent-host case passed the actual supplied card and iframe heading, then tried the tab +chooser behind the file sheet's backdrop. Its page snapshot shows the preview dialog and preserved +draft underneath. Beta's `SheetTabs` and existing compact sheet suite own file opening in a sheet. +Before editing, advisor and coordinator approved the existing `closeSheet(page, "u2d-report.html")` +adapter after the unchanged preview assertions, verifying sheet/preview closed and the same +composer/draft/full-flow zero-RPC checks. Classification: harness file-tab assumption against beta +compact sheet ownership. The original 60-second timeout and traces remain in +`evidence/u2d/artifacts-33e270f60/`; no timeout or product change is made, and the green desktop +absent-host case is not rerun. + +## Gaps + +- Native Find is a native surface; the browser proof cannot reach it, so it stays an unverified + device check rather than an implied pass. +- Device audio capture and playback, packaged Electron and nine-locale visual checks remain U7 work. +- Earlier upstream-beta environment failures involving the Claude provider/binary, packaged zsh + prompt and missing `gh` remain open; this layer does not waive them. +- Capability flags (`durableAgentQueueV1`, `companionStreamPortV1`, `durableVoiceInputV1`) are + recorded as source presence only. No activation is claimed, and C1, C2, A3 and the rest of T0-T10 + are out of this layer. + +## Test-only changes, classified before editing + +The replacement writer preserved clean `9ec641052` and its registered-handler 3/3 green receipt +(`evidence/u2d/status-handler.log`). Advisor review accepted the registered-handler architecture and +requested stronger reconnect proof. The coordinator explicitly approved these test-only refinements: +await the real first flush promise before resetting the enqueue spy; retain the exact pending +`item-2` through downgrade, then dispatch it exactly once when capability returns; and check every +incapable-transport subscription for absence of the queue selector. Existing assertions and product +code remain unchanged. Only the changed reconnect files are rerun after this strengthening. + +At `f605c8dd0`, the strengthened handler passes 3/3 and the selector case passes 1/1. Exact-SHA +static checks found the mock's inferred empty argument tuple, an unsafe acknowledgement cast in the +existing queue subscription case, and formatter whitespace in `session.test.ts` and `session.ts`. +Before the carry-test edit, the advisor and coordinator approved: reuse the real enqueue signature; +find the acknowledgement by type and request ID and throw if missing; preserve every assertion; +format through npm with the `session.ts` change confirmed whitespace-only. These are test harness, +test safety and formatting corrections, with no production behavior change. + +At `71dcafa6d`, the desktop durable browser case reached a real pending daemon item and its UI, +then failed because the test expected a DOM confirmation. The browser uses `window.confirm`, +which Playwright dismissed without a listener. Classification: unhandled browser-confirm +interaction. Before editing, the advisor and coordinator approved observing the actual dialog +(waiter before Delete, exact localized type/text, accept), preserving all deletion, independent +promotion, daemon and wire assertions. They also approved cleanup of only this helper's fixture on +setup failure, preserving the original error and handing cleanup to the caller only on success. + +Both compact queue cases stopped in setup because the new helper expected an always-visible +desktop title tab. Both populated artifact cases reached Stream but expected files under its +default pending-only filter. Before editing, the advisor and coordinator approved two harness-only +adaptations: verify compact title/running in beta's canonical chooser, dismiss it, then verify Stop +and the working indicator; select Show All and verify Show Open Only before the same real artifact +card assertion. This proves the all-items view, not default visibility. Unsupported-host exposure +and the compact switcher's presence remain independent failing assertions; no product fix is +authorized by these adaptations. + +At `400dae50d`, both durable queue widths, compact local queue and desktop all-items artifacts +pass. The compact artifact click is intercepted by the canonical chooser's bottom-sheet backdrop +after View artifacts selects the view. Before editing, the advisor and coordinator approved an +explicit chooser dismissal and closed-state assertion before the unchanged filter/card/wire steps. +Classification: access after explicit dismissal, not automatic dismissal. The independent compact +switcher failure remains. An isolated unsupported-destination observation is also authorized; +owning-doc policy tension requires an explicit ruling before any visibility or expectation change. + +The `9b5a69159` focused run exposed a previously unreceipted old-host voice assertion: the real +adapter deliberately receives exactly `(true, "agent-1")`, with no durable options, whereas the new +test expected a third argument containing null. Advisor and coordinator approved the exact single +two-argument assertion with capture, zero receipt reads and cleanup retained. Classification: +absent durable options, not a transmitted null identity. The chooser's coordinate dismissal also +hit the menu overlay; the approved canonical backdrop locator and position replace that click, +preserving the closed-state assertion and every subsequent artifact assertion. + +### Retained-file defect and explicit contract ruling + +The pinned baseline's owning doc requires compact Chat/Stream navigation and an older-host +upgrade notice with existing files retained. The advisor explicitly retracted its earlier hidden +entry/no-compact-switcher requirements; the coordinator approved correcting those browser +contracts as baseline preservation. Original suppression/layout failures remain recorded as +superseded assertions, separately from the retained-file defect below. + +Before repair, `9b5a69159` trace observations prove that actual app-bound agent snapshots at both +widths contain `README.md` and seeded `unsupported-report.html`. The completed desktop observation +collects two files but renders zero cards, with both the Stream upgrade notice ("Your file artifacts +are below") and an artifacts unsupported notice. Actual app outbound artifact and companion RPC +counts are zero. The absent companion flag is passed again as `ArtifactFeed` support, whose early +return suppresses supplied files. This contradiction also exists in the pinned carry; it is not an +integration regression or a waiver. + +Before editing, advisor and coordinator approved removing that sole artifact support prop, +plumbing and early return. The companion gate and upgrade notice, connection/empty states, +supported-host mutations and file-opening behavior stay owned by their existing code. The +unsupported branch receives no mutation callbacks. Focused with-files/without-files cases and +corrected browser gates must prove supplied snapshots, upgrade notice, file card/open, retained +draft, absent companion mutation controls and zero artifact/companion RPCs through the whole flow. +Ordinary workspace-file reads and previews are allowed. No wider product change is authorized. + +### The queue enqueue case: attribution corrected, not a product defect + +The first gate run showed the carry's enqueue case failing, and an early reading called it a +swallowed reply. Observation-only spies on the delivery lanes disproved that: `delivery.reply` +returns true for the enqueue response and `sendOwned` delivers it to the targeted lane with the +requesting socket as its source, and the queue update is not delivered to that socket because it +advertises owned subscriptions, which means the modern lane and a subscription are required. The +case's failure was a lane-model mismatch plus a missing harness stub, not a product defect. + +The instrumentation also proved the harness dependency: without `agentManager.getAgent` the enqueue +path answers `rpc_error: Request failed: createStub: "getAgent" was called but not stubbed`, so every +queue case that enqueues needs that stub. The spies were removed and the case now runs on the modern +model with its payload expectations unchanged, alongside a separate legacy capability case. + +Recorded before any edit, per the sign-off. Every item below is a test or test-fixture change; no +product behavior changes and no expectation is relaxed. If a new case exposes a defect, the cause and +a repair design go to review before any product edit. + +| Change | Kind | Where | +| --- | --- | --- | +| Side-conversation capability case subscribes all three sources, keeps its expectations, adds `allowsOutbound` assertions for update and removal, separates release suppression from capability removal, keeps the legacy capable case | Setup correction to match accepted U1 semantics | `packages/server/src/server/session.test.ts` | +| Queue subscription cases: capable and subscribed receives, capable and unsubscribed does not, release suppresses, mixed sources stay isolated, downgrade restores | New cases | `packages/server/src/server/session.test.ts` | +| Same client through capable, incapable and capable again, asserting the outbound selector list each time | New case | `packages/client/src/daemon-client.test.ts` | +| Registered status handler driven with a pending outbox through absent, capable and downgrade | New case in a new suite, because no existing suite mounts the session provider and a production extraction is not authorized | `packages/app/src/contexts/session-queue-resume.test.tsx` | +| Voice runtime with the durable-voice feature absent mints no transport generation and sends no receipts read | New case | `packages/app/src/voice/voice-runtime.test.ts` | +| Audio cancel-during-preparation, mic loss and stale-callback cases | Existing carry cases, run and cited, not duplicated | `packages/app/src/audio/*` | +| Queue promotion and deletion with daemon and UI assertions; artifacts view and compact entry with outbound capture; corrected old-host retained-file contract under the explicit ruling above | New cases and approved contract correction | `packages/app/e2e/browser/agent-message-submission.spec.ts`, `packages/app/e2e/browser/agent-stream-ui.spec.ts` | diff --git a/fork/handover-beta-upgrade-u2e-2026-10-18.md b/fork/handover-beta-upgrade-u2e-2026-10-18.md new file mode 100644 index 00000000000..5a8c01f1e05 --- /dev/null +++ b/fork/handover-beta-upgrade-u2e-2026-10-18.md @@ -0,0 +1,112 @@ +# Beta upgrade, U2e ACP model-switch handover (2026-10-18) + +Owning branch `fork/acp-model-switch-0.12.0-beta.1`, isolated worktree +`/home/ctaylor/repos/paseo-upgrade-acp-model-switch`. Accepted U2d remains unchanged in +`/home/ctaylor/repos/paseo-upgrade-tmad-baseline`. Neptune's exclusive private candidate runs +the checks; no install, activation, publication, daemon restart or later-layer work is included. + +## Inputs and merge + +| Input | SHA | +| --- | --- | +| Accepted U2d parent | `79422b485d7f68dfa24d36a81caa03ead5807992` | +| Pinned ACP carry parent | `de8ea216a9d4a2a64bb01a593143f02bddcf8d0f` | +| Merge base | `cbc2017186b980e7928bc376cfdeabb90ef56aa2` | +| Source merge, both parents preserved | `7a9072d1ac38562244a394d70833de826d24a703` | +| Read-only preflight merge tree | `a2426d5fbcfe643020b5487ab31b746a5eb04276` | + +The pin contributes exactly two unique commits: `85d391441` rejects requested model-selection +failures; `de8ea216a` supplies configured default thinking to CLI runs. From the merge base, +ours changes 1,144 paths and the carry five. Four paths are shared, one is carry-only. The fresh +merge matches preflight: two conflicted paths with one import hunk each, two automatic shared +merges and one carry-only path. The source merge changes exactly five files, 389 additions and +70 deletions. No old basket is replayed. + +## Conflict and automatic-merge audit + +| Path | Result | +| --- | --- | +| CLI `commands/agent/run.ts` | Keep accepted shared `resolveCallerAgentId`; retire the carry's obsolete inline-caller error import. Use existing `Pick`; no redundant client type. Preserve beta `waitsForFinish`, `--no-wait`, legacy aliases, structured-output restrictions, explicit daemon target and caller/workspace precedence. | +| CLI `commands/agent/run.test.ts` | Union `waitsForFinish` and `resolveRunThinkingOption` imports. Keep accepted caller/wait/transport/validation assertions, six carried default-thinking cases and six approved command-level cases. | +| Server `providers/acp-agent.ts` | Shared automatic merge; blob equals the inspected trial `17e13394032823c39127cc9ee2beac1fec5af00b`. Preserve usage/environment/session identity, history-only runtime release, argument hints, cancellation ledger, staged successors and late-event ownership. | +| Server `providers/acp-agent.test.ts` | Shared automatic merge; blob equals trial `3cef9deb9966173c275f97f4647e6cb3b1bfe93d`. Preserve argument-hint fixture and expectations, cancellation/successor/history/configured-model/mode cases. Model-warning expectations intentionally become rejection expectations. | +| Server `providers/generic-acp-agent.request-errors.test.ts` | Carry-only; blob equals pin `8eb64208f25c6fb7047e9b3524ea487e00f7334a`. Retain existing mode/effort errors and real fake-process JSON-RPC coverage for creation, resume, later rejection and config-only success. | + +The intentional behavior change retires model-specific warning/silent-default handling and +`isModelSelectionUnavailableError`. Invalid requested model choices and failed model RPCs reject. +Only normalized method-not-found `-32601` permits config-option selection. Other RPC errors retain +their details; unsuccessful switches retain the current model. Initialization/resume still close +after failure and preserve the original error. Invalid-mode warnings and unrelated feature +tolerance remain. + +Configured CLI thinking is a separate retained behavior. Omitted effort uses the selected model's +configured default, then its marked-default option; omitted model uses the default catalog model, +then the first. Explicit trimmed effort bypasses lookup. Unknown explicit models and models +without a default leave effort unset; catalog errors reject. Lookup and both creation paths use +the resolved workspace directory and the same explicitly targeted connected client. + +Beta owns argument hints already; no duplicate hint or initial-wait implementation is restored. +The shared caller helper owns absent cross-daemon callers and transport failures. No protocol, +client, session, manager, registry, GJC, Pi, app, manifest or dependency edits are needed. + +## Evidence and review + +Receipts live on Neptune under +`~/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u2e/`; local copies live under +`/home/ctaylor/.jcode/scratch/beta-upgrade-20261017/u2e/`. + +Preflight report `preflight-79422b485-de8ea216a.md`, merge-tree output and +`preflight-inventory.json` were delivered to the existing advisor and coordinator before edits. +Advisor approved the bounded design; coordinator explicitly authorized implementation and the +command-level tests. Advisor source clearance at the exact merge SHA is saved in +`advisor-source-7a9072d1a.txt`: no blocking source or test-validity finding. +Final advisor **ACCEPT** at that source SHA is saved in `advisor-final-7a9072d1a.txt`, SHA256 +`697f917587b0de0a2bc618c5d535aa1206318e2d9b5b63f89cbe614dfc1bceb0`. The coordinator independently +verified both parents, source/build hashes, owning build, 177 passing tests and static checks. + +| Check at source `7a9072d1ac38562244a394d70833de826d24a703` | Receipt | Result | +| --- | --- | --- | +| Owning `npm run build:server`, before focused tests | `build-7a9072d1a.log` | Exit 0 | +| CLI `run.test.ts`, `--bail=1` | `cli-run-7a9072d1a.log` | 25/25 pass | +| Server `acp-agent.test.ts`, `--bail=1` | `acp-agent-7a9072d1a.log` | 141/141 pass | +| Server `generic-acp-agent.request-errors.test.ts`, `--bail=1` | `generic-acp-agent.request-errors-7a9072d1a.log` | 11/11 pass | +| Required typecheck, lint, format | `static-7a9072d1a.log` | All exit 0 | + +Source static SHA256: `eee6ebbb574042d9426668573fbdb373181b67c468aeeaec055d783d245baee9`. +Owning build SHA256: `382e9e21325a9bb7a0206dd6840f595f770af54249b30ea42836db469881cc36`. + +The sealed source inventory `receipts-7a9072d1a.sha256` contains 18 receipts and reproduction +scripts, SHA256 `5ce308fa77a544673f1bc344a633f897f0ff03f006f2c1f2e8254e5a1ed69154`. +All entries were verified locally and on Neptune. Documentation-seal formatting, final-head static +and final handover integrity receipts sit outside this source inventory; they do not replace the +source test receipts. + +The six new command cases execute `runRunCommand` through a test connected-client adapter: +ordinary and structured creation each prove computed and trimmed explicit effort, resolved cwd +distinct from requested cwd, exact target, exactly one create and close, and catalog bypass for +explicit effort. Structured output uses the real response parser. Two catalog-failure cases prove +rejection with no creation or wait and one close. Existing helper assertions remain separate. + +`integration-inventory-7a9072d1a.json` binds both parents, all five changed blobs and 20 unchanged +seams to the source SHA. It proves source preservation, not new runtime coverage. Unchanged +manager/session/client/protocol/target/GJC/Pi and U2d queue/artifact suites are not rerun. Their +older receipts retain their original SHA and scope in the [U2d ledger](handover-beta-upgrade-u2d-2026-10-17.md) +and its preceding layer links; an inspected source path is not promoted into a runtime receipt. + +The first local commit hook attempted format/lint/typecheck in the dependency-free Uranus +worktree and failed on missing tools; app pretypecheck could not start its build because `tsc` +was absent. No suite ran or build completed. `local-hook-incident.txt` records this blocked attempt; +it supplies no verification evidence. The actual local merge used `LEFTHOOK=0` after Neptune's +`npm run format` passed. All owning build/test/static validation runs on Neptune. + +## Acceptance boundary + +Source and receipts are accepted. This handover is the only change after the source merge. +The docs seal requires typecheck, lint and format at the exact final head, recorded externally as +`static-.log`, plus clean matching local and Neptune heads in `handover-.txt`. +No passing focused suite is rerun for this documentation-only delta. + +Coordinator U2e ADVANCE verification remains separate; this ledger does not grant it. U2d's +native/device, packaged Electron, locale and environment limitations remain as recorded in its +ledger. A1 and later layers require their own explicit preflight/design authorization; no wider +fixes or production actions are authorized. diff --git a/fork/handover-beta-upgrade-u2f-2026-10-18.md b/fork/handover-beta-upgrade-u2f-2026-10-18.md new file mode 100644 index 00000000000..b053b745c6e --- /dev/null +++ b/fork/handover-beta-upgrade-u2f-2026-10-18.md @@ -0,0 +1,143 @@ +# Beta upgrade, U2f A1 diagnostics handover (2026-10-18) + +Owning branch `fork/a1-diagnostics-0.12.0-beta.1`, isolated worktree +`/home/ctaylor/repos/paseo-upgrade-a1`. Accepted local U2e and U2d worktrees remain +unchanged. Checks use Neptune's exclusive private candidate. This carry includes +no later layer, installation, publication, activation or daemon restart. + +## Inputs and candidate ownership + +| Input | SHA | +| --- | --- | +| Accepted U2e parent | `216eaa8fad88f4c09cf3479f73822f1d68e406e3` | +| Pinned A1 parent | `831f6a858127a41a6eeeef1dce2e6df0c905e18c` | +| Common merge base | `cbc2017186b980e7928bc376cfdeabb90ef56aa2` | +| Source merge, both parents preserved | `2747fae346da7bb37591cf6e40cd7ae5269c23cc` | +| Source tree | `c7685f8ff3405428ad5b2042e95e9970cc7c0731` | +| Read-only trial tree | `8495a5f8be22cf2c5e3d8b75242930ed52bbe72d` | + +A1 was published in `929d7427163474f5c0cbfc45192436d3de7540c6` but was not an +ancestor of captured `origin/custom` (`7ce6fca987721c33ad2b87fcab8d1cb59f4b0c8b`) +or accepted U2e. Its pin contains exactly two unique commits: `09beed6e2` +preserves structured startup errors; `831f6a858` adds mode-rejection evidence. +The owning plan requires explicit preservation rather than a basket replay. + +The candidate order must include this separate owner immediately after ACP: + +```text +fork/acp-model-switch-0.12.0-beta.1 +fork/a1-diagnostics-0.12.0-beta.1 +``` + +The coordinator will commit that order in the control fork's separate +`fork/campaign/upgrade-0.12.0-beta.1.manifest.txt` before baseline assembly, +with all accepted heads pinned in comments. Candidate ownership remains open +until that file is committed; the owning branch alone does not close the +manifest omission. No live manifest was edited. Its read-only captured SHA256 remains +`95b83dd57269bd0b754de4adbaeed4ce4ffef5e1d94eb4382fbe17e43d289bf6`. + +## Resolution and preservation + +The fresh merge reproduced preflight: four shared paths, one test conflict hunk +and three automatic shared merges. There were no carry-only paths. The pin's +48 additions / 3 deletions become 122 additions / 3 deletions after the two +approved additive tests. No pre-existing test line or assertion is removed. + +| Server path | Final treatment | +| --- | --- | +| `agent/providers/acp-agent.test.ts` | Union the carried mode-rejection test with the accepted stored-values test title and body. Retain U2e model rejection assertions and add the nonstandard-object summary and real-wrapper cases. | +| `agent/providers/acp-agent.ts` | Automatic shared merge equals the reviewed trial. Replace only the non-ACP/non-Error summary coercion and non-ACP object Error construction with the existing formatter. | +| `creation/index.ts` | Automatic shared merge equals the reviewed trial. Import the existing formatter and replace the failed-snapshot error expression; keep admission, receipt, stage, resource, retry and observer ownership. | +| `creation/index.test.ts` | Preserve the automatic carried structured-object test and add returned/observed/persisted real-Error coverage. | + +Mode request wrapping already exists upstream and in accepted beta. Its carried +test is inherited equivalence coverage. The three formatter substitutions are +the missing production delta. The original A1 review and release evidence are +recorded in the preflight; historical receipts retain their original SHAs. + +U2e still owns rejected model switches, numeric method-not-found `-32601` +config fallback, failure retaining the current model, initialization cleanup +and original errors. ACP cancellation, staged successor/history, argument hints, +configured models and modes remain covered by their retained assertions. CLI +caller identity, waitsForFinish, daemon targeting and computed thinking are +unchanged. The unrelated spawn-error and worktree-wrapper paths are untouched. + +## Diagnostic exposure and authority + +The carry reuses `agent/providers/diagnostic-utils.ts`; no second formatter is +introduced. Creation failures from real Errors now include code, signal, +stderr, stdout and cause, in addition to message. Nonstandard objects serialize +as JSON. ACP Error identity and numeric code handling remain unchanged. + +The advisor and coordinator explicitly accepted this published diagnostic +expansion within existing operator-facing receipt/subscription authority. +These strings are unredacted and have no global size cap. The existing helper +caps individual Error stderr/stdout fields at 4,096 characters; that does not +cap arbitrary object JSON, messages, causes or aggregate output. Diagnostics +can persist in creation receipts and reach authorized clients and turn errors. + +Pino's structured header redaction and the daemon diagnostic-export scrubber +are separate owners; neither protects these creation/turn strings. No new +export, upload, logging expansion, sanitizer, schema, authentication or +authorization change is included. Existing creation and subscription permission +mapping and delivery lifetime remain unchanged. The preflight traces the +current agent-only worktree wrapper's independent coercion boundary; this carry +does not claim all provider objects survive every UI path. + +## Verification and review + +Receipts live on Neptune under +`~/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u2f/`; local copies live +under `/home/ctaylor/.jcode/scratch/beta-upgrade-20261017/u2f/`. + +The persistent advisor approved the bounded design before edits. Coordinator +implementation sign-off explicitly accepted the diagnostic expansion, conflict +union, two additive tests, failing-first checks and unchanged authority. +Exact source was sent for advisor review while Neptune's checks ran. + +Four bounded new cases each failed against accepted U2e production before the +substitutions: wrapper object details, summary object details, creation object +coercion and creation real-Error extras/cause. Each run selected only that case; +the inherited mode test was excluded. `failing-first-source.txt` binds accepted +production blobs and formatted test hashes. The failures are assertion failures +for missing diagnostic content, not harness or compilation failures. + +The real-wrapper test calls `applyConfiguredOverrides` and the existing +`setSessionMode` seam, verifies an Error with exact serialized rejection detail, +one dispatch, no config fallback and unchanged mode. The creation test uses real +temporary receipt files, verifies exact formatted Error content in returned and +observed snapshots, then reads it through a fresh CreationService subscription. +It preserves failedStage, errorCode, outcomeUnknown and workspace assertions. +All added diagnostic strings are synthetic and non-secret. + +| Check at source `2747fae346da7bb37591cf6e40cd7ae5269c23cc` | Receipt | Result | +| --- | --- | --- | +| Owning `npm run build:server`, before complete suites | `build-2747fae34.log` | Exit 0 | +| ACP `acp-agent.test.ts`, `--bail=1` | `acp-agent-2747fae34.log` | 144/144 pass | +| Creation `creation/index.test.ts`, `--bail=1` | `creation-2747fae34.log` | 13/13 pass | +| Required typecheck, lint and format | `static-2747fae34.log` | All exit 0 | + +Build SHA256: `c0e44672f909c42c434b79d25999365eb69a5e509ae766444c39376020909630`. +Source static SHA256: `44e62642138e6cf0eb09a40a2efc14a739b6884f1fd3b93a657334328d89ef91`. +The two changed suites ran once in full after the owning build: 157 passing +tests. No source edit followed those checks. No build or test ran on Uranus. + +Advisor source clearance is saved in `advisor-source-2747fae34.txt`. Final +**ACCEPT** at the same source SHA is saved in `advisor-final-2747fae34.txt`, +SHA256 `07870802cda1d17c69bae6619b85881f83104a114fbfdccd05cbfa2a55f3a3cf`. +The advisor checked the exact receipts and required this completed verification +record before sealing. Prior platform/environment gaps remain open; acceptance +does not grant ADVANCE, activation or a later layer. + +`receipts-2747fae34.sha256` seals 31 source receipts and reproduction files, +SHA256 `528de2e01d5c0c6036488a81b554ddb424f478cd6fc782d78f0912a16264d7cb`. +Later docs-only formatting, final-head static and handover integrity receipts +sit outside that source inventory and do not replace its runtime evidence. + +`source-inventory-2747fae34.json` binds both parents, four changed paths and 20 +unchanged seams. Its SHA256 is +`6cf8a8d24884731df0ee9dcc3847444d5ab2051eef774f235642fd091b3410b6`. +It proves source preservation, not runtime coverage. Unchanged CLI and real ACP +request-error suites retain their U2e 25/11 passing receipts at the original SHA; +unchanged formatter, permission, app and browser suites are not rerun. See the +[U2e ledger](handover-beta-upgrade-u2e-2026-10-18.md) for preceding evidence. diff --git a/fork/handover-beta-upgrade-u3-6762-2026-10-18.md b/fork/handover-beta-upgrade-u3-6762-2026-10-18.md new file mode 100644 index 00000000000..39ea14a7e3c --- /dev/null +++ b/fork/handover-beta-upgrade-u3-6762-2026-10-18.md @@ -0,0 +1,127 @@ +# Beta upgrade, U3 #6762 handover (2026-10-18) + +Owning branch `fork/snapshot-trimming-0.12.0-beta.1`, isolated worktree +`/home/ctaylor/repos/paseo-upgrade-snapshot-trimming`, starts directly from accepted +#7169 `78209041d`. The disposable basket remains at that accepted head. All nine +earlier owners and the original custom checkout remain unchanged. Checks ran +on Neptune's exclusive private candidate; no build or test ran on Uranus. + +## Fixed input and integration + +| Identity | SHA | +| --- | --- | +| Accepted parent | `78209041d21f7a308393f5ed7208d7bf49a46960` | +| Frozen #6762 base | `cd77ecd837df40d042599d8847403eb416b35b04` | +| Frozen #6762 head | `6c71d34ef9225ac7dad7f84ef8993d8ceebf9a32` | +| Frozen test-merge | `52daa97fd4ac12ad7a899e2490add2c520339eba` | +| Single original subject | `74fe3ee8d81d54ca53f9be1c91f2bab0b25fed24` | +| Attributed carry | `40252cc7fddceb7c77c1c7810f7eeab6ac8fd839` | +| Final source and approved preservation tests | `82b8722519d4b8228345e1bbe7d0c434b8448727` | +| Final source tree | `5a785da3e0d39a504fa083a14f6a764d95f56052` | + +Frozen `upstream-pins.json` SHA256 remains +`d26697e552936677125975c675f94e85b7de4f24e7294a4ef041ee75ca104833`. +The original single subject, frozen base-to-head net and frozen test-merge +first-parent diff are byte-equal: two files, 59 additions, zero deletions, +SHA256 `b7da49f9ef94a9df682a831f7ae7f7b432a3a87f28e6ab3056b8c8cbebcbdb5d`. +Only the original subject was cherry-picked with its author and exact `-x` +attribution; three main-sync commits and unrelated upstream ancestry are excluded. + +Fresh preflight and actual integration had zero conflicts. The sole automatic +content merge in `agent-projections.ts` preserves the accepted artifact and +companion-entry additions. The carry tree exactly matches the preflight trial +`0c4abe6b1fcb5694bce3a2445efaf9286d8f3ac1`. No shared hunk required resolution. + +The only production addition omits `metadata.asyncQuestions` from the existing +wire projection's sanitized clone. Private stored records retain the full resume +log. Existing MCP omission, empty-metadata handling, native handles, unrelated +metadata, live pending permissions and retained stream facts remain. Stored +snapshots keep their existing empty pending-permissions policy until restoration. +This is neither a general sanitizer nor a total snapshot-size bound. + +`source-inventory-82b872251.json`, SHA256 +`fe4663425c9ea79e1cfc91c015f74a695c25e85de9569ccaa9b133be92ece4e2`, +proves the production delta is exactly the approved three lines, both upstream +test bodies are unchanged, and all 5,944 accepted paths outside the four changed +paths are identical. Earlier side-conversation, queue, receipt/subscription, +ACP model/cancellation and #7179/#7169 ownership is preserved without rerunning +unchanged suites. No protocol, dependency, authorization or provider change occurs. + +## Behavioral proof and receipts + +Local receipts: +`/home/ctaylor/.jcode/scratch/beta-upgrade-20261017/u3-6762-implementation/`. +Neptune receipts: +`~/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u3-6762-implementation/`. +The separate 20-entry preflight seal remains unchanged at SHA256 +`e26e7e107ded248031a0f7a2cc4825b4ee47c1e6c2ac7177dd40e60f44603cd5`. + +Five selected cases failed first against accepted production on Neptune. Both +upstream omission cases, the mixed-metadata case, actual disk-reload case and +strengthened Codex wrapper case each failed at the intended wire omission +assertion because `asyncQuestions` remained present. These were behavioral +failures after setup, not import, bootstrap or provider-availability failures. +Their five `red-*.log` files and the unchanged production blob identity remain. + +The mixed case checks unrelated metadata/native handle, exact sanitized pending +permission, artifact/companion facts, source/record nonmutation and a detached +wire mutation. The storage case uses `applySnapshot`, actual JSON, an independent +store reload, wire projection and a second independent reload; disk bytes remain +unchanged. The Codex case uses the real session wrapper and AgentManager with +the existing fake app-server adapter: the actual pending request remains +actionable, answering removes it, and the full answered private log remains +while wire snapshots omit it. Existing answer, rewind, Stop, late-follow-up, +retry and resume cases remain in the full changed suite. + +| Check at exact source `82b872251` | Receipt | Result | +| --- | --- | --- | +| Owning `npm run build:server`, before suites | `build-82b872251.log` | Exit 0 | +| Complete `agent-projections.test.ts` | `projections-82b872251.log` | 23 pass | +| Complete `agent-storage.test.ts` | `storage-82b872251.log` | 21 pass | +| Complete `codex-async-questions.test.ts` | `codex-questions-82b872251.log` | 11 pass | +| Required typecheck / lint / format | `static-82b872251.log` | 0 / 0 / 0 | + +All three changed full files ran once after the owning build: 55 passing unit +cases. No product or assertion repair was needed. Build SHA256 is +`5182dcbb7f7d644bf140362af94f93a393bb424a5dc83da8a8e4fac01c047a94`; +source static SHA256 is +`33e25a474d17474f6ca5d49ed9cce08c33eabe2e5f7c00985f2845b66d44e0cc`. +The local edit-only formatter attempt lacked `oxfmt` (exit 127). Existing Neptune +dependencies completed the same npm formatting operation; no installation or +environment repair occurred. This is separate from required static evidence. + +## Review, seal and remaining gaps + +Advisor **ACCEPT** at exact source `82b872251`: matching log hashes, owning +build, 55 passing tests, exact-source static and preservation inventory were +reviewed directly. No further source correction is required. The saved verdict +`advisor-final-82b872251.txt` has SHA256 +`47cf56e4c92e1f222ac8110e129b541789f0f4e58c7b303888714f01060f6007`. + +The 31-entry source seal `receipts-82b872251.sha256` has SHA256 +`cae07b3c4badb0b92bfbe52237f595efd2b85e03f3d45e21ce0196df6322828f`. +Both hosts verify every entry. It retains all five intended failing-first +receipts, the failed local formatter attempt and the successful Neptune checks. +Final docs-head static and clean-host receipts remain outside that source seal +in `final-static.log`, `final-static.summary` and `receipts-final.sha256`. +The docs-only seal does not change the checked source tree. No green suite or +build is rerun for that seal. + +The targeted docs-format command encountered the explicit `fork/**/*.md` +formatter exclusion. The full `npm run format` script succeeded; both command +receipts are retained separately. No formatter configuration changed. + +Both inherited real-provider gaps remain explicit and unclosed through U7: + +- **#7179 REAL Claude turn survival UNVERIFIED:** both real runs failed at + createAgent availability admission before dispatch/sentinel/controls; + underlying cause unknown. +- **#7169 REAL OMP UNVERIFIED:** `beforeAll` `omp --version` exited 127 with + `env: bun: No such file or directory`; all 14 skipped before resources, body, + turn or sentinel. No runtime cleanup path was exercised. + +Projection unit results do not close either gap or the earlier physical/native, +packaged Electron and locale obligations. No runtime-green claim, provider/auth +probe, environment repair, basket/manifest write, later subject, publication, +live configuration change, restart, installation or activation is included. +Coordinator ADVANCE remains a separate gate. diff --git a/fork/handover-beta-upgrade-u3-7057-2026-10-18.md b/fork/handover-beta-upgrade-u3-7057-2026-10-18.md new file mode 100644 index 00000000000..dcfd2db2c64 --- /dev/null +++ b/fork/handover-beta-upgrade-u3-7057-2026-10-18.md @@ -0,0 +1,116 @@ +# Beta upgrade, U3 #7057 handover (2026-10-18) + +Owner `fork/notification-rearming-0.12.0-beta.1` in isolated worktree +`/home/ctaylor/repos/paseo-upgrade-notification-rearming` starts directly from +accepted #6762. All ten earlier owners and original custom remain unchanged. +The disposable basket remains at accepted `df8df0bbe`. All checks ran on the +exclusive Neptune candidate; no build or suite ran on Uranus. + +## Fixed input and integration + +| Identity | SHA | +| --- | --- | +| Accepted parent | `df8df0bbef3969e87bdaa2d15bac2ca47447ad39` | +| Frozen base, original subject parent | `208e323035ab40bbf3b3476fb6175330bc79821c` | +| Frozen head, single original subject | `d2174afaa8ab5260fc87b4e93f99459151c53384` | +| Frozen test-merge | `86b409d05fbfae3b650cafa54f2c4f1bf85be657` | +| Attributed carry | `09bf154e6989d52c44e538e739de358f8834355a` | +| Initial strengthened source | `78af0c59f8a28c8daeb83e0c307228d19d9cb768` | +| Final source | `19adfb230998f215fa28887d763e9824bd32b276` | +| Final source tree | `1a1f39e93c17b13858b468725d83e60fa0ffbaf2` | + +Frozen pins SHA256 remains +`d26697e552936677125975c675f94e85b7de4f24e7294a4ef041ee75ca104833`. +The frozen head is the original single subject: three files, 140 additions and +one deletion. Only that commit was cherry-picked with its author and `-x` +attribution. No unrelated upstream ancestry or synthetic merge was integrated. + +Fresh preflight and actual carry have zero conflicts and three automatic content +merges. Carry tree `943dfd9130e9c8984f5768dec35a7894fa1e68d7` exactly equals +the approved trial. Production hunks equal the original subject; all four +upstream test bodies remain byte-equal. All 5,946 paths outside the three changed +source/test paths remain identical to accepted parent. `source-inventory.json`, +SHA256 `114c324d3694a9014603bcc51c199c223d2e1f6548bc9659c54c5d3dc438a649`, +records those identities and the preserved ten owner refs and clean worktrees. + +The carry keeps finish notification watching armed across a child's error and +later autonomous recovery. Accepted #6008 early completion, terminal/cancel/close, +permission, replaced-arm, sourced caller/dispatch, run-start and #7169 semantics +remain. No provider, protocol, queue, subscription or authorization code changes. + +## Behavioral evidence and classifications + +Receipts are under local scratch +`/home/ctaylor/.jcode/scratch/beta-upgrade-20261017/u3-7057-implementation/` +and Neptune +`~/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u3-7057-implementation/`. +The separate 20-entry preflight seal remains unchanged at SHA256 +`1c82bf4616f9d2887629cd948d8f03698f002a208c05b3bd59942d4d7b364d4a`. + +Four compatible recovery cases fail first against accepted production on Neptune: +upstream low-level/MCP recovery and the two additive repeated-error cases each +reach the missing second parent notification, expected two messages, received +one. Production blob identities match accepted HEAD. The corrected additive MCP +red is `red-repeated-mcp-corrected.log`; its earlier harness failure is separate. + +Two superseded body assumptions remain explicit. `red-repeated-mcp.log` omitted +the existing system-error assistant response from its expected body. +`mcp-server-78af0c59f-failed.log` then expected only the second error, while the +existing manager joins contiguous assistant chunks without a separator. The +autonomous-turn adapter introduces no user-message boundary. Both corrections +received advisor design rulings and coordinator approval before edits. They +change literal test expectations only; no product, event, timing, timeout or +upstream assertion changed. The corrected final cumulative response was initially +source-derived, then actually asserted by the passing full MCP execution. + +The additive cases verify exact ordered `errored, errored, finished` parsed child +identities, counts and full bodies. Duplicate error observations produce one +notice per cycle. The real manager/storage case observes lifecycle and parent-idle +boundaries and verifies the child's sole original sourced prompt. No second tool +call or watcher rearm manufactures recovery. + +| Check | Exact source | Receipt | Result | +| --- | --- | --- | --- | +| Owning `npm run build:server`, before suites | `78af0c59f` | `build-source.log` | Exit 0 | +| Complete `agent-prompt.test.ts` | `78af0c59f` | `agent-prompt-source.log` | 24 pass | +| Complete corrected `mcp-server.test.ts` | `19adfb230` | `mcp-server-revised.log` | 148 pass | +| Required typecheck / lint / format | `19adfb230` | `static-revised.log` | 0 / 0 / 0 | + +The final test-only child changes three expectation lines in the MCP file. +Production and the low-level suite blobs are unchanged, so the owning build and +24 passing cases are reused. No unchanged green rerun occurred. Exact initial +source static also passed and remains separate. Final source static SHA256 is +`30671909975fb254bffdb7ea6ad6f50ee86423f057ea243d43bbccb189efd22e`. + +## Review, seal and remaining gaps + +Advisor **ACCEPT** at exact source `19adfb230` follows direct source inspection, +actual log hashes and reconciliation of the 172 affected unit passes, owning +build and required static. Saved verdict `advisor-final-source.txt` SHA256 is +`02be8f9fa6a055d9f332088cc7a19f06adda9e650a828b3f4721fc21522fed14`. +No further source correction is required. + +The 58-entry source inventory `receipts-source.sha256` has SHA256 +`d1a19fa097425343033c9902357b4f11db955d4db48b254a02a0246602896482`. +It retains all four intended reds, both superseded failures, attributed history, +source inventories, actual checks and advisor verdicts. Both hosts verify every +entry. Final docs-head static and clean-host receipts are recorded separately in +`final-static.log`, `final-static.summary`, `final-completion.json` and +`receipts-final.sha256`. The docs-only seal changes no checked package source; +no build or unit suite reruns for it. The full npm formatter respects the existing +`fork/**/*.md` exclusion; no formatter policy changes. + +Both inherited real-provider gaps remain separate and unclosed through U7: + +- **#7179 REAL Claude turn survival UNVERIFIED:** both real runs failed at + createAgent availability admission before dispatch/sentinel/controls; + underlying cause unknown. +- **#7169 REAL OMP UNVERIFIED:** `beforeAll` `omp --version` exited 127 with + `env: bun: No such file or directory`; all 14 skipped before resources, body, + turn or sentinel. Runtime cleanup was not exercised. + +HeldTurn adapter proof does not close either runtime gap or earlier native, +packaged Electron and locale obligations. No provider/auth probe, environment +repair, basket/manifest edit, later subject, live configuration write, publication, +installation, daemon restart or activation occurs. Coordinator ADVANCE is a +separate gate. diff --git a/fork/handover-beta-upgrade-u3-7062-2026-10-18.md b/fork/handover-beta-upgrade-u3-7062-2026-10-18.md new file mode 100644 index 00000000000..7ad1e01a367 --- /dev/null +++ b/fork/handover-beta-upgrade-u3-7062-2026-10-18.md @@ -0,0 +1,134 @@ +# Beta upgrade, U3 #7062 handover (2026-10-18) + +Owner `fork/attention-edges-0.12.0-beta.1` in isolated worktree +`/home/ctaylor/repos/paseo-upgrade-attention-edges` starts directly from accepted +#7057. All eleven earlier owners and original custom remain clean and unchanged. +The disposable basket remains at accepted `e96eb390f`. Checks ran only on the +exclusive Neptune candidate; no build or suite ran on Uranus. + +## Fixed input and preservation + +| Identity | SHA | +| --- | --- | +| Accepted parent | `e96eb390f5419bf51c357988b65fd86b82ea6ad9` | +| Frozen base, original subject parent | `208e323035ab40bbf3b3476fb6175330bc79821c` | +| Frozen head, single original subject | `a48bb2208688a4c71a5f91c7dce8ceac3b2b444b` | +| Frozen test-merge | `36b00f1afb9748b34e1c39d76ddf0c2eefe7fad8` | +| Attributed carry | `e8a37bd418b63f724a6909b2421fb5711dcb169b` | +| Initial additive source | `32a4b3233eab1baf6bf99b27f08f705cd9ecbd5e` | +| Final strengthened source | `05e0ccfdf3725d82acc5855ce091d76e82fe2659` | +| Final source tree | `5469fb36e99dac71910561b014c02e439cca56d2` | + +Frozen pins SHA256 remains +`d26697e552936677125975c675f94e85b7de4f24e7294a4ef041ee75ca104833`. +Only the original subject was cherry-picked with its author and `-x` attribution; +no unrelated upstream ancestry or synthetic merge was integrated. Fresh trials +have zero conflicts and two automatic content merges, in manager source and its +test. Carry tree `d295d9390b24193033ca06e8f2e87d9edccb2bb6` exactly equals the +approved trial. Production hunks equal the original subject; the upstream test +body remains byte-equal, SHA256 +`8642593cbe48e4d5ad3b26906bd42567e093e85949b8ff06dea281ff118a3ad1`. + +`source-inventory.json`, SHA256 +`625e9d949cfa14bc4e29e45563ff1684467a0fb82037097c854f85d615cc7f23`, +verifies all 5,947 outside paths unchanged and all accepted test bodies intact. +Only manager source and the two affected test files differ from accepted parent. +The final test-only child changes only flushes and storage readers in the two +additive cases, plus formatter whitespace; every payload assertion is preserved. + +Each new finish/error edge refreshes unread finish/error attention. Duplicate +observations do not refresh it; clearing during the same error remains read. +Permission priority, internal-agent exclusion, delegated callback suppression +and status tracking before guards remain. Accepted #7057 rearming and #6008 early +completion survive unchanged, as do terminal/cancel/close, permissions, replaced +arms, sourced caller/dispatch, run-start, #7169 and earlier fork owners. No +provider, protocol, dependency, authorization or subscription code changes. + +## Behavioral evidence and classifications + +Receipts are under local scratch +`/home/ctaylor/.jcode/scratch/beta-upgrade-20261017/u3-7062-implementation/` +and Neptune +`~/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u3-7062-implementation/`. +The separate 20-entry preflight seal remains unchanged at SHA256 +`bf1e9cd843e6416552bd38c262c30c17c720d67132439928b6f28ce538471105`. + +Three compatible selected cases failed first against accepted production on +Neptune. `red-upstream.log` reaches the second edge with expected error attention +but observes stale finished attention. `red-same-reason.log` reaches a second +actual error edge and finds its timestamp unchanged. `red-coexistence.log` finds +the same stale timestamp after the second sourced parent notification and parent +idle have already been observed. Notification progress alone does not count as +#7062 proof. Exact production blob identities, commands, exit codes and clean +restoration are retained. All three failures are intended behavioral reds. + +Initial source `32a4b3233` passed the owning build, 228 manager cases, 149 MCP +cases and all required static checks. Its same-instance `AgentStorage.get` +observations are **cache-backed snapshot assertions**, not independent disk +proof. The unchanged upstream test also retains its original same-instance read. +Source inspection identified this distinction before acceptance; advisor and +coordinator approved the bounded strengthening before edits. Initial receipts +remain separate and retain their actual successful outcomes. + +At `05e0ccfdf`, every existing additive snapshot assertion follows actual manager +and storage flushes and reads through a new independent `AgentStorage` instance +at the same path/logger. Four manager observations and two observations in each +of three MCP cycles now reload actual disk. Readers are read-only and have fresh +caches. Payload assertions are unchanged: exact status, unread flag, reason, +timestamp, callback sequence, duplicate silence and clear-then-observe behavior. + +The MCP case independently verifies attention and the exact ordered parsed +`errored, errored, finished` source identities, message counts and literal +cumulative response bodies. The child receives only the original sourced prompt; +there is no second tool call or explicit rearm. Date-only control retains real +lifecycle timers and observed running/parent-idle boundaries. Cleanup attempts +every acquired resource, restores the clock on every exit, retains/rethrows a +primary error and reports cleanup failures; cleanup-only aggregate throws after +finally. All earlier #7057 assertions remain unchanged. + +| Check | Exact source | Receipt | Result | +| --- | --- | --- | --- | +| Owning `npm run build:server`, before suites | `32a4b3233` | `build-source.log` | Exit 0 | +| Initial complete manager / MCP files | `32a4b3233` | `agent-manager-source.log`, `mcp-server-source.log` | 228 / 149 pass; cache-backed snapshot reads | +| Initial typecheck / lint / format | `32a4b3233` | `static-source.log` | 0 / 0 / 0 | +| Strengthened complete manager file | `05e0ccfdf` | `agent-manager-revised.log` | 228 pass | +| Strengthened complete MCP file | `05e0ccfdf` | `mcp-server-revised.log` | 149 pass | +| Exact strengthened source static | `05e0ccfdf` | `static-revised.log` | 0 / 0 / 0 | + +The build is reused because the strengthened child changes tests only. Both +changed full files were rerun specifically; unchanged agent-prompt greens were +reused. No unchanged green suite or build was rerun. +Exact strengthened source static SHA256 is +`8de2970e7aa2c5eae756b1e3f8c4c60ab3aec26df48bb1cafe46e40a5255cea6`. + +## Review, seal and remaining gaps + +Advisor **ACCEPT** at exact source `05e0ccfdf` follows direct source inspection and +verification of actual log hashes, all 377 affected passes and required static. +No bounded findings remain. Saved verdict `advisor-final-source.txt` SHA256 is +`fbbbf3172d674ebd83dc247e88eb026d1982a6843e55eb33faaad48fc6851e48`. + +The 47-entry source inventory `receipts-source.sha256` has SHA256 +`e225a5747f06224b69c41ee76060c79f3afbaff4ccc2ef34a84291a03698085e`. +It retains all three intended reds, both source revisions and their actual +outcomes, the cache classification, attributed history and advisor verdicts. +Both hosts verify every entry. Final docs-head static and clean-host receipts +are recorded separately in `final-static.log`, +`final-static.summary`, `final-completion.json` and `receipts-final.sha256`. +The docs-only seal changes no checked package source and requires no build or +unit rerun. The npm formatter retains the existing `fork/**/*.md` exclusion. + +Both inherited real-provider gaps remain separate and unclosed through U7: + +- **#7179 REAL Claude turn survival UNVERIFIED:** both real runs failed at + createAgent availability admission before dispatch/sentinel/controls; + underlying cause unknown. +- **#7169 REAL OMP UNVERIFIED:** `beforeAll` `omp --version` exited 127 with + `env: bun: No such file or directory`; all 14 skipped before resources, body, + turn or sentinel. Runtime cleanup was not exercised. + +Manager/MCP adapter evidence does not close either runtime gap or earlier native, +packaged Electron and locale obligations. No provider/auth probe, environment +repair, basket/manifest edit, later subject, live configuration write, +publication, installation, daemon restart or activation occurs. Coordinator +ADVANCE remains a separate gate. diff --git a/fork/handover-beta-upgrade-u3-7106-2026-10-18.md b/fork/handover-beta-upgrade-u3-7106-2026-10-18.md new file mode 100644 index 00000000000..6b263f5cf92 --- /dev/null +++ b/fork/handover-beta-upgrade-u3-7106-2026-10-18.md @@ -0,0 +1,125 @@ +# Beta upgrade, U3 #7106 handover (2026-10-18) + +Owner `fork/heartbeat-listing-0.12.0-beta.1` in isolated worktree +`/home/ctaylor/repos/paseo-upgrade-heartbeat-listing` starts directly from +accepted #7146. All thirteen earlier owners and original custom remain clean +and unchanged. Checks run on the task-authorized exclusive Neptune candidate; +no build, installation or suite runs on Uranus. + +## Fixed input and preservation + +| Identity | SHA | +| --- | --- | +| Accepted parent | `67531e3301901041ded5d159a5df5f7cc32ff5cf` | +| Accepted parent tree | `41fe84256a5ea15af10e91aaccf66ca03da6b768` | +| Frozen base, actual subject parent | `8388f161865134f53d55b8e4c4c3cf5296d515de` | +| Frozen head, single original subject | `4922bedf72804b0867abf17147e7c2fb2eb14279` | +| Excluded synthetic test merge | `34f97b3a9a772ec0b2755364360db281eece55be` | +| Attributed carry | `41403446173bab2305ac2c665d2ab036d6279ca8` | +| Final source | `817b48ab183a649e5a03f999087fa7e5224b5955` | +| Final source tree | `6aa47fbed3f628334bed93ff12ac8766c49f9d57` | + +Control `97e954c716fa4876ee7b0609ef71a2aba2710288` supplies thirteen exact comment +pins. Every ref, clean owning worktree and serial ancestry was verified before +the disposable basket advanced ff-only from accepted #7062 to accepted #7146. +Its HEAD/tree equal the accepted parent above. No assembly commit, build or +green rerun was needed: exact SHA/tree identity permits evidence reuse. The +three-entry assembly seal verifies on both hosts, SHA256 +`5fcff402cf64eeae94d6dcefab1f40949fe0bcbd8ce214dd914f172ca2c3dd5c`. +The basket stays at accepted #7146 throughout this owning carry. + +Frozen pins SHA256 remains +`d26697e552936677125975c675f94e85b7de4f24e7294a4ef041ee75ca104833`. +Actual subject parent equals frozen base; one unique subject has the same +byte-for-byte net, two files with 64 additions and four deletions. Its original +author and `-x` are preserved. Synthetic test-merge ancestry and unrelated main +are excluded. The historical published-fork MCP applicability conflict is +distinct from the current adaptation. + +Fresh explicit-parent trial found one EOF conflict in `mcp-server.test.ts` and +one automatic production merge in `tools/paseo-tools.ts`. The complete accepted +protocol-negotiation regression and complete upstream listing describe are +unioned. The needed ScheduleService value import is retained. Production changes +only the upstream listing-filter removal. `source-inventory.json` verifies every +accepted test byte and upstream fixture, with only the additive scoped-caller +case on top. Every other package path is unchanged. + +The advisor explicitly approved all-daemon enumeration: the existing listing +description already specifies that scope. Heartbeat summaries now appear for +top-level and scoped callers. Enumeration grants no new mutation authority. +Exact caller-agent ownership for heartbeat deletion and new-agent target checks +for the other schedule tools remain unchanged. No #6982 helper, tool, policy or +target-error contract is adopted. Existing summary projection still omits run +history. Schedule execution, queue/receipt/subscription/readiness, permissions, +side conversations, #7057 rearming and #7062 attention owners remain unchanged. +There are no protocol, dependency, provider or live configuration changes. + +## Behavioral evidence and classifications + +Receipts are under local scratch +`/home/ctaylor/.jcode/scratch/beta-upgrade-20261017/u3-7106-implementation/` +and Neptune +`~/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u3-7106-implementation/`. +The separate seventeen-entry preflight seal verifies on both hosts, SHA256 +`0e162258e350455a503cdcc29ab0bd30e62a54e4c5ec55b2b69df633788448a3`. +Persistent advisor approved the exact carry and one additive scoped-caller case +before implementation, within the user's existing authorization. + +Two selected failing-first cases run against accepted #7146 with identical +production blob hashes. The unchanged upstream fixture fails at expected two +summaries versus actual one; 149 other cases skip. The additive scoped case +fails at expected two heartbeats versus actual zero; 150 others skip. These +are intended missing-listing failures, not cleanup, timing or environment +failures. Both reverse-patch clean receipts are retained. No assertion or +semantic repair was needed after those runs. + +Both cases use real temporary storage, ScheduleService and registered tools. +Neither starts the service tick loop or executes a provider. The unchanged +upstream case covers active new-agent and paused heartbeat summaries, absent +`runs`, deletion and an empty list. The additive case covers own and foreign +heartbeat identities, absent `runs`, exact rejection of foreign deletion with +the full record intact, successful own deletion and retained foreign listing. +The existing flush/remove helper cleans each fixture's temporary state. + +| Check at exact source `817b48ab1` | Receipt | Result | +| --- | --- | --- | +| Owning `npm run build:server`, before suite | `build-source.log` | Exit 0 | +| Complete changed MCP test file, once | `mcp-source.log` | 151 pass | +| `npm run typecheck` / `lint` / `format:check` | `static-source.log` | 0 / 0 / 0 | + +Exact source static SHA256 is +`b791b485b95c0d1d31c9cefc295cf028eeb9b82dda4905fb29ac4c2a0a84a604`. +No unchanged green suite or build is rerun. The docs-only child requires exact +final-head static checks; package sources and tested behavior remain identical. + +## Review, seal and remaining gaps + +Advisor **ACCEPT** at exact source `817b48ab1` follows direct source inspection +and verification of actual receipt hashes, all 151 MCP passes and required +static checks. No bounded findings remain. + +The 33-entry source inventory `receipts-source.sha256` has SHA256 +`ca22e34adc6f4d9cba0ca7ba3d4e99d9ba9f19a8c72e6dd1f111040978c6505d`. +It retains both intended red runs, attributed source, preservation inventory +and advisor verdict. Both hosts verify every entry. + +Final docs-head static and clean-host receipts are recorded separately in +`final-static.log`, `final-static.summary`, `final-completion.json` and +`receipts-final.sha256`. The docs-only seal changes no checked package source +and requires no build or unit rerun. The npm formatter retains the existing +`fork/**/*.md` exclusion. + +Both inherited real-provider gaps remain separate and unclosed through U7: + +- **#7179 REAL Claude turn survival UNVERIFIED:** both real runs failed at + createAgent availability admission before dispatch/sentinel/controls; + underlying cause unknown. +- **#7169 REAL OMP UNVERIFIED:** `beforeAll` `omp --version` exited 127 with + `env: bun: No such file or directory`; all 14 skipped before resources, body, + turn or sentinel. Runtime cleanup was not exercised. + +MCP unit evidence does not close either runtime gap or earlier native, packaged +Electron and locale obligations. No provider/auth probe, environment repair, +further basket/manifest edit, later subject, live configuration write, +publication, installation, daemon restart or activation occurs. Coordinator +ADVANCE remains a separate gate. diff --git a/fork/handover-beta-upgrade-u3-7146-2026-10-18.md b/fork/handover-beta-upgrade-u3-7146-2026-10-18.md new file mode 100644 index 00000000000..9c775726b90 --- /dev/null +++ b/fork/handover-beta-upgrade-u3-7146-2026-10-18.md @@ -0,0 +1,128 @@ +# Beta upgrade, U3 #7146 handover (2026-10-18) + +Owner `fork/node-declaration-walk-0.12.0-beta.1` in isolated worktree +`/home/ctaylor/repos/paseo-upgrade-node-declaration-walk` starts directly from +accepted #7062. All twelve earlier owners and original custom remain clean and +unchanged. Checks run only on the exclusive Neptune candidate. + +## Fixed input and preservation + +| Identity | SHA | +| --- | --- | +| Accepted parent | `65723a80fcedaca36ac558fe9bc82b86fc84172f` | +| Accepted parent tree | `96268d00f141eb0052950d301adcd7534a30e010` | +| Frozen base, excluded sibling #7141 | `c1558d29eab78c898743adb613afa01ba4f0e780` | +| Actual original subject parent | `8d9a7123ba38353029352a93a85cca7160af6f07` | +| Frozen head, single original subject | `b86cbd38e5628e7329ff31cec5af89c87bfc4ac9` | +| Attributed carry | `973bd72caa0196379967ebbc2bb3ff6477a37654` | +| Final source | `7a43f7930657dab0b645f4c29c29a29cd27f677a` | +| Final source tree | `50beb2adf9c165002ed1f234ad29efb8e979c40d` | + +Control `91088fd130cdd62722a0e6180672e0ad3a4a3a79` supplies twelve exact comment +pins. Each ref, clean owner and serial ancestry was verified before the disposable +basket advanced ff-only from accepted #7057 to accepted #7062. Basket HEAD/tree +equal the accepted parent above. No assembly commit, build or green rerun was +needed; exact SHA/tree identity permits evidence reuse. Three assembly receipts +verify on both hosts, seal SHA256 +`aff6949e881d7105577d0ee09a94bd948b52a3395c999021e6c0c2f58d36a3e6`. +The basket stays there throughout this separate owning carry. + +Frozen pins SHA256 remains +`d26697e552936677125975c675f94e85b7de4f24e7294a4ef041ee75ca104833`. +The frozen base is a sibling of the subject, with the same actual parent. Its +raw diff to the subject includes unrelated replica-cache reversions: 86 test +lines and three production lines. Both reversions are excluded completely. +Only the actual parent-to-head subject, two compiler files with 55 additions and +seven deletions, is attributed with its original author and `-x`. No unrelated +ancestry or synthetic test merge is integrated. The frozen synthetic merge object +was unavailable locally and was not used as an input. + +Fresh explicit-parent trial had zero conflicts and two automatic content merges, +in compiler source and tests. Carry tree +`122ab36f9164af2a25f08eef9ece75a2de537d43` exactly equals that trial; both files' +carry hunks equal the original subject. The three upstream fixtures remain +byte-equal, SHA256 +`67491350c314662d9d13601255397438aca92ddd31fc214b2a1901ded14dd91d`. +`source-inventory.json` verifies all 5,949 outside paths unchanged, including both +replica-cache files, and every accepted test body intact. Only compiler source +and its existing test file differ from the accepted parent. + +Declaration-only `import "node"` maps to `@types/node`; Node host classification +recognizes builtins and future `node:` names independently of the host version. +Checks on both original and mapped names run before host-type skipping. Client +and shared Node imports still produce explicit architectural errors. Fork SDK +normalization, canonical/renamed aliases, host-private entries, protocol type-only +exemption, missing third-party declarations, runtime ownership, physical realpath, +symlink and linked-dependency confinement remain. Plugins are trusted, +unsandboxed code; this is no new security or sandbox guarantee. There are no SDK, +protocol, dependency, provider, installation or live configuration changes. + +## Behavioral evidence and classifications + +Receipts are under local scratch +`/home/ctaylor/.jcode/scratch/beta-upgrade-20261017/u3-7146-implementation/` +and Neptune +`~/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u3-7146-implementation/`. +The separate thirteen-entry preflight seal verifies on both hosts, SHA256 +`e1bef97825a273191307f262e98bc57f9cdee04519da2b1e42e2f6618d19eed3`. +Persistent advisor approved the exact two-file carry and four additional negative +cases before implementation, within the user's existing authorization. + +The initial three exact expanded-title selectors matched no tests: each exited +zero with all 90 cases skipped. Those original receipts remain as a selection +gap, not red or green evidence. A corrected common-title-prefix selector changes +only the command selection and runs all three unchanged upstream fixtures +against accepted production: three fail, 87 skip. `red-three-fixtures.log` records +unresolved Node declaration failure, including future `node:paseo-future-builtin` +in `@types/node`. No test body or assertion changed. Exact accepted production +blob identity, commands, exits and clean restoration are retained. + +Four additive cases use real temporary dependency declarations reached from +client/shared owners, crossed with ambient `node`/future `node:` imports. Each +requires the literal Node architectural error naming the owner, original/mapped +specifier and canonical declaring file; unresolved-type failures cannot satisfy +the assertion. No compiler or declaration-reader mock is used. All existing SDK, +runtime and physical-owner tests remain unchanged. + +| Check at exact source `7a43f7930` | Receipt | Result | +| --- | --- | --- | +| Owning `npm run build:server`, before suite | `build-source.log` | Exit 0 | +| Complete compiler test file, once | `compiler-source.log` | 94 pass | +| `npm run typecheck` / `lint` / `format:check` | `static-source.log` | 0 / 0 / 0 | + +Exact source static SHA256 is +`6d5b8f80b2bfe5b61fc2bc313c73b541c0a64e88c2ddfc1205d7a473d6a8d386`. +No unchanged green suite or build is rerun. The docs-only child requires exact +final-head static checks; package sources and tested behavior remain identical. + +## Review, seal and remaining gaps + +Advisor **ACCEPT** at exact source `7a43f7930` follows direct source inspection and +verification of actual receipt hashes, all 94 compiler passes and required static. +The four boundary cases require architectural errors and canonical paths; the +zero-selection runs remain non-proof. No bounded findings remain. + +The 37-entry source inventory `receipts-source.sha256` has SHA256 +`f6a4612548ada5bfc6996d4ef952a62d2d3c316a0756a00ddb2f10738be5f2a5`. +It retains the intended red run, original selection gap, attributed source, +preservation inventory and advisor verdict. Both hosts verify every entry. +Final docs-head static and clean-host receipts are recorded separately in +`final-static.log`, `final-static.summary`, `final-completion.json` and +`receipts-final.sha256`. The docs-only seal changes no checked package source +and requires no build or unit rerun. The npm formatter retains the existing +`fork/**/*.md` exclusion. + +Both inherited real-provider gaps remain separate and unclosed through U7: + +- **#7179 REAL Claude turn survival UNVERIFIED:** both real runs failed at + createAgent availability admission before dispatch/sentinel/controls; + underlying cause unknown. +- **#7169 REAL OMP UNVERIFIED:** `beforeAll` `omp --version` exited 127 with + `env: bun: No such file or directory`; all 14 skipped before resources, body, + turn or sentinel. Runtime cleanup was not exercised. + +Compiler evidence does not close either runtime gap or earlier native, packaged +Electron and locale obligations. No provider/auth probe, environment repair, +further basket/manifest edit, later subject, live configuration write, +publication, installation, daemon restart or activation occurs. Coordinator +ADVANCE remains a separate gate. diff --git a/fork/handover-beta-upgrade-u3-7169-2026-10-18.md b/fork/handover-beta-upgrade-u3-7169-2026-10-18.md new file mode 100644 index 00000000000..fa53b7228ea --- /dev/null +++ b/fork/handover-beta-upgrade-u3-7169-2026-10-18.md @@ -0,0 +1,157 @@ +# Beta upgrade, U3 #7169 handover (2026-10-18) + +Owning branch `fork/slash-followup-0.12.0-beta.1`, isolated worktree +`/home/ctaylor/repos/paseo-upgrade-slash-followup`. The disposable basket remains +at accepted `ea141f351`; all earlier source owners and the original custom +checkout remain unchanged. Checks ran on Neptune's exclusive private candidate. + +**REAL OMP UNVERIFIED.** The real suite failed in `beforeAll`: `omp --version` +returned exit 127 with `env: bun: No such file or directory`. All 14 tests were +skipped; no test resources, body, turn, sentinel or cleanup path ran. This is +separate from #7179's real Claude availability-admission gap, which remains +UNVERIFIED through U7 with underlying cause unknown. Neither gap is a passing +runtime receipt or an established subject product failure. + +## Fixed input and integration + +| Identity | SHA | +| --- | --- | +| Accepted #7179 parent | `ea141f351920e51f7b7e0116352f998d8e97deb7` | +| Frozen #7169 base | `ae0b2588bf3a8f884b5b7207285e4df52bdcc01d` | +| Frozen #7169 head | `57427189cead2594dabb670a593c9a61b156921c` | +| Exact published squash | `cd77ecd837df40d042599d8847403eb416b35b04` | +| Attributed carry | `183aa718c870b9bdca79650ff2c07b4f14bc98e2` | +| Additive behavioral proof and bounded real cleanup | `b44b9f54b704d8e3dd195b553f099eb30a7cb8c7` | +| Approved test-only synchronization and callback extraction | `b2b8f342d2bb7e791578505ff75af7bd2f40379e` | +| Corrected source tree | `6d84b74037c7985b3750d6f5a37aa849966e31d8` | + +The frozen `upstream-pins.json` SHA256 remains +`d26697e552936677125975c675f94e85b7de4f24e7294a4ef041ee75ca104833`. +The four frozen commits' net patch is byte-equal to the published squash patch, +stable patch ID `c7e3b5fac11acbccbaa0d46cd4dc8a0500869cb1`. Only that single +published commit was cherry-picked with its original author and exact `-x` +trailer. Its unrelated parent history is excluded. The carry's sole parent is +accepted #7179; the pin is attributed input, not a merge parent. + +Fresh explicit-base inventory found two conflicted files and nine automatic +merges. The approved import union retains side-conversation imports alongside +the parser. The test union adds the envelope case before the accepted ACP +cancellation test, retaining its full name, fence comment and body. MCP's +automatic union retains earlier fork tests; eight OMP paths had identical +accepted/base blobs and received the pinned content. The carry is exactly +403 additions / 51 deletions across 11 files. No raw upstream basket is merged. + +The sourced envelope is unwrapped only for provider command classification. +Recording retains its source and client identity; structured prompts pass +through. Idle OMP commands use the existing prompt lifecycle and request-ID +correlation; busy commands retain their active turn without aborting. The sole +private runtime `followUp` helper and its fake are retired after their caller +migrates; native active steering and existing RPC variants remain. No protocol, +dependency, authentication, authorization or broader provider change is included. + +`source-inventory-b2b8f342d.json`, SHA256 +`14e194e12c4ac1cff1b3177e9fa1a0cad41939245f4b0f84d3f730723bde3622`, +proves all 5,936 accepted paths outside the 11 subject paths remain unchanged. +Production remains identical to the attributed carry, including five exact +published OMP production blobs. Accepted manager tests are unchanged except the +additive case; the ACP cancellation tail and side-conversation import are exact. +The corrected child changes only MCP and the real harness. Its two extracted +real acceptance bodies are equal after formatting whitespace/trailing commas; +legacy real cases and the three reused unit-file blobs remain exact. This is +source preservation evidence, not real-provider runtime proof. + +## Behavioral proof and receipts + +Receipts live under local scratch +`/home/ctaylor/.jcode/scratch/beta-upgrade-20261017/u3-7169/` and Neptune +`~/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u3-7169/`. + +Compatible cases failed first against accepted #7179 production on Neptune. +The sourced manager command returned false instead of true. Both idle OMP +commands recorded no prompt instead of the exact streaming prompt. The first +selection expression matched only the manager case because parameterized test +names contain quotes; that one-failure receipt and its skipped OMP file remain. +The corrected selection ran both intended OMP cases: two behavioral failures, +71 skipped. No product/assertion change occurred between those selections. + +The final tests cover `/follow-up` and `/steer` symmetrically: idle success, +early and late rejection using an ACK gate at the actual injected runtime seam, +unrelated request-ID rejection, exact ACK identity, terminal error and parent +notification. Actual session events prove one `turn_started` despite a later +native start. Busy delivery preserves the active turn and does not abort. +Manager coverage retains the original sourced timeline envelope/client identity +and verifies structured-input identity and human-pasted-envelope behavior. + +| Check | Exact source | Receipt | Result | +| --- | --- | --- | --- | +| Owning `npm run build:server`, before unit files | `b44b9f54b` | `build-b44b9f54b.log` | Exit 0 | +| Complete `agent-manager.test.ts` | `b44b9f54b` | `agent-manager-b44b9f54b.log` | 226 pass | +| Complete OMP `agent.test.ts` | `b44b9f54b` | `omp-agent-b44b9f54b.log` | 73 pass | +| Complete OMP `cli-runtime.test.ts` | `b44b9f54b` | `omp-cli-runtime-b44b9f54b.log` | 23 pass | +| Initial complete MCP attempt, bail on first failure | `b44b9f54b` | `mcp-server-b44b9f54b.log` | 71 pass, 1 fail; remainder not run | +| Corrected complete MCP | `b2b8f342d` | `mcp-server-b2b8f342d.log` | 146 pass | +| Initial typecheck / lint / format | `b44b9f54b` | `static-b44b9f54b.log` | 0 / 1 / 0; five harness lint findings retained | +| Corrected typecheck / lint / format | `b2b8f342d` | `static-b2b8f342d.log` | 0 / 0 / 0 | +| Focused real OMP selection | `b44b9f54b` | `real-omp-b44b9f54b.log` | Exit 1 in beforeAll; all 14 skipped | + +Build SHA256 is +`73c066b07b2edee03b1d79e7e7c5880b43c4dfea679e42419e220fc2748ccff5`. +Corrected static SHA256 is +`766d35ea79e3b98e2d18d1428daf61904d5c64a7d4631c29227d17532aeb7cc7`. +The final receipts cover 468 passing affected unit cases. The owning build and +three unchanged green unit files are reused after the test-only correction; +only failed/changed MCP and required static reran. The blocked real suite did +not rerun solely for mechanical callback extraction. No build or test ran on +Uranus, and no unchanged green suite reran. + +## Failure classification and bounded corrections + +The first strengthened rejection case observed manager `idle` immediately after +the fake runtime received its prompt. `nextPrompt()` establishes runtime receipt, +not ingestion of the manager's asynchronous `turn_started` event. Advisor and +coordinator approved waiting for actual manager `running` while the ACK remains +gated, before the unrelated-result injection. The immediate assertion after that +injection and all ACK-order, correlation, terminal, parent and no-abort assertions +remain. This is test startup synchronization, not a product correction. + +The first lint receipt contains four nested-callback errors introduced by the +bounded real wrapper and one mutable-reverse error. The approved correction +lifts exactly the two complete idle callback bodies into named top-level helpers +and uses `toReversed()` for the same LIFO cleanup. Assertions, cleanup +registrations, sentinels, models and timeouts remain unchanged; no suppression +was added. Both source heads received advisor clearance. + +The real selection requires the existing executable/version preflight. Its +actual `omp --version` command failed because its `bun` interpreter could not +resolve in the run environment. This does not prove OMP is uninstalled, a version +mismatch, authentication failure or quota issue. No provider installation, +authentication check, environment repair, model substitution or timeout/sentinel +adjustment occurred. No real command reached dispatch, admission or turn survival. + +The approved harness attempts every acquired client, daemon and temporary root, +plus registered MCP cleanup, even after an earlier cleanup failure. Setup/body +errors retain their identity and report cleanup failures; cleanup-only failures +throw an aggregate after `finally`. Those paths are source reviewed, not runtime +exercised by the preflight failure; no injected cleanup-fault proof is claimed. + +## Review and seal + +The persistent advisor approved the bounded design before implementation, +cleared both source heads and approved both mechanical corrections before edits. +Its final **CONDITIONAL ACCEPT** at `b2b8f342d` verifies the source inventory, +468 unit passes and build/static receipts, with the real OMP gap explicit. +`advisor-final-b2b8f342d.txt` has SHA256 +`54840170dbfc0a252d2530ffbf5414b43a4ac781cd99d83b1e23fc07bf0200e8`. + +`receipts-b2b8f342d.sha256` seals 68 source, review and reproduction files, +SHA256 `4663b8093c08f08fc273417c4eefb7f6c844dae832f38ce3fddb94f33e6aa3ef`. +It retains the initial MCP, lint and real failures separately, plus corrected +passing receipts. The earlier 17-entry preflight seal remains unchanged. +Final docs formatting, exact docs-head static and clean integrity receipts sit +outside this source seal. Only this handover and the owning plan row belong in +the docs-only commit. + +Coordinator ADVANCE remains ungranted. No later subject, basket mutation, +publication, live configuration change, restart, installation or activation is +part of this owner. The separate #7179 real gap and other U7 platform/runtime +obligations remain open. diff --git a/fork/handover-beta-upgrade-u3-7179-2026-10-18.md b/fork/handover-beta-upgrade-u3-7179-2026-10-18.md new file mode 100644 index 00000000000..0edf3de0b10 --- /dev/null +++ b/fork/handover-beta-upgrade-u3-7179-2026-10-18.md @@ -0,0 +1,134 @@ +# Beta upgrade, U3 #7179 handover (2026-10-18) + +Owning branch `fork/claude-turn-survival-0.12.0-beta.1`, isolated worktree +`/home/ctaylor/repos/paseo-upgrade-claude-turn-survival`. The disposable basket +remains at accepted baseline `6a2d930ee`; all previous source owners remain +unchanged. Checks ran on Neptune's exclusive private candidate. + +**REAL Claude turn survival UNVERIFIED.** Both real runs failed during +`createAgent` availability admission, before dispatch, sentinel or controls. +The underlying cause is unknown. Advisor acceptance is conditional on keeping +this gap explicit; the coordinator will consider source-only progression with +the real gap tracked at U7. ADVANCE and later preflight remain ungranted. + +## Fixed input and source ownership + +| Identity | SHA | +| --- | --- | +| Accepted A1 parent | `6a2d930ee4845e121c718a143742b9d2cb8909c0` | +| Exact #7179 subject pin | `4e63574404ddf2a8153455d6a79bf45c4756fff8` | +| Subject's upstream parent, excluded from integration | `30122b1ae11369f275cf931b68078716d5a8c4c3` | +| Attributed source cherry-pick | `34176c6142b357f03f7040f51646de69a4bd07ac` | +| Approved test-only cleanup correction | `2b5f4be7d11f7a619f8d2317eb50639efcfd4dd5` | +| Corrected source tree | `f0d74140fc67f110844d1ed6d040a466152010de` | + +The checked-in `upstream-pins.json` SHA256 remains +`d26697e552936677125975c675f94e85b7de4f24e7294a4ef041ee75ca104833`. +The single subject was cherry-picked with its original author and exact source +trailer. Its parent history was excluded: #6242 background-subagent UI, #7098 +question-response UI and lockfile/Nix signatures are not carried here. The pin +is attributed input, not a merge parent. The sole source-cherry-pick parent is +accepted A1; the cleanup correction is its direct child. + +Fresh preflight and actual application both found one conflicted production +file and one hunk. The approved union retains `ensureQuery`'s entry and +post-build closed-session guards and carries the exact upstream active-query +reuse condition. The automatically merged `previousQuery` identity comparison +distinguishes a reused running query from a rejected newly launched query. +Production remains exactly 5 additions / 3 deletions from accepted A1. + +Current mode, plan state, original mode-error rethrow, side-question restart +refusal, cancellation, process reaping, autonomous-turn ownership and all other +fork seams remain unchanged. No protocol, dependency, provider configuration, +authentication or authorization change is included. No earlier owner is retired. + +`source-inventory-2b5f4be7d.json`, SHA256 +`0ce95c8a930a8a05f7ee5dfd1b93d8095bb061df408d9c5bf6a557568a5069af`, +proves the exact production substitutions, unchanged upstream test and real +acceptance bodies, and all 5,943 accepted paths outside the production file. +The only additions are the two carried test files. The cleanup-only child +changes neither production nor the four unit files; owning-build inputs remain +unchanged. This inventory proves source preservation, not runtime behavior. + +## Tests and exact receipts + +Receipts live under local scratch +`/home/ctaylor/.jcode/scratch/beta-upgrade-20261017/u3-7179/` and Neptune +`~/.paseo-fork/candidates/upgrade-0.12.0-beta.1/evidence/u3-7179/`. + +The three original mode/model/commands cases each failed first against accepted +A1 production with `query closed before turn finished`, rather than setup or +compilation failure. Separate failing-first logs retain each result and the +accepted production and original test blobs. The complete new suite then passed +all five cases after the carry. The additive active/idle rejection cases assert +original error identity, retained mode, actual running-query survival, pending +effort on the next turn and retirement of the rejected idle replacement query. + +| Check | Exact source | Receipt | Result | +| --- | --- | --- | --- | +| Owning `npm run build:server`, before unit files | `34176c614` | `build-34176c614.log` | Exit 0 | +| Complete `agent.live-settings.test.ts` | `34176c614` | `live-settings-34176c614.log` | 5 pass | +| Complete `agent.redesign.test.ts` | `34176c614` | `redesign-34176c614.log` | 40 pass | +| Complete `side-question.test.ts` | `34176c614` | `side-question-34176c614.log` | 23 pass | +| Complete `agent.interrupt-restart-regression.test.ts` | `34176c614` | `interrupt-restart-34176c614.log` | 14 pass | +| Initial typecheck / lint / format | `34176c614` | `static-34176c614.log` | 0 / 1 / 0; original lint failure retained | +| Corrected typecheck / lint / format | `2b5f4be7d` | `static-2b5f4be7d.log` | 0 / 0 / 0 | +| Initial real-provider case | `34176c614` | `real-mid-turn-34176c614.log` | Exit 1; availability admission gap | +| Changed real-provider case | `2b5f4be7d` | `real-mid-turn-2b5f4be7d.log` | Exit 1; availability admission gap | + +Build SHA256 is +`f96132c525485f8868def3e7e585759ca902dc69a736a3541919ba76d57d2815`. +Corrected source static SHA256 is +`f42d7a9cbca831a2eb4bdce1cb920ced5ec6dfbafca5fcd179fd5c1fcd8dfb24`. +The four affected unit files ran once: 82 passing cases. The build and unit +receipts retain their original source SHA and are reused after the approved +cleanup-only correction. No unchanged green suite was rerun. No build or test +ran on Uranus. + +## Real-provider gap and cleanup classification + +Both real failures report `Provider 'claude' is not available` with +`exit code: unknown`, at `client.createAgent` (initial line 27, corrected line +28). Their test bodies ran 352 ms and 401 ms. Neither reached timeline +subscription, message dispatch, sentinel creation, thinking/mode controls or the +first-command completion assertion. Neither supplies a passing runtime receipt +or a #7179 product-failure verdict. + +Read-only source tracing identifies the ready-provider admission check and +Claude's default launch resolver. It does not establish a missing installation, +configuration, version, authentication or quota cause. A separate attempted +diagnostic import failed with `ERR_MODULE_NOT_FOUND` before loading a nonexistent +unbundled dist module; it is retained as a failed diagnostic command and supplies +no provider-cause evidence. No provider/auth command, install, environment change, +model substitution or timeout/sentinel adjustment was performed for diagnosis. + +Both runs acquired daemon and client resources before creation failed. Cleanup +attempts each acquired resource independently, preserving the primary throwable +and reporting cleanup failures. Both receipts retain the original admission +error and report no cleanup aggregate; this is not injected cleanup-fault proof. +The first static run flagged the success-body cleanup throw inside `finally`. +Advisor and coordinator approved moving that throw after `finally`, collecting +failures outside and reporting inside only when a primary failure exists. The +original lint failure and both failed real runs remain separate receipts. + +The unchanged real-case contract would prove only the first foreground command +completes after the controls. It does not claim all three commands or final DONE. +That proof remains open at U7; no provider installation, auth check or assertion +relaxation is authorized by this handover. + +## Review and seal + +The persistent advisor approved design before implementation, cleared both exact +source heads, and issued **CONDITIONAL ACCEPT** at `2b5f4be7d`. Its final ruling +is `advisor-final-2b5f4be7d.txt`, SHA256 +`226e2f5bc5a011da862c0552dd2574561e9c815688f7c482e8bbed90f03fc0ff`. +Coordinator authorized the bounded carry and cleanup correction, then the +docs-only seal with the real gap explicit. This does not grant progression. + +`receipts-2b5f4be7d.sha256` seals 62 source, review and reproduction files, +SHA256 `738ee1b846d133991ab90d275c257d7aab806b7fd30ffa75036b320962156f17`. +It includes both real failures, the original failed static receipt and corrected +passing static receipt. The earlier 13-entry preflight inventory is preserved. +Final docs-only formatting, final-head static and clean-head integrity receipts +sit outside this sealed source inventory. The handover and owning-plan row are +the only intended docs-seal changes; no later subject or basket edit is included. diff --git a/fork/plans/tmad-desvio-0.11.1.md b/fork/plans/tmad-desvio-0.11.1.md new file mode 100644 index 00000000000..4dec04d5297 --- /dev/null +++ b/fork/plans/tmad-desvio-0.11.1.md @@ -0,0 +1,77 @@ +# 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 new file mode 100644 index 00000000000..cd4028a55a2 --- /dev/null +++ b/fork/plans/tmad-maintained-port-plan.md @@ -0,0 +1,323 @@ +# 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 new file mode 100644 index 00000000000..e57ab3a275b --- /dev/null +++ b/fork/plans/tmad-port-work-items.md @@ -0,0 +1,198 @@ +# 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 new file mode 100644 index 00000000000..9b5b8ff68c4 --- /dev/null +++ b/fork/plans/tmad-port/STATUS.md @@ -0,0 +1,182 @@ +# 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 new file mode 100644 index 00000000000..ebe312885c1 --- /dev/null +++ b/fork/plans/tmad-port/briefs/COMMON.md @@ -0,0 +1,50 @@ +# 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 new file mode 100644 index 00000000000..b8005a7814c --- /dev/null +++ b/fork/plans/tmad-port/briefs/ORCHESTRATOR.md @@ -0,0 +1,73 @@ +# 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 new file mode 100644 index 00000000000..b781de39325 --- /dev/null +++ b/fork/plans/tmad-port/briefs/brief-P0.md @@ -0,0 +1,14 @@ +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 new file mode 100644 index 00000000000..89218f28f17 --- /dev/null +++ b/fork/plans/tmad-port/briefs/brief-P2.md @@ -0,0 +1,9 @@ +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 new file mode 100644 index 00000000000..444c76fdc4c --- /dev/null +++ b/fork/plans/tmad-port/briefs/brief-TM01.md @@ -0,0 +1,25 @@ +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 new file mode 100644 index 00000000000..2d9cb9a63d6 --- /dev/null +++ b/fork/plans/tmad-port/briefs/brief-TM02.md @@ -0,0 +1,16 @@ +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 new file mode 100644 index 00000000000..e75b51f6f6d --- /dev/null +++ b/fork/plans/tmad-port/briefs/brief-TM03.md @@ -0,0 +1,13 @@ +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 new file mode 100644 index 00000000000..5ffeb970f45 --- /dev/null +++ b/fork/plans/tmad-port/briefs/brief-TM04.md @@ -0,0 +1,11 @@ +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 new file mode 100644 index 00000000000..e6ad13b855e --- /dev/null +++ b/fork/plans/tmad-port/briefs/brief-TM07.md @@ -0,0 +1,12 @@ +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 new file mode 100644 index 00000000000..d3a5533d203 --- /dev/null +++ b/fork/plans/tmad-port/evidence/.baseline-merge-status.txt @@ -0,0 +1,31 @@ +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 new file mode 100644 index 00000000000..351bd0f3d23 --- /dev/null +++ b/fork/plans/tmad-port/evidence/.manifest-refs.txt @@ -0,0 +1,24 @@ +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 new file mode 100644 index 00000000000..36805e38c5d --- /dev/null +++ b/fork/plans/tmad-port/evidence/P0-feature-map.md @@ -0,0 +1,308 @@ +# 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 new file mode 100644 index 00000000000..0f627f59dd1 --- /dev/null +++ b/fork/plans/tmad-port/evidence/P0-inputs.txt @@ -0,0 +1,46 @@ +# 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 new file mode 100644 index 00000000000..3ca3a8874ca --- /dev/null +++ b/fork/plans/tmad-port/evidence/P0.md @@ -0,0 +1,185 @@ +# 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 new file mode 100644 index 00000000000..af61a9a0de1 --- /dev/null +++ b/fork/plans/tmad-port/evidence/P2.md @@ -0,0 +1,402 @@ +# 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 new file mode 100644 index 00000000000..33233475318 --- /dev/null +++ b/fork/plans/tmad-port/evidence/P6-assembly-2026-10-08.md @@ -0,0 +1,149 @@ +# 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 new file mode 100644 index 00000000000..feaa3eebfe9 --- /dev/null +++ b/fork/plans/tmad-port/evidence/P6-conflict-resolution-log-2026-10-08.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 00000000000..08ca88655a2 --- /dev/null +++ b/fork/plans/tmad-port/evidence/P6-runtime/README.md @@ -0,0 +1,61 @@ +# 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 new file mode 100644 index 00000000000..6bee999eae1 --- /dev/null +++ b/fork/plans/tmad-port/evidence/P6-runtime/p6-final-enabled-runtime.log @@ -0,0 +1,15 @@ +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 new file mode 100644 index 00000000000..3208ade31ab --- /dev/null +++ b/fork/plans/tmad-port/evidence/P6-runtime/p6-frozen-voice-client-server-tests.log @@ -0,0 +1,64 @@ + + 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 new file mode 100644 index 00000000000..342454abc7b --- /dev/null +++ b/fork/plans/tmad-port/evidence/P6-runtime/p6-full-custom-voice-app-tests.log @@ -0,0 +1,8 @@ + + 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 new file mode 100644 index 00000000000..b038ae51942 --- /dev/null +++ b/fork/plans/tmad-port/evidence/P6-runtime/p6-full-custom-voice-client-server-tests.log @@ -0,0 +1,9 @@ +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 new file mode 100644 index 00000000000..d1dacf59c9c --- /dev/null +++ b/fork/plans/tmad-port/evidence/P6-runtime/p6-noqueue-custom-runtime.log @@ -0,0 +1,14 @@ +{ + "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 new file mode 100644 index 00000000000..9b283e7b28f --- /dev/null +++ b/fork/plans/tmad-port/evidence/P6-runtime/pending-fixture.json.txt @@ -0,0 +1,15 @@ +{ + "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 new file mode 100644 index 00000000000..23bc5f29ebc --- /dev/null +++ b/fork/plans/tmad-port/evidence/P6-runtime/queue-removal-enabled-runtime-check.ts.txt @@ -0,0 +1,56 @@ +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 new file mode 100644 index 00000000000..cf7fcd7e767 --- /dev/null +++ b/fork/plans/tmad-port/evidence/P6-runtime/queue-removal-runtime-check.ts.txt @@ -0,0 +1,88 @@ +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 new file mode 100644 index 00000000000..f607bcd56d4 --- /dev/null +++ b/fork/plans/tmad-port/evidence/TM-01.md @@ -0,0 +1,287 @@ +# 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 new file mode 100644 index 00000000000..26eacc513ce --- /dev/null +++ b/fork/plans/tmad-port/evidence/TM-02.md @@ -0,0 +1,189 @@ +# 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 new file mode 100644 index 00000000000..aa4dab7d2c4 --- /dev/null +++ b/fork/plans/tmad-port/evidence/TM-03.md @@ -0,0 +1,252 @@ +# 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 new file mode 100644 index 00000000000..3179d94edfe --- /dev/null +++ b/fork/plans/tmad-port/evidence/TM-04-2026-10-08.md @@ -0,0 +1,299 @@ +# 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 new file mode 100644 index 00000000000..2e88d58e208 --- /dev/null +++ b/fork/plans/tmad-port/evidence/TM-07.md @@ -0,0 +1,263 @@ +# 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 new file mode 100644 index 00000000000..c1c3d070dea --- /dev/null +++ b/fork/plans/tmad-port/evidence/desvio-0.11.1-focused-tests.txt @@ -0,0 +1,28 @@ +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 new file mode 100644 index 00000000000..fd517a22ed3 --- /dev/null +++ b/fork/plans/tmad-port/evidence/desvio-0.11.1-runtime.txt @@ -0,0 +1,14 @@ +{ + "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 new file mode 100644 index 00000000000..1edcf72b50c --- /dev/null +++ b/fork/plans/tmad-port/evidence/manifest-frozen-2026-10-02.txt @@ -0,0 +1,202 @@ +# 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 new file mode 100644 index 00000000000..0e1981678f6 --- /dev/null +++ b/fork/plans/tmad-port/evidence/pluto-cli-typecheck-2026-10-08.md @@ -0,0 +1,49 @@ +# 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 new file mode 100644 index 00000000000..41223dbd251 --- /dev/null +++ b/fork/plans/tmad-port/evidence/pluto-readiness-2026-10-08.md @@ -0,0 +1,65 @@ +# 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 new file mode 100644 index 00000000000..91e681ea5f2 --- /dev/null +++ b/fork/plans/tmad-port/evidence/pluto-side-conversation-events-2026-10-08.md @@ -0,0 +1,87 @@ +# 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 new file mode 100644 index 00000000000..42900f2ec07 --- /dev/null +++ b/fork/plans/tmad-port/evidence/pluto-side-conversation-review-2026-10-08.md @@ -0,0 +1,32 @@ +# 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 new file mode 100644 index 00000000000..b5993cd60ac --- /dev/null +++ b/fork/plans/tmad-port/evidence/review-P0.md @@ -0,0 +1,135 @@ +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 new file mode 100644 index 00000000000..938e8d1b82f --- /dev/null +++ b/fork/plans/tmad-port/evidence/review-P2.md @@ -0,0 +1,195 @@ +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 new file mode 100644 index 00000000000..5804256b2fa --- /dev/null +++ b/fork/plans/tmad-port/evidence/review-P6-final-2026-10-08.md @@ -0,0 +1,164 @@ +# 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 new file mode 100644 index 00000000000..160b1253e53 --- /dev/null +++ b/fork/plans/tmad-port/evidence/review-TM-01-delta.md @@ -0,0 +1,148 @@ +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 new file mode 100644 index 00000000000..4928de2c6a8 --- /dev/null +++ b/fork/plans/tmad-port/evidence/review-TM-01.md @@ -0,0 +1,177 @@ +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 new file mode 100644 index 00000000000..b987ef76812 --- /dev/null +++ b/fork/plans/tmad-port/evidence/review-TM-02.md @@ -0,0 +1,199 @@ +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 new file mode 100644 index 00000000000..f5bf1cdd35b --- /dev/null +++ b/fork/plans/tmad-port/evidence/review-TM-03.md @@ -0,0 +1,197 @@ +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 new file mode 100644 index 00000000000..f3f33b59905 --- /dev/null +++ b/fork/plans/tmad-port/evidence/review-TM-04-2026-10-08.md @@ -0,0 +1,145 @@ +# 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 new file mode 100644 index 00000000000..37d6025b911 --- /dev/null +++ b/fork/plans/tmad-port/evidence/review-TM-07.md @@ -0,0 +1,144 @@ +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 new file mode 100644 index 00000000000..4ec942504d3 --- /dev/null +++ b/fork/plans/tmad-port/evidence/stream-rollback.md @@ -0,0 +1,75 @@ +# 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/packages/app/e2e/browser/agent-message-submission.spec.ts b/packages/app/e2e/browser/agent-message-submission.spec.ts index 24f26f1c44f..78ec9c975d8 100644 --- a/packages/app/e2e/browser/agent-message-submission.spec.ts +++ b/packages/app/e2e/browser/agent-message-submission.spec.ts @@ -22,6 +22,8 @@ import { fillComposerDraft, holdSendButton, sendDraftToQueue, + configureComposerQueueSend, + queueComposerWithButton, startRunningMockAgent, submitMessage, } from "../support/helpers/composer"; @@ -73,6 +75,150 @@ 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 80832e5fe10..c3f3e21cd60 100644 --- a/packages/app/e2e/browser/agent-stream-ui.spec.ts +++ b/packages/app/e2e/browser/agent-stream-ui.spec.ts @@ -1,4 +1,6 @@ import { test, expect } from "../support/fixtures"; +import type { Page } from "@playwright/test"; +import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate"; import { awaitAssistantMessage, expectAgentIdle, @@ -18,7 +20,13 @@ import { import { delayCreatedAgentInitialTailResponse } from "../support/helpers/agent-timeline-gate"; import { selectModel } from "../support/helpers/app"; import { clickNewChat } from "../support/helpers/launcher"; -import { expectComposerVisible, startRunningMockAgent } from "../support/helpers/composer"; +import { closeSheet } from "../support/helpers/sheet"; +import { + expectComposerVisible, + expectComposerDraft, + fillComposerDraft, + startRunningMockAgent, +} from "../support/helpers/composer"; import { openAgentRoute, seedMockAgentWorkspace, @@ -27,6 +35,195 @@ 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/browser/branch-switcher.spec.ts b/packages/app/e2e/browser/branch-switcher.spec.ts index 690713c673c..3f86f3f932e 100644 --- a/packages/app/e2e/browser/branch-switcher.spec.ts +++ b/packages/app/e2e/browser/branch-switcher.spec.ts @@ -4,8 +4,8 @@ import { expect, test, type Page } from "../support/fixtures"; import { daemonWsRoutePattern } from "../support/helpers/daemon-port"; import { gotoAppShell } from "../support/helpers/app"; import { - expectNoBranchSwitcherInWorkspaceHeader, expectWorkspaceBranch, + expectWorkspaceHeaderBranch, openChangesPanel, switchBranchFromChangesPanel, } from "../support/helpers/branch-switcher"; @@ -164,14 +164,14 @@ test.describe("Branch switcher", () => { title: customTitle, }); - // The header shows the custom title verbatim (a plain static title), never a - // branch name, and the branch switcher does not live in the header. + // The header title shows the custom title verbatim; the real branch ("main") is a + // separate control beside it, so a title is never mistaken for a branch. const headerTitle = page .getByTestId("workspace-header-title") .filter({ visible: true }) .first(); await expect(headerTitle).toHaveText(customTitle, { timeout: 30_000 }); - await expectNoBranchSwitcherInWorkspaceHeader(page); + await expectWorkspaceHeaderBranch(page, "main"); // The diff panel's switcher tracks the real branch ("main"), not the title, // and switching it checks out the real branch on disk. @@ -181,6 +181,7 @@ test.describe("Branch switcher", () => { await switchBranchFromChangesPanel(page, { from: "main", to: "dev" }); await expectWorkspaceBranch(page, "dev"); await expectFailedRefreshRecovery(page, workspace.repoPath, releaseBranches); + await expectWorkspaceHeaderBranch(page, "dev"); // The custom title is unaffected by the branch switch. await expect(headerTitle).toHaveText(customTitle, { timeout: 30_000 }); diff --git a/packages/app/e2e/browser/chat-find.spec.ts b/packages/app/e2e/browser/chat-find.spec.ts index e8c4b279ae5..6923beb797e 100644 --- a/packages/app/e2e/browser/chat-find.spec.ts +++ b/packages/app/e2e/browser/chat-find.spec.ts @@ -185,7 +185,9 @@ test("loads older history through prompt navigation and finds repeated rendered const jumps = await trackPromptJumpRequests(page, agent.agentId); await openAgentRoute(page, agent); await expect(page.getByText("Prompt number 44", { exact: true })).toBeVisible(); - await expect(page.getByText("Prompt number 0", { exact: true })).toHaveCount(0); + await expect( + page.getByTestId("user-message").getByText("Prompt number 0", { exact: true }), + ).toHaveCount(0); await searchChat(page, "hello world"); await expectHighlight(page, "hello world"); await expect(status(page)).toHaveText("1 of 90"); @@ -429,9 +431,13 @@ async function openChatWithVirtualizedTallMessage(page: Page): Promise { + await page.evaluate(() => { + const released = new Promise((resolve) => { + document.addEventListener("release-clipboard-write", () => resolve(), { once: true }); + }); + const write = navigator.clipboard.writeText.bind(navigator.clipboard); + navigator.clipboard.writeText = async (value) => { + navigator.clipboard.writeText = write; + await released; + await write(value); + }; + }); +} + +function readClipboard(page: Page): Promise { + return page.evaluate(() => navigator.clipboard.readText()); +} + const RED_PIXEL = Buffer.from( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9ZQmcAAAAASUVORK5CYII=", "base64", @@ -141,6 +159,105 @@ async function seedAgentWithFileLink(input: LinkedFile) { } test.describe("CodeMirror workspace file editing", () => { + for (const width of [390, 1280]) { + test(`copies linked file paths from the viewer at ${width}px`, async ({ page, context }) => { + await page.setViewportSize({ width, height: 844 }); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + const session = await seedAgentWithFileLink({ + target: "report%20draft.md:2", + fileName: "report%20draft.md", + content: "# Report\n\nA draft report.", + }); + try { + await openAgentRoute(page, session); + await page.getByText("report%20draft.md:2", { exact: true }).click(); + await expect(page.getByTestId("file-source-editor")).toBeVisible(); + const trigger = page.getByTestId("file-path-actions-trigger").filter({ visible: true }); + await trigger.click(); + await page.getByTestId("file-path-actions-copy-path").click(); + await expect + .poll(() => readClipboard(page)) + .toBe(path.join(session.cwd, "report%20draft.md")); + await expect(page.getByText("Copied File path", { exact: true })).toBeVisible(); + + await selectFileView(page, "Preview"); + await trigger.click(); + await page.getByTestId("file-path-actions-copy-relative-path").click(); + await expect.poll(() => readClipboard(page)).toBe("report%20draft.md"); + await expect(page.getByTestId("markdown-preview-frame")).toBeVisible(); + } finally { + await session.cleanup(); + } + }); + } + + test("copies an outside-workspace link without offering a misleading relative path", async ({ + page, + context, + withWorkspace, + }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + const outside = await withWorkspace({ prefix: "outside-file-path-" }); + const absolutePath = path.join(outside.repoPath, "external.md"); + await writeFile(absolutePath, "# External report", "utf8"); + const session = await seedMockAgentWorkspace({ + repoPrefix: "linked-external-file-", + title: "External file link", + initialPrompt: "Show the external report", + featureValues: { mockAssistantResponse: `[External report](${absolutePath})` }, + }); + try { + await openAgentRoute(page, session); + await openAssistantMarkdownLink(page, "External report"); + const trigger = page.getByTestId("file-path-actions-trigger").filter({ visible: true }); + await trigger.click(); + await expect(page.getByTestId("file-path-actions-copy-relative-path")).toHaveCount(0); + await page.getByTestId("file-path-actions-copy-path").click(); + await expect.poll(() => readClipboard(page)).toBe(absolutePath); + } finally { + await session.cleanup(); + } + }); + + test("keeps a failed clipboard write visible and lets the reader retry", async ({ + page, + context, + withWorkspace, + }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + const workspace = await withWorkspace({ prefix: "file-path-copy-failure-" }); + await writeFile(path.join(workspace.repoPath, "report.md"), "# Report", "utf8"); + await workspace.navigateTo(); + await openWorkspaceFile(page, "report.md"); + await page.evaluate(() => { + const write = navigator.clipboard.writeText.bind(navigator.clipboard); + const exec = document.execCommand.bind(document); + document.execCommand = (command, ...args) => { + if (command !== "copy") return exec(command, ...args); + document.execCommand = exec; + throw new DOMException("Clipboard access denied", "NotAllowedError"); + }; + navigator.clipboard.writeText = async () => { + navigator.clipboard.writeText = write; + throw new DOMException("Clipboard access denied", "NotAllowedError"); + }; + }); + const trigger = page.getByTestId("file-path-actions-trigger").filter({ visible: true }); + await trigger.click(); + await page.getByTestId("file-path-actions-copy-path").click(); + await expect(page.getByText("Copy failed", { exact: true })).toBeVisible(); + await expect(trigger).toBeEnabled(); + await delayNextClipboardWrite(page); + await trigger.click(); + await page.getByTestId("file-path-actions-copy-path").click(); + await expect(trigger).toBeDisabled(); + await page.evaluate(() => document.dispatchEvent(new Event("release-clipboard-write"))); + await expect(trigger).toBeEnabled(); + await expect.poll(() => readClipboard(page)).toBe(path.join(workspace.repoPath, "report.md")); + await expect(page.getByText("Copy failed", { exact: true })).toBeHidden(); + await expect(page.getByText("Copied File path", { exact: true })).toBeVisible(); + }); + test("opens explicit screenshot links and explains missing files", async ({ page }) => { const session = await seedMockAgentWorkspace({ repoPrefix: "screenshot-markdown-link-", diff --git a/packages/app/e2e/browser/pinned-prompt.spec.ts b/packages/app/e2e/browser/pinned-prompt.spec.ts new file mode 100644 index 00000000000..1313f15a945 --- /dev/null +++ b/packages/app/e2e/browser/pinned-prompt.spec.ts @@ -0,0 +1,152 @@ +import type { Page } from "@playwright/test"; +import { expect, test } from "../support/fixtures"; +import { + expectTimelinePromptLandedBelowTop, + expectTimelinePromptVisible, + openAgentTimeline, + scrollTimelinePromptIntoView, + seedLongMockAgentTimeline, + type LongTimelineAgent, +} from "../support/helpers/timeline-pagination"; + +// Wide enough that the transcript is well clear of the compact form factor, which has no pin. +const WIDE_VIEWPORT = { width: 1440, height: 900 }; +const COMPACT_VIEWPORT = { width: 420, height: 860 }; +// Enough turns below `prompts[8]` to fill a viewport: a prompt can only scroll clear of the +// transcript top when the content beneath it is taller than the viewport, and the mock's turns are +// short. Keep this above 13 so `prompts[8]` stays reachable. +const LOADED_TURNS = 14; + +function timeline(page: Page) { + return page.locator('[data-testid="agent-chat-scroll"]:visible').first(); +} + +function pinnedPrompt(page: Page) { + return page.getByTestId("pinned-prompt"); +} + +/** The outgoing pin remains mounted during its exit animation. */ +async function expectSettledPin(page: Page, prompt: string): Promise { + await expect(pinnedPrompt(page).filter({ hasText: prompt })).toHaveCount(1); + await expect(pinnedPrompt(page)).toHaveCount(1); + await expect(pinnedPrompt(page)).toContainText(prompt); +} + +/** Scrolls down until the prompt's own row has left the top of the transcript. */ +async function scrollPromptAboveFold(page: Page, prompt: string): Promise { + await scrollTimelinePromptIntoView(page, prompt); + const promptRow = timeline(page) + .locator("[data-history-row-id]") + .filter({ hasText: prompt }) + .first(); + const [timelineBox, promptBox] = await Promise.all([ + timeline(page).boundingBox(), + promptRow.boundingBox(), + ]); + if (!timelineBox || !promptBox) throw new Error(`Expected a rendered prompt for ${prompt}`); + // The reading line is 8px below the viewport top, and a row's box includes its trailing gap. + // Scroll until the row, not just the bubble inside it, clears that line. + const distance = promptBox.y + promptBox.height - timelineBox.y + 2; + await timeline(page).evaluate((element, delta) => { + if (element instanceof HTMLElement) element.scrollTop += delta; + }, distance); + await expect + .poll(async () => { + const box = await promptRow.boundingBox(); + return box === null || box.y + box.height < timelineBox.y; + }) + .toBe(true); +} + +/** Aligns the prompt row with the transcript's reading line at its top edge. */ +async function scrollPromptToReadingLine(page: Page, prompt: string): Promise { + const activeTimeline = timeline(page); + const promptRow = activeTimeline.locator("[data-history-row-id]").filter({ hasText: prompt }); + const [timelineBox, rowBox] = await Promise.all([ + activeTimeline.boundingBox(), + promptRow.boundingBox(), + ]); + if (!timelineBox || !rowBox) { + throw new Error(`Expected a rendered timeline prompt for ${prompt}`); + } + await activeTimeline.hover(); + await page.mouse.wheel(0, rowBox.y - timelineBox.y - 8); + await expectTimelinePromptLandedBelowTop(page, prompt); +} + +test.describe("pinned current prompt", () => { + let agent: LongTimelineAgent; + + test.beforeAll(async () => { + test.setTimeout(120_000); + agent = await seedLongMockAgentTimeline({ turns: LOADED_TURNS }); + }); + + test.afterAll(async () => { + if (agent) { + await agent.cleanup(); + } + }); + + test.beforeEach(async ({ page }) => { + await page.setViewportSize(WIDE_VIEWPORT); + await openAgentTimeline(page, agent); + await expectTimelinePromptVisible(page, agent.newestPrompt); + }); + + test("pins nothing while the prompt's own bubble is on screen", async ({ page }) => { + // A prompt can be visible lower in the viewport while the reader is still in an earlier + // turn. Put its row at the reading line to verify the prompt does not pin itself. + await scrollPromptToReadingLine(page, agent.prompts[8]!); + + await expect(pinnedPrompt(page)).toHaveCount(0); + }); + + test("pins the prompt of the turn being read once its bubble scrolls past the top", async ({ + page, + }) => { + await scrollPromptAboveFold(page, agent.prompts[8]!); + + await expectSettledPin(page, agent.prompts[8]!); + }); + + test("swaps the pin when the reader crosses into the next turn", async ({ page }) => { + await scrollPromptAboveFold(page, agent.prompts[6]!); + await expectSettledPin(page, agent.prompts[6]!); + + await scrollPromptAboveFold(page, agent.prompts[7]!); + + await expectSettledPin(page, agent.prompts[7]!); + }); + + test("scrolls the real message back under the pin when clicked", async ({ page }) => { + await scrollPromptAboveFold(page, agent.prompts[8]!); + await expectSettledPin(page, agent.prompts[8]!); + await pinnedPrompt(page).click(); + + await expectTimelinePromptLandedBelowTop(page, agent.prompts[8]!); + // The prompt is the reading row again, so its own bubble carries the turn. + await expect(pinnedPrompt(page)).toHaveCount(0); + }); + + test("hides the pin on a compact viewport", async ({ page }) => { + await scrollPromptAboveFold(page, agent.prompts[8]!); + await expectSettledPin(page, agent.prompts[8]!); + + await page.setViewportSize(COMPACT_VIEWPORT); + + await expect(pinnedPrompt(page)).toHaveCount(0); + }); + + test("fades a prompt longer than the pinned cap", async ({ page }) => { + const longPrompt = Array.from({ length: 80 }, (_unused, line) => `pinned cap line ${line}`) + .join(" ") + .concat(" end"); + await agent.client.sendAgentMessage(agent.agentId, longPrompt); + await agent.client.waitForFinish(agent.agentId, 15_000); + await scrollPromptAboveFold(page, longPrompt); + + await expect(pinnedPrompt(page)).toBeVisible(); + await expect(page.getByTestId("pinned-prompt-fade")).toBeVisible(); + }); +}); diff --git a/packages/app/e2e/browser/plan-card-markdown.spec.ts b/packages/app/e2e/browser/plan-card-markdown.spec.ts index 7faae09dca9..d429d2af0db 100644 --- a/packages/app/e2e/browser/plan-card-markdown.spec.ts +++ b/packages/app/e2e/browser/plan-card-markdown.spec.ts @@ -1,17 +1,30 @@ import type { Locator, Page } from "@playwright/test"; import { expect, test } from "../support/fixtures"; +import { attachFileFromMenu } from "../support/helpers/composer"; import { waitForPermissionPrompt } from "../support/helpers/permissions"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; +import { createAgentTabFromMenu } from "../support/helpers/workspace-tabs"; + +const TEST_JSON = { + name: "handoff-draft.json", + mimeType: "application/json", + buffer: Buffer.from(JSON.stringify({ draft: "keep" })), +}; // Literal shell commands and copyright markers must survive Markdown rendering. test.describe("Plan card markdown", () => { - test("renders plan text verbatim", async ({ page }) => { + test("renders plan text verbatim, copies it, and opens one editable handoff draft", async ({ + page, + }) => { test.setTimeout(180_000); const session = await seedMockAgentWorkspace({ repoPrefix: "plan-card-markdown-", title: "Plan card markdown e2e", initialPrompt: "Emit synthetic plan approval.", + // A model with thinking levels, so the handoff's effort has something to carry. + model: "ten-second-stream", + thinkingOptionId: "high", }); try { @@ -25,6 +38,109 @@ test.describe("Plan card markdown", () => { await expect(planCard).toContainText("---buzz"); await expect(planCard).not.toContainText("©"); await expect(planCard).not.toContainText("—buzz"); + await page.context().grantPermissions(["clipboard-read", "clipboard-write"]); + const readClipboard = () => page.evaluate("navigator.clipboard.readText()"); + await planCard.getByTestId("plan-copy-content").click(); + await expect.poll(readClipboard).toContain("(c)"); + await planCard.getByTestId("plan-copy-link").click(); + await expect.poll(readClipboard).toContain(`/agent/${session.agentId}`); + + // A draft that already holds text and an attachment. Handing off must open its own draft and + // leave this one alone. + await createAgentTabFromMenu(page); + const existingDraftTab = page + .locator('[data-testid^="workspace-tab-draft_"][aria-selected="true"]') + .filter({ visible: true }); + await expect(existingDraftTab).toHaveCount(1); + const existingDraftTabId = await existingDraftTab.getAttribute("data-testid"); + expect(existingDraftTabId).not.toBeNull(); + const existingDraftComposer = page + .getByRole("textbox", { name: "Message agent..." }) + .filter({ visible: true }); + await existingDraftComposer.fill("keep this draft"); + await attachFileFromMenu(page, TEST_JSON); + await expect(page.getByTestId("composer-file-attachment-pill")).toContainText( + TEST_JSON.name, + { + timeout: 30_000, + }, + ); + + // The plan card lives in the source agent's tab, so hand off from there. + await page + .getByTestId(`workspace-tab-agent_${session.agentId}`) + .filter({ visible: true }) + .click(); + await planCard.getByTestId("permission-plan-handoff").click(); + const handoffDraftTab = page + .locator('[data-testid^="workspace-tab-draft_"][aria-selected="true"]') + .filter({ visible: true }); + await expect(handoffDraftTab).toHaveCount(1); + const handoffDraftTabId = await handoffDraftTab.getAttribute("data-testid"); + expect(handoffDraftTabId).not.toBeNull(); + expect(handoffDraftTabId).not.toBe(existingDraftTabId); + const composer = page + .getByRole("textbox", { name: "Message agent..." }) + .filter({ visible: true }); + await expect(composer).toBeEditable(); + await expect(composer).toHaveValue(/Implement the following proposed plan\./); + await expect(composer).toHaveValue(/Add the \(c\) README note/); + await expect(composer).toHaveValue(new RegExp(session.agentId)); + const sourceAgent = (await session.client.fetchAgents({ scope: "active" })).entries.find( + ({ agent }) => agent.id === session.agentId, + )?.agent; + expect(sourceAgent).toBeDefined(); + expect(sourceAgent!.thinkingOptionId).toBe("high"); + const agents = await session.client.fetchAgents({ scope: "active" }); + expect( + agents.entries.filter(({ agent }) => agent.workspaceId === session.workspaceId), + ).toHaveLength(1); + + // The draft that was already open still has its own text and attachment. + await page.getByTestId(existingDraftTabId!).click(); + const restoredDraftComposer = page + .getByRole("textbox", { name: "Message agent..." }) + .filter({ visible: true }); + await expect(restoredDraftComposer).toHaveValue("keep this draft"); + await expect(page.getByTestId("composer-file-attachment-pill")).toContainText(TEST_JSON.name); + + // Submit the handoff draft, not the one that was already open. + await page.getByTestId(handoffDraftTabId!).click(); + await expect(composer).toHaveValue(/Implement the following proposed plan\./); + const handoffPrompt = await composer.inputValue(); + await page.getByRole("button", { name: "Send message" }).filter({ visible: true }).click(); + await expect + .poll(async () => { + let count = 0; + for (const { agent } of (await session.client.fetchAgents({ scope: "active" })).entries) { + if (agent.workspaceId === session.workspaceId) count += 1; + } + return count; + }) + .toBe(2); + const destination = (await session.client.fetchAgents({ scope: "active" })).entries.find( + ({ agent }) => agent.workspaceId === session.workspaceId && agent.id !== session.agentId, + )?.agent; + expect(destination).toBeDefined(); + // The created agent runs on the provider the source agent used, account included. + expect(destination!.provider).toBe(sourceAgent!.provider); + expect(destination!.model).toBe(sourceAgent!.model); + expect(destination!.thinkingOptionId).toBe(sourceAgent!.thinkingOptionId); + const timelineClient = session.client as typeof session.client & { + fetchAgentTimeline(agentId: string): Promise<{ + entries: Array<{ item: { type: string; text?: string } }>; + }>; + }; + await expect + .poll(async () => { + let count = 0; + for (const { item } of (await timelineClient.fetchAgentTimeline(destination!.id)) + .entries) { + if (item.type === "user_message" && item.text === handoffPrompt) count += 1; + } + return count; + }) + .toBe(1); } finally { await session.cleanup(); } diff --git a/packages/app/e2e/browser/project-pull-requests.spec.ts b/packages/app/e2e/browser/project-pull-requests.spec.ts new file mode 100644 index 00000000000..99dfb232719 --- /dev/null +++ b/packages/app/e2e/browser/project-pull-requests.spec.ts @@ -0,0 +1,138 @@ +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { test, expect } from "../support/fixtures"; +import { gotoAppShell } from "../support/helpers/app"; +import { createLocalGithubPrFixture } from "../support/helpers/github-fixtures"; +import { + connectNewWorkspaceDaemonClient, + openProjectViaDaemon, + expectStartingRefPickerTriggerPr, +} from "../support/helpers/new-workspace"; +import { projectEquivalenceViewKey } from "../support/helpers/project-view-key"; +import { waitForSidebarHydration } from "../support/helpers/workspace-ui"; + +test("project PR shortcut opens a fullscreen list and hands the selected PR to workspace setup", async ({ + page, +}, testInfo) => { + const fixture = await createLocalGithubPrFixture(); + const checkRun = (name: string, conclusion: string) => ({ + __typename: "CheckRun", + name, + status: "COMPLETED", + conclusion, + detailsUrl: `https://github.com/paseo-e2e/local-fixture/actions/runs/${name}`, + }); + await writeFile( + path.join(fixture.mainCheckout.path, ".paseo-e2e-pull-requests.json"), + JSON.stringify( + Array.from({ length: 20 }, (_, index) => ({ + number: index + 1, + title: index === 0 ? fixture.pr.title : `Pull request ${index + 1}`, + url: fixture.pr.url, + state: "OPEN", + body: null, + labels: [], + baseRefName: "main", + headRefName: fixture.pr.branch, + updatedAt: "2026-01-01T00:00:00Z", + additions: index === 0 ? 123 : 0, + deletions: index === 0 ? 4 : 7, + statusCheckRollup: + index === 0 + ? [checkRun("build", "SUCCESS"), checkRun("test", "SUCCESS")] + : [checkRun("lint", "FAILURE"), checkRun("integration", "FAILURE")], + })), + ), + ); + const client = await connectNewWorkspaceDaemonClient(); + const project = await openProjectViaDaemon(client, fixture.mainCheckout.path); + try { + await gotoAppShell(page); + await waitForSidebarHydration(page); + const shortcut = page.getByTestId(`sidebar-project-pull-requests-${project.projectId}`); + await page + .getByTestId(`sidebar-project-row-${projectEquivalenceViewKey(project.projectKey)}`) + .hover(); + await shortcut.click(); + await expect(page.getByTestId("project-pr-1")).toContainText(fixture.pr.title); + await expect(page.getByTestId("project-pr-20")).toBeVisible(); + await expect( + page.getByTestId("project-pr-checks-1").getByTestId("project-pr-check-passed"), + ).toHaveCount(1); + const failed = page.getByTestId("project-pr-checks-2"); + await expect(failed.getByTestId("project-pr-check-failure")).toHaveCount(2); + await failed.getByRole("button", { name: "lint", exact: true }).hover(); + await expect(page.getByTestId("project-pr-check-tooltip")).toContainText("lint"); + await page + .context() + .route("https://github.com/**", (route) => route.fulfill({ body: "CI details" })); + const popupPromise = page.waitForEvent("popup"); + await failed.getByRole("button", { name: "lint", exact: true }).click(); + const popup = await popupPromise; + await expect(popup).toHaveURL("https://github.com/paseo-e2e/local-fixture/actions/runs/lint"); + await popup.close(); + await expect(page.getByTestId("project-pr-close")).toBeVisible(); + const list = page.getByTestId("project-pr-scroll"); + await list.hover(); + await page.mouse.wheel(0, 10000); + await expect.poll(() => list.evaluate((element) => element.scrollTop)).toBeGreaterThan(0); + await expect(page.getByTestId("project-pr-20")).toBeInViewport(); + await expect(page.getByTestId("project-pr-search")).toBeInViewport(); + await page.mouse.wheel(0, -10000); + await expect(page.getByTestId("project-pr-1")).toBeInViewport(); + await page.mouse.move(600, 20); + await page.screenshot({ path: testInfo.outputPath("pull-requests-desktop.png") }); + await page.keyboard.press("Escape"); + await expect(page.getByTestId("project-pr-close")).toBeHidden(); + await page + .getByTestId(`sidebar-project-row-${projectEquivalenceViewKey(project.projectKey)}`) + .hover(); + await shortcut.click(); + await page.getByTestId("project-pr-1").click(); + await expectStartingRefPickerTriggerPr(page, { + number: fixture.pr.number, + title: fixture.pr.title, + headRef: fixture.pr.branch, + }); + // Precondition only: a seeded selection has to be in the route for history to replay it. + // Back/Forward restoration itself is proven in the navigation history suites. + await expect(page).toHaveURL(/changeRequest=/); + await expect(page.getByTestId("project-pr-close")).toBeHidden(); + await expect(page.getByTestId("workspace-create-isolation-trigger")).toContainText( + "New worktree", + ); + } finally { + await client.removeProject(project.projectId); + await client.close(); + await fixture.cleanup(); + } +}); + +test.describe("compact project PR browser", () => { + test.use({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }); + + test("opens a project PR and seeds workspace setup", async ({ page }, testInfo) => { + const fixture = await createLocalGithubPrFixture(); + const client = await connectNewWorkspaceDaemonClient(); + const project = await openProjectViaDaemon(client, fixture.mainCheckout.path); + try { + await gotoAppShell(page); + await page.getByRole("button", { name: "Open menu", exact: true }).click(); + await waitForSidebarHydration(page); + await page.getByTestId(`sidebar-project-pull-requests-${project.projectId}`).click(); + await expect(page.getByTestId("project-pr-overlay")).toBeVisible(); + await expect(page.getByTestId("project-pr-1")).toContainText(fixture.pr.title); + await page.screenshot({ path: testInfo.outputPath("pull-requests-compact.png") }); + await page.getByTestId("project-pr-1").click(); + await expectStartingRefPickerTriggerPr(page, { + number: fixture.pr.number, + title: fixture.pr.title, + headRef: fixture.pr.branch, + }); + } finally { + await client.removeProject(project.projectId); + await client.close(); + await fixture.cleanup(); + } + }); +}); diff --git a/packages/app/e2e/browser/provider-account-create.spec.ts b/packages/app/e2e/browser/provider-account-create.spec.ts new file mode 100644 index 00000000000..2485d538e0d --- /dev/null +++ b/packages/app/e2e/browser/provider-account-create.spec.ts @@ -0,0 +1,143 @@ +import { expect, test } from "../support/fixtures"; +import { gotoAppShell, openSettings } from "../support/helpers/app"; +import { connectDaemonClient } from "../support/helpers/daemon-client-loader"; +import { getServerId } from "../support/helpers/server-id"; +import { + expectProviderInstalledInSettings, + fillProviderAccountForm, + openProviderAccountEditForm, + openProviderAccountForm, + openSettingsHost, + openSettingsHostSection, + submitProviderAccountForm, +} from "../support/helpers/settings"; + +const BASE_PROVIDER_ID = "claude"; +const ACCOUNT = { + id: "claude-work", + label: "Claude (Work)", +} as const; +const EDITED_ACCOUNT = { + id: "claude-company", + label: "Claude (Company)", +} as const; + +interface ProviderAccountDaemonClient { + connect(): Promise; + close(): Promise; + patchDaemonConfig(config: { + removeProviders?: string[]; + replaceProviders?: Record; + }): Promise; + getDaemonConfig(): Promise<{ + config: { + providers?: Record< + string, + { extends?: string; label?: string; description?: string; env?: Record } + >; + }; + }>; +} + +test.describe("provider accounts", () => { + test("creates and edits a second account for a builtin provider", async ({ page }) => { + test.setTimeout(120_000); + const client = await connectDaemonClient({ + clientIdPrefix: "provider-account-e2e", + }); + + try { + await client.patchDaemonConfig({ removeProviders: [ACCOUNT.id] }).catch(() => undefined); + await client + .patchDaemonConfig({ removeProviders: [EDITED_ACCOUNT.id] }) + .catch(() => undefined); + + await gotoAppShell(page); + await openSettings(page); + await openSettingsHost(page, getServerId()); + await openSettingsHostSection(page, getServerId(), "providers"); + + await openProviderAccountForm(page, BASE_PROVIDER_ID); + + // The id is derived from the label until it is edited by hand. + await page.getByTestId("provider-account-label-input").fill(ACCOUNT.label); + await expect(page.getByTestId("provider-account-id-input")).toHaveValue(ACCOUNT.id); + + // A reserved id is rejected inline. + await page.getByTestId("provider-account-id-input").fill(BASE_PROVIDER_ID); + await expect(page.getByTestId("provider-account-id-error")).toBeVisible(); + await page.getByTestId("provider-account-id-input").fill(ACCOUNT.id); + await expect(page.getByTestId("provider-account-id-error")).toHaveCount(0); + + await fillProviderAccountForm(page, { + label: ACCOUNT.label, + providerId: ACCOUNT.id, + description: "Work account", + env: [{ key: "ANTHROPIC_API_KEY", value: "sk-e2e-test" }], + }); + await submitProviderAccountForm(page); + + await expect(page.getByTestId("provider-account-sheet")).toHaveCount(0); + await expectProviderInstalledInSettings(page, ACCOUNT.label); + + await expect + .poll(async () => { + const { config } = await client.getDaemonConfig(); + const entry = config.providers?.[ACCOUNT.id]; + if (!entry) return null; + return { + extends: entry.extends, + label: entry.label, + description: entry.description, + env: entry.env, + }; + }) + .toEqual({ + extends: BASE_PROVIDER_ID, + label: ACCOUNT.label, + description: "Work account", + env: { ANTHROPIC_API_KEY: "sk-e2e-test" }, + }); + + await openProviderAccountEditForm(page, ACCOUNT.id); + await expect(page.getByTestId("provider-account-label-input")).toHaveValue(ACCOUNT.label); + await expect(page.getByTestId("provider-account-id-input")).toHaveValue(ACCOUNT.id); + await expect(page.getByTestId("provider-account-description-input")).toHaveValue( + "Work account", + ); + await expect(page.getByTestId("provider-account-env-key-0")).toHaveValue("ANTHROPIC_API_KEY"); + + await fillProviderAccountForm(page, { + label: EDITED_ACCOUNT.label, + providerId: EDITED_ACCOUNT.id, + description: "", + env: [{ key: "CLAUDE_CONFIG_DIR", value: "/tmp/claude-company" }], + }); + await submitProviderAccountForm(page); + + await expect(page.getByTestId("provider-account-sheet")).toHaveCount(0); + await expectProviderInstalledInSettings(page, EDITED_ACCOUNT.label); + await expect + .poll(async () => { + const { config } = await client.getDaemonConfig(); + return { + old: config.providers?.[ACCOUNT.id] ?? null, + edited: config.providers?.[EDITED_ACCOUNT.id] ?? null, + }; + }) + .toEqual({ + old: null, + edited: { + extends: BASE_PROVIDER_ID, + label: EDITED_ACCOUNT.label, + env: { CLAUDE_CONFIG_DIR: "/tmp/claude-company" }, + }, + }); + } finally { + await client + .patchDaemonConfig({ removeProviders: [ACCOUNT.id, EDITED_ACCOUNT.id] }) + .catch(() => undefined); + await client.close().catch(() => undefined); + } + }); +}); diff --git a/packages/app/e2e/browser/provider-removal.spec.ts b/packages/app/e2e/browser/provider-removal.spec.ts index b72fb868d65..a70c4035da7 100644 --- a/packages/app/e2e/browser/provider-removal.spec.ts +++ b/packages/app/e2e/browser/provider-removal.spec.ts @@ -84,7 +84,14 @@ test.describe("provider removal", () => { await openSettingsHost(page, getServerId()); await openSettingsHostSection(page, getServerId(), "providers"); - await expect(page.getByTestId("provider-actions-claude")).toHaveCount(0); + // Builtin providers get an actions menu for adding accounts, but they can + // never be removed. + await page.getByTestId("provider-actions-claude").click(); + await expect(page.getByTestId("provider-add-account-claude")).toBeVisible(); + await expect(page.getByTestId("provider-remove-claude")).toHaveCount(0); + await page.keyboard.press("Escape"); + await expect(page.getByTestId("provider-add-account-claude")).toHaveCount(0); + await openAddProviderArea(page); await installAcpCatalogProvider(page, CUSTOM_PROVIDER.name); await expectProviderInstalledInSettings(page, CUSTOM_PROVIDER.name); diff --git a/packages/app/e2e/browser/viewed-agent-timelines.spec.ts b/packages/app/e2e/browser/viewed-agent-timelines.spec.ts index 934a48d264f..93e40420fc8 100644 --- a/packages/app/e2e/browser/viewed-agent-timelines.spec.ts +++ b/packages/app/e2e/browser/viewed-agent-timelines.spec.ts @@ -199,7 +199,7 @@ async function startVisibleTurn( prompt: string, ): Promise { await scenario.client.sendAgentMessage(scenario.firstAgentId, prompt); - await expect(page.getByText(prompt, { exact: true })).toBeVisible(); + await expect(page.getByTestId("user-message").getByText(prompt, { exact: true })).toBeVisible(); await expectInlineWorkingIndicator(page); } @@ -250,7 +250,7 @@ async function openSevenChats(page: Page, scenario: ViewedTimelineScenario) { } async function expectCurrentChatWithoutCatchUp(page: Page, message: string) { - await expect(page.getByText(message, { exact: true })).toBeVisible(); + await expect(page.getByTestId("user-message").getByText(message, { exact: true })).toBeVisible(); await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0); } @@ -340,12 +340,16 @@ test.describe("Viewed agent timelines", () => { "Committed while the first chat is hidden.", ); await expect( - page.getByText("Committed while the first chat is hidden.", { exact: true }), + page + .getByTestId("user-message") + .getByText("Committed while the first chat is hidden.", { exact: true }), ).toHaveCount(0); expect(await countChatCommits(page, scenario.firstAgentId)).toBe(hiddenCommits); await selectAgent(page, "First viewed chat"); await expect( - page.getByText("Committed while the first chat is hidden.", { exact: true }), + page + .getByTestId("user-message") + .getByText("Committed while the first chat is hidden.", { exact: true }), ).toBeVisible(); await expect(page.getByText("(end of synthetic stream)", { exact: true })).toBeVisible(); await expect(composer).toHaveValue("Unsent draft survives hidden streaming"); @@ -374,7 +378,9 @@ test.describe("Viewed agent timelines", () => { ).toBeVisible(); await expect(page.getByRole("textbox", { name: "Message agent..." })).toHaveCount(2); await commitMessage(scenario, scenario.firstAgentId, "First visible pane update."); - await expect(page.getByText("First visible pane update.", { exact: true })).toBeVisible(); + await expect( + page.getByTestId("user-message").getByText("First visible pane update.", { exact: true }), + ).toBeVisible(); await expect( page.getByRole("button", { name: "Second viewed chat", exact: true }), ).toBeVisible(); @@ -391,9 +397,11 @@ test.describe("Viewed agent timelines", () => { try { await commitMessage(scenario, scenario.firstAgentId, "Visible before the connection drops."); await openAgent(page, scenario, scenario.firstAgentId); - const previousMessage = page.getByText("Visible before the connection drops.", { - exact: true, - }); + const previousMessage = page + .getByTestId("user-message") + .getByText("Visible before the connection drops.", { + exact: true, + }); await expect(previousMessage).toBeVisible(); await expect(page.getByRole("button", { name: "First viewed chat" })).toHaveAttribute( "aria-selected", @@ -425,9 +433,11 @@ test.describe("Viewed agent timelines", () => { await page.screenshot({ path: testInfo.outputPath("updating-chat.png") }); gate.releaseHeldTimelineResponses(); await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0); - const recoveredMessage = page.getByText("Committed while the chat reconnects.", { - exact: true, - }); + const recoveredMessage = page + .getByTestId("user-message") + .getByText("Committed while the chat reconnects.", { + exact: true, + }); await expect(recoveredMessage).toHaveCount(1); await expect(recoveredMessage).toBeVisible(); } finally { diff --git a/packages/app/e2e/browser/workspace-package-scripts.spec.ts b/packages/app/e2e/browser/workspace-package-scripts.spec.ts new file mode 100644 index 00000000000..a777b286ee1 --- /dev/null +++ b/packages/app/e2e/browser/workspace-package-scripts.spec.ts @@ -0,0 +1,216 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { test, expect, type Page } from "../support/fixtures"; +import { createTempGitRepo } from "../support/helpers/workspace"; +import { + connectWorkspaceSetupClient, + openWorkspaceScriptsMenu, +} from "../support/helpers/workspace-setup"; +import { getServerId } from "../support/helpers/server-id"; +import { buildHostWorkspaceRoute } from "../../src/utils/host-routes"; + +test("nested package scripts run, appear in the sidebar, and expose their result", async ({ + page, +}, testInfo) => { + const client = await connectWorkspaceSetupClient(); + const manifest = JSON.stringify({ + scripts: { + build: + "node -e \"setInterval(() => { if(require('fs').existsSync('finish')) process.exit(0) }, 50)\"", + }, + }); + const repo = await createTempGitRepo("package-scripts-", { + files: [ + { path: "package.json", content: JSON.stringify({ scripts: { build: "echo root" } }) }, + { path: "packages/web/package.json", content: manifest }, + ], + }); + try { + const created = await client.createWorkspace({ + source: { kind: "directory", path: repo.path }, + }); + expect(created.error).toBeFalsy(); + const workspaceId = created.workspace!.id; + await page.goto(buildHostWorkspaceRoute(getServerId(), workspaceId)); + await openWorkspaceScriptsMenu(page); + const nestedGroup = page.getByTestId("workspace-scripts-group-packages/web/package.json"); + await expect(nestedGroup).toBeVisible(); + const scriptId = "package.json:packages%2Fweb%2Fpackage.json:build"; + const row = page.getByTestId(`workspace-scripts-item-${scriptId}`); + await expect(row).not.toBeVisible(); + await nestedGroup.click(); + await expect(row).toContainText("build"); + await page.getByTestId(`workspace-scripts-start-${scriptId}`).click(); + await expect( + page.getByLabel("Script packages/web/build running", { exact: true }).first(), + ).toBeVisible(); + await page.screenshot({ path: testInfo.outputPath("running-package-script.png") }); + await page.keyboard.press("Escape"); + await writeFile(join(repo.path, "packages/web/finish"), "done"); + await expect + .poll(async () => { + const result = await client.listWorkspaceScripts(workspaceId); + return result.scripts?.find((script) => script.scriptName === scriptId)?.exitCode; + }) + .toBe(0); + await openWorkspaceScriptsMenu(page); + await nestedGroup.click(); + await expect(row).toContainText("exit 0"); + await expect(page.getByLabel("Script packages/web/build running", { exact: true })).toHaveCount( + 0, + ); + await page.screenshot({ path: testInfo.outputPath("completed-package-script.png") }); + + await page.keyboard.press("Escape"); + await writeFile(join(repo.path, "packages/web/package.json"), "{"); + await openWorkspaceScriptsMenu(page); + await expect( + page.getByTestId("workspace-scripts-item-package.json:package.json:build"), + ).toBeVisible(); + await expect(page.getByRole("menuitem", { name: /Retry/ })).not.toBeVisible(); + await page.keyboard.press("Escape"); + await writeFile(join(repo.path, "packages/web/package.json"), manifest); + await openWorkspaceScriptsMenu(page); + await nestedGroup.click(); + await expect(row).toBeVisible(); + } finally { + await client.close(); + await repo.cleanup(); + } +}); + +test("long script lists stay bounded, scroll, and filter by name", async ({ page }, testInfo) => { + const client = await connectWorkspaceSetupClient(); + const scripts = Object.fromEntries( + Array.from({ length: 80 }, (_, index) => [ + `task-${String(index).padStart(2, "0")}`, + "echo done", + ]), + ); + const repo = await createTempGitRepo("script-search-", { + files: [{ path: "package.json", content: JSON.stringify({ scripts }) }], + }); + try { + const created = await client.createWorkspace({ + source: { kind: "directory", path: repo.path }, + }); + expect(created.error).toBeFalsy(); + await page.goto(buildHostWorkspaceRoute(getServerId(), created.workspace!.id)); + await openWorkspaceScriptsMenu(page); + const menu = page.getByTestId("workspace-scripts-menu"); + const lastRow = page.getByTestId("workspace-scripts-item-package.json:package.json:task-79"); + await expect(lastRow).toBeAttached(); + const bounds = await menu.boundingBox(); + expect(bounds!.height).toBeLessThanOrEqual(422); + await lastRow.scrollIntoViewIfNeeded(); + await expect(lastRow).toBeInViewport(); + expect((await menu.boundingBox())!.height).toBeLessThanOrEqual(422); + const search = page.getByTestId("workspace-scripts-search"); + await search.scrollIntoViewIfNeeded(); + await search.fill("TASK-79"); + await expect(menu.locator('[data-testid^="workspace-scripts-item-"]')).toHaveCount(1); + await expect(lastRow).toBeInViewport(); + await page.screenshot({ path: testInfo.outputPath("searched-scripts.png") }); + await search.fill("no-matches"); + await expect(menu).toContainText("No matching scripts"); + await search.fill(""); + await expect(menu.locator('[data-testid^="workspace-scripts-item-"]')).toHaveCount(80); + await page.screenshot({ path: testInfo.outputPath("scrollable-scripts.png") }); + await page.keyboard.press("Escape"); + } finally { + await client.close(); + await repo.cleanup(); + } +}); + +test("discovers and runs a nested package script from the compact sheet", async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + const client = await connectWorkspaceSetupClient(); + const repo = await createTempGitRepo("package-scripts-compact-", { + files: [ + { path: "package.json", content: JSON.stringify({ scripts: { build: "echo root" } }) }, + { + path: "packages/web/package.json", + content: JSON.stringify({ + scripts: { + dev: 'node -e "setInterval(() => {}, 100000)"', + }, + }), + }, + ], + }); + try { + const created = await client.createWorkspace({ + source: { kind: "directory", path: repo.path }, + }); + expect(created.error).toBeFalsy(); + const workspaceId = created.workspace!.id; + await page.goto(buildHostWorkspaceRoute(getServerId(), workspaceId)); + + await runDiscoveredScriptFromCompactHeader(page); + } finally { + await client.close(); + await repo.cleanup(); + } +}); + +test("keeps compact script discovery working after a desktop to compact resize", async ({ + page, +}) => { + const client = await connectWorkspaceSetupClient(); + const repo = await createTempGitRepo("package-scripts-resize-", { + files: [ + { path: "package.json", content: JSON.stringify({ scripts: { build: "echo root" } }) }, + { + path: "packages/web/package.json", + content: JSON.stringify({ + scripts: { + dev: 'node -e "setInterval(() => {}, 100000)"', + }, + }), + }, + ], + }); + try { + const created = await client.createWorkspace({ + source: { kind: "directory", path: repo.path }, + }); + expect(created.error).toBeFalsy(); + const workspaceId = created.workspace!.id; + // Desktop first, then the same mounted app narrows to the compact layout. + await page.goto(buildHostWorkspaceRoute(getServerId(), workspaceId)); + await expect(page.getByTestId("workspace-scripts-button")).toBeVisible({ timeout: 30_000 }); + await page.setViewportSize({ width: 390, height: 844 }); + await expect(page.getByTestId("workspace-header-menu-trigger")).toBeVisible({ + timeout: 30_000, + }); + + await runDiscoveredScriptFromCompactHeader(page); + } finally { + await client.close(); + await repo.cleanup(); + } +}); + +/** Compact puts scripts on a page of the header menu; discovery still runs on demand. */ +async function runDiscoveredScriptFromCompactHeader(page: Page): Promise { + await page.getByTestId("workspace-header-menu-trigger").click(); + // Compact menu surfaces are sheets, so the content carries the -content test id. + const menu = page.getByTestId("workspace-header-menu-content"); + await expect(menu).toBeVisible({ timeout: 10_000 }); + await page.getByTestId("workspace-header-scripts").click(); + const scriptId = "package.json:packages%2Fweb%2Fpackage.json:dev"; + const row = page.getByTestId(`workspace-scripts-row-${scriptId}`); + await expect(row).toContainText("dev", { timeout: 15_000 }); + await row.click(); + // Starting the script closes the sheet and opens its own terminal. + await expect(menu).not.toBeVisible({ timeout: 20_000 }); + await expect(page.getByTestId("terminal-surface").first()).toBeVisible({ timeout: 30_000 }); + // The selected script is the one running: reopening the menu reports its row as running. + await page.getByTestId("workspace-header-menu-trigger").click(); + await expect(menu).toBeVisible({ timeout: 10_000 }); + await page.getByTestId("workspace-header-scripts").click(); + await expect(page.getByTestId(`workspace-scripts-row-${scriptId}`)).toContainText("Running", { + timeout: 15_000, + }); +} diff --git a/packages/app/e2e/support/helpers/branch-switcher.ts b/packages/app/e2e/support/helpers/branch-switcher.ts index fa43ce33b28..4e58da2b1b1 100644 --- a/packages/app/e2e/support/helpers/branch-switcher.ts +++ b/packages/app/e2e/support/helpers/branch-switcher.ts @@ -51,9 +51,10 @@ export async function switchBranchFromChangesPanel( await expect(picker).not.toBeVisible({ timeout: 30_000 }); } -// The workspace header title is a plain static title in Model B; the branch -// switcher must never appear there. Asserting on the header testID keeps this -// honest even as the switcher continues to exist inside the Changes panel. -export async function expectNoBranchSwitcherInWorkspaceHeader(page: Page): Promise { - await expect(page.getByTestId("workspace-header-branch-switcher")).toHaveCount(0); +// The header title stays the workspace's own name; the real branch shows beside it in the +// ` → ` pair and follows checkouts made elsewhere, such as from the Changes panel. +export async function expectWorkspaceHeaderBranch(page: Page, branchName: string): Promise { + await expect( + page.getByTestId("workspace-header-current-branch").filter({ visible: true }).first(), + ).toContainText(branchName, { timeout: 30_000 }); } diff --git a/packages/app/e2e/support/helpers/daemon-websocket-gate.ts b/packages/app/e2e/support/helpers/daemon-websocket-gate.ts index c33976879f1..8721fd968e8 100644 --- a/packages/app/e2e/support/helpers/daemon-websocket-gate.ts +++ b/packages/app/e2e/support/helpers/daemon-websocket-gate.ts @@ -109,15 +109,22 @@ function stripCanonicalSubmittedPrompts( message: string | Buffer, enabled: boolean, messageType: unknown, + additionalFeatures: readonly string[] = [], ): string | Buffer { - if (!enabled || messageType !== "status" || typeof message !== "string") return message; + if ( + (!enabled && additionalFeatures.length === 0) || + 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; - delete payload.features.canonicalSubmittedPrompts; + if (enabled) delete payload.features.canonicalSubmittedPrompts; + for (const feature of additionalFeatures) delete payload.features[feature]; return JSON.stringify(envelope); } @@ -302,6 +309,7 @@ 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; @@ -330,6 +338,14 @@ 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>(); @@ -519,6 +535,7 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n outboundMessage, stripCanonicalSubmittedPromptsFeature, serverMessage?.type, + strippedServerFeatures, ); const isTimelineResponse = serverMessage?.type === "fetch_agent_timeline_response"; if (isTimelineResponse) { @@ -544,6 +561,7 @@ 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); } @@ -851,6 +869,15 @@ 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/e2e-worker.ts b/packages/app/e2e/support/helpers/e2e-worker.ts index 1f1cf783a24..4e4f3982d55 100644 --- a/packages/app/e2e/support/helpers/e2e-worker.ts +++ b/packages/app/e2e/support/helpers/e2e-worker.ts @@ -83,6 +83,10 @@ if (origin === fixtureRemote) { process.stdout.write("[]"); process.exit(0); } + if (command === "pr list" && require("fs").existsSync(".paseo-e2e-pull-requests.json")) { + process.stdout.write(require("fs").readFileSync(".paseo-e2e-pull-requests.json", "utf8")); + process.exit(0); + } if (command === "pr list" || command === "pr view") { const isFork = args.includes("2"); const pr = { diff --git a/packages/app/e2e/support/helpers/plugin-buttons.ts b/packages/app/e2e/support/helpers/plugin-buttons.ts index b28050fd009..6bebca21b79 100644 --- a/packages/app/e2e/support/helpers/plugin-buttons.ts +++ b/packages/app/e2e/support/helpers/plugin-buttons.ts @@ -579,6 +579,7 @@ export async function withButtonShowcase( test.step("compact workspace menu carries header buttons with their actions, menus, and content", async () => { await openCompactWorkspaceMenu(page); await expectWorkspaceMenuRows(page, [ + "Scripts", "Deploy application", "Header checks", "Header status", diff --git a/packages/app/e2e/support/helpers/seed-client.ts b/packages/app/e2e/support/helpers/seed-client.ts index 41e676473f4..15e67117d74 100644 --- a/packages/app/e2e/support/helpers/seed-client.ts +++ b/packages/app/e2e/support/helpers/seed-client.ts @@ -1,6 +1,7 @@ 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"; @@ -32,6 +33,8 @@ 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<{ @@ -129,6 +132,7 @@ export interface SeedDaemonClient { workspaceId?: string; model: string | null; currentModeId: string | null; + thinkingOptionId?: string | null; status: string; title?: string | null; }; diff --git a/packages/app/e2e/support/helpers/settings.ts b/packages/app/e2e/support/helpers/settings.ts index 796d0b45f5a..7062fed154c 100644 --- a/packages/app/e2e/support/helpers/settings.ts +++ b/packages/app/e2e/support/helpers/settings.ts @@ -495,6 +495,50 @@ export async function installAcpCatalogProvider(page: Page, providerName: string await page.getByRole("button", { name: `Add ${providerName}`, exact: true }).click(); } +export interface ProviderAccountFormInput { + label: string; + providerId?: string; + description?: string; + env?: { key: string; value: string }[]; +} + +export async function openProviderAccountForm(page: Page, providerId: string): Promise { + await page.getByTestId(`provider-actions-${providerId}`).click(); + await page.getByTestId(`provider-add-account-${providerId}`).click(); + await expect(page.getByTestId("provider-account-sheet")).toBeVisible(); +} + +export async function openProviderAccountEditForm(page: Page, providerId: string): Promise { + await page.getByTestId(`provider-actions-${providerId}`).click(); + await page.getByTestId(`provider-edit-account-${providerId}`).click(); + await expect(page.getByTestId("provider-account-sheet")).toBeVisible(); +} + +export async function fillProviderAccountForm( + page: Page, + input: ProviderAccountFormInput, +): Promise { + await page.getByTestId("provider-account-label-input").fill(input.label); + if (input.providerId !== undefined) { + await page.getByTestId("provider-account-id-input").fill(input.providerId); + } + if (input.description !== undefined) { + await page.getByTestId("provider-account-description-input").fill(input.description); + } + const env = input.env ?? []; + for (const [index, variable] of env.entries()) { + if (index > 0) { + await page.getByTestId("provider-account-env-add").click(); + } + await page.getByTestId(`provider-account-env-key-${index}`).fill(variable.key); + await page.getByTestId(`provider-account-env-value-${index}`).fill(variable.value); + } +} + +export async function submitProviderAccountForm(page: Page): Promise { + await page.getByTestId("provider-account-submit").click(); +} + export async function expectProviderInstalledInSettings( page: Page, providerName: string, diff --git a/packages/app/e2e/support/helpers/workspace-setup.ts b/packages/app/e2e/support/helpers/workspace-setup.ts index a89f52c70a6..4b6354a8e6a 100644 --- a/packages/app/e2e/support/helpers/workspace-setup.ts +++ b/packages/app/e2e/support/helpers/workspace-setup.ts @@ -23,6 +23,7 @@ type WorkspaceSetupDaemonClient = Pick< | "fetchWorkspaces" | "listTerminals" | "observeEvents" + | "listWorkspaceScripts" | "removeProject" | "subscribeRawMessages" >; diff --git a/packages/app/e2e/support/helpers/workspace-ui.ts b/packages/app/e2e/support/helpers/workspace-ui.ts index 3e8aa0401c4..3e1f799a7e7 100644 --- a/packages/app/e2e/support/helpers/workspace-ui.ts +++ b/packages/app/e2e/support/helpers/workspace-ui.ts @@ -76,19 +76,38 @@ export async function waitForWorkspaceInSidebar( }); } +// Beside the title, a wide git checkout shows ` → ` instead of the project name +// (`WorkspaceHeaderProjectRow`), so `subtitle` is satisfied by either the project name or the +// branch pair being there. Pass `branch` to pin the current branch shown in that pair. export async function expectWorkspaceHeader( page: Page, - input: { title: string; subtitle: string }, + input: { title: string; subtitle?: string; branch?: string }, ): Promise { const titleLocator = page.getByTestId("workspace-header-title").filter({ visible: true }); - const subtitleLocator = page.getByTestId("workspace-header-subtitle").filter({ visible: true }); await expect(titleLocator.first()).toHaveText(input.title, { timeout: 30_000, }); - await expect(subtitleLocator.first()).toHaveText(input.subtitle, { - timeout: 30_000, - }); + if (input.subtitle !== undefined) { + const subtitleLocator = page.getByTestId("workspace-header-subtitle").filter({ visible: true }); + const branchesLocator = page.getByTestId("workspace-header-branches").filter({ visible: true }); + await expect(subtitleLocator.first().or(branchesLocator.first())).toBeVisible({ + timeout: 30_000, + }); + if ((await subtitleLocator.count()) > 0) { + await expect(subtitleLocator.first()).toHaveText(input.subtitle, { + timeout: 30_000, + }); + } + } + if (input.branch !== undefined) { + const branchLocator = page + .getByTestId("workspace-header-current-branch") + .filter({ visible: true }); + await expect(branchLocator.first()).toContainText(input.branch, { + timeout: 30_000, + }); + } } export async function setTabVisibility( diff --git a/packages/app/package.json b/packages/app/package.json index 62f1f65ba4d..c24f575f8fc 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -18,6 +18,7 @@ "web": "npm --prefix ../.. run build:client && concurrently --kill-others --names protocol,client,expo --prefix-colors yellow,blue,magenta \"npm --prefix ../.. run watch:protocol\" \"npm --prefix ../.. run watch:client\" \"npm run web:expo\"", "web:expo": "expo start --web", "lint": "expo lint", + "pretypecheck": "npm run build --workspace=@getpaseo/expo-two-way-audio", "typecheck": "tsgo --noEmit", "test": "vitest run", "test:browser": "vitest run --project browser", diff --git a/packages/app/scripts/generate-voice-failure-phrases.mjs b/packages/app/scripts/generate-voice-failure-phrases.mjs new file mode 100644 index 00000000000..dba28c9705d --- /dev/null +++ b/packages/app/scripts/generate-voice-failure-phrases.mjs @@ -0,0 +1,132 @@ +#!/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 daa78baea28..a71d566dede 100644 --- a/packages/app/src/agent-stream/chat-find/index.tsx +++ b/packages/app/src/agent-stream/chat-find/index.tsx @@ -1,12 +1,170 @@ +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"; -export function ChatFind({ children }: ChatFindProps) { - return children; +/** + * 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 ChatFindExpansion({ children }: ChatFindExpansionProps) { - return children(false); + +/** 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)}; } -/** Native has no chat find, so no message is ever selected by one. */ -export function useChatFindSelectedMessageId(): string | null { - return null; + +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} + + ); } + +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 new file mode 100644 index 00000000000..13fc31138f5 --- /dev/null +++ b/packages/app/src/agent-stream/chat-find/matches.test.ts @@ -0,0 +1,22 @@ +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 new file mode 100644 index 00000000000..ce070d6771c --- /dev/null +++ b/packages/app/src/agent-stream/chat-find/matches.ts @@ -0,0 +1,23 @@ +/** + * 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 new file mode 100644 index 00000000000..685a7c89254 --- /dev/null +++ b/packages/app/src/agent-stream/chat-find/native-viewport.test.ts @@ -0,0 +1,66 @@ +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 new file mode 100644 index 00000000000..269fc7a9ba3 --- /dev/null +++ b/packages/app/src/agent-stream/chat-find/native-viewport.ts @@ -0,0 +1,84 @@ +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/chat-find/ranges.browser.test.ts b/packages/app/src/agent-stream/chat-find/ranges.browser.test.ts index 8af6f83f656..20e22634e81 100644 --- a/packages/app/src/agent-stream/chat-find/ranges.browser.test.ts +++ b/packages/app/src/agent-stream/chat-find/ranges.browser.test.ts @@ -122,3 +122,12 @@ it("keeps text around nested plugin blocks in separate occurrences", () => { expect(findRenderedMatches(row, "details").map((range) => range.toString())).toEqual(["details"]); expect(findRenderedMatches(row, "beta").map((range) => range.toString())).toEqual(["beta"]); }); + +it("finds wide-character text across inline formatting", () => { + const row = content( + '
통합 구현은 전체 테스트
', + ); + expect(findRenderedMatches(row, "구현은 전체").map((range) => range.toString())).toEqual([ + "구현은 전체", + ]); +}); diff --git a/packages/app/src/agent-stream/disclosure.browser.test.tsx b/packages/app/src/agent-stream/disclosure.browser.test.tsx index 020e5d8e947..eeb94b1ce0e 100644 --- a/packages/app/src/agent-stream/disclosure.browser.test.tsx +++ b/packages/app/src/agent-stream/disclosure.browser.test.tsx @@ -10,6 +10,7 @@ import { PlanCard } from "@/components/plan-card"; import { MessagePreview } from "@/components/user-message"; import { createUserMessageExpansion } from "@/components/user-message/expansion"; import { UserMessageExpansionContext } from "@/components/user-message/expansion-context"; +import { ToastApiProvider } from "@/contexts/toast-context"; import { DisclosureRow } from "./disclosure"; import type { DisclosureTriggerEdge, StreamViewportHandle } from "./strategy"; @@ -48,6 +49,17 @@ interface Hold { * A timeline row whose viewport records each hold. Like the strategies, it runs `apply` itself, so * a toggle that skips the hold still changes state but leaves no record. */ +const toastApi = { show: () => () => {}, copied: () => {}, error: () => {} }; + +// Plan cards copy through the toast context, which the real app shell always provides. +function withProviders(node: ReactNode) { + return ( + + {node} + + ); +} + function mountRow(rowId: string, isApplied: () => boolean, children: ReactNode) { const holds: Hold[] = []; const viewport: StreamViewportHandle = { @@ -62,11 +74,11 @@ function mountRow(rowId: string, isApplied: () => boolean, children: ReactNode) viewportRef.current = viewport; act(() => root.render( - + withProviders( {children} - - , + , + ), ), ); return holds; @@ -126,11 +138,7 @@ describe("timeline disclosures hold their row", () => { it("toggles a plan card outside a timeline row, as the pending permission card renders", () => { act(() => - root.render( - - - , - ), + root.render(withProviders()), ); const header = () => view().getByRole("button", { name: "Plan" }); const isExpanded = () => header().getAttribute("aria-expanded") === "true"; diff --git a/packages/app/src/agent-stream/native-message-scroll.test.ts b/packages/app/src/agent-stream/native-message-scroll.test.ts new file mode 100644 index 00000000000..832d4fca06c --- /dev/null +++ b/packages/app/src/agent-stream/native-message-scroll.test.ts @@ -0,0 +1,93 @@ +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 new file mode 100644 index 00000000000..4e2a14a4b31 --- /dev/null +++ b/packages/app/src/agent-stream/native-message-scroll.ts @@ -0,0 +1,32 @@ +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/pinned-prompt/model.test.ts b/packages/app/src/agent-stream/pinned-prompt/model.test.ts new file mode 100644 index 00000000000..99198440d2a --- /dev/null +++ b/packages/app/src/agent-stream/pinned-prompt/model.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from "vitest"; +import type { StreamItem } from "@/types/stream"; +import { resolvePinnedPrompt } from "./model"; + +function userMessage(id: string, text: string): StreamItem { + return { kind: "user_message", id, text, timestamp: new Date(0) }; +} + +function assistantMessage(id: string): StreamItem { + return { kind: "assistant_message", id, text: `reply ${id}`, timestamp: new Date(0) }; +} + +const items: StreamItem[] = [ + userMessage("p1", "first prompt"), + assistantMessage("a1"), + assistantMessage("a2"), + userMessage("p2", "second prompt"), + assistantMessage("a3"), +]; + +describe("resolvePinnedPrompt", () => { + it("pins the prompt that started the turn the reader is inside", () => { + expect(resolvePinnedPrompt({ items, readingRowId: "a1" })).toEqual({ + id: "p1", + text: "first prompt", + }); + expect(resolvePinnedPrompt({ items, readingRowId: "a2" })).toEqual({ + id: "p1", + text: "first prompt", + }); + expect(resolvePinnedPrompt({ items, readingRowId: "a3" })).toEqual({ + id: "p2", + text: "second prompt", + }); + }); + + it("pins nothing while the prompt's own bubble is the reading row", () => { + expect(resolvePinnedPrompt({ items, readingRowId: "p1" })).toBeNull(); + expect(resolvePinnedPrompt({ items, readingRowId: "p2" })).toBeNull(); + }); + + it("pins nothing without a reading row, or for a row outside the window", () => { + expect(resolvePinnedPrompt({ items, readingRowId: null })).toBeNull(); + expect(resolvePinnedPrompt({ items, readingRowId: "gone" })).toBeNull(); + expect(resolvePinnedPrompt({ items: [], readingRowId: "a1" })).toBeNull(); + }); + + it("pins nothing when the window opens mid-turn with no preceding prompt", () => { + const midTurn = [assistantMessage("a1"), assistantMessage("a2")]; + + expect(resolvePinnedPrompt({ items: midTurn, readingRowId: "a2" })).toBeNull(); + }); + + it("pins nothing for an attachment-only prompt that has no text", () => { + const imagesOnly = [userMessage("p1", " "), assistantMessage("a1")]; + + expect(resolvePinnedPrompt({ items: imagesOnly, readingRowId: "a1" })).toBeNull(); + }); + + it("pins a prompt in loaded history while the reader is in the live head", () => { + const history = [userMessage("p1", "first prompt"), assistantMessage("a1")]; + const liveHead = [assistantMessage("live-1")]; + + expect( + resolvePinnedPrompt({ items: [...history, ...liveHead], readingRowId: "live-1" }), + ).toEqual({ id: "p1", text: "first prompt" }); + }); +}); diff --git a/packages/app/src/agent-stream/pinned-prompt/model.ts b/packages/app/src/agent-stream/pinned-prompt/model.ts new file mode 100644 index 00000000000..0c76f18bd13 --- /dev/null +++ b/packages/app/src/agent-stream/pinned-prompt/model.ts @@ -0,0 +1,43 @@ +import type { StreamItem } from "@/types/stream"; + +export interface PinnedPromptResolution { + id: string; + text: string; +} + +/** + * The prompt that started the turn the reader is inside: the nearest preceding `user_message`. + * + * When that message is itself the reading row its own bubble is straddling the reading line and + * therefore on screen, so there is nothing to pin. That equality check is what makes the pinned + * header appear as the prompt slides out of view and disappear as it slides back in. + * + * `items` must be in the strategy's render order (history, then live head), which is the order the + * reading position is measured against. + */ +export function resolvePinnedPrompt(input: { + items: readonly StreamItem[]; + readingRowId: string | null; +}): PinnedPromptResolution | null { + const { items, readingRowId } = input; + if (readingRowId === null) { + return null; + } + const readingIndex = items.findIndex((item) => item.id === readingRowId); + if (readingIndex <= 0) { + return null; + } + for (let index = readingIndex; index >= 0; index -= 1) { + const item = items[index]; + if (item?.kind !== "user_message") { + continue; + } + if (index === readingIndex) { + return null; + } + // An attachment-only prompt has no text, and an empty pinned bubble is worse than no pin. + const text = item.text.trim(); + return text.length === 0 ? null : { id: item.id, text }; + } + return null; +} diff --git a/packages/app/src/agent-stream/pinned-prompt/pinned-prompt.tsx b/packages/app/src/agent-stream/pinned-prompt/pinned-prompt.tsx new file mode 100644 index 00000000000..7aa223d8e9c --- /dev/null +++ b/packages/app/src/agent-stream/pinned-prompt/pinned-prompt.tsx @@ -0,0 +1,14 @@ +import type { ReadingSignalSource } from "../reading-signal"; +import type { PinnedPromptResolution } from "./model"; + +export interface PinnedPromptProps { + pinnedId: ReadingSignalSource; + promptById: ReadonlyMap; + onJumpToPrompt: (itemId: string) => void; +} + +// Pinning needs the reading position, which only the web viewport measures. Native navigates the +// transcript by scrolling, so there is no header to render. +export function PinnedPrompt(_props: PinnedPromptProps): null { + return null; +} diff --git a/packages/app/src/agent-stream/pinned-prompt/pinned-prompt.web.tsx b/packages/app/src/agent-stream/pinned-prompt/pinned-prompt.web.tsx new file mode 100644 index 00000000000..9c40964fb65 --- /dev/null +++ b/packages/app/src/agent-stream/pinned-prompt/pinned-prompt.web.tsx @@ -0,0 +1,211 @@ +import { useCallback, useId, useState, useSyncExternalStore } from "react"; +import { useTranslation } from "react-i18next"; +import { + Pressable, + StyleSheet as RNStyleSheet, + Text, + View, + type LayoutChangeEvent, +} from "react-native"; +import Animated, { FadeIn, FadeOut, useReducedMotion } from "react-native-reanimated"; +import Svg, { Defs, LinearGradient as SvgLinearGradient, Rect, Stop } from "react-native-svg"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import type { Theme } from "@/styles/theme"; +import { PROMPT_JUMP_TOP_INSET_PX } from "../prompt-jump-settle"; +import type { PinnedPromptResolution } from "./model"; +import type { PinnedPromptProps } from "./pinned-prompt"; + +const PINNED_PROMPT_SCALE = 0.7; +const PINNED_PROMPT_MAX_LINES = 5; +const CONTENT_LINE_HEIGHT_RATIO = 1.4; + +// The animated shell is the rail's flex child, so the width cap has to live here: a `flexShrink` +// on the bubble inside it would only ever be measured against the shell's own content width. +// Plain RN styles on purpose — see docs/unistyles.md on Reanimated + Unistyles styles. +const shellStyles = RNStyleSheet.create({ + shell: { + minWidth: 0, + maxWidth: "100%", + flexShrink: 1, + }, +}); + +export function PinnedPrompt({ pinnedId, promptById, onJumpToPrompt }: PinnedPromptProps) { + const pinnedItemId = useSyncExternalStore(pinnedId.subscribe, pinnedId.getValue); + const isCompact = useIsCompactFormFactor(); + const prompt = pinnedItemId === null ? null : (promptById.get(pinnedItemId) ?? null); + // A pinned header would eat a phone viewport, where the transcript is already the whole screen. + if (isCompact) { + return null; + } + // The layer stays mounted across pins so the bubble's exit animation has a parent to run under. + // Keying the bubble on the prompt resets its overflow measurement, so a short prompt following a + // long one never inherits its fade. + return ( + + + {prompt ? ( + + ) : null} + + + ); +} + +function PinnedPromptBubble({ + prompt, + onJumpToPrompt, +}: { + prompt: PinnedPromptResolution; + onJumpToPrompt: (itemId: string) => void; +}) { + const { t } = useTranslation(); + const prefersReducedMotion = useReducedMotion(); + const [clipHeight, setClipHeight] = useState(0); + const [contentHeight, setContentHeight] = useState(0); + + // A retained agent tab is hidden with `display: none`, which reports a zero-height layout. Keep + // the last real measurement rather than publishing hidden geometry. + const handleClipLayout = useCallback((event: LayoutChangeEvent) => { + const { height } = event.nativeEvent.layout; + if (height > 0) { + setClipHeight(height); + } + }, []); + const handleContentLayout = useCallback((event: LayoutChangeEvent) => { + const { height } = event.nativeEvent.layout; + if (height > 0) { + setContentHeight(height); + } + }, []); + const handlePress = useCallback(() => onJumpToPrompt(prompt.id), [onJumpToPrompt, prompt.id]); + + // `overflow: hidden` on the clip box does not shrink its child's box, so the inner view reports + // the prompt's full height even while the clip box is capped. + const isOverflowing = clipHeight > 0 && contentHeight > clipHeight; + + return ( + + + + + {prompt.text} + + + {isOverflowing ? : null} + + + ); +} + +function PinnedPromptFadeSvg({ gradientId, color }: { gradientId: string; color: string }) { + return ( + + + + {/* Vary opacity rather than interpolating toward `transparent`, which crosses black in + some engines and leaves a grey fringe. */} + + + + + + + ); +} + +const ThemedPinnedPromptFadeSvg = withUnistyles(PinnedPromptFadeSvg); +const bubbleColorMapping = (theme: Theme) => ({ color: theme.colors.surface3 }); + +/** + * Fades the clipped tail of the prompt into the bubble. It sits inside the bubble's padding so the + * rounded bottom corners stay opaque — fading the bubble itself would dissolve its shape into the + * transcript scrolling underneath. + */ +function PinnedPromptFade() { + // React-generated ids contain characters that are invalid inside SVG fragment references. + const gradientId = `pinned-prompt-fade-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; + return ( + + + + ); +} + +const styles = StyleSheet.create((theme) => { + // Matches the real bubble's web line height in components/message.tsx. + const lineHeight = Math.round(theme.fontSize.content * CONTENT_LINE_HEIGHT_RATIO); + return { + // An absolutely positioned sibling of the transcript, so the scroll container's content box + // never changes and the bottom-anchor controller never sees the pin. + layer: { + position: "absolute", + top: 0, + left: 0, + right: 0, + alignItems: "center", + // The scaled bubble's top-right corner stays at its layout corner, so matching the jump + // inset lands the real message exactly where the pin was and the pin un-zooms in place. + paddingTop: PROMPT_JUMP_TOP_INSET_PX, + }, + // The transcript's own content rail, right-aligned like the real user bubble. + rail: { + width: "100%", + maxWidth: theme.contentMaxWidth, + paddingHorizontal: theme.spacing[2], + flexDirection: "row", + justifyContent: "flex-end", + }, + bubble: { + backgroundColor: theme.colors.surface3, + borderRadius: theme.borderRadius["2xl"], + borderTopRightRadius: theme.borderRadius.sm, + paddingHorizontal: theme.spacing[4], + paddingVertical: theme.spacing[4], + // The shell above owns the width cap; the bubble fills it, so a wrapped prompt is never wider + // than the real message's rail and the scale leaves it at 70% of the content width at most. + minWidth: 0, + transform: [{ scale: PINNED_PROMPT_SCALE }], + // Scale toward the top-right corner so the right edge stays on the rail whatever the + // bubble's width. CSS string form on purpose: Unistyles' web converter only translates + // `transform` arrays, so RN's array origin would reach the DOM verbatim and fall back to + // center. This file is web-only, so the native array concern does not apply. + transformOrigin: "100% 0", + cursor: "pointer", + // Large, low-alpha shadow so the pin reads as floating over the transcript without a hard + // edge against it. + ...theme.shadow.lg, + }, + clip: { + maxHeight: lineHeight * PINNED_PROMPT_MAX_LINES, + overflow: "hidden", + }, + text: { + color: theme.colors.foreground, + fontSize: theme.fontSize.content, + lineHeight, + overflowWrap: "anywhere", + // The pin sits inside AssistantSelectionCopySurface, which serializes the DOM selection on + // copy. Selectable pinned text would silently duplicate the prompt in the clipboard. + userSelect: "none", + }, + fade: { + position: "absolute", + left: theme.spacing[4], + right: theme.spacing[4], + bottom: theme.spacing[4], + height: Math.round(lineHeight * 1.5), + }, + }; +}); diff --git a/packages/app/src/agent-stream/pinned-prompt/use-pinned-prompt.ts b/packages/app/src/agent-stream/pinned-prompt/use-pinned-prompt.ts new file mode 100644 index 00000000000..7bca0a5c16b --- /dev/null +++ b/packages/app/src/agent-stream/pinned-prompt/use-pinned-prompt.ts @@ -0,0 +1,61 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import { useStableEvent } from "@/hooks/use-stable-event"; +import type { StreamItem } from "@/types/stream"; +import { createReadingSignal, type ReadingSignalSource } from "../reading-signal"; +import { resolvePinnedPrompt, type PinnedPromptResolution } from "./model"; + +export interface UsePinnedPromptInput { + history: StreamItem[]; + liveHead: StreamItem[]; +} + +export interface PinnedPromptState { + pinnedId: ReadingSignalSource; + promptById: ReadonlyMap; + reportReadingPosition: (rowId: string | null) => void; +} + +export function usePinnedPrompt({ history, liveHead }: UsePinnedPromptInput): PinnedPromptState { + const [pinnedId] = useState(() => createReadingSignal(null)); + const readingRowIdRef = useRef(null); + const items = useMemo(() => [...history, ...liveHead], [history, liveHead]); + + // Only the id travels through the signal. The overlay looks the text up from `promptById`, which + // changes when the timeline does rather than on every scroll frame. + const publishPinnedPrompt = useStableEvent(() => { + const resolution = resolvePinnedPrompt({ items, readingRowId: readingRowIdRef.current }); + pinnedId.publish(resolution?.id ?? null); + }); + + const reportReadingPosition = useStableEvent((rowId: string | null) => { + readingRowIdRef.current = rowId; + publishPinnedPrompt(); + }); + + // Re-resolve whenever the rows change. This also covers the transcript reporting its reading + // position before the items arrive, and a reader who never scrolls. + // + // Deliberately no reset on agent or epoch change. The viewport is a child of this hook's owner, + // so on a timeline replacement its effects report the fresh reading row *before* an effect here + // would run; clearing the ref at that point would discard the report and leave the pin empty + // until the next scroll. A stale row id is harmless — it fails the lookup and resolves to null. + useEffect(() => { + publishPinnedPrompt(); + }, [items, publishPinnedPrompt]); + + const promptById = useMemo(() => { + const byId = new Map(); + for (const item of items) { + if (item.kind !== "user_message") { + continue; + } + const text = item.text.trim(); + if (text.length > 0) { + byId.set(item.id, { id: item.id, text }); + } + } + return byId; + }, [items]); + + return { pinnedId, promptById, reportReadingPosition }; +} diff --git a/packages/app/src/agent-stream/presentation.ts b/packages/app/src/agent-stream/presentation.ts index 8e197aed239..850e4b8c145 100644 --- a/packages/app/src/agent-stream/presentation.ts +++ b/packages/app/src/agent-stream/presentation.ts @@ -53,6 +53,12 @@ const NO_COLLAPSED_TURNS: StreamPresentation["turns"] = collapseTurns({ previousSummaryRowsByHostId: new Map(), }); +/** Find and scrolling address a plugin row by the source it replaces. */ +export function getStreamItemMessageId(item: StreamItem): string { + if (item.kind === "plugin") return item.sourceId ?? item.id; + return item.id; +} + /** Source messages reach plugins before display projection. */ export function createStreamPresentation() { const userMessageCache = new WeakMap(); diff --git a/packages/app/src/agent-stream/reading-signal.ts b/packages/app/src/agent-stream/reading-signal.ts new file mode 100644 index 00000000000..e4cd39679f2 --- /dev/null +++ b/packages/app/src/agent-stream/reading-signal.ts @@ -0,0 +1,39 @@ +export interface ReadingSignalSource { + subscribe: (listener: () => void) => () => void; + getValue: () => T; +} + +export interface ReadingSignal extends ReadingSignalSource { + publish: (value: T) => void; +} + +/** + * The transcript reports its reading position on every scroll frame, far more often than it + * re-renders. Keeping the derived value outside React lets the surfaces that mark the reading + * position subscribe to it without dragging the transcript through a render on each frame. + * + * Hold a primitive so the unchanged-value check below is reference-free: scrolling within one turn + * then resolves to the same value and notifies nobody. + */ +export function createReadingSignal(initial: T): ReadingSignal { + const listeners = new Set<() => void>(); + let current = initial; + return { + subscribe(listener) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + getValue: () => current, + publish(value) { + if (value === current) { + return; + } + current = value; + for (const listener of listeners) { + listener(); + } + }, + }; +} diff --git a/packages/app/src/agent-stream/strategy-native.tsx b/packages/app/src/agent-stream/strategy-native.tsx index 106c9c3bb49..fed1c1c8638 100644 --- a/packages/app/src/agent-stream/strategy-native.tsx +++ b/packages/app/src/agent-stream/strategy-native.tsx @@ -33,6 +33,7 @@ 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 { @@ -204,6 +205,9 @@ 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 = @@ -448,6 +452,23 @@ 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") => { @@ -460,6 +481,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat bottomAnchorController.prepareForStickyViewportChange(); }, holdRow, + scrollToMessage: messageScroller.scrollToMessage, }; viewportRef.current = handle; return () => { @@ -467,7 +489,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat viewportRef.current = null; } }; - }, [agentId, bottomAnchorController, holdRow, viewportRef]); + }, [agentId, bottomAnchorController, holdRow, messageScroller, 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/strategy-web.test.tsx b/packages/app/src/agent-stream/strategy-web.test.tsx index 3601c8b0b2d..6529c79ae06 100644 --- a/packages/app/src/agent-stream/strategy-web.test.tsx +++ b/packages/app/src/agent-stream/strategy-web.test.tsx @@ -367,6 +367,101 @@ describe("createWebStreamStrategy", () => { expect(scrollContainer?.dataset.overlayScrollbar).toBe("true"); }); + it("ignores decorative mutations while following but tracks actual content and viewport growth", async () => { + const callbacks: ResizeObserverCallback[] = []; + const resize = () => { + for (const callback of callbacks) callback([], {} as ResizeObserver); + }; + Object.defineProperty(globalThis, "ResizeObserver", { + configurable: true, + value: class { + constructor(callback: ResizeObserverCallback) { + callbacks.push(callback); + } + observe() {} + unobserve() {} + disconnect() {} + }, + }); + const scrollTo = vi.fn(function ( + this: HTMLElement, + options?: ScrollToOptions | number, + y?: number, + ) { + const top = typeof options === "object" ? (options.top ?? 0) : (y ?? 0); + this.scrollTop = Math.max(0, Math.min(top, this.scrollHeight - this.clientHeight)); + }); + HTMLElement.prototype.scrollTo = scrollTo; + const strategy = createWebStreamStrategy({ isMobileBreakpoint: false }); + const viewportRef = React.createRef(); + const input: StreamRenderInput = { + agentId: "agent", + segments: { historyVirtualized: [], historyMounted: [], liveHead: [userMessage(1)] }, + boundary: { hasVirtualizedHistory: false, hasMountedHistory: false, hasLiveHead: true }, + renderers: { + ...createRenderers(vi.fn()), + renderLiveHeadRow: () => ( + + ), + }, + listEmptyComponent: null, + viewportRef, + routeBottomAnchorRequest: null, + isAuthoritativeHistoryReady: true, + onNearBottomChange: vi.fn(), + onNearHistoryStart: vi.fn().mockReturnValue(true), + isLoadingOlderHistory: false, + hasOlderHistory: false, + olderHistoryProgressKey: null, + scrollEnabled: true, + listStyle: null, + baseListContentContainerStyle: null, + forwardListContentContainerStyle: null, + contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH, + }; + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + act(() => root!.render(strategy.render(input))); + const viewport = container.querySelector('[data-testid="agent-chat-scroll"]')!; + let contentHeight = 669; + let viewportHeight = 600; + Object.defineProperties(viewport, { + clientHeight: { configurable: true, get: () => viewportHeight }, + scrollHeight: { configurable: true, get: () => contentHeight }, + clientWidth: { configurable: true, value: 900 }, + scrollWidth: { configurable: true, value: 900 }, + }); + act(resize); + await act(async () => { + await new Promise(requestAnimationFrame); + }); + viewport.scrollTop = 48; + scrollTo.mockClear(); + const control = container.querySelector('[data-testid="decorative-control"]')!; + await act(async () => { + control.replaceChildren(document.createElement("svg")); + }); + expect(scrollTo).not.toHaveBeenCalled(); + expect(viewport.scrollTop).toBe(48); + // Paced text and async image layout can grow below the reader without rerendering the viewport. + contentHeight = 690; + await act(async () => { + control.appendChild(document.createTextNode("grown content")); + }); + expect(viewport.scrollTop).toBe(90); + contentHeight = 730; + act(resize); + expect(viewport.scrollTop).toBe(130); + viewportHeight = 580; + scrollTo.mockClear(); + act(resize); + expect(scrollTo).toHaveBeenCalled(); + expect(viewport.scrollTop).toBe(150); + }); + it("rerenders a stable live-head row when its revision changes", () => { const strategy = createWebStreamStrategy({ isMobileBreakpoint: false }); const viewportRef = React.createRef(); diff --git a/packages/app/src/agent-stream/strategy-web.tsx b/packages/app/src/agent-stream/strategy-web.tsx index c47e0720f47..367ad5b6136 100644 --- a/packages/app/src/agent-stream/strategy-web.tsx +++ b/packages/app/src/agent-stream/strategy-web.tsx @@ -951,11 +951,13 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool updateScrollMetrics(); evaluateHistoryStart(); } + let observedContentGeometry = getObservedViewportGeometry(scrollContainer); const observer = new ResizeObserver(() => { flushSync(() => { measureVirtualizedRows(); }); const nextGeometry = getObservedViewportGeometry(scrollContainer); + observedContentGeometry = nextGeometry; if (pendingResumeGeometryCheckRef.current) { pendingResumeGeometryCheckRef.current = false; reportReadingPosition(); @@ -988,7 +990,12 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool // Observe those commits too, so the next frame sees the grown content at the // bottom instead of waiting for the resize notification after animation frames. const contentChanges = new MutationObserver(() => { - if (isActiveRef.current && followOutputRef.current) forceStickToBottom(); + const nextGeometry = getObservedViewportGeometry(scrollContainer); + const changed = !observedViewportGeometriesEqual(observedContentGeometry, nextGeometry); + observedContentGeometry = nextGeometry; + // Hover decorations can replace children without growing content. Moving the viewport + // then can move a pressed button out from under the pointer before mouseup. + if (changed && isActiveRef.current && followOutputRef.current) forceStickToBottom(); }); if (contentNode) contentChanges.observe(contentNode, { childList: true, characterData: true, subtree: true }); diff --git a/packages/app/src/agent-stream/turn-footer.tsx b/packages/app/src/agent-stream/turn-footer.tsx index 6699fb800b5..fcdc4437e1d 100644 --- a/packages/app/src/agent-stream/turn-footer.tsx +++ b/packages/app/src/agent-stream/turn-footer.tsx @@ -53,6 +53,7 @@ export const TurnFooter = memo(function TurnFooter({ supportsTimelineCursor, onForkAssistantTurn, onForkInFlightTurn, + onPin, }: { isRunning: boolean; inFlightTurnStartedAt: Date | null; @@ -61,6 +62,7 @@ export const TurnFooter = memo(function TurnFooter({ supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; onForkInFlightTurn?: InFlightTurnForkHandler; + onPin?: (text: string) => void; }) { if (isRunning) { return ( @@ -83,6 +85,7 @@ export const TurnFooter = memo(function TurnFooter({ startIndex={host.startIndex} supportsTimelineCursor={supportsTimelineCursor} onForkAssistantTurn={onForkAssistantTurn} + onPin={onPin} /> ); }); @@ -94,6 +97,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ startIndex, supportsTimelineCursor, onForkAssistantTurn, + onPin, }: { strategy: TurnContentStrategy; items: StreamItem[]; @@ -101,6 +105,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ startIndex: number; supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; + onPin?: (text: string) => void; }) { return ( @@ -111,6 +116,7 @@ export const CompletedTurnFooterRow = memo(function CompletedTurnFooterRow({ startIndex={startIndex} supportsTimelineCursor={supportsTimelineCursor} onForkAssistantTurn={onForkAssistantTurn} + onPin={onPin} /> ); @@ -167,6 +173,7 @@ function CompletedTurnFooter({ startIndex, supportsTimelineCursor, onForkAssistantTurn, + onPin, }: { strategy: TurnContentStrategy; items: StreamItem[]; @@ -174,6 +181,7 @@ function CompletedTurnFooter({ startIndex: number; supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; + onPin?: (text: string) => void; }) { const getContent = useCallback( () => @@ -205,6 +213,7 @@ function CompletedTurnFooter({ completedAt={timing?.completedAt} durationMs={timing?.durationMs} onFork={boundary && onForkAssistantTurn ? handleFork : undefined} + onPin={onPin} /> ); @@ -241,7 +250,7 @@ const stylesheet = StyleSheet.create((theme) => ({ paddingBottom: TURN_FOOTER_BOTTOM_SPACING, }, turnFooterContent: { - height: TURN_FOOTER_CONTENT_HEIGHT, + minHeight: TURN_FOOTER_CONTENT_HEIGHT, flexDirection: "row", alignItems: "center", justifyContent: "flex-start", diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index 7ea2c7e5d94..5933de06f6c 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -1,4 +1,6 @@ import { ChatFind, ChatFindExpansion } from "@/agent-stream/chat-find"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import React, { forwardRef, @@ -42,6 +44,7 @@ import { } from "@/components/message"; import { PlanCard } from "@/components/plan-card"; import { getStreamItemMessageId, type StreamItem } from "@/types/stream"; +import type { AgentDeepLinkTarget } from "@getpaseo/protocol/agent-deep-link"; import type { PendingMessageSubmission } from "@/composer/submission/model"; import type { TurnPresentation } from "@/timeline/turn-liveness"; import type { PendingPermission } from "@/types/shared"; @@ -52,6 +55,7 @@ import type { } from "@getpaseo/protocol/agent-types"; import type { AgentScreenAgent } from "@/hooks/use-agent-screen-state-machine"; import { useSessionStore } from "@/stores/session-store"; +import { useWorkspaceDirectory } from "@/stores/session-store-hooks"; import { useRevealedText } from "@/hooks/use-revealed-text"; import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions"; import { useLoadOlderAgentHistory } from "@/hooks/use-load-older-agent-history"; @@ -82,6 +86,8 @@ import { renderStreamRow, type RenderStreamItem } from "./stream-row"; import { type NearBottom, useIsNearBottom, useNearBottom } from "./near-bottom"; import { ChatOutlineRail } from "@/agent-stream/chat-outline/rail"; import { useChatOutline } from "@/agent-stream/chat-outline/use-chat-outline"; +import { PinnedPrompt } from "@/agent-stream/pinned-prompt/pinned-prompt"; +import { usePinnedPrompt } from "@/agent-stream/pinned-prompt/use-pinned-prompt"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan"; import { @@ -118,6 +124,30 @@ import { useRetainedPanelActive } from "@/components/retained-panel"; import { useStreamHistoryWindow } from "./use-stream-history-window"; import { PluginTimelineItemView, useInstalledTimelineTransform } from "@/plugins/timeline"; +type InlinePathError = "pathUnavailable" | "outsideWorkspaceDirectory"; +interface InlinePathErrorAlertProps { + error: InlinePathError | null; + onDismiss: () => void; +} + +function InlinePathErrorAlert({ error, onDismiss }: InlinePathErrorAlertProps) { + const { t } = useTranslation(); + if (!error) { + return null; + } + return ( + + + + ); +} + function renderLiveAuxiliaryNode(input: { pendingPermissions: ReactNode; turnFooter: ReactNode; @@ -148,6 +178,7 @@ function BottomOverlayInset({ height }: { height: number }) { function renderPendingPermissionsNode(input: { pendingPermissions: PendingPermission[]; + serverId: string; client: DaemonClient | null; }): ReactNode { if (input.pendingPermissions.length === 0) { @@ -156,7 +187,12 @@ function renderPendingPermissionsNode(input: { return ( {input.pendingPermissions.map((permission) => ( - + ))} ); @@ -175,6 +211,7 @@ function renderStreamItemWithTurnFooter(input: { strategy: TurnContentStrategy; supportsTimelineCursor: boolean; onForkAssistantTurn?: AssistantTurnForkHandler; + onPin?: (text: string) => void; }): ReactNode { if (!input.content) { return null; @@ -189,6 +226,7 @@ function renderStreamItemWithTurnFooter(input: { startIndex={footerHost.startIndex} supportsTimelineCursor={input.supportsTimelineCursor} onForkAssistantTurn={input.onForkAssistantTurn} + onPin={input.onPin} /> ) : null; const content = ( @@ -382,6 +420,8 @@ const AgentStreamViewComponent = forwardRef(null); + const dismissInlinePathError = useStableEvent(() => setInlinePathError(null)); const [expandedInlineToolCallIds, setExpandedInlineToolCallIds] = useState>( new Set(), ); @@ -415,11 +455,16 @@ const AgentStreamViewComponent = forwardRef state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true, ); - const workspaceRoot = context.cwd?.trim() || ""; + const workspaceRoot = context.cwd.trim(); + const destinationRoot = useWorkspaceDirectory(resolvedServerId, context.workspaceId ?? null); + const planSource = useMemo( + () => (resolvedServerId ? { serverId: resolvedServerId, agentId } : undefined), + [resolvedServerId, agentId], + ); const { revealDirectory } = useFileExplorerActions({ serverId: resolvedServerId, workspaceId: context.workspaceId, - workspaceRoot, + workspaceRoot: destinationRoot, }); const agentHistoryPagination = useLoadOlderAgentHistory({ serverId: resolvedServerId, @@ -439,6 +484,11 @@ const AgentStreamViewComponent = forwardRef { + setInlinePathError(null); + setExpandedInlineToolCallIds(new Set()); + setExpandedTurnHostIds(new Set()); + }, [agentId]); const isActive = useRetainedPanelActive(); const openInlineFile = useStableEvent( @@ -469,14 +519,23 @@ const AgentStreamViewComponent = forwardRef createInlinePathOpener({ - workspaceRoot, + workspaceRoot: destinationRoot ?? "", + sourceCwd: workspaceRoot, resolveRelativeFiles: true, + onError: setInlinePathError, client, openFile: openInlineFile, openDirectory: openInlineDirectory, openOutsideDirectory: openInlineOutsideDirectory, }), - [workspaceRoot, client, openInlineFile, openInlineDirectory, openInlineOutsideDirectory], + [ + workspaceRoot, + destinationRoot, + client, + openInlineFile, + openInlineDirectory, + openInlineOutsideDirectory, + ], ); useEffect(() => { if (!isActive) inlinePathOpener.cancel(); @@ -629,6 +688,13 @@ const AgentStreamViewComponent = forwardRef { + viewportRef.current?.scrollToMessage?.(itemId); + }); useImperativeHandle( ref, @@ -712,6 +778,31 @@ 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 ( @@ -725,6 +816,8 @@ const AgentStreamViewComponent = forwardRef ); }, - [context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId], + [ + context.capabilities, + agentId, + client, + pendingClientMessageIds, + resolvedServerId, + handlePin, + handleQAndA, + ], ); const renderAssistantMessageItem = useCallback( @@ -811,6 +912,7 @@ const AgentStreamViewComponent = forwardRef ); }, - [context.cwd, resolvedServerId, setInlineDetailsExpanded, handleToolCallOpenFile], + [context.cwd, resolvedServerId, setInlineDetailsExpanded, handleToolCallOpenFile, planSource], ); // Read through a stable event so live group updates do not change the renderer identity @@ -972,11 +1075,13 @@ const AgentStreamViewComponent = forwardRef renderPendingPermissionsNode({ pendingPermissions: pendingPermissionItems, + serverId: resolvedServerId, client, }), - [client, pendingPermissionItems], + [client, pendingPermissionItems, resolvedServerId], ); const turnFooterNode = useMemo( () => @@ -1008,11 +1114,13 @@ const AgentStreamViewComponent = forwardRef ) : null, [ handleForkAssistantTurn, handleForkInFlightTurn, + handlePin, readOnly, isTurnActive, baseRenderModel.turnTiming.runningStartedAt, @@ -1068,6 +1176,7 @@ const AgentStreamViewComponent = forwardRef + @@ -1210,6 +1320,11 @@ const AgentStreamViewComponent = forwardRef + { itemId: string; + source?: AgentDeepLinkTarget; onInlineDetailsExpandedChangeByItemId: (itemId: string, expanded: boolean) => void; } @@ -1405,6 +1521,7 @@ function ThoughtSlot({ function ToolCallSlot({ itemId, + source, onInlineDetailsExpandedChangeByItemId, ...rest }: ToolCallSlotProps) { @@ -1413,7 +1530,12 @@ function ToolCallSlot({ [onInlineDetailsExpandedChangeByItemId, itemId], ); return ( - + ); } @@ -1483,15 +1605,21 @@ function PermissionActionButton({ function PermissionRequestCard({ permission, + serverId, client, }: { permission: PendingPermission; + serverId: string; client: DaemonClient | null; }) { const { t } = useTranslation(); const isMobile = useIsCompactFormFactor(); const { request } = permission; + const permissionPlanSource = useMemo( + () => (serverId ? { serverId, agentId: permission.agentId } : undefined), + [serverId, permission.agentId], + ); const isPlanRequest = request.kind === "plan"; const title = isPlanRequest ? t("agentStream.permission.plan") @@ -1672,6 +1800,7 @@ function PermissionRequestCard({ title={title} description={description} text={planMarkdown} + source={permissionPlanSource} outcome="pending" footer={footer} testID="permission-plan-card" @@ -1690,6 +1819,7 @@ function PermissionRequestCard({ diff --git a/packages/app/src/app/_layout.tsx b/packages/app/src/app/_layout.tsx index b4ca122f777..6ac5ddb7cfa 100644 --- a/packages/app/src/app/_layout.tsx +++ b/packages/app/src/app/_layout.tsx @@ -104,6 +104,7 @@ import { useGlobalNewWorkspaceAction } from "@/hooks/use-global-new-workspace-ac import { useLatchedBoolean } from "@/hooks/use-latched-boolean"; import { useFaviconStatus } from "@/hooks/use-favicon-status"; import { useKeyboardShortcuts } from "@/keyboard/use-shortcuts"; +import { NavigationHistoryRecorder } from "@/navigation/history/recorder"; import { KeyboardShiftProvider } from "@/keyboard/shift"; import { useCompactWebViewportZoomLock } from "@/hooks/use-compact-web-viewport-zoom-lock"; import { useOpenProject } from "@/hooks/use-open-project"; @@ -660,6 +661,7 @@ function ProvidersWrapper({ children }: { children: ReactNode }) { + {children} diff --git a/packages/app/src/app/new.tsx b/packages/app/src/app/new.tsx index 67db3c2c96c..058a7e9b1be 100644 --- a/packages/app/src/app/new.tsx +++ b/packages/app/src/app/new.tsx @@ -1,5 +1,6 @@ import { useLocalSearchParams } from "expo-router"; import { useMemo } from "react"; +import { parseInitialChangeRequest } from "@/screens/project-pull-requests/model"; import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary"; import { ComposerEditingScope, @@ -18,18 +19,21 @@ export default function NewWorkspaceRoute() { name?: string; projectId?: string; draftId?: string; + changeRequest?: string; }>(); const serverId = typeof params.serverId === "string" ? params.serverId : ""; const sourceDirectory = typeof params.dir === "string" ? params.dir : undefined; const displayName = typeof params.name === "string" ? params.name : undefined; const projectId = typeof params.projectId === "string" ? params.projectId : undefined; const draftId = typeof params.draftId === "string" ? params.draftId : undefined; + const initialChangeRequest = parseInitialChangeRequest(params.changeRequest); const screenKey = JSON.stringify([ serverId, sourceDirectory ?? null, displayName ?? null, projectId ?? null, draftId ?? null, + params.changeRequest ?? null, ]); // The shell remounts this route when the viewport crosses the compact breakpoint; @@ -51,6 +55,7 @@ export default function NewWorkspaceRoute() { displayName={displayName} projectId={projectId} draftId={draftId} + initialChangeRequest={initialChangeRequest} /> diff --git a/packages/app/src/artifacts/feed.tsx b/packages/app/src/artifacts/feed.tsx new file mode 100644 index 00000000000..41e81441472 --- /dev/null +++ b/packages/app/src/artifacts/feed.tsx @@ -0,0 +1,353 @@ +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/assistant-file-links/parse.test.ts b/packages/app/src/assistant-file-links/parse.test.ts index 3390d0cfa9c..a192b2f1ca2 100644 --- a/packages/app/src/assistant-file-links/parse.test.ts +++ b/packages/app/src/assistant-file-links/parse.test.ts @@ -1,4 +1,5 @@ -import { describe, expect, it } from "vitest"; +import { assert, describe, expect, it } from "vitest"; +import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target"; import { classifyAssistantFileLink, normalizeInlinePathTarget, @@ -542,8 +543,33 @@ describe("parseAssistantFileLink", () => { }); describe("normalizeInlinePathTarget", () => { + it("keeps a conversation's source file when the displayed checkout contains the same path", () => { + const sourceRoot = "/checkouts/source"; + const destinationRoot = "/checkouts/displayed"; + const target = parseAssistantFileLink("src/app.ts#L12-L20", { workspaceRoot: sourceRoot }); + assert(target); + const normalized = normalizeInlinePathTarget(target.path, { + sourceCwd: sourceRoot, + workspaceRoot: destinationRoot, + }); + assert(normalized && "file" in normalized && normalized.file); + expect(normalized.file).toBe("/checkouts/source/src/app.ts"); + expect(target).toMatchObject({ lineStart: 12, lineEnd: 20 }); + expect( + resolveFilePreviewReadTarget({ + path: normalized.file, + workspaceRoot: destinationRoot, + }), + ).toEqual({ cwd: "/", path: "/checkouts/source/src/app.ts" }); + }); + it("keeps relative file paths as file targets", () => { - expect(normalizeInlinePathTarget("packages/app/src/components/message.tsx")).toEqual({ + expect( + normalizeInlinePathTarget("packages/app/src/components/message.tsx", { + sourceCwd: "/Users/test/project", + workspaceRoot: "/Users/test/project", + }), + ).toEqual({ directory: "packages/app/src/components", file: "packages/app/src/components/message.tsx", }); @@ -551,10 +577,10 @@ describe("normalizeInlinePathTarget", () => { it("resolves absolute paths under cwd back to workspace-relative paths", () => { expect( - normalizeInlinePathTarget( - "/Users/test/project/packages/app/src/components/message.tsx", - "/Users/test/project", - ), + normalizeInlinePathTarget("/Users/test/project/packages/app/src/components/message.tsx", { + sourceCwd: "/Users/test/project", + workspaceRoot: "/Users/test/project", + }), ).toEqual({ directory: "packages/app/src/components", file: "packages/app/src/components/message.tsx", @@ -562,7 +588,12 @@ describe("normalizeInlinePathTarget", () => { }); it("keeps absolute paths outside cwd as absolute file targets", () => { - expect(normalizeInlinePathTarget("/tmp/message.tsx", "/Users/test/project")).toEqual({ + expect( + normalizeInlinePathTarget("/tmp/message.tsx", { + sourceCwd: "/Users/test/project", + workspaceRoot: "/Users/test/project", + }), + ).toEqual({ directory: "/tmp", file: "/tmp/message.tsx", }); @@ -570,7 +601,10 @@ describe("normalizeInlinePathTarget", () => { it("keeps tilde paths as home-relative file targets", () => { expect( - normalizeInlinePathTarget("~/.paseo/plans/file-preview.md", "/Users/test/project"), + normalizeInlinePathTarget("~/.paseo/plans/file-preview.md", { + sourceCwd: "/Users/test/project", + workspaceRoot: "/Users/test/project", + }), ).toEqual({ directory: "~/.paseo/plans", file: "~/.paseo/plans/file-preview.md", @@ -578,18 +612,98 @@ describe("normalizeInlinePathTarget", () => { }); it("treats cwd itself as the workspace root directory", () => { - expect(normalizeInlinePathTarget("/Users/test/project", "/Users/test/project")).toEqual({ + expect( + normalizeInlinePathTarget("/Users/test/project", { + sourceCwd: "/Users/test/project", + workspaceRoot: "/Users/test/project", + }), + ).toEqual({ directory: ".", }); }); it("keeps trailing-slash paths as directories", () => { expect( - normalizeInlinePathTarget("/Users/test/project/packages/app/", "/Users/test/project"), + normalizeInlinePathTarget("/Users/test/project/packages/app/", { + sourceCwd: "/Users/test/project", + workspaceRoot: "/Users/test/project", + }), ).toEqual({ directory: "packages/app", }); }); + + it("anchors relative tool paths to the conversation before handing them to another workspace", () => { + expect( + normalizeInlinePathTarget("src/app.ts", { + sourceCwd: "/checkouts/source", + workspaceRoot: "/checkouts/displayed", + }), + ).toEqual({ directory: "/checkouts/source/src", file: "/checkouts/source/src/app.ts" }); + }); + + it.each([ + [ + "file:///checkouts/source/src/app.ts#L12", + "/checkouts/source", + "/checkouts/displayed", + "/checkouts/source/src/app.ts", + ], + ["C:\\source\\src\\app.ts#L12", "C:/source", "C:/displayed", "C:/source/src/app.ts"], + ["src/app.ts#L12", "/project/packages/app", "/project", "packages/app/src/app.ts"], + ])("preserves file identity and line numbers from %s", (link, sourceCwd, workspaceRoot, file) => { + const target = parseAssistantFileLink(link, { workspaceRoot: sourceCwd }); + assert(target); + expect(target.lineStart).toBe(12); + expect(normalizeInlinePathTarget(target.path, { sourceCwd, workspaceRoot })).toMatchObject({ + file, + }); + }); + + it.each([ + ["./", "/project", "."], + ["src/", "/project/packages/app", "packages/app/src"], + ["/project/packages/app/", "/other", "packages/app"], + ])("keeps directory %s relative to the displayed workspace", (rawPath, sourceCwd, directory) => { + expect(normalizeInlinePathTarget(rawPath, { sourceCwd, workspaceRoot: "/project" })).toEqual({ + directory, + }); + }); + + it.each([ + ["src/", "/other", "/other/src"], + ["/other/", "/other", "/other"], + ["/project-other/src/", "/project", "/project-other/src"], + ["/project/../other/", "/project", "/project/../other"], + ["~/plans/", "/project", "~/plans"], + ])("retains outside directory %s for its own Files panel", (rawPath, sourceCwd, directory) => { + expect(normalizeInlinePathTarget(rawPath, { sourceCwd, workspaceRoot: "/project" })).toEqual({ + directory, + }); + }); + + it("retains absolute paths when the displayed workspace is unavailable", () => { + expect(normalizeInlinePathTarget("src/app.ts", { sourceCwd: "/source" })).toEqual({ + directory: "/source/src", + file: "/source/src/app.ts", + }); + expect(normalizeInlinePathTarget("src/", { sourceCwd: "/source" })).toEqual({ + directory: "/source/src", + }); + expect(normalizeInlinePathTarget("/source/src/app.ts", {})).toMatchObject({ + file: "/source/src/app.ts", + }); + }); + + it("refuses to anchor unresolved relative paths to the displayed checkout", () => { + expect(normalizeInlinePathTarget("src/app.ts", { workspaceRoot: "/project" })).toBeNull(); + expect( + normalizeInlinePathTarget("../app.ts", { + sourceCwd: "/source", + workspaceRoot: "/project", + }), + ).toBeNull(); + }); }); describe("encoded filename line markers", () => { diff --git a/packages/app/src/assistant-file-links/parse.ts b/packages/app/src/assistant-file-links/parse.ts index 8e02310fea4..15876a122d6 100644 --- a/packages/app/src/assistant-file-links/parse.ts +++ b/packages/app/src/assistant-file-links/parse.ts @@ -50,9 +50,13 @@ export type AssistantFileLinkClassification = target: InlinePathTarget; }; -export interface NormalizedInlinePathTarget { - directory: string; - file?: string; +export type NormalizedInlinePathTarget = + | { directory: string; file?: string } + | { error: "outsideWorkspaceDirectory" }; + +interface NormalizeInlinePathOptions { + sourceCwd?: string; + workspaceRoot?: string; } function normalizePathToken(value: string): string | null { @@ -485,47 +489,48 @@ function parseLocalPathParts( export function normalizeInlinePathTarget( rawPath: string, - cwd?: string, + { sourceCwd, workspaceRoot }: NormalizeInlinePathOptions, ): NormalizedInlinePathTarget | null { - if (!rawPath) { - return null; - } - const normalizedInput = normalizePathInput(rawPath); if (!normalizedInput) { return null; } - let normalized = normalizedInput; - const cwdRelative = resolvePathAgainstCwd(normalized, cwd); - if (cwdRelative) { - normalized = cwdRelative; - } - - if (normalized.startsWith("./")) { - normalized = normalized.slice(2) || "."; - } - - if (!normalized.length) { - normalized = "."; - } - - if (normalized === ".") { - return { directory: "." }; - } - - if (normalized.endsWith("/")) { - const dir = normalized.replace(/\/+$/, ""); - return { directory: dir.length > 0 ? dir : "." }; + let sourcePath = normalizedInput; + const needsSourceRoot = !isAbsolutePath(sourcePath) && !isHomeRelativePath(sourcePath); + if (needsSourceRoot) { + const sourceRoot = normalizePathInput(sourceCwd); + if (!sourceRoot || !isAbsolutePath(sourceRoot)) { + return null; + } + const resolved = resolveRelativePathUnderRoot(sourcePath, sourceRoot); + if (!resolved) { + return null; + } + sourcePath = resolved; + } + + const workspaceRelative = resolvePathAgainstCwd(sourcePath, workspaceRoot); + const isDirectory = + normalizedInput.endsWith("/") || + resolvePathAgainstCwd(sourcePath, sourceCwd) === "." || + workspaceRelative === "."; + if (isDirectory) { + const directory = workspaceRelative?.replace(/\/+$/, "") || "."; + const belongsToWorkspace = + workspaceRoot !== undefined && + workspaceRelative !== null && + resolveRelativePathUnderRoot(directory, workspaceRoot) !== null; + if (!belongsToWorkspace) { + return { directory: sourcePath.replace(/\/+$/, "") || "/" }; + } + return { directory }; } - const lastSlash = normalized.lastIndexOf("/"); - const directory = lastSlash >= 0 ? normalized.slice(0, lastSlash) : "."; - - return { - directory: directory.length > 0 ? directory : ".", - file: normalized, - }; + const file = workspaceRelative ?? sourcePath; + const lastSlash = file.lastIndexOf("/"); + const directory = lastSlash >= 0 ? file.slice(0, lastSlash) : "."; + return { directory: directory || ".", file }; } function isAllowedAbsolutePath(pathValue: string, workspaceRoot?: string): boolean { diff --git a/packages/app/src/assistant-file-links/path-open.test.ts b/packages/app/src/assistant-file-links/path-open.test.ts index f54ee887652..a844a7da298 100644 --- a/packages/app/src/assistant-file-links/path-open.test.ts +++ b/packages/app/src/assistant-file-links/path-open.test.ts @@ -178,3 +178,36 @@ it("keeps a later selection when an earlier nested-file lookup finishes last", a await earlier; expect(opened).toEqual(["guide.md"]); }); + +it("resolves relative links from the agent cwd into the workspace before probing folders", async () => { + const { createInlinePathOpener } = await import("./path-open"); + const probes: string[] = []; + const opened: string[] = []; + const errors: Array = []; + const opener = createInlinePathOpener({ + workspaceRoot: "/repo", + sourceCwd: "/repo/project", + openOutsideDirectory: () => {}, + client: { + listDirectory: async (root, file) => { + probes.push(`${root}:${file}`); + }, + }, + openFile: (location) => { + opened.push(`file:${location.path}`); + }, + openDirectory: (directory) => { + opened.push(`directory:${directory}`); + }, + onError: (error) => { + errors.push(error); + }, + }); + await opener.open({ raw: "./docs", path: "./docs" }, "preferred"); + expect(probes).toEqual(["/repo:project/docs"]); + expect(opened).toEqual(["directory:project/docs"]); + expect(errors).toEqual([null]); + await opener.open({ raw: "/outside/", path: "/outside/" }, "preferred"); + expect(errors).toEqual([null, null]); + expect(opened).toEqual(["directory:project/docs"]); +}); diff --git a/packages/app/src/assistant-file-links/path-open.ts b/packages/app/src/assistant-file-links/path-open.ts index 7ff50c9a1a4..7209527d6e0 100644 --- a/packages/app/src/assistant-file-links/path-open.ts +++ b/packages/app/src/assistant-file-links/path-open.ts @@ -51,10 +51,9 @@ export async function resolveInlinePathOpen(input: PathOpenInput): Promise; - getDirectorySuggestions: GetDirectorySuggestions; - } | null; + sourceCwd?: string; + onError?: (error: "pathUnavailable" | "outsideWorkspaceDirectory" | null) => void; + client: (PathOpenInput["client"] & { getDirectorySuggestions?: GetDirectorySuggestions }) | null; resolveRelativeFiles?: boolean; openFile: (location: WorkspaceFileLocation, disposition: OpenFileDisposition) => void; openDirectory: (path: string) => void; @@ -64,8 +63,19 @@ export function createInlinePathOpener(input: { return { async open(target: InlinePathTarget, disposition: OpenFileDisposition) { const ownGeneration = ++generation; - const normalized = normalizeInlinePathTarget(target.path, input.workspaceRoot); - if (!normalized) return; + const normalized = normalizeInlinePathTarget(target.path, { + sourceCwd: input.sourceCwd ?? input.workspaceRoot, + workspaceRoot: input.workspaceRoot, + }); + if (!normalized) { + input.onError?.("pathUnavailable"); + return; + } + if ("error" in normalized) { + input.onError?.(normalized.error); + return; + } + input.onError?.(null); const destination = await resolveInlinePathOpen({ ...normalized, lineStart: target.lineStart, @@ -79,7 +89,7 @@ export function createInlinePathOpener(input: { input.openOutsideDirectory(destination.directoryPath); } else if (normalized.file) { const resolvedTarget = - input.resolveRelativeFiles && input.client + input.resolveRelativeFiles && input.client?.getDirectorySuggestions ? await resolveMissingNestedRelativeFile({ target, workspaceRoot: input.workspaceRoot, @@ -87,8 +97,11 @@ export function createInlinePathOpener(input: { }) : target; if (ownGeneration !== generation) return; - const resolved = normalizeInlinePathTarget(resolvedTarget.path, input.workspaceRoot); - if (!resolved?.file) return; + const resolved = normalizeInlinePathTarget(resolvedTarget.path, { + sourceCwd: input.sourceCwd ?? input.workspaceRoot, + workspaceRoot: input.workspaceRoot, + }); + if (!resolved || "error" in resolved || !resolved.file) return; const location = normalizeWorkspaceFileLocation({ path: resolved.file, lineStart: resolvedTarget.lineStart, diff --git a/packages/app/src/assistant-selection-copy/content.browser.test.ts b/packages/app/src/assistant-selection-copy/content.browser.test.ts index 5c4fcfb3315..0f42d4bfc52 100644 --- a/packages/app/src/assistant-selection-copy/content.browser.test.ts +++ b/packages/app/src/assistant-selection-copy/content.browser.test.ts @@ -815,3 +815,14 @@ it("copies a workspace image path instead of its temporary display URL", () => { "![chart](assets/chart.png)", ); }); + +it("copies a non-Latin selection without dropping wide characters", () => { + const message = mountFixture(); + const korean = "통합 구현은 전체 테스트를 통과했습니다"; + message.innerHTML = `

${korean}

`; + const paragraph = fixtureElement(message, "p"); + const through = korean.indexOf(" 전체"); + expect( + createAssistantSelectionClipboardContent(selectText(paragraph, 0, through))?.plainText, + ).toBe(korean.slice(0, through)); +}); diff --git a/packages/app/src/audio/audio-engine.native.test.ts b/packages/app/src/audio/audio-engine.native.test.ts new file mode 100644 index 00000000000..37c98bd583c --- /dev/null +++ b/packages/app/src/audio/audio-engine.native.test.ts @@ -0,0 +1,117 @@ +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 ed9f15a7650..68697f32c99 100644 --- a/packages/app/src/audio/audio-engine.native.ts +++ b/packages/app/src/audio/audio-engine.native.ts @@ -1,3 +1,4 @@ +import * as native from "@getpaseo/expo-two-way-audio"; import type { AudioEngine, AudioEngineCallbacks, @@ -15,8 +16,6 @@ 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 new file mode 100644 index 00000000000..866c857b88c --- /dev/null +++ b/packages/app/src/audio/audio-engine.web.test.ts @@ -0,0 +1,106 @@ +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 5516575e695..0a7f436a99c 100644 --- a/packages/app/src/audio/audio-engine.web.ts +++ b/packages/app/src/audio/audio-engine.web.ts @@ -285,6 +285,12 @@ 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 2627d899cf6..498b4175d79 100644 --- a/packages/app/src/audio/playback.test.ts +++ b/packages/app/src/audio/playback.test.ts @@ -113,9 +113,10 @@ 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 8d0744b79c5..4f714d72e73 100644 --- a/packages/app/src/audio/playback.ts +++ b/packages/app/src/audio/playback.ts @@ -24,7 +24,18 @@ export function createPlaybackQueue( active = item; try { if (item.controller.signal.aborted) throw new Error("Playback stopped"); - item.resolve(await start(item.source, item.controller.signal)); + // 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); + } } catch (error) { item.reject(error); } finally { diff --git a/packages/app/src/command-center/agent-control-contributions.ts b/packages/app/src/command-center/agent-control-contributions.ts index b16ee905496..a7ee19ab938 100644 --- a/packages/app/src/command-center/agent-control-contributions.ts +++ b/packages/app/src/command-center/agent-control-contributions.ts @@ -143,7 +143,7 @@ function buildModelGroup(source: AgentControlContributionSource): CommandCenterC for (const provider of source.models.providers) { if (provider.modelSelection.kind !== "models") continue; const agentProvider = provider.id; - const icon = source.icons.provider(agentProvider); + const icon = source.icons.provider(provider.baseProviderId ?? agentProvider); for (const model of provider.modelSelection.rows) { if (!model.modelId) continue; const modelId = model.modelId; diff --git a/packages/app/src/companion-stream/feed.test.tsx b/packages/app/src/companion-stream/feed.test.tsx new file mode 100644 index 00000000000..1409524e047 --- /dev/null +++ b/packages/app/src/companion-stream/feed.test.tsx @@ -0,0 +1,97 @@ +// @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 new file mode 100644 index 00000000000..8be892f92b4 --- /dev/null +++ b/packages/app/src/companion-stream/feed.tsx @@ -0,0 +1,539 @@ +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 new file mode 100644 index 00000000000..466e33b3d4a --- /dev/null +++ b/packages/app/src/companion-stream/model.test.ts @@ -0,0 +1,58 @@ +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 new file mode 100644 index 00000000000..9b6f3e01f1c --- /dev/null +++ b/packages/app/src/companion-stream/model.ts @@ -0,0 +1,30 @@ +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 new file mode 100644 index 00000000000..341610924f7 --- /dev/null +++ b/packages/app/src/components/agent-view-switcher.tsx @@ -0,0 +1,68 @@ +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/combined-model-selector.tsx b/packages/app/src/components/combined-model-selector.tsx index 05b118b866c..a1002e599cb 100644 --- a/packages/app/src/components/combined-model-selector.tsx +++ b/packages/app/src/components/combined-model-selector.tsx @@ -11,7 +11,10 @@ import { ModelBrowser, ModelProviderGlyph, useModelBrowser } from "@/components/ import { resolveModelBrowserScrolling } from "@/components/model-browser-view"; import { useIsCompactFormFactor } from "@/constants/layout"; import { isNative, isWeb } from "@/constants/platform"; -import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection"; +import { + resolveProviderIconId, + type ProviderSelectorProvider, +} from "@/provider-selection/provider-selection"; import { ICON_SIZE, type Theme } from "@/styles/theme"; import { TOOLBAR_GLYPH_SIZES, @@ -259,7 +262,7 @@ export function CombinedModelSelector({ {selectedProvider.trim().length > 0 ? ( void; + onQAndA?: (text: string, messageId?: string) => void; capabilities?: AgentCapabilityFlags; client?: DaemonClient | null; isFirstInGroup?: boolean; @@ -402,6 +407,8 @@ export const UserMessage = memo(function UserMessage({ images = [], attachments = [], timestamp, + onPin, + onQAndA, capabilities, client, isFirstInGroup = true, @@ -432,6 +439,11 @@ 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); @@ -538,6 +550,15 @@ export const UserMessage = memo(function UserMessage({ onRewind={handleRewind} /> ) : null} + {onPin ? ( + + ) : null} + {onQAndA ? ( + + ) : null} Promise | void; + onPin?: (text: string) => void; } const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({ @@ -564,6 +586,7 @@ const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({ minWidth: 0, minHeight: 24, flexDirection: "row", + flexWrap: "wrap", alignItems: "flex-start", gap: theme.spacing[2], }, @@ -582,10 +605,10 @@ const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({ }, labelButton: { flex: 1, + minWidth: 72, minHeight: 24, flexDirection: "row", alignItems: "center", - minWidth: 0, }, label: { width: "100%", @@ -613,6 +636,7 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({ completedAt, durationMs, onFork, + onPin, }: AssistantTurnFooterProps) { const { t } = useTranslation(); const [hovered, setHovered] = useState(false); @@ -661,12 +685,23 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({ }, [onFork], ); + const handlePin = useCallback(() => { + if (onPin && getContent) { + onPin(getContent()); + } + }, [onPin, getContent]); const canFork = Boolean(onFork); return ( - {getContent || canFork ? ( + {onPin || 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; @@ -2261,6 +2358,7 @@ interface ToolCallProps { itemId: string; /** Shown as its own row rather than inside a tool call group. */ standalone?: boolean; + source?: AgentDeepLinkTarget; } export const ToolCall = memo(function ToolCall({ @@ -2284,6 +2382,7 @@ export const ToolCall = memo(function ToolCall({ maxDetailHeight = 400, itemId, standalone = true, + source, }: ToolCallProps) { const { openToolCall } = useToolCallSheet(); const { expanded: isExpanded, toggle: toggleExpanded } = useToolCallExpanded({ @@ -2415,6 +2514,7 @@ export const ToolCall = memo(function ToolCall({ @@ -2459,5 +2559,6 @@ function areToolCallPropsEqual(previous: ToolCallProps, next: ToolCallProps) { if (previous.maxDetailHeight !== next.maxDetailHeight) return false; if (previous.itemId !== next.itemId) return false; if (previous.standalone !== next.standalone) return false; + if (previous.source !== next.source) return false; return true; } diff --git a/packages/app/src/components/model-browser.tsx b/packages/app/src/components/model-browser.tsx index 82edd1458d0..67220565b83 100644 --- a/packages/app/src/components/model-browser.tsx +++ b/packages/app/src/components/model-browser.tsx @@ -48,6 +48,7 @@ import { filterAndRankModelRows, getAllProviderModelRows, getProviderModelRows, + resolveProviderIconId, resolveSelectedModelLabel, type ProviderSelectionModelRow, type ProviderSelectorProvider, @@ -340,7 +341,7 @@ export function useModelBrowser({ title: view.providerLabel, leading: ( , - [row.provider, serverId], + () => ( + + ), + [row.iconProviderId, row.provider, serverId], ); const description = showProviderLabel ? buildProviderQualifiedDescription(row) : row.description; @@ -1009,8 +1017,14 @@ function GroupProviderButton({ ); }, [selection, t]); const leadingSlot = useMemo( - () => , - [provider.id, serverId], + () => ( + + ), + [provider.baseProviderId, provider.id, serverId], ); const trailingSlot = useMemo( () => ( diff --git a/packages/app/src/components/plan-card.tsx b/packages/app/src/components/plan-card.tsx index 65aaa96e921..29a982d5de0 100644 --- a/packages/app/src/components/plan-card.tsx +++ b/packages/app/src/components/plan-card.tsx @@ -1,4 +1,7 @@ import { useDisclosureHold } from "@/agent-stream/disclosure"; +import type { AgentDeepLinkTarget } from "@getpaseo/protocol/agent-deep-link"; +import { PlanCopyActions } from "@/components/plan-copy-actions"; +import { PlanHandoffButton } from "@/components/plan-handoff-button"; import { MarkdownRenderer } from "@/components/markdown/renderer"; import { isWeb } from "@/constants/platform"; import type { Theme } from "@/styles/theme"; @@ -16,6 +19,7 @@ interface PlanCardProps { text: string; outcome?: PlanOutcome; footer?: ReactNode; + source?: AgentDeepLinkTarget; disableOuterSpacing?: boolean; testID?: string; } @@ -34,6 +38,7 @@ function PlanCardContent({ text, outcome, footer, + source, disableOuterSpacing = false, testID, }: PlanCardProps) { @@ -64,19 +69,22 @@ function PlanCardContent({ return ( - - - - - {resolvedTitle} - + + + + + + {resolvedTitle} + + + {expanded ? ( {description ? {description} : null} @@ -84,6 +92,7 @@ function PlanCardContent({ ) : null} {footer ? {footer} : null} + {source ? : null} ); } @@ -107,6 +116,13 @@ const styles = StyleSheet.create((theme) => ({ gap: theme.spacing[2], minHeight: 24, }, + headerToggle: { + flex: 1, + minWidth: 0, + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, chevron: {}, chevronExpanded: { transform: [{ rotate: "90deg" }] }, body: { gap: theme.spacing[2] }, diff --git a/packages/app/src/components/plan-copy-actions.tsx b/packages/app/src/components/plan-copy-actions.tsx new file mode 100644 index 00000000000..5619639fe9e --- /dev/null +++ b/packages/app/src/components/plan-copy-actions.tsx @@ -0,0 +1,63 @@ +import { useCallback } from "react"; +import { useMutation } from "@tanstack/react-query"; +import * as Clipboard from "expo-clipboard"; +import { Copy, Link } from "lucide-react-native"; +import { Text } from "react-native"; +import { useTranslation } from "react-i18next"; +import { buildAgentDeepLink, type AgentDeepLinkTarget } from "@getpaseo/protocol/agent-deep-link"; +import { Button } from "@/components/ui/button"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { useToast } from "@/contexts/toast-context"; + +export function PlanCopyActions({ text, source }: { text: string; source?: AgentDeepLinkTarget }) { + return ( + <> + + {source ? : null} + + ); +} + +function PlanCopyButton({ content, kind }: { content: string; kind: "content" | "link" }) { + const { t } = useTranslation(); + const toast = useToast(); + const label = t( + kind === "content" ? "agentStream.permission.copyContent" : "agentStream.permission.copyLink", + ); + const copy = useMutation({ + mutationFn: async () => { + const copied = await Clipboard.setStringAsync(content); + if (!copied) throw new Error("Clipboard write failed"); + }, + onSuccess: () => + toast.copied( + t( + kind === "content" + ? "agentStream.permission.contentCopied" + : "agentStream.permission.linkCopied", + ), + ), + onError: () => toast.error(t("agentStream.permission.copyFailed")), + }); + const { mutate } = copy; + const handlePress = useCallback(() => mutate(), [mutate]); + + return ( + + + + ); +} diff --git a/packages/app/src/components/plan-handoff.test.tsx b/packages/app/src/components/plan-handoff.test.tsx new file mode 100644 index 00000000000..1befb0a3931 --- /dev/null +++ b/packages/app/src/components/plan-handoff.test.tsx @@ -0,0 +1,194 @@ +/** + * @vitest-environment jsdom + */ +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 { buildPlanHandoffPrompt } from "./plan-handoff"; + +const harness = vi.hoisted(() => ({ + session: null as unknown, + sendMessage: vi.fn(), + saveDraftInput: vi.fn(), + navigateToWorkspace: vi.fn(), + toastError: vi.fn(), +})); + +vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) })); +vi.mock("lucide-react-native", () => ({ ArrowRight: () => null })); +vi.mock("@/components/ui/button", () => ({ + Button: ({ + children, + onPress, + disabled, + testID, + }: { + children?: React.ReactNode; + onPress?: () => void; + disabled?: boolean; + testID?: string; + }) => ( + + ), +})); +vi.mock("@/contexts/toast-context", () => ({ + useToast: () => ({ error: harness.toastError }), +})); +vi.mock("@/stores/session-store", () => ({ + useSessionStore: { getState: () => harness.session }, +})); +vi.mock("@/stores/navigation-active-workspace-store", () => ({ + navigateToWorkspace: harness.navigateToWorkspace, +})); +vi.mock("@/stores/draft-store", () => ({ + useDraftStore: { getState: () => ({ saveDraftInput: harness.saveDraftInput }) }, +})); + +import { PlanHandoffButton } from "./plan-handoff-button"; + +const SOURCE = { serverId: "server-1", agentId: "agent-1" }; + +describe("buildPlanHandoffPrompt", () => { + it("preserves literal plan text and identifies the source agent", () => { + const plan = '# Plan\n\nAdd the (c) note with --name="my repo".\n\n---buzz'; + const prompt = buildPlanHandoffPrompt({ + instruction: "Implement the following proposed plan.", + plan, + source: { serverId: "server-1", agentId: "agent-1" }, + }); + + expect(prompt).toContain(plan); + expect(prompt).toContain("Source: paseo://"); + expect(prompt).toContain("agent-1"); + expect(prompt.match(/Implement the following proposed plan\./g)).toHaveLength(1); + }); +}); + +describe("PlanHandoffButton", () => { + let root: Root | null = null; + let container: HTMLElement | null = null; + + const agent = { + id: "agent-1", + workspaceId: "ws-1", + // A configured provider instance, not the bare provider name: the handoff has to carry the + // exact one the source agent runs on, account included. + provider: "claude-work", + cwd: "/code/project", + model: "opus", + thinkingOptionId: "high", + options: { "web-search": true }, + }; + + const handoffButton = () => + container?.querySelector('[data-testid="permission-plan-handoff"]') ?? null; + + const press = () => { + act(() => { + handoffButton()?.click(); + }); + }; + + beforeEach(() => { + // The app's JSX compiles to the classic runtime here, and the button does not import React. + vi.stubGlobal("React", React); + harness.sendMessage.mockClear(); + harness.saveDraftInput.mockClear(); + harness.navigateToWorkspace.mockClear(); + harness.toastError.mockClear(); + harness.session = { + sessions: { + "server-1": { + client: { sendMessage: harness.sendMessage }, + agents: new Map([["agent-1", agent]]), + workspaces: new Map([["ws-1", { workspaceId: "ws-1" }]]), + }, + }, + }; + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + act(() => { + root?.render(); + }); + }); + + afterEach(() => { + act(() => { + root?.unmount(); + }); + root = null; + container?.remove(); + container = null; + vi.unstubAllGlobals(); + }); + + // The source agent's workspace can be gone by the time the plan is read. The button has to say so + // and leave no trace: no draft, no navigation, and still usable afterwards. + it("reports an unavailable source without saving a draft or navigating", () => { + // The host session is still there but the source agent's workspace is gone, which is the state + // the button has to detect rather than trust. + harness.session = { + sessions: { + "server-1": { + client: { sendMessage: harness.sendMessage }, + agents: new Map([["agent-1", agent]]), + workspaces: new Map(), + }, + }, + }; + + press(); + + expect(harness.saveDraftInput).not.toHaveBeenCalled(); + expect(harness.navigateToWorkspace).not.toHaveBeenCalled(); + expect(harness.toastError).toHaveBeenCalledWith("agentStream.permission.handoffFailed"); + expect(handoffButton()?.disabled).toBe(false); + expect(handoffButton()?.textContent).toBe("agentStream.permission.handOff"); + }); + + it("opens one editable draft under a fresh key and sends nothing", () => { + press(); + + expect(harness.saveDraftInput).toHaveBeenCalledTimes(1); + const saved = harness.saveDraftInput.mock.calls[0]?.[0] as { + draftKey: string; + draft: { text: string; attachments: unknown[] }; + }; + // A fresh draft id, so an existing draft for the source agent is never overwritten. + expect(saved.draftKey).toMatch(/^draft:server-1:draft_/); + expect(saved.draftKey).not.toBe("agent:server-1:agent-1"); + expect(saved.draft.text).toContain("# Plan"); + expect(saved.draft.text).toContain("agent-1"); + expect(saved.draft.attachments).toEqual([]); + + const [navigation] = harness.navigateToWorkspace.mock.calls[0] as [ + { + serverId: string; + workspaceId: string; + target: { kind: string; draftId: string; setup: Record }; + }, + ]; + expect(navigation.serverId).toBe("server-1"); + expect(navigation.workspaceId).toBe("ws-1"); + expect(navigation.target.kind).toBe("draft"); + expect(saved.draftKey).toBe(`draft:server-1:${navigation.target.draftId}`); + expect(navigation.target.setup).toEqual({ + provider: "claude-work", + cwd: "/code/project", + model: "opus", + thinkingOptionId: "high", + modeId: null, + providerOptions: { "web-search": true }, + }); + + // Handing off drafts; it never sends. + expect(harness.sendMessage).not.toHaveBeenCalled(); + expect(handoffButton()?.disabled).toBe(true); + press(); + expect(harness.saveDraftInput).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/app/src/components/plan-handoff.ts b/packages/app/src/components/plan-handoff.ts new file mode 100644 index 00000000000..6020ccf46c9 --- /dev/null +++ b/packages/app/src/components/plan-handoff.ts @@ -0,0 +1,10 @@ +import { buildAgentDeepLink, type AgentDeepLinkTarget } from "@getpaseo/protocol/agent-deep-link"; + +/** Keep the source plan intact so the destination can inspect or edit it before sending. */ +export function buildPlanHandoffPrompt(input: { + plan: string; + source: AgentDeepLinkTarget; + instruction: string; +}): string { + return `${input.instruction}\n\n${input.plan}\n\nSource: ${buildAgentDeepLink(input.source)}`; +} diff --git a/packages/app/src/components/provider-account-sheet.tsx b/packages/app/src/components/provider-account-sheet.tsx new file mode 100644 index 00000000000..8c23b95792f --- /dev/null +++ b/packages/app/src/components/provider-account-sheet.tsx @@ -0,0 +1,412 @@ +import { + useCallback, + useMemo, + useSyncExternalStore, + type ComponentProps, + type ReactElement, +} from "react"; +import { useTranslation } from "react-i18next"; +import { Pressable, Text, View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { Plus, X } from "lucide-react-native"; +import type { MutableDaemonConfig, MutableDaemonConfigPatch } from "@getpaseo/protocol/messages"; +import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { Button } from "@/components/ui/button"; +import { Field, FormTextInput } from "@/components/ui/form-field"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { useProviderAccountFormModel } from "@/provider-accounts/use-provider-account-form-model"; +import type { + ProviderAccountEnvRow, + ProviderAccountFormModel, + ProviderAccountFormState, +} from "@/provider-accounts/provider-account-form-model"; +import type { Theme } from "@/styles/theme"; + +const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const ThemedX = withUnistyles(X, foregroundMutedColorMapping); +const ThemedPlus = withUnistyles(Plus, foregroundMutedColorMapping); +const ADD_VARIABLE_ICON = ; + +export interface ProviderAccountSaveInput { + providerId: string; + originalProviderId?: string; + patch: MutableDaemonConfigPatch; +} + +export interface ProviderAccountSheetProps { + visible: boolean; + baseProviderId: string; + baseProviderLabel: string; + existingProviderIds: readonly string[]; + account?: { + providerId: string; + config: MutableDaemonConfig["providers"][string]; + }; + /** Daemons without this migrate nothing on rename, so the sheet warns before you save. */ + supportsProviderConfigRename?: boolean; + onClose: () => void; + /** Resolves true when the account was written; the sheet then closes. */ + onSave: (input: ProviderAccountSaveInput) => Promise; +} + +export function ProviderAccountSheet(props: ProviderAccountSheetProps): ReactElement | null { + if (!props.visible) return null; + return ; +} + +function OpenProviderAccountSheet({ + visible, + baseProviderId, + baseProviderLabel, + existingProviderIds, + account, + supportsProviderConfigRename = false, + onClose, + onSave, +}: ProviderAccountSheetProps): ReactElement { + const { t } = useTranslation(); + const controlSize: NonNullable["size"]> = + useIsCompactFormFactor() ? "md" : "sm"; + const snapshot = useMemo( + () => ({ baseProviderId, baseProviderLabel, existingProviderIds, account }), + [account, baseProviderId, baseProviderLabel, existingProviderIds], + ); + const model = useProviderAccountFormModel(snapshot); + const state = useSyncExternalStore(model.subscribe, model.getState, model.getState); + + const handleSubmit = useCallback(async () => { + if (state.isSubmitting) return; + model.markSubmitAttempted(); + const patch = model.buildPatch(); + if (!patch) return; + + model.setSubmitting(true); + try { + const saved = await onSave({ + providerId: state.providerId.trim(), + originalProviderId: account?.providerId, + patch, + }); + if (saved) { + onClose(); + return; + } + } finally { + model.setSubmitting(false); + } + }, [account?.providerId, model, onClose, onSave, state.isSubmitting, state.providerId]); + + const handleSubmitPress = useCallback(() => { + void handleSubmit(); + }, [handleSubmit]); + + // Renaming an account on a daemon that can't migrate agents leaves those chats orphaned. + const showRenameWarning = + !supportsProviderConfigRename && + account !== undefined && + state.providerId.trim().length > 0 && + state.providerId.trim() !== account.providerId; + + const header = useMemo( + () => ({ + title: t( + state.isEditing + ? "settings.providers.account.editTitle" + : "settings.providers.account.title", + { provider: baseProviderLabel }, + ), + }), + [baseProviderLabel, state.isEditing, t], + ); + + const footer = useMemo( + () => ( + + + + + ), + [handleSubmitPress, onClose, state.isEditing, state.isSubmitting, t], + ); + + return ( + + + + + + + + + {showRenameWarning ? ( + + {t("settings.providers.account.warnings.renameUnsupported")} + + ) : null} + + + + + + + + {state.envRows.map((row, index) => ( + + ))} + + + + + ); +} + +type Translate = ReturnType["t"]; + +function resolveProviderIdError(state: ProviderAccountFormState, t: Translate): string | null { + switch (state.providerIdError) { + case "required": + return t("settings.providers.account.errors.idRequired"); + case "invalid": + return t("settings.providers.account.errors.idInvalid"); + case "taken": + return t("settings.providers.account.errors.idTaken"); + default: + return null; + } +} + +function resolveEnvError( + state: ProviderAccountFormState, + row: ProviderAccountEnvRow, + t: Translate, +): string | null { + switch (state.envErrors[row.id]) { + case "keyRequired": + return t("settings.providers.account.errors.envKeyRequired"); + case "duplicate": + return t("settings.providers.account.errors.envDuplicate"); + default: + return null; + } +} + +interface EnvVarRowProps { + row: ProviderAccountEnvRow; + index: number; + model: ProviderAccountFormModel; + controlSize: NonNullable["size"]>; + disabled: boolean; + error: string | null; +} + +function EnvVarRow({ + row, + index, + model, + controlSize, + disabled, + error, +}: EnvVarRowProps): ReactElement { + const { t } = useTranslation(); + const handleKeyChange = useCallback( + (value: string) => { + model.setEnvKey(row.id, value); + }, + [model, row.id], + ); + const handleValueChange = useCallback( + (value: string) => { + model.setEnvValue(row.id, value); + }, + [model, row.id], + ); + const handleRemove = useCallback(() => { + model.removeEnvRow(row.id); + }, [model, row.id]); + + return ( + + + + + + + + + + + + + {error ? {error} : null} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + footer: { + flex: 1, + flexDirection: "row", + gap: theme.spacing[3], + }, + footerButton: { + flex: 1, + }, + envRows: { + gap: theme.spacing[2], + }, + envRowGroup: { + gap: theme.spacing[1], + }, + envRow: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, + envKeyField: { + flex: 1, + minWidth: 0, + }, + envValueField: { + flex: 1, + minWidth: 0, + }, + envRemoveButton: { + width: 28, + height: 28, + alignItems: "center", + justifyContent: "center", + borderRadius: theme.borderRadius.lg, + }, + renameWarning: { + color: theme.colors.palette.amber[500], + fontSize: theme.fontSize.sm, + lineHeight: Math.round(theme.fontSize.sm * 1.4), + marginTop: -theme.spacing[1], + }, + envRowError: { + color: theme.colors.palette.red[300], + fontSize: theme.fontSize.sm, + lineHeight: Math.round(theme.fontSize.sm * 1.4), + }, + addEnvButton: { + alignSelf: "flex-start", + }, +})); diff --git a/packages/app/src/components/provider-icon-name.test.ts b/packages/app/src/components/provider-icon-name.test.ts index 00839266272..e7f8190014f 100644 --- a/packages/app/src/components/provider-icon-name.test.ts +++ b/packages/app/src/components/provider-icon-name.test.ts @@ -58,3 +58,18 @@ describe("known provider icon names", () => { } }); }); + +it("resolves account icons through their configured base without shadowing real providers", () => { + expect(resolveProviderIconName("claude-work", undefined, "claude")).toEqual({ + kind: "builtin", + id: "claude", + }); + expect(resolveProviderIconName("gemini-work", undefined, "gemini")).toEqual({ + kind: "catalog", + id: "gemini", + }); + expect(resolveProviderIconName("codex", undefined, "claude")).toEqual({ + kind: "builtin", + id: "codex", + }); +}); diff --git a/packages/app/src/components/provider-icon-name.ts b/packages/app/src/components/provider-icon-name.ts index 38d4344cd14..bc4c53beb0b 100644 --- a/packages/app/src/components/provider-icon-name.ts +++ b/packages/app/src/components/provider-icon-name.ts @@ -11,7 +11,11 @@ export type ProviderIconName = const BUILTIN_PROVIDER_IDS = new Set(BUILTIN_PROVIDER_ICON_NAMES); const KNOWN_PROVIDER_IDS = new Set(KNOWN_PROVIDER_ICON_NAMES); -export function resolveProviderIconName(provider: string, iconSvg?: string): ProviderIconName { +export function resolveProviderIconName( + provider: string, + iconSvg?: string, + baseProviderId?: string, +): ProviderIconName { if (BUILTIN_PROVIDER_IDS.has(provider)) { return { kind: "builtin", id: provider }; } @@ -21,5 +25,7 @@ export function resolveProviderIconName(provider: string, iconSvg?: string): Pro if (KNOWN_PROVIDER_IDS.has(provider)) { return { kind: "catalog", id: provider }; } - return { kind: "bot" }; + return baseProviderId && baseProviderId !== provider + ? resolveProviderIconName(baseProviderId) + : { kind: "bot" }; } diff --git a/packages/app/src/components/provider-icons.ts b/packages/app/src/components/provider-icons.ts index 995c0876da4..d7f1a628c83 100644 --- a/packages/app/src/components/provider-icons.ts +++ b/packages/app/src/components/provider-icons.ts @@ -1,5 +1,5 @@ import { useStore } from "zustand"; -import { providerSnapshotIcons } from "@/data/provider-icons"; +import { providerSnapshotIconAliases, providerSnapshotIcons } from "@/data/provider-icons"; import { Bot } from "lucide-react-native"; import { createElement, useCallback, type ComponentType } from "react"; import { SvgXml } from "react-native-svg"; @@ -86,8 +86,12 @@ function getSnapshotProviderIcon(provider: string, svg: string): ProviderIconCom return component; } -function resolveProviderIcon(provider: string, svg?: string): ProviderIconComponent { - const name = resolveProviderIconName(provider, svg); +function resolveProviderIcon( + provider: string, + svg?: string, + baseProviderId?: string, +): ProviderIconComponent { + const name = resolveProviderIconName(provider, svg, baseProviderId); if (name.kind === "builtin") { return BUILTIN_PROVIDER_ICONS[name.id]; } @@ -104,7 +108,10 @@ export function useProviderIcon(provider: string, serverId?: string | null): Pro const svg = useStore(providerSnapshotIcons, (state) => serverId ? state.get(serverId)?.get(provider) : undefined, ); - return resolveProviderIcon(provider, svg); + const base = useStore(providerSnapshotIconAliases, (state) => + serverId ? state.get(serverId)?.get(provider) : undefined, + ); + return resolveProviderIcon(provider, svg, base); } /** Subscribe once for consumers that render a collection of providers. */ @@ -112,8 +119,12 @@ export function useProviderIcons(serverId?: string | null) { const icons = useStore(providerSnapshotIcons, (state) => serverId ? state.get(serverId) : undefined, ); + const aliases = useStore(providerSnapshotIconAliases, (state) => + serverId ? state.get(serverId) : undefined, + ); return useCallback( - (provider: string) => resolveProviderIcon(provider, icons?.get(provider)), - [icons], + (provider: string) => + resolveProviderIcon(provider, icons?.get(provider), aliases?.get(provider)), + [icons, aliases], ); } diff --git a/packages/app/src/components/realtime-voice-overlay.test.tsx b/packages/app/src/components/realtime-voice-overlay.test.tsx new file mode 100644 index 00000000000..8bdf287c604 --- /dev/null +++ b/packages/app/src/components/realtime-voice-overlay.test.tsx @@ -0,0 +1,116 @@ +/** @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 88b2e378b41..fef244eadca 100644 --- a/packages/app/src/components/realtime-voice-overlay.tsx +++ b/packages/app/src/components/realtime-voice-overlay.tsx @@ -1,30 +1,65 @@ import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { Pressable, View } from "react-native"; -import { StyleSheet, useUnistyles } from "react-native-unistyles"; -import { Mic, MicOff, Square } from "lucide-react-native"; +import { Pressable, Text, View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { Mic, MicOff, PhoneOff, 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( @@ -40,8 +75,26 @@ 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 ? ( - + ) : ( - + )} @@ -76,14 +147,9 @@ export function RealtimeVoiceOverlay({ style={stopButtonStyle} > {isSwitching ? ( - + ) : ( - + )} @@ -105,8 +171,23 @@ const styles = StyleSheet.create((theme) => ({ borderWidth: theme.borderWidth[1], borderColor: theme.colors.border, }, - meterContainer: { + 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: { alignItems: "center", justifyContent: "center", }, diff --git a/packages/app/src/components/sidebar-workspace-list.tsx b/packages/app/src/components/sidebar-workspace-list.tsx index 5e41741a5e7..8c2c7997b06 100644 --- a/packages/app/src/components/sidebar-workspace-list.tsx +++ b/packages/app/src/components/sidebar-workspace-list.tsx @@ -1,4 +1,5 @@ import { LoadingSpinner } from "@/components/ui/loading-spinner"; +import { ProjectPullRequestsShortcut } from "@/screens/project-pull-requests/shortcut"; import { View, Text, @@ -63,7 +64,7 @@ import { } from "@/utils/host-routes"; import { shouldShowSidebarHostLabels, - useSidebarProjectStatusBucket, + useSidebarProjectStatus, type SidebarProjectEntry, type SidebarWorkspaceEntry, type SidebarWorkspacePlacement, @@ -248,6 +249,7 @@ interface ProjectHeaderRowProps { displayName: string; iconDataUri: string | null; statusBucket: SidebarStateBucket | null; + statusEnteredAt?: number | null; selected?: boolean; chevron: "expand" | "collapse" | null; onPress: () => void; @@ -408,6 +410,7 @@ const prBadgeStyles = StyleSheet.create((theme) => ({ function ProjectRowTrailingActions({ projectViewKey, + canBrowsePullRequests, displayName, worktreeTarget, settingsTarget, @@ -420,6 +423,7 @@ function ProjectRowTrailingActions({ removeProjectStatus, }: { projectViewKey: string; + canBrowsePullRequests: boolean; displayName: string; worktreeTarget: SidebarProjectHostTarget | null; settingsTarget: { serverId: string; projectId: string } | null; @@ -434,6 +438,13 @@ function ProjectRowTrailingActions({ const actionsVisible = isHovered || platformIsNative || isMobileBreakpoint; return ( + {worktreeTarget && canBrowsePullRequests ? ( + + ) : null} {worktreeTarget ? ( - {showShortcutBadge && shortcutNumber !== null ? ( @@ -998,10 +998,11 @@ function ProjectHeaderRow({ ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref} onPointerEnter={handlePointerEnter} onPointerLeave={handlePointerLeave} + style={projectRowStyle({ pressed: isPressed })} > {rowChildren} + + host.serverId === worktreeTarget?.serverId && host.worktreeSupport !== "unsupported", + )} + projectViewKey={project.viewKey} + displayName={displayName} + worktreeTarget={worktreeTarget} + settingsTarget={settingsTarget} + projectPath={projectPath} + isHovered={isHovered} + isMobileBreakpoint={isMobileBreakpoint} + isProjectActive={isProjectActive} + onBeginWorkspaceSetup={handleBeginWorkspaceSetup} + onRemoveProject={onRemoveProject} + removeProjectStatus={removeProjectStatus} + /> ); } @@ -1023,11 +1041,12 @@ function ProjectHeaderRow({ ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref} onPointerEnter={handlePointerEnter} onPointerLeave={handlePointerLeave} + style={projectRowStyle({ pressed: isPressed })} > {rowChildren} + + host.serverId === worktreeTarget?.serverId && host.worktreeSupport !== "unsupported", + )} + projectViewKey={project.viewKey} + displayName={displayName} + worktreeTarget={worktreeTarget} + settingsTarget={settingsTarget} + projectPath={projectPath} + isHovered={isHovered} + isMobileBreakpoint={isMobileBreakpoint} + isProjectActive={isProjectActive} + onBeginWorkspaceSetup={handleBeginWorkspaceSetup} + onRemoveProject={onRemoveProject} + removeProjectStatus={removeProjectStatus} + /> ({ zIndex: 3, ...theme.shadow.md, }, + projectRowPressTarget: { + // Cover the row's vertical padding while trailing actions remain sibling targets. + marginVertical: -theme.spacing[2], + paddingVertical: theme.spacing[2], + flex: 1, + minWidth: 0, + alignSelf: "stretch", + justifyContent: "center", + }, projectRowLeft: { flexDirection: "row", alignItems: "center", diff --git a/packages/app/src/components/sidebar/project-leading-visual.tsx b/packages/app/src/components/sidebar/project-leading-visual.tsx index 1830e3fa10d..68b2a648e96 100644 --- a/packages/app/src/components/sidebar/project-leading-visual.tsx +++ b/packages/app/src/components/sidebar/project-leading-visual.tsx @@ -2,6 +2,8 @@ import { ActivityIndicator, View, type ViewStyle } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { useTranslation } from "react-i18next"; import { ChevronDown, ChevronRight, CircleAlert } from "lucide-react-native"; +import Animated from "react-native-reanimated"; +import { useStatusPulse } from "@/hooks/use-status-pulse"; import { ProjectIconView } from "@/components/project-icon-view"; import { getStatusBucketLabel } from "@/hooks/sidebar-status-view-model"; import { densityIconBox, densityIconProps } from "@/styles/density"; @@ -61,6 +63,7 @@ export function ProjectLeadingVisual({ displayName, iconDataUri, statusBucket, + statusEnteredAt, projectViewKey, backdrop, chevron = null, @@ -71,6 +74,7 @@ export function ProjectLeadingVisual({ iconDataUri: string | null; /** Aggregate status of the project's workspaces; null when it shouldn't be surfaced. */ statusBucket: SidebarStateBucket | null; + statusEnteredAt?: number | null; projectViewKey: string; /** The row's current background, so the status badge can knock out of it. */ backdrop: SidebarSurfaceBackdrop; @@ -100,6 +104,7 @@ export function ProjectLeadingVisual({ displayName={displayName} projectViewKey={projectViewKey} statusBucket={statusBucket} + statusEnteredAt={statusEnteredAt} backdrop={backdrop} /> ); @@ -115,6 +120,7 @@ export function ProjectStatusIndicator({ displayName, projectViewKey, statusBucket, + statusEnteredAt, backdrop, loading = false, testID, @@ -123,6 +129,7 @@ export function ProjectStatusIndicator({ displayName: string; projectViewKey: string; statusBucket: SidebarStateBucket | null; + statusEnteredAt?: number | null; /** The row's current background, so the status badge can knock out of it. */ backdrop: SidebarSurfaceBackdrop; loading?: boolean; @@ -157,6 +164,7 @@ export function ProjectStatusIndicator({ )} @@ -168,13 +176,16 @@ export function ProjectStatusIndicator({ function ProjectStatusBadge({ content, statusBucket, + statusEnteredAt, backdrop, }: { content: ProjectStatusBadgeContent; statusBucket: SidebarStateBucket; + statusEnteredAt?: number | null; backdrop: SidebarSurfaceBackdrop; }) { const { t } = useTranslation(); + const pulseStyle = useStatusPulse(statusBucket, statusEnteredAt); // Running skips the shell. The ring is wider than the 12pt shell and carries its own knockout, // so nesting it inside would clip it against the very thing that was meant to separate it from // the icon. It anchors to the same corner instead, growing around the centre the dot had. @@ -197,11 +208,13 @@ function ProjectStatusBadge({ style={[styles.statusBadge, getStatusBadgeBackdropStyle(backdrop)]} testID="project-status-badge" > - {content.kind === "alert" ? ( - - ) : ( - - )} + + {content.kind === "alert" ? ( + + ) : ( + + )} + ); } diff --git a/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx b/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx index ac872ffbd89..cf29e4021fc 100644 --- a/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx +++ b/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx @@ -413,7 +413,12 @@ export function SidebarWorkspaceContextMenu({ hostBadgeLabel, pullRequestLabel, serviceLabel: serviceSummary - ? t(workspaceServiceLabelKey(serviceSummary), { name: serviceSummary.name }) + ? [ + t(workspaceServiceLabelKey(serviceSummary), { name: serviceSummary.name }), + ...serviceSummary.otherScripts.map((name) => + t("sidebar.workspace.status.scriptRunning", { name }), + ), + ].join(", ") : null, t, }); diff --git a/packages/app/src/components/sidebar/sidebar-workspace-row-content.tsx b/packages/app/src/components/sidebar/sidebar-workspace-row-content.tsx index 710ac03e1b1..bf3d8c2adfa 100644 --- a/packages/app/src/components/sidebar/sidebar-workspace-row-content.tsx +++ b/packages/app/src/components/sidebar/sidebar-workspace-row-content.tsx @@ -2,6 +2,8 @@ import { memo, useMemo, useCallback, useState, type ReactNode } from "react"; import { Text, View, type ViewStyle } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native"; +import Animated from "react-native-reanimated"; +import { useStatusPulse } from "@/hooks/use-status-pulse"; import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual"; import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop"; import { @@ -152,6 +154,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte displayName={leadingProjectName} projectViewKey={workspace.projectViewKey} statusBucket={workspace.statusBucket} + statusEnteredAt={workspace.statusEnteredAt?.getTime()} backdrop={backdrop} loading={isLoading} testID={`sidebar-row-project-icon-${workspace.workspaceKey}`} @@ -159,6 +162,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte ) : ( + - + ); } if (bucket === "attention") { return ( - + - + ); } diff --git a/packages/app/src/components/sidebar/workspace-meta-row/index.tsx b/packages/app/src/components/sidebar/workspace-meta-row/index.tsx index d539fcf0648..1adb3bab65d 100644 --- a/packages/app/src/components/sidebar/workspace-meta-row/index.tsx +++ b/packages/app/src/components/sidebar/workspace-meta-row/index.tsx @@ -2,7 +2,7 @@ import { Fragment, useCallback, useState, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; import { Pressable, Text, View, type GestureResponderEvent } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { ExternalLink, Folder, GitBranch, Globe } from "lucide-react-native"; +import { ExternalLink, Folder, GitBranch, Globe, SquareTerminal } from "lucide-react-native"; import { workspaceLabelKey, type WorkspaceLabelDefinition, @@ -38,6 +38,7 @@ const ThemedExternalLink = withUnistyles(ExternalLink); const ThemedFolder = withUnistyles(Folder); const ThemedGitBranch = withUnistyles(GitBranch); const ThemedGlobe = withUnistyles(Globe); +const ThemedSquareTerminal = withUnistyles(SquareTerminal); /** Stable identity so a row without labels doesn't re-select its items on every render. */ const EMPTY_LABELS: readonly WorkspaceLabelDefinition[] = []; @@ -284,16 +285,29 @@ const CHECK_STATE_ACCESSIBLE_KEYS = { function ServiceItem({ summary }: { summary: WorkspaceServiceSummary }) { const { t } = useTranslation(); const unhealthy = summary.health === "unhealthy"; + const Icon = summary.type === "script" ? ThemedSquareTerminal : ThemedGlobe; return ( - + {summary.name} + {summary.otherScripts.map((name) => ( + + + + {name} + + + ))} ); } diff --git a/packages/app/src/components/sidebar/workspace-meta-row/meta-items.test.ts b/packages/app/src/components/sidebar/workspace-meta-row/meta-items.test.ts index d569ab6f3cf..6a5ba977f3f 100644 --- a/packages/app/src/components/sidebar/workspace-meta-row/meta-items.test.ts +++ b/packages/app/src/components/sidebar/workspace-meta-row/meta-items.test.ts @@ -14,7 +14,12 @@ const PR_HINT: PrHint = { checksStatus: "success", }; -const SERVICE: WorkspaceServiceSummary = { name: "web", health: null }; +const SERVICE: WorkspaceServiceSummary = { + name: "web", + health: null, + type: "service", + otherScripts: [], +}; const LABELS: WorkspaceLabelDefinition[] = [{ name: "Urgent", color: "red" }]; diff --git a/packages/app/src/components/sidebar/workspace-meta-row/service-summary.test.ts b/packages/app/src/components/sidebar/workspace-meta-row/service-summary.test.ts index 46147dae6e3..657c01ab69f 100644 --- a/packages/app/src/components/sidebar/workspace-meta-row/service-summary.test.ts +++ b/packages/app/src/components/sidebar/workspace-meta-row/service-summary.test.ts @@ -29,14 +29,35 @@ describe("selectWorkspaceServiceSummary", () => { expect(selectWorkspaceServiceSummary([script({ scriptName: "web" })])).toEqual({ name: "web", health: null, + type: "service", + otherScripts: [], }); }); - it("ignores plain commands entirely", () => { - // A test watcher running says nothing about whether the workspace is up. + it("includes running plain commands", () => { + expect(selectWorkspaceServiceSummary([script({ scriptName: "test", type: "script" })])).toEqual( + { name: "test", health: null, type: "script", otherScripts: [] }, + ); + }); + + it("keeps regular scripts visible alongside a service and qualifies nested package names", () => { expect( - selectWorkspaceServiceSummary([script({ scriptName: "test", type: "script" })]), - ).toBeNull(); + selectWorkspaceServiceSummary([ + script({ scriptName: "web", type: "service" }), + script({ scriptName: "build", type: "script" }), + script({ + scriptName: "package-id", + type: "script", + packageJson: { path: "packages/api/package.json", script: "build" }, + }), + script({ scriptName: "finished", type: "script", lifecycle: "stopped" }), + ]), + ).toEqual({ + name: "web", + health: null, + type: "service", + otherScripts: ["build", "packages/api/build"], + }); }); it("prefers an unhealthy service over a healthy one regardless of order", () => { @@ -45,7 +66,7 @@ describe("selectWorkspaceServiceSummary", () => { script({ scriptName: "web", health: "healthy" }), script({ scriptName: "api", health: "unhealthy" }), ]), - ).toEqual({ name: "api", health: "unhealthy" }); + ).toEqual({ name: "api", health: "unhealthy", type: "service", otherScripts: [] }); }); it("takes the first running service when none is failing", () => { @@ -54,7 +75,7 @@ describe("selectWorkspaceServiceSummary", () => { script({ scriptName: "web", health: "healthy" }), script({ scriptName: "api", health: null }), ]), - ).toEqual({ name: "web", health: "healthy" }); + ).toEqual({ name: "web", health: "healthy", type: "service", otherScripts: [] }); }); it("skips a stopped service to reach a running one", () => { @@ -63,20 +84,25 @@ describe("selectWorkspaceServiceSummary", () => { script({ scriptName: "web", lifecycle: "stopped" }), script({ scriptName: "api" }), ]), - ).toEqual({ name: "api", health: null }); + ).toEqual({ name: "api", health: null, type: "service", otherScripts: [] }); }); }); describe("workspaceServiceLabelKey", () => { it("names an unhealthy service differently from a running one", () => { - expect(workspaceServiceLabelKey({ name: "web", health: "unhealthy" })).toBe( - "workspace.status.serviceUnhealthy", - ); + expect( + workspaceServiceLabelKey({ + name: "web", + health: "unhealthy", + type: "service", + otherScripts: [], + }), + ).toBe("sidebar.workspace.status.serviceUnhealthy"); }); it.each([["healthy"], [null]] as const)("treats %s as simply running", (health) => { - expect(workspaceServiceLabelKey({ name: "web", health })).toBe( - "workspace.status.serviceRunning", - ); + expect( + workspaceServiceLabelKey({ name: "web", health, type: "service", otherScripts: [] }), + ).toBe("sidebar.workspace.status.serviceRunning"); }); }); diff --git a/packages/app/src/components/sidebar/workspace-meta-row/service-summary.ts b/packages/app/src/components/sidebar/workspace-meta-row/service-summary.ts index 78a2338f1cf..5df17cfea54 100644 --- a/packages/app/src/components/sidebar/workspace-meta-row/service-summary.ts +++ b/packages/app/src/components/sidebar/workspace-meta-row/service-summary.ts @@ -2,48 +2,47 @@ import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list" type WorkspaceScript = SidebarWorkspaceEntry["scripts"][number]; -/** - * The one running service a row reports, by name. - * - * Services only. A workspace also runs plain commands — test watchers, build steps — and those - * are not what the row is for: they start and finish on their own and say nothing about whether - * the workspace is up. The name rather than the port because the name is what you called it, and - * a row that reads "web" tells you more than one that reads ":3000". - */ export interface WorkspaceServiceSummary { name: string; health: WorkspaceScript["health"]; + type: "service" | "script"; + otherScripts: string[]; } -/** - * A workspace can run several services and the row has space for one, so a failing one wins: a - * healthy service is the unremarkable case and any of them will do to say "this is up", while an - * unhealthy one is the only thing on the line you would act on. - */ +/** Show one service (a failing one first) alongside every running regular script. */ export function selectWorkspaceServiceSummary( scripts: SidebarWorkspaceEntry["scripts"], ): WorkspaceServiceSummary | null { - let firstHealthy: WorkspaceServiceSummary | null = null; + let service: WorkspaceScript | null = null; + const commands: string[] = []; for (const script of scripts) { if (script.lifecycle !== "running") continue; - if ((script.type ?? "service") !== "service") continue; - - const summary: WorkspaceServiceSummary = { name: script.scriptName, health: script.health }; - if (script.health === "unhealthy") { - return summary; + if (script.type === "script") { + const packageJson = script.packageJson; + let name = script.scriptName; + if (packageJson) { + const directory = packageJson.path.slice(0, -"package.json".length); + name = directory ? `${directory}${packageJson.script}` : packageJson.script; + } + commands.push(name); + } else if (!service || script.health === "unhealthy") { + service = script; } - firstHealthy ??= summary; } - return firstHealthy; + if (service) + return { + name: service.scriptName, + health: service.health, + type: "service", + otherScripts: commands, + }; + const [name, ...otherScripts] = commands; + return name === undefined ? null : { name, health: null, type: "script", otherScripts }; } -/** - * The accessible name for a service, as a key both the meta row and the row's own accessibility - * label read. Health is the whole difference between them, so it is decided once here rather than - * at each call site. - */ export function workspaceServiceLabelKey(summary: WorkspaceServiceSummary): string { + if (summary.type === "script") return "sidebar.workspace.status.scriptRunning"; return summary.health === "unhealthy" - ? "workspace.status.serviceUnhealthy" - : "workspace.status.serviceRunning"; + ? "sidebar.workspace.status.serviceUnhealthy" + : "sidebar.workspace.status.serviceRunning"; } diff --git a/packages/app/src/components/terminal-emulator-contract.ts b/packages/app/src/components/terminal-emulator-contract.ts index b4e3dd93e16..1710cc7557a 100644 --- a/packages/app/src/components/terminal-emulator-contract.ts +++ b/packages/app/src/components/terminal-emulator-contract.ts @@ -24,6 +24,7 @@ export interface TerminalEmulatorHandle { copySelection: (clipboard: TerminalClipboardWriter) => Promise; clear: () => void; claimSize: () => void; + restoreSurface: () => void; showKeyboard: () => void; blur: () => void; } diff --git a/packages/app/src/components/terminal-emulator-native-grid.native.tsx b/packages/app/src/components/terminal-emulator-native-grid.native.tsx index ad71316f3ca..c500314f8ab 100644 --- a/packages/app/src/components/terminal-emulator-native-grid.native.tsx +++ b/packages/app/src/components/terminal-emulator-native-grid.native.tsx @@ -455,6 +455,7 @@ function NativeTerminalEmulator({ schedulePaint(); }, claimSize: claimActiveTerminalSize, + restoreSurface: claimActiveTerminalSize, showKeyboard: () => { inputRef.current?.showKeyboard(); claimActiveTerminalSizeForAction("showKeyboard"); diff --git a/packages/app/src/components/terminal-emulator.tsx b/packages/app/src/components/terminal-emulator.tsx index 7504843c54a..0330a088432 100644 --- a/packages/app/src/components/terminal-emulator.tsx +++ b/packages/app/src/components/terminal-emulator.tsx @@ -45,6 +45,7 @@ export interface TerminalEmulatorHandle { copySelection: (clipboard: TerminalClipboardWriter) => Promise; clear: () => void; claimSize: () => void; + restoreSurface: () => void; showKeyboard: () => void; blur: () => void; } @@ -267,6 +268,9 @@ export default function TerminalEmulator({ claimSize: () => { runtimeRef.current?.resize({ forceClaim: true, shouldClaim: true }); }, + restoreSurface: () => { + runtimeRef.current?.restoreSurface(); + }, showKeyboard: () => { runtimeRef.current?.resize({ forceClaim: true, shouldClaim: true }); runtimeRef.current?.focus(); @@ -299,6 +303,9 @@ export default function TerminalEmulator({ claimSize: () => { runtimeRef.current?.resize({ forceClaim: true, shouldClaim: true }); }, + restoreSurface: () => { + runtimeRef.current?.restoreSurface(); + }, showKeyboard: () => { runtimeRef.current?.resize({ forceClaim: true, shouldClaim: true }); runtimeRef.current?.focus(); diff --git a/packages/app/src/components/terminal-pane.tsx b/packages/app/src/components/terminal-pane.tsx index a841d70fa69..f1e1fc7cb50 100644 --- a/packages/app/src/components/terminal-pane.tsx +++ b/packages/app/src/components/terminal-pane.tsx @@ -444,6 +444,13 @@ export function TerminalPane({ [terminalStreamKey], ); + useEffect(() => { + if (!isTerminalPresented) { + return; + } + emulatorRef.current?.restoreSurface(); + }, [isTerminalPresented]); + useEffect(() => { if (isMobile || !isPaneFocused || !terminalId) { lastAutoFocusKeyRef.current = null; diff --git a/packages/app/src/components/ui/segmented-control.tsx b/packages/app/src/components/ui/segmented-control.tsx index 05d7fedec4e..918875ecbd3 100644 --- a/packages/app/src/components/ui/segmented-control.tsx +++ b/packages/app/src/components/ui/segmented-control.tsx @@ -26,7 +26,9 @@ interface SegmentedControlProps { onValueChange: (value: T) => void; size?: ControlSize; hideLabels?: boolean; + textWrap?: boolean; style?: StyleProp; + segmentStyle?: StyleProp; testID?: string; } @@ -51,7 +53,9 @@ export function SegmentedControl({ onValueChange, size: sizeProp, hideLabels = false, + textWrap = false, style, + segmentStyle, testID, }: SegmentedControlProps) { const containedSize = useContainedControlSize(); @@ -61,7 +65,10 @@ export function SegmentedControl({ md: { container: styles.containerMd, segment: styles.segmentMd, label: styles.labelMd }, }[size]; const containerSizeStyle = sizeStyles.container; - const segmentSizeStyle = sizeStyles.segment; + const segmentSizeStyle = useMemo( + () => [sizeStyles.segment, segmentStyle], + [sizeStyles.segment, segmentStyle], + ); const labelSizeStyle = sizeStyles.label; const iconSize = controlIconSize[size]; @@ -82,6 +89,7 @@ export function SegmentedControl({ isSelected={isSelected} iconSize={iconSize} hideLabels={hideLabels} + textWrap={textWrap} segmentSizeStyle={segmentSizeStyle} labelSizeStyle={labelSizeStyle} currentValue={value} @@ -98,6 +106,7 @@ function SegmentItem({ isSelected, iconSize, hideLabels, + textWrap, segmentSizeStyle, labelSizeStyle, currentValue, @@ -107,14 +116,20 @@ 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], - [labelSizeStyle, isSelected], + () => [ + styles.label, + labelSizeStyle, + isSelected && styles.labelSelected, + textWrap && styles.labelWrap, + ], + [labelSizeStyle, isSelected, textWrap], ); const handlePress = useCallback(() => { if (!option.disabled && option.value !== currentValue) { @@ -125,12 +140,13 @@ 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], + [isSelected, option.disabled, segmentSizeStyle, textWrap], ); const accessibilityState = useMemo( () => ({ selected: isSelected, disabled: option.disabled }), @@ -154,7 +170,7 @@ function SegmentItem({ /> ) : null} {hideLabels ? null : ( - + {option.label} )} @@ -220,5 +236,13 @@ 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 697f848a09a..28380e6acbd 100644 --- a/packages/app/src/composer/actions.test.ts +++ b/packages/app/src/composer/actions.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it, vi } from "vitest"; -import type { AgentAttachment, ForgeSearchItem } from "@getpaseo/protocol/messages"; +import type { + AgentAttachment, + AgentQueueSnapshot, + ForgeSearchItem, +} from "@getpaseo/protocol/messages"; import type { AttachmentMetadata, ComposerAttachment, @@ -20,20 +24,27 @@ 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, @@ -1041,6 +1052,460 @@ 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 f810ef19c6d..061a32ceae7 100644 --- a/packages/app/src/composer/actions.ts +++ b/packages/app/src/composer/actions.ts @@ -2,6 +2,12 @@ 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, @@ -15,6 +21,7 @@ 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"; @@ -24,6 +31,18 @@ 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 { @@ -436,3 +455,348 @@ 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/agent-controls/model-sheet.tsx b/packages/app/src/composer/agent-controls/model-sheet.tsx index c9da7d778e7..09306110371 100644 --- a/packages/app/src/composer/agent-controls/model-sheet.tsx +++ b/packages/app/src/composer/agent-controls/model-sheet.tsx @@ -22,7 +22,10 @@ import { AgentControlTrigger } from "@/composer/agent-controls/control"; import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph"; import { resolveModelTriggerLabels } from "@/composer/agent-controls/layout"; import { resolveModelSheetOpening } from "@/composer/agent-controls/model-sheet-flow"; -import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection"; +import { + resolveProviderIconId, + type ProviderSelectorProvider, +} from "@/provider-selection/provider-selection"; import { useIsCompactFormFactor } from "@/constants/layout"; import { isNative, isWeb } from "@/constants/platform"; import { readMeasuredWidth } from "@/hooks/use-container-width"; @@ -188,7 +191,7 @@ export function CompactModelSheet({ profiles, serverId, }); - const ModelIcon = useProviderIcon(selectedProvider, serverId); + const ModelIcon = useProviderIcon(resolveProviderIconId(providers, selectedProvider), serverId); const hasSelectedProvider = selectedProvider.trim().length > 0; const rootHeader = useMemo( () => ({ diff --git a/packages/app/src/composer/index.tsx b/packages/app/src/composer/index.tsx index 4b31c4e0c6a..b093b2c7fdc 100644 --- a/packages/app/src/composer/index.tsx +++ b/packages/app/src/composer/index.tsx @@ -47,8 +47,14 @@ import { usePointerCapabilities } from "@/hooks/pointer-capabilities"; import { useShallow } from "zustand/shallow"; import { ArrowUp, + ChevronDown, + ChevronUp, + MoreVertical, + RotateCcw, Square, Pencil, + Trash2, + X, AudioLines, CircleDot, FileText, @@ -87,6 +93,7 @@ import { encodeImages } from "@/utils/encode-images"; import { focusWithRetries } from "@/utils/web-focus"; import { cancelComposerAgent, + deleteQueuedComposerMessage, dispatchComposerAgentMessage, editQueuedComposerMessage, findForgeItemByOption, @@ -94,14 +101,32 @@ 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"; @@ -389,21 +414,47 @@ 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 } = - args; + const { + queuedMessages, + handleEditQueuedMessage, + handleSendQueuedNow, + editLabel, + sendNowLabel, + durable, + } = args; if (queuedMessages.length === 0) return null; return ( - {queuedMessages.map((item) => ( + {queuedMessages.map((item, index) => ( ))} @@ -685,6 +739,28 @@ 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({ @@ -693,6 +769,9 @@ function QueuedMessageRow({ onSendNow, editLabel, sendNowLabel, + isFirst, + isLast, + durable, }: QueuedMessageRowProps) { const handleEdit = useCallback(() => { onEdit(item.id); @@ -700,28 +779,137 @@ 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} - + + + {item.text} + + {stateBadge !== null || item.lastError ? ( + + {stateBadge} + {item.lastError && needsAttention ? ( + + {item.lastError} + + ) : null} + + ) : null} + - - - - - - + {durable && needsAttention ? ( + <> + + + + + + + + ) : ( + <> + {!item.deliveryState || item.deliveryState === "pending" ? ( + <> + + + + + + + + ) : null} + {durable ? ( + + + {({ hovered, open }) => ( + + )} + + + + {durable.labels.moveUp} + + + {durable.labels.moveDown} + + + + {durable.labels.remove} + + + + ) : null} + + )} ); @@ -1159,9 +1347,15 @@ function offersVoiceMode(input: { isVoiceModeForAgent: boolean; hasAgent: boolean; isAgentRunning: boolean; + supportsVoiceConcurrentInput: boolean; showVoice: boolean; }): boolean { - return input.showVoice && !input.isVoiceModeForAgent && input.hasAgent && !input.isAgentRunning; + return ( + input.showVoice && + !input.isVoiceModeForAgent && + input.hasAgent && + (!input.isAgentRunning || input.supportsVoiceConcurrentInput) + ); } function ComposerVoiceModeButton({ @@ -1367,6 +1561,23 @@ 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( @@ -1744,8 +1955,87 @@ 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, @@ -1754,18 +2044,21 @@ function ComposerContentImpl({ }); if (!result.queued) return; - replaceUserInput(""); - setSelectedAttachments([]); - resetSuppression(); - clearSentAttachments(queuedAttachments); + clearComposer(); }, [ agentId, + applyAgentQueueSnapshot, clearSentAttachments, + client, + queueOutbox, queueWriter, resetSuppression, + serverId, setSelectedAttachments, - replaceUserInput, + setUserInput, + supportsDurableQueue, + supportsForgeSearch, ], ); @@ -2050,6 +2343,33 @@ 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, @@ -2059,12 +2379,70 @@ function ComposerContentImpl({ replaceUserInput(result.text); setSelectedAttachments(result.attachments); }, - [agentId, queueWriter, replaceUserInput, setSelectedAttachments], + [ + agentId, + applyAgentQueueSnapshot, + client, + getAppliedQueueRevision, + handleQueuedMutationResult, + queueWriter, + replaceUserInput, + serverId, + setSelectedAttachments, + supportsDurableQueue, + ], ); 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, @@ -2078,7 +2456,152 @@ function ComposerContentImpl({ setSendError(result.errorMessage); } }, - [agentId, queueWriter, submitMessage, t], + [ + 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], ); const handleQueue = useCallback( @@ -2167,6 +2690,7 @@ function ComposerContentImpl({ isVoiceModeForAgent, hasAgent, isAgentRunning, + supportsVoiceConcurrentInput, showVoice: mode.showVoice, }) ? ( @@ -2191,6 +2715,7 @@ function ComposerContentImpl({ isVoiceSwitching, mode.showVoice, realtimeVoiceButtonStyle, + supportsVoiceConcurrentInput, t, voiceToggleKeys, ], @@ -2473,17 +2998,71 @@ function ComposerContentImpl({ ], ); - const queueList = useMemo( - () => - renderQueueTrack({ - queuedMessages, - handleEditQueuedMessage, - handleSendQueuedNow, - editLabel: t("composer.attachments.editQueuedMessage"), - sendNowLabel: t("composer.attachments.sendQueuedMessageNow"), - }), - [handleEditQueuedMessage, handleSendQueuedNow, queuedMessages, t], - ); + // 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 autocompleteConfiguration = useMemo( () => ({ @@ -2617,6 +3196,9 @@ function ComposerContentImpl({ voiceServerId={serverId} voiceAgentId={agentId} isAgentRunning={isAgentRunning} + supportsVoiceConcurrentInput={supportsVoiceConcurrentInput} + isCancellingAgent={isCancellingAgent} + onCancelAgent={handleCancelAgent} defaultSendBehavior={activeSendBehavior} sendShortcut={appSettings.sendShortcut} onQueue={handleQueue} @@ -2801,6 +3383,21 @@ 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", @@ -2826,6 +3423,12 @@ 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 a3ae8652ae8..7b53775e7f7 100644 --- a/packages/app/src/composer/input/input.tsx +++ b/packages/app/src/composer/input/input.tsx @@ -193,6 +193,12 @@ 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. */ @@ -623,6 +629,9 @@ function MessageInputOverlay({ onRetryFailedRecording, onDiscardFailedRecording, onRealtimeVoiceStop, + isAgentRunning, + isCancellingAgent, + onCancelAgent, }: { showDictationOverlay: boolean; showRealtimeOverlay: boolean; @@ -630,6 +639,8 @@ function MessageInputOverlay({ | { isMuted: boolean; isVoiceSwitching: boolean; + failure: import("@/voice/voice-failure").VoiceFailureKind | null; + lastInputStatus: import("@/voice/voice-runtime").VoiceInputStatus | null; toggleMute: () => void; } | null @@ -646,6 +657,9 @@ function MessageInputOverlay({ onRetryFailedRecording: () => void; onDiscardFailedRecording: () => void; onRealtimeVoiceStop: () => void; + isAgentRunning?: boolean; + isCancellingAgent?: boolean; + onCancelAgent?: () => void; }) { if (showDictationOverlay) { return ( @@ -669,8 +683,13 @@ function MessageInputOverlay({ ); } @@ -953,6 +972,7 @@ interface ToggleRealtimeVoiceContext { isConnected: boolean; disabled: boolean; isAgentRunning: boolean; + supportsVoiceConcurrentInput: boolean; handleStopRealtimeVoice: () => Promise | void; toast: { error: (msg: string) => void }; interruptBeforeVoiceMessage: string; @@ -968,7 +988,7 @@ function toggleRealtimeVoiceImpl(ctx: ToggleRealtimeVoiceContext): void { void ctx.handleStopRealtimeVoice(); return; } - if (ctx.isAgentRunning) { + if (ctx.isAgentRunning && !ctx.supportsVoiceConcurrentInput) { ctx.toast.error(ctx.interruptBeforeVoiceMessage); return; } @@ -1192,6 +1212,9 @@ 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; @@ -1240,6 +1263,9 @@ 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, @@ -1322,6 +1348,9 @@ export const MessageInput = forwardRef( voiceServerId, voiceAgentId, isAgentRunning, + supportsVoiceConcurrentInput, + isCancellingAgent, + onCancelAgent, defaultSendBehavior, sendShortcut, onQueue, @@ -1710,9 +1739,6 @@ export const MessageInput = forwardRef( await stopRealtimeVoice({ voice, isRealtimeVoiceForCurrentAgent, - isAgentRunning, - client, - voiceAgentId, }); } catch (error) { console.error("[MessageInput] Failed to stop realtime voice", error); @@ -1721,7 +1747,7 @@ export const MessageInput = forwardRef( toast.error(message); } } - }, [client, isAgentRunning, isRealtimeVoiceForCurrentAgent, toast, voice, voiceAgentId]); + }, [isRealtimeVoiceForCurrentAgent, toast, voice]); const handleToggleRealtimeVoiceShortcut = useCallback(() => { toggleRealtimeVoiceImpl({ @@ -1731,6 +1757,7 @@ export const MessageInput = forwardRef( isConnected, disabled, isAgentRunning, + supportsVoiceConcurrentInput, handleStopRealtimeVoice, toast, interruptBeforeVoiceMessage: t("composer.voice.interruptBeforeVoice"), @@ -1742,6 +1769,7 @@ export const MessageInput = forwardRef( exitFullscreen, isAgentRunning, isConnected, + supportsVoiceConcurrentInput, t, toast, voice, @@ -2297,6 +2325,9 @@ export const MessageInput = forwardRef( onRetryFailedRecording={handleRetryFailedRecording} onDiscardFailedRecording={handleDiscardFailedRecording} onRealtimeVoiceStop={handleRealtimeVoiceStop} + isAgentRunning={isAgentRunning} + isCancellingAgent={isCancellingAgent} + onCancelAgent={onCancelAgent} /> ), @@ -2318,6 +2349,9 @@ 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 ad492976b30..6cf1e13bde3 100644 --- a/packages/app/src/composer/input/state.test.ts +++ b/packages/app/src/composer/input/state.test.ts @@ -529,44 +529,17 @@ describe("resolveMessageInputEnterAction", () => { }); describe("stopRealtimeVoice", () => { - 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); + it("stops voice mode without cancelling the running agent", async () => { + const cancelAgent = vi.fn().mockResolvedValue(undefined); 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: async () => { - calls.push("stop voice"); - }, - }, + voice: { stopVoice }, isRealtimeVoiceForCurrentAgent: true, - isAgentRunning: true, - client: { - cancelAgent: async () => { - calls.push("cancel agent"); - }, - }, - voiceAgentId: "agent-1", }); - expect(calls).toEqual(["cancel agent", "stop voice"]); + expect(stopVoice).toHaveBeenCalled(); + expect(cancelAgent).not.toHaveBeenCalled(); }); }); diff --git a/packages/app/src/composer/input/state.ts b/packages/app/src/composer/input/state.ts index 67c80307451..2e9b368961b 100644 --- a/packages/app/src/composer/input/state.ts +++ b/packages/app/src/composer/input/state.ts @@ -42,9 +42,6 @@ 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 { @@ -223,13 +220,9 @@ export function runMessageInputKeyboardAction( export async function stopRealtimeVoice(ctx: StopRealtimeVoiceContext): Promise { if (!ctx.voice || !ctx.isRealtimeVoiceForCurrentAgent) return; - 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); - } - + // 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. await ctx.voice.stopVoice(); } diff --git a/packages/app/src/composer/queue-sync.test.ts b/packages/app/src/composer/queue-sync.test.ts new file mode 100644 index 00000000000..0962a02ee1f --- /dev/null +++ b/packages/app/src/composer/queue-sync.test.ts @@ -0,0 +1,204 @@ +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 new file mode 100644 index 00000000000..75608bc2523 --- /dev/null +++ b/packages/app/src/composer/queue-sync.ts @@ -0,0 +1,101 @@ +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 183b4ef479d..8932cf8abc3 100644 --- a/packages/app/src/contexts/session-context.tsx +++ b/packages/app/src/contexts/session-context.tsx @@ -17,6 +17,7 @@ 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, @@ -312,29 +313,33 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider useEffect(() => { const unregister = voiceRuntime?.registerSession({ serverId, - setVoiceMode: async (enabled, agentId) => { + setVoiceMode: async (enabled, agentId, input) => { if (!client) { throw new Error(t("common.errors.daemonUnavailable")); } - await client.setVoiceMode(enabled, agentId); + return client.setVoiceMode(enabled, agentId, input); }, - sendVoiceAudioChunk: async (audioData, mimeType) => { + sendVoiceAudioChunk: async (audioData, mimeType, transport) => { if (!client) { throw new Error(t("common.errors.daemonUnavailable")); } - await client.sendVoiceAudioChunk(audioData, mimeType); + await client.sendVoiceAudioChunk(audioData, mimeType, false, transport); }, - audioPlayed: async (chunkId) => { + audioPlayed: async (chunkId, error, transport) => { if (!client) { throw new Error(t("common.errors.daemonUnavailable")); } - await client.audioPlayed(chunkId); + await client.audioPlayed(chunkId, error, transport); }, - abortRequest: async () => { + readVoiceInputReceipts: async (input) => { + if (!client) throw new Error(t("common.errors.daemonUnavailable")); + return client.readVoiceInputReceipts(input); + }, + abortRequest: async (transport) => { if (!client) { throw new Error(t("common.errors.daemonUnavailable")); } - await client.abortRequest(); + await client.abortRequest(transport); }, setAssistantAudioPlaying: (isPlaying) => { setIsPlayingAudio(serverId, isPlaying); @@ -347,6 +352,44 @@ 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) { @@ -479,6 +522,9 @@ 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", ], @@ -513,6 +559,11 @@ 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); @@ -536,6 +587,20 @@ 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; } }); @@ -653,11 +718,18 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider if (message.type !== "transcription_result") return; const transcriptText = message.payload.text.trim(); - voiceRuntime?.onTranscriptionResult(serverId, transcriptText); + voiceRuntime?.onTranscriptionResult(serverId, transcriptText, message.payload); }); 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); }); @@ -687,6 +759,7 @@ 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 new file mode 100644 index 00000000000..248b260d0cf --- /dev/null +++ b/packages/app/src/contexts/session-queue-resume.test.tsx @@ -0,0 +1,248 @@ +/** + * @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 4c8d04e2f1b..54bf40ccf91 100644 --- a/packages/app/src/contexts/voice-context.tsx +++ b/packages/app/src/contexts/voice-context.tsx @@ -8,6 +8,8 @@ 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"; @@ -30,6 +32,8 @@ const EMPTY_SNAPSHOT: VoiceRuntimeSnapshot = { isVoiceMode: false, isVoiceSwitching: false, isMuted: false, + failure: null, + lastInputStatus: null, activeServerId: null, activeAgentId: null, }; @@ -115,6 +119,14 @@ 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; @@ -126,7 +138,9 @@ export function VoiceProvider({ children }: VoiceProviderProps) { runtime?.handleCaptureVolume(level); }, onInterruption: () => { - void runtime?.stopVoice().catch((error) => { + if (!runtime?.getSnapshot().isVoiceMode) return; + notifyMicrophoneLostRef.current(); + void runtime.handleMicrophoneLost().catch((error) => { console.error("[VoiceEngine] Failed to stop after audio interruption:", error); }); }, diff --git a/packages/app/src/data/provider-icons.ts b/packages/app/src/data/provider-icons.ts index 9556be7ab24..d4ef822425f 100644 --- a/packages/app/src/data/provider-icons.ts +++ b/packages/app/src/data/provider-icons.ts @@ -5,13 +5,23 @@ export const providerSnapshotIcons = createStore new Map(), ); +export const providerSnapshotIconAliases = createStore< + ReadonlyMap> +>(() => new Map()); + export function replaceProviderSnapshotIcons( serverId: string, - entries: readonly Pick[], + entries: readonly Pick[], ): void { const icons = new Map(); + const aliases = new Map(); for (const entry of entries) { + if (entry.baseProviderId) aliases.set(entry.provider, entry.baseProviderId); if (entry.iconSvg) icons.set(entry.provider, entry.iconSvg); } + providerSnapshotIconAliases.setState( + (previous) => new Map(previous).set(serverId, aliases), + true, + ); providerSnapshotIcons.setState((previous) => new Map(previous).set(serverId, icons), true); } diff --git a/packages/app/src/file-panels/source/file-actions.tsx b/packages/app/src/file-panels/source/file-actions.tsx new file mode 100644 index 00000000000..29c40c4f338 --- /dev/null +++ b/packages/app/src/file-panels/source/file-actions.tsx @@ -0,0 +1,83 @@ +import { useWorkspace } from "@getpaseo/plugin/client"; +import { useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import * as Clipboard from "expo-clipboard"; +import { Copy } from "lucide-react-native"; +import { withUnistyles } from "react-native-unistyles"; +import { FileActionsContextMenuContent } from "@/components/file-actions-menu"; +import { DropdownMenu } from "@/components/ui/dropdown-menu"; +import { LoadingSpinner } from "@/components/ui/loading-spinner"; +import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { useToast } from "@/contexts/toast-context"; +import type { DismissToast } from "@/components/toast-host"; +import { useStableEvent } from "@/hooks/use-stable-event"; +import type { Theme } from "@/styles/theme"; +import { resolveWorkspaceFilePaths } from "@/workspace/file-open"; + +const ThemedCopy = withUnistyles(Copy); +const ThemedSpinner = withUnistyles(LoadingSpinner); +const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); + +/** The same path actions as Explorer, directly accessible from the file viewer. */ +export function FilePathActions({ path, workspaceId }: { path: string; workspaceId: string }) { + const { t } = useTranslation(); + const toast = useToast(); + const compact = useIsCompactFormFactor(); + const workspaceRoot = useWorkspace(workspaceId, (workspace) => workspace.directory); + const paths = workspaceRoot ? resolveWorkspaceFilePaths({ path, workspaceRoot }) : null; + const relativePath = paths?.relativePath; + const [pending, setPending] = useState(false); + const copying = useRef(false); + const dismissError = useRef(null); + + const copy = useStableEvent(async (value: string) => { + if (copying.current) return; + copying.current = true; + setPending(true); + dismissError.current?.(); + try { + const copied = await Clipboard.setStringAsync(value); + if (!copied) throw new Error("Clipboard write failed"); + toast.copied(t("workspace.tabs.toasts.filePathCopiedLabel")); + } catch { + dismissError.current = toast.show(t("workspace.tabs.toasts.copyFailed"), { + variant: "error", + durationMs: null, + }); + } finally { + copying.current = false; + setPending(false); + } + }); + const copyPath = useStableEvent(() => { + void copy(path); + }); + const copyRelativePath = useStableEvent(() => { + if (relativePath) void copy(relativePath); + }); + const iconSize = paneContentToolbarIconSize(compact); + + return ( + + + {pending ? ( + + ) : ( + + )} + + + + ); +} diff --git a/packages/app/src/file-panels/source/panel.tsx b/packages/app/src/file-panels/source/panel.tsx index 906719bce6f..53308d9617b 100644 --- a/packages/app/src/file-panels/source/panel.tsx +++ b/packages/app/src/file-panels/source/panel.tsx @@ -134,6 +134,8 @@ function ReadonlyTextFile({ return ( ) : null} + {conflict ? : null} diff --git a/packages/app/src/git/use-forge-search-query.test.ts b/packages/app/src/git/use-forge-search-query.test.ts index 5cc800a9b4b..81ab219ea13 100644 --- a/packages/app/src/git/use-forge-search-query.test.ts +++ b/packages/app/src/git/use-forge-search-query.test.ts @@ -35,6 +35,28 @@ describe("forgeSearchQueryKey", () => { }); describe("buildForgeSearchQueryOptions", () => { + it("lists a project's open change requests with a bounded blank query", async () => { + const requests: unknown[] = []; + const query = buildForgeSearchQueryOptions({ + client: { + async searchForge(options) { + requests.push(options); + return { items: [], authState: "authenticated", error: null, requestId: "request-1" }; + }, + }, + serverId: "server-1", + cwd: "/project", + query: "", + kinds: ["change_request"], + limit: 20, + enabled: true, + supportsForgeSearch: true, + }); + await query.queryFn(); + expect(requests).toEqual([ + { cwd: "/project", query: "", limit: 20, kinds: ["change_request"] }, + ]); + }); it("forwards kinds to the forge search request when specified", async () => { const requests: unknown[] = []; const query = buildForgeSearchQueryOptions({ diff --git a/packages/app/src/git/use-forge-search-query.ts b/packages/app/src/git/use-forge-search-query.ts index 9839828bf88..6ae1634387a 100644 --- a/packages/app/src/git/use-forge-search-query.ts +++ b/packages/app/src/git/use-forge-search-query.ts @@ -49,6 +49,7 @@ export interface ForgeSearchClient { type LegacyGitHubSearchKind = "github-issue" | "github-pr"; interface ForgeSearchQueryInput { + limit?: number; client: ForgeSearchClient | null; serverId: string; cwd: string; @@ -85,7 +86,10 @@ export function buildForgeSearchQueryOptions(input: ForgeSearchQueryInput) { const transport = input.supportsForgeSearch === true ? "forge" : "github"; return { - queryKey: forgeSearchQueryKey(input.serverId, input.cwd, query, input.kinds, transport), + queryKey: [ + ...forgeSearchQueryKey(input.serverId, input.cwd, query, input.kinds, transport), + ...(input.limit ? [input.limit] : []), + ], queryFn: async (): Promise => { if (!input.client) { throw new Error( @@ -93,8 +97,8 @@ export function buildForgeSearchQueryOptions(input: ForgeSearchQueryInput) { ); } const request = input.kinds - ? { cwd: input.cwd, query, limit: 20, kinds: input.kinds } - : { cwd: input.cwd, query, limit: 20 }; + ? { cwd: input.cwd, query, limit: input.limit ?? 20, kinds: input.kinds } + : { cwd: input.cwd, query, limit: input.limit ?? 20 }; // COMPAT(githubSearchRpc): use the legacy GitHub RPC with daemons that // predate forge.search.*. Remove after 2027-01-17 once the supported // daemon floor is >= v0.2.0. diff --git a/packages/app/src/hooks/sidebar-workspaces-view-model.test.ts b/packages/app/src/hooks/sidebar-workspaces-view-model.test.ts index 7aa85c1fafa..b2c7d550d03 100644 --- a/packages/app/src/hooks/sidebar-workspaces-view-model.test.ts +++ b/packages/app/src/hooks/sidebar-workspaces-view-model.test.ts @@ -11,6 +11,7 @@ import { computeSidebarOrderUpdates, createSidebarWorkspacePlacementSelector, createSidebarWorkspaceEntry, + deriveProjectStatus, deriveProjectStatusBucket, deriveSidebarLoadingState, shouldShowSidebarHostLabels, @@ -996,3 +997,17 @@ it("prepends newly discovered manual workspaces without dropping filtered saved computeSidebarOrderUpdates({ projects, persistedProjectOrder: ["p"] }).workspaceOrders, ).toEqual([]); }); + +it("uses the newest timestamp only among workspaces matching the project badge", () => { + const older = { ...projectWorkspace("older", "needs_input"), statusEnteredAt: new Date(1000) }; + const newer = { ...projectWorkspace("newer", "needs_input"), statusEnteredAt: new Date(2000) }; + const unread = { ...projectWorkspace("unread", "attention"), statusEnteredAt: new Date(3000) }; + expect( + deriveProjectStatus({ + workspaces: [older, newer, unread].map((entry) => + workspacePlacement({ workspaceId: entry.id }), + ), + sessions: { srv: sessionWith({ workspaces: [older, newer, unread] }) }, + }), + ).toEqual({ bucket: "needs_input", enteredAt: 2000 }); +}); diff --git a/packages/app/src/hooks/sidebar-workspaces-view-model.ts b/packages/app/src/hooks/sidebar-workspaces-view-model.ts index da1086da458..1559ebcf67b 100644 --- a/packages/app/src/hooks/sidebar-workspaces-view-model.ts +++ b/packages/app/src/hooks/sidebar-workspaces-view-model.ts @@ -199,11 +199,17 @@ export interface ProjectStatusSession { * activity-index + effective-status pipeline as per-workspace rows (one pass over the * session's agents per server, not per workspace) rather than re-deriving it. */ -export function deriveProjectStatusBucket(input: { +export function deriveProjectStatusBucket( + input: Parameters[0], +): SidebarStateBucket { + return deriveProjectStatus(input).bucket; +} + +export function deriveProjectStatus(input: { workspaces: readonly SidebarWorkspacePlacement[]; sessions: Record; pendingCreateAttempts?: Record; -}): SidebarStateBucket { +}): { bucket: SidebarStateBucket; enteredAt: number | null } { const workspaceIdsByServer = new Map(); for (const placement of input.workspaces) { const existing = workspaceIdsByServer.get(placement.serverId); @@ -214,7 +220,7 @@ export function deriveProjectStatusBucket(input: { } } - const buckets: SidebarStateBucket[] = []; + const statuses: ReturnType[] = []; for (const [serverId, workspaceIds] of workspaceIdsByServer) { const session = input.sessions[serverId]; if (!session) continue; @@ -225,18 +231,26 @@ export function deriveProjectStatusBucket(input: { }); const workspace = workspaceKey ? session.workspaces.get(workspaceKey) : undefined; if (!workspace) continue; - buckets.push( + statuses.push( deriveEffectiveWorkspaceStatus({ serverId, workspace, pendingCreateAttempts: input.pendingCreateAttempts, workspaceAgentActivity: session.workspaceAgentActivity, - }).status, + }), ); } } - return aggregateSidebarStateBuckets(buckets); + const bucket = aggregateSidebarStateBuckets(statuses.map((status) => status.status)); + let enteredAt: number | null = null; + for (const status of statuses) { + const timestamp = status.enteredAt?.getTime(); + if (status.status === bucket && timestamp != null && Number.isFinite(timestamp)) { + enteredAt = Math.max(enteredAt ?? timestamp, timestamp); + } + } + return { bucket, enteredAt }; } /** One bounded projection per sidebar; unchanged placements survive project reordering. */ diff --git a/packages/app/src/hooks/use-sidebar-workspaces-list.ts b/packages/app/src/hooks/use-sidebar-workspaces-list.ts index 378c4b48622..67a47f23a90 100644 --- a/packages/app/src/hooks/use-sidebar-workspaces-list.ts +++ b/packages/app/src/hooks/use-sidebar-workspaces-list.ts @@ -1,5 +1,6 @@ import { useHostFeatureMap } from "@/runtime/host-features"; import { useCallback, useEffect, useMemo } from "react"; +import { shallow } from "zustand/shallow"; import { useStoreWithEqualityFn } from "zustand/traditional"; import { useCreateFlowStore } from "@/stores/create-flow-store"; import { useSessionStore } from "@/stores/session-store"; @@ -13,15 +14,13 @@ import { createSidebarWorkspacePlacementSelector, computeSidebarOrderUpdates, createSidebarWorkspaceEntry, - deriveProjectStatusBucket, + deriveProjectStatus, deriveSidebarLoadingState, type ProjectStatusSession, type SidebarProjectEntry, type SidebarWorkspaceEntry, type SidebarWorkspacePlacement, } from "./sidebar-workspaces-view-model"; -import type { SidebarStateBucket } from "@/utils/sidebar-agent-state"; - export { appendMissingOrderKeys, applyStoredOrdering, @@ -30,7 +29,7 @@ export { createSidebarWorkspaceEntry, buildSidebarWorkspacePlacementModel, computeSidebarOrderUpdates, - deriveProjectStatusBucket, + deriveProjectStatus, deriveSidebarLoadingState, shouldShowSidebarHostLabels, type SidebarLoadingState, @@ -48,16 +47,16 @@ export { * * `SidebarProjectEntry` is structural — it carries workspace identity but no status — and * `ProjectBlock` is memoized on that stable reference, so the row can't learn about a - * child's status without its own subscription. Returns a primitive, so status churn in a - * project only re-renders the row when the aggregate actually moves. + * child's status without its own subscription. Compares the bucket and timestamp, so status + * churn in a project only re-renders the row when its aggregate status changes. * * Pass `enabled: false` while the project is expanded: the child rows show their own dots * and the selector is pure cost. */ -export function useSidebarProjectStatusBucket(input: { +export function useSidebarProjectStatus(input: { workspaces: readonly SidebarWorkspacePlacement[]; enabled: boolean; -}): SidebarStateBucket | null { +}): ReturnType | null { const { workspaces, enabled } = input; const pendingCreateAttempts = useStoreWithEqualityFn( useCreateFlowStore, @@ -68,7 +67,7 @@ export function useSidebarProjectStatusBucket(input: { const selector = useCallback( (state: { sessions: Record }) => { if (!enabled) return null; - return deriveProjectStatusBucket({ + return deriveProjectStatus({ workspaces, sessions: state.sessions, pendingCreateAttempts, @@ -77,7 +76,7 @@ export function useSidebarProjectStatusBucket(input: { [enabled, pendingCreateAttempts, workspaces], ); - return useStoreWithEqualityFn(useSessionStore, selector, Object.is); + return useStoreWithEqualityFn(useSessionStore, selector, shallow); } const EMPTY_ORDER: string[] = []; diff --git a/packages/app/src/hooks/use-status-pulse.browser.test.tsx b/packages/app/src/hooks/use-status-pulse.browser.test.tsx new file mode 100644 index 00000000000..0bc9c95ef5d --- /dev/null +++ b/packages/app/src/hooks/use-status-pulse.browser.test.tsx @@ -0,0 +1,96 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import Animated from "react-native-reanimated"; +import { afterEach, expect, it, vi } from "vitest"; +import { useStatusPulse } from "./use-status-pulse"; +import type { SidebarStateBucket } from "@/utils/sidebar-agent-state"; + +// Only the OS preference is substituted; the browser runs the real animation. +const preference = vi.hoisted(() => ({ reduced: false })); +vi.mock("react-native-reanimated", async (importOriginal) => ({ + ...(await importOriginal()), + useReducedMotion: () => preference.reduced, +})); + +// Metro resolves these CommonJS imports; Vite's unbundled Reanimated path does not. +vi.mock("react-native-reanimated/lib/module/ReanimatedModule/js-reanimated/webUtils", async () => { + const compiler = await vi.importActual<{ default: unknown }>( + "react-native-web/dist/exports/StyleSheet/compiler/createReactDOMStyle", + ); + const preprocess = await vi.importActual>( + "react-native-web/dist/exports/StyleSheet/preprocess", + ); + return { + createReactDOMStyle: compiler.default, + createTransformValue: preprocess.createTransformValue, + createTextShadowValue: preprocess.createTextShadowValue, + }; +}); + +let root: Root | undefined; +let container: HTMLDivElement; + +function Badge({ bucket, timestamp }: { bucket: SidebarStateBucket; timestamp?: number }) { + const style = useStatusPulse(bucket, timestamp); + return ; +} + +function render(bucket: SidebarStateBucket, timestamp?: number) { + if (!root) { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + } + act(() => root?.render()); +} + +function opacity() { + const badge = container.querySelector('[data-testid="badge"]'); + if (!badge) throw new Error("Missing badge"); + return Number(getComputedStyle(badge).opacity); +} + +afterEach(() => { + act(() => root?.unmount()); + root = undefined; + container.remove(); + preference.reduced = false; +}); + +it("pulses recent attention, expires at its original deadline, and stays solid after remount", async () => { + const timestamp = Date.now() - 58_500; + render("attention", timestamp); + await expect.poll(opacity).toBeLessThan(0.9); + await expect.poll(opacity, { timeout: 2500 }).toBe(1); + act(() => root?.unmount()); + root = undefined; + container.remove(); + render("attention", timestamp); + expect(opacity()).toBe(1); +}); + +it("stops when the state clears and starts for a new question", async () => { + const timestamp = Date.now(); + render("needs_input", timestamp); + await expect.poll(opacity).toBeLessThan(0.9); + render("done", timestamp); + await expect.poll(opacity).toBe(1); + render("needs_input", Date.now()); + await expect.poll(opacity).toBeLessThan(0.9); +}); + +it.each([undefined, Number.NaN, Date.now() - 120_000])( + "keeps absent, invalid, and old timestamps solid (%s)", + async (timestamp) => { + render("attention", timestamp); + await new Promise((resolve) => setTimeout(resolve, 850)); + expect(opacity()).toBe(1); + }, +); + +it("keeps recent badges solid with reduced motion", async () => { + preference.reduced = true; + render("needs_input", Date.now()); + await new Promise((resolve) => setTimeout(resolve, 850)); + expect(opacity()).toBe(1); +}); diff --git a/packages/app/src/hooks/use-status-pulse.ts b/packages/app/src/hooks/use-status-pulse.ts new file mode 100644 index 00000000000..41a2df1b77d --- /dev/null +++ b/packages/app/src/hooks/use-status-pulse.ts @@ -0,0 +1,46 @@ +import { useEffect } from "react"; +import { + cancelAnimation, + Easing, + useAnimatedStyle, + useReducedMotion, + useSharedValue, + withRepeat, + withTiming, +} from "react-native-reanimated"; +import { useRetainedPanelActive } from "@/components/retained-panel"; +import type { SidebarStateBucket } from "@/utils/sidebar-agent-state"; + +export function useStatusPulse(bucket: SidebarStateBucket | null, enteredAt?: number | null) { + const opacity = useSharedValue(1); + const reduceMotion = useReducedMotion(); + const active = useRetainedPanelActive(); + + useEffect(() => { + cancelAnimation(opacity); + opacity.value = 1; + const eligible = bucket === "attention" || bucket === "needs_input"; + if (!eligible || !active || reduceMotion || enteredAt == null || !Number.isFinite(enteredAt)) { + return; + } + const remaining = enteredAt + 60_000 - Date.now(); + if (remaining <= 0) return; + + opacity.value = withRepeat( + withTiming(0.45, { duration: 750, easing: Easing.inOut(Easing.ease) }), + -1, + true, + ); + const stop = () => { + cancelAnimation(opacity); + opacity.value = 1; + }; + const timeout = setTimeout(stop, remaining); + return () => { + clearTimeout(timeout); + stop(); + }; + }, [active, bucket, enteredAt, opacity, reduceMotion]); + + return useAnimatedStyle(() => ({ opacity: opacity.value }), [opacity]); +} diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index db2954f172c..b4c7b29d340 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -18,6 +18,7 @@ export const ar: TranslationResources = { title: "بحث", placeholder: "بحث في اللوحة", + updateHost: "حدّث المضيف لاستخدام البحث", close: "إغلاق البحث", matches: "نتائج البحث", previous: "التطابق السابق", @@ -189,7 +190,7 @@ export const ar: TranslationResources = { unmuteVoice: "إلغاء كتم الصوت", muteVoice: "كتم الصوت", dictation: "الإملاء", - interruptBeforeVoice: "قم بمقاطعة الوكيل قبل بدء الوضع الصوتي", + interruptBeforeVoice: "حدّث المضيف لاستخدام الصوت أثناء عمل الوكيل", }, attachments: { addImage: "أضف صورة", @@ -223,6 +224,20 @@ 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: "أرشفة هذا الوكيل وابدأ مسودة جديدة", @@ -273,6 +288,7 @@ export const ar: TranslationResources = { scrollToBottom: "قم بالتمرير إلى الأسفل", historyLoadFailed: "تعذر تحميل سجل الوكيل", messageCapped: "تم اقتطاع هذه الرسالة ({{bytes}} بايت).", + pinnedPrompt: { jump: "انتقل إلى هذه الرسالة" }, permission: { rejectedPlan: "خطة مرفوضة", approvedPlan: "خطة معتمدة", @@ -285,9 +301,87 @@ export const ar: TranslationResources = { implement: "ينفذ", question: "كيف تريد المتابعة؟", proposedPlan: "الخطة المقترحة", + handOff: "تسليم", + handedOff: "تم التسليم", + handoffPrompt: "نفّذ الخطة المقترحة التالية.", + handoffFailed: "تعذّر تسليم الخطة.", + copyContent: "نسخ المحتوى", + copyLink: "نسخ الرابط", + contentCopied: "تم نسخ الخطة", + linkCopied: "تم نسخ رابط الجلسة", + copyFailed: "تعذر نسخ الخطة.", }, }, 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: "فشل تحميل الوكيل", @@ -582,6 +676,9 @@ export const ar: TranslationResources = { }, errors: { failedToListDirectory: "فشل في سرد ​​الدليل", + pathUnavailable: "لا يمكن تحديد هذا المسار من دليل عمل المحادثة.", + outsideWorkspaceDirectory: + "هذا المجلد خارج مساحة العمل الحالية. افتحه من مساحة العمل المصدر.", createFailed: "فشل إنشاء العنصر", renameFailed: "فشل إعادة تسمية العنصر", duplicateFailed: "فشل تكرار العنصر", @@ -713,12 +810,15 @@ export const ar: TranslationResources = { reloadAgent: "إعادة تحميل الوكيل", reloadAgentTooltip: "قم بإعادة تحميل الوكيل لتحديث المهارات أو MCPs أو حالة تسجيل الدخول.", close: "يغلق", + findInChat: "بحث في الدردشة", renameTerminal: "إعادة تسمية المحطة", + viewArtifacts: "عرض الملفات المنتَجة", renameAgent: "إعادة تسمية الوكيل", }, actions: { newTab: "علامة تبويب جديدة", newAgent: "وكيل جديد", + recentlyClosed: "المغلقة مؤخرًا", newTerminal: "محطة جديدة", preparingTerminal: "إعداد علامة التبويب المحطة الطرفية", preparingTerminalTooltip: "جارٍ تحضير المحطة...", @@ -735,6 +835,12 @@ export const ar: TranslationResources = { terminalProfilesMenu: "Terminal profiles", editTerminalProfiles: "Edit profiles", }, + recentAgents: { + title: "المغلقة مؤخرًا", + loading: "جارٍ التحميل…", + empty: "لا توجد وكلاء مغلقة في مساحة العمل هذه", + showAll: "عرض الكل في السجل", + }, explorerSidebar: { open: "افتح اللوحة الجانبية", close: "إغلاق اللوحة الجانبية", @@ -808,8 +914,23 @@ export const ar: TranslationResources = { workspacePathCopiedLabel: "مسار Workspace", branchNameCopiedLabel: "اسم الفرع", }, + branches: { + current: "الفرع الحالي: {{branchName}}. اضغط لعرض إجراءات الفرع.", + base: "مقارنة مع {{branchName}}. اضغط لتغيير الفرع الأساسي.", + setBase: "تعيين الفرع الأساسي", + baseTitle: "مقارنة مع", + baseUnavailable: "حدّث المضيف لتغيير الفرع الأساسي", + baseFailed: "فشل تغيير الفرع الأساسي", + rename: "إعادة تسمية الفرع…", + renameTitle: "إعادة تسمية الفرع", + renameSubmit: "إعادة التسمية", + renameFailed: "اسم فرع غير صالح", + switch: "تبديل الفرع…", + }, }, scripts: { + rootPackage: "الجذر", + searchPlaceholder: "البحث عن السكربتات أو الحزم…", title: "البرامج النصية", actions: { chooseUrl: "اختيار الرابط", @@ -837,6 +958,8 @@ export const ar: TranslationResources = { direct: "مباشر", }, states: { + empty: "لم يتم العثور على نصوص برمجية", + noMatches: "لا توجد سكربتات مطابقة", exitCode: "الخروج من{{code}}", startFailed: "فشل بدء تشغيل{{scriptName}}", stopFailed: "فشل إيقاف{{scriptName}}", @@ -1356,6 +1479,7 @@ export const ar: TranslationResources = { }, workspace: { status: { + scriptRunning: "النص البرمجي {{name}} قيد التشغيل", serviceRunning: "الخدمة {{name}} قيد التشغيل", serviceUnhealthy: "الخدمة {{name}} غير سليمة", creating: "جارٍ الإنشاء...", @@ -1410,6 +1534,28 @@ export const ar: TranslationResources = { }, }, }, + projectPullRequests: { + checks: { + passed: "نجحت جميع الفحوصات", + pending: "الفحوصات قيد التشغيل", + skipped: "تم تخطي الفحوصات", + updateRequired: "حدّث هذا المضيف لعرض حالة CI.", + }, + title: "طلبات السحب", + shortcut: "تصفح طلبات السحب لـ {{project}}", + search: "البحث في طلبات السحب", + clearSearch: "مسح البحث", + open: "مفتوحة", + closed: "مغلقة", + results: "{{count}} نتيجة", + authRequired: "سجّل الدخول إلى خدمة Git على هذا المضيف لتصفح طلبات السحب.", + loading: "جارٍ تحميل طلبات السحب…", + empty: "لا توجد طلبات سحب مطابقة.", + limit: "يتم عرض حتى {{count}} نتيجة. حدّد البحث أكثر.", + start: "إنشاء شجرة عمل من #{{number}}: {{title}}", + updated: "تم التحديث {{date}}", + external: "فتح #{{number}} في المتصفح", + }, newWorkspace: { title: "مساحة عمل جديدة", create: "يخلق", @@ -2005,10 +2151,25 @@ 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: { @@ -2742,6 +2903,8 @@ export const ar: TranslationResources = { jumpToWorkspace: "انتقل إلى مساحة العمل", jumpToTab: "انتقل إلى علامة التبويب", previousWorkspace: "مساحة العمل السابقة", + historyBack: "رجوع", + historyForward: "تقدم", nextWorkspace: "مساحة العمل التالية", previousTab: "علامة التبويب السابقة", nextTab: "علامة التبويب التالية", @@ -3085,9 +3248,49 @@ export const ar: TranslationResources = { updateErrorTitle: "غير قادر على تحديث الموفر", actions: { menu: "{{name}} actions", + addAccount: "إضافة حساب", + editAccount: "تعديل الحساب", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "إضافة حساب {{provider}}", + editTitle: "تعديل حساب {{provider}}", + errorTitle: "تعذر حفظ الحساب", + submit: "إضافة حساب", + save: "حفظ التغييرات", + fields: { + label: "الاسم", + providerId: "معرّف المزود", + description: "الوصف", + env: "متغيرات البيئة", + envKey: "اسم المتغير", + envValue: "قيمة المتغير", + }, + placeholders: { + label: "{{provider}} (العمل)", + providerId: "claude-work", + description: "اختياري", + envKey: "الاسم", + envValue: "القيمة", + }, + actions: { + addVariable: "إضافة متغير", + removeVariable: "إزالة المتغير", + }, + warnings: { + renameUnsupported: + "لا يستطيع هذا المضيف نقل المحادثات الحالية إلى المعرّف الجديد. ستصبح المحادثات التي تستخدم هذا الحساب غير متاحة حتى تحدّث المضيف أو تستعيد المعرّف السابق.", + }, + errors: { + labelRequired: "أدخل اسمًا.", + idRequired: "أدخل معرّف المزود.", + idInvalid: "استخدم أحرفًا صغيرة وأرقامًا وشرطات، بدءًا بحرف.", + idTaken: "معرّف المزود هذا مستخدم بالفعل.", + envKeyRequired: "أدخل اسم المتغير.", + envDuplicate: "هذا المتغير معيّن بالفعل.", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 6230084e2b5..f4fa02fa228 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -14,6 +14,7 @@ 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", @@ -185,7 +186,7 @@ export const en = { unmuteVoice: "Unmute voice", muteVoice: "Mute voice", dictation: "Dictation", - interruptBeforeVoice: "Interrupt the agent before starting voice mode", + interruptBeforeVoice: "Update the host to use voice while the agent works", }, attachments: { addImage: "Add image", @@ -219,6 +220,20 @@ 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", @@ -269,6 +284,9 @@ export const en = { scrollToBottom: "Scroll to bottom", historyLoadFailed: "Couldn't load agent history", messageCapped: "This message was capped ({{bytes}} bytes).", + pinnedPrompt: { + jump: "Scroll to this message", + }, permission: { rejectedPlan: "Rejected plan", approvedPlan: "Approved plan", @@ -281,9 +299,89 @@ export const en = { implement: "Implement", question: "How would you like to proceed?", proposedPlan: "Proposed plan", + handOff: "Hand off", + handedOff: "Handed off", + handoffPrompt: "Implement the following proposed plan.", + handoffFailed: "Could not hand off the plan.", + copyContent: "Copy content", + copyLink: "Copy link", + contentCopied: "Plan copied", + linkCopied: "Session link copied", + copyFailed: "Could not copy the plan.", }, }, 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", @@ -579,6 +677,9 @@ export const en = { }, errors: { failedToListDirectory: "Failed to list directory", + pathUnavailable: "This path cannot be resolved from the conversation's working directory.", + outsideWorkspaceDirectory: + "This folder is outside the current workspace. Open it from its source workspace.", createFailed: "Failed to create entry", renameFailed: "Failed to rename entry", duplicateFailed: "Failed to duplicate entry", @@ -710,12 +811,15 @@ 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: { newTab: "New tab", newAgent: "New agent", + recentlyClosed: "Recently closed", newTerminal: "New terminal", preparingTerminal: "Preparing terminal tab", preparingTerminalTooltip: "Preparing terminal...", @@ -732,6 +836,12 @@ export const en = { terminalProfilesMenu: "Terminal profiles", editTerminalProfiles: "Edit profiles", }, + recentAgents: { + title: "Recently closed", + loading: "Loading…", + empty: "No closed agents in this workspace", + showAll: "Show all in History", + }, explorerSidebar: { open: "Open Explorer sidebar", close: "Close Explorer sidebar", @@ -803,8 +913,23 @@ export const en = { workspacePathCopiedLabel: "Workspace path", branchNameCopiedLabel: "Branch name", }, + branches: { + current: "Current branch: {{branchName}}. Press for branch actions.", + base: "Compared with {{branchName}}. Press to change the base branch.", + setBase: "Set base branch", + baseTitle: "Compare with", + baseUnavailable: "Update the host to change the base branch", + baseFailed: "Failed to change base branch", + rename: "Rename branch…", + renameTitle: "Rename branch", + renameSubmit: "Rename", + renameFailed: "Invalid branch name", + switch: "Switch branch…", + }, }, scripts: { + rootPackage: "Root", + searchPlaceholder: "Search scripts or packages…", title: "Scripts", actions: { chooseUrl: "Choose URL", @@ -832,6 +957,8 @@ export const en = { direct: "Direct", }, states: { + empty: "No scripts found", + noMatches: "No matching scripts", exitCode: "exit {{code}}", startFailed: "Failed to start {{scriptName}}", stopFailed: "Failed to stop {{scriptName}}", @@ -1364,6 +1491,7 @@ export const en = { }, workspace: { status: { + scriptRunning: "Script {{name}} running", serviceRunning: "Service {{name}} running", serviceUnhealthy: "Service {{name}} unhealthy", creating: "Creating...", @@ -1418,6 +1546,28 @@ export const en = { }, }, }, + projectPullRequests: { + checks: { + passed: "All checks passed", + pending: "Checks running", + skipped: "Checks skipped", + updateRequired: "Update this host to see CI status.", + }, + title: "Pull requests", + shortcut: "Browse pull requests for {{project}}", + search: "Search pull requests", + clearSearch: "Clear search", + open: "Open", + closed: "Closed", + results: "Results: {{count}}", + authRequired: "Sign in to your git forge on this host to browse pull requests.", + loading: "Loading pull requests…", + empty: "No matching pull requests.", + limit: "Showing up to {{count}} results. Refine your search to find more.", + start: "Create worktree from #{{number}}: {{title}}", + updated: "Updated {{date}}", + external: "Open #{{number}} in browser", + }, newWorkspace: { title: "New workspace", create: "Create", @@ -2031,10 +2181,25 @@ 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 and interrupt turn", + stop: "Stop realtime voice", }, }, rewind: { @@ -2832,6 +2997,8 @@ export const en = { jumpToWorkspace: "Jump to workspace", jumpToTab: "Jump to tab", previousWorkspace: "Previous workspace", + historyBack: "Back", + historyForward: "Forward", nextWorkspace: "Next workspace", previousTab: "Previous tab", nextTab: "Next tab", @@ -3180,9 +3347,49 @@ export const en = { updateErrorTitle: "Unable to update provider", actions: { menu: "{{name}} actions", + addAccount: "Add account", + editAccount: "Edit account", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "Add {{provider}} account", + editTitle: "Edit {{provider}} account", + errorTitle: "Unable to save account", + submit: "Add account", + save: "Save changes", + fields: { + label: "Name", + providerId: "Provider ID", + description: "Description", + env: "Environment variables", + envKey: "Variable name", + envValue: "Variable value", + }, + placeholders: { + label: "{{provider}} (Work)", + providerId: "claude-work", + description: "Optional", + envKey: "NAME", + envValue: "Value", + }, + actions: { + addVariable: "Add variable", + removeVariable: "Remove variable", + }, + warnings: { + renameUnsupported: + "This host can't move existing chats to the new ID. Chats using this account will be unavailable until you update the host or restore the old ID.", + }, + errors: { + labelRequired: "Enter a name.", + idRequired: "Enter a provider ID.", + idInvalid: "Use lowercase letters, numbers, and dashes, starting with a letter.", + idTaken: "This provider ID is already taken.", + envKeyRequired: "Enter a variable name.", + envDuplicate: "This variable is already set.", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index d618389af0e..f37c9aae395 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -19,6 +19,7 @@ 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", @@ -191,7 +192,7 @@ export const es: TranslationResources = { unmuteVoice: "Activar voz", muteVoice: "voz muda", dictation: "Dictado", - interruptBeforeVoice: "Interrumpir al agente antes de iniciar el modo de voz.", + interruptBeforeVoice: "Actualiza el host para usar la voz mientras el agente trabaja", }, attachments: { addImage: "Agregar imagen", @@ -226,6 +227,20 @@ 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", @@ -276,6 +291,7 @@ export const es: TranslationResources = { scrollToBottom: "Desplazarse hacia abajo", historyLoadFailed: "No se pudo cargar el historial del agente", messageCapped: "Este mensaje fue truncado ({{bytes}} bytes).", + pinnedPrompt: { jump: "Desplazarse a este mensaje" }, permission: { rejectedPlan: "Plan rechazado", approvedPlan: "Plan aprobado", @@ -288,9 +304,90 @@ export const es: TranslationResources = { implement: "Implementar", question: "¿Cómo le gustaría proceder?", proposedPlan: "Plan propuesto", + handOff: "Transferir", + handedOff: "Transferido", + handoffPrompt: "Implementa el siguiente plan propuesto.", + handoffFailed: "No se pudo transferir el plan.", + copyContent: "Copiar contenido", + copyLink: "Copiar enlace", + contentCopied: "Plan copiado", + linkCopied: "Enlace de sesión copiado", + copyFailed: "No se pudo copiar el plan.", }, }, 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", @@ -589,6 +686,10 @@ export const es: TranslationResources = { }, errors: { failedToListDirectory: "No se pudo listar el directorio", + pathUnavailable: + "No se puede resolver esta ruta desde el directorio de trabajo de la conversación.", + outsideWorkspaceDirectory: + "Esta carpeta está fuera del espacio de trabajo actual. Ábrela desde su espacio de trabajo de origen.", createFailed: "No se pudo crear la entrada", renameFailed: "No se pudo renombrar la entrada", duplicateFailed: "No se pudo duplicar la entrada", @@ -721,12 +822,15 @@ 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: { newTab: "Nueva pestaña", newAgent: "Nuevo agente", + recentlyClosed: "Cerrados recientemente", newTerminal: "Nueva terminal", preparingTerminal: "Preparando la pestaña del terminal", preparingTerminalTooltip: "Preparando terminal...", @@ -743,6 +847,12 @@ export const es: TranslationResources = { terminalProfilesMenu: "Terminal profiles", editTerminalProfiles: "Edit profiles", }, + recentAgents: { + title: "Cerrados recientemente", + loading: "Cargando…", + empty: "No hay agentes cerrados en este espacio de trabajo", + showAll: "Mostrar todo en Historial", + }, explorerSidebar: { open: "Abrir panel lateral", close: "Cerrar panel lateral", @@ -817,8 +927,23 @@ export const es: TranslationResources = { workspacePathCopiedLabel: "RutaWorkspace", branchNameCopiedLabel: "Nombre de la sucursal", }, + branches: { + current: "Rama actual: {{branchName}}. Pulsa para ver acciones de la rama.", + base: "Comparado con {{branchName}}. Pulsa para cambiar la rama base.", + setBase: "Definir rama base", + baseTitle: "Comparar con", + baseUnavailable: "Actualiza el host para cambiar la rama base", + baseFailed: "No se pudo cambiar la rama base", + rename: "Renombrar rama…", + renameTitle: "Renombrar rama", + renameSubmit: "Renombrar", + renameFailed: "Nombre de rama no válido", + switch: "Cambiar de rama…", + }, }, scripts: { + rootPackage: "Raíz", + searchPlaceholder: "Buscar scripts o paquetes…", title: "Scripts", actions: { chooseUrl: "Elegir URL", @@ -846,6 +971,8 @@ export const es: TranslationResources = { direct: "Directa", }, states: { + empty: "No se encontraron scripts", + noMatches: "No hay scripts coincidentes", exitCode: "salir de{{code}}", startFailed: "No se pudo iniciar{{scriptName}}", stopFailed: "No se pudo detener{{scriptName}}", @@ -1393,6 +1520,7 @@ export const es: TranslationResources = { }, workspace: { status: { + scriptRunning: "Script {{name}} en ejecución", serviceRunning: "Servicio {{name}} en ejecución", serviceUnhealthy: "Servicio {{name}} con fallos", creating: "Creando...", @@ -1447,6 +1575,28 @@ export const es: TranslationResources = { }, }, }, + projectPullRequests: { + checks: { + passed: "Todas las comprobaciones pasaron", + pending: "Comprobaciones en curso", + skipped: "Comprobaciones omitidas", + updateRequired: "Actualiza este host para ver el estado de CI.", + }, + title: "Pull requests", + shortcut: "Ver pull requests de {{project}}", + search: "Buscar pull requests", + clearSearch: "Borrar búsqueda", + open: "Abiertas", + closed: "Cerradas", + results: "{{count}} resultados", + authRequired: "Inicia sesión en tu forja Git en este host para ver las pull requests.", + loading: "Cargando pull requests…", + empty: "No hay pull requests coincidentes.", + limit: "Se muestran hasta {{count}} resultados. Refina la búsqueda.", + start: "Crear worktree desde #{{number}}: {{title}}", + updated: "Actualizado {{date}}", + external: "Abrir #{{number}} en el navegador", + }, newWorkspace: { title: "Nuevo espacio de trabajo", create: "Crear", @@ -2055,10 +2205,26 @@ 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 e interrumpir el turno.", + stop: "Detener la voz en tiempo real", }, }, rewind: { @@ -2766,6 +2932,8 @@ export const es: TranslationResources = { jumpToWorkspace: "Saltar al espacio de trabajo", jumpToTab: "Saltar a la pestaña", previousWorkspace: "Espacio de trabajo anterior", + historyBack: "Atrás", + historyForward: "Adelante", nextWorkspace: "Siguiente espacio de trabajo", previousTab: "Pestaña anterior", nextTab: "Pestaña siguiente", @@ -3115,9 +3283,49 @@ export const es: TranslationResources = { updateErrorTitle: "No se puede actualizar el proveedor", actions: { menu: "{{name}} actions", + addAccount: "Añadir cuenta", + editAccount: "Editar cuenta", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "Añadir cuenta de {{provider}}", + editTitle: "Editar cuenta de {{provider}}", + errorTitle: "No se pudo guardar la cuenta", + submit: "Añadir cuenta", + save: "Guardar cambios", + fields: { + label: "Nombre", + providerId: "ID del proveedor", + description: "Descripción", + env: "Variables de entorno", + envKey: "Nombre de la variable", + envValue: "Valor de la variable", + }, + placeholders: { + label: "{{provider}} (Trabajo)", + providerId: "claude-work", + description: "Opcional", + envKey: "NOMBRE", + envValue: "Valor", + }, + actions: { + addVariable: "Añadir variable", + removeVariable: "Quitar variable", + }, + warnings: { + renameUnsupported: + "Este host no puede mover los chats existentes al nuevo ID. Los chats que usan esta cuenta no estarán disponibles hasta que actualices el host o restaures el ID anterior.", + }, + errors: { + labelRequired: "Escribe un nombre.", + idRequired: "Escribe un ID de proveedor.", + idInvalid: "Usa minúsculas, números y guiones, empezando por una letra.", + idTaken: "Este ID de proveedor ya está en uso.", + envKeyRequired: "Escribe el nombre de la variable.", + envDuplicate: "Esta variable ya está definida.", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index fbfed51b346..4a28e89cba2 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -19,6 +19,7 @@ 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", @@ -191,7 +192,8 @@ export const fr: TranslationResources = { unmuteVoice: "Réactiver le micro", muteVoice: "Couper le micro", dictation: "Dictée", - interruptBeforeVoice: "Interrompez l’agent avant de démarrer le mode vocal", + interruptBeforeVoice: + "Mettez à jour l’hôte pour utiliser la voix pendant que l’agent travaille", }, attachments: { addImage: "Ajouter une image", @@ -226,6 +228,20 @@ 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", @@ -276,6 +292,7 @@ export const fr: TranslationResources = { scrollToBottom: "Faire défiler vers le bas", historyLoadFailed: "Impossible de charger l’historique de l’agent", messageCapped: "Ce message a été tronqué ({{bytes}} octets).", + pinnedPrompt: { jump: "Faire défiler jusqu’à ce message" }, permission: { rejectedPlan: "Plan refusé", approvedPlan: "Plan approuvé", @@ -288,9 +305,90 @@ export const fr: TranslationResources = { implement: "Implémenter", question: "Comment souhaitez-vous procéder ?", proposedPlan: "Plan proposé", + handOff: "Transférer", + handedOff: "Transféré", + handoffPrompt: "Mets en œuvre le plan proposé ci-dessous.", + handoffFailed: "Impossible de transférer le plan.", + copyContent: "Copier le contenu", + copyLink: "Copier le lien", + contentCopied: "Plan copié", + linkCopied: "Lien de session copié", + copyFailed: "Impossible de copier le plan.", }, }, 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", @@ -587,6 +685,10 @@ export const fr: TranslationResources = { }, errors: { failedToListDirectory: "Impossible de lister le répertoire", + pathUnavailable: + "Ce chemin ne peut pas être résolu depuis le répertoire de travail de la conversation.", + outsideWorkspaceDirectory: + "Ce dossier se trouve hors de l’espace de travail actuel. Ouvrez-le depuis son espace de travail d’origine.", createFailed: "Impossible de créer l’élément", renameFailed: "Impossible de renommer l’élément", duplicateFailed: "Impossible de dupliquer l’élément", @@ -720,12 +822,15 @@ 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: { newTab: "Nouvel onglet", newAgent: "Nouvel agent", + recentlyClosed: "Fermés récemment", newTerminal: "Nouveau terminal", preparingTerminal: "Préparation de l’onglet de terminal…", preparingTerminalTooltip: "Préparation du terminal…", @@ -742,6 +847,12 @@ export const fr: TranslationResources = { terminalProfilesMenu: "Profils de terminal", editTerminalProfiles: "Modifier les profils", }, + recentAgents: { + title: "Fermés récemment", + loading: "Chargement…", + empty: "Aucun agent fermé dans cet espace de travail", + showAll: "Tout afficher dans l’historique", + }, explorerSidebar: { open: "Ouvrir la barre latérale de l’explorateur", close: "Fermer la barre latérale de l’explorateur", @@ -817,8 +928,23 @@ export const fr: TranslationResources = { workspacePathCopiedLabel: "Chemin de l’espace de travail", branchNameCopiedLabel: "Nom de la branche", }, + branches: { + current: "Branche actuelle : {{branchName}}. Appuyez pour les actions de branche.", + base: "Comparé avec {{branchName}}. Appuyez pour changer la branche de base.", + setBase: "Définir la branche de base", + baseTitle: "Comparer avec", + baseUnavailable: "Mettez à jour l’hôte pour changer la branche de base", + baseFailed: "Impossible de changer la branche de base", + rename: "Renommer la branche…", + renameTitle: "Renommer la branche", + renameSubmit: "Renommer", + renameFailed: "Nom de branche invalide", + switch: "Changer de branche…", + }, }, scripts: { + rootPackage: "Racine", + searchPlaceholder: "Rechercher des scripts ou des packages…", title: "Scripts", actions: { chooseUrl: "Choisir l’URL", @@ -846,6 +972,8 @@ export const fr: TranslationResources = { direct: "Directe", }, states: { + empty: "Aucun script trouvé", + noMatches: "Aucun script correspondant", exitCode: "sortie {{code}}", startFailed: "Impossible de démarrer {{scriptName}}", stopFailed: "Impossible d’arrêter {{scriptName}}", @@ -1386,6 +1514,7 @@ export const fr: TranslationResources = { }, workspace: { status: { + scriptRunning: "Script {{name}} en cours", serviceRunning: "Service {{name}} en cours d’exécution", serviceUnhealthy: "Service {{name}} en échec", creating: "Création…", @@ -1440,6 +1569,28 @@ export const fr: TranslationResources = { }, }, }, + projectPullRequests: { + checks: { + passed: "Tous les contrôles ont réussi", + pending: "Contrôles en cours", + skipped: "Contrôles ignorés", + updateRequired: "Mettez à jour cet hôte pour voir l’état CI.", + }, + title: "Pull requests", + shortcut: "Parcourir les pull requests de {{project}}", + search: "Rechercher des pull requests", + clearSearch: "Effacer la recherche", + open: "Ouvertes", + closed: "Fermées", + results: "{{count}} résultats", + authRequired: "Connectez-vous à votre forge Git sur cet hôte pour parcourir les pull requests.", + loading: "Chargement des pull requests…", + empty: "Aucune pull request correspondante.", + limit: "Affichage limité à {{count}} résultats. Affinez votre recherche.", + start: "Créer un worktree depuis #{{number}} : {{title}}", + updated: "Mis à jour le {{date}}", + external: "Ouvrir #{{number}} dans le navigateur", + }, newWorkspace: { title: "Nouvel espace de travail", create: "Créer", @@ -2053,10 +2204,27 @@ 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 et interrompre le tour", + stop: "Arrêter la voix en temps réel", }, }, rewind: { @@ -2767,6 +2935,8 @@ export const fr: TranslationResources = { jumpToWorkspace: "Aller à l’espace de travail", jumpToTab: "Aller à l’onglet", previousWorkspace: "Espace de travail précédent", + historyBack: "Retour", + historyForward: "Avancer", nextWorkspace: "Espace de travail suivant", previousTab: "Onglet précédent", nextTab: "Onglet suivant", @@ -3121,9 +3291,50 @@ export const fr: TranslationResources = { updateErrorTitle: "Impossible de mettre à jour le fournisseur", actions: { menu: "Actions de {{name}}", + addAccount: "Ajouter un compte", + editAccount: "Modifier le compte", remove: "Supprimer le fournisseur", removing: "Suppression…", }, + account: { + title: "Ajouter un compte {{provider}}", + editTitle: "Modifier le compte {{provider}}", + errorTitle: "Impossible d'enregistrer le compte", + submit: "Ajouter un compte", + save: "Enregistrer", + fields: { + label: "Nom", + providerId: "ID du fournisseur", + description: "Description", + env: "Variables d'environnement", + envKey: "Nom de la variable", + envValue: "Valeur de la variable", + }, + placeholders: { + label: "{{provider}} (Travail)", + providerId: "claude-work", + description: "Facultatif", + envKey: "NOM", + envValue: "Valeur", + }, + actions: { + addVariable: "Ajouter une variable", + removeVariable: "Supprimer la variable", + }, + warnings: { + renameUnsupported: + "Cet hôte ne peut pas déplacer les conversations existantes vers le nouvel ID. Les conversations utilisant ce compte seront indisponibles tant que vous n'aurez pas mis à jour l'hôte ou restauré l'ancien ID.", + }, + errors: { + labelRequired: "Saisissez un nom.", + idRequired: "Saisissez un ID de fournisseur.", + idInvalid: + "Utilisez des minuscules, des chiffres et des tirets, en commençant par une lettre.", + idTaken: "Cet ID de fournisseur est déjà utilisé.", + envKeyRequired: "Saisissez le nom de la variable.", + envDuplicate: "Cette variable est déjà définie.", + }, + }, remove: { confirmTitle: "Supprimer {{name}} ?", confirmMessage: diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 41c879a2c16..22ff7fb33fc 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -19,6 +19,7 @@ export const ja: TranslationResources = { title: "検索", placeholder: "ペイン内を検索", + updateHost: "検索を使うにはホストを更新してください", close: "検索を閉じる", matches: "検索結果", previous: "前の一致", @@ -191,7 +192,7 @@ export const ja: TranslationResources = { unmuteVoice: "音声のミュートを解除", muteVoice: "音声をミュート", dictation: "音声入力", - interruptBeforeVoice: "音声モードを開始する前にエージェントを中断してください", + interruptBeforeVoice: "エージェントの作業中に音声を使うにはホストを更新してください", }, attachments: { addImage: "画像を追加", @@ -226,6 +227,20 @@ export const ja: TranslationResources = { pasteImageFailed: "画像を貼り付けられませんでした", fileTooLarge: "{{fileName}}が大きすぎます(最大{{size}})", }, + queued: { + menu: "キュー済みメッセージの操作", + moveUp: "上へ移動", + moveDown: "下へ移動", + delete: "削除", + discard: "破棄", + retry: "再試行", + sending: "送信中...", + unconfirmed: "未確認", + failed: "失敗", + changedOnAnotherDevice: "このキュー済みメッセージは別のデバイスで変更されました", + deleteTitle: "キュー済みメッセージを削除しますか?", + deleteMessage: "このエージェントに接続しているすべてのデバイスから削除されます", + }, clientCommands: { archiveAgent: "現在のエージェントをアーカイブ", freshDraft: "このエージェントをアーカイブして新しい下書きを開始", @@ -276,6 +291,7 @@ export const ja: TranslationResources = { scrollToBottom: "下にスクロール", historyLoadFailed: "エージェントの履歴を読み込めませんでした", messageCapped: "このメッセージは上限で切り詰められました({{bytes}}バイト)。", + pinnedPrompt: { jump: "このメッセージまでスクロール" }, permission: { rejectedPlan: "却下されたプラン", approvedPlan: "承認されたプラン", @@ -288,9 +304,87 @@ export const ja: TranslationResources = { implement: "実装", question: "どのように続けますか?", proposedPlan: "提案されたプラン", + handOff: "引き継ぐ", + handedOff: "引き継ぎ済み", + handoffPrompt: "次の提案されたプランを実装してください。", + handoffFailed: "プランを引き継げませんでした。", + copyContent: "内容をコピー", + copyLink: "リンクをコピー", + contentCopied: "プランをコピーしました", + linkCopied: "セッションリンクをコピーしました", + copyFailed: "プランをコピーできませんでした。", }, }, 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: "エージェントの読み込みに失敗しました", @@ -589,6 +683,9 @@ export const ja: TranslationResources = { }, errors: { failedToListDirectory: "ディレクトリの一覧取得に失敗しました", + pathUnavailable: "このパスは会話の作業ディレクトリから解決できません。", + outsideWorkspaceDirectory: + "このフォルダーは現在のワークスペースの外にあります。元のワークスペースから開いてください。", createFailed: "エントリの作成に失敗しました", renameFailed: "エントリの名前変更に失敗しました", duplicateFailed: "エントリの複製に失敗しました", @@ -721,12 +818,15 @@ export const ja: TranslationResources = { reloadAgentTooltip: "スキル、MCP、ログイン状態を更新するためにエージェントを再読み込みします。", close: "閉じる", + findInChat: "チャット内を検索", renameTerminal: "ターミナルの名前を変更", + viewArtifacts: "アーティファクトを表示", renameAgent: "エージェントの名前を変更", }, actions: { newTab: "新しいタブ", newAgent: "新しいエージェント", + recentlyClosed: "最近閉じた項目", newTerminal: "新しいターミナル", preparingTerminal: "ターミナルタブを準備中", preparingTerminalTooltip: "ターミナルを準備中...", @@ -743,6 +843,12 @@ export const ja: TranslationResources = { terminalProfilesMenu: "ターミナルプロファイル", editTerminalProfiles: "プロファイルを編集", }, + recentAgents: { + title: "最近閉じた項目", + loading: "読み込み中…", + empty: "このワークスペースに閉じたエージェントはありません", + showAll: "履歴ですべて表示", + }, explorerSidebar: { open: "サイドパネルを開く", close: "サイドパネルを閉じる", @@ -813,8 +919,23 @@ export const ja: TranslationResources = { workspacePathCopiedLabel: "ワークスペースパス", branchNameCopiedLabel: "ブランチ名", }, + branches: { + current: "現在のブランチ: {{branchName}}。押すとブランチ操作を表示します。", + base: "{{branchName}} と比較中。押すとベースブランチを変更します。", + setBase: "ベースブランチを設定", + baseTitle: "比較対象", + baseUnavailable: "ベースブランチを変更するにはホストを更新してください", + baseFailed: "ベースブランチを変更できませんでした", + rename: "ブランチ名を変更…", + renameTitle: "ブランチ名を変更", + renameSubmit: "変更", + renameFailed: "無効なブランチ名です", + switch: "ブランチを切り替え…", + }, }, scripts: { + rootPackage: "ルート", + searchPlaceholder: "スクリプトまたはパッケージを検索…", title: "スクリプト", actions: { chooseUrl: "URLを選択", @@ -842,6 +963,8 @@ export const ja: TranslationResources = { direct: "直接接続", }, states: { + empty: "スクリプトが見つかりません", + noMatches: "一致するスクリプトがありません", exitCode: "終了コード: {{code}}", startFailed: "{{scriptName}}の起動に失敗しました", stopFailed: "{{scriptName}}の停止に失敗しました", @@ -1371,6 +1494,7 @@ export const ja: TranslationResources = { }, workspace: { status: { + scriptRunning: "スクリプト {{name}} を実行中", serviceRunning: "サービス {{name}} 実行中", serviceUnhealthy: "サービス {{name}} 異常", creating: "作成中...", @@ -1425,6 +1549,29 @@ export const ja: TranslationResources = { }, }, }, + projectPullRequests: { + checks: { + passed: "すべてのチェックに成功", + pending: "チェック実行中", + skipped: "チェックをスキップ", + updateRequired: "CI ステータスを表示するには、このホストを更新してください。", + }, + title: "プルリクエスト", + shortcut: "{{project}} のプルリクエストを表示", + search: "プルリクエストを検索", + clearSearch: "検索をクリア", + open: "オープン", + closed: "クローズ", + results: "{{count}} 件", + authRequired: + "プルリクエストを表示するには、このホストの Git サービスにサインインしてください。", + loading: "プルリクエストを読み込み中…", + empty: "一致するプルリクエストはありません。", + limit: "最大 {{count}} 件を表示しています。検索条件を絞り込んでください。", + start: "#{{number}} から worktree を作成: {{title}}", + updated: "更新日 {{date}}", + external: "#{{number}} をブラウザーで開く", + }, newWorkspace: { title: "新しいワークスペース", create: "作成", @@ -2027,10 +2174,25 @@ 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: { @@ -2732,6 +2894,8 @@ export const ja: TranslationResources = { jumpToWorkspace: "ワークスペースにジャンプ", jumpToTab: "タブにジャンプ", previousWorkspace: "前のワークスペース", + historyBack: "戻る", + historyForward: "進む", nextWorkspace: "次のワークスペース", previousTab: "前のタブ", nextTab: "次のタブ", @@ -3083,9 +3247,49 @@ export const ja: TranslationResources = { updateErrorTitle: "プロバイダーを更新できません", actions: { menu: "{{name}} actions", + addAccount: "アカウントを追加", + editAccount: "アカウントを編集", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "{{provider}} アカウントを追加", + editTitle: "{{provider}} アカウントを編集", + errorTitle: "アカウントを保存できません", + submit: "アカウントを追加", + save: "変更を保存", + fields: { + label: "名前", + providerId: "プロバイダー ID", + description: "説明", + env: "環境変数", + envKey: "変数名", + envValue: "変数の値", + }, + placeholders: { + label: "{{provider}}(仕事)", + providerId: "claude-work", + description: "省略可", + envKey: "名前", + envValue: "値", + }, + actions: { + addVariable: "変数を追加", + removeVariable: "変数を削除", + }, + warnings: { + renameUnsupported: + "このホストは既存のチャットを新しい ID に移行できません。ホストを更新するか元の ID に戻すまで、このアカウントを使うチャットは利用できません。", + }, + errors: { + labelRequired: "名前を入力してください。", + idRequired: "プロバイダー ID を入力してください。", + idInvalid: "英小文字・数字・ハイフンを使い、先頭は英字にしてください。", + idTaken: "このプロバイダー ID は既に使われています。", + envKeyRequired: "変数名を入力してください。", + envDuplicate: "この変数は既に設定されています。", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 03d82ff2726..ef02273338a 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -18,6 +18,7 @@ export const ko: TranslationResources = { title: "찾기", placeholder: "패널에서 찾기", + updateHost: "찾기를 사용하려면 호스트를 업데이트하세요", close: "찾기 닫기", matches: "검색 결과", previous: "이전 일치 항목", @@ -189,7 +190,7 @@ export const ko: TranslationResources = { unmuteVoice: "음성 음소거 해제", muteVoice: "음성 음소거", dictation: "받아쓰기", - interruptBeforeVoice: "음성 모드를 시작하기 전에 에이전트를 중단하세요", + interruptBeforeVoice: "에이전트 작업 중 음성을 사용하려면 호스트를 업데이트하세요", }, attachments: { addImage: "이미지 추가", @@ -223,6 +224,20 @@ export const ko: TranslationResources = { pasteImageFailed: "이미지를 붙여넣지 못했습니다.", fileTooLarge: "{{fileName}}이(가) 너무 큽니다 (최대 {{size}})", }, + queued: { + menu: "대기 중 메시지 옵션", + moveUp: "위로 이동", + moveDown: "아래로 이동", + delete: "삭제", + discard: "버리기", + retry: "다시 시도", + sending: "보내는 중...", + unconfirmed: "확인 안 됨", + failed: "실패", + changedOnAnotherDevice: "이 대기 중 메시지는 다른 기기에서 변경되었습니다", + deleteTitle: "대기 중 메시지를 삭제할까요?", + deleteMessage: "이 에이전트에 연결된 모든 기기에서 제거됩니다", + }, clientCommands: { archiveAgent: "현재 에이전트 보관", freshDraft: "이 에이전트를 보관하고 새 초안을 시작합니다", @@ -273,6 +288,7 @@ export const ko: TranslationResources = { scrollToBottom: "맨 아래로 스크롤", historyLoadFailed: "에이전트 기록을 로드할 수 없습니다.", messageCapped: "이 메시지는 길이 제한으로 잘렸습니다({{bytes}}바이트).", + pinnedPrompt: { jump: "이 메시지로 스크롤" }, permission: { rejectedPlan: "거부된 계획", approvedPlan: "승인된 계획", @@ -285,9 +301,89 @@ export const ko: TranslationResources = { implement: "구현", question: "어떻게 진행할까요?", proposedPlan: "제안된 계획", + handOff: "전달", + handedOff: "전달됨", + handoffPrompt: "다음 제안된 계획을 구현하세요.", + handoffFailed: "계획을 전달할 수 없습니다.", + copyContent: "내용 복사", + copyLink: "링크 복사", + contentCopied: "계획을 복사했습니다", + linkCopied: "세션 링크를 복사했습니다", + copyFailed: "계획을 복사할 수 없습니다.", }, }, 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: "에이전트를 불러오지 못했습니다", @@ -583,6 +679,9 @@ export const ko: TranslationResources = { }, errors: { failedToListDirectory: "디렉터리 목록을 불러오지 못했습니다", + pathUnavailable: "대화의 작업 디렉터리에서 이 경로를 확인할 수 없습니다.", + outsideWorkspaceDirectory: + "이 폴더는 현재 작업 공간 밖에 있습니다. 원본 작업 공간에서 여세요.", createFailed: "항목을 만들지 못했습니다", renameFailed: "항목 이름을 바꾸지 못했습니다", duplicateFailed: "항목을 복제하지 못했습니다", @@ -715,12 +814,15 @@ export const ko: TranslationResources = { reloadAgentTooltip: "스킬, MCP 또는 로그인 상태를 업데이트하려면 에이전트를 다시 로드하세요.", close: "닫기", + findInChat: "채팅에서 찾기", renameTerminal: "터미널 이름 변경", + viewArtifacts: "아티팩트 보기", renameAgent: "에이전트 이름 변경", }, actions: { newTab: "새 탭", newAgent: "새 에이전트", + recentlyClosed: "최근 닫은 항목", newTerminal: "새 터미널", preparingTerminal: "터미널 탭 준비 중", preparingTerminalTooltip: "터미널 준비 중...", @@ -737,6 +839,12 @@ export const ko: TranslationResources = { terminalProfilesMenu: "터미널 프로필", editTerminalProfiles: "프로필 편집", }, + recentAgents: { + title: "최근 닫은 항목", + loading: "불러오는 중…", + empty: "이 작업 공간에 닫힌 에이전트가 없습니다", + showAll: "기록에서 모두 보기", + }, explorerSidebar: { open: "사이드 패널 열기", close: "사이드 패널 닫기", @@ -808,8 +916,23 @@ export const ko: TranslationResources = { workspacePathCopiedLabel: "워크스페이스 경로", branchNameCopiedLabel: "브랜치 이름", }, + branches: { + current: "현재 브랜치: {{branchName}}. 눌러서 브랜치 작업을 표시합니다.", + base: "{{branchName}}와 비교 중. 눌러서 베이스 브랜치를 변경합니다.", + setBase: "베이스 브랜치 설정", + baseTitle: "비교 대상", + baseUnavailable: "베이스 브랜치를 변경하려면 호스트를 업데이트하세요", + baseFailed: "베이스 브랜치를 변경하지 못했습니다", + rename: "브랜치 이름 변경…", + renameTitle: "브랜치 이름 변경", + renameSubmit: "변경", + renameFailed: "유효하지 않은 브랜치 이름입니다", + switch: "브랜치 전환…", + }, }, scripts: { + rootPackage: "루트", + searchPlaceholder: "스크립트 또는 패키지 검색…", title: "스크립트", actions: { chooseUrl: "URL를 선택하세요", @@ -837,6 +960,8 @@ export const ko: TranslationResources = { direct: "직접", }, states: { + empty: "스크립트가 없습니다", + noMatches: "일치하는 스크립트가 없습니다", exitCode: "종료 {{code}}", startFailed: "{{scriptName}}을(를) 시작하지 못했습니다", stopFailed: "{{scriptName}}를 중지하지 못했습니다.", @@ -1363,6 +1488,7 @@ export const ko: TranslationResources = { }, workspace: { status: { + scriptRunning: "스크립트 {{name}} 실행 중", serviceRunning: "서비스 {{name}} 실행 중", serviceUnhealthy: "서비스 {{name}} 비정상", creating: "생성하는 중...", @@ -1417,6 +1543,28 @@ export const ko: TranslationResources = { }, }, }, + projectPullRequests: { + checks: { + passed: "모든 검사 통과", + pending: "검사 실행 중", + skipped: "검사 건너뜀", + updateRequired: "CI 상태를 보려면 이 호스트를 업데이트하세요.", + }, + title: "풀 리퀘스트", + shortcut: "{{project}}의 풀 리퀘스트 보기", + search: "풀 리퀘스트 검색", + clearSearch: "검색 지우기", + open: "열림", + closed: "닫힘", + results: "결과 {{count}}개", + authRequired: "풀 리퀘스트를 보려면 이 호스트에서 Git 서비스에 로그인하세요.", + loading: "풀 리퀘스트 로딩 중…", + empty: "일치하는 풀 리퀘스트가 없습니다.", + limit: "최대 {{count}}개의 결과를 표시합니다. 검색 범위를 좁히세요.", + start: "#{{number}}에서 worktree 만들기: {{title}}", + updated: "업데이트 {{date}}", + external: "브라우저에서 #{{number}} 열기", + }, newWorkspace: { title: "새 워크스페이스", create: "생성", @@ -2016,10 +2164,26 @@ 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: { @@ -2720,6 +2884,8 @@ export const ko: TranslationResources = { jumpToWorkspace: "워크스페이스로 이동", jumpToTab: "탭으로 이동", previousWorkspace: "이전 워크스페이스", + historyBack: "뒤로", + historyForward: "앞으로", nextWorkspace: "다음 워크스페이스", previousTab: "이전 탭", nextTab: "다음 탭", @@ -3067,9 +3233,49 @@ export const ko: TranslationResources = { updateErrorTitle: "프로바이더를 업데이트할 수 없습니다", actions: { menu: "{{name}} 작업", + addAccount: "계정 추가", + editAccount: "계정 편집", remove: "프로바이더 제거", removing: "제거 중...", }, + account: { + title: "{{provider}} 계정 추가", + editTitle: "{{provider}} 계정 편집", + errorTitle: "계정을 저장할 수 없습니다", + submit: "계정 추가", + save: "변경 사항 저장", + fields: { + label: "이름", + providerId: "프로바이더 ID", + description: "설명", + env: "환경 변수", + envKey: "변수 이름", + envValue: "변수 값", + }, + placeholders: { + label: "{{provider}} (업무)", + providerId: "claude-work", + description: "선택 사항", + envKey: "NAME", + envValue: "값", + }, + actions: { + addVariable: "변수 추가", + removeVariable: "변수 제거", + }, + warnings: { + renameUnsupported: + "이 호스트는 기존 대화를 새 ID로 옮길 수 없습니다. 호스트를 업데이트하거나 이전 ID를 복원할 때까지 이 계정을 사용하는 대화를 사용할 수 없습니다.", + }, + errors: { + labelRequired: "이름을 입력하세요.", + idRequired: "프로바이더 ID를 입력하세요.", + idInvalid: "영문 소문자로 시작하고 소문자, 숫자, 하이픈만 사용하세요.", + idTaken: "이미 사용 중인 프로바이더 ID입니다.", + envKeyRequired: "변수 이름을 입력하세요.", + envDuplicate: "이미 설정된 변수입니다.", + }, + }, remove: { confirmTitle: "{{name}}를 제거하시겠습니까?", confirmMessage: diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index daa023e4d72..87c0dc9e4e1 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -19,6 +19,7 @@ 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", @@ -190,7 +191,7 @@ export const ptBR: TranslationResources = { unmuteVoice: "Ativar som da voz", muteVoice: "Silenciar voz", dictation: "Ditado", - interruptBeforeVoice: "Interrompa o agente antes de iniciar o modo de voz", + interruptBeforeVoice: "Atualize o host para usar voz enquanto o agente trabalha", }, attachments: { addImage: "Adicionar imagem", @@ -224,6 +225,20 @@ 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", @@ -274,6 +289,7 @@ export const ptBR: TranslationResources = { scrollToBottom: "Rolar para o fim", historyLoadFailed: "Não foi possível carregar o histórico do agente", messageCapped: "Esta mensagem foi truncada ({{bytes}} bytes).", + pinnedPrompt: { jump: "Rolar até esta mensagem" }, permission: { rejectedPlan: "Plano rejeitado", approvedPlan: "Plano aprovado", @@ -286,9 +302,90 @@ export const ptBR: TranslationResources = { implement: "Implementar", question: "Como você quer prosseguir?", proposedPlan: "Plano proposto", + handOff: "Transferir", + handedOff: "Transferido", + handoffPrompt: "Implemente o plano proposto a seguir.", + handoffFailed: "Não foi possível transferir o plano.", + copyContent: "Copiar conteúdo", + copyLink: "Copiar link", + contentCopied: "Plano copiado", + linkCopied: "Link da sessão copiado", + copyFailed: "Não foi possível copiar o plano.", }, }, 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", @@ -587,6 +684,10 @@ export const ptBR: TranslationResources = { }, errors: { failedToListDirectory: "Falha ao listar diretório", + pathUnavailable: + "Não é possível resolver este caminho a partir do diretório de trabalho da conversa.", + outsideWorkspaceDirectory: + "Esta pasta está fora do espaço de trabalho atual. Abra-a no espaço de trabalho de origem.", createFailed: "Falha ao criar entrada", renameFailed: "Falha ao renomear entrada", duplicateFailed: "Falha ao duplicar entrada", @@ -718,12 +819,15 @@ 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: { newTab: "Nova aba", newAgent: "Novo agente", + recentlyClosed: "Fechados recentemente", newTerminal: "Novo terminal", preparingTerminal: "Preparando aba de terminal", preparingTerminalTooltip: "Preparando terminal...", @@ -740,6 +844,12 @@ export const ptBR: TranslationResources = { terminalProfilesMenu: "Perfis de terminal", editTerminalProfiles: "Editar perfis", }, + recentAgents: { + title: "Fechados recentemente", + loading: "Carregando…", + empty: "Não há agentes fechados neste espaço de trabalho", + showAll: "Mostrar tudo no Histórico", + }, explorerSidebar: { open: "Abrir painel lateral", close: "Fechar painel lateral", @@ -812,8 +922,23 @@ export const ptBR: TranslationResources = { workspacePathCopiedLabel: "Caminho do workspace", branchNameCopiedLabel: "Nome da branch", }, + branches: { + current: "Branch atual: {{branchName}}. Toque para ações da branch.", + base: "Comparado com {{branchName}}. Toque para alterar a branch base.", + setBase: "Definir branch base", + baseTitle: "Comparar com", + baseUnavailable: "Atualize o host para alterar a branch base", + baseFailed: "Falha ao alterar a branch base", + rename: "Renomear branch…", + renameTitle: "Renomear branch", + renameSubmit: "Renomear", + renameFailed: "Nome de branch inválido", + switch: "Trocar de branch…", + }, }, scripts: { + rootPackage: "Raiz", + searchPlaceholder: "Buscar scripts ou pacotes…", title: "Scripts", actions: { chooseUrl: "Escolher URL", @@ -841,6 +966,8 @@ export const ptBR: TranslationResources = { direct: "Direta", }, states: { + empty: "Nenhum script encontrado", + noMatches: "Nenhum script correspondente", exitCode: "saída {{code}}", startFailed: "Falha ao iniciar {{scriptName}}", stopFailed: "Falha ao parar {{scriptName}}", @@ -1382,6 +1509,7 @@ export const ptBR: TranslationResources = { }, workspace: { status: { + scriptRunning: "Script {{name}} em execução", serviceRunning: "Serviço {{name}} em execução", serviceUnhealthy: "Serviço {{name}} com falha", creating: "Criando...", @@ -1436,6 +1564,28 @@ export const ptBR: TranslationResources = { }, }, }, + projectPullRequests: { + checks: { + passed: "Todas as verificações passaram", + pending: "Verificações em andamento", + skipped: "Verificações ignoradas", + updateRequired: "Atualize este host para ver o status de CI.", + }, + title: "Pull requests", + shortcut: "Ver pull requests de {{project}}", + search: "Buscar pull requests", + clearSearch: "Limpar busca", + open: "Abertas", + closed: "Fechadas", + results: "{{count}} resultados", + authRequired: "Entre na sua plataforma Git neste host para ver pull requests.", + loading: "Carregando pull requests…", + empty: "Nenhuma pull request correspondente.", + limit: "Exibindo até {{count}} resultados. Refine sua busca.", + start: "Criar worktree a partir de #{{number}}: {{title}}", + updated: "Atualizado em {{date}}", + external: "Abrir #{{number}} no navegador", + }, newWorkspace: { title: "Novo workspace", create: "Criar", @@ -2039,10 +2189,25 @@ 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 e interromper a resposta", + stop: "Parar voz em tempo real", }, }, rewind: { @@ -2745,6 +2910,8 @@ export const ptBR: TranslationResources = { jumpToWorkspace: "Ir para workspace", jumpToTab: "Ir para aba", previousWorkspace: "Workspace anterior", + historyBack: "Voltar", + historyForward: "Avançar", nextWorkspace: "Próximo workspace", previousTab: "Aba anterior", nextTab: "Próxima aba", @@ -3095,9 +3262,49 @@ export const ptBR: TranslationResources = { updateErrorTitle: "Não foi possível atualizar provedor", actions: { menu: "{{name}} actions", + addAccount: "Adicionar conta", + editAccount: "Editar conta", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "Adicionar conta do {{provider}}", + editTitle: "Editar conta do {{provider}}", + errorTitle: "Não foi possível salvar a conta", + submit: "Adicionar conta", + save: "Salvar alterações", + fields: { + label: "Nome", + providerId: "ID do provedor", + description: "Descrição", + env: "Variáveis de ambiente", + envKey: "Nome da variável", + envValue: "Valor da variável", + }, + placeholders: { + label: "{{provider}} (Trabalho)", + providerId: "claude-work", + description: "Opcional", + envKey: "NOME", + envValue: "Valor", + }, + actions: { + addVariable: "Adicionar variável", + removeVariable: "Remover variável", + }, + warnings: { + renameUnsupported: + "Este host não consegue mover as conversas existentes para o novo ID. As conversas que usam esta conta ficarão indisponíveis até você atualizar o host ou restaurar o ID anterior.", + }, + errors: { + labelRequired: "Digite um nome.", + idRequired: "Digite um ID de provedor.", + idInvalid: "Use letras minúsculas, números e hifens, começando por uma letra.", + idTaken: "Este ID de provedor já está em uso.", + envKeyRequired: "Digite o nome da variável.", + envDuplicate: "Esta variável já está definida.", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index d50e0b740de..6467b545300 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -19,6 +19,7 @@ export const ru: TranslationResources = { title: "Найти", placeholder: "Найти в панели", + updateHost: "Обновите хост, чтобы использовать поиск", close: "Закрыть поиск", matches: "Совпадения", previous: "Предыдущее совпадение", @@ -190,7 +191,7 @@ export const ru: TranslationResources = { unmuteVoice: "Включить звук", muteVoice: "Отключить голос", dictation: "Диктовка", - interruptBeforeVoice: "Остановите агента перед запуском голосового режима", + interruptBeforeVoice: "Обновите хост, чтобы использовать голос, пока агент работает", }, attachments: { addImage: "Добавить изображение", @@ -225,6 +226,20 @@ export const ru: TranslationResources = { pasteImageFailed: "Не удалось вставить изображение", fileTooLarge: "Файл {{fileName}} слишком большой (максимальный размер: {{size}})", }, + queued: { + menu: "Действия с сообщением в очереди", + moveUp: "Вверх", + moveDown: "Вниз", + delete: "Удалить", + discard: "Отменить", + retry: "Повторить", + sending: "Отправка...", + unconfirmed: "Не подтверждено", + failed: "Ошибка", + changedOnAnotherDevice: "Это сообщение в очереди изменено на другом устройстве", + deleteTitle: "Удалить сообщение из очереди?", + deleteMessage: "Оно будет удалено на всех устройствах, подключенных к этому агенту", + }, clientCommands: { archiveAgent: "Архивировать текущего агента", freshDraft: "Архивировать этого агента и создать новый черновик", @@ -275,6 +290,7 @@ export const ru: TranslationResources = { scrollToBottom: "Прокрутить вниз", historyLoadFailed: "Не удалось загрузить историю агента", messageCapped: "Это сообщение было обрезано ({{bytes}} байт).", + pinnedPrompt: { jump: "Прокрутить до этого сообщения" }, permission: { rejectedPlan: "Отклонённый план", approvedPlan: "Одобренный план", @@ -287,9 +303,87 @@ export const ru: TranslationResources = { implement: "Реализовать", question: "Как бы вы хотели продолжить?", proposedPlan: "Предлагаемый план", + handOff: "Передать", + handedOff: "Передано", + handoffPrompt: "Реализуй следующий предложенный план.", + handoffFailed: "Не удалось передать план.", + copyContent: "Копировать содержимое", + copyLink: "Копировать ссылку", + contentCopied: "План скопирован", + linkCopied: "Ссылка на сессию скопирована", + copyFailed: "Не удалось скопировать план.", }, }, 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: "Не удалось загрузить агента", @@ -587,6 +681,9 @@ export const ru: TranslationResources = { }, errors: { failedToListDirectory: "Не удалось получить содержимое каталога", + pathUnavailable: "Не удаётся определить этот путь относительно рабочего каталога беседы.", + outsideWorkspaceDirectory: + "Эта папка находится вне текущего рабочего пространства. Откройте её в исходном рабочем пространстве.", createFailed: "Не удалось создать элемент", renameFailed: "Не удалось переименовать элемент", duplicateFailed: "Не удалось создать копию элемента", @@ -720,12 +817,15 @@ export const ru: TranslationResources = { reloadAgent: "Перезагрузить агента", reloadAgentTooltip: "Перезагрузите агента, чтобы обновить навыки, MCP или статус входа.", close: "Закрыть", + findInChat: "Найти в чате", renameTerminal: "Переименовать терминал", + viewArtifacts: "Открыть артефакты", renameAgent: "Переименовать агента", }, actions: { newTab: "Новая вкладка", newAgent: "Новый агент", + recentlyClosed: "Недавно закрытые", newTerminal: "Новый терминал", preparingTerminal: "Подготовка вкладки терминала", preparingTerminalTooltip: "Подготовка терминала...", @@ -742,6 +842,12 @@ export const ru: TranslationResources = { terminalProfilesMenu: "Профили терминала", editTerminalProfiles: "Изменить профили", }, + recentAgents: { + title: "Недавно закрытые", + loading: "Загрузка…", + empty: "В этой рабочей области нет закрытых агентов", + showAll: "Показать все в истории", + }, explorerSidebar: { open: "Открыть боковую панель", close: "Закрыть боковую панель", @@ -816,8 +922,23 @@ export const ru: TranslationResources = { workspacePathCopiedLabel: "Путь к рабочему пространству", branchNameCopiedLabel: "Имя ветки", }, + branches: { + current: "Текущая ветка: {{branchName}}. Нажмите для действий с веткой.", + base: "Сравнение с {{branchName}}. Нажмите, чтобы изменить базовую ветку.", + setBase: "Задать базовую ветку", + baseTitle: "Сравнить с", + baseUnavailable: "Обновите хост, чтобы изменить базовую ветку", + baseFailed: "Не удалось изменить базовую ветку", + rename: "Переименовать ветку…", + renameTitle: "Переименовать ветку", + renameSubmit: "Переименовать", + renameFailed: "Недопустимое имя ветки", + switch: "Переключить ветку…", + }, }, scripts: { + rootPackage: "Корень", + searchPlaceholder: "Поиск скриптов или пакетов…", title: "Скрипты", actions: { chooseUrl: "Выбрать URL", @@ -845,6 +966,8 @@ export const ru: TranslationResources = { direct: "Прямой адрес", }, states: { + empty: "Скрипты не найдены", + noMatches: "Подходящие скрипты не найдены", exitCode: "Код выхода: {{code}}", startFailed: "Не удалось запустить скрипт {{scriptName}}", stopFailed: "Не удалось остановить скрипт {{scriptName}}", @@ -1374,6 +1497,7 @@ export const ru: TranslationResources = { }, workspace: { status: { + scriptRunning: "Скрипт {{name}} выполняется", serviceRunning: "Сервис {{name}} запущен", serviceUnhealthy: "Сервис {{name}} работает некорректно", creating: "Создание...", @@ -1428,6 +1552,28 @@ export const ru: TranslationResources = { }, }, }, + projectPullRequests: { + checks: { + passed: "Все проверки пройдены", + pending: "Проверки выполняются", + skipped: "Проверки пропущены", + updateRequired: "Обновите этот хост для просмотра статуса CI.", + }, + title: "Пул-реквесты", + shortcut: "Просмотреть пул-реквесты {{project}}", + search: "Поиск пул-реквестов", + clearSearch: "Очистить поиск", + open: "Открытые", + closed: "Закрытые", + results: "Результатов: {{count}}", + authRequired: "Войдите в свой Git-сервис на этом хосте для просмотра пул-реквестов.", + loading: "Загрузка пул-реквестов…", + empty: "Подходящих пул-реквестов нет.", + limit: "Показано до {{count}} результатов. Уточните поиск.", + start: "Создать рабочее дерево из #{{number}}: {{title}}", + updated: "Обновлено {{date}}", + external: "Открыть #{{number}} в браузере", + }, newWorkspace: { title: "Новое рабочее пространство", create: "Создать", @@ -2039,10 +2185,26 @@ 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: { @@ -2752,6 +2914,8 @@ export const ru: TranslationResources = { jumpToWorkspace: "Перейти к рабочему пространству", jumpToTab: "Перейти на вкладку", previousWorkspace: "Предыдущее рабочее пространство", + historyBack: "Назад", + historyForward: "Вперёд", nextWorkspace: "Следующее рабочее пространство", previousTab: "Предыдущая вкладка", nextTab: "Следующая вкладка", @@ -3105,9 +3269,49 @@ export const ru: TranslationResources = { updateErrorTitle: "Не удалось обновить провайдера", actions: { menu: "Действия с {{name}}", + addAccount: "Добавить аккаунт", + editAccount: "Изменить аккаунт", remove: "Удалить провайдера", removing: "Удаление...", }, + account: { + title: "Добавить аккаунт {{provider}}", + editTitle: "Изменить аккаунт {{provider}}", + errorTitle: "Не удалось сохранить аккаунт", + submit: "Добавить аккаунт", + save: "Сохранить изменения", + fields: { + label: "Название", + providerId: "ID провайдера", + description: "Описание", + env: "Переменные окружения", + envKey: "Имя переменной", + envValue: "Значение переменной", + }, + placeholders: { + label: "{{provider}} (Работа)", + providerId: "claude-work", + description: "Необязательно", + envKey: "ИМЯ", + envValue: "Значение", + }, + actions: { + addVariable: "Добавить переменную", + removeVariable: "Удалить переменную", + }, + warnings: { + renameUnsupported: + "Этот хост не может перенести существующие чаты на новый ID. Чаты, использующие эту учётную запись, будут недоступны, пока вы не обновите хост или не вернёте прежний ID.", + }, + errors: { + labelRequired: "Введите название.", + idRequired: "Введите ID провайдера.", + idInvalid: "Используйте строчные буквы, цифры и дефисы, начиная с буквы.", + idTaken: "Этот ID провайдера уже занят.", + envKeyRequired: "Введите имя переменной.", + envDuplicate: "Эта переменная уже задана.", + }, + }, remove: { confirmTitle: "Удалить {{name}}?", confirmMessage: diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index b035ed5bc94..3f406f3a7cf 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -18,6 +18,7 @@ export const zhCN: TranslationResources = { title: "查找", placeholder: "在窗格中查找", + updateHost: "更新主机以使用查找", close: "关闭查找", matches: "查找结果", previous: "上一个匹配项", @@ -189,7 +190,7 @@ export const zhCN: TranslationResources = { unmuteVoice: "取消静音", muteVoice: "静音", dictation: "听写", - interruptBeforeVoice: "启动语音模式前请先中断 Agent", + interruptBeforeVoice: "更新主机以在 Agent 工作时使用语音", }, attachments: { addImage: "添加图片", @@ -223,6 +224,20 @@ 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 并开始新的草稿", @@ -273,6 +288,7 @@ export const zhCN: TranslationResources = { scrollToBottom: "滚动到底部", historyLoadFailed: "无法加载智能体历史记录", messageCapped: "此消息已被截断({{bytes}} 字节)。", + pinnedPrompt: { jump: "滚动到此消息" }, permission: { rejectedPlan: "已拒绝的计划", approvedPlan: "已批准的计划", @@ -285,9 +301,86 @@ export const zhCN: TranslationResources = { implement: "实施", question: "你想如何继续?", proposedPlan: "建议计划", + handOff: "移交", + handedOff: "已移交", + handoffPrompt: "请实施以下建议的计划。", + handoffFailed: "无法移交计划。", + copyContent: "复制内容", + copyLink: "复制链接", + contentCopied: "已复制计划", + linkCopied: "已复制会话链接", + copyFailed: "无法复制计划。", }, }, 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 失败", @@ -582,6 +675,8 @@ export const zhCN: TranslationResources = { }, errors: { failedToListDirectory: "列出目录失败", + pathUnavailable: "无法从对话的工作目录解析此路径。", + outsideWorkspaceDirectory: "此文件夹位于当前工作区之外。请从其源工作区打开。", createFailed: "创建条目失败", renameFailed: "重命名条目失败", duplicateFailed: "复制条目失败", @@ -713,12 +808,15 @@ export const zhCN: TranslationResources = { reloadAgent: "重新加载 Agent", reloadAgentTooltip: "重新加载 Agent 以更新 skills、MCPs 或登录状态。", close: "关闭", + findInChat: "在聊天中查找", renameTerminal: "重命名 Terminal", + viewArtifacts: "查看产出文件", renameAgent: "重命名 Agent", }, actions: { newTab: "新建标签页", newAgent: "新建 Agent", + recentlyClosed: "最近关闭", newTerminal: "新建 Terminal", preparingTerminal: "正在准备 Terminal 标签", preparingTerminalTooltip: "正在准备 Terminal...", @@ -735,6 +833,12 @@ export const zhCN: TranslationResources = { terminalProfilesMenu: "Terminal profiles", editTerminalProfiles: "Edit profiles", }, + recentAgents: { + title: "最近关闭", + loading: "正在加载…", + empty: "此工作区没有已关闭的代理", + showAll: "在历史记录中查看全部", + }, explorerSidebar: { open: "打开侧边面板", close: "关闭侧边面板", @@ -804,8 +908,23 @@ export const zhCN: TranslationResources = { workspacePathCopiedLabel: "Workspace 路径", branchNameCopiedLabel: "分支名称", }, + branches: { + current: "当前分支:{{branchName}}。按下查看分支操作。", + base: "与 {{branchName}} 比较。按下更改基础分支。", + setBase: "设置基础分支", + baseTitle: "比较对象", + baseUnavailable: "请更新主机以更改基础分支", + baseFailed: "更改基础分支失败", + rename: "重命名分支…", + renameTitle: "重命名分支", + renameSubmit: "重命名", + renameFailed: "分支名称无效", + switch: "切换分支…", + }, }, scripts: { + rootPackage: "根目录", + searchPlaceholder: "搜索脚本或软件包…", title: "Scripts", actions: { chooseUrl: "选择 URL", @@ -833,6 +952,8 @@ export const zhCN: TranslationResources = { direct: "直接地址", }, states: { + empty: "未找到脚本", + noMatches: "没有匹配的脚本", exitCode: "exit {{code}}", startFailed: "启动 {{scriptName}} 失败", stopFailed: "停止 {{scriptName}} 失败", @@ -1346,6 +1467,7 @@ export const zhCN: TranslationResources = { }, workspace: { status: { + scriptRunning: "脚本 {{name}} 正在运行", serviceRunning: "服务 {{name}} 运行中", serviceUnhealthy: "服务 {{name}} 异常", creating: "正在创建...", @@ -1399,6 +1521,28 @@ export const zhCN: TranslationResources = { }, }, }, + projectPullRequests: { + checks: { + passed: "所有检查均已通过", + pending: "检查正在运行", + skipped: "检查已跳过", + updateRequired: "请更新此主机以查看 CI 状态。", + }, + title: "拉取请求", + shortcut: "浏览 {{project}} 的拉取请求", + search: "搜索拉取请求", + clearSearch: "清除搜索", + open: "未关闭", + closed: "已关闭", + results: "{{count}} 个结果", + authRequired: "请在此主机上登录 Git 托管服务以浏览拉取请求。", + loading: "正在加载拉取请求…", + empty: "没有匹配的拉取请求。", + limit: "最多显示 {{count}} 个结果。请缩小搜索范围。", + start: "从 #{{number}} 创建工作树:{{title}}", + updated: "更新于 {{date}}", + external: "在浏览器中打开 #{{number}}", + }, newWorkspace: { title: "新建 workspace", create: "创建", @@ -1982,10 +2126,25 @@ 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 并中断 turn", + stop: "停止 realtime voice", }, }, rewind: { @@ -2676,6 +2835,8 @@ export const zhCN: TranslationResources = { jumpToWorkspace: "跳转到 workspace", jumpToTab: "跳转到标签", previousWorkspace: "上一个 workspace", + historyBack: "后退", + historyForward: "前进", nextWorkspace: "下一个 workspace", previousTab: "上一个标签", nextTab: "下一个标签", @@ -3014,9 +3175,49 @@ export const zhCN: TranslationResources = { updateErrorTitle: "无法更新 Provider", actions: { menu: "{{name}} actions", + addAccount: "添加账户", + editAccount: "编辑账户", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "添加 {{provider}} 账户", + editTitle: "编辑 {{provider}} 账户", + errorTitle: "无法保存账户", + submit: "添加账户", + save: "保存更改", + fields: { + label: "名称", + providerId: "Provider ID", + description: "描述", + env: "环境变量", + envKey: "变量名", + envValue: "变量值", + }, + placeholders: { + label: "{{provider}}(工作)", + providerId: "claude-work", + description: "可选", + envKey: "名称", + envValue: "值", + }, + actions: { + addVariable: "添加变量", + removeVariable: "移除变量", + }, + warnings: { + renameUnsupported: + "此主机无法将现有对话迁移到新 ID。在你更新主机或恢复原 ID 之前,使用该账户的对话将不可用。", + }, + errors: { + labelRequired: "请输入名称。", + idRequired: "请输入 Provider ID。", + idInvalid: "只能使用小写字母、数字和连字符,且以字母开头。", + idTaken: "该 Provider ID 已被占用。", + envKeyRequired: "请输入变量名。", + envDuplicate: "该变量已设置。", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/keyboard/actions.ts b/packages/app/src/keyboard/actions.ts index ef656a40a59..918335ec285 100644 --- a/packages/app/src/keyboard/actions.ts +++ b/packages/app/src/keyboard/actions.ts @@ -40,6 +40,8 @@ export type KeyboardActionId = | "workspace.pane.close" | "workspace.navigate.index" | "workspace.navigate.relative" + | "history.back" + | "history.forward" | "sidebar.toggle.left" | "sidebar.toggle.right" | "sidebar.toggle.both" diff --git a/packages/app/src/keyboard/keyboard-shortcuts.test.ts b/packages/app/src/keyboard/keyboard-shortcuts.test.ts index 9eddf4b5b52..d343f83091e 100644 --- a/packages/app/src/keyboard/keyboard-shortcuts.test.ts +++ b/packages/app/src/keyboard/keyboard-shortcuts.test.ts @@ -214,11 +214,11 @@ describe("keyboard-shortcuts", () => { payload: { delta: -1 }, }, { - name: "matches workspace relative navigation on desktop via Mod+]", + name: "matches history forward on desktop via Mod+]", event: { key: "]", code: "BracketRight", ctrlKey: true }, context: { usesDesktopBindings: true }, - action: "workspace.navigate.relative", - payload: { delta: 1 }, + action: "history.forward", + payload: null, }, { name: "matches tab relative navigation via Alt+Shift+]", diff --git a/packages/app/src/keyboard/keyboard-shortcuts.ts b/packages/app/src/keyboard/keyboard-shortcuts.ts index d6db467da3d..d793b6649f5 100644 --- a/packages/app/src/keyboard/keyboard-shortcuts.ts +++ b/packages/app/src/keyboard/keyboard-shortcuts.ts @@ -158,6 +158,8 @@ export const SHORTCUT_HELP_ROW_ORDER: Record = { + "history-back": "settings.shortcuts.help.historyBack", + "history-forward": "settings.shortcuts.help.historyForward", "new-agent": "settings.shortcuts.help.openProject", "new-workspace": "settings.shortcuts.help.newWorkspace", "switch-project": "settings.shortcuts.help.switchProject", @@ -640,11 +644,41 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [ }, }, + // --- In-app history (Electron only; browsers own their back/forward shortcuts) --- + { + id: "history-back-cmd-bracket-left-mac", + action: "history.back", + combo: "Cmd+[", + when: { mac: true, desktopBindings: true, commandCenter: false }, + help: { id: "history-back", section: "general", label: "Back" }, + }, + { + id: "history-back-ctrl-bracket-left-non-mac", + action: "history.back", + combo: "Ctrl+[", + when: { mac: false, desktopBindings: true, commandCenter: false, terminal: false }, + help: { id: "history-back", section: "general", label: "Back" }, + }, + { + id: "history-forward-cmd-bracket-right-mac", + action: "history.forward", + combo: "Cmd+]", + when: { mac: true, desktopBindings: true, commandCenter: false }, + help: { id: "history-forward", section: "general", label: "Forward" }, + }, + { + id: "history-forward-ctrl-bracket-right-non-mac", + action: "history.forward", + combo: "Ctrl+]", + when: { mac: false, desktopBindings: true, commandCenter: false, terminal: false }, + help: { id: "history-forward", section: "general", label: "Forward" }, + }, + // --- Workspace relative navigation --- { id: "workspace-navigate-relative-cmd-left-mac", action: "workspace.navigate.relative", - combo: "Cmd+[", + combo: "Cmd+Alt+[", when: { mac: true, desktopBindings: true, commandCenter: false }, payload: { type: "delta", delta: -1 }, help: { @@ -656,7 +690,7 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [ { id: "workspace-navigate-relative-ctrl-left-non-mac", action: "workspace.navigate.relative", - combo: "Ctrl+[", + combo: "Ctrl+Alt+[", when: { mac: false, desktopBindings: true, commandCenter: false, terminal: false }, payload: { type: "delta", delta: -1 }, help: { @@ -668,7 +702,7 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [ { id: "workspace-navigate-relative-cmd-right-mac", action: "workspace.navigate.relative", - combo: "Cmd+]", + combo: "Cmd+Alt+]", when: { mac: true, desktopBindings: true, commandCenter: false }, payload: { type: "delta", delta: 1 }, help: { @@ -680,7 +714,7 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [ { id: "workspace-navigate-relative-ctrl-right-non-mac", action: "workspace.navigate.relative", - combo: "Ctrl+]", + combo: "Ctrl+Alt+]", when: { mac: false, desktopBindings: true, commandCenter: false, terminal: false }, payload: { type: "delta", delta: 1 }, help: { diff --git a/packages/app/src/keyboard/route-shortcut.test.ts b/packages/app/src/keyboard/route-shortcut.test.ts index 5eddf3eeffc..1d1fc2763d9 100644 --- a/packages/app/src/keyboard/route-shortcut.test.ts +++ b/packages/app/src/keyboard/route-shortcut.test.ts @@ -436,3 +436,20 @@ describe("routeKeyboardShortcut — unknown actions", () => { ).toEqual({ kind: "none" }); }); }); + +describe("routeKeyboardShortcut — history", () => { + it("routes each direction to one history step", () => { + expect( + routeKeyboardShortcut({ action: "history.back", payload: null }, makeCtx()), + ).toEqual({ + kind: "history-go", + delta: -1, + }); + expect( + routeKeyboardShortcut({ action: "history.forward", payload: null }, makeCtx()), + ).toEqual({ + kind: "history-go", + delta: 1, + }); + }); +}); diff --git a/packages/app/src/keyboard/route-shortcut.ts b/packages/app/src/keyboard/route-shortcut.ts index 79579689fda..0225b4054e3 100644 --- a/packages/app/src/keyboard/route-shortcut.ts +++ b/packages/app/src/keyboard/route-shortcut.ts @@ -29,6 +29,7 @@ export type ShortcutAction = | { kind: "navigate-last-workspace" } | { kind: "router-replace"; route: string } | { kind: "router-back" } + | { kind: "history-go"; delta: 1 | -1 } | { kind: "router-push"; route: string } | { kind: "open-project-picker" } | { kind: "callback"; name: ShortcutCallbackName } @@ -208,6 +209,10 @@ export function routeKeyboardShortcut( return { kind: "open-project-picker" }; case "settings.toggle": return routeSettingsToggle(ctx); + case "history.back": + return { kind: "history-go", delta: -1 }; + case "history.forward": + return { kind: "history-go", delta: 1 }; case "command-center.toggle": return { kind: "command-center-toggle", nextOpen: !ctx.commandCenterOpen }; case "command-center.files": diff --git a/packages/app/src/keyboard/use-shortcuts.ts b/packages/app/src/keyboard/use-shortcuts.ts index b762d8dfcfe..f605d6c7b76 100644 --- a/packages/app/src/keyboard/use-shortcuts.ts +++ b/packages/app/src/keyboard/use-shortcuts.ts @@ -7,6 +7,7 @@ import type { KeyboardInputEvent } from "./internal/overlays"; import { hasActiveOverlay } from "./internal/overlay-dispatch"; import { useCallback, useEffect, useMemo, useRef } from "react"; import { usePathname, useRouter } from "expo-router"; +import { goHistory } from "@/navigation/history/replay"; import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store"; import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store"; import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context"; @@ -139,6 +140,8 @@ export function useKeyboardShortcuts({ case "router-back": router.back(); return true; + case "history-go": + return goHistory(action.delta); case "router-push": router.push(action.route as Parameters[0]); return true; diff --git a/packages/app/src/navigation/history/model.test.ts b/packages/app/src/navigation/history/model.test.ts new file mode 100644 index 00000000000..c8b713d29c4 --- /dev/null +++ b/packages/app/src/navigation/history/model.test.ts @@ -0,0 +1,295 @@ +import { describe, expect, it } from "vitest"; +import { + classifyLocation, + EMPTY_HISTORY_STATE, + entriesEqual, + HISTORY_ENTRY_CAP, + isTransientPathname, + pushEntry, + replaceEntryAt, + resolveWorkspaceReplay, + stepIndex, + type HistoryEntry, + type HistoryState, +} from "./model"; + +type WorkspaceTarget = Extract["target"]; + +function workspace( + workspaceId: string, + tabId: string | null = null, + target: WorkspaceTarget = null, +): HistoryEntry { + return { kind: "workspace", serverId: "srv", workspaceId, tabId, target }; +} + +function route(path: string): HistoryEntry { + return { kind: "route", path }; +} + +function stateOf(entries: HistoryEntry[], index = entries.length - 1): HistoryState { + return { entries, index }; +} + +describe("entriesEqual", () => { + it("compares workspace entries by workspace and tab only", () => { + expect( + entriesEqual(workspace("ws", "t1", { kind: "files" }), workspace("ws", "t1", null)), + ).toBe(true); + expect(entriesEqual(workspace("ws", "t1"), workspace("ws", "t2"))).toBe(false); + expect(entriesEqual(workspace("ws", "t1"), workspace("other", "t1"))).toBe(false); + }); + + it("compares route entries by path and never across kinds", () => { + expect(entriesEqual(route("/settings/general"), route("/settings/general"))).toBe(true); + expect(entriesEqual(route("/settings/general"), route("/sessions"))).toBe(false); + expect(entriesEqual(route("/sessions"), workspace("ws"))).toBe(false); + }); +}); + +describe("pushEntry", () => { + it("appends and advances the index", () => { + const state = pushEntry(EMPTY_HISTORY_STATE, workspace("a")); + expect(state).toEqual(stateOf([workspace("a")])); + }); + + it("is a no-op when the entry equals the current one", () => { + const state = stateOf([workspace("a", "t1")]); + expect(pushEntry(state, workspace("a", "t1", { kind: "files" }))).toBe(state); + }); + + it("drops the forward branch when pushing after going back", () => { + const state = stateOf([workspace("a"), workspace("b"), workspace("c")], 0); + expect(pushEntry(state, route("/sessions"))).toEqual( + stateOf([workspace("a"), route("/sessions")]), + ); + }); + + it("caps the stack by dropping the oldest entries and shifting the index", () => { + let state = EMPTY_HISTORY_STATE; + for (let i = 0; i < HISTORY_ENTRY_CAP + 5; i += 1) { + state = pushEntry(state, workspace(`ws-${i}`)); + } + expect(state.entries).toHaveLength(HISTORY_ENTRY_CAP); + expect(state.entries[0]).toEqual(workspace("ws-5")); + expect(state.index).toBe(HISTORY_ENTRY_CAP - 1); + }); +}); + +describe("replaceEntryAt", () => { + it("swaps an entry without moving the index", () => { + const state = stateOf([workspace("a"), workspace("b")], 0); + const next = replaceEntryAt(state, 1, workspace("b", "t9")); + expect(next.entries[1]).toEqual(workspace("b", "t9")); + expect(next.index).toBe(0); + }); + + it("ignores out-of-range indices", () => { + const state = stateOf([workspace("a")]); + expect(replaceEntryAt(state, 3, workspace("z"))).toBe(state); + }); +}); + +describe("stepIndex", () => { + const entries = [workspace("a"), workspace("b"), workspace("c"), workspace("d")]; + const alive = () => true; + + it("moves one step in either direction", () => { + expect(stepIndex(stateOf(entries, 2), -1, alive)).toBe(1); + expect(stepIndex(stateOf(entries, 2), 1, alive)).toBe(3); + }); + + it("returns null at the ends", () => { + expect(stepIndex(stateOf(entries, 0), -1, alive)).toBeNull(); + expect(stepIndex(stateOf(entries, 3), 1, alive)).toBeNull(); + expect(stepIndex(EMPTY_HISTORY_STATE, -1, alive)).toBeNull(); + }); + + it("skips dead entries in both directions", () => { + const isAlive = (entry: HistoryEntry) => + entry.kind === "workspace" && entry.workspaceId !== "b" && entry.workspaceId !== "c"; + expect(stepIndex(stateOf(entries, 3), -1, isAlive)).toBe(0); + expect(stepIndex(stateOf(entries, 0), 1, isAlive)).toBe(3); + }); + + it("returns null when every remaining entry is dead", () => { + expect(stepIndex(stateOf(entries, 3), -1, () => false)).toBeNull(); + }); +}); + +describe("isTransientPathname", () => { + it.each([ + "/", + "", + "/welcome", + "/pair-scan", + "/settings", + "/settings/", + "/settings/hosts/srv", + "/h/srv", + "/h/srv/", + "/h/srv/agent/agent-1", + "/h/srv/sessions", + "/h/srv/settings", + "/h/srv/open-project", + "/h/srv/plugin/plug/surface", + "/welcome?x=1", + ])("treats %s as transient", (pathname) => { + expect(isTransientPathname(pathname)).toBe(true); + }); + + it.each([ + "/settings/general", + "/settings/hosts/srv/connections", + "/settings/hosts/srv/projects/proj-1", + "/sessions", + "/schedules", + "/new", + "/open-project", + "/h/srv/plugin/plug/sidebar/surface", + "/h/srv/plugin/plug/surface/contribution", + ])("treats %s as a resting route", (pathname) => { + expect(isTransientPathname(pathname)).toBe(false); + }); +}); + +describe("classifyLocation", () => { + it("returns a tab-less workspace entry for a workspace route", () => { + expect(classifyLocation({ pathname: "/h/srv/workspace/ws-1", params: {} })).toEqual( + workspace("ws-1"), + ); + }); + + it("falls back to route params on cold mount at /", () => { + expect( + classifyLocation({ pathname: "/", params: { serverId: "srv", workspaceId: "ws-1" } }), + ).toEqual(workspace("ws-1")); + }); + + it("returns null for transient routes", () => { + expect(classifyLocation({ pathname: "/welcome", params: {} })).toBeNull(); + expect(classifyLocation({ pathname: "/h/srv/agent/a1", params: {} })).toBeNull(); + expect(classifyLocation({ pathname: "/", params: {} })).toBeNull(); + }); + + it("returns a route entry with a normalized path otherwise", () => { + expect(classifyLocation({ pathname: "/settings/general/", params: {} })).toEqual( + route("/settings/general"), + ); + expect(classifyLocation({ pathname: "/sessions?x=1", params: {} })).toEqual(route("/sessions")); + }); + + it("preserves creation inputs in the route history entry", () => { + expect( + classifyLocation({ + pathname: "/new", + params: { + serverId: "host-1", + dir: "/code/a b", + name: "Feature & fix", + projectId: "project-1", + draftId: "draft-1", + changeRequest: '{"kind":"change_request","number":7}', + }, + }), + ).toEqual( + route( + "/new?serverId=host-1&dir=%2Fcode%2Fa%20b&name=Feature%20%26%20fix&projectId=project-1&draftId=draft-1&changeRequest=%7B%22kind%22%3A%22change_request%22%2C%22number%22%3A7%7D", + ), + ); + }); + + // A selected change request is checkout context: two PR selections are two different places, and + // the same selection twice is one entry. + it("keeps distinct change requests as distinct history entries", () => { + const at = (changeRequest: string) => + classifyLocation({ pathname: "/new", params: { serverId: "host-1", changeRequest } }); + + const seven = at('{"kind":"change_request","number":7}'); + const eight = at('{"kind":"change_request","number":8}'); + + expect(seven).not.toBeNull(); + expect(eight).not.toBeNull(); + expect(entriesEqual(seven!, eight!)).toBe(false); + expect(entriesEqual(seven!, at('{"kind":"change_request","number":7}')!)).toBe(true); + }); +}); + +describe("resolveWorkspaceReplay", () => { + const entry = ( + tabId: string | null, + target: WorkspaceTarget, + ): Extract => ({ + kind: "workspace", + serverId: "srv", + workspaceId: "ws", + tabId, + target, + }); + const ctx = (overrides: Partial[1]> = {}) => ({ + workspaceExists: true, + tabExists: true, + agentExists: () => true, + ...overrides, + }); + + it("routes an absent workspace to its recovery screen", () => { + expect( + resolveWorkspaceReplay(entry("t", { kind: "files" }), ctx({ workspaceExists: false })), + ).toEqual({ kind: "workspace-only" }); + }); + + it("focuses an existing tab", () => { + expect( + resolveWorkspaceReplay(entry("tab_1", { kind: "terminal", terminalId: "x" }), ctx()), + ).toEqual({ kind: "focus", tabId: "tab_1" }); + }); + + const reopenable: WorkspaceTarget[] = [ + { kind: "files" }, + { kind: "changes_tree" }, + { kind: "pull_request" }, + { kind: "working_diff" }, + { kind: "file", path: "src/a.ts" }, + ]; + it.each(reopenable)("re-opens a closed %o tab", (target) => { + expect(resolveWorkspaceReplay(entry("gone", target), ctx({ tabExists: false }))).toEqual({ + kind: "reopen", + target, + }); + }); + + it("re-opens a closed agent tab only while the agent still exists", () => { + const target = { kind: "agent", agentId: "a1" } as const; + expect(resolveWorkspaceReplay(entry("agent_a1", target), ctx({ tabExists: false }))).toEqual({ + kind: "reopen", + target, + }); + expect( + resolveWorkspaceReplay( + entry("agent_a1", target), + ctx({ tabExists: false, agentExists: () => false }), + ), + ).toEqual({ kind: "dead" }); + }); + + const dead: WorkspaceTarget[] = [ + { kind: "terminal", terminalId: "t" }, + { kind: "browser", browserId: "b" }, + { kind: "draft", draftId: "d" }, + { kind: "commit_diff", sha: "abc" }, + { kind: "setup", workspaceId: "ws" }, + { kind: "new_tab" }, + ]; + it.each(dead)("leaves a closed %o tab for dead", (target) => { + expect(resolveWorkspaceReplay(entry("gone", target), ctx({ tabExists: false }))).toEqual({ + kind: "dead", + }); + }); + + it("navigates to the workspace alone when no tab was recorded", () => { + expect(resolveWorkspaceReplay(entry(null, null), ctx({ tabExists: false }))).toEqual({ + kind: "workspace-only", + }); + }); +}); diff --git a/packages/app/src/navigation/history/model.ts b/packages/app/src/navigation/history/model.ts new file mode 100644 index 00000000000..ac0003fe60f --- /dev/null +++ b/packages/app/src/navigation/history/model.ts @@ -0,0 +1,194 @@ +import type { WorkspaceTabTarget } from "@/workspace-tabs/model"; +import { + parseActiveWorkspaceSelection, + type RouteSelectionInput, +} from "@/stores/navigation-active-workspace-store/navigation"; + +/** + * One place the user was looking at. Workspace entries carry the focused tab so back/forward + * steps through tabs as well as workspaces. `target` is payload for re-opening a closed tab, + * never identity: only `tabId` decides whether two entries are the same place. + */ +export type HistoryEntry = + | { + kind: "workspace"; + serverId: string; + workspaceId: string; + tabId: string | null; + target: WorkspaceTabTarget | null; + } + | { kind: "route"; path: string }; + +export interface HistoryState { + entries: readonly HistoryEntry[]; + index: number; +} + +export const EMPTY_HISTORY_STATE: HistoryState = { entries: [], index: -1 }; + +export const HISTORY_ENTRY_CAP = 100; + +export function entriesEqual(a: HistoryEntry, b: HistoryEntry): boolean { + if (a.kind === "route") { + return b.kind === "route" && a.path === b.path; + } + if (b.kind === "route") { + return false; + } + return a.serverId === b.serverId && a.workspaceId === b.workspaceId && a.tabId === b.tabId; +} + +/** Appends a visited location: no-op on the current entry, drops the forward branch, caps size. */ +export function pushEntry(state: HistoryState, entry: HistoryEntry): HistoryState { + const current = state.entries[state.index]; + if (current && entriesEqual(current, entry)) { + return state; + } + const kept = state.entries.slice(0, state.index + 1); + kept.push(entry); + const overflow = Math.max(0, kept.length - HISTORY_ENTRY_CAP); + const entries = overflow > 0 ? kept.slice(overflow) : kept; + return { entries, index: entries.length - 1 }; +} + +export function replaceEntryAt( + state: HistoryState, + index: number, + entry: HistoryEntry, +): HistoryState { + if (index < 0 || index >= state.entries.length) { + return state; + } + const entries = state.entries.slice(); + entries[index] = entry; + return { entries, index: state.index }; +} + +/** Next index in `delta` direction whose entry is still alive, or null at the end of the stack. */ +export function stepIndex( + state: HistoryState, + delta: 1 | -1, + isAlive: (entry: HistoryEntry) => boolean, +): number | null { + for ( + let index = state.index + delta; + index >= 0 && index < state.entries.length; + index += delta + ) { + const entry = state.entries[index]; + if (entry && isAlive(entry)) { + return index; + } + } + return null; +} + +// Routes that only exist to redirect somewhere else. Recording them would leave a dead entry in +// front of every real destination. A deny-list rather than an allow-list so new resting routes +// are recorded without anyone remembering this file. +const TRANSIENT_EXACT_PATHS = new Set(["", "/", "/welcome", "/pair-scan", "/settings"]); +const TRANSIENT_PATH_PATTERNS: readonly RegExp[] = [ + /^\/settings\/hosts\/[^/]+$/, + /^\/h\/[^/]+$/, + /^\/h\/[^/]+\/(agent|sessions|settings|open-project)(\/|$)/, + // The three-segment plugin URL is the legacy redirect. Current plugin surfaces add both a + // contribution kind and id, so those remain resting routes and belong in app history. + /^\/h\/[^/]+\/plugin\/[^/]+\/[^/]+$/, +]; + +function normalizePathname(pathname: string): string { + const withoutSearch = pathname.split(/[?#]/, 1)[0] ?? ""; + if (withoutSearch.length > 1 && withoutSearch.endsWith("/")) { + return withoutSearch.slice(0, -1); + } + return withoutSearch; +} + +export function isTransientPathname(pathname: string): boolean { + const normalized = normalizePathname(pathname); + if (TRANSIENT_EXACT_PATHS.has(normalized)) { + return true; + } + return TRANSIENT_PATH_PATTERNS.some((pattern) => pattern.test(normalized)); +} + +/** + * Turns the current route into a history entry, or null for routes that are not a resting place. + * Workspace entries come back with no tab; the recorder fills that in from the layout store. + */ +export function classifyLocation(input: RouteSelectionInput): HistoryEntry | null { + const selection = parseActiveWorkspaceSelection(input); + if (selection) { + return { kind: "workspace", ...selection, tabId: null, target: null }; + } + if (isTransientPathname(input.pathname)) { + return null; + } + const path = normalizePathname(input.pathname); + if (path === "/new") { + // These are the route's screen inputs. Without them Back opens a blank creation form and + // loses the selected host, source directory, draft context, or the change request the form + // was seeded with. + const keys = ["serverId", "dir", "name", "projectId", "draftId", "changeRequest"] as const; + const query = keys.flatMap((key) => { + const value = input.params[key]; + return typeof value === "string" + ? [`${encodeURIComponent(key)}=${encodeURIComponent(value)}`] + : []; + }); + return { kind: "route", path: query.length > 0 ? `${path}?${query.join("&")}` : path }; + } + return { kind: "route", path }; +} + +export type WorkspaceReplayPlan = + | { kind: "focus"; tabId: string } + | { kind: "reopen"; target: WorkspaceTabTarget } + | { kind: "workspace-only" } + | { kind: "dead" }; + +export interface WorkspaceReplayContext { + workspaceExists: boolean; + tabExists: boolean; + agentExists: (agentId: string) => boolean; +} + +// Targets whose tab can be recreated from the target alone once it has been closed. Anything +// backed by a live resource (terminal, browser, draft, subagent) or that is intentionally +// ephemeral (commit_diff, setup, new_tab) is left for dead instead of resurrecting a shell. +function isReopenableTarget(target: WorkspaceTabTarget, ctx: WorkspaceReplayContext): boolean { + switch (target.kind) { + case "file": + case "files": + case "changes_tree": + case "working_diff": + case "pull_request": + case "plugin": + return true; + case "agent": + return ctx.agentExists(target.agentId); + default: + return false; + } +} + +export function resolveWorkspaceReplay( + entry: Extract, + ctx: WorkspaceReplayContext, +): WorkspaceReplayPlan { + if (!ctx.workspaceExists) { + // Archived workspaces disappear from the live map. The workspace route owns authoritative + // recovery and can offer Restore or Unarchive once it has inspected the daemon state. + return { kind: "workspace-only" }; + } + if (entry.tabId && ctx.tabExists) { + return { kind: "focus", tabId: entry.tabId }; + } + if (entry.target && isReopenableTarget(entry.target, ctx)) { + return { kind: "reopen", target: entry.target }; + } + if (entry.tabId === null && entry.target === null) { + return { kind: "workspace-only" }; + } + return { kind: "dead" }; +} diff --git a/packages/app/src/navigation/history/record-location.test.ts b/packages/app/src/navigation/history/record-location.test.ts new file mode 100644 index 00000000000..613c8ab9f81 --- /dev/null +++ b/packages/app/src/navigation/history/record-location.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, it } from "vitest"; +import { createWorkspaceLayoutStore } from "@/stores/workspace-layout-store"; +import { classifyLocation, type HistoryEntry } from "./model"; +import { recordNavigationLocation } from "./recorder"; +import { goHistory, type HistoryReplayDeps } from "./replay"; +import { selectActiveWorkspaceTabId } from "./select-active-tab"; +import { createNavigationHistoryStore } from "./store"; + +function createNavigation() { + const layout = createWorkspaceLayoutStore(undefined, { + getItem: () => null, + setItem: () => {}, + removeItem: () => {}, + }); + const history = createNavigationHistoryStore(); + let pathname = "/"; + const observe = () => { + const location = classifyLocation({ pathname, params: {} }); + if (!location) return; + let entry: HistoryEntry = location; + if (location.kind === "workspace") { + const key = `${location.serverId}:${location.workspaceId}`; + const tabId = selectActiveWorkspaceTabId(layout.getState(), key); + const tab = layout + .getState() + .getWorkspaceTabs(key) + .find((candidate) => candidate.tabId === tabId); + entry = { ...location, tabId, target: tab?.target ?? null }; + } + recordNavigationLocation(history, entry); + }; + const navigate = (path: string) => { + pathname = path; + observe(); + }; + const deps: HistoryReplayDeps = { + navigateToRoute: navigate, + navigateToWorkspace: ({ serverId, workspaceId, target }) => { + if (target) + layout + .getState() + .openTab({ workspaceKey: `${serverId}:${workspaceId}`, target, intent: "reveal" }); + // Route observation follows synchronous replay changes, as it does in the React effect. + pathname = `/h/${serverId}/workspace/${workspaceId}`; + }, + focusTab: (key, tabId) => { + layout.getState().focusTab(key, tabId); + }, + getFocusedTabId: (key) => selectActiveWorkspaceTabId(layout.getState(), key), + workspaceExists: () => true, + tabExists: (key, tabId) => + layout + .getState() + .getWorkspaceTabs(key) + .some((tab) => tab.tabId === tabId), + agentExists: () => true, + }; + const step = (delta: 1 | -1) => { + const result = goHistory(delta, history, deps); + observe(); + return result; + }; + return { layout, history, observe, navigate, step, pathname: () => pathname }; +} + +describe("recorded navigation replay", () => { + it("preserves Forward after visiting a workspace before its layout exists", () => { + const nav = createNavigation(); + nav.navigate("/settings/general"); + nav.navigate("/h/srv/workspace/first"); + nav.layout.getState().openTab({ + workspaceKey: "srv:first", + target: { kind: "agent", agentId: "a1" }, + intent: "reveal", + }); + nav.observe(); + nav.navigate("/sessions"); + const visited = nav.history.getState().entries; + expect(nav.step(-1)).toBe(true); + expect(nav.pathname()).toBe("/h/srv/workspace/first"); + expect(nav.step(-1)).toBe(true); + expect(nav.pathname()).toBe("/settings/general"); + expect(nav.step(1)).toBe(true); + expect(nav.pathname()).toBe("/h/srv/workspace/first"); + expect(nav.step(1)).toBe(true); + expect(nav.pathname()).toBe("/sessions"); + expect(nav.history.getState()).toEqual({ entries: visited, index: 2 }); + }); + + it("records a settled empty workspace and ignores composer focus changes", () => { + const nav = createNavigation(); + nav.navigate("/welcome"); + const tabId = nav.layout + .getState() + .openTab({ workspaceKey: "srv:empty", target: { kind: "new_tab" }, intent: "new" }); + nav.navigate("/h/srv/workspace/empty"); + nav.layout.getState().unfocusPane("srv:empty"); + nav.observe(); + expect(nav.history.getState()).toEqual({ + entries: [ + { + kind: "workspace", + serverId: "srv", + workspaceId: "empty", + tabId, + target: { kind: "new_tab" }, + }, + ], + index: 0, + }); + }); + + it("keeps retargeted tabs replayable and reopens a closed file without losing Forward", () => { + const nav = createNavigation(); + const key = "srv:first"; + const tabId = nav.layout + .getState() + .openTab({ workspaceKey: key, target: { kind: "file", path: "first.ts" }, intent: "new" })!; + nav.navigate("/h/srv/workspace/first"); + nav.layout.getState().replaceTab(key, tabId, { kind: "file", path: "second.ts" }); + nav.observe(); + expect(nav.history.getState().entries).toEqual([ + { + kind: "workspace", + serverId: "srv", + workspaceId: "first", + tabId, + target: { kind: "file", path: "second.ts" }, + }, + ]); + nav.navigate("/sessions"); + nav.layout.getState().closeTab(key, tabId); + expect(nav.step(-1)).toBe(true); + expect(nav.pathname()).toBe("/h/srv/workspace/first"); + expect(nav.step(1)).toBe(true); + expect(nav.pathname()).toBe("/sessions"); + expect(nav.history.getState().entries).toHaveLength(2); + }); + + it("keeps Forward when a closed duplicate replays into another tab with the same target", () => { + const nav = createNavigation(); + const key = "srv:first"; + const target = { kind: "file", path: "same.ts" } as const; + const first = nav.layout.getState().openTab({ workspaceKey: key, target, intent: "new" }); + const second = nav.layout.getState().openTab({ workspaceKey: key, target, intent: "new" }); + expect(first).not.toBe(second); + nav.navigate("/h/srv/workspace/first"); + nav.navigate("/sessions"); + nav.layout.getState().closeTab(key, second!); + + expect(nav.step(-1)).toBe(true); + expect(nav.history.getState().entries[0]).toEqual({ + kind: "workspace", + serverId: "srv", + workspaceId: "first", + tabId: first, + target, + }); + expect(nav.step(1)).toBe(true); + expect(nav.pathname()).toBe("/sessions"); + expect(nav.history.getState().entries).toHaveLength(2); + }); +}); diff --git a/packages/app/src/navigation/history/recorder.test.tsx b/packages/app/src/navigation/history/recorder.test.tsx new file mode 100644 index 00000000000..9710cf3159c --- /dev/null +++ b/packages/app/src/navigation/history/recorder.test.tsx @@ -0,0 +1,271 @@ +/** + * @vitest-environment jsdom + */ +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"; + +vi.hoisted(() => { + (globalThis as unknown as { __DEV__: boolean }).__DEV__ = false; +}); + +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); + }), + }, + }; +}); + +interface RouteSnapshot { + pathname: string; + params: Record; +} + +const routeStore = vi.hoisted(() => { + let state: { pathname: string; params: Record } = { pathname: "/", params: {} }; + const listeners = new Set<() => void>(); + return { + get: () => state, + set: (next: { pathname: string; params?: Record }) => { + state = { pathname: next.pathname, params: next.params ?? {} }; + for (const listener of listeners) listener(); + }, + subscribe: (listener: () => void) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }; +}); + +vi.mock("expo-router", async () => { + const ReactModule = await import("react"); + return { + usePathname: () => + ReactModule.useSyncExternalStore(routeStore.subscribe, () => routeStore.get().pathname), + useGlobalSearchParams: () => + ReactModule.useSyncExternalStore(routeStore.subscribe, () => routeStore.get().params), + router: { navigate: vi.fn(), push: vi.fn(), replace: vi.fn() }, + }; +}); + +import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store"; +import type { HistoryEntry } from "./model"; +import { NavigationHistoryRecorder } from "./recorder"; +import { createNavigationHistoryStore } from "./store"; + +const WS1 = "srv:ws-1"; +const WS2 = "srv:ws-2"; +// Main-pane targets with deterministic ids. `files` / `changes_tree` live in the Explorer +// sidebar pane, which the recorder ignores. +const AGENT = { kind: "agent", agentId: "a1" } as const; +const TERMINAL = { kind: "terminal", terminalId: "t1" } as const; + +const ws = ( + workspaceId: string, + tabId: string | null, + target: Extract["target"] = null, +): HistoryEntry => ({ kind: "workspace", serverId: "srv", workspaceId, tabId, target }); + +describe("NavigationHistoryRecorder", () => { + let root: Root | null = null; + let container: HTMLElement | null = null; + let history: ReturnType; + + const layout = () => useWorkspaceLayoutStore.getState(); + + const navigate = (snapshot: RouteSnapshot | string) => { + act(() => { + routeStore.set(typeof snapshot === "string" ? { pathname: snapshot } : snapshot); + }); + }; + + beforeEach(async () => { + await useWorkspaceLayoutStore.persist.rehydrate(); + layout().purgeWorkspace(WS1); + layout().purgeWorkspace(WS2); + routeStore.set({ pathname: "/" }); + history = createNavigationHistoryStore(); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + await act(async () => { + root?.render(); + }); + }); + + afterEach(() => { + act(() => { + root?.unmount(); + }); + root = null; + container?.remove(); + container = null; + }); + + it("records nothing for transient routes", () => { + navigate("/welcome"); + navigate("/h/srv"); + expect(history.getState().entries).toEqual([]); + }); + + it("records the creation route with its draft and source directory", () => { + navigate({ + pathname: "/new", + params: { serverId: "srv", dir: "/code/a b", draftId: "draft-1" }, + }); + + expect(history.getState().entries).toEqual([ + { kind: "route", path: "/new?serverId=srv&dir=%2Fcode%2Fa%20b&draftId=draft-1" }, + ]); + }); + + // A selected change request is checkout context the form was seeded with. It has to survive + // recording, and a swap to a different change request has to be a distinct entry rather than a + // no-op, which is what the recorder's memo dependencies decide. + it("records the creation route's change request and follows a swap to another one", () => { + const selectChangeRequest = (number: number) => + navigate({ + pathname: "/new", + params: { + serverId: "srv", + draftId: "draft-1", + changeRequest: `{"kind":"change_request","number":${number}}`, + }, + }); + const path = (number: number) => + `/new?serverId=srv&draftId=draft-1&changeRequest=${encodeURIComponent( + `{"kind":"change_request","number":${number}}`, + )}`; + + selectChangeRequest(7); + expect(history.getState().entries).toEqual([{ kind: "route", path: path(7) }]); + + selectChangeRequest(8); + expect(history.getState().entries).toEqual([ + { kind: "route", path: path(7) }, + { kind: "route", path: path(8) }, + ]); + expect(history.getState().index).toBe(1); + }); + + it("records app-wide routes and workspaces as the pathname changes", () => { + act(() => { + layout().openTab({ workspaceKey: WS1, target: AGENT, intent: "reveal" }); + }); + navigate("/settings/general"); + navigate("/h/srv/workspace/ws-1"); + navigate("/sessions"); + + expect(history.getState().entries).toEqual([ + { kind: "route", path: "/settings/general" }, + ws("ws-1", "agent_a1", AGENT), + { kind: "route", path: "/sessions" }, + ]); + expect(history.getState().index).toBe(2); + }); + + it("records the focused tab and follows tab changes inside the active workspace", () => { + act(() => { + layout().openTab({ workspaceKey: WS1, target: AGENT, intent: "reveal" }); + }); + navigate("/h/srv/workspace/ws-1"); + act(() => { + layout().openTab({ workspaceKey: WS1, target: TERMINAL, intent: "reveal" }); + }); + act(() => { + layout().focusTab(WS1, "agent_a1"); + }); + + expect(history.getState().entries).toEqual([ + ws("ws-1", "agent_a1", AGENT), + ws("ws-1", "terminal_t1", TERMINAL), + ws("ws-1", "agent_a1", AGENT), + ]); + }); + + it("refreshes a tab's replay target when its id is retained during replacement", () => { + act(() => { + layout().openTab({ workspaceKey: WS1, target: AGENT, intent: "reveal" }); + }); + navigate("/h/srv/workspace/ws-1"); + + act(() => { + layout().replaceTab(WS1, "agent_a1", { kind: "agent", agentId: "a2" }); + }); + + expect(history.getState().entries).toEqual([ + ws("ws-1", "agent_a1", { kind: "agent", agentId: "a2" }), + ]); + }); + + it("ignores tab changes in a workspace that is not on screen", () => { + act(() => { + layout().openTab({ workspaceKey: WS1, target: AGENT, intent: "reveal" }); + }); + navigate("/h/srv/workspace/ws-1"); + act(() => { + layout().openTab({ workspaceKey: WS2, target: TERMINAL, intent: "reveal" }); + layout().openTab({ workspaceKey: WS2, target: AGENT, intent: "reveal" }); + }); + + expect(history.getState().entries).toEqual([ws("ws-1", "agent_a1", AGENT)]); + }); + + it("does not record while pane focus is parked in the composer", () => { + act(() => { + layout().openTab({ workspaceKey: WS1, target: AGENT, intent: "reveal" }); + }); + navigate("/h/srv/workspace/ws-1"); + act(() => { + layout().unfocusPane(WS1); + }); + + expect(history.getState().entries).toEqual([ws("ws-1", "agent_a1", AGENT)]); + }); + + it("treats landing on the current entry after a replay as a no-op", () => { + act(() => { + layout().openTab({ workspaceKey: WS1, target: AGENT, intent: "reveal" }); + layout().openTab({ workspaceKey: WS2, target: TERMINAL, intent: "reveal" }); + }); + navigate("/h/srv/workspace/ws-1"); + navigate("/h/srv/workspace/ws-2"); + expect(history.getState().index).toBe(1); + + // What goHistory(-1) does: move the index, then navigate. + act(() => { + history.setIndex(0); + }); + navigate("/h/srv/workspace/ws-1"); + + expect(history.getState().entries).toHaveLength(2); + expect(history.getState().index).toBe(0); + + // A genuine new navigation afterwards truncates the forward branch. + navigate("/settings/general"); + expect(history.getState().entries).toEqual([ + ws("ws-1", "agent_a1", AGENT), + { kind: "route", path: "/settings/general" }, + ]); + }); + + it("picks up the workspace from route params on cold mount at /", () => { + act(() => { + layout().openTab({ workspaceKey: WS1, target: AGENT, intent: "reveal" }); + }); + navigate({ pathname: "/", params: { serverId: "srv", workspaceId: "ws-1" } }); + + expect(history.getState().entries).toEqual([ws("ws-1", "agent_a1", AGENT)]); + }); +}); diff --git a/packages/app/src/navigation/history/recorder.tsx b/packages/app/src/navigation/history/recorder.tsx new file mode 100644 index 00000000000..23f29b100d1 --- /dev/null +++ b/packages/app/src/navigation/history/recorder.tsx @@ -0,0 +1,119 @@ +import { useGlobalSearchParams, usePathname } from "expo-router"; +import { useEffect, useMemo } from "react"; +import { + useWorkspaceLayoutStore, + useWorkspaceLayoutStoreHydrated, +} from "@/stores/workspace-layout-store"; +import { workspaceTabTargetsEqual } from "@/workspace-tabs/identity"; +import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model"; +import { classifyLocation, entriesEqual, type HistoryEntry } from "./model"; +import { selectActiveWorkspaceTabId } from "./select-active-tab"; +import { navigationHistoryStore, type NavigationHistoryStore } from "./store"; + +/** + * Records where the user is looking as navigation history. Mounted once, renders nothing. + * + * Observation is a React effect on (pathname, focused tab of the pathname's workspace), not a raw + * store subscription. `navigateToWorkspace` writes the destination's layout before the pathname + * flips, so a raw subscription would see a torn (old pathname, new tab) sample. Selecting the tab + * for the workspace the pathname names makes that intermediate state invisible: while the + * pathname still says A, A's tab is unchanged and nothing is recorded. + * + * Replay never needs to suppress recording. It moves the index first, so the landing location + * equals the current entry and the compare below turns it into a no-op. + */ +export function NavigationHistoryRecorder({ + store = navigationHistoryStore, +}: { + store?: NavigationHistoryStore; +}) { + const pathname = usePathname(); + const params = useGlobalSearchParams<{ + serverId?: string | string[]; + workspaceId?: string | string[]; + dir?: string | string[]; + name?: string | string[]; + projectId?: string | string[]; + draftId?: string | string[]; + changeRequest?: string | string[]; + }>(); + const { serverId, workspaceId, dir, name, projectId, draftId, changeRequest } = params; + const hydrated = useWorkspaceLayoutStoreHydrated(); + + const location = useMemo( + () => + classifyLocation({ + pathname, + params: { serverId, workspaceId, dir, name, projectId, draftId, changeRequest }, + }), + [pathname, serverId, workspaceId, dir, name, projectId, draftId, changeRequest], + ); + const workspaceKey = + location?.kind === "workspace" ? buildWorkspaceTabPersistenceKey(location) : null; + const focusedTabId = useWorkspaceLayoutStore((state) => + workspaceKey && hydrated ? selectActiveWorkspaceTabId(state, workspaceKey) : null, + ); + // getWorkspaceTabs normalizes the persisted layout and therefore returns fresh tab objects. + // Subscribe to a primitive target signature so same-ID retargets trigger this observer without + // handing Zustand an uncached object snapshot. + const focusedTabTargetSignature = useWorkspaceLayoutStore((state) => { + if (!workspaceKey || !hydrated) { + return null; + } + const activeTabId = selectActiveWorkspaceTabId(state, workspaceKey); + const focusedTab = activeTabId + ? state.getWorkspaceTabs(workspaceKey).find((candidate) => candidate.tabId === activeTabId) + : undefined; + return focusedTab ? JSON.stringify(focusedTab.target) : null; + }); + + useEffect(() => { + if (!location) { + return; + } + let entry: HistoryEntry; + if (location.kind === "workspace") { + if (!hydrated || !workspaceKey) { + return; + } + const tab = focusedTabId + ? useWorkspaceLayoutStore + .getState() + .getWorkspaceTabs(workspaceKey) + .find((candidate) => candidate.tabId === focusedTabId) + : undefined; + entry = { ...location, tabId: focusedTabId, target: tab?.target ?? null }; + } else { + entry = location; + } + recordNavigationLocation(store, entry); + }, [focusedTabId, focusedTabTargetSignature, hydrated, location, store, workspaceKey]); + + return null; +} + +export function recordNavigationLocation(store: NavigationHistoryStore, entry: HistoryEntry) { + // Missing layouts and Explorer-only focus are transitional. Settled empty workspaces have + // a New tab; recording a tabless location cannot restore its focus when replayed. + if (entry.kind === "workspace" && (!entry.tabId || !entry.target)) { + return; + } + const { entries, index } = store.getState(); + const current = entries[index]; + if (current && entriesEqual(current, entry)) { + // A same-kind tab replacement can keep the tab id while changing its target. Keep the + // current entry's replay payload fresh without turning that retarget into a new place. + if ( + current.kind === "workspace" && + entry.kind === "workspace" && + ((current.target === null) !== (entry.target === null) || + (current.target !== null && + entry.target !== null && + !workspaceTabTargetsEqual(current.target, entry.target))) + ) { + store.replaceCurrent(entry); + } + return; + } + store.record(entry); +} diff --git a/packages/app/src/navigation/history/replay.test.ts b/packages/app/src/navigation/history/replay.test.ts new file mode 100644 index 00000000000..fc6cc835160 --- /dev/null +++ b/packages/app/src/navigation/history/replay.test.ts @@ -0,0 +1,212 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.hoisted(() => { + (globalThis as unknown as { __DEV__: boolean }).__DEV__ = false; +}); + +// goHistory takes its deps by injection; these mocks only keep the default-deps module graph +// (expo-router, the persisted layout store) from loading native code under vitest. +vi.mock("expo-router", () => ({ + router: { navigate: vi.fn(), push: vi.fn(), replace: vi.fn(), dismissTo: vi.fn() }, +})); +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 type { HistoryEntry } from "./model"; +import { goHistory, type HistoryReplayDeps } from "./replay"; +import { createNavigationHistoryStore } from "./store"; + +const ws = ( + workspaceId: string, + tabId: string | null, + target: Extract["target"] = null, +): HistoryEntry => ({ kind: "workspace", serverId: "srv", workspaceId, tabId, target }); + +const route = (path: string): HistoryEntry => ({ kind: "route", path }); + +function createFakeDeps(overrides: Partial = {}) { + const calls: string[] = []; + const deps: HistoryReplayDeps = { + navigateToWorkspace: (input) => + calls.push(`navigate:${input.workspaceId}:${input.target ? input.target.kind : "no-target"}`), + focusTab: (workspaceKey, tabId) => calls.push(`focus:${workspaceKey}:${tabId}`), + getFocusedTabId: () => "files", + navigateToRoute: (path) => calls.push(`route:${path}`), + workspaceExists: () => true, + tabExists: () => true, + agentExists: () => true, + ...overrides, + }; + return { deps, calls }; +} + +function storeWith(entries: HistoryEntry[], index = entries.length - 1) { + const store = createNavigationHistoryStore(); + for (const entry of entries) { + store.record(entry); + } + store.setIndex(index); + return store; +} + +describe("goHistory", () => { + it("returns false at the ends without navigating", () => { + const { deps, calls } = createFakeDeps(); + const store = storeWith([ws("a", "t1")]); + + expect(goHistory(-1, store, deps)).toBe(false); + expect(goHistory(1, store, deps)).toBe(false); + expect(calls).toEqual([]); + expect(store.getState().index).toBe(0); + }); + + it("moves the index before navigating, then navigates with the target and focuses the exact tab", () => { + const observedIndexAtNavigate: number[] = []; + const store = storeWith([ws("a", "tab_dup", { kind: "agent", agentId: "ag" }), ws("b", "t2")]); + const { deps, calls } = createFakeDeps({ + navigateToWorkspace: (input) => { + observedIndexAtNavigate.push(store.getState().index); + calls.push(`navigate:${input.workspaceId}:${input.target?.kind ?? "no-target"}`); + }, + }); + + expect(goHistory(-1, store, deps)).toBe(true); + + expect(observedIndexAtNavigate).toEqual([0]); + expect(calls).toEqual(["navigate:a:agent", "focus:srv:a:tab_dup"]); + }); + + it("navigates without a target when the entry has none, and does not focus", () => { + const store = storeWith([ws("a", null), ws("b", "t2")]); + const { deps, calls } = createFakeDeps({ tabExists: () => false }); + + expect(goHistory(-1, store, deps)).toBe(true); + + expect(calls).toEqual(["navigate:a:no-target"]); + }); + + it("re-opens a closed tab through its target and rewrites the entry to the deterministic id", () => { + const store = storeWith([ws("a", "tab_random", { kind: "files" }), ws("b", "t2")]); + const { deps, calls } = createFakeDeps({ tabExists: () => false }); + + expect(goHistory(-1, store, deps)).toBe(true); + + expect(calls).toEqual(["navigate:a:files"]); + expect(store.getState().entries[0]).toEqual(ws("a", "files", { kind: "files" })); + expect(store.getState().index).toBe(0); + }); + + it("keeps Forward when reveal focuses a duplicate tab with the same target", () => { + const store = storeWith([ + ws("a", "closed-agent-tab", { kind: "agent", agentId: "ag" }), + route("/settings/general"), + ]); + const { deps, calls } = createFakeDeps({ + tabExists: () => false, + getFocusedTabId: () => "other-agent-tab", + }); + + expect(goHistory(-1, store, deps)).toBe(true); + expect(calls).toEqual(["navigate:a:agent"]); + expect(store.getState().entries[0]).toEqual( + ws("a", "other-agent-tab", { kind: "agent", agentId: "ag" }), + ); + expect(store.getState().entries[1]).toEqual(route("/settings/general")); + expect(goHistory(1, store, deps)).toBe(true); + expect(calls).toEqual(["navigate:a:agent", "route:/settings/general"]); + }); + + it("skips closed transient tabs and lands on archived workspace recovery", () => { + const store = storeWith([ + ws("alive", "t0"), + ws("archived", "t1"), + ws("closed-terminal", "gone", { kind: "terminal", terminalId: "term" }), + ws("current", "t3"), + ]); + const { deps, calls } = createFakeDeps({ + workspaceExists: (_serverId, workspaceId) => workspaceId !== "archived", + tabExists: (_key, tabId) => tabId !== "gone", + }); + + expect(goHistory(-1, store, deps)).toBe(true); + + expect(store.getState().index).toBe(1); + expect(calls).toEqual(["navigate:archived:no-target"]); + }); + + it("routes an absent workspace without changing archive state", () => { + const store = storeWith([ws("archived", "t1"), ws("current", "t3")]); + const { deps, calls } = createFakeDeps({ workspaceExists: () => false }); + + expect(goHistory(-1, store, deps)).toBe(true); + expect(calls).toEqual(["navigate:archived:no-target"]); + expect(store.getState().index).toBe(0); + }); + + it("replays route entries through navigateToRoute", () => { + const store = storeWith([ws("a", "t1"), route("/settings/general")], 0); + const { deps, calls } = createFakeDeps(); + + expect(goHistory(1, store, deps)).toBe(true); + + expect(calls).toEqual(["route:/settings/general"]); + expect(store.getState().index).toBe(1); + }); + + // Selecting a PR, leaving, then stepping Back has to land on the creation form with the PR still + // selected, and Forward has to return to where the user went next. + it("restores a seeded creation route's change request through back and forward", () => { + const seededPath = `/new?serverId=srv&draftId=draft-1&changeRequest=${encodeURIComponent( + '{"kind":"change_request","number":7}', + )}`; + const store = storeWith([route(seededPath), route("/sessions")]); + const { deps, calls } = createFakeDeps(); + + expect(goHistory(-1, store, deps)).toBe(true); + expect(calls).toEqual([`route:${seededPath}`]); + expect(store.getState().index).toBe(0); + + expect(goHistory(1, store, deps)).toBe(true); + expect(calls).toEqual([`route:${seededPath}`, "route:/sessions"]); + expect(store.getState().index).toBe(1); + }); + + it("walks forward and back symmetrically", () => { + const store = storeWith([ws("a", "t1"), ws("b", "t2"), ws("c", "t3")]); + const { deps } = createFakeDeps(); + + goHistory(-1, store, deps); + goHistory(-1, store, deps); + expect(store.getState().index).toBe(0); + goHistory(1, store, deps); + expect(store.getState().index).toBe(1); + goHistory(1, store, deps); + expect(store.getState().index).toBe(2); + expect(goHistory(1, store, deps)).toBe(false); + }); + + it("uses a fresh spy to prove focus follows navigate in call order", () => { + const order = vi.fn<(step: string) => void>(); + const store = storeWith([ws("a", "t1", { kind: "files" }), ws("b", "t2")]); + const { deps } = createFakeDeps({ + navigateToWorkspace: () => order("navigate"), + focusTab: () => order("focus"), + }); + + goHistory(-1, store, deps); + + expect(order.mock.calls.map(([step]) => step)).toEqual(["navigate", "focus"]); + }); +}); diff --git a/packages/app/src/navigation/history/replay.ts b/packages/app/src/navigation/history/replay.ts new file mode 100644 index 00000000000..7b099e64198 --- /dev/null +++ b/packages/app/src/navigation/history/replay.ts @@ -0,0 +1,123 @@ +import { router, type Href } from "expo-router"; +import { + navigateToWorkspace, + type NavigateToWorkspaceInput, +} from "@/stores/navigation-active-workspace-store"; +import { useSessionStore } from "@/stores/session-store"; +import { findPaneContainingTab, useWorkspaceLayoutStore } from "@/stores/workspace-layout-store"; +import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity"; +import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model"; +import { resolveWorkspaceReplay, stepIndex, type HistoryEntry } from "./model"; +import { selectActiveWorkspaceTabId } from "./select-active-tab"; +import { navigationHistoryStore, type NavigationHistoryStore } from "./store"; + +export interface HistoryReplayDeps { + navigateToWorkspace: (input: NavigateToWorkspaceInput) => void; + focusTab: (workspaceKey: string, tabId: string) => void; + getFocusedTabId: (workspaceKey: string) => string | null; + navigateToRoute: (path: string) => void; + workspaceExists: (serverId: string, workspaceId: string) => boolean; + tabExists: (workspaceKey: string, tabId: string) => boolean; + agentExists: (serverId: string, agentId: string) => boolean; +} + +const defaultDeps: HistoryReplayDeps = { + navigateToWorkspace: (input) => { + navigateToWorkspace(input); + }, + focusTab: (workspaceKey, tabId) => + useWorkspaceLayoutStore.getState().focusTab(workspaceKey, tabId), + getFocusedTabId: (workspaceKey) => + selectActiveWorkspaceTabId(useWorkspaceLayoutStore.getState(), workspaceKey), + // `navigate`, not `push`: it reuses an identical route already on top, so replaying a settings + // entry twice does not grow the router stack (see docs/expo-router.md on phantom entries). + navigateToRoute: (path) => router.navigate(path as Href), + workspaceExists: (serverId, workspaceId) => + resolveWorkspaceMapKeyByIdentity({ + workspaces: useSessionStore.getState().sessions[serverId]?.workspaces, + workspaceId, + }) !== null, + tabExists: (workspaceKey, tabId) => { + const layout = useWorkspaceLayoutStore.getState().layoutByWorkspace[workspaceKey]; + return layout ? findPaneContainingTab(layout.root, tabId) !== null : false; + }, + agentExists: (serverId, agentId) => + useSessionStore.getState().sessions[serverId]?.agents.has(agentId) ?? false, +}; + +function planForEntry(entry: HistoryEntry, deps: HistoryReplayDeps) { + if (entry.kind === "route") { + return null; + } + const workspaceKey = buildWorkspaceTabPersistenceKey(entry); + return resolveWorkspaceReplay(entry, { + workspaceExists: deps.workspaceExists(entry.serverId, entry.workspaceId), + tabExists: Boolean(workspaceKey && entry.tabId && deps.tabExists(workspaceKey, entry.tabId)), + agentExists: (agentId) => deps.agentExists(entry.serverId, agentId), + }); +} + +/** + * Steps the history and navigates to the entry it lands on. Returns false when there is nothing + * alive in that direction so the shortcut reports itself unhandled. + * + * The index moves before anything is dispatched: the recorder compares what it observes against + * the current entry, so landing on the destination is a no-op rather than a fresh push. + */ +export function goHistory( + delta: 1 | -1, + store: NavigationHistoryStore = navigationHistoryStore, + deps: HistoryReplayDeps = defaultDeps, +): boolean { + const state = store.getState(); + const nextIndex = stepIndex(state, delta, (entry) => planForEntry(entry, deps)?.kind !== "dead"); + if (nextIndex === null) { + return false; + } + const entry = state.entries[nextIndex]; + if (!entry) { + return false; + } + store.setIndex(nextIndex); + + if (entry.kind === "route") { + deps.navigateToRoute(entry.path); + return true; + } + + const plan = planForEntry(entry, deps); + const workspaceKey = buildWorkspaceTabPersistenceKey(entry); + switch (plan?.kind) { + case "focus": + // Passing the target keeps navigateToWorkspace from revealing an attention agent instead. + // Reveal focuses the first tab matching the target, which may be a duplicate, so the exact + // tab is focused afterwards. Both are synchronous store writes and collapse into one render. + deps.navigateToWorkspace({ + serverId: entry.serverId, + workspaceId: entry.workspaceId, + ...(entry.target ? { target: entry.target } : {}), + }); + if (workspaceKey) { + deps.focusTab(workspaceKey, plan.tabId); + } + return true; + case "reopen": + deps.navigateToWorkspace({ + serverId: entry.serverId, + workspaceId: entry.workspaceId, + target: plan.target, + }); + // Reveal can select a duplicate tab with the same target. Match the tab it actually + // focused so the recorder leaves the forward branch intact. + const focusedTabId = workspaceKey ? deps.getFocusedTabId(workspaceKey) : null; + if (focusedTabId) { + store.replaceCurrent({ ...entry, tabId: focusedTabId }); + } + return true; + case "workspace-only": + deps.navigateToWorkspace({ serverId: entry.serverId, workspaceId: entry.workspaceId }); + return true; + default: + return false; + } +} diff --git a/packages/app/src/navigation/history/select-active-tab.test.ts b/packages/app/src/navigation/history/select-active-tab.test.ts new file mode 100644 index 00000000000..9a9608dec06 --- /dev/null +++ b/packages/app/src/navigation/history/select-active-tab.test.ts @@ -0,0 +1,105 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.hoisted(() => { + (globalThis as unknown as { __DEV__: boolean }).__DEV__ = false; +}); + +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 { createWorkspaceLayoutStore } from "@/stores/workspace-layout-store"; +import { selectActiveWorkspaceTabId } from "./select-active-tab"; + +const KEY = "srv:ws-1"; +// Main-pane targets. `files` / `changes_tree` are Explorer sidebar views, which the selector +// ignores on purpose. +const AGENT = { kind: "agent", agentId: "a1" } as const; +const TERMINAL = { kind: "terminal", terminalId: "t1" } as const; + +function createStore() { + let counter = 0; + return createWorkspaceLayoutStore({ + createNodeId: (prefix: "pane" | "group") => `${prefix}_${(counter += 1)}`, + createFocusRestorationToken: () => `token_${(counter += 1)}`, + }); +} + +describe("selectActiveWorkspaceTabId", () => { + let store: ReturnType; + + beforeEach(() => { + store = createStore(); + }); + + it("returns null when the workspace has no layout", () => { + expect(selectActiveWorkspaceTabId(store.getState(), KEY)).toBeNull(); + }); + + it("returns the focused pane's focused tab", () => { + const agentTabId = store + .getState() + .openTab({ workspaceKey: KEY, target: AGENT, intent: "reveal" }); + store.getState().openTab({ workspaceKey: KEY, target: TERMINAL, intent: "reveal" }); + + expect(selectActiveWorkspaceTabId(store.getState(), KEY)).toBe("terminal_t1"); + + store.getState().focusTab(KEY, agentTabId!); + expect(selectActiveWorkspaceTabId(store.getState(), KEY)).toBe("agent_a1"); + }); + + it("keeps reporting the tab while pane focus is parked in the composer", () => { + store.getState().openTab({ workspaceKey: KEY, target: AGENT, intent: "reveal" }); + const token = store.getState().unfocusPane(KEY); + + expect(store.getState().layoutByWorkspace[KEY]?.focusedPaneId).toBeNull(); + expect(selectActiveWorkspaceTabId(store.getState(), KEY)).toBe("agent_a1"); + + if (token) { + store.getState().restorePaneFocus(KEY, token); + } + expect(selectActiveWorkspaceTabId(store.getState(), KEY)).toBe("agent_a1"); + }); + + it("keeps reporting the main tab when the user focuses the Explorer sidebar", () => { + store.getState().openTab({ workspaceKey: KEY, target: AGENT, intent: "reveal" }); + const explorerPaneId = store.getState().showExplorerSidebar(KEY); + expect(explorerPaneId).not.toBeNull(); + + // The store steers workspace focus away from the Explorer pane itself, so the selector sees + // the main pane throughout. + store.getState().focusPane(KEY, explorerPaneId!); + + expect(store.getState().layoutByWorkspace[KEY]?.focusedPaneId).not.toBe(explorerPaneId); + expect(selectActiveWorkspaceTabId(store.getState(), KEY)).toBe("agent_a1"); + }); + + it("returns null if a layout ever reports the Explorer pane as focused", () => { + store.getState().openTab({ workspaceKey: KEY, target: AGENT, intent: "reveal" }); + const explorerPaneId = store.getState().showExplorerSidebar(KEY); + const state = store.getState(); + const layout = state.layoutByWorkspace[KEY]!; + + // Persisted layouts predate the focus steering; guard against one that still points there. + expect( + selectActiveWorkspaceTabId( + { + ...state, + layoutByWorkspace: { [KEY]: { ...layout, focusedPaneId: explorerPaneId } }, + }, + KEY, + ), + ).toBeNull(); + }); +}); diff --git a/packages/app/src/navigation/history/select-active-tab.ts b/packages/app/src/navigation/history/select-active-tab.ts new file mode 100644 index 00000000000..9c89ec29d69 --- /dev/null +++ b/packages/app/src/navigation/history/select-active-tab.ts @@ -0,0 +1,37 @@ +import type { WorkspaceLayout } from "@/stores/workspace-layout-actions"; +import { findPaneById, resolveExplorerSidebarPaneId } from "@/stores/workspace-layout-store"; + +export interface ActiveTabLayoutState { + layoutByWorkspace: Record; + focusRestorationByWorkspace: Record; + explorerSidebarPaneIdByWorkspace: Record; +} + +/** + * The tab the user is looking at in a workspace: the focused pane's focused tab. Falls back to + * the pane focus will return to, because `unfocusPane` nulls `focusedPaneId` while focus sits in + * the composer or sidebar and that must not read as "no tab". The Explorer sidebar pane never + * counts; selecting a view there is not a place to navigate back to. + */ +export function selectActiveWorkspaceTabId( + state: ActiveTabLayoutState, + workspaceKey: string, +): string | null { + const layout = state.layoutByWorkspace[workspaceKey]; + if (!layout) { + return null; + } + const paneId = + layout.focusedPaneId ?? state.focusRestorationByWorkspace[workspaceKey]?.restorePaneId ?? null; + if (!paneId) { + return null; + } + const explorerPaneId = resolveExplorerSidebarPaneId( + layout, + state.explorerSidebarPaneIdByWorkspace[workspaceKey], + ); + if (paneId === explorerPaneId) { + return null; + } + return findPaneById(layout.root, paneId)?.focusedTabId ?? null; +} diff --git a/packages/app/src/navigation/history/store.test.ts b/packages/app/src/navigation/history/store.test.ts new file mode 100644 index 00000000000..1740f256100 --- /dev/null +++ b/packages/app/src/navigation/history/store.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it, vi } from "vitest"; +import { createNavigationHistoryStore } from "./store"; +import type { HistoryEntry } from "./model"; + +const ws = (workspaceId: string, tabId: string | null = null): HistoryEntry => ({ + kind: "workspace", + serverId: "srv", + workspaceId, + tabId, + target: null, +}); + +describe("navigation history store", () => { + it("starts empty", () => { + const store = createNavigationHistoryStore(); + expect(store.getState()).toEqual({ entries: [], index: -1 }); + }); + + it("records entries and notifies subscribers", () => { + const store = createNavigationHistoryStore(); + const listener = vi.fn(); + store.subscribe(listener); + + store.record(ws("a")); + store.record(ws("b")); + + expect(store.getState().entries).toEqual([ws("a"), ws("b")]); + expect(store.getState().index).toBe(1); + expect(listener).toHaveBeenCalledTimes(2); + }); + + it("does not notify when recording the current entry again", () => { + const store = createNavigationHistoryStore(); + store.record(ws("a")); + const listener = vi.fn(); + store.subscribe(listener); + + store.record(ws("a")); + + expect(listener).not.toHaveBeenCalled(); + }); + + it("moves the index only within bounds", () => { + const store = createNavigationHistoryStore(); + store.record(ws("a")); + store.record(ws("b")); + + store.setIndex(0); + expect(store.getState().index).toBe(0); + store.setIndex(5); + expect(store.getState().index).toBe(0); + store.setIndex(-1); + expect(store.getState().index).toBe(0); + }); + + it("replaces the current entry in place", () => { + const store = createNavigationHistoryStore(); + store.record(ws("a")); + store.record(ws("b", "old")); + store.setIndex(1); + + store.replaceCurrent(ws("b", "new")); + + expect(store.getState().entries[1]).toEqual(ws("b", "new")); + expect(store.getState().index).toBe(1); + }); + + it("unsubscribes listeners", () => { + const store = createNavigationHistoryStore(); + const listener = vi.fn(); + const unsubscribe = store.subscribe(listener); + unsubscribe(); + + store.record(ws("a")); + + expect(listener).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/app/src/navigation/history/store.ts b/packages/app/src/navigation/history/store.ts new file mode 100644 index 00000000000..763fcd8076a --- /dev/null +++ b/packages/app/src/navigation/history/store.ts @@ -0,0 +1,50 @@ +import { + EMPTY_HISTORY_STATE, + pushEntry, + replaceEntryAt, + type HistoryEntry, + type HistoryState, +} from "./model"; + +/** + * In-memory history of visited locations, scoped to this app session like a browser window's + * back/forward list. A closure store rather than zustand so the keyboard executor can read and + * step it synchronously; same shape as the last-workspace selection store. + */ +export function createNavigationHistoryStore() { + let state: HistoryState = EMPTY_HISTORY_STATE; + const listeners = new Set<() => void>(); + + function setState(next: HistoryState) { + if (next === state) { + return; + } + state = next; + for (const listener of listeners) { + listener(); + } + } + + return { + getState: () => state, + record: (entry: HistoryEntry) => setState(pushEntry(state, entry)), + setIndex: (index: number) => { + if (index < 0 || index >= state.entries.length || index === state.index) { + return; + } + setState({ entries: state.entries, index }); + }, + replaceCurrent: (entry: HistoryEntry) => setState(replaceEntryAt(state, state.index, entry)), + reset: () => setState(EMPTY_HISTORY_STATE), + subscribe: (listener: () => void): (() => void) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }; +} + +export type NavigationHistoryStore = ReturnType; + +export const navigationHistoryStore = createNavigationHistoryStore(); diff --git a/packages/app/src/panels/agent-panel.tsx b/packages/app/src/panels/agent-panel.tsx index cf582a99f50..ae2bd1f67ad 100644 --- a/packages/app/src/panels/agent-panel.tsx +++ b/packages/app/src/panels/agent-panel.tsx @@ -23,10 +23,17 @@ 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 { useRetainedPanelActive } from "@/components/retained-panel"; +import { + RetainedPanel, + RetainedPanelActivity, + 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 { @@ -66,6 +73,7 @@ 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, @@ -83,6 +91,7 @@ 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 { @@ -120,6 +129,8 @@ interface ChatAgentStateShape { options?: Agent["options"]; controls?: Agent["controls"]; lastError?: Agent["lastError"] | null; + artifacts?: Agent["artifacts"]; + companionEntries?: Agent["companionEntries"]; } interface ChatAgentSelectedState extends ChatAgentStateShape { @@ -180,6 +191,8 @@ 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, @@ -1036,6 +1049,8 @@ function ChatAgentContent({ ); } +const EMPTY_COMPANION_ENTRIES: readonly CompanionEntry[] = []; + const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ serverId, workspaceId, @@ -1094,13 +1109,34 @@ 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. @@ -1159,7 +1195,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} - {composerSection} + {composerSlot} {dockOverlay} ); @@ -1264,14 +1327,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ > {dock} - - {isArchivingCurrentAgent ? ( - - - {t("agentPanel.states.archivingTitle")} - {t("agentPanel.states.archivingSubtitle")} - - ) : null} + ); @@ -1284,6 +1340,106 @@ 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, @@ -1309,6 +1465,20 @@ 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, @@ -1813,6 +1983,8 @@ 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/provider-accounts/provider-account-form-model.test.ts b/packages/app/src/provider-accounts/provider-account-form-model.test.ts new file mode 100644 index 00000000000..190197521c4 --- /dev/null +++ b/packages/app/src/provider-accounts/provider-account-form-model.test.ts @@ -0,0 +1,300 @@ +import { describe, expect, it } from "vitest"; +import { + canAddProviderAccount, + deriveProviderAccountId, + groupProviderAccounts, + groupProviderAccountsBy, + openProviderAccountForm, + resolveProviderAccountBaseId, + type ProviderAccountFormSnapshot, +} from "./provider-account-form-model"; + +const SNAPSHOT: ProviderAccountFormSnapshot = { + baseProviderId: "claude", + baseProviderLabel: "Claude Code", + existingProviderIds: ["claude", "codex", "junie"], +}; + +function openForm(overrides: Partial = {}) { + return openProviderAccountForm({ ...SNAPSHOT, ...overrides }); +} + +describe("canAddProviderAccount", () => { + it("accepts builtin providers that can be extended", () => { + expect(canAddProviderAccount({ providerId: "claude", source: "builtin" })).toBe(true); + expect(canAddProviderAccount({ providerId: "omp", source: "builtin" })).toBe(true); + }); + + it("rejects acp and custom rows", () => { + expect(canAddProviderAccount({ providerId: "acp", source: "builtin" })).toBe(false); + expect(canAddProviderAccount({ providerId: "junie", source: "custom" })).toBe(false); + expect(canAddProviderAccount({ providerId: "junie", source: undefined })).toBe(false); + }); + + it("still offers builtins when the daemon omits source", () => { + expect(canAddProviderAccount({ providerId: "claude", source: undefined })).toBe(true); + }); +}); + +describe("deriveProviderAccountId", () => { + it("slugs a label into a legal provider id", () => { + expect(deriveProviderAccountId("Claude (Work)")).toBe("claude-work"); + expect(deriveProviderAccountId(" Z.AI ")).toBe("z-ai"); + expect(deriveProviderAccountId("2nd Account")).toBe("nd-account"); + expect(deriveProviderAccountId("!!!")).toBe(""); + }); +}); + +describe("provider account presentation", () => { + const providers = { + "claude-work": { extends: "claude" }, + "codex-work": { extends: "codex" }, + catalog: { extends: "acp" }, + }; + + it("resolves the built-in base used for an account icon", () => { + expect(resolveProviderAccountBaseId("claude-work", providers)).toBe("claude"); + expect(resolveProviderAccountBaseId("catalog", providers)).toBeNull(); + expect(resolveProviderAccountBaseId("claude", providers)).toBeNull(); + }); + + it("groups accounts immediately after their built-in base", () => { + const items = ["claude", "codex", "copilot", "catalog", "claude-work", "codex-work"].map( + (id) => ({ id }), + ); + expect(groupProviderAccounts(items, providers).map((item) => item.id)).toEqual([ + "claude", + "claude-work", + "codex", + "codex-work", + "copilot", + "catalog", + ]); + }); + + it("groups by an explicit base accessor", () => { + const items = [ + { id: "claude" }, + { id: "codex" }, + { id: "claude-work", baseProviderId: "claude" }, + { id: "orphan", baseProviderId: "missing" }, + ]; + expect( + groupProviderAccountsBy(items, (item) => + "baseProviderId" in item ? item.baseProviderId : null, + ).map((item) => item.id), + ).toEqual(["claude", "claude-work", "codex", "orphan"]); + }); +}); + +describe("provider account form model", () => { + it("tracks the label until the id is edited by hand", () => { + const model = openForm(); + model.setLabel("Claude Work"); + expect(model.getState().providerId).toBe("claude-work"); + expect(model.getState().providerIdEdited).toBe(false); + + model.setProviderId("work"); + model.setLabel("Claude Personal"); + expect(model.getState().providerId).toBe("work"); + expect(model.getState().providerIdEdited).toBe(true); + }); + + it("hides required errors until submit is attempted", () => { + const model = openForm(); + expect(model.getState().labelError).toBeNull(); + expect(model.getState().providerIdError).toBeNull(); + expect(model.getState().canSubmit).toBe(false); + + model.markSubmitAttempted(); + expect(model.getState().labelError).toBe("required"); + expect(model.getState().providerIdError).toBe("required"); + }); + + it("reports format and collision errors as soon as the id is touched", () => { + const model = openForm(); + model.setProviderId("Claude Work"); + expect(model.getState().providerIdError).toBe("invalid"); + + model.setProviderId("junie"); + expect(model.getState().providerIdError).toBe("taken"); + + model.setProviderId("acp"); + expect(model.getState().providerIdError).toBe("taken"); + + model.setProviderId("claude-work"); + expect(model.getState().providerIdError).toBeNull(); + }); + + it("rejects env rows with a value but no key, and duplicate keys", () => { + const model = openForm(); + model.setLabel("Claude Work"); + const [firstRow] = model.getState().envRows; + if (!firstRow) throw new Error("expected a seeded env row"); + + model.setEnvValue(firstRow.id, "sk-test"); + expect(model.getState().envErrors[firstRow.id]).toBe("keyRequired"); + expect(model.getState().canSubmit).toBe(false); + + model.setEnvKey(firstRow.id, "ANTHROPIC_API_KEY"); + expect(model.getState().envErrors).toEqual({}); + expect(model.getState().canSubmit).toBe(true); + + model.addEnvRow(); + const secondRow = model.getState().envRows[1]; + if (!secondRow) throw new Error("expected a second env row"); + model.setEnvKey(secondRow.id, "ANTHROPIC_API_KEY"); + expect(model.getState().envErrors[secondRow.id]).toBe("duplicate"); + expect(model.getState().canSubmit).toBe(false); + + model.removeEnvRow(secondRow.id); + expect(model.getState().canSubmit).toBe(true); + }); + + it("keeps one env row after removing the last one", () => { + const model = openForm(); + const [firstRow] = model.getState().envRows; + if (!firstRow) throw new Error("expected a seeded env row"); + model.removeEnvRow(firstRow.id); + expect(model.getState().envRows).toHaveLength(1); + }); + + it("builds the config patch and drops empty rows", () => { + const model = openForm(); + model.setLabel("Claude (Work)"); + model.setDescription(" Work account "); + const [firstRow] = model.getState().envRows; + if (!firstRow) throw new Error("expected a seeded env row"); + model.setEnvKey(firstRow.id, " ANTHROPIC_API_KEY "); + model.setEnvValue(firstRow.id, " sk-test "); + model.addEnvRow(); + + expect(model.buildPatch()).toEqual({ + providers: { + "claude-work": { + extends: "claude", + label: "Claude (Work)", + description: "Work account", + env: { ANTHROPIC_API_KEY: " sk-test " }, + }, + }, + }); + }); + + it("omits description when blank and returns no patch while invalid", () => { + const model = openForm(); + model.setLabel("Claude Work"); + expect(model.buildPatch()).toEqual({ + providers: { + "claude-work": { extends: "claude", label: "Claude Work", env: {} }, + }, + }); + + model.setProviderId("claude"); + expect(model.buildPatch()).toBeNull(); + }); + + it("revalidates when the provider snapshot gains the id", () => { + const model = openForm({ existingProviderIds: [] }); + model.setLabel("Claude Work"); + expect(model.getState().canSubmit).toBe(true); + + model.applyExistingProviderIds(["claude-work"]); + model.markSubmitAttempted(); + expect(model.getState().providerIdError).toBe("taken"); + expect(model.getState().canSubmit).toBe(false); + }); + + it("blocks submission while submitting", () => { + const model = openForm(); + model.setLabel("Claude Work"); + model.setSubmitting(true); + expect(model.getState().canSubmit).toBe(false); + model.setSubmitting(false); + expect(model.getState().canSubmit).toBe(true); + }); + + it("opens an existing account with its editable fields and environment", () => { + const model = openForm({ + existingProviderIds: ["claude", "claude-work", "claude-personal"], + account: { + providerId: "claude-work", + config: { + extends: "claude", + label: "Claude (Work)", + description: "Company account", + env: { CLAUDE_CONFIG_DIR: "/work/claude", TOKEN: " keep spaces " }, + }, + }, + }); + + expect(model.getState()).toMatchObject({ + isEditing: true, + label: "Claude (Work)", + providerId: "claude-work", + providerIdError: null, + description: "Company account", + canSubmit: true, + }); + expect(model.getState().envRows.map(({ key, value }) => ({ key, value }))).toEqual([ + { key: "CLAUDE_CONFIG_DIR", value: "/work/claude" }, + { key: "TOKEN", value: " keep spaces " }, + ]); + }); + + it("replaces an edited account exactly while preserving fields outside the form", () => { + const model = openForm({ + existingProviderIds: ["claude", "claude-work"], + account: { + providerId: "claude-work", + config: { + extends: "claude", + label: "Old label", + description: "Delete me", + env: { OLD_TOKEN: "old", KEEP: "old" }, + command: ["claude", "--work"], + additionalModels: [{ id: "work-model", label: "Work model" }], + }, + }, + }); + model.setLabel("Work"); + model.setDescription(" "); + const [oldToken, keep] = model.getState().envRows; + if (!oldToken || !keep) throw new Error("expected seeded environment rows"); + model.removeEnvRow(oldToken.id); + model.setEnvValue(keep.id, "new"); + + expect(model.buildPatch()).toEqual({ + replaceProviders: { + "claude-work": { + extends: "claude", + label: "Work", + env: { KEEP: "new" }, + command: ["claude", "--work"], + additionalModels: [{ id: "work-model", label: "Work model" }], + }, + }, + }); + }); + + it("renames an account atomically and still rejects another account id", () => { + const model = openForm({ + existingProviderIds: ["claude", "claude-work", "claude-personal"], + account: { + providerId: "claude-work", + config: { extends: "claude", label: "Work", env: {} }, + }, + }); + + model.setProviderId("claude-personal"); + expect(model.getState().providerIdError).toBe("taken"); + model.setProviderId("claude-company"); + expect(model.buildPatch()).toEqual({ + replaceProviders: { + "claude-company": { extends: "claude", label: "Work", env: {} }, + }, + removeProviders: ["claude-work"], + renameProviders: { "claude-work": "claude-company" }, + }); + }); +}); diff --git a/packages/app/src/provider-accounts/provider-account-form-model.ts b/packages/app/src/provider-accounts/provider-account-form-model.ts new file mode 100644 index 00000000000..0b84d36302a --- /dev/null +++ b/packages/app/src/provider-accounts/provider-account-form-model.ts @@ -0,0 +1,398 @@ +import type { MutableDaemonConfig, MutableDaemonConfigPatch } from "@getpaseo/protocol/messages"; + +/** Provider ids the daemon reserves; a new account can never claim one. */ +export const RESERVED_PROVIDER_IDS = [ + "claude", + "codex", + "copilot", + "opencode", + "pi", + "omp", + "acp", +] as const; + +/** + * Builtin providers an account can extend. `acp` is excluded: ACP entries are + * installed from the catalog with their own command, not cloned per account. + */ +export const ACCOUNT_BASE_PROVIDER_IDS = [ + "claude", + "codex", + "copilot", + "opencode", + "pi", + "omp", +] as const; + +// Mirrors ProviderOverridesSchema in packages/protocol/src/provider-config.ts. +export const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9-]*$/; + +export function canAddProviderAccount(input: { + providerId: string; + source: "builtin" | "custom" | undefined; +}): boolean { + // `source` is optional on the wire, so daemons that predate it report + // undefined. Reject only an explicit "custom": the daemon reports a builtin + // id as "builtin" regardless of overrides, so no custom row can reach here. + if (input.source === "custom") return false; + return (ACCOUNT_BASE_PROVIDER_IDS as readonly string[]).includes(input.providerId); +} + +export function resolveProviderAccountBaseId( + providerId: string, + providers: Record> | undefined, +): string | null { + const extendsProvider = providers?.[providerId]?.extends; + return typeof extendsProvider === "string" && + (ACCOUNT_BASE_PROVIDER_IDS as readonly string[]).includes(extendsProvider) + ? extendsProvider + : null; +} + +export function groupProviderAccounts( + items: readonly T[], + providers: Record> | undefined, +): T[] { + return groupProviderAccountsBy(items, (item) => resolveProviderAccountBaseId(item.id, providers)); +} + +/** + * Orders each provider account immediately after the base provider it extends. + * Accounts whose base is missing from the list keep their original order at the end. + */ +export function groupProviderAccountsBy( + items: readonly T[], + getBaseId: (item: T) => string | null | undefined, +): T[] { + const accountsByBase = new Map(); + const accountIds = new Set(); + + for (const item of items) { + const baseProviderId = getBaseId(item); + if (!baseProviderId) continue; + accountIds.add(item.id); + const accounts = accountsByBase.get(baseProviderId) ?? []; + accounts.push(item); + accountsByBase.set(baseProviderId, accounts); + } + + const grouped: T[] = []; + for (const item of items) { + if (accountIds.has(item.id)) continue; + grouped.push(item, ...(accountsByBase.get(item.id) ?? [])); + } + + for (const item of items) { + if (accountIds.has(item.id) && !grouped.includes(item)) { + grouped.push(item); + } + } + return grouped; +} + +export function deriveProviderAccountId(label: string): string { + return label + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^[^a-z]+/, "") + .replace(/-+$/, ""); +} + +export type ProviderAccountLabelError = "required"; +export type ProviderAccountIdError = "required" | "invalid" | "taken"; +export type ProviderAccountEnvError = "keyRequired" | "duplicate"; + +export interface ProviderAccountEnvRow { + id: string; + key: string; + value: string; +} + +export interface ProviderAccountFormState { + isEditing: boolean; + baseProviderId: string; + baseProviderLabel: string; + label: string; + providerId: string; + /** False while the id still tracks the label; the id input remounts on change. */ + providerIdEdited: boolean; + description: string; + envRows: ProviderAccountEnvRow[]; + /** Errors are only populated once the user can act on them. */ + labelError: ProviderAccountLabelError | null; + providerIdError: ProviderAccountIdError | null; + envErrors: Record; + canSubmit: boolean; + isSubmitting: boolean; +} + +export interface ProviderAccountFormSnapshot { + baseProviderId: string; + baseProviderLabel: string; + existingProviderIds: readonly string[]; + account?: { + providerId: string; + config: MutableDaemonConfig["providers"][string]; + }; +} + +export interface ProviderAccountFormModel { + getState: () => ProviderAccountFormState; + subscribe: (listener: () => void) => () => void; + close: () => void; + applyExistingProviderIds: (providerIds: readonly string[]) => void; + setLabel: (value: string) => void; + setProviderId: (value: string) => void; + setDescription: (value: string) => void; + addEnvRow: () => void; + removeEnvRow: (rowId: string) => void; + setEnvKey: (rowId: string, value: string) => void; + setEnvValue: (rowId: string, value: string) => void; + setSubmitting: (value: boolean) => void; + markSubmitAttempted: () => void; + buildPatch: () => MutableDaemonConfigPatch | null; +} + +interface InternalState { + originalProviderId: string | null; + label: string; + providerId: string; + providerIdEdited: boolean; + description: string; + envRows: ProviderAccountEnvRow[]; + existingProviderIds: readonly string[]; + submitAttempted: boolean; + isSubmitting: boolean; +} + +interface Validation { + labelError: ProviderAccountLabelError | null; + providerIdError: ProviderAccountIdError | null; + envErrors: Record; +} + +function validate(internal: InternalState): Validation { + const labelError: ProviderAccountLabelError | null = + internal.label.trim().length === 0 ? "required" : null; + + const providerId = internal.providerId.trim(); + const taken = new Set([ + ...RESERVED_PROVIDER_IDS, + ...internal.existingProviderIds + .map((value) => value.trim()) + .filter((value) => value !== internal.originalProviderId), + ]); + let providerIdError: ProviderAccountIdError | null = null; + if (providerId.length === 0) { + providerIdError = "required"; + } else if (!PROVIDER_ID_PATTERN.test(providerId)) { + providerIdError = "invalid"; + } else if (taken.has(providerId)) { + providerIdError = "taken"; + } + + const envErrors: Record = {}; + const seenKeys = new Set(); + for (const row of internal.envRows) { + const key = row.key.trim(); + if (key.length === 0) { + if (row.value.trim().length > 0) { + envErrors[row.id] = "keyRequired"; + } + continue; + } + if (seenKeys.has(key)) { + envErrors[row.id] = "duplicate"; + continue; + } + seenKeys.add(key); + } + + return { labelError, providerIdError, envErrors }; +} + +function project(internal: InternalState, snapshot: ProviderAccountFormSnapshot) { + const validation = validate(internal); + const isValid = + validation.labelError === null && + validation.providerIdError === null && + Object.keys(validation.envErrors).length === 0; + + // "required" is noise until the user tries to submit; format and collision + // errors are actionable the moment the id field has been touched. + const showLabelError = internal.submitAttempted; + const showProviderIdError = + internal.submitAttempted || + (internal.providerIdEdited && validation.providerIdError !== "required"); + + const state: ProviderAccountFormState = { + isEditing: internal.originalProviderId !== null, + baseProviderId: snapshot.baseProviderId, + baseProviderLabel: snapshot.baseProviderLabel, + label: internal.label, + providerId: internal.providerId, + providerIdEdited: internal.providerIdEdited, + description: internal.description, + envRows: internal.envRows, + labelError: showLabelError ? validation.labelError : null, + providerIdError: showProviderIdError ? validation.providerIdError : null, + envErrors: validation.envErrors, + canSubmit: isValid && !internal.isSubmitting, + isSubmitting: internal.isSubmitting, + }; + return state; +} + +export function buildProviderAccountConfigPatch(input: { + providerId: string; + baseProviderId: string; + label: string; + description: string; + envRows: readonly ProviderAccountEnvRow[]; + originalProviderId?: string; + originalConfig?: MutableDaemonConfig["providers"][string]; +}): MutableDaemonConfigPatch { + const env: Record = {}; + for (const row of input.envRows) { + const key = row.key.trim(); + if (key.length === 0) continue; + env[key] = row.value; + } + const description = input.description.trim(); + + const providerId = input.providerId.trim(); + const providerConfig: MutableDaemonConfig["providers"][string] = { + ...input.originalConfig, + extends: input.baseProviderId, + label: input.label.trim(), + env, + }; + if (description) { + providerConfig.description = description; + } else { + delete providerConfig.description; + } + + if (input.originalProviderId) { + return { + replaceProviders: { [providerId]: providerConfig }, + ...(providerId !== input.originalProviderId + ? { + removeProviders: [input.originalProviderId], + renameProviders: { [input.originalProviderId]: providerId }, + } + : {}), + }; + } + return { providers: { [providerId]: providerConfig } }; +} + +export function openProviderAccountForm( + snapshot: ProviderAccountFormSnapshot, +): ProviderAccountFormModel { + let rowCounter = 0; + const createRow = (): ProviderAccountEnvRow => { + rowCounter += 1; + return { id: `env-${rowCounter}`, key: "", value: "" }; + }; + + const accountConfig = snapshot.account?.config; + const accountEnv = accountConfig?.env; + const initialEnvRows = + accountEnv && typeof accountEnv === "object" && !Array.isArray(accountEnv) + ? Object.entries(accountEnv).flatMap(([key, value]) => + typeof value === "string" ? [{ ...createRow(), key, value }] : [], + ) + : []; + + let internal: InternalState = { + originalProviderId: snapshot.account?.providerId ?? null, + label: typeof accountConfig?.label === "string" ? accountConfig.label : "", + providerId: snapshot.account?.providerId ?? "", + providerIdEdited: snapshot.account !== undefined, + description: typeof accountConfig?.description === "string" ? accountConfig.description : "", + envRows: initialEnvRows.length > 0 ? initialEnvRows : [createRow()], + existingProviderIds: [...snapshot.existingProviderIds], + submitAttempted: false, + isSubmitting: false, + }; + + let listeners = new Set<() => void>(); + let state = project(internal, snapshot); + + const publish = (next: InternalState) => { + internal = next; + state = project(internal, snapshot); + for (const listener of listeners) listener(); + }; + + const mapRows = (rowId: string, update: (row: ProviderAccountEnvRow) => ProviderAccountEnvRow) => + internal.envRows.map((row) => (row.id === rowId ? update(row) : row)); + + return { + getState: () => state, + subscribe: (listener) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + close: () => { + listeners = new Set(); + }, + applyExistingProviderIds: (providerIds) => { + const next = [...providerIds]; + const unchanged = + next.length === internal.existingProviderIds.length && + next.every((value, index) => value === internal.existingProviderIds[index]); + if (unchanged) return; + publish({ ...internal, existingProviderIds: next }); + }, + setLabel: (value) => { + publish({ + ...internal, + label: value, + providerId: internal.providerIdEdited + ? internal.providerId + : deriveProviderAccountId(value), + }); + }, + setProviderId: (value) => { + publish({ ...internal, providerId: value, providerIdEdited: true }); + }, + setDescription: (value) => { + publish({ ...internal, description: value }); + }, + addEnvRow: () => { + publish({ ...internal, envRows: [...internal.envRows, createRow()] }); + }, + removeEnvRow: (rowId) => { + const remaining = internal.envRows.filter((row) => row.id !== rowId); + publish({ ...internal, envRows: remaining.length > 0 ? remaining : [createRow()] }); + }, + setEnvKey: (rowId, value) => { + publish({ ...internal, envRows: mapRows(rowId, (row) => ({ ...row, key: value })) }); + }, + setEnvValue: (rowId, value) => { + publish({ ...internal, envRows: mapRows(rowId, (row) => ({ ...row, value })) }); + }, + setSubmitting: (value) => { + publish({ ...internal, isSubmitting: value }); + }, + markSubmitAttempted: () => { + publish({ ...internal, submitAttempted: true }); + }, + buildPatch: () => { + if (!state.canSubmit) return null; + return buildProviderAccountConfigPatch({ + providerId: internal.providerId, + baseProviderId: snapshot.baseProviderId, + label: internal.label, + description: internal.description, + envRows: internal.envRows, + originalProviderId: internal.originalProviderId ?? undefined, + originalConfig: snapshot.account?.config, + }); + }, + }; +} diff --git a/packages/app/src/provider-accounts/use-provider-account-form-model.ts b/packages/app/src/provider-accounts/use-provider-account-form-model.ts new file mode 100644 index 00000000000..4923fc6e9f1 --- /dev/null +++ b/packages/app/src/provider-accounts/use-provider-account-form-model.ts @@ -0,0 +1,21 @@ +import { useEffect, useState } from "react"; +import { + openProviderAccountForm, + type ProviderAccountFormSnapshot, +} from "./provider-account-form-model"; + +export function useProviderAccountFormModel(snapshot: ProviderAccountFormSnapshot) { + const [model] = useState(() => openProviderAccountForm(snapshot)); + + useEffect(() => { + return () => { + model.close(); + }; + }, [model]); + + useEffect(() => { + model.applyExistingProviderIds(snapshot.existingProviderIds); + }, [model, snapshot.existingProviderIds]); + + return model; +} diff --git a/packages/app/src/provider-selection/provider-selection.test.ts b/packages/app/src/provider-selection/provider-selection.test.ts index 1c04c0b154c..58032b8615c 100644 --- a/packages/app/src/provider-selection/provider-selection.test.ts +++ b/packages/app/src/provider-selection/provider-selection.test.ts @@ -10,6 +10,7 @@ import { filterAndRankModelRows, matchesModelSearch, resolveEffectiveComposerModeId, + resolveProviderIconId, resolveSelectedModelLabel, resolveSubmissionReadiness, } from "./provider-selection"; @@ -52,6 +53,26 @@ describe("combined model selector data", () => { }; } + it("orders provider accounts after their base provider and borrows its icon", () => { + const providers = buildSelectableProviderSelectorProviders([ + snapshotEntry({ provider: "claude", label: "Claude" }), + snapshotEntry({ provider: "codex", label: "Codex" }), + snapshotEntry({ + provider: "claude-work", + label: "Claude (Work)", + source: "custom", + baseProviderId: "claude", + }), + ]); + + expect(providers.map((provider) => provider.id)).toEqual(["claude", "claude-work", "codex"]); + expect(resolveProviderIconId(providers, "claude-work")).toBe("claude"); + expect(resolveProviderIconId(providers, "codex")).toBe("codex"); + const accountRows = + providers[1].modelSelection.kind === "models" ? providers[1].modelSelection.rows : []; + expect(accountRows[0]?.iconProviderId).toBe("claude"); + }); + it("builds selector providers from ready enabled snapshot entries", () => { expect( buildSelectableProviderSelectorProviders([ diff --git a/packages/app/src/provider-selection/provider-selection.ts b/packages/app/src/provider-selection/provider-selection.ts index 592824341a7..af225de26f2 100644 --- a/packages/app/src/provider-selection/provider-selection.ts +++ b/packages/app/src/provider-selection/provider-selection.ts @@ -7,6 +7,7 @@ import type { import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest"; import type { DraftCommandTarget } from "@/agent-commands"; import { i18n } from "@/i18n/i18next"; +import { groupProviderAccountsBy } from "@/provider-accounts/provider-account-form-model"; import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match"; import { filterSelectableModels } from "./model-catalog"; @@ -23,6 +24,8 @@ export interface ProviderSelectionModelRow { modelLabel: string; description?: string; isDefault?: boolean; + /** Provider whose icon this row shows; differs from `provider` for provider accounts. */ + iconProviderId?: string; } function buildModelRowKey(provider: string, modelId: string): string { @@ -37,9 +40,19 @@ export type ProviderModelSelection = export interface ProviderSelectorProvider { id: string; label: string; + /** Builtin provider this account extends; drives grouping and the row icon. */ + baseProviderId?: string; modelSelection: ProviderModelSelection; } +/** The provider whose icon represents `providerId` — an account borrows its base provider's icon. */ +export function resolveProviderIconId( + providers: readonly ProviderSelectorProvider[], + providerId: string, +): string { + return providers.find((entry) => entry.id === providerId)?.baseProviderId ?? providerId; +} + export interface ProviderSelectionState { provider: AgentProvider | null; modelId: string; @@ -58,11 +71,13 @@ function buildModelRows( provider: string, providerLabel: string, models: AgentModelDefinition[], + iconProviderId?: string, ): ProviderSelectionModelRow[] { return models.map((model) => ({ favoriteKey: buildModelRowKey(provider, model.id), provider, providerLabel, + iconProviderId, modelId: model.id, modelLabel: model.label, description: model.description ?? model.id, @@ -73,11 +88,13 @@ function buildModelRows( function buildSyntheticDefaultRow( provider: string, providerLabel: string, + iconProviderId?: string, ): ProviderSelectionModelRow { return { favoriteKey: buildModelRowKey(provider, ""), provider, providerLabel, + iconProviderId, modelId: "", modelLabel: i18n.t("providerSelection.defaultModel"), description: undefined, @@ -89,27 +106,35 @@ function buildModelSelection( provider: string, providerLabel: string, models: AgentModelDefinition[] | null, + iconProviderId?: string, ): ProviderModelSelection { if (models === null) { return { kind: "loading" }; } const selectableModels = filterSelectableModels(models) ?? []; if (selectableModels.length === 0) { - return { kind: "models", rows: [buildSyntheticDefaultRow(provider, providerLabel)] }; + return { + kind: "models", + rows: [buildSyntheticDefaultRow(provider, providerLabel, iconProviderId)], + }; } - return { kind: "models", rows: buildModelRows(provider, providerLabel, selectableModels) }; + return { + kind: "models", + rows: buildModelRows(provider, providerLabel, selectableModels, iconProviderId), + }; } function buildEntryModelSelection( entry: ProviderSnapshotEntry, label: string, isConnected: boolean, + iconProviderId?: string, ): ProviderModelSelection { if ((entry.models?.length ?? 0) > 0) { - return buildModelSelection(entry.provider, label, entry.models ?? null); + return buildModelSelection(entry.provider, label, entry.models ?? null, iconProviderId); } if (entry.status === "ready") { - return buildModelSelection(entry.provider, label, entry.models ?? null); + return buildModelSelection(entry.provider, label, entry.models ?? null, iconProviderId); } if (entry.status === "loading") { return isConnected @@ -130,33 +155,42 @@ export function buildProviderSelectorProviders(input: { providerDefinitions: AgentProviderDefinition[]; modelsByProvider: Map; }): ProviderSelectorProvider[] { - return input.providerDefinitions.map((definition) => ({ - id: definition.id, - label: definition.label, - modelSelection: buildModelSelection( - definition.id, - definition.label, - input.modelsByProvider.has(definition.id) - ? (input.modelsByProvider.get(definition.id) ?? []) - : null, - ), - })); + return groupProviderAccountsBy( + input.providerDefinitions.map((definition) => ({ + id: definition.id, + label: definition.label, + baseProviderId: definition.baseProviderId, + modelSelection: buildModelSelection( + definition.id, + definition.label, + input.modelsByProvider.has(definition.id) + ? (input.modelsByProvider.get(definition.id) ?? []) + : null, + definition.baseProviderId, + ), + })), + (provider) => provider.baseProviderId, + ); } export function buildSelectableProviderSelectorProviders( entries: ProviderSnapshotEntry[] | undefined, isConnected = true, ): ProviderSelectorProvider[] { - return (entries ?? []) - .filter((entry) => entry.enabled) - .map((entry) => { - const label = entry.label ?? entry.provider; - return { - id: entry.provider, - label, - modelSelection: buildEntryModelSelection(entry, label, isConnected), - }; - }); + return groupProviderAccountsBy( + (entries ?? []) + .filter((entry) => entry.enabled) + .map((entry) => { + const label = entry.label ?? entry.provider; + return { + id: entry.provider, + label, + baseProviderId: entry.baseProviderId, + modelSelection: buildEntryModelSelection(entry, label, isConnected, entry.baseProviderId), + }; + }), + (provider) => provider.baseProviderId, + ); } export function getProviderModelRows( diff --git a/packages/app/src/runtime/host-features.test.ts b/packages/app/src/runtime/host-features.test.ts new file mode 100644 index 00000000000..c4186816309 --- /dev/null +++ b/packages/app/src/runtime/host-features.test.ts @@ -0,0 +1,33 @@ +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 15a86b7bb4c..babce5975bf 100644 --- a/packages/app/src/runtime/host-runtime.ts +++ b/packages/app/src/runtime/host-runtime.ts @@ -576,6 +576,8 @@ 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 e9304513b9e..7ea2519516e 100644 --- a/packages/app/src/runtime/replica-cache/index.ts +++ b/packages/app/src/runtime/replica-cache/index.ts @@ -6,6 +6,8 @@ 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, @@ -257,6 +259,8 @@ 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({ @@ -277,6 +281,7 @@ const StoredAgentSchema = z.strictObject({ const WorkspaceScriptSchema = z.strictObject({ scriptName: z.string(), + packageJson: z.object({ path: z.string(), script: z.string() }).optional(), type: z.enum(["script", "service"]), hostname: z.string(), port: z.number().int().positive().nullable(), @@ -660,6 +665,15 @@ 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, @@ -694,6 +708,7 @@ function serializeAgent(agent: Agent): StoredAgent { attentionReason: agent.attentionReason ?? null, attentionTimestamp: agent.attentionTimestamp?.toISOString() ?? null, archivedAt: agent.archivedAt?.toISOString() ?? null, + ...serializeStreamStateFields(agent), }; return { snapshot, @@ -754,6 +769,7 @@ function serializeWorkspace(workspace: WorkspaceDescriptor): StoredWorkspace { diffStat: workspace.diffStat, scripts: workspace.scripts.map((script) => ({ scriptName: script.scriptName, + packageJson: script.packageJson, type: script.type, hostname: script.hostname, port: script.port, diff --git a/packages/app/src/screens/new-workspace-screen.tsx b/packages/app/src/screens/new-workspace-screen.tsx index bab4df8f015..9b835c38ef7 100644 --- a/packages/app/src/screens/new-workspace-screen.tsx +++ b/packages/app/src/screens/new-workspace-screen.tsx @@ -175,6 +175,7 @@ function buildFirstAgentContext(input: { } interface NewWorkspaceScreenProps { + initialChangeRequest?: ForgeSearchItem; serverId: string; sourceDirectory?: string; projectId?: string; @@ -205,6 +206,7 @@ function useWorkspaceIsolation(input: { setup: NewWorkspaceSetup; supportsMultiplicity: boolean; canCreateWorktree: boolean; + initialWorktree?: boolean; }): WorkspaceIsolationState { const { setup, supportsMultiplicity, canCreateWorktree } = input; // The last isolation choice is remembered alongside the other New Workspace @@ -212,7 +214,8 @@ function useWorkspaceIsolation(input: { // the remembered default until the screen remounts. const { preferences } = useFormPreferences(); const { manualIsolation } = useNewWorkspaceSetupState(setup); - const isolation = manualIsolation ?? preferences.isolation ?? "local"; + const isolation = + manualIsolation ?? (input.initialWorktree ? "worktree" : (preferences.isolation ?? "local")); const isWorktree = isolation === "worktree" && canCreateWorktree; return { @@ -856,6 +859,7 @@ export function NewWorkspaceScreen({ projectId, displayName: displayNameProp, draftId, + initialChangeRequest, }: NewWorkspaceScreenProps) { const queryClient = useQueryClient(); const { t } = useTranslation(); @@ -1013,6 +1017,7 @@ export function NewWorkspaceScreen({ isDraftHandoffActive, updatePreferences: updateFormPreferences, setAttachments: chatDraft.setAttachments, + initialChangeRequest, }); const dispatchPickerSelection = setup.dispatchPicker; const selectedItem = useNewWorkspaceSetupState(setup).pickerSelection.selectedItem; @@ -1052,6 +1057,7 @@ export function NewWorkspaceScreen({ setup, supportsMultiplicity: supportsWorkspaceMultiplicity, canCreateWorktree, + initialWorktree: Boolean(initialChangeRequest), }); const branchSuggestionsQuery = useQuery({ @@ -1127,6 +1133,13 @@ export function NewWorkspaceScreen({ [baseItem, effectiveIsolation, isPending, pluginProject], ); + const initialRequestAttached = useRef(false); + useEffect(() => { + if (!initialChangeRequest || initialRequestAttached.current) return; + initialRequestAttached.current = true; + selectPickerItem({ kind: "github-pr", item: initialChangeRequest }); + }, [initialChangeRequest, selectPickerItem]); + const handleSelectOption = useCallback( (id: string) => { const item = itemById.get(id); @@ -1625,6 +1638,7 @@ function usePluginSetup(input: { isDraftHandoffActive: boolean; updatePreferences: ReturnType["updatePreferences"]; setAttachments: ReturnType["setAttachments"]; + initialChangeRequest?: ForgeSearchItem; }) { const { serverId, @@ -1650,13 +1664,20 @@ function usePluginSetup(input: { const inputs = { serverId, locked, project: pluginProject, canCreateWorktree, supportsMetadata }; // Both are stable for the life of the screen: preferences write through the query client, and // the draft is keyed per mount. A command and a pick run the same effects. - const [setup] = useState(() => - createNewWorkspaceSetup(inputs, { + const [setup] = useState(() => { + const created = createNewWorkspaceSetup(inputs, { persistIsolation: (isolation) => void updatePreferences({ isolation }), syncBaseAttachment: (item) => setAttachments((attachments) => syncPickerPrAttachment({ attachments, item })), - }), - ); + }); + if (input.initialChangeRequest) { + created.dispatchPicker({ + type: "picker-selected", + item: { kind: "github-pr", item: input.initialChangeRequest }, + }); + } + return created; + }); useLayoutEffect(() => setup.syncInputs(inputs)); return { setup, pluginProject, canCreateWorktree, isPending: locked }; } diff --git a/packages/app/src/screens/project-pull-requests/checks-view.tsx b/packages/app/src/screens/project-pull-requests/checks-view.tsx new file mode 100644 index 00000000000..d941e4384f0 --- /dev/null +++ b/packages/app/src/screens/project-pull-requests/checks-view.tsx @@ -0,0 +1,112 @@ +import { useCallback, useMemo } from "react"; +import { Text, View, type GestureResponderEvent } from "react-native"; +import { Check, X, Clock, CircleSlash, Minus } from "lucide-react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { useTranslation } from "react-i18next"; +import type { ForgeSearchItem } from "@getpaseo/protocol/messages"; +import type { Theme } from "@/styles/theme"; +import { Button } from "@/components/ui/button"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { openExternalUrl } from "@/utils/open-external-url"; +import { useToast } from "@/contexts/toast-context"; +import { checkLabel, getCheckIndicators } from "./checks"; + +const ICONS = { + passed: withUnistyles(Check), + failure: withUnistyles(X), + pending: withUnistyles(Clock), + cancelled: withUnistyles(CircleSlash), + skipped: withUnistyles(Minus), +}; +type IndicatorStatus = keyof typeof ICONS; +const COLORS = { + passed: (theme: Theme) => ({ color: theme.colors.statusSuccess }), + failure: (theme: Theme) => ({ color: theme.colors.statusDanger }), + pending: (theme: Theme) => ({ color: theme.colors.statusWarning }), + cancelled: (theme: Theme) => ({ color: theme.colors.foregroundMuted }), + skipped: (theme: Theme) => ({ color: theme.colors.foregroundMuted }), +}; + +export function PullRequestChecks({ item }: { item: ForgeSearchItem }) { + const { t } = useTranslation(); + const { failures, cancelled, summary } = getCheckIndicators(item.checks); + return ( + + {summary ? ( + + ) : null} + {failures.map((check) => ( + + ))} + {cancelled.map((check) => ( + + ))} + + ); +} + +function CheckStatusButton({ + status, + label, + url, +}: { + status: IndicatorStatus; + label: string; + url: string; +}) { + const { t } = useTranslation(); + const toast = useToast(); + const onPress = useCallback( + (event: GestureResponderEvent) => { + event.stopPropagation(); + void openExternalUrl(url).catch((error: unknown) => + toast.error(error instanceof Error ? error.message : t("common.errors.error")), + ); + }, + [url, toast, t], + ); + const icon = useMemo(() => { + const Icon = ICONS[status]; + return ; + }, [status]); + return ( + + + + ) : null} + + ); + if (loading) return {t("projectPullRequests.loading")}; + if (items.length === 0) + return {t("projectPullRequests.empty")}; + return items.map((item) => ( + + )); +} + +function PullRequestRow({ + item, + supportsChecks, + onSelect, +}: { + item: ForgeSearchItem; + supportsChecks: boolean; + onSelect: (item: ForgeSearchItem) => void; +}) { + const { t } = useTranslation(); + const select = useCallback( + (event: GestureResponderEvent) => { + event.stopPropagation(); + onSelect(item); + }, + [item, onSelect], + ); + const toast = useToast(); + const openExternal = useCallback( + (event: GestureResponderEvent) => { + event.stopPropagation(); + void openExternalUrl(item.url).catch((error: unknown) => { + toast.error(error instanceof Error ? error.message : t("common.errors.error")); + }); + }, + [item.url, toast, t], + ); + const state = pullRequestState(item.state); + const rowStyle = useCallback( + ({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [ + styles.row, + (hovered || pressed) && styles.rowHighlighted, + ], + [], + ); + return ( + + + + + + + {item.title} + {supportsChecks && item.checks ? : null} + {item.labels.map((label) => ( + + ))} + + + #{item.number} + {item.headRefName ? ` · ${item.headRefName}` : ""} + {item.baseRefName ? ` → ${item.baseRefName}` : ""} + {item.updatedAt + ? ` · ${t("projectPullRequests.updated", { date: new Date(item.updatedAt).toLocaleDateString() })}` + : ""} + + +