mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-30 12:16:12 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d2d4105366 | ||
|
|
37cb22dac8 | ||
|
|
397d1e14d6 | ||
|
|
d193e419e9 | ||
|
|
bd20e3fe98 | ||
|
|
39eaba6181 | ||
|
|
63ede58d7d |
+13
-77
@@ -152,7 +152,7 @@ Users can also detach an existing subagent from the subagents track. Detach is d
|
||||
|
||||
`notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback.
|
||||
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. The daemon saves a queued message, then acknowledges it with a receipt, before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
|
||||
|
||||
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
|
||||
|
||||
@@ -170,64 +170,33 @@ A command the provider accepts out of band is the one exception to admission ord
|
||||
|
||||
One provider prompt has one session mode. A batch released by a steer, an interrupt, or a person's prompt uses the latest explicit choice in it, the person's own first. Queued messages with conflicting choices keep separate ordered dispatches.
|
||||
|
||||
A provider switch can wait in the queue too (`agent.provider.switch.request` with
|
||||
`activeTurnBehavior: "queue"`). The message carries the target provider and settings, shares a prompt
|
||||
with nothing, and divides the queue: what is ahead of it goes to the current provider, and it and
|
||||
what follows go to the target. A direct prompt therefore takes along only the queued rows ahead of
|
||||
the switch. Promoting the switch cuts the running turn once the target is known to be usable. A chat
|
||||
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
|
||||
the message and holds the queue; the reason is in the daemon log.
|
||||
|
||||
The queue is saved in `$PASEO_HOME/agent-queues/` ([data model](data-model.md#directory-layout)),
|
||||
and a message is saved before its receipt is sent. Inline images are first saved as uploads, so the
|
||||
queue file holds references. An empty message is refused, and a recipient holds at most 100
|
||||
messages.
|
||||
|
||||
A message is marked `dispatching` before the provider can receive it and removed when the provider
|
||||
admits it. A dispatch that is not admitted returns the message to its place. A refused turn start
|
||||
also holds the queue: retrying by itself would be refused again and would add the prompt to the
|
||||
history each time. A message that cannot be sent is removed so that it does not block the ones
|
||||
behind it.
|
||||
|
||||
Shutdown does not send the queue. It waits only for dispatches already in flight, and everything
|
||||
else stays saved, held messages included. Closing an idle runtime keeps the queue. Archiving or
|
||||
deleting the agent clears it.
|
||||
|
||||
Bootstrap restores queues before restart recovery resumes agents, and before finish subscriptions,
|
||||
change-request watches, and ingress start. A held queue stays held. Other queues are sent, after the
|
||||
resume prompt for an agent that restart recovery resumes. A crash can leave a message marked
|
||||
`dispatching`, so the daemon looks for it in the recipient's history: a message found there is
|
||||
removed, and one not found, or whose history cannot be read, is sent again.
|
||||
|
||||
A client that retries a queued message with the same `messageId` is acknowledged again at once. The
|
||||
completed send receipt is written after dispatch, and a different request under that `messageId`
|
||||
conflicts. Completion waits cover queued admission within their original timeout and cancellation
|
||||
scope, and return at permission checkpoints and when the queue is held.
|
||||
The pending message window is in memory. Clean shutdown flushes it, held messages included, before
|
||||
closing agents; an abrupt crash can lose queued prompts. A durable send receipt remains pending until actual dispatch
|
||||
acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued
|
||||
admission within their original timeout and cancellation scope, and return at permission
|
||||
checkpoints and when a Stop holds the queue.
|
||||
|
||||
Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module
|
||||
persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses
|
||||
`$PASEO_HOME/finish-subscriptions.json`. Registration must commit before creation or queued-prompt
|
||||
acknowledgment promises a notification. A pending replacement retains its predecessor until dispatch
|
||||
accepts; rejected dispatch removes only the candidate. The record keeps the prompt's `messageId`, so
|
||||
withdrawing that message removes the subscription, also after a restart. Recovery coalesces
|
||||
registrations for the same caller, child, and host into one watch.
|
||||
accepts; rejected dispatch removes only the candidate. Recovery coalesces registrations for the same
|
||||
caller, child, and host into one watch.
|
||||
|
||||
Bootstrap restores these watches after repairing stale running records to `closed` and before opening
|
||||
ingress. Reading a closed child's result does not load its provider. A finish notification reports that
|
||||
the child has settled (see below); the parent decides whether its task is complete. A child chosen for restart
|
||||
recovery is observed only after its resume was sent, so the parent never hears that it was closed
|
||||
in between. A subscription whose prompt is still queued stays pending until that prompt is
|
||||
dispatched, so a held follow-up reports nothing. Archived or deleted parents suppress delivery;
|
||||
in between. Archived or deleted parents suppress delivery;
|
||||
parent-owned creation watches also stop
|
||||
reporting after detachment.
|
||||
|
||||
Intent remains stored until the parent's notification dispatch is acknowledged. Dispatch failure
|
||||
retries the captured notification; it does not change the child's reported outcome. Remote host loss
|
||||
follows the [connected-host observation policy](connected-hosts.md#delegating-agents). Shutdown stops
|
||||
observation and retains outstanding intent. A final or permission notice has an id derived from its
|
||||
subscription, so observing the same outcome again while the notice is queued adds nothing. A crash
|
||||
after successful dispatch but before removal commits can repeat the notification. This is an
|
||||
at-least-once wakeup, without turn attribution or exactly-once delivery.
|
||||
follows the [connected-host observation policy](connected-hosts.md#delegating-agents). Shutdown stops observation before flushing message delivery, retaining
|
||||
outstanding intent. A crash after successful dispatch but before removal commits can repeat the
|
||||
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
|
||||
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
|
||||
|
||||
A turn end is not always a settled child. A child can end its turn with work that will start its next
|
||||
turn by itself: a running turn, queued messages, a pending provider wake-up
|
||||
@@ -428,39 +397,6 @@ that leaves the lifecycle at `error`, and replaces unread `finished` attention;
|
||||
agent would show the green dot or none. Subagents track marks are the exception: they follow the
|
||||
child's lifecycle, because the track is where a failed child stays visible.
|
||||
|
||||
## The queue track
|
||||
|
||||
The queue track is the list above the composer of the messages the host holds for the open agent
|
||||
(`packages/app/src/composer/queue/`). One list covers every sender, in the order the host sends
|
||||
them: your queued prompts, agent messages, finish notifications, and change-request updates.
|
||||
|
||||
The host owns the [queue](#relationships) and the app keeps no copy of it. `packages/app/src/agent-queue/`
|
||||
reads the list on mount and after each reconnect, and replaces it on each `agent.queue.update`. A
|
||||
queued message therefore survives a reload, is sent with every client closed, and shows on every
|
||||
client that views the agent. Files upload to the host before the message is queued, so any device
|
||||
can open a row's attachments.
|
||||
|
||||
Rows take these commands:
|
||||
|
||||
- **Send now** promotes the row with your send behavior setting: `steer`, otherwise `interrupt`.
|
||||
- **Edit** is offered on your own messages only. It withdraws the row, then replaces the composer
|
||||
draft with its text and attachments, and stages the row's provider switch again. If the host
|
||||
already started sending the row, the draft stays as it is.
|
||||
- **Cancel** withdraws the row.
|
||||
|
||||
A message you send directly (`steer` or `interrupt`) takes the queued rows with it, ahead of your
|
||||
text.
|
||||
|
||||
A message sent mid-turn with a staged provider switch is queued whatever the send behavior, and its
|
||||
row names the target.
|
||||
|
||||
A row the host is `dispatching` takes no command. A held queue shows a paused notice. The notice
|
||||
does not name Stop, because a refused turn start holds the queue too.
|
||||
|
||||
A host without `server_info.features.agentMessageQueue` has no queue track. The composer offers no
|
||||
Queue action there, and a `queue` send behavior sends as `steer`, so it does not cut the running
|
||||
turn.
|
||||
|
||||
## The subagents track
|
||||
|
||||
The track is a pill at the foot of an agent's pane (`packages/app/src/subagents/track.tsx`): a count you can read at a glance, and a panel behind it — a popover on wide screens, a sheet on compact ones — holding the rows. It floats over the transcript rather than sitting in a band above the composer, so the timeline scrolls underneath it; `packages/app/src/panels/agent-tracks.tsx` owns that placement, and the pill frame is shared with the task list in `packages/app/src/composer/tracks.tsx`.
|
||||
|
||||
@@ -60,9 +60,6 @@ $PASEO_HOME/
|
||||
│ └── {agentId}.json # One file per agent
|
||||
├── schedules/
|
||||
│ └── {scheduleId}.json # One file per schedule
|
||||
├── agent-queues/
|
||||
│ ├── {agentId}.json # Undelivered messages for one agent; removed when empty
|
||||
│ └── {agentId}.json.corrupt.{ms} # Unreadable queue file, set aside at startup
|
||||
├── projects/
|
||||
│ ├── projects.json # Project registry
|
||||
│ ├── workspaces.json # Workspace registry
|
||||
|
||||
+2
-2
@@ -57,8 +57,8 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
||||
- **Composer toolbar** — The bottom control row inside the composer input. Contains agent controls, attachment button, voice controls, and stop/send controls. Code: `leftContent`, `beforeVoiceContent`, and `rightContent` slots in `MessageInput` (`packages/app/src/composer/input/input.tsx`). Forbidden: "Status bar".
|
||||
- **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 `<thing> 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](agent-lifecycle.md#the-queue-track) is a lane inside the composer itself. Code: `ComposerQueueTrack` (`packages/app/src/composer/queue/track.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 lists the messages the host holds until the turn ends. A queued message does not enter the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as it does for a person's queued message. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the `<thing> 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. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as the queue track does for a person. 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).
|
||||
|
||||
@@ -26,7 +26,7 @@ The package keeps the npm tarball's layout, including its build output:
|
||||
|
||||
- Metro, Vitest and TypeScript load `lib/`, not `src/`. A JavaScript change edits `src/` and the matching `lib/module` and `lib/typescript` files.
|
||||
- `android/generated` and `ios/generated` are checked-in codegen output (`includesGeneratedCode`). A change to a native component spec regenerates both; `scripts/postinstall-patches.test.mjs` compares them against the specs.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`. A parser change rebuilds them with upstream's `packages/core/cpp/wasm/build.sh`.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`, `cpp/parser` and `cpp/wasm`. A parser change rebuilds both, or web keeps the old behavior while iOS and Android change. Run `cpp/wasm/build.sh` with `OUT_DIR` set to `src/web/wasm`, in `emscripten/emsdk:4.0.10` with the `-s GROWABLE_ARRAYBUFFERS=0` line removed. That version reproduces the committed JavaScript glue and has no such setting. The `lib/module` copy is the Babel output of the new file.
|
||||
- Upstream's Gradle, CMake and CocoaPods scripts detect upstream's own monorepo by the paths `packages/core` and a root `vendor/`. Do not add either path to this repository.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
|
||||
|
||||
@@ -42,7 +42,7 @@ Some fork changes are backports. A sync past the upstream version drops them in
|
||||
|
||||
## Engine constraints
|
||||
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded.
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
|
||||
|
||||
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
|
||||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# Online client replacement: timeline recovery
|
||||
|
||||
Verified on macOS arm64 with Node 22.20.0, Chromium 145 (Playwright), and a real isolated daemon. Replies use the deterministic test provider; no external AI API is involved.
|
||||
|
||||
## Reproduction
|
||||
|
||||
1. Open two chats on one host and return to the first.
|
||||
2. Delay the active connection's real pong frames by 1 second, forwarding all real traffic, and wait for a measured liveness RTT.
|
||||
3. Add another direct endpoint for the same daemon.
|
||||
4. Advance the browser clock in 10-second steps. Each step waits for real delayed heartbeat replies and the public probe-cycle completion barrier, including replacement handshakes. The production selector and its timer constants are unchanged.
|
||||
5. Verify that every observed host snapshot stays online with a client, then confirm exactly one client-generation change to the faster endpoint.
|
||||
6. Require the Reconnecting alert to disappear within 3 seconds and verify a new message in the visible chat.
|
||||
7. Commit a message to the hidden second chat before reopening it. Verify that message is recovered, then verify another live message.
|
||||
|
||||
The two paths are localhost and 127.0.0.1 to the same daemon. The test does not force host state or replace a private client field. It controls browser time, not the daemon clock or real socket responses. Subscription assertions require the needed agents without requiring all other agents to be absent; exact matching remains the shared helper's default. The test has a 180-second timeout and a bounded clock-step budget allowing one candidate backoff. Observers, handles, timers, and scenario data are cleaned up even on failure.
|
||||
|
||||
## Before: exact final test source
|
||||
|
||||
Temporarily remove only the production `sync.setConnected(...)` seed, run the final regression, and restore the source in a `finally` block. The host remains online and changes to generation 2, but Reconnecting does not settle:
|
||||
|
||||
```text
|
||||
Error: expect(locator).toHaveCount(expected) failed
|
||||
Locator: getByRole('alert').filter({ hasText: 'Reconnecting' })
|
||||
Expected: 0
|
||||
Received: 1
|
||||
Timeout: 3000ms
|
||||
1 failed
|
||||
```
|
||||
|
||||
The frame below is extracted without modification from that final RED trace while the assertion was waiting, before fixture cleanup.
|
||||
|
||||

|
||||
|
||||
## After
|
||||
|
||||
Restore the production seed without changing the test files, then run:
|
||||
|
||||
```sh
|
||||
npm run test:e2e --workspace=@getpaseo/app -- \
|
||||
e2e/browser/viewed-agent-timelines.spec.ts \
|
||||
--grep 'online connection replacement|visible chat reports updating until reconnect' \
|
||||
--workers=1
|
||||
```
|
||||
|
||||
```text
|
||||
✓ an online connection replacement keeps every open chat synchronized (1.6m)
|
||||
✓ a visible chat reports updating until reconnect catch-up completes (35.9s)
|
||||
2 passed (2.3m)
|
||||
```
|
||||
|
||||
The online replacement case previously took 4.8 minutes with wall-clock probe waits. The final controlled-clock run takes 1.6 minutes. [Recorded hashes](red-green.json) confirm both test files are identical between final RED and GREEN and the production source was restored exactly.
|
||||
|
||||

|
||||
|
||||
## Other checks
|
||||
|
||||
```sh
|
||||
npm run typecheck
|
||||
npm run lint -- packages/app/e2e/browser/viewed-agent-timelines.spec.ts packages/app/e2e/support/helpers/timeline-delivery.ts
|
||||
npm run format
|
||||
```
|
||||
|
||||
Whole-workspace typecheck exited 0. Changed-file lint reported `Found 0 warnings and 0 errors.` Formatting passed.
|
||||
|
||||
The original runtime fix is unchanged by this test follow-up. Its previous native validation remains: both unmodified and fixed renderers exported with `PASEO_WEB_PLATFORM=electron npm exec -- expo export --platform web`; server dependencies and desktop main built through repository scripts; both packaged locally with `electron-builder --config electron-builder.yml --publish never --mac --arm64 --dir -c.mac.notarize=false`, with certificate discovery disabled.
|
||||
|
||||
The existing `packages/desktop/e2e/packaged-app-smoke.js --app <built-app>` passed for both packages with fresh temporary user data/daemon homes and loopback ports:
|
||||
|
||||
```text
|
||||
Packaged desktop smoke: real app renderer and preload bridge loaded
|
||||
Packaged desktop smoke: renderer-started desktop daemon reported running
|
||||
Packaged desktop smoke: every built-in plugin started
|
||||
Packaged desktop smoke: running bundled CLI shim daemon status
|
||||
Packaged desktop smoke: creating terminal through bundled CLI shim
|
||||
Packaged desktop smoke: terminal hook command completed
|
||||
Packaged desktop smoke passed: real renderer and preload loaded; renderer-started desktop daemon;
|
||||
CLI shim daemon status and terminal smoke succeeded
|
||||
```
|
||||
|
||||
The final summary omits ephemeral PID/listen values. The native smoke establishes packaged startup and terminal functionality, not native reconnect coverage.
|
||||
|
||||
## Coverage limits
|
||||
|
||||
- Web: real browser/daemon regression, with controlled browser scheduling, before and after.
|
||||
- macOS desktop: prior arm64 packaging and native startup/CLI/terminal smoke of the unchanged runtime fix.
|
||||
- iOS, Android, Windows desktop, Linux desktop: not tested.
|
||||
- External relay transport and a real provider turn: not tested by this regression.
|
||||
- The test requires eventual history recovery; it does not change the product's hidden-chat subscription policy or prohibit every transient toast frame.
|
||||
- These are local results. No full-suite or GitHub CI pass is claimed.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 128 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 57 KiB |
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"production_source_restored": true,
|
||||
"test_sha256": {
|
||||
"packages/app/e2e/browser/viewed-agent-timelines.spec.ts": "1857d0ca187648d8377557cd82428a64546530795cf884c7474e921a1118c003",
|
||||
"packages/app/e2e/support/helpers/timeline-delivery.ts": "23d0adb9f92daac6d0841d584abb7aa272a2981861d7d211c8213e98a9af90da"
|
||||
},
|
||||
"red": {
|
||||
"result": "expected failure",
|
||||
"assertion": "Reconnecting alert expected 0, received 1",
|
||||
"timeout_ms": 3000
|
||||
},
|
||||
"green": {
|
||||
"passed": 2,
|
||||
"online_replacement_duration": "1.6m",
|
||||
"ordinary_reconnect_duration": "35.9s",
|
||||
"total_duration": "2.3m"
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
expectComposerVisible,
|
||||
cancelAgent,
|
||||
composerLocator,
|
||||
configureComposerInterruptSend,
|
||||
expectQueuedMessageButton,
|
||||
fillComposerDraft,
|
||||
holdSendButton,
|
||||
@@ -405,6 +404,15 @@ async function queueMessage(page: Page, prompt: string): Promise<void> {
|
||||
await sendDraftToQueue(page);
|
||||
}
|
||||
|
||||
async function expectQueuedSendFailuresRestored(page: Page, prompts: string[]): Promise<void> {
|
||||
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(
|
||||
prompts.length,
|
||||
);
|
||||
for (const prompt of prompts) {
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: prompt })).toHaveCount(0);
|
||||
}
|
||||
}
|
||||
|
||||
async function expectFailedSubmissionRestored(page: Page, prompt: string): Promise<void> {
|
||||
await expectComposerDraft(page, prompt);
|
||||
await expectComposerEditable(page);
|
||||
@@ -423,14 +431,14 @@ async function expectInterruptedTurnOrderAfterReconnect(
|
||||
});
|
||||
const prompt = "Keep this prompt before its response.";
|
||||
try {
|
||||
await configureComposerInterruptSend(page);
|
||||
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Start the turn that will be interrupted.");
|
||||
await expect(page.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible();
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible();
|
||||
await queueMessage(page, prompt);
|
||||
gate.setAgentStreamSuppressed(true);
|
||||
await submitMessage(page, prompt);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).click();
|
||||
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(promptRow).toBeVisible();
|
||||
await gate.waitForServerMessage("send_agent_message_response");
|
||||
@@ -651,14 +659,14 @@ async function expectLegacyAssistantStartsAfterInterruptedPrompt(
|
||||
});
|
||||
const prompt = "Start the replacement answer after this prompt.";
|
||||
try {
|
||||
await configureComposerInterruptSend(page);
|
||||
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Start the interrupted answer.");
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toBeVisible();
|
||||
await queueMessage(page, prompt);
|
||||
gate.setAssistantMessageIdsStripped(true);
|
||||
gate.setAgentStreamEventSuppressed("turn_canceled", true);
|
||||
await submitMessage(page, prompt);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).click();
|
||||
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
const replacementAnswer = page.getByText("(end of synthetic stream)", { exact: true }).last();
|
||||
await expect(promptRow).toBeVisible();
|
||||
@@ -1090,7 +1098,6 @@ test.describe("Agent message submission", () => {
|
||||
gate.holdNextServerMessage("cancel_agent_response");
|
||||
await page.getByRole("button", { name: "Stop agent", exact: true }).click();
|
||||
await gate.waitForHeldServerMessage();
|
||||
await page.getByRole("button", { name: "Send queued message now" }).click();
|
||||
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: secondPrompt })).toHaveCount(
|
||||
1,
|
||||
@@ -1336,8 +1343,6 @@ test.describe("Agent message submission", () => {
|
||||
await test.step("holding Send queues the draft", async () => {
|
||||
await fillComposerDraft(page, queuedPrompt);
|
||||
await holdSendButton(page, "Send and steer");
|
||||
expect((await gate.waitForRequest()).activeTurnBehavior).toBe("queue");
|
||||
gate.accept();
|
||||
await expectQueuedMessageButton(page);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectAgentReadyToInterrupt(page);
|
||||
@@ -1346,22 +1351,19 @@ test.describe("Agent message submission", () => {
|
||||
).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("tapping Send still steers and takes the queued row along", async () => {
|
||||
await test.step("tapping Send still steers", async () => {
|
||||
const steeredPrompt = "Steer this turn with a tap.";
|
||||
await fillComposerDraft(page, steeredPrompt);
|
||||
await page.getByRole("button", { name: "Send and steer", exact: true }).click();
|
||||
|
||||
const request = await gate.waitForRequest(2);
|
||||
const request = await gate.waitForRequest();
|
||||
expect(request.text).toBe(steeredPrompt);
|
||||
expect(request.activeTurnBehavior).toBe("steer");
|
||||
gate.accept(1);
|
||||
gate.accept();
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: steeredPrompt }),
|
||||
).toHaveCount(1);
|
||||
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(0);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: queuedPrompt }),
|
||||
).toHaveCount(1);
|
||||
await expectQueuedMessageButton(page);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
@@ -1378,21 +1380,26 @@ test.describe("Agent message submission", () => {
|
||||
await replaySteeredSleepTurnInBrowser(page, testInfo, "codex");
|
||||
});
|
||||
|
||||
test("restores the draft when queueing loses the connection", async ({ page }, testInfo) => {
|
||||
test("restores overlapping queued sends when their connection fails", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(120_000);
|
||||
const gate = await gateNextAgentMessage(page);
|
||||
const agent = await startRunningMockAgent(page, {
|
||||
prefix: `queue-connection-lost-${testInfo.workerIndex}-`,
|
||||
prefix: `overlapping-queued-send-${testInfo.workerIndex}-`,
|
||||
model: "one-minute-stream",
|
||||
prompt: "Keep the agent running while a message queues.",
|
||||
prompt: "Keep the agent running while messages queue.",
|
||||
});
|
||||
const prompt = "Keep this draft if queueing fails.";
|
||||
const prompts = ["Restore the first queued send.", "Restore the second queued send."];
|
||||
try {
|
||||
await fillComposerDraft(page, prompt);
|
||||
await sendDraftToQueue(page);
|
||||
await gate.waitForRequest();
|
||||
await queueMessage(page, prompts[0]);
|
||||
await queueMessage(page, prompts[1]);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).first().click();
|
||||
await gate.waitForRequest(1);
|
||||
await page.getByRole("button", { name: "Send queued message now" }).first().click();
|
||||
await gate.waitForRequest(2);
|
||||
await gate.disconnect();
|
||||
await expectFailedSubmissionRestored(page, prompt);
|
||||
await expectQueuedSendFailuresRestored(page, prompts);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
|
||||
@@ -1,288 +0,0 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { expectAgentIdle } from "../support/helpers/agent-stream";
|
||||
import {
|
||||
attachComposerTestImage,
|
||||
cancelAgent,
|
||||
composerLocator,
|
||||
expectAttachmentPill,
|
||||
expectComposerDraft,
|
||||
expectComposerVisible,
|
||||
fillComposerDraft,
|
||||
sendDraftToQueue,
|
||||
} from "../support/helpers/composer";
|
||||
import {
|
||||
cancelQueuedMessage,
|
||||
editQueuedMessage,
|
||||
expectDeliveredImage,
|
||||
expectComposerOnScreen,
|
||||
expectDeliveredOnce,
|
||||
expectSenderIconUnsquashed,
|
||||
openSecondClient,
|
||||
queuedRow,
|
||||
queuedRows,
|
||||
queueMessage,
|
||||
queuePausedNotice,
|
||||
queueThroughHost,
|
||||
reopenAgent,
|
||||
scrollQueueFrom,
|
||||
seedAgentWithOpenTurn,
|
||||
sendQueuedMessageNow,
|
||||
} from "../support/helpers/composer-queue";
|
||||
import { openAgentRoute } from "../support/helpers/mock-agent";
|
||||
|
||||
test.describe("Composer queue", () => {
|
||||
test("a queued image prompt can be edited, survives a reload, and is delivered once", async ({
|
||||
page,
|
||||
}) => {
|
||||
const prompt = "Describe this screenshot.";
|
||||
const revised = "Describe this screenshot in one line.";
|
||||
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-edit-", title: "Queue edit" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await test.step("queue a prompt with an image", async () => {
|
||||
await attachComposerTestImage(page);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await queueMessage(page, prompt);
|
||||
await expect(queuedRow(page, prompt)).toContainText("1 attachment");
|
||||
});
|
||||
|
||||
await test.step("Edit takes the text and image back into the composer", async () => {
|
||||
await editQueuedMessage(page, prompt);
|
||||
await expect(queuedRows(page)).toHaveCount(0);
|
||||
await expectComposerDraft(page, prompt);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await expect(composerLocator(page)).toBeFocused();
|
||||
});
|
||||
|
||||
await test.step("queue the revised prompt with the same image", async () => {
|
||||
await queueMessage(page, revised);
|
||||
await expect(queuedRow(page, revised)).toContainText("1 attachment");
|
||||
});
|
||||
|
||||
await test.step("the row is still there after a reload", async () => {
|
||||
await page.reload();
|
||||
await expect(queuedRow(page, revised)).toBeVisible({ timeout: 30_000 });
|
||||
await expect(queuedRows(page)).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("the prompt is delivered once when the turn ends", async () => {
|
||||
await agent.finishTurn();
|
||||
await expectDeliveredOnce(page, revised);
|
||||
await expectDeliveredImage(page, revised);
|
||||
await expect(queuedRows(page)).toHaveCount(0);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("Stop pauses the queue until the user sends a row", async ({ page }) => {
|
||||
const prompt = "Run after I say so.";
|
||||
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-held-", title: "Queue held" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await queueMessage(page, prompt);
|
||||
await expect(queuePausedNotice(page)).toHaveCount(0);
|
||||
|
||||
await cancelAgent(page);
|
||||
|
||||
await expectAgentIdle(page);
|
||||
await expect(queuePausedNotice(page)).toBeVisible();
|
||||
await expect(queuedRow(page, prompt)).toBeVisible();
|
||||
|
||||
await sendQueuedMessageNow(page, prompt);
|
||||
|
||||
await expectDeliveredOnce(page, prompt);
|
||||
await expect(queuePausedNotice(page)).toHaveCount(0);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("the host delivers a queued prompt with every client closed", async ({ page }) => {
|
||||
const prompt = "Continue while I am away.";
|
||||
const agent = await seedAgentWithOpenTurn({
|
||||
repoPrefix: "queue-closed-",
|
||||
title: "Queue closed",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await queueMessage(page, prompt);
|
||||
|
||||
await page.close();
|
||||
await agent.finishTurn();
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
const reopened = await reopenAgent(page, agent);
|
||||
|
||||
await expectDeliveredOnce(reopened, prompt);
|
||||
await expect(queuedRows(reopened)).toHaveCount(0);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("two clients share one queue", async ({ browser, page }) => {
|
||||
const unwanted = "Do not run this one.";
|
||||
const urgent = "Run this one now.";
|
||||
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-sync-", title: "Queue sync" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const second = await openSecondClient(browser, page, agent);
|
||||
try {
|
||||
await expectComposerVisible(second.page);
|
||||
|
||||
await test.step("a row queued on one client appears on the other", async () => {
|
||||
await queueMessage(page, unwanted);
|
||||
await expect(queuedRow(second.page, unwanted)).toBeVisible();
|
||||
await fillComposerDraft(second.page, urgent);
|
||||
await sendDraftToQueue(second.page);
|
||||
await expect(queuedRows(page)).toContainText([unwanted, urgent]);
|
||||
});
|
||||
|
||||
await test.step("Cancel on one client removes the row on the other", async () => {
|
||||
await cancelQueuedMessage(second.page, unwanted);
|
||||
await expect(queuedRow(page, unwanted)).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("Send now on one client updates the other", async () => {
|
||||
await sendQueuedMessageNow(page, urgent);
|
||||
await expectDeliveredOnce(second.page, urgent);
|
||||
await expect(
|
||||
second.page.getByTestId("user-message").filter({ hasText: unwanted }),
|
||||
).toHaveCount(0);
|
||||
});
|
||||
} finally {
|
||||
await second.close();
|
||||
}
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("a long queue scrolls without pushing the composer off screen", async ({ page }) => {
|
||||
const texts = Array.from({ length: 20 }, (_, index) => `Queued update ${index + 1}.`);
|
||||
const first = "Queued update 1.";
|
||||
const last = "Queued update 20.";
|
||||
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-long-", title: "Queue long" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await queueThroughHost(agent, texts);
|
||||
await expect(queuedRows(page)).toHaveCount(20);
|
||||
|
||||
for (const viewport of [
|
||||
{ width: 1280, height: 800 },
|
||||
{ width: 390, height: 844 },
|
||||
// A phone with its keyboard open.
|
||||
{ width: 390, height: 500 },
|
||||
]) {
|
||||
await test.step(`${viewport.width}x${viewport.height}`, async () => {
|
||||
await page.setViewportSize(viewport);
|
||||
await expect(queuedRow(page, first)).toBeVisible();
|
||||
await expectComposerOnScreen(page);
|
||||
|
||||
await scrollQueueFrom(page, first, 5000);
|
||||
// Scrolled to the end, a fractional frame height can clip a sub-pixel of the row.
|
||||
await expect(queuedRow(page, last)).toBeInViewport({ ratio: 0.99 });
|
||||
await expectComposerOnScreen(page);
|
||||
|
||||
await scrollQueueFrom(page, last, -5000);
|
||||
await expect(queuedRow(page, first)).toBeInViewport({ ratio: 1 });
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("a message queued by another agent can be cancelled but not edited", async ({ page }) => {
|
||||
const message = "The release notes are ready for review.";
|
||||
const agent = await seedAgentWithOpenTurn({
|
||||
repoPrefix: "queue-sender-",
|
||||
title: "Queue recipient",
|
||||
});
|
||||
try {
|
||||
const sender = await agent.client.createAgent({
|
||||
provider: "mock",
|
||||
cwd: agent.cwd,
|
||||
workspaceId: agent.workspaceId,
|
||||
title: "Release coordination and changelog verification helper for the mobile team",
|
||||
model: "e2e-fast-stream",
|
||||
});
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await agent.client.sendAgentMessage(agent.agentId, message, {
|
||||
sourceAgentId: sender.id,
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
|
||||
const row = queuedRow(page, message);
|
||||
await expect(row).toContainText("Sent by Release coordination");
|
||||
await expect(row.getByRole("button", { name: "Send queued message now" })).toBeEnabled();
|
||||
await expect(row.getByRole("button", { name: "Cancel queued message" })).toBeEnabled();
|
||||
await expect(row.getByRole("button", { name: "Edit queued message" })).toHaveCount(0);
|
||||
|
||||
await test.step("a long sender name truncates without squashing its icon", async () => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expect(row).toBeInViewport();
|
||||
await expectSenderIconUnsquashed(row);
|
||||
});
|
||||
|
||||
await cancelQueuedMessage(page, message);
|
||||
|
||||
await expect(queuedRows(page)).toHaveCount(0);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("editing a queued image prompt on a short phone viewport keeps remaining queued rows visible", async ({
|
||||
page,
|
||||
}) => {
|
||||
const withImage = "Describe this screenshot.";
|
||||
const remaining = Array.from({ length: 4 }, (_, index) => `Remaining update ${index + 1}.`);
|
||||
const agent = await seedAgentWithOpenTurn({
|
||||
repoPrefix: "queue-compact-edit-",
|
||||
title: "Queue compact edit",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await attachComposerTestImage(page);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await queueMessage(page, withImage);
|
||||
await queueThroughHost(agent, remaining);
|
||||
await expect(queuedRows(page)).toHaveCount(5);
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 500 });
|
||||
await editQueuedMessage(page, withImage);
|
||||
await expectComposerDraft(page, withImage);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await expect(composerLocator(page)).toBeInViewport({ ratio: 1 });
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Send and steer", exact: true }),
|
||||
).toBeInViewport({
|
||||
ratio: 1,
|
||||
});
|
||||
|
||||
// The queue scroll viewport must keep a readable slice (>= 90px) above the restored image pill,
|
||||
// not collapse to a sliver inside a 0.6*viewport slot clamp.
|
||||
const scrollFrameHeight = await page
|
||||
.getByRole("list", { name: "Queued messages" })
|
||||
.evaluate((list) => {
|
||||
const scrollView = list.parentElement?.parentElement;
|
||||
return scrollView ? scrollView.getBoundingClientRect().height : 0;
|
||||
});
|
||||
expect(scrollFrameHeight).toBeGreaterThanOrEqual(90);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -499,56 +499,6 @@ test.describe.serial("Provider switching in chat", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("edits a queued switch and sends it now, cutting the running turn", async ({ page }) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
const queuedPrompt = "Take over now on the Direct provider.";
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-queued-edit-",
|
||||
title: "Provider switch queued edit",
|
||||
model: "one-minute-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await submitMessage(page, "Run a one-minute mock turn first.");
|
||||
await expectAgentReadyToInterrupt(page);
|
||||
await stageDirectProviderDesktop(page);
|
||||
|
||||
const banner = page.getByTestId("staged-provider-switch-banner");
|
||||
const queuedRow = page.getByRole("listitem").filter({ hasText: queuedPrompt });
|
||||
await submitMessage(page, queuedPrompt);
|
||||
await expect(queuedRow).toContainText(`Switches to ${DIRECT_PROVIDER.label}`);
|
||||
await expect(banner).toHaveCount(0);
|
||||
await captureQaScreenshot(page, "queued-provider-switch.png");
|
||||
|
||||
await queuedRow.getByRole("button", { name: "Edit queued message" }).click();
|
||||
await expect(queuedRow).toHaveCount(0);
|
||||
await expect(banner).toBeVisible();
|
||||
|
||||
await submitMessage(page, queuedPrompt);
|
||||
await expect(queuedRow).toContainText(`Switches to ${DIRECT_PROVIDER.label}`);
|
||||
await queuedRow.getByRole("button", { name: "Send queued message now" }).click();
|
||||
|
||||
await expect(page.getByTestId("provider-switch-marker")).toBeVisible({ timeout: 30_000 });
|
||||
await expect(
|
||||
page.getByTestId("assistant-message").filter({ hasText: queuedPrompt }).last(),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
await expectAgentIdle(page);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: DIRECT_PROVIDER.id,
|
||||
model: DIRECT_PROVIDER.modelId,
|
||||
modeId: "build",
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("switches providers cleanly on a compact viewport with zero horizontal overflow", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { buildHostAgentDetailRoute } from "@/utils/host-routes";
|
||||
import { test } from "../support/fixtures";
|
||||
import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
|
||||
import { observeTimelineSubscriptions } from "../support/helpers/timeline-delivery";
|
||||
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
|
||||
import { selectWorkspaceInSidebar } from "../support/helpers/sidebar";
|
||||
@@ -254,7 +255,226 @@ async function expectCurrentChatWithoutCatchUp(page: Page, message: string) {
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function delayActiveDaemonPongs(page: Page, port: string) {
|
||||
let deliveredPongs = 0;
|
||||
let inFlightPings = 0;
|
||||
const delayedPongs = new Set<ReturnType<typeof setTimeout>>();
|
||||
await page.routeWebSocket(
|
||||
(url) => url.hostname === "localhost" && url.port === port,
|
||||
(socket) => {
|
||||
const server = socket.connectToServer();
|
||||
socket.onMessage((message) => {
|
||||
if (typeof message === "string" && JSON.parse(message).type === "ping") inFlightPings += 1;
|
||||
server.send(message);
|
||||
});
|
||||
server.onMessage((message) => {
|
||||
if (typeof message === "string" && JSON.parse(message).type === "pong") {
|
||||
const timer = setTimeout(() => {
|
||||
delayedPongs.delete(timer);
|
||||
socket.send(message);
|
||||
deliveredPongs += 1;
|
||||
inFlightPings -= 1;
|
||||
}, 1_000);
|
||||
delayedPongs.add(timer);
|
||||
} else {
|
||||
socket.send(message);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
return {
|
||||
delivered: () => deliveredPongs,
|
||||
settled: () => inFlightPings === 0 && delayedPongs.size === 0,
|
||||
dispose: () => {
|
||||
for (const timer of delayedPongs) clearTimeout(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function readActiveLivenessRtt(page: Page): Promise<number> {
|
||||
return page.evaluate((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getClient(id: string): { getLastLivenessRttMs(): number | null } | null;
|
||||
};
|
||||
return runtime.getClient(serverId)?.getLastLivenessRttMs() ?? 0;
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function readHostConnection(page: Page) {
|
||||
return page.evaluate((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): {
|
||||
clientGeneration: number;
|
||||
connectionStatus: string;
|
||||
activeConnectionId: string;
|
||||
};
|
||||
};
|
||||
const snapshot = runtime.getSnapshot(serverId);
|
||||
return {
|
||||
generation: snapshot.clientGeneration,
|
||||
status: snapshot.connectionStatus,
|
||||
connection: snapshot.activeConnectionId,
|
||||
};
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function settleHostProbeCycle(page: Page): Promise<void> {
|
||||
await page.evaluate(async (serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
runProbeCycleNow(id: string): Promise<void>;
|
||||
};
|
||||
// Joins any in-flight cycle through its final replacement handshake.
|
||||
await runtime.runProbeCycleNow(serverId);
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function observeContinuousHostConnection(page: Page) {
|
||||
const observation = await page.evaluateHandle((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): { connectionStatus: string; client: unknown } | null;
|
||||
subscribe(id: string, listener: () => void): () => void;
|
||||
};
|
||||
const connected: boolean[] = [];
|
||||
const record = () => {
|
||||
const snapshot = runtime.getSnapshot(serverId);
|
||||
connected.push(snapshot?.connectionStatus === "online" && snapshot.client !== null);
|
||||
};
|
||||
record();
|
||||
const unsubscribe = runtime.subscribe(serverId, record);
|
||||
return {
|
||||
stop() {
|
||||
unsubscribe();
|
||||
return connected;
|
||||
},
|
||||
};
|
||||
}, getServerId());
|
||||
let stopped: Promise<boolean[]> | null = null;
|
||||
return {
|
||||
stop() {
|
||||
stopped ??= observation
|
||||
.evaluate((recorder) => recorder.stop())
|
||||
.finally(() => observation.dispose());
|
||||
return stopped;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function advanceToOnlineReplacement(
|
||||
page: Page,
|
||||
delayedPongs: Awaited<ReturnType<typeof delayActiveDaemonPongs>>,
|
||||
beforeGeneration: number,
|
||||
) {
|
||||
// Advance scheduling, not the sockets: settle real heartbeat and probe replies
|
||||
// between hops, including the replacement handshake, without altering production timers.
|
||||
for (let step = 0; step < 60; step += 1) {
|
||||
if ((await readHostConnection(page)).generation !== beforeGeneration) break;
|
||||
await expect.poll(delayedPongs.settled, { timeout: 10_000 }).toBe(true);
|
||||
await settleHostProbeCycle(page);
|
||||
const pongsBefore = delayedPongs.delivered();
|
||||
await page.clock.fastForward(10_000);
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
(await readHostConnection(page)).generation !== beforeGeneration ||
|
||||
delayedPongs.delivered() > pongsBefore,
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
await settleHostProbeCycle(page);
|
||||
}
|
||||
}
|
||||
|
||||
test.describe("Viewed agent timelines", () => {
|
||||
test("an online connection replacement keeps every open chat synchronized", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.clock.install();
|
||||
const port = getE2EDaemonPort();
|
||||
const delayedEndpoint = `localhost:${port}`;
|
||||
const fasterEndpoint = `127.0.0.1:${port}`;
|
||||
const delayedPongs = await delayActiveDaemonPongs(page, port);
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
const scenario = await seedViewedTimelineScenario();
|
||||
let connectionObservation:
|
||||
| Awaited<ReturnType<typeof observeContinuousHostConnection>>
|
||||
| undefined;
|
||||
try {
|
||||
await commitMessage(scenario, scenario.firstAgentId, "BEFORE_CONNECTION_REPLACEMENT");
|
||||
await openAgent(page, scenario, scenario.firstAgentId);
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId]);
|
||||
await expectReconnectingToastGone(page);
|
||||
// The adaptive selector needs an RTT from the active socket, not only its startup probe.
|
||||
await expect.poll(delayedPongs.delivered, { timeout: 30_000 }).toBeGreaterThan(1);
|
||||
await expect
|
||||
.poll(() => readActiveLivenessRtt(page), { timeout: 30_000 })
|
||||
.toBeGreaterThanOrEqual(800);
|
||||
|
||||
// Add another real route to the same daemon. Delaying only the active route's real
|
||||
// pong frames gives the ordinary adaptive selector three consistently faster probes.
|
||||
// No host state is forced offline and no client or timeline owner is replaced by the test.
|
||||
connectionObservation = await observeContinuousHostConnection(page);
|
||||
const beforeGeneration = await page.evaluate(
|
||||
async ({ serverId, endpoint, activeEndpoint }) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): {
|
||||
clientGeneration: number;
|
||||
connectionStatus: string;
|
||||
activeConnectionId: string;
|
||||
};
|
||||
upsertDirectConnection(input: { serverId: string; endpoint: string }): Promise<unknown>;
|
||||
};
|
||||
const before = runtime.getSnapshot(serverId);
|
||||
if (
|
||||
before.connectionStatus !== "online" ||
|
||||
before.activeConnectionId !== `direct:${activeEndpoint}`
|
||||
) {
|
||||
throw new Error("Expected the initial real connection to be online");
|
||||
}
|
||||
await runtime.upsertDirectConnection({ serverId, endpoint });
|
||||
return before.clientGeneration;
|
||||
},
|
||||
{ serverId: getServerId(), endpoint: fasterEndpoint, activeEndpoint: delayedEndpoint },
|
||||
);
|
||||
subscriptions.reset();
|
||||
await advanceToOnlineReplacement(page, delayedPongs, beforeGeneration);
|
||||
await expect
|
||||
.poll(() => readHostConnection(page), { timeout: 3_000 })
|
||||
.toEqual({
|
||||
generation: beforeGeneration + 1,
|
||||
status: "online",
|
||||
connection: `direct:${fasterEndpoint}`,
|
||||
});
|
||||
expect(await connectionObservation.stop()).not.toContain(false);
|
||||
await expectReconnectingToastGone(page, { timeout: 3_000 });
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath("after-online-connection-replacement.png"),
|
||||
});
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId], { match: "includes" });
|
||||
await commitMessage(scenario, scenario.firstAgentId, "FIRST_CHAT_AFTER_REPLACEMENT");
|
||||
await expect(page.getByText("FIRST_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
|
||||
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_WHILE_HIDDEN");
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await expectReconnectingToastGone(page, { timeout: 3_000 });
|
||||
await expect(page.getByText("SECOND_CHAT_WHILE_HIDDEN", { exact: true })).toBeVisible();
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId], {
|
||||
match: "includes",
|
||||
});
|
||||
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_AFTER_REPLACEMENT");
|
||||
await expect(page.getByText("SECOND_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath("both-chats-synchronized.png") });
|
||||
} finally {
|
||||
try {
|
||||
await connectionObservation?.stop();
|
||||
} finally {
|
||||
delayedPongs.dispose();
|
||||
await scenario.cleanup();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("a reloaded layout subscribes only the chat it restores into", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { readScrollMetrics, waitForContentGrowth, expectNearBottom } from "./agent-bottom-anchor";
|
||||
import { agentStopButton } from "./composer";
|
||||
|
||||
export async function awaitAssistantMessage(page: Page, hasText?: string | RegExp): Promise<void> {
|
||||
const messages = page.getByTestId("assistant-message");
|
||||
@@ -15,7 +14,7 @@ export async function awaitToolCall(page: Page, toolName: string | RegExp): Prom
|
||||
}
|
||||
|
||||
export async function expectAgentIdle(page: Page, timeout = 30_000): Promise<void> {
|
||||
await expect(agentStopButton(page)).toHaveCount(0, { timeout });
|
||||
await expect(page.getByRole("button", { name: /stop|cancel/i })).toHaveCount(0, { timeout });
|
||||
}
|
||||
|
||||
// The working indicator is an animated spinner View — no semantic ARIA role, testId is correct.
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
import { expect, type Browser, type Locator, type Page } from "@playwright/test";
|
||||
import { hideDeveloperToasts } from "../developer-ui.mjs";
|
||||
import {
|
||||
agentStopButton,
|
||||
composerLocator,
|
||||
expectComposerDraft,
|
||||
fillComposerDraft,
|
||||
sendDraftToQueue,
|
||||
} from "./composer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
|
||||
|
||||
export interface AgentWithOpenTurn extends MockAgentWorkspace {
|
||||
/** Ends the open turn from outside the app, so it also works with every page closed. */
|
||||
finishTurn(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A mock agent whose first turn stays open on a plan approval. The turn ends when the test
|
||||
* answers it, so nothing here depends on how long a stream runs.
|
||||
*/
|
||||
export async function seedAgentWithOpenTurn(input: {
|
||||
repoPrefix: string;
|
||||
title: string;
|
||||
}): Promise<AgentWithOpenTurn> {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
...input,
|
||||
initialPrompt: "Emit synthetic plan approval.",
|
||||
});
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
return {
|
||||
...agent,
|
||||
async finishTurn() {
|
||||
const fetched = await agent.client.fetchAgent({ agentId: agent.agentId });
|
||||
const request = fetched?.agent.pendingPermissions[0];
|
||||
if (!request) throw new Error("The agent has no open turn to finish");
|
||||
await agent.client.respondToPermission(agent.agentId, request.id, { behavior: "allow" });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function queuedRows(page: Page): Locator {
|
||||
return page.getByRole("list", { name: "Queued messages" }).getByRole("listitem");
|
||||
}
|
||||
|
||||
export function queuedRow(page: Page, text: string): Locator {
|
||||
return queuedRows(page).filter({ hasText: text });
|
||||
}
|
||||
|
||||
export async function queueMessage(page: Page, text: string): Promise<void> {
|
||||
await fillComposerDraft(page, text);
|
||||
await sendDraftToQueue(page);
|
||||
await expect(queuedRow(page, text)).toBeVisible();
|
||||
await expectComposerDraft(page, "");
|
||||
}
|
||||
|
||||
export async function editQueuedMessage(page: Page, text: string): Promise<void> {
|
||||
await queuedRow(page, text)
|
||||
.getByRole("button", { name: "Edit queued message", exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
export async function cancelQueuedMessage(page: Page, text: string): Promise<void> {
|
||||
await queuedRow(page, text)
|
||||
.getByRole("button", { name: "Cancel queued message", exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
export async function sendQueuedMessageNow(page: Page, text: string): Promise<void> {
|
||||
await queuedRow(page, text)
|
||||
.getByRole("button", { name: "Send queued message now", exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
export function queuePausedNotice(page: Page): Locator {
|
||||
return page.getByText("Queue paused until you send a message", { exact: true });
|
||||
}
|
||||
|
||||
/** Queues through the host, for tests that need more rows than are worth typing. */
|
||||
export async function queueThroughHost(agent: AgentWithOpenTurn, texts: string[]): Promise<void> {
|
||||
for (const text of texts) {
|
||||
await agent.client.sendAgentMessage(agent.agentId, text, { activeTurnBehavior: "queue" });
|
||||
}
|
||||
}
|
||||
|
||||
/** The composer input and Stop are both fully on screen. */
|
||||
export async function expectComposerOnScreen(page: Page): Promise<void> {
|
||||
await expect(composerLocator(page)).toBeInViewport({ ratio: 1 });
|
||||
await expect(agentStopButton(page)).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
/** Turns the mouse wheel over one row, as a user does to move through the queue. */
|
||||
export async function scrollQueueFrom(page: Page, text: string, deltaY: number): Promise<void> {
|
||||
await queuedRow(page, text).hover();
|
||||
await page.mouse.wheel(0, deltaY);
|
||||
}
|
||||
|
||||
/** The icon leading a row's "Sent by" line is drawn at its full width. */
|
||||
export async function expectSenderIconUnsquashed(row: Locator): Promise<void> {
|
||||
const icon = await row.locator("svg").first().boundingBox();
|
||||
if (!icon) throw new Error("The row has no visible sender icon");
|
||||
expect(icon.width).toBeGreaterThanOrEqual(icon.height);
|
||||
}
|
||||
|
||||
/** The queued prompt reached the transcript exactly once and left the queue. */
|
||||
export async function expectDeliveredOnce(page: Page, text: string): Promise<void> {
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: text })).toHaveCount(1, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(queuedRow(page, text)).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectDeliveredImage(page: Page, text: string): Promise<void> {
|
||||
await expect(
|
||||
page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: text })
|
||||
.getByRole("button", { name: "Open image attachment" }),
|
||||
).toHaveCount(1);
|
||||
}
|
||||
|
||||
/** A page opened after the first one was closed, with the same stored app data. */
|
||||
export async function reopenAgent(page: Page, agent: AgentWithOpenTurn): Promise<Page> {
|
||||
const reopened = await page.context().newPage();
|
||||
await hideDeveloperToasts(reopened);
|
||||
await openAgentRoute(reopened, agent);
|
||||
return reopened;
|
||||
}
|
||||
|
||||
/** A second client of the same host: its own browser context and its own client id. */
|
||||
export async function openSecondClient(
|
||||
browser: Browser,
|
||||
page: Page,
|
||||
agent: AgentWithOpenTurn,
|
||||
): Promise<{ page: Page; close(): Promise<void> }> {
|
||||
const context = await browser.newContext({ storageState: await page.context().storageState() });
|
||||
const second = await context.newPage();
|
||||
await second.addInitScript(() => localStorage.removeItem("@paseo:client-id-v1"));
|
||||
await hideDeveloperToasts(second);
|
||||
await openAgentRoute(second, agent);
|
||||
return { page: second, close: () => context.close() };
|
||||
}
|
||||
@@ -103,13 +103,8 @@ export async function expectQueuedMessageButton(page: Page): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
/** The composer's Stop button. Queued rows also have a Cancel button, so match the whole name. */
|
||||
export function agentStopButton(page: Page) {
|
||||
return page.getByRole("button", { name: /^(stop|canceling) agent$/i });
|
||||
}
|
||||
|
||||
export async function cancelAgent(page: Page): Promise<void> {
|
||||
const stopButton = agentStopButton(page).first();
|
||||
const stopButton = page.getByRole("button", { name: /stop|cancel/i }).first();
|
||||
await expect(stopButton).toBeVisible({ timeout: 10_000 });
|
||||
await stopButton.click();
|
||||
}
|
||||
@@ -305,7 +300,9 @@ export async function startRunningMockAgent(
|
||||
await page.goto(agentUrl);
|
||||
await expectComposerVisible(page);
|
||||
await client.sendAgentMessage(agent.id, opts.prompt);
|
||||
await expect(agentStopButton(page).first()).toBeVisible({ timeout: 30_000 });
|
||||
await expect(page.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
return {
|
||||
client,
|
||||
repo,
|
||||
@@ -470,12 +467,6 @@ export async function configureComposerQueueSend(page: Page): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
export async function configureComposerInterruptSend(page: Page): Promise<void> {
|
||||
await page.addInitScript(() =>
|
||||
localStorage.setItem("@paseo:app-settings", JSON.stringify({ sendBehavior: "interrupt" })),
|
||||
);
|
||||
}
|
||||
|
||||
/** Drive the real tab chooser's commands even when fullscreen covers its pointer surface.
|
||||
* This exercises retained activity changes, not a claim that covered chrome is clickable.
|
||||
*/
|
||||
|
||||
@@ -168,11 +168,6 @@ export interface SeedDaemonClient {
|
||||
timeout?: number,
|
||||
): Promise<{ status: string }>;
|
||||
cancelAgent(agentId: string): Promise<void>;
|
||||
respondToPermission(
|
||||
agentId: string,
|
||||
requestId: string,
|
||||
response: { behavior: "allow" },
|
||||
): Promise<void>;
|
||||
sendAgentMessage(
|
||||
agentId: string,
|
||||
text: string,
|
||||
@@ -187,9 +182,9 @@ export interface SeedDaemonClient {
|
||||
): Promise<{ status: string; final?: { lastError?: string | null } | null }>;
|
||||
archiveAgent(agentId: string): Promise<{ archivedAt: string }>;
|
||||
refreshAgent(agentId: string): Promise<unknown>;
|
||||
fetchAgent(options: { agentId: string }): Promise<{
|
||||
agent: { id: string; archivedAt?: string | null; pendingPermissions: Array<{ id: string }> };
|
||||
} | null>;
|
||||
fetchAgent(options: {
|
||||
agentId: string;
|
||||
}): Promise<{ agent: { id: string; archivedAt?: string | null } } | null>;
|
||||
getLastServerInfoMessage(): {
|
||||
features?: {
|
||||
projectAdd?: boolean;
|
||||
|
||||
@@ -9,6 +9,7 @@ interface SessionMessage {
|
||||
|
||||
interface TimelineSubscriptionWaitOptions {
|
||||
timeout?: number;
|
||||
match?: "exact" | "includes";
|
||||
}
|
||||
|
||||
function readSessionMessage(message: WebSocketMessage): SessionMessage | null {
|
||||
@@ -56,7 +57,7 @@ export function observeTimelineSubscriptions(page: Page) {
|
||||
.poll(() => acknowledgedAgentIds?.slice().sort() ?? null, {
|
||||
timeout: options.timeout ?? 15_000,
|
||||
})
|
||||
.toEqual(expected);
|
||||
.toEqual(options.match === "includes" ? expect.arrayContaining(expected) : expected);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
import { expect, test } from "vitest";
|
||||
import type { PaseoAgentQueueItem } from "@getpaseo/client";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { createHostAgentQueueModel } from "./host";
|
||||
|
||||
interface Observer {
|
||||
snapshot(): void;
|
||||
update(message: SessionOutboundMessage): void;
|
||||
error(error: unknown): void;
|
||||
}
|
||||
|
||||
function item(id: string): PaseoAgentQueueItem {
|
||||
return {
|
||||
id,
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T00:00:00.000Z",
|
||||
text: `message ${id}`,
|
||||
sender: { kind: "user" },
|
||||
held: false,
|
||||
state: "queued",
|
||||
};
|
||||
}
|
||||
|
||||
/** A host runtime plus the daemon client it hands out. */
|
||||
function fakeHost(options: { supportsQueue: boolean }) {
|
||||
let connected = false;
|
||||
let notify = () => {};
|
||||
const observers: Observer[] = [];
|
||||
const calls: unknown[][] = [];
|
||||
let releases = 0;
|
||||
let queue = [item("a")];
|
||||
const client = {
|
||||
getLastServerInfoMessage: () =>
|
||||
connected ? { features: { agentMessageQueue: options.supportsQueue } } : null,
|
||||
listAgentQueue: async (agentId: string) => {
|
||||
calls.push(["list", agentId]);
|
||||
return { held: false, items: queue };
|
||||
},
|
||||
withdrawAgentQueueItem: async (agentId: string, messageId: string) => {
|
||||
calls.push(["withdraw", agentId, messageId]);
|
||||
return { withdrawn: true as const, item: item(messageId) };
|
||||
},
|
||||
promoteAgentQueueItem: async (agentId: string, messageId: string, behavior: string) => {
|
||||
calls.push(["promote", agentId, messageId, behavior]);
|
||||
return { promoted: true as const };
|
||||
},
|
||||
observeAgentQueue: () => ({
|
||||
subscribe: (observer: Observer) => {
|
||||
observers.push(observer);
|
||||
},
|
||||
release: async () => {
|
||||
releases++;
|
||||
},
|
||||
}),
|
||||
};
|
||||
return {
|
||||
host: {
|
||||
getClient: () => client,
|
||||
subscribe: (listener: () => void) => {
|
||||
notify = listener;
|
||||
return () => {};
|
||||
},
|
||||
},
|
||||
observers,
|
||||
calls,
|
||||
releases: () => releases,
|
||||
setQueue: (next: PaseoAgentQueueItem[]) => {
|
||||
queue = next;
|
||||
},
|
||||
connect: () => {
|
||||
connected = true;
|
||||
notify();
|
||||
},
|
||||
disconnect: () => {
|
||||
connected = false;
|
||||
notify();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
function queueUpdate(agentId: string, items: PaseoAgentQueueItem[]): SessionOutboundMessage {
|
||||
return { type: "agent.queue.update", payload: { agentId, held: false, items } };
|
||||
}
|
||||
|
||||
test("lists on connect, follows its own agent's updates, and lists again on reconnect", async () => {
|
||||
const runtime = fakeHost({ supportsQueue: true });
|
||||
const model = createHostAgentQueueModel("host", "agent", runtime.host);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
expect(runtime.observers).toHaveLength(0);
|
||||
|
||||
runtime.connect();
|
||||
runtime.observers[0].snapshot();
|
||||
await settle();
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [item("a")] });
|
||||
|
||||
runtime.observers[0].update(queueUpdate("other-agent", []));
|
||||
expect(model.getSnapshot().items).toEqual([item("a")]);
|
||||
runtime.observers[0].update(queueUpdate("agent", [item("a"), item("b")]));
|
||||
expect(model.getSnapshot().items).toEqual([item("a"), item("b")]);
|
||||
|
||||
runtime.disconnect();
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "stale", items: [item("a"), item("b")] });
|
||||
expect(runtime.releases()).toBe(1);
|
||||
|
||||
runtime.setQueue([]);
|
||||
runtime.connect();
|
||||
runtime.observers[1].snapshot();
|
||||
await settle();
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
|
||||
runtime.observers[0].update(queueUpdate("agent", [item("late")]));
|
||||
expect(model.getSnapshot().items).toEqual([]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("sends withdraw and promote for the observed agent", async () => {
|
||||
const runtime = fakeHost({ supportsQueue: true });
|
||||
const model = createHostAgentQueueModel("host", "agent", runtime.host);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
runtime.connect();
|
||||
runtime.observers[0].update(queueUpdate("agent", [item("a"), item("b")]));
|
||||
|
||||
await model.promote("b", "interrupt");
|
||||
await model.withdraw("a");
|
||||
|
||||
expect(runtime.calls).toEqual([
|
||||
["promote", "agent", "b", "interrupt"],
|
||||
["withdraw", "agent", "a"],
|
||||
]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("rejects a command while the host is disconnected", async () => {
|
||||
const runtime = fakeHost({ supportsQueue: true });
|
||||
const model = createHostAgentQueueModel("host", "agent", runtime.host);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
runtime.connect();
|
||||
runtime.observers[0].update(queueUpdate("agent", [item("a")]));
|
||||
runtime.disconnect();
|
||||
|
||||
await expect(model.withdraw("a")).rejects.toThrow("Host disconnected");
|
||||
expect(runtime.calls).toEqual([]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("has no queue and asks nothing of a host without the feature", async () => {
|
||||
const runtime = fakeHost({ supportsQueue: false });
|
||||
const model = createHostAgentQueueModel("host", "agent", runtime.host);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
|
||||
runtime.connect();
|
||||
await settle();
|
||||
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
|
||||
expect(runtime.observers).toHaveLength(0);
|
||||
expect(runtime.calls).toEqual([]);
|
||||
unsubscribe();
|
||||
});
|
||||
@@ -1,118 +0,0 @@
|
||||
import type {
|
||||
PaseoAgentQueuePromoteResult,
|
||||
PaseoAgentQueueState,
|
||||
PaseoAgentQueueWithdrawResult,
|
||||
} from "@getpaseo/client";
|
||||
import type { ActiveTurnBehavior, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { createAgentQueueModel, type AgentQueueModel } from "./model";
|
||||
|
||||
interface AgentQueueClient {
|
||||
getLastServerInfoMessage(): { features?: { agentMessageQueue?: boolean } | null } | null;
|
||||
listAgentQueue(agentId: string): Promise<PaseoAgentQueueState>;
|
||||
withdrawAgentQueueItem(
|
||||
agentId: string,
|
||||
messageId: string,
|
||||
): Promise<PaseoAgentQueueWithdrawResult>;
|
||||
promoteAgentQueueItem(
|
||||
agentId: string,
|
||||
messageId: string,
|
||||
activeTurnBehavior: ActiveTurnBehavior,
|
||||
): Promise<PaseoAgentQueuePromoteResult>;
|
||||
observeAgentQueue(): {
|
||||
subscribe(observer: {
|
||||
snapshot(): void;
|
||||
update(message: SessionOutboundMessage): void;
|
||||
error(error: unknown): void;
|
||||
}): unknown;
|
||||
release(): Promise<void>;
|
||||
};
|
||||
}
|
||||
|
||||
interface AgentQueueHost {
|
||||
getClient(): AgentQueueClient | null;
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
function hostFor(serverId: string): AgentQueueHost {
|
||||
const host = getHostRuntimeStore();
|
||||
return {
|
||||
getClient: () => host.getSnapshot(serverId)?.client ?? null,
|
||||
subscribe: (listener) => host.subscribe(serverId, listener),
|
||||
};
|
||||
}
|
||||
|
||||
export function createHostAgentQueueModel(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
host: AgentQueueHost = hostFor(serverId),
|
||||
): AgentQueueModel {
|
||||
let client: AgentQueueClient | null = null;
|
||||
const connected = () => {
|
||||
if (!client) throw new Error("Host disconnected");
|
||||
return client;
|
||||
};
|
||||
return createAgentQueueModel({
|
||||
list: async () => connected().listAgentQueue(agentId),
|
||||
withdraw: async (messageId) => connected().withdrawAgentQueueItem(agentId, messageId),
|
||||
promote: async (messageId, activeTurnBehavior) =>
|
||||
connected().promoteAgentQueueItem(agentId, messageId, activeTurnBehavior),
|
||||
observe: ({ snapshot, update, disconnected, failed }) => {
|
||||
let release: (() => void) | undefined;
|
||||
let currentObservation: ReturnType<AgentQueueClient["observeAgentQueue"]> | undefined;
|
||||
const sync = () => {
|
||||
const candidate = host.getClient();
|
||||
// The runtime keeps the client across reconnects, but clears server info until handshake.
|
||||
const next = candidate?.getLastServerInfoMessage() ? candidate : null;
|
||||
if (next === client) return;
|
||||
const previousRelease = release;
|
||||
client = next;
|
||||
release = undefined;
|
||||
disconnected();
|
||||
previousRelease?.();
|
||||
if (!client) return;
|
||||
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
|
||||
if (client.getLastServerInfoMessage()?.features?.agentMessageQueue !== true) {
|
||||
update({ held: false, items: [] });
|
||||
return;
|
||||
}
|
||||
const observedClient = client;
|
||||
const observation = client.observeAgentQueue();
|
||||
currentObservation = observation;
|
||||
const isCurrent = () => client === observedClient && currentObservation === observation;
|
||||
observation.subscribe({
|
||||
snapshot: () => {
|
||||
if (isCurrent()) snapshot();
|
||||
},
|
||||
update: (message) => {
|
||||
if (
|
||||
isCurrent() &&
|
||||
message.type === "agent.queue.update" &&
|
||||
message.payload.agentId === agentId
|
||||
) {
|
||||
update({ held: message.payload.held, items: message.payload.items });
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
if (isCurrent()) failed();
|
||||
},
|
||||
});
|
||||
release = () => {
|
||||
if (currentObservation === observation) currentObservation = undefined;
|
||||
void observation
|
||||
.release()
|
||||
.catch((error: unknown) =>
|
||||
console.error("Agent queue subscription cleanup failed", error),
|
||||
);
|
||||
};
|
||||
};
|
||||
const unsubscribe = host.subscribe(sync);
|
||||
sync();
|
||||
return () => {
|
||||
unsubscribe();
|
||||
client = null;
|
||||
release?.();
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { useMemo, useSyncExternalStore } from "react";
|
||||
import { createHostAgentQueueModel } from "./host";
|
||||
import type { AgentQueueModel, AgentQueueSnapshot } from "./model";
|
||||
|
||||
export type { AgentQueueModel, AgentQueueSnapshot } from "./model";
|
||||
|
||||
/** Observes one agent's queue for as long as the caller is mounted. */
|
||||
export function useAgentQueue(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): { model: AgentQueueModel; queue: AgentQueueSnapshot } {
|
||||
const model = useMemo(() => createHostAgentQueueModel(serverId, agentId), [serverId, agentId]);
|
||||
const queue = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||
return { model, queue };
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
import { expect, test } from "vitest";
|
||||
import type {
|
||||
PaseoAgentQueueItem,
|
||||
PaseoAgentQueueState,
|
||||
PaseoAgentQueueWithdrawResult,
|
||||
} from "@getpaseo/client";
|
||||
import { createAgentQueueModel, type AgentQueuePort } from "./model";
|
||||
|
||||
function item(id: string, patch: Partial<PaseoAgentQueueItem> = {}): PaseoAgentQueueItem {
|
||||
return {
|
||||
id,
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T00:00:00.000Z",
|
||||
text: `message ${id}`,
|
||||
sender: { kind: "user" },
|
||||
held: false,
|
||||
state: "queued",
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve(value: T): void;
|
||||
reject(error: Error): void;
|
||||
}
|
||||
|
||||
function deferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((done, fail) => {
|
||||
resolve = done;
|
||||
reject = fail;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
/** A host queue the test drives: it records commands and answers them when told to. */
|
||||
function fakeQueueHost() {
|
||||
const lists: Deferred<PaseoAgentQueueState>[] = [];
|
||||
const withdrawals: Array<{ messageId: string } & Deferred<PaseoAgentQueueWithdrawResult>> = [];
|
||||
const promotions: Array<{ messageId: string; behavior: string }> = [];
|
||||
let callbacks: Parameters<AgentQueuePort["observe"]>[0] | null = null;
|
||||
const port: AgentQueuePort = {
|
||||
list: () => {
|
||||
const read = deferred<PaseoAgentQueueState>();
|
||||
lists.push(read);
|
||||
return read.promise;
|
||||
},
|
||||
withdraw: (messageId) => {
|
||||
const request = deferred<PaseoAgentQueueWithdrawResult>();
|
||||
withdrawals.push({ messageId, ...request });
|
||||
return request.promise;
|
||||
},
|
||||
promote: async (messageId, behavior) => {
|
||||
promotions.push({ messageId, behavior });
|
||||
return { promoted: true };
|
||||
},
|
||||
observe: (next) => {
|
||||
callbacks = next;
|
||||
return () => {
|
||||
callbacks = null;
|
||||
};
|
||||
},
|
||||
};
|
||||
return {
|
||||
port,
|
||||
lists,
|
||||
withdrawals,
|
||||
promotions,
|
||||
isObserved: () => callbacks !== null,
|
||||
connect: () => callbacks?.snapshot(),
|
||||
disconnect: () => callbacks?.disconnected(),
|
||||
fail: () => callbacks?.failed(),
|
||||
publish: (queue: PaseoAgentQueueState) => callbacks?.update(queue),
|
||||
};
|
||||
}
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
test("hydrates the queue the host holds when observation starts", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "loading", held: false, items: [] });
|
||||
|
||||
host.connect();
|
||||
host.lists[0].resolve({ held: true, items: [item("a", { held: true })] });
|
||||
await settle();
|
||||
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
status: "ready",
|
||||
held: true,
|
||||
items: [item("a", { held: true })],
|
||||
});
|
||||
unsubscribe();
|
||||
expect(host.isObserved()).toBe(false);
|
||||
});
|
||||
|
||||
test("replaces the whole queue with each live update, ahead of a slower list", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.connect();
|
||||
|
||||
host.publish({ held: false, items: [item("a"), item("b", { seq: 2 })] });
|
||||
host.lists[0].resolve({ held: false, items: [] });
|
||||
await settle();
|
||||
|
||||
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["a", "b"]);
|
||||
host.publish({ held: false, items: [item("b", { seq: 2 })] });
|
||||
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["b"]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("keeps the last rows while disconnected and reads the queue again on reconnect", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.connect();
|
||||
host.lists[0].resolve({ held: false, items: [item("a")] });
|
||||
await settle();
|
||||
|
||||
host.disconnect();
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "stale", items: [item("a")] });
|
||||
host.connect();
|
||||
host.lists[1].resolve({ held: false, items: [] });
|
||||
await settle();
|
||||
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("offers a retry when the queue cannot be read", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.connect();
|
||||
host.lists[0].reject(new Error("timeout"));
|
||||
await settle();
|
||||
expect(model.getSnapshot().status).toBe("error");
|
||||
|
||||
model.retry();
|
||||
host.lists[1].resolve({ held: false, items: [item("a")] });
|
||||
await settle();
|
||||
|
||||
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [item("a")] });
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("marks a row busy while it is withdrawn and returns the withdrawn message", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.publish({ held: false, items: [item("a"), item("b", { seq: 2 })] });
|
||||
|
||||
const first = model.withdraw("a");
|
||||
const second = model.withdraw("a");
|
||||
expect(model.getSnapshot().busy).toEqual(new Set(["a"]));
|
||||
host.withdrawals[0].resolve({ withdrawn: true, item: item("a") });
|
||||
|
||||
expect(await first).toEqual({ withdrawn: true, item: item("a") });
|
||||
expect(await second).toBeNull();
|
||||
expect(host.withdrawals).toHaveLength(1);
|
||||
expect(model.getSnapshot().busy).toEqual(new Set());
|
||||
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["b"]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("keeps the row when the host already started sending it", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.publish({ held: false, items: [item("a")] });
|
||||
|
||||
const result = model.withdraw("a");
|
||||
host.withdrawals[0].resolve({ withdrawn: false, reason: "already_dispatching" });
|
||||
|
||||
expect(await result).toEqual({ withdrawn: false, reason: "already_dispatching" });
|
||||
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["a"]);
|
||||
expect(model.getSnapshot().busy).toEqual(new Set());
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("releases the row and reports the error when a command fails", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.publish({ held: false, items: [item("a")] });
|
||||
|
||||
const result = model.withdraw("a");
|
||||
host.withdrawals[0].reject(new Error("Host disconnected"));
|
||||
|
||||
await expect(result).rejects.toThrow("Host disconnected");
|
||||
expect(model.getSnapshot().busy).toEqual(new Set());
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("promotes a row with the chosen send behavior", async () => {
|
||||
const host = fakeQueueHost();
|
||||
const model = createAgentQueueModel(host.port);
|
||||
const unsubscribe = model.subscribe(() => {});
|
||||
host.publish({ held: true, items: [item("a", { held: true })] });
|
||||
|
||||
expect(await model.promote("a", "steer")).toEqual({ promoted: true });
|
||||
expect(host.promotions).toEqual([{ messageId: "a", behavior: "steer" }]);
|
||||
unsubscribe();
|
||||
});
|
||||
@@ -1,145 +0,0 @@
|
||||
import type {
|
||||
PaseoAgentQueueItem,
|
||||
PaseoAgentQueuePromoteResult,
|
||||
PaseoAgentQueueState,
|
||||
PaseoAgentQueueWithdrawResult,
|
||||
} from "@getpaseo/client";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
|
||||
export interface AgentQueuePort {
|
||||
list(): Promise<PaseoAgentQueueState>;
|
||||
withdraw(messageId: string): Promise<PaseoAgentQueueWithdrawResult>;
|
||||
promote(
|
||||
messageId: string,
|
||||
activeTurnBehavior: ActiveTurnBehavior,
|
||||
): Promise<PaseoAgentQueuePromoteResult>;
|
||||
observe(callbacks: {
|
||||
snapshot(): void;
|
||||
disconnected(): void;
|
||||
failed(): void;
|
||||
update(queue: PaseoAgentQueueState): void;
|
||||
}): () => void;
|
||||
}
|
||||
|
||||
export interface AgentQueueSnapshot {
|
||||
status: "loading" | "stale" | "ready" | "error";
|
||||
/** The host waits for Send now or the next prompt before it sends these. */
|
||||
held: boolean;
|
||||
/** Admission order. The first row is sent next. */
|
||||
items: PaseoAgentQueueItem[];
|
||||
/** Rows with a command in flight. */
|
||||
busy: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One agent's queue as the host holds it. The host is the only writer: every update replaces
|
||||
* the rows, and a command changes nothing here until the host answers it.
|
||||
*/
|
||||
export function createAgentQueueModel(port: AgentQueuePort) {
|
||||
let state: AgentQueueSnapshot = {
|
||||
status: "loading",
|
||||
held: false,
|
||||
items: [],
|
||||
busy: new Set(),
|
||||
};
|
||||
let hasRead = false;
|
||||
let sequence = 0;
|
||||
let stop: (() => void) | undefined;
|
||||
let observationFailed = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
const publish = (patch: Partial<AgentQueueSnapshot>) => {
|
||||
state = { ...state, ...patch };
|
||||
for (const listener of listeners) listener();
|
||||
};
|
||||
const replace = (queue: PaseoAgentQueueState) => {
|
||||
hasRead = true;
|
||||
publish({ status: "ready", held: queue.held, items: queue.items });
|
||||
};
|
||||
const pending = () => (hasRead ? "stale" : "loading");
|
||||
const refresh = async () => {
|
||||
const request = ++sequence;
|
||||
publish({ status: pending() });
|
||||
try {
|
||||
const queue = await port.list();
|
||||
if (request === sequence) replace(queue);
|
||||
} catch {
|
||||
if (request === sequence) publish({ status: "error" });
|
||||
}
|
||||
};
|
||||
const start = () => {
|
||||
observationFailed = false;
|
||||
stop = port.observe({
|
||||
snapshot: () => {
|
||||
void refresh();
|
||||
},
|
||||
disconnected: () => {
|
||||
sequence++;
|
||||
publish({ status: pending() });
|
||||
},
|
||||
failed: () => {
|
||||
observationFailed = true;
|
||||
sequence++;
|
||||
publish({ status: "error" });
|
||||
},
|
||||
update: (queue) => {
|
||||
sequence++;
|
||||
replace(queue);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
/** Runs one command per row at a time. Returns null when the row cannot take one. */
|
||||
const command = async <T>(messageId: string, run: () => Promise<T>): Promise<T | null> => {
|
||||
const row = state.items.find((entry) => entry.id === messageId);
|
||||
if (!row || row.state === "dispatching" || state.busy.has(messageId)) return null;
|
||||
publish({ busy: new Set(state.busy).add(messageId) });
|
||||
try {
|
||||
return await run();
|
||||
} finally {
|
||||
const busy = new Set(state.busy);
|
||||
busy.delete(messageId);
|
||||
publish({ busy });
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
getSnapshot: () => state,
|
||||
withdraw: (messageId: string) =>
|
||||
command(messageId, async () => {
|
||||
const result = await port.withdraw(messageId);
|
||||
// The host confirmed the removal. Drop the row now so it is not pressable again
|
||||
// between this answer and the next update.
|
||||
if (result.withdrawn) {
|
||||
publish({ items: state.items.filter((entry) => entry.id !== messageId) });
|
||||
}
|
||||
return result;
|
||||
}),
|
||||
promote: (messageId: string, activeTurnBehavior: ActiveTurnBehavior) =>
|
||||
command(messageId, () => port.promote(messageId, activeTurnBehavior)),
|
||||
retry: () => {
|
||||
if (observationFailed) {
|
||||
stop?.();
|
||||
stop = undefined;
|
||||
publish({ status: pending() });
|
||||
start();
|
||||
} else {
|
||||
void refresh();
|
||||
}
|
||||
},
|
||||
subscribe(listener: () => void) {
|
||||
listeners.add(listener);
|
||||
if (!stop) start();
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (!listeners.size) {
|
||||
sequence++;
|
||||
stop?.();
|
||||
stop = undefined;
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type AgentQueueModel = ReturnType<typeof createAgentQueueModel>;
|
||||
@@ -954,6 +954,19 @@ it("keeps table cell pipes escaped in text/plain table syntax and literal in tex
|
||||
expect(content?.html).toContain("<td>Value | detail</td>");
|
||||
});
|
||||
|
||||
it("keeps a table cell's line breaks inside its row", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML =
|
||||
"<table><thead><tr><th>Name<br>label</th><th>Note</th></tr></thead><tbody><tr><td>first<br>second</td><td><br> stays text</td></tr></tbody></table>";
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
|
||||
expect(content?.plainText).toBe(
|
||||
"| Name<br>label | Note |\n| --- | --- |\n| first<br>second | <br> stays text |",
|
||||
);
|
||||
expect(content?.html).toContain("<th>Name<br>\nlabel</th>");
|
||||
expect(content?.html).toContain("<td>first<br>\nsecond</td>");
|
||||
expect(content?.html).toContain("<td><br> stays text</td>");
|
||||
});
|
||||
|
||||
it("copies a workspace image path instead of its temporary display URL", () => {
|
||||
const message = mountFixture();
|
||||
const sources = JSON.stringify({ "blob:preview": "assets/chart.png" });
|
||||
|
||||
@@ -69,12 +69,13 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
});
|
||||
turndown.use(gfm);
|
||||
// text/plain still carries tables as GFM syntax, so a cell's pipe stays escaped there.
|
||||
// A row is one line, so a cell's line break goes back to `<br>`.
|
||||
turndown.addRule("escapedGfmTableCell", {
|
||||
filter: ["th", "td"],
|
||||
replacement: (content, node) => {
|
||||
const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0;
|
||||
const prefix = index === 0 ? "| " : " ";
|
||||
return `${prefix}${content.replace(/\|/g, "\\|")} |`;
|
||||
return `${prefix}${content.replace(/\|/g, "\\|").replace(/ *\n/g, "<br>")} |`;
|
||||
},
|
||||
});
|
||||
// A link Paseo recognized pastes as the text the reply showed. Rich paste keeps it as a
|
||||
|
||||
@@ -108,8 +108,6 @@ export type UserComposerAttachment =
|
||||
| { kind: "file"; attachment: UploadedFileAttachment }
|
||||
| WorkspaceFileComposerAttachment
|
||||
| PluginResourceComposerAttachment
|
||||
// An attachment taken back from a queued message. The host already holds it in wire form.
|
||||
| { kind: "agent_attachment"; attachment: AgentAttachment }
|
||||
| { kind: "forge_issue"; item: ForgeSearchItem }
|
||||
| { kind: "forge_change_request"; item: ForgeSearchItem }
|
||||
// COMPAT(githubAttachmentKinds): legacy persisted attachment kinds retained
|
||||
|
||||
@@ -131,18 +131,13 @@ export function AttachmentLabel({ icon, title, subtitle }: AttachmentLabelProps)
|
||||
);
|
||||
}
|
||||
|
||||
/** Holds a thumbnail's space while its image loads. */
|
||||
export function AttachmentThumbnailPlaceholder() {
|
||||
return <View style={styles.thumbnailPlaceholder} />;
|
||||
}
|
||||
|
||||
/** Square image preview pill body. */
|
||||
export function AttachmentThumbnail({ metadata }: { metadata: AttachmentMetadata }) {
|
||||
const preview = useAttachmentPreviewUrl(metadata);
|
||||
const uri = preview.status === "ready" ? preview.url : null;
|
||||
const source = useMemo(() => (uri ? { uri } : null), [uri]);
|
||||
if (!source) {
|
||||
return <AttachmentThumbnailPlaceholder />;
|
||||
return <View style={styles.thumbnailPlaceholder} />;
|
||||
}
|
||||
return <Image source={source} style={styles.thumbnail} />;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Parser } from "htmlparser2";
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { decodeString } from "micromark-util-decode-string";
|
||||
import type { Nodes } from "mdast";
|
||||
|
||||
@@ -53,6 +55,8 @@ export function normalizeMarkdownHtml(source: string): string {
|
||||
} else if ("children" in node) node.children.forEach(protectCode);
|
||||
}
|
||||
protectCode(tree);
|
||||
// Only `<br>` reads these, so a source without one skips the extra parse.
|
||||
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, codeRanges) : [];
|
||||
const links: (string | undefined)[] = [];
|
||||
let previousTag: { name: string; end: number } | null = null;
|
||||
const convert = (raw: string, offset: number): string => {
|
||||
@@ -84,7 +88,16 @@ export function normalizeMarkdownHtml(source: string): string {
|
||||
: /^\s*$/.test(source.slice(0, offset));
|
||||
previousTag = { name, end: offset + raw.length };
|
||||
if (EMPHASIS[name]) return EMPHASIS[name];
|
||||
const boundary = layoutBoundary(name, source, raw, offset, closing, startsAfterBoundary);
|
||||
const inTable = tableRanges.some(({ start, end }) => offset >= start && offset < end);
|
||||
const boundary = layoutBoundary(
|
||||
name,
|
||||
source,
|
||||
raw,
|
||||
offset,
|
||||
closing,
|
||||
startsAfterBoundary,
|
||||
inTable,
|
||||
);
|
||||
if (boundary !== null) return boundary;
|
||||
if (name === "a") return markdownAnchor(raw, closing, links);
|
||||
if (name === "img" && !closing) {
|
||||
@@ -167,8 +180,15 @@ function layoutBoundary(
|
||||
offset: number,
|
||||
closing: boolean,
|
||||
startsAfterBoundary: boolean,
|
||||
inTable: boolean,
|
||||
): string | null {
|
||||
if (name === "br") return closing ? "" : " \n";
|
||||
// Inside GFM table cells, emit ` \u2028 ` so row boundaries stay intact while giving flanking
|
||||
// emphasis/strikethrough delimiters and URLs/autolinks whitespace boundaries on both sides before
|
||||
// the cell-scoped parser turns ` \u2028 ` back into a `LineBreak` node.
|
||||
if (name === "br") {
|
||||
if (closing) return "";
|
||||
return inTable ? " \u2028 " : " \n";
|
||||
}
|
||||
if (name === "summary") return closing ? "**\n\n" : "**";
|
||||
if (name === "details")
|
||||
return (closing ? offset + raw.length === source.length : offset === 0) ? "" : "\n\n";
|
||||
@@ -177,3 +197,67 @@ function layoutBoundary(
|
||||
return /^<t[dh]\b/i.test(source.slice(offset + raw.length)) ? " " : "";
|
||||
return null;
|
||||
}
|
||||
|
||||
function hasNonWhitespaceAfterNewline(value: string): boolean {
|
||||
const lastNewline = value.lastIndexOf("\n");
|
||||
return /[^\s]/.test(lastNewline === -1 ? value : value.slice(lastNewline + 1));
|
||||
}
|
||||
|
||||
function isTableWrapperTag(raw: string, inCode: boolean): boolean {
|
||||
if (inCode) return false;
|
||||
if (raw.startsWith("<!--")) return true;
|
||||
const name = /^<\/?([A-Za-z][A-Za-z0-9-]*)/.exec(raw)?.[1].toLowerCase();
|
||||
return name === "summary" || name === "details" || (name !== undefined && BLOCK_TAGS.has(name));
|
||||
}
|
||||
|
||||
function collectTableRanges(
|
||||
source: string,
|
||||
codeRanges: readonly { start: number; end: number }[],
|
||||
): { start: number; end: number }[] {
|
||||
let cursor = 0;
|
||||
let codeIndex = 0;
|
||||
let lineHasPrefixText = false;
|
||||
// Advance line/code state monotonically in a single forward pass so large single-line HTML tables stay O(n)
|
||||
// while nested leading wrappers (e.g. `<details><summary>Results</summary><div>| A | B |`) follow
|
||||
// line breaks introduced by earlier masked tags.
|
||||
const tableSource = source.replace(HTML, (raw, offset: number) => {
|
||||
for (let index = cursor; index < offset; index++) {
|
||||
const code = source.charCodeAt(index);
|
||||
if (code === 10) lineHasPrefixText = false;
|
||||
else if (code !== 32 && code !== 9 && code !== 13) lineHasPrefixText = true;
|
||||
}
|
||||
cursor = offset + raw.length;
|
||||
while (codeIndex < codeRanges.length && codeRanges[codeIndex].end <= offset) codeIndex++;
|
||||
const inCode = codeIndex < codeRanges.length && offset >= codeRanges[codeIndex].start;
|
||||
if (!isTableWrapperTag(raw, inCode)) {
|
||||
if (inCode || /^<code\b/i.test(raw)) {
|
||||
if (hasNonWhitespaceAfterNewline(raw)) lineHasPrefixText = true;
|
||||
else if (raw.includes("\n")) lineHasPrefixText = false;
|
||||
} else if (raw.includes("\n")) {
|
||||
lineHasPrefixText = false;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
const blanked = raw.replace(/[^\n]/g, " ");
|
||||
if (!lineHasPrefixText && blanked.length > 0 && !blanked.endsWith("\n")) {
|
||||
return `${blanked.slice(0, -1)}\n`;
|
||||
}
|
||||
if (blanked.includes("\n")) lineHasPrefixText = false;
|
||||
return blanked;
|
||||
});
|
||||
const tableRanges: { start: number; end: number }[] = [];
|
||||
function findTables(node: Nodes) {
|
||||
if (node.type === "table" && node.position) {
|
||||
const start = node.position.start.offset;
|
||||
const end = node.position.end.offset;
|
||||
if (start !== undefined && end !== undefined) tableRanges.push({ start, end });
|
||||
} else if ("children" in node) node.children.forEach(findTables);
|
||||
}
|
||||
findTables(
|
||||
fromMarkdown(tableSource, {
|
||||
extensions: [{ disable: { null: ["htmlFlow", "htmlText"] } }, gfmTable()],
|
||||
mdastExtensions: [gfmTableFromMarkdown()],
|
||||
}),
|
||||
);
|
||||
return tableRanges;
|
||||
}
|
||||
|
||||
@@ -838,6 +838,188 @@ describe("GitHub comment HTML normalization", () => {
|
||||
])("normalizes %s without changing code", (source, expected) => {
|
||||
expect(prepareMarkdownSource(source).render()).toBe(expected);
|
||||
});
|
||||
|
||||
it("keeps <br> line breaks inside GFM table headers and cells within a single row", async () => {
|
||||
const source = [
|
||||
"| Col<br>One | Col<br />Two |",
|
||||
"| --- | --- |",
|
||||
"| First<br>Second<br/>Third | Plain |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const table = tree.children?.find((node) => node.type === "Table");
|
||||
expect(table).toBeDefined();
|
||||
const headRows = table?.children?.find((node) => node.type === "TableHead")?.children ?? [];
|
||||
const bodyRows = table?.children?.find((node) => node.type === "TableBody")?.children ?? [];
|
||||
expect(headRows).toHaveLength(1);
|
||||
expect(bodyRows).toHaveLength(1);
|
||||
const [headCells, bodyCells] = [headRows[0].children ?? [], bodyRows[0].children ?? []];
|
||||
expect(headCells[0].children).toEqual([
|
||||
{ type: "Text", content: "Col" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "One" },
|
||||
]);
|
||||
expect(headCells[1].children).toEqual([
|
||||
{ type: "Text", content: "Col" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Two" },
|
||||
]);
|
||||
expect(bodyCells[0].children).toEqual([
|
||||
{ type: "Text", content: "First" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Second" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Third" },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"<details><summary>Results</summary>\n\n| A | B |\n| - | - |\n| 1<br>2 | 3 |\n</details>",
|
||||
"<details><summary>Results</summary>| A | B |\n| - | - |\n| 1<br>2 | 3 |</details>",
|
||||
"<details><summary>Results</summary><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div></details>",
|
||||
"<span></span><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div>",
|
||||
])("keeps table <br> inside wrapped table cells: %s", async (source) => {
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const table = tree.children?.find((node) => node.type === "Table");
|
||||
expect(table).toBeDefined();
|
||||
const body = table?.children?.find((node) => node.type === "TableBody");
|
||||
expect(body?.children).toHaveLength(1);
|
||||
expect(body?.children?.[0]?.children?.[0]?.children).toEqual([
|
||||
{ type: "Text", content: "1" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "2" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("recognizes file paths and URLs separated by <br> inside table cells", async () => {
|
||||
const source = [
|
||||
"| Paths | Mixed | URLs |",
|
||||
"| --- | --- | --- |",
|
||||
"| src/first.ts<br>src/second.ts | https://example.com/first<br>src/second.ts | https://example.com/first<br>https://example.com/second |",
|
||||
].join("\n");
|
||||
const prepared = prepareMarkdownSource(source);
|
||||
const linked = recognizeTextLinks(
|
||||
await parseMarkdown(prepared.render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
}),
|
||||
prepared.linkRecognition.text,
|
||||
prepared.linkRecognition.inlineCode,
|
||||
);
|
||||
const table = linked.children?.find((node) => node.type === "Table");
|
||||
const row = table?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/first.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/first.ts" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/second.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/second.ts" }],
|
||||
},
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/first" },
|
||||
children: [{ type: "Text", content: "https://example.com/first" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/second.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/second.ts" }],
|
||||
},
|
||||
]);
|
||||
expect(row?.children?.[2]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/first" },
|
||||
children: [{ type: "Text", content: "https://example.com/first" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/second" },
|
||||
children: [{ type: "Text", content: "https://example.com/second" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps literal U+2028 outside tables, inline code, and escaped <br> untouched", async () => {
|
||||
const source = [
|
||||
"before\u2028after `before\u2028after`",
|
||||
"",
|
||||
"| Inline | Escaped | Entity |",
|
||||
"| --- | --- | --- |",
|
||||
"| `before\u2028after` | \\<br> | <br> `<br>` |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const collectLineBreaks = (node: ASTNode): number =>
|
||||
(node.type === "LineBreak" ? 1 : 0) +
|
||||
(node.children?.reduce((count, child) => count + collectLineBreaks(child), 0) ?? 0);
|
||||
expect(collectLineBreaks(tree)).toBe(0);
|
||||
|
||||
const paragraph = tree.children?.find((node) => node.type === "Paragraph");
|
||||
expect(paragraph?.children).toEqual([
|
||||
{ type: "Text", content: "before\u2028after " },
|
||||
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
|
||||
]);
|
||||
|
||||
const row = tree.children
|
||||
?.find((node) => node.type === "Table")
|
||||
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([{ type: "Text", content: "<br>" }]);
|
||||
expect(row?.children?.[2]?.children).toEqual([
|
||||
{ type: "Text", content: "<br> " },
|
||||
{ type: "Code", children: [{ type: "Text", content: "<br>" }] },
|
||||
]);
|
||||
expect(prepareMarkdownSource("<table><tr><td>a<br>b</td></tr></table>").render()).toBe(
|
||||
"a \nb",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves emphasis and strong delimiters adjacent to <br> inside table cells", async () => {
|
||||
const source = [
|
||||
"| A | B |",
|
||||
"| --- | --- |",
|
||||
"| **方案 B(最猛 · 推荐)**<br>阶梯首充 | **`基准 → 30% → 50%`**<br>*(复购:基准)* |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const row = tree.children
|
||||
?.find((node) => node.type === "Table")
|
||||
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{ type: "Strong", children: [{ type: "Text", content: "方案 B(最猛 · 推荐)" }] },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "阶梯首充" },
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([
|
||||
{
|
||||
type: "Strong",
|
||||
children: [{ type: "Code", children: [{ type: "Text", content: "基准 → 30% → 50%" }] }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Emphasis", children: [{ type: "Text", content: "(复购:基准)" }] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves backslashes and decodes entities inside HTML code", () => {
|
||||
|
||||
@@ -25,18 +25,22 @@ import {
|
||||
uploadFileAttachments,
|
||||
cancelComposerAgent,
|
||||
dispatchComposerAgentMessage,
|
||||
enqueueComposerAgentMessage,
|
||||
editQueuedComposerMessage,
|
||||
findForgeItemByOption,
|
||||
isAttachmentSelectedForForgeItem,
|
||||
openComposerAttachment,
|
||||
pickAndPersistImages,
|
||||
queueComposerMessage,
|
||||
removeComposerAttachmentAtIndex,
|
||||
sendQueuedComposerMessageNow,
|
||||
toggleForgeAttachment,
|
||||
toggleForgeAttachmentFromPicker,
|
||||
type MessageSubmissionWriter,
|
||||
type AttachmentPersister,
|
||||
type ComposerCancelClient,
|
||||
type ComposerSendClient,
|
||||
type QueueWriter,
|
||||
type QueuedComposerMessage,
|
||||
} from "./actions";
|
||||
|
||||
const imageMetadata: AttachmentMetadata = {
|
||||
@@ -180,7 +184,7 @@ interface FakeSendCall {
|
||||
text: string;
|
||||
options: {
|
||||
messageId: string;
|
||||
activeTurnBehavior?: "interrupt" | "steer" | "queue";
|
||||
activeTurnBehavior?: "interrupt" | "steer";
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments: AgentAttachment[];
|
||||
};
|
||||
@@ -302,6 +306,19 @@ function writeSubmission(fake: FakeStream, agentId: string, state: FakeSubmissio
|
||||
submissionsByFakeStream.set(fake, submissions);
|
||||
}
|
||||
|
||||
function createFakeQueue(
|
||||
initial: Map<string, QueuedComposerMessage[]> = new Map(),
|
||||
): QueueWriter & { state: Map<string, QueuedComposerMessage[]> } {
|
||||
const fake: QueueWriter & { state: Map<string, QueuedComposerMessage[]> } = {
|
||||
state: new Map(initial),
|
||||
read: (agentId) => fake.state.get(agentId) ?? [],
|
||||
write: (updater) => {
|
||||
fake.state = updater(fake.state);
|
||||
},
|
||||
};
|
||||
return fake;
|
||||
}
|
||||
|
||||
const passthroughUploadImages = async (
|
||||
images: AttachmentMetadata[],
|
||||
): Promise<UploadedFileAttachment[]> =>
|
||||
@@ -738,186 +755,147 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("enqueueComposerAgentMessage", () => {
|
||||
it("hands a trimmed message to the host queue without adding a timeline row", async () => {
|
||||
const client = createFakeSendClient();
|
||||
const review = reviewWorkspaceAttachment("Queued review.");
|
||||
|
||||
await enqueueComposerAgentMessage({
|
||||
client,
|
||||
describe("queueComposerMessage", () => {
|
||||
it("queues a trimmed message under the agent id and returns the new entry", () => {
|
||||
const queue = createFakeQueue();
|
||||
const result = queueComposerMessage({
|
||||
agentId: "agent",
|
||||
text: " queue this ",
|
||||
attachments: [{ kind: "image", metadata: imageWithId("img-queue") }, review],
|
||||
uploadImages: passthroughUploadImages,
|
||||
text: " draft ",
|
||||
attachments: [],
|
||||
queue,
|
||||
});
|
||||
|
||||
expect(client.calls).toEqual([
|
||||
{
|
||||
agentId: "agent",
|
||||
text: "queue this",
|
||||
options: {
|
||||
messageId: expect.any(String),
|
||||
activeTurnBehavior: "queue",
|
||||
attachments: [
|
||||
review.attachment,
|
||||
expect.objectContaining({
|
||||
type: "uploaded_file",
|
||||
id: "upload_img-queue",
|
||||
role: "image",
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
expect(result.queued?.text).toBe("draft");
|
||||
expect(queue.state.get("agent")).toEqual([
|
||||
{ id: result.queued?.id, text: "draft", attachments: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("sends nothing for an empty message with no attachments", async () => {
|
||||
const client = createFakeSendClient();
|
||||
|
||||
await enqueueComposerAgentMessage({ client, agentId: "agent", text: " ", attachments: [] });
|
||||
|
||||
expect(client.calls).toEqual([]);
|
||||
});
|
||||
|
||||
it("queues a staged provider switch with the message so the host runs it on that provider", async () => {
|
||||
const client = createFakeSendClient();
|
||||
const switches: unknown[] = [];
|
||||
let queuedSwitches = 0;
|
||||
|
||||
const input: Parameters<typeof enqueueComposerAgentMessage>[0] = {
|
||||
client: {
|
||||
...client,
|
||||
switchAgentProvider: async (agentId, options) => {
|
||||
switches.push({ agentId, options });
|
||||
return {};
|
||||
},
|
||||
},
|
||||
it("does not queue an empty message with no attachments", () => {
|
||||
const queue = createFakeQueue();
|
||||
const result = queueComposerMessage({
|
||||
agentId: "agent",
|
||||
text: "do Z",
|
||||
text: " ",
|
||||
attachments: [],
|
||||
stagedProviderSwitch: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
modeId: "auto",
|
||||
thinkingOptionId: null,
|
||||
providerOptions: { fast_mode: true },
|
||||
},
|
||||
onProviderSwitchQueued: () => {
|
||||
queuedSwitches += 1;
|
||||
},
|
||||
};
|
||||
await enqueueComposerAgentMessage(input);
|
||||
// Nothing to send leaves the switch with the composer.
|
||||
await enqueueComposerAgentMessage({ ...input, text: " " });
|
||||
|
||||
expect(queuedSwitches).toBe(1);
|
||||
expect(client.calls).toEqual([]);
|
||||
expect(switches).toEqual([
|
||||
{
|
||||
agentId: "agent",
|
||||
options: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
modeId: "auto",
|
||||
thinkingOptionId: null,
|
||||
providerOptions: { fast_mode: true },
|
||||
text: "do Z",
|
||||
messageId: expect.any(String),
|
||||
activeTurnBehavior: "queue",
|
||||
attachments: [],
|
||||
},
|
||||
},
|
||||
]);
|
||||
queue,
|
||||
});
|
||||
expect(result.queued).toBeNull();
|
||||
expect(queue.state.get("agent")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects when the host refuses the message", async () => {
|
||||
const rejection = new Error("Agent not found");
|
||||
const client = createFakeSendClient({ rejection });
|
||||
it("captures workspace review attachments at queue time alongside user attachments", () => {
|
||||
const queue = createFakeQueue();
|
||||
const review = reviewWorkspaceAttachment("Initial queued review.");
|
||||
const image = imageWithId("img-queue");
|
||||
queueComposerMessage({
|
||||
agentId: "agent",
|
||||
text: "queue this",
|
||||
attachments: [{ kind: "image", metadata: image }, review],
|
||||
queue,
|
||||
});
|
||||
|
||||
await expect(
|
||||
enqueueComposerAgentMessage({ client, agentId: "agent", text: "hello", attachments: [] }),
|
||||
).rejects.toBe(rejection);
|
||||
expect(queue.state.get("agent")?.[0]?.attachments).toEqual([
|
||||
{ kind: "image", metadata: image },
|
||||
review,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("attachments restored from a queued message", () => {
|
||||
const uploadedImage: Extract<AgentAttachment, { type: "uploaded_file" }> = {
|
||||
type: "uploaded_file",
|
||||
id: "upload_restored",
|
||||
fileName: "photo.png",
|
||||
mimeType: "image/png",
|
||||
size: 42,
|
||||
path: "/home/user/.paseo/uploads/upload_restored/photo.png",
|
||||
role: "image",
|
||||
};
|
||||
const restoredImage: UserComposerAttachment = {
|
||||
kind: "agent_attachment",
|
||||
attachment: uploadedImage,
|
||||
};
|
||||
const restoredIssue: UserComposerAttachment = {
|
||||
kind: "agent_attachment",
|
||||
attachment: {
|
||||
type: "forge_issue",
|
||||
mimeType: "application/paseo-forge-issue",
|
||||
forge: "github",
|
||||
number: issueItem.number,
|
||||
title: issueItem.title,
|
||||
url: issueItem.url,
|
||||
},
|
||||
};
|
||||
describe("editQueuedComposerMessage", () => {
|
||||
it("returns null and leaves the queue untouched when the message id is missing", () => {
|
||||
const queue = createFakeQueue(
|
||||
new Map([["agent", [{ id: "other", text: "other", attachments: [] }]]]),
|
||||
);
|
||||
const result = editQueuedComposerMessage({ agentId: "agent", messageId: "missing", queue });
|
||||
expect(result).toBeNull();
|
||||
expect(queue.state.get("agent")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("queues the same uploaded image again without uploading it", async () => {
|
||||
const client = createFakeSendClient();
|
||||
it("returns the text and only user attachments, removing the queued entry", () => {
|
||||
const review = reviewWorkspaceAttachment("Queued snapshot.");
|
||||
const image = imageWithId("img-queued-edit");
|
||||
const queue = createFakeQueue(
|
||||
new Map([
|
||||
[
|
||||
"agent",
|
||||
[
|
||||
{
|
||||
id: "msg-1",
|
||||
text: "queued draft",
|
||||
attachments: [{ kind: "image", metadata: image }, review],
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
await enqueueComposerAgentMessage({
|
||||
client,
|
||||
agentId: "agent",
|
||||
text: "again",
|
||||
attachments: [restoredImage],
|
||||
const result = editQueuedComposerMessage({ agentId: "agent", messageId: "msg-1", queue });
|
||||
expect(result).toEqual({
|
||||
text: "queued draft",
|
||||
attachments: [{ kind: "image", metadata: image }],
|
||||
});
|
||||
|
||||
expect(client.uploadCalls).toEqual([]);
|
||||
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
|
||||
expect(queue.state.get("agent")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a sent uploaded image as an image on the optimistic message", async () => {
|
||||
const client = createFakeSendClient();
|
||||
const stream = createFakeStream();
|
||||
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
describe("sendQueuedComposerMessageNow", () => {
|
||||
it("returns missing without submitting when the message id is gone", async () => {
|
||||
const queue = createFakeQueue();
|
||||
const submitted: Array<{ text: string; attachments: ComposerAttachment[] }> = [];
|
||||
const result = await sendQueuedComposerMessageNow({
|
||||
agentId: "agent",
|
||||
text: "look",
|
||||
attachments: [restoredImage],
|
||||
submission: stream,
|
||||
});
|
||||
|
||||
const { type: _type, role: _role, ...upload } = uploadedImage;
|
||||
const shown = [...(stream.tail.get("agent") ?? []), ...(stream.head.get("agent") ?? [])];
|
||||
expect(shown).toEqual([
|
||||
expect.objectContaining({ images: [{ ...upload, storageType: "daemon-upload" }] }),
|
||||
]);
|
||||
expect(client.uploadCalls).toEqual([]);
|
||||
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
|
||||
});
|
||||
|
||||
it("counts a restored forge item as selected and toggles it off", () => {
|
||||
expect(isAttachmentSelectedForForgeItem([restoredIssue], issueItem)).toBe(true);
|
||||
expect(isAttachmentSelectedForForgeItem([restoredIssue], prItem)).toBe(false);
|
||||
expect(toggleForgeAttachment([restoredIssue], issueItem)).toEqual([]);
|
||||
});
|
||||
|
||||
it("opens the URL of a restored forge item", () => {
|
||||
const urls: string[] = [];
|
||||
openComposerAttachment({
|
||||
attachment: restoredIssue,
|
||||
setLightboxMetadata: () => {
|
||||
throw new Error("unexpected lightbox call");
|
||||
messageId: "msg-1",
|
||||
queue,
|
||||
submitMessage: async (input) => {
|
||||
submitted.push(input);
|
||||
},
|
||||
openWorkspaceAttachment: () => false,
|
||||
openExternalUrl: (url) => urls.push(url),
|
||||
});
|
||||
expect(urls).toEqual([issueItem.url]);
|
||||
expect(result).toEqual({ status: "missing" });
|
||||
expect(submitted).toEqual([]);
|
||||
});
|
||||
|
||||
it("removes the queued entry and submits its text + attachments", async () => {
|
||||
const review = reviewWorkspaceAttachment("Queued for send.");
|
||||
const queue = createFakeQueue(
|
||||
new Map([["agent", [{ id: "msg-1", text: "send me", attachments: [review] }]]]),
|
||||
);
|
||||
const submitted: Array<{ text: string; attachments: ComposerAttachment[] }> = [];
|
||||
const result = await sendQueuedComposerMessageNow({
|
||||
agentId: "agent",
|
||||
messageId: "msg-1",
|
||||
queue,
|
||||
submitMessage: async (input) => {
|
||||
submitted.push(input);
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({ status: "submitted" });
|
||||
expect(queue.state.get("agent")).toEqual([]);
|
||||
expect(submitted).toEqual([{ text: "send me", attachments: [review] }]);
|
||||
});
|
||||
|
||||
it("restores the queued entry to the front and surfaces the error message on failure", async () => {
|
||||
const queue = createFakeQueue(
|
||||
new Map([
|
||||
[
|
||||
"agent",
|
||||
[
|
||||
{ id: "msg-1", text: "first", attachments: [] },
|
||||
{ id: "msg-2", text: "second", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
const result = await sendQueuedComposerMessageNow({
|
||||
agentId: "agent",
|
||||
messageId: "msg-1",
|
||||
queue,
|
||||
submitMessage: async () => {
|
||||
throw new Error("network down");
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({ status: "failed", errorMessage: "network down" });
|
||||
const state = queue.state.get("agent");
|
||||
expect(state?.map((m) => m.id)).toEqual(["msg-1", "msg-2"]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -4,8 +4,6 @@ import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type {
|
||||
ActiveTurnBehavior,
|
||||
AgentActiveTurnBehavior,
|
||||
AgentAttachment,
|
||||
AgentSnapshotPayload,
|
||||
ForgeSearchItem,
|
||||
UploadedFileAttachment,
|
||||
@@ -17,8 +15,10 @@ import type {
|
||||
ComposerAttachment,
|
||||
UserComposerAttachment,
|
||||
} from "@/attachments/types";
|
||||
import { isWorkspaceAttachment } from "@/attachments/workspace-attachment-utils";
|
||||
import { forgeItemKey } from "@/composer/attachments/forge-item-key";
|
||||
import {
|
||||
isWorkspaceAttachment,
|
||||
userAttachmentsOnly,
|
||||
} from "@/attachments/workspace-attachment-utils";
|
||||
import {
|
||||
splitComposerAttachmentsForSubmit,
|
||||
type ComposerAttachmentSubmitFormat,
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
createPendingProviderSwitchItem,
|
||||
createUserMessage,
|
||||
generateMessageId,
|
||||
toDaemonUploadedImageAttachments,
|
||||
type ProviderSwitchItem,
|
||||
type UserMessageItem,
|
||||
} from "@/types/stream";
|
||||
@@ -35,6 +34,12 @@ import type { MessageSubmissionRejectionOutcome } from "@/composer/submission/mo
|
||||
import type { PickedImageAttachmentInput } from "@/hooks/image-attachment-picker";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
export interface QueuedComposerMessage {
|
||||
id: string;
|
||||
text: string;
|
||||
attachments: ComposerAttachment[];
|
||||
}
|
||||
|
||||
export interface AttachmentPersister {
|
||||
persistFromBlob: (input: {
|
||||
blob: Blob;
|
||||
@@ -60,7 +65,7 @@ export interface ComposerSendClient {
|
||||
text: string,
|
||||
options: {
|
||||
messageId: string;
|
||||
activeTurnBehavior?: AgentActiveTurnBehavior;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
|
||||
},
|
||||
@@ -77,7 +82,6 @@ export interface ComposerSendClient {
|
||||
messageId: string;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments?: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
|
||||
activeTurnBehavior?: "queue";
|
||||
},
|
||||
) => Promise<{ agent?: AgentSnapshotPayload }>;
|
||||
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
|
||||
@@ -102,6 +106,13 @@ export interface MessageSubmissionWriter {
|
||||
reject: (agentId: string, clientMessageId: string) => MessageSubmissionRejectionOutcome;
|
||||
}
|
||||
|
||||
export interface QueueWriter {
|
||||
read: (agentId: string) => QueuedComposerMessage[];
|
||||
write: (
|
||||
updater: (prev: Map<string, QueuedComposerMessage[]>) => Map<string, QueuedComposerMessage[]>,
|
||||
) => void;
|
||||
}
|
||||
|
||||
export async function pickAndPersistImages(input: {
|
||||
pickImages: () => Promise<PickedImageAttachmentInput[] | null>;
|
||||
persister: Pick<
|
||||
@@ -247,13 +258,12 @@ export async function dispatchComposerAgentMessage(
|
||||
});
|
||||
const clientMessageId = generateMessageId();
|
||||
const timestamp = new Date();
|
||||
const sent = separateUploadedImages(wirePayload.attachments);
|
||||
const userMessage = createUserMessage({
|
||||
clientMessageId,
|
||||
text: input.text,
|
||||
timestamp,
|
||||
images: [...wirePayload.images, ...sent.images],
|
||||
attachments: sent.attachments,
|
||||
images: wirePayload.images,
|
||||
attachments: wirePayload.attachments,
|
||||
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
|
||||
? { turnId: input.activeTurnId }
|
||||
: {}),
|
||||
@@ -265,7 +275,12 @@ export async function dispatchComposerAgentMessage(
|
||||
pendingProviderSwitch ? { providerSwitch: pendingProviderSwitch } : undefined,
|
||||
);
|
||||
try {
|
||||
const imagePayload = await prepareImagePayload(input, wirePayload.images);
|
||||
const imagePayload = input.uploadImages
|
||||
? { attachments: await input.uploadImages(wirePayload.images) }
|
||||
: await prepareImageAttachmentsForSend({
|
||||
client: input.client,
|
||||
images: wirePayload.images,
|
||||
});
|
||||
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
|
||||
const result = await input.client.switchAgentProvider(input.agentId, {
|
||||
provider: input.stagedProviderSwitch.provider,
|
||||
@@ -298,70 +313,108 @@ export async function dispatchComposerAgentMessage(
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareImagePayload(
|
||||
input: Pick<DispatchComposerAgentMessageInput, "client" | "uploadImages">,
|
||||
images: AttachmentMetadata[],
|
||||
) {
|
||||
if (input.uploadImages) return { attachments: await input.uploadImages(images) };
|
||||
return await prepareImageAttachmentsForSend({ client: input.client, images });
|
||||
export interface QueueComposerMessageInput {
|
||||
agentId: string;
|
||||
text: string;
|
||||
attachments: ComposerAttachment[];
|
||||
queue: QueueWriter;
|
||||
}
|
||||
|
||||
/** Images the host already holds render as images, the way its timeline echo does. */
|
||||
function separateUploadedImages(attachments: AgentAttachment[]) {
|
||||
const uploads: UploadedFileAttachment[] = [];
|
||||
const rest: AgentAttachment[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type === "uploaded_file" && attachment.role === "image") {
|
||||
uploads.push(attachment);
|
||||
} else {
|
||||
rest.push(attachment);
|
||||
}
|
||||
export interface QueueComposerMessageResult {
|
||||
queued: QueuedComposerMessage | null;
|
||||
}
|
||||
|
||||
export function queueComposerMessage(input: QueueComposerMessageInput): QueueComposerMessageResult {
|
||||
const trimmed = input.text.trim();
|
||||
if (!trimmed && input.attachments.length === 0) {
|
||||
return { queued: null };
|
||||
}
|
||||
const images = toDaemonUploadedImageAttachments(
|
||||
uploads.map(({ id, fileName, mimeType, size, path }) => ({
|
||||
id,
|
||||
fileName,
|
||||
mimeType,
|
||||
size,
|
||||
path,
|
||||
})),
|
||||
);
|
||||
return { images: images ?? [], attachments: rest };
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands a message to the host's queue. The timeline gets no row until the host dispatches it;
|
||||
* until then the queue track shows it. A staged provider switch goes with the message: the host
|
||||
* switches when the message's turn comes.
|
||||
*/
|
||||
export async function enqueueComposerAgentMessage(
|
||||
input: Omit<
|
||||
DispatchComposerAgentMessageInput,
|
||||
"submission" | "activeTurnBehavior" | "activeTurnId" | "onProviderSwitchCommitted"
|
||||
> & { onProviderSwitchQueued?: () => void },
|
||||
): Promise<void> {
|
||||
const text = input.text.trim();
|
||||
if (!text && input.attachments.length === 0) return;
|
||||
const wirePayload = splitComposerAttachmentsForSubmit(input.attachments, {
|
||||
format: input.attachmentSubmitFormat,
|
||||
});
|
||||
const imagePayload = await prepareImagePayload(input, wirePayload.images);
|
||||
const queued = {
|
||||
messageId: generateMessageId(),
|
||||
activeTurnBehavior: "queue" as const,
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
const item: QueuedComposerMessage = {
|
||||
id: generateMessageId(),
|
||||
text: trimmed,
|
||||
attachments: input.attachments,
|
||||
};
|
||||
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
|
||||
await input.client.switchAgentProvider(input.agentId, {
|
||||
...input.stagedProviderSwitch,
|
||||
...queued,
|
||||
text,
|
||||
input.queue.write((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(input.agentId, [...(prev.get(input.agentId) ?? []), item]);
|
||||
return next;
|
||||
});
|
||||
return { queued: item };
|
||||
}
|
||||
|
||||
export interface EditQueuedComposerMessageInput {
|
||||
agentId: string;
|
||||
messageId: string;
|
||||
queue: QueueWriter;
|
||||
}
|
||||
|
||||
export interface EditQueuedComposerMessageResult {
|
||||
text: string;
|
||||
attachments: UserComposerAttachment[];
|
||||
}
|
||||
|
||||
export function editQueuedComposerMessage(
|
||||
input: EditQueuedComposerMessageInput,
|
||||
): EditQueuedComposerMessageResult | 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 {
|
||||
text: item.text,
|
||||
attachments: userAttachmentsOnly(item.attachments),
|
||||
};
|
||||
}
|
||||
|
||||
export interface SendQueuedComposerMessageNowInput {
|
||||
agentId: string;
|
||||
messageId: string;
|
||||
queue: QueueWriter;
|
||||
submitMessage: (input: { text: string; attachments: ComposerAttachment[] }) => Promise<void>;
|
||||
failedToSendMessage?: string;
|
||||
}
|
||||
|
||||
export type SendQueuedComposerMessageNowResult =
|
||||
| { status: "missing" }
|
||||
| { status: "submitted" }
|
||||
| { status: "failed"; errorMessage: string };
|
||||
|
||||
export async function sendQueuedComposerMessageNow(
|
||||
input: SendQueuedComposerMessageNowInput,
|
||||
): Promise<SendQueuedComposerMessageNowResult> {
|
||||
const item = input.queue.read(input.agentId).find((q) => q.id === input.messageId);
|
||||
if (!item) return { status: "missing" };
|
||||
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;
|
||||
});
|
||||
try {
|
||||
await input.submitMessage({ text: item.text, attachments: item.attachments });
|
||||
return { status: "submitted" };
|
||||
} catch (error) {
|
||||
input.queue.write((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(input.agentId, [item, ...(prev.get(input.agentId) ?? [])]);
|
||||
return next;
|
||||
});
|
||||
input.onProviderSwitchQueued?.();
|
||||
return;
|
||||
return {
|
||||
status: "failed",
|
||||
errorMessage:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: (input.failedToSendMessage ?? i18n.t("composer.errors.failedToSend")),
|
||||
};
|
||||
}
|
||||
await input.client.sendAgentMessage(input.agentId, text, queued);
|
||||
}
|
||||
|
||||
export interface OpenComposerAttachmentInput {
|
||||
@@ -379,13 +432,6 @@ export function openComposerAttachment(input: OpenComposerAttachmentInput): void
|
||||
if (input.attachment.kind === "file" || input.attachment.kind === "workspace_file") {
|
||||
return;
|
||||
}
|
||||
if (input.attachment.kind === "agent_attachment") {
|
||||
// An uploaded image opens through its pill, which holds the downloaded copy.
|
||||
if ("url" in input.attachment.attachment) {
|
||||
input.openExternalUrl(input.attachment.attachment.url);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (isWorkspaceAttachment(input.attachment)) {
|
||||
input.openWorkspaceAttachment({ attachment: input.attachment });
|
||||
return;
|
||||
@@ -399,11 +445,31 @@ export function buildForgeAttachment(item: ForgeSearchItem): UserComposerAttachm
|
||||
: { kind: "forge_issue", item };
|
||||
}
|
||||
|
||||
function isForgeAttachment(
|
||||
attachment: UserComposerAttachment,
|
||||
): attachment is Extract<
|
||||
UserComposerAttachment,
|
||||
{ kind: "forge_issue" | "forge_change_request" | "github_issue" | "github_pr" }
|
||||
> {
|
||||
return (
|
||||
attachment.kind === "forge_issue" ||
|
||||
attachment.kind === "forge_change_request" ||
|
||||
// COMPAT(githubAttachmentKinds): accept legacy persisted attachment kinds
|
||||
// until 2027-01-17, when supported floors are >= v0.2.0 and old drafts no
|
||||
// longer require them.
|
||||
attachment.kind === "github_issue" ||
|
||||
attachment.kind === "github_pr"
|
||||
);
|
||||
}
|
||||
|
||||
export function toggleForgeAttachment(
|
||||
current: UserComposerAttachment[],
|
||||
item: ForgeSearchItem,
|
||||
): UserComposerAttachment[] {
|
||||
const matches = (attachment: UserComposerAttachment) => isSameForgeItem(attachment, item);
|
||||
const matches = (attachment: UserComposerAttachment) =>
|
||||
isForgeAttachment(attachment) &&
|
||||
attachment.item.kind === item.kind &&
|
||||
attachment.item.number === item.number;
|
||||
if (current.some(matches)) {
|
||||
return current.filter((attachment) => !matches(attachment));
|
||||
}
|
||||
@@ -421,7 +487,12 @@ export function toggleForgeAttachmentFromPicker({
|
||||
item,
|
||||
markForgeAttachmentRemoved,
|
||||
}: ToggleForgeAttachmentFromPickerInput): UserComposerAttachment[] {
|
||||
const existingAttachment = current.find((attachment) => isSameForgeItem(attachment, item));
|
||||
const existingAttachment = current.find(
|
||||
(attachment) =>
|
||||
isForgeAttachment(attachment) &&
|
||||
attachment.item.kind === item.kind &&
|
||||
attachment.item.number === item.number,
|
||||
);
|
||||
if (existingAttachment) {
|
||||
markForgeAttachmentRemoved(existingAttachment);
|
||||
}
|
||||
@@ -439,9 +510,10 @@ export function isAttachmentSelectedForForgeItem(
|
||||
current: readonly ComposerAttachment[],
|
||||
item: ForgeSearchItem,
|
||||
): boolean {
|
||||
return current.some((attachment) => isSameForgeItem(attachment, item));
|
||||
}
|
||||
|
||||
function isSameForgeItem(attachment: ComposerAttachment, item: ForgeSearchItem): boolean {
|
||||
return forgeItemKey(attachment) === `${item.kind}:${item.number}`;
|
||||
return userAttachmentsOnly(current).some(
|
||||
(attachment) =>
|
||||
isForgeAttachment(attachment) &&
|
||||
attachment.item.kind === item.kind &&
|
||||
attachment.item.number === item.number,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { ComposerAttachment } from "@/attachments/types";
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
|
||||
/** `issue:101` or `change_request:202` for an attachment that points at a forge item. */
|
||||
export function forgeItemKey(attachment: ComposerAttachment | undefined): string | null {
|
||||
switch (attachment?.kind) {
|
||||
case "forge_issue":
|
||||
case "forge_change_request":
|
||||
// COMPAT(githubAttachmentKinds): accept legacy persisted attachment kinds
|
||||
// until 2027-01-17, when supported floors are >= v0.2.0 and old drafts no
|
||||
// longer require them.
|
||||
case "github_issue":
|
||||
case "github_pr":
|
||||
return `${attachment.item.kind}:${attachment.item.number}`;
|
||||
case "agent_attachment":
|
||||
return agentAttachmentForgeKey(attachment.attachment);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function agentAttachmentForgeKey(attachment: AgentAttachment): string | null {
|
||||
switch (attachment.type) {
|
||||
case "forge_issue":
|
||||
case "github_issue":
|
||||
return `issue:${attachment.number}`;
|
||||
case "forge_change_request":
|
||||
case "github_pr":
|
||||
return `change_request:${attachment.number}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import { useCallback, useMemo, type ReactElement } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
AttachmentLabel,
|
||||
AttachmentPill,
|
||||
AttachmentThumbnail,
|
||||
AttachmentThumbnailPlaceholder,
|
||||
} from "@/components/attachment-pill";
|
||||
import { getAgentAttachmentPillContent } from "@/attachments/attachment-pill-content";
|
||||
import type { ComposerAttachment } from "@/attachments/types";
|
||||
import { useDaemonUploadedImage } from "@/attachments/use-daemon-uploaded-image";
|
||||
import { useHostRuntimeClient } from "@/runtime/host-runtime";
|
||||
import type { UploadedFileAttachment } from "@getpaseo/protocol/messages";
|
||||
|
||||
type RestoredAttachment = Extract<ComposerAttachment, { kind: "agent_attachment" }>;
|
||||
|
||||
interface RestoredAttachmentPillProps {
|
||||
serverId: string;
|
||||
attachment: RestoredAttachment;
|
||||
index: number;
|
||||
disabled: boolean;
|
||||
onOpen: (attachment: ComposerAttachment) => void;
|
||||
onRemove: (index: number) => void;
|
||||
openImageLabel: string;
|
||||
removeImageLabel: string;
|
||||
}
|
||||
|
||||
/** The tray pill for an attachment taken back from a queued message. */
|
||||
export function RestoredAttachmentPill(props: RestoredAttachmentPillProps): ReactElement {
|
||||
const wire = props.attachment.attachment;
|
||||
if (wire.type === "uploaded_file" && wire.role === "image") {
|
||||
return <RestoredImagePill {...props} upload={wire} />;
|
||||
}
|
||||
return <RestoredLabelPill {...props} />;
|
||||
}
|
||||
|
||||
/** An image the host holds. It is downloaded to preview it, and sent again by reference. */
|
||||
function RestoredImagePill({
|
||||
serverId,
|
||||
upload,
|
||||
index,
|
||||
disabled,
|
||||
onOpen,
|
||||
onRemove,
|
||||
openImageLabel,
|
||||
removeImageLabel,
|
||||
}: RestoredAttachmentPillProps & { upload: UploadedFileAttachment }): ReactElement {
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const image = useMemo(
|
||||
() => ({
|
||||
id: upload.id,
|
||||
fileName: upload.fileName,
|
||||
mimeType: upload.mimeType,
|
||||
size: upload.size,
|
||||
path: upload.path,
|
||||
storageType: "daemon-upload" as const,
|
||||
}),
|
||||
[upload],
|
||||
);
|
||||
const metadata = useDaemonUploadedImage({ image, client, serverId });
|
||||
const handleOpen = useCallback(() => {
|
||||
if (metadata) onOpen({ kind: "image", metadata });
|
||||
}, [metadata, onOpen]);
|
||||
const handleRemove = useCallback(() => onRemove(index), [onRemove, index]);
|
||||
return (
|
||||
<AttachmentPill
|
||||
testID="composer-image-attachment-pill"
|
||||
onOpen={handleOpen}
|
||||
onRemove={handleRemove}
|
||||
openAccessibilityLabel={openImageLabel}
|
||||
removeAccessibilityLabel={removeImageLabel}
|
||||
disabled={disabled}
|
||||
>
|
||||
{metadata ? <AttachmentThumbnail metadata={metadata} /> : <AttachmentThumbnailPlaceholder />}
|
||||
</AttachmentPill>
|
||||
);
|
||||
}
|
||||
|
||||
function RestoredLabelPill({
|
||||
attachment,
|
||||
index,
|
||||
disabled,
|
||||
onOpen,
|
||||
onRemove,
|
||||
}: RestoredAttachmentPillProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const content = getAgentAttachmentPillContent(attachment.attachment, t);
|
||||
const handleOpen = useCallback(() => onOpen(attachment), [onOpen, attachment]);
|
||||
const handleRemove = useCallback(() => onRemove(index), [onRemove, index]);
|
||||
return (
|
||||
<AttachmentPill
|
||||
testID="composer-restored-attachment-pill"
|
||||
onOpen={handleOpen}
|
||||
onRemove={handleRemove}
|
||||
openAccessibilityLabel={content.title}
|
||||
removeAccessibilityLabel={t("composer.attachments.removeAttachment")}
|
||||
disabled={disabled}
|
||||
>
|
||||
<AttachmentLabel icon={content.icon} title={content.title} subtitle={content.subtitle} />
|
||||
</AttachmentPill>
|
||||
);
|
||||
}
|
||||
@@ -55,11 +55,6 @@ export function splitComposerAttachmentsForSubmit(
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attachment.kind === "agent_attachment") {
|
||||
agentAttachments.push(attachment.attachment);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attachment.kind === "workspace_file") {
|
||||
agentAttachments.push(workspaceFileAttachmentToAgentAttachment(attachment));
|
||||
continue;
|
||||
|
||||
@@ -209,7 +209,7 @@ function useWorkspaceAttachmentBinding({
|
||||
|
||||
const completeSubmit = useCallback(
|
||||
({ result, outgoingAttachments }: CompleteSubmitInput) => {
|
||||
if (result === "submitted" || result === "queued") {
|
||||
if (result === "submitted") {
|
||||
clearSentAttachments(outgoingAttachments);
|
||||
}
|
||||
if (result === "queued" || result === "submitted" || result === "failed") {
|
||||
|
||||
@@ -82,8 +82,9 @@ function ComposerViewport({
|
||||
);
|
||||
}
|
||||
|
||||
/** Bound the complete composer slot (tracks and input) to the visible viewport capacity. */
|
||||
/** Bound the complete composer (including its controls), not just the text input. */
|
||||
function ComposerViewportContent({ style, ...props }: ViewProps) {
|
||||
const compact = useIsCompactFormFactor();
|
||||
const sizing = useContext(ViewportSizing);
|
||||
if (!sizing) throw new Error("ComposerViewportContent requires ComposerViewport");
|
||||
const constraint = useAnimatedStyle(() => ({
|
||||
@@ -92,60 +93,11 @@ function ComposerViewportContent({ style, ...props }: ViewProps) {
|
||||
// Fullscreen styles override it with a static minHeight instead of feeding the mode
|
||||
// in here: Reanimated applies a dependency change frames after the React commit,
|
||||
// so the fullscreen slot would paint clamped to the inline cap first.
|
||||
maxHeight: sizing.value?.capacity,
|
||||
}));
|
||||
|
||||
return (
|
||||
<Animated.View testID="composer-viewport-content" {...props} style={[style, constraint]} />
|
||||
);
|
||||
}
|
||||
|
||||
interface ComposerInputCapProps {
|
||||
fullscreen?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cap the inline editing box below the dock's viewport capacity so tracks above it
|
||||
* (like the queued message list) keep room instead of collapsing when an attachment pill
|
||||
* or multi-line draft grows the input.
|
||||
*/
|
||||
export function ComposerInputCap({ fullscreen = false, children }: ComposerInputCapProps) {
|
||||
const compact = useIsCompactFormFactor();
|
||||
const sizing = useContext(ViewportSizing);
|
||||
if (!sizing) {
|
||||
return (
|
||||
<View style={fullscreen ? dockStyles.fullscreenFill : dockStyles.composer}>{children}</View>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ConstrainedComposerInputCap sizing={sizing} compact={compact} fullscreen={fullscreen}>
|
||||
{children}
|
||||
</ConstrainedComposerInputCap>
|
||||
);
|
||||
}
|
||||
|
||||
function ConstrainedComposerInputCap({
|
||||
sizing,
|
||||
compact,
|
||||
fullscreen,
|
||||
children,
|
||||
}: {
|
||||
sizing: SharedValue<ComposerCapacity | undefined>;
|
||||
compact: boolean;
|
||||
fullscreen: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const constraint = useAnimatedStyle(() => ({
|
||||
maxHeight: resolveInlineComposerCapacity(sizing.value?.capacity, compact),
|
||||
}));
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
style={[fullscreen ? dockStyles.fullscreenSurface : dockStyles.composer, constraint]}
|
||||
>
|
||||
{children}
|
||||
</Animated.View>
|
||||
<Animated.View testID="composer-viewport-content" {...props} style={[style, constraint]} />
|
||||
);
|
||||
}
|
||||
|
||||
@@ -342,7 +294,6 @@ const dockStyles = StyleSheet.create({
|
||||
// Yoga applies minHeight after maxHeight, so this fills the viewport over the
|
||||
// inline cap that ComposerViewportContent keeps animating.
|
||||
fullscreenSurface: { flex: 1, minHeight: "100%" },
|
||||
fullscreenFill: { flex: 1, minHeight: 0, width: "100%" },
|
||||
centeredViewport: { flex: 1, alignItems: "center", justifyContent: "center" },
|
||||
centered: { flexShrink: 1, width: "100%" },
|
||||
// Reserve the composer's own capped height before the setup scroll view shrinks.
|
||||
|
||||
@@ -1,25 +1,14 @@
|
||||
export { ComposerDockBackground } from "./internal/background";
|
||||
export { ComposerFullscreenBody, ComposerFullscreenFooter } from "./internal/fullscreen";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useState, useCallback, useMemo, useRef, type ReactNode } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
import { resolveInlineComposerCapacity } from "./internal/capacity";
|
||||
import { useFullscreenSlotFrame } from "./internal/fullscreen";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { HEADER_INNER_HEIGHT } from "@/constants/layout";
|
||||
|
||||
const ViewportHeightContext = createContext<number | undefined>(undefined);
|
||||
|
||||
interface ComposerDockProps {
|
||||
children: [ReactNode, ReactNode, ReactNode?];
|
||||
centered?: boolean;
|
||||
@@ -32,39 +21,40 @@ export function ComposerDock({
|
||||
centered = false,
|
||||
fullscreen = false,
|
||||
}: ComposerDockProps) {
|
||||
const compact = useIsCompactFormFactor();
|
||||
const [surfaceSize, setSurfaceSize] = useState<{ width: number; height: number }>();
|
||||
const surfaceRef = useRef<View>(null);
|
||||
const fullscreenFrame = useFullscreenSlotFrame(fullscreen, surfaceRef, surfaceSize);
|
||||
const constraint = useMemo(
|
||||
() =>
|
||||
surfaceSize?.height !== undefined
|
||||
? inlineUnistylesStyle({ maxHeight: surfaceSize.height })
|
||||
: undefined,
|
||||
[surfaceSize?.height],
|
||||
() => ({ maxHeight: resolveInlineComposerCapacity(surfaceSize?.height, compact) }),
|
||||
[surfaceSize?.height, compact],
|
||||
);
|
||||
const measureViewport = useCallback((event: import("react-native").LayoutChangeEvent) => {
|
||||
const { width, height } = event.nativeEvent.layout;
|
||||
if (height > 0) setSurfaceSize({ width, height });
|
||||
}, []);
|
||||
const body = centered ? (
|
||||
<View ref={surfaceRef} style={styles.centered} onLayout={measureViewport}>
|
||||
<View style={styles.form}>
|
||||
<ScrollView style={styles.setup} keyboardShouldPersistTaps="handled">
|
||||
{content}
|
||||
</ScrollView>
|
||||
<View
|
||||
style={
|
||||
fullscreen
|
||||
? [styles.fullscreenComposer, fullscreenFrame]
|
||||
: [styles.centeredComposer, constraint]
|
||||
}
|
||||
>
|
||||
{composer}
|
||||
if (centered) {
|
||||
return (
|
||||
<View ref={surfaceRef} style={styles.centered} onLayout={measureViewport}>
|
||||
<View style={styles.form}>
|
||||
<ScrollView style={styles.setup} keyboardShouldPersistTaps="handled">
|
||||
{content}
|
||||
</ScrollView>
|
||||
<View
|
||||
style={
|
||||
fullscreen
|
||||
? [styles.fullscreenComposer, fullscreenFrame]
|
||||
: [styles.centeredComposer, constraint]
|
||||
}
|
||||
>
|
||||
{composer}
|
||||
</View>
|
||||
{overlay}
|
||||
</View>
|
||||
{overlay}
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
);
|
||||
}
|
||||
return (
|
||||
<View ref={surfaceRef} style={styles.surface} onLayout={measureViewport}>
|
||||
<View style={styles.content}>{content}</View>
|
||||
<View
|
||||
@@ -77,43 +67,12 @@ export function ComposerDock({
|
||||
{overlay}
|
||||
</View>
|
||||
);
|
||||
return (
|
||||
<ViewportHeightContext.Provider value={surfaceSize?.height}>
|
||||
{body}
|
||||
</ViewportHeightContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/** Cap the inline editing box below the viewport capacity so tracks above it keep room. */
|
||||
export function ComposerInputCap({
|
||||
fullscreen = false,
|
||||
children,
|
||||
}: {
|
||||
fullscreen?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const compact = useIsCompactFormFactor();
|
||||
const viewportHeight = useContext(ViewportHeightContext);
|
||||
const cap = useMemo(
|
||||
() =>
|
||||
!fullscreen && viewportHeight !== undefined
|
||||
? inlineUnistylesStyle({
|
||||
maxHeight: resolveInlineComposerCapacity(viewportHeight, compact),
|
||||
})
|
||||
: undefined,
|
||||
[compact, fullscreen, viewportHeight],
|
||||
);
|
||||
return (
|
||||
<View style={fullscreen ? styles.fullscreenFill : [styles.inputCap, cap]}>{children}</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
surface: { flex: 1, overflow: "hidden" },
|
||||
content: { flex: 1, justifyContent: "flex-end" },
|
||||
composer: { width: "100%", flexShrink: 1, paddingBottom: theme.spacing[4] },
|
||||
inputCap: { width: "100%", flexShrink: 1 },
|
||||
fullscreenFill: { flex: 1, minHeight: 0, width: "100%" },
|
||||
// Fixed, not absolute: a touch pan that starts inside an overflow-hidden ancestor
|
||||
// never reaches the zoomed visual viewport, while a fixed box chains to the viewport
|
||||
// directly. React Native Web renders `fixed`; React Native's style type omits it.
|
||||
|
||||
@@ -14,7 +14,6 @@ import { buildForgeSearchQueryOptions, type ForgeSearchClient } from "@/git/use-
|
||||
import { extractForgeRefs, type ForgeRef } from "@/git/forge-refs";
|
||||
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
|
||||
import { isAttachmentSelectedForForgeItem, toggleForgeAttachment } from "./actions";
|
||||
import { forgeItemKey } from "./attachments/forge-item-key";
|
||||
|
||||
const AUTO_ATTACH_DEBOUNCE_MS = 300;
|
||||
|
||||
@@ -149,7 +148,7 @@ export function useComposerForgeAutoAttach(
|
||||
]);
|
||||
|
||||
const markForgeAttachmentRemoved = useCallback((attachment: ComposerAttachment | undefined) => {
|
||||
const key = forgeItemKey(attachment);
|
||||
const key = attachmentKey(attachment);
|
||||
if (key) {
|
||||
removedRefKeysRef.current.add(key);
|
||||
}
|
||||
@@ -506,7 +505,7 @@ function isSameLookupTarget(
|
||||
}
|
||||
|
||||
function hasForgeAttachment(attachments: UserComposerAttachment[], ref: ForgeRef): boolean {
|
||||
return attachments.some((attachment) => forgeItemKey(attachment) === forgeRefKey(ref));
|
||||
return attachments.some((attachment) => attachmentKey(attachment) === forgeRefKey(ref));
|
||||
}
|
||||
|
||||
function forgeItemMatchesRef(item: ForgeSearchItem, ref: ForgeRef): boolean {
|
||||
@@ -520,3 +519,15 @@ function forgeItemKind(ref: ForgeRef): ForgeSearchItem["kind"] {
|
||||
function forgeRefKey(ref: ForgeRef): string {
|
||||
return `${forgeItemKind(ref)}:${ref.number}`;
|
||||
}
|
||||
|
||||
function attachmentKey(attachment: ComposerAttachment | undefined): string | null {
|
||||
if (
|
||||
attachment?.kind !== "forge_change_request" &&
|
||||
attachment?.kind !== "forge_issue" &&
|
||||
attachment?.kind !== "github_pr" &&
|
||||
attachment?.kind !== "github_issue"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return `${attachment.item.kind}:${attachment.item.number}`;
|
||||
}
|
||||
|
||||
+315
-184
@@ -17,17 +17,16 @@ import {
|
||||
getStagedProviderSwitch,
|
||||
isStagedProviderSwitchInFlight,
|
||||
settleCommittedProviderSwitch,
|
||||
settleStagedProviderSwitch,
|
||||
useFailedStartupSettings,
|
||||
useIsStagedProviderSwitchInFlight,
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "@/composer/provider-switch";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { resolveProviderLabel } from "@/utils/provider-definitions";
|
||||
import {
|
||||
View,
|
||||
Pressable,
|
||||
Text,
|
||||
StyleSheet as RNStyleSheet,
|
||||
type PressableStateCallbackType,
|
||||
@@ -65,7 +64,9 @@ import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
ArrowUp,
|
||||
Square,
|
||||
Pencil,
|
||||
AudioLines,
|
||||
CircleDot,
|
||||
FileText,
|
||||
@@ -105,15 +106,19 @@ import { focusWithRetries } from "@/utils/web-focus";
|
||||
import {
|
||||
cancelComposerAgent,
|
||||
dispatchComposerAgentMessage,
|
||||
enqueueComposerAgentMessage,
|
||||
editQueuedComposerMessage,
|
||||
findForgeItemByOption,
|
||||
isAttachmentSelectedForForgeItem,
|
||||
openComposerAttachment,
|
||||
pickAndPersistImages,
|
||||
queueComposerMessage,
|
||||
removeComposerAttachmentAtIndex,
|
||||
sendQueuedComposerMessageNow,
|
||||
toggleForgeAttachmentFromPicker,
|
||||
uploadFileAttachments,
|
||||
type AttachmentPersister,
|
||||
type QueueWriter,
|
||||
type QueuedComposerMessage,
|
||||
} from "@/composer/actions";
|
||||
import { useVoiceOptional } from "@/contexts/voice-context";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
@@ -173,12 +178,6 @@ import type { ComposerFocusOptions } from "@/composer/model";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { insertAtSelection } from "@/composer/insert-text";
|
||||
import { composerWorkspaceAttachment } from "@/composer/attachments/workspace";
|
||||
import { forgeItemKey } from "@/composer/attachments/forge-item-key";
|
||||
import { RestoredAttachmentPill } from "@/composer/attachments/restored-pill";
|
||||
import type { RestoredQueuedMessage } from "@/composer/queue/actions";
|
||||
import { ComposerQueueTrack } from "@/composer/queue/track";
|
||||
import { ComposerInputCap } from "@/composer/dock";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import { useWorkspaceAttachmentsForScopes } from "@/attachments/workspace-attachments-store";
|
||||
import { droppedItemsToSelectedFiles } from "@/composer/attachments/drop";
|
||||
import { getFileTypeLabel } from "@/attachments/file-types";
|
||||
@@ -221,6 +220,8 @@ const composerImageAttachmentPersister: Pick<
|
||||
persistFromFileUri: persistAttachmentFromFileUri,
|
||||
};
|
||||
|
||||
type QueuedMessage = QueuedComposerMessage;
|
||||
|
||||
type AttachmentListUpdater =
|
||||
| UserComposerAttachment[]
|
||||
| ((prev: UserComposerAttachment[]) => UserComposerAttachment[]);
|
||||
@@ -434,6 +435,34 @@ function renderAttachmentTray(args: RenderAttachmentTrayArgs): ReactElement | nu
|
||||
);
|
||||
}
|
||||
|
||||
interface RenderQueueTrackArgs {
|
||||
queuedMessages: readonly QueuedMessage[];
|
||||
handleEditQueuedMessage: (id: string) => void;
|
||||
handleSendQueuedNow: (id: string) => Promise<void>;
|
||||
editLabel: string;
|
||||
sendNowLabel: string;
|
||||
}
|
||||
|
||||
function renderQueueTrack(args: RenderQueueTrackArgs): ReactElement | null {
|
||||
const { queuedMessages, handleEditQueuedMessage, handleSendQueuedNow, editLabel, sendNowLabel } =
|
||||
args;
|
||||
if (queuedMessages.length === 0) return null;
|
||||
return (
|
||||
<View style={styles.queueTrack}>
|
||||
{queuedMessages.map((item) => (
|
||||
<QueuedMessageRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
onEdit={handleEditQueuedMessage}
|
||||
onSendNow={handleSendQueuedNow}
|
||||
editLabel={editLabel}
|
||||
sendNowLabel={sendNowLabel}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
interface RenderComposerAttachmentPillArgs {
|
||||
serverId: string;
|
||||
attachment: ComposerAttachment;
|
||||
@@ -493,22 +522,6 @@ function renderComposerAttachmentPill(args: RenderComposerAttachmentPillArgs): R
|
||||
onRemove,
|
||||
});
|
||||
}
|
||||
if (attachment.kind === "agent_attachment") {
|
||||
const wire = attachment.attachment;
|
||||
return (
|
||||
<RestoredAttachmentPill
|
||||
key={wire.type === "uploaded_file" ? wire.id : `${wire.type}:${index}`}
|
||||
serverId={args.serverId}
|
||||
attachment={attachment}
|
||||
index={index}
|
||||
disabled={disabled}
|
||||
onOpen={onOpen}
|
||||
onRemove={onRemove}
|
||||
openImageLabel={labels.openImage}
|
||||
removeImageLabel={labels.removeImage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (attachment.kind === "plugin_resource") {
|
||||
return (
|
||||
<PluginResourceAttachmentPill
|
||||
@@ -712,6 +725,54 @@ function resolveMessageInputPassthroughAction(
|
||||
}
|
||||
}
|
||||
|
||||
interface QueuedMessageRowProps {
|
||||
item: QueuedMessage;
|
||||
onEdit: (id: string) => void;
|
||||
onSendNow: (id: string) => void;
|
||||
editLabel: string;
|
||||
sendNowLabel: string;
|
||||
}
|
||||
|
||||
function QueuedMessageRow({
|
||||
item,
|
||||
onEdit,
|
||||
onSendNow,
|
||||
editLabel,
|
||||
sendNowLabel,
|
||||
}: QueuedMessageRowProps) {
|
||||
const handleEdit = useCallback(() => {
|
||||
onEdit(item.id);
|
||||
}, [onEdit, item.id]);
|
||||
const handleSendNow = useCallback(() => {
|
||||
onSendNow(item.id);
|
||||
}, [onSendNow, item.id]);
|
||||
return (
|
||||
<View style={styles.queueItem}>
|
||||
<Text style={styles.queueText} numberOfLines={2} ellipsizeMode="tail">
|
||||
{item.text}
|
||||
</Text>
|
||||
<View style={styles.queueActions}>
|
||||
<Pressable
|
||||
onPress={handleEdit}
|
||||
style={styles.queueActionButton}
|
||||
accessibilityLabel={editLabel}
|
||||
accessibilityRole="button"
|
||||
>
|
||||
<ThemedPencil size={ICON_SIZE.sm} uniProps={iconForegroundMapping} />
|
||||
</Pressable>
|
||||
<Pressable
|
||||
onPress={handleSendNow}
|
||||
style={[styles.queueActionButton, styles.queueSendButton]}
|
||||
accessibilityLabel={sendNowLabel}
|
||||
accessibilityRole="button"
|
||||
>
|
||||
<ThemedArrowUp size={ICON_SIZE.sm} uniProps={iconAccentForegroundMapping} />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
interface ImageAttachmentPillProps {
|
||||
attachment: Extract<ComposerAttachment, { kind: "image" }>;
|
||||
index: number;
|
||||
@@ -994,6 +1055,7 @@ interface ComposerProps {
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
const EMPTY_ARRAY: readonly QueuedMessage[] = [];
|
||||
const StableMessageInput = memo(MessageInput);
|
||||
|
||||
interface ComposerAutocompleteHandle {
|
||||
@@ -1336,10 +1398,6 @@ function ComposerContentImpl({
|
||||
const stagedProviderLabel = stagedSwitch
|
||||
? resolveProviderLabel(stagedSwitch.provider, providerSnapshotEntries)
|
||||
: null;
|
||||
const providerLabel = useCallback(
|
||||
(provider: string) => resolveProviderLabel(provider, providerSnapshotEntries),
|
||||
[providerSnapshotEntries],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
@@ -1355,6 +1413,7 @@ function ComposerContentImpl({
|
||||
const handleCancelStagedSwitch = useCallback(() => {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
setSendError(null);
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const handleRetryFailedStartupSettings = useCallback(() => {
|
||||
@@ -1367,6 +1426,16 @@ function ComposerContentImpl({
|
||||
void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "discard");
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const queuedMessagesRaw = useSessionStore((state) =>
|
||||
state.sessions[serverId]?.queuedMessages?.get(agentId),
|
||||
);
|
||||
const queuedSendError = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.queuedSendErrors?.get(agentId) ?? null,
|
||||
);
|
||||
const queuedMessages = queuedMessagesRaw ?? EMPTY_ARRAY;
|
||||
|
||||
const setQueuedMessages = useSessionStore((state) => state.setQueuedMessages);
|
||||
|
||||
const isCompactFormFactor = useIsCompactFormFactor();
|
||||
const isCompactLayout = resolveCompactLayout(isCompactLayoutOverride, isCompactFormFactor);
|
||||
const controlSizing = controlSizingForLayout(isCompactFormFactor);
|
||||
@@ -1384,6 +1453,7 @@ function ComposerContentImpl({
|
||||
removeAttachment,
|
||||
openAttachment,
|
||||
beginSubmit,
|
||||
clearSentAttachments,
|
||||
completeSubmit,
|
||||
resetSuppression,
|
||||
} = composerWorkspaceAttachment.useBinding({
|
||||
@@ -1731,6 +1801,7 @@ function ComposerContentImpl({
|
||||
const pendingSwitch = canSwitch ? getStagedProviderSwitch(serverId, targetAgentId) : null;
|
||||
const stagedProviderSwitch =
|
||||
pendingSwitch && pendingSwitch.provider !== liveProvider ? pendingSwitch : null;
|
||||
useSessionStore.getState().setQueuedSendError(serverId, targetAgentId, null);
|
||||
if (stagedProviderSwitch) {
|
||||
beginStagedProviderSwitch(serverId, targetAgentId);
|
||||
}
|
||||
@@ -1806,37 +1877,43 @@ function ComposerContentImpl({
|
||||
}
|
||||
return false;
|
||||
});
|
||||
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
|
||||
const supportsQueue = useHostFeature(serverId, "agentMessageQueue");
|
||||
const activeSendBehavior = resolveActiveSendBehavior(
|
||||
appSettings.sendBehavior,
|
||||
hasPendingPermission,
|
||||
supportsQueue,
|
||||
);
|
||||
const hasAgent = agentState.status !== null;
|
||||
|
||||
const enqueueMessage = useCallback(
|
||||
async (text: string, queuedAttachments: ComposerAttachment[]) => {
|
||||
if (!client) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
const targetAgentId = agentIdRef.current;
|
||||
await enqueueComposerAgentMessage({
|
||||
client,
|
||||
agentId: targetAgentId,
|
||||
text,
|
||||
const queueWriter = useMemo<QueueWriter>(
|
||||
() => ({
|
||||
read: (id) => useSessionStore.getState().sessions[serverId]?.queuedMessages?.get(id) ?? [],
|
||||
write: (updater) => setQueuedMessages(serverId, updater),
|
||||
}),
|
||||
[serverId, setQueuedMessages],
|
||||
);
|
||||
|
||||
const queueMessage = useCallback(
|
||||
(queuedMessage: string, queuedAttachments: ComposerAttachment[]) => {
|
||||
const result = queueComposerMessage({
|
||||
agentId,
|
||||
text: queuedMessage,
|
||||
attachments: queuedAttachments,
|
||||
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
|
||||
supportsForgeAttachments: supportsForgeSearch,
|
||||
}),
|
||||
stagedProviderSwitch: stagedSwitch,
|
||||
// The host owns the switch now. A choice made since then stays staged.
|
||||
onProviderSwitchQueued: () => {
|
||||
if (stagedSwitch) settleStagedProviderSwitch(serverId, targetAgentId, stagedSwitch);
|
||||
},
|
||||
queue: queueWriter,
|
||||
});
|
||||
if (!result.queued) return;
|
||||
|
||||
replaceUserInput("");
|
||||
setSelectedAttachments([]);
|
||||
resetSuppression();
|
||||
clearSentAttachments(queuedAttachments);
|
||||
},
|
||||
[client, serverId, stagedSwitch, supportsForgeSearch, t],
|
||||
[
|
||||
agentId,
|
||||
clearSentAttachments,
|
||||
queueWriter,
|
||||
resetSuppression,
|
||||
setSelectedAttachments,
|
||||
replaceUserInput,
|
||||
],
|
||||
);
|
||||
|
||||
const sendMessageWithContent = useCallback(
|
||||
@@ -1852,15 +1929,12 @@ function ComposerContentImpl({
|
||||
allowEmptySubmit,
|
||||
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
|
||||
submitBehavior,
|
||||
isAgentRunning: isAgentRunning && supportsQueue,
|
||||
isAgentRunning,
|
||||
// Parent-managed submits are still valid submit paths even when the
|
||||
// transport is disconnected, because the parent decides the failure mode.
|
||||
canSubmit: Boolean(sendAgentMessageRef.current || onSubmitMessageRef.current),
|
||||
queueMessage: async ({ message: queuedText, attachments: queuedAttachments }) => {
|
||||
if (submitBehavior !== "preserve-and-lock") {
|
||||
beginSubmit(queuedAttachments);
|
||||
}
|
||||
await enqueueMessage(queuedText, queuedAttachments);
|
||||
queueMessage: ({ message: queuedText, attachments: queuedAttachments }) => {
|
||||
queueMessage(queuedText, queuedAttachments);
|
||||
},
|
||||
submitMessage: async ({ message: submitText, attachments: submitAttachments }) => {
|
||||
if (submitBehavior !== "preserve-and-lock") {
|
||||
@@ -1890,10 +1964,9 @@ function ComposerContentImpl({
|
||||
beginSubmit,
|
||||
clearDraft,
|
||||
completeSubmit,
|
||||
enqueueMessage,
|
||||
hasExternalContent,
|
||||
isAgentRunning,
|
||||
supportsQueue,
|
||||
queueMessage,
|
||||
setSelectedAttachments,
|
||||
replaceUserInput,
|
||||
stagedSwitch,
|
||||
@@ -2141,25 +2214,39 @@ function ComposerContentImpl({
|
||||
});
|
||||
}, [agentId, hasAgent, isConnected, serverId, voice]);
|
||||
|
||||
const handleRestoreQueuedMessage = useCallback(
|
||||
(message: RestoredQueuedMessage) => {
|
||||
replaceUserInput(message.text);
|
||||
setSelectedAttachments(message.attachments);
|
||||
if (message.providerSwitch) {
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, agentId, message.providerSwitch);
|
||||
}
|
||||
focusInput();
|
||||
const handleEditQueuedMessage = useCallback(
|
||||
(id: string) => {
|
||||
const result = editQueuedComposerMessage({
|
||||
agentId,
|
||||
messageId: id,
|
||||
queue: queueWriter,
|
||||
});
|
||||
if (!result) return;
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
replaceUserInput(result.text);
|
||||
setSelectedAttachments(result.attachments);
|
||||
},
|
||||
[agentId, focusInput, replaceUserInput, serverId, setSelectedAttachments],
|
||||
[agentId, queueWriter, replaceUserInput, serverId, setSelectedAttachments],
|
||||
);
|
||||
const handleQueuedMessageAlreadySending = useCallback(() => {
|
||||
toastErrorRef.current(t("composer.queue.alreadySending"));
|
||||
}, [t]);
|
||||
const handleQueueError = useCallback(
|
||||
(error: unknown) => {
|
||||
setSendError(resolveErrorMessage(error) ?? t("composer.errors.failedToSend"));
|
||||
|
||||
const handleSendQueuedNow = useCallback(
|
||||
async (id: string) => {
|
||||
if (!sendAgentMessageRef.current && !onSubmitMessageRef.current) return;
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
// Reuse the regular send path; server-side send atomically interrupts any active run.
|
||||
const result = await sendQueuedComposerMessageNow({
|
||||
agentId,
|
||||
messageId: id,
|
||||
queue: queueWriter,
|
||||
submitMessage: ({ text, attachments: queuedAttachments }) =>
|
||||
submitMessage(text, queuedAttachments),
|
||||
failedToSendMessage: t("composer.errors.failedToSend"),
|
||||
});
|
||||
if (result.status === "failed") {
|
||||
setSendError(result.errorMessage);
|
||||
}
|
||||
},
|
||||
[t],
|
||||
[agentId, queueWriter, serverId, submitMessage, t],
|
||||
);
|
||||
|
||||
const handleQueue = useCallback(
|
||||
@@ -2178,15 +2265,15 @@ function ComposerContentImpl({
|
||||
commands: pluginClientSlashCommands,
|
||||
});
|
||||
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
|
||||
void sendMessageWithContent(payload.text, outgoingAttachments);
|
||||
queueMessage(payload.text, outgoingAttachments);
|
||||
},
|
||||
[
|
||||
attachments,
|
||||
buildOutgoingAttachments,
|
||||
pluginClientSlashCommands,
|
||||
queueMessage,
|
||||
runClientSlashCommand,
|
||||
runPluginClientSlashCommand,
|
||||
sendMessageWithContent,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2305,7 +2392,14 @@ function ComposerContentImpl({
|
||||
);
|
||||
|
||||
const hasGithubAttachment = useMemo(
|
||||
() => selectedAttachments.some((attachment) => forgeItemKey(attachment) !== null),
|
||||
() =>
|
||||
selectedAttachments.some(
|
||||
(attachment) =>
|
||||
attachment.kind === "forge_change_request" ||
|
||||
attachment.kind === "forge_issue" ||
|
||||
attachment.kind === "github_pr" ||
|
||||
attachment.kind === "github_issue",
|
||||
),
|
||||
[selectedAttachments],
|
||||
);
|
||||
// Composer stays mounted for each focused agent, so avoid a forge CLI call
|
||||
@@ -2551,6 +2645,18 @@ function ComposerContentImpl({
|
||||
],
|
||||
);
|
||||
|
||||
const queueList = useMemo(
|
||||
() =>
|
||||
renderQueueTrack({
|
||||
queuedMessages,
|
||||
handleEditQueuedMessage,
|
||||
handleSendQueuedNow,
|
||||
editLabel: t("composer.attachments.editQueuedMessage"),
|
||||
sendNowLabel: t("composer.attachments.sendQueuedMessageNow"),
|
||||
}),
|
||||
[handleEditQueuedMessage, handleSendQueuedNow, queuedMessages, t],
|
||||
);
|
||||
|
||||
const autocompleteConfiguration = useMemo(
|
||||
() => ({
|
||||
setUserInput: replaceUserInput,
|
||||
@@ -2593,7 +2699,8 @@ function ComposerContentImpl({
|
||||
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
|
||||
const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer;
|
||||
const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined;
|
||||
const displayError = externalError || sendError || failedStartupSettings?.errorMessage;
|
||||
const displayError =
|
||||
externalError || sendError || failedStartupSettings?.errorMessage || queuedSendError;
|
||||
const sendErrorNode = useMemo(
|
||||
() =>
|
||||
displayError ? (
|
||||
@@ -2664,60 +2771,6 @@ function ComposerContentImpl({
|
||||
t,
|
||||
]);
|
||||
|
||||
const messageInputNode = (
|
||||
<RenderProfile id="MessageInput">
|
||||
<StableMessageInput
|
||||
ref={messageInputRef}
|
||||
editingSession={editingSession}
|
||||
submissionError={sendErrorNode}
|
||||
value={textSource.getSnapshot()}
|
||||
onChangeText={setUserInput}
|
||||
onSubmit={handleSubmit}
|
||||
hasExternalContent={hasExternalContent}
|
||||
allowEmptySubmit={allowEmptySubmit}
|
||||
submitButtonAccessibilityLabel={submitButtonAccessibilityLabel}
|
||||
submitButtonTestID={submitButtonTestID}
|
||||
submitIcon={submitIcon}
|
||||
isSubmitDisabled={isSubmitDisabled}
|
||||
isSubmitLoading={isSubmitLoadingVisible}
|
||||
preserveHeightOnSubmit={submitBehavior === "preserve-and-lock"}
|
||||
attachments={selectedAttachments}
|
||||
cwd={cwd}
|
||||
attachmentMenuItems={attachmentMenuItems}
|
||||
onAttachButtonRef={handleAttachButtonRef}
|
||||
onAddImages={addImages}
|
||||
onPasteImages={handleNativePasteImages}
|
||||
client={client}
|
||||
isReadyForDictation={isDictationReady}
|
||||
placeholder={messagePlaceholder}
|
||||
autoFocus={messageInputAutoFocus}
|
||||
autoFocusKey={`${serverId}:${agentId}:${autoFocusKey ?? ""}`}
|
||||
disabled={isSubmitLoading}
|
||||
leftContent={leftContent}
|
||||
beforeVoiceContent={beforeVoiceContent}
|
||||
voiceModeContent={voiceModeContent}
|
||||
activeActionContent={activeActionContent}
|
||||
voiceServerId={serverId}
|
||||
voiceAgentId={agentId}
|
||||
isAgentRunning={isAgentRunning}
|
||||
defaultSendBehavior={activeSendBehavior}
|
||||
sendShortcut={appSettings.sendShortcut}
|
||||
onQueue={supportsQueue ? handleQueue : undefined}
|
||||
onSubmitLoadingPress={submitLoadingPressHandler}
|
||||
onKeyPress={handleCommandKeyPress}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
onFocusChange={handleFocusChange}
|
||||
onHeightChange={onComposerHeightChange}
|
||||
inputWrapperStyle={inputWrapperStyle}
|
||||
attachmentSlot={attachmentTray}
|
||||
inputMode={inputMode}
|
||||
readOnly={readOnly}
|
||||
textReplacement={textReplacement}
|
||||
submitLabel={submitLabel}
|
||||
/>
|
||||
</RenderProfile>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ComposerKeyboardRegistration
|
||||
@@ -2742,63 +2795,101 @@ function ComposerContentImpl({
|
||||
dataSet={isFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
|
||||
>
|
||||
<View style={inputAreaContentStyle}>
|
||||
{!isFullscreen && hasAgent && supportsQueue ? (
|
||||
<ComposerQueueTrack
|
||||
serverId={serverId}
|
||||
agentId={agentId}
|
||||
sendBehavior={appSettings.sendBehavior}
|
||||
providerLabel={providerLabel}
|
||||
onRestore={handleRestoreQueuedMessage}
|
||||
onAlreadySending={handleQueuedMessageAlreadySending}
|
||||
onError={handleQueueError}
|
||||
/>
|
||||
) : null}
|
||||
{isFullscreen ? null : queueList}
|
||||
{isFullscreen ? null : stagedSwitchBannerNode}
|
||||
{!isFullscreen && sendErrorNode}
|
||||
|
||||
<ComposerInputCap fullscreen={isFullscreen}>
|
||||
<ComposerAutocompleteBinding
|
||||
<ComposerAutocompleteBinding
|
||||
text={textSource}
|
||||
cursor={cursor}
|
||||
recall={recall}
|
||||
inputRef={messageInputRef}
|
||||
anchorStyle={messageInputContainerStyle}
|
||||
show={mode.showAutocomplete && !isFullscreen && !isComposerLocked}
|
||||
ref={autocompleteRef}
|
||||
configuration={autocompleteConfiguration}
|
||||
>
|
||||
<ComposerForgeBinding
|
||||
text={textSource}
|
||||
cursor={cursor}
|
||||
recall={recall}
|
||||
inputRef={messageInputRef}
|
||||
anchorStyle={messageInputContainerStyle}
|
||||
show={mode.showAutocomplete && !isFullscreen && !isComposerLocked}
|
||||
ref={autocompleteRef}
|
||||
configuration={autocompleteConfiguration}
|
||||
>
|
||||
<ComposerForgeBinding
|
||||
text={textSource}
|
||||
configuration={forgeConfiguration}
|
||||
ref={forgeAutoAttachRef}
|
||||
onResolvingChange={setIsForgeResolving}
|
||||
/>
|
||||
configuration={forgeConfiguration}
|
||||
ref={forgeAutoAttachRef}
|
||||
onResolvingChange={setIsForgeResolving}
|
||||
/>
|
||||
|
||||
{/* MessageInput handles everything: text, dictation, attachments, all buttons */}
|
||||
{messageInputNode}
|
||||
<Combobox
|
||||
options={githubSearchOptions}
|
||||
value=""
|
||||
onSelect={noop}
|
||||
keepOpenOnSelect
|
||||
searchable
|
||||
searchPlaceholder={t("composer.github.searchPlaceholder", {
|
||||
context: forgePresentation.changeRequestContext,
|
||||
})}
|
||||
title={t("composer.github.title", {
|
||||
context: forgePresentation.changeRequestContext,
|
||||
})}
|
||||
open={isGithubPickerOpen}
|
||||
onOpenChange={handleGithubPickerOpenChange}
|
||||
onSearchQueryChange={setGithubSearchQuery}
|
||||
desktopPlacement="top-start"
|
||||
anchorRef={attachButtonRef}
|
||||
emptyText={githubEmptyText}
|
||||
renderOption={renderGithubPickerOption}
|
||||
{/* MessageInput handles everything: text, dictation, attachments, all buttons */}
|
||||
<RenderProfile id="MessageInput">
|
||||
<StableMessageInput
|
||||
ref={messageInputRef}
|
||||
editingSession={editingSession}
|
||||
submissionError={sendErrorNode}
|
||||
value={textSource.getSnapshot()}
|
||||
onChangeText={setUserInput}
|
||||
onSubmit={handleSubmit}
|
||||
hasExternalContent={hasExternalContent}
|
||||
allowEmptySubmit={allowEmptySubmit}
|
||||
submitButtonAccessibilityLabel={submitButtonAccessibilityLabel}
|
||||
submitButtonTestID={submitButtonTestID}
|
||||
submitIcon={submitIcon}
|
||||
isSubmitDisabled={isSubmitDisabled}
|
||||
isSubmitLoading={isSubmitLoadingVisible}
|
||||
preserveHeightOnSubmit={submitBehavior === "preserve-and-lock"}
|
||||
attachments={selectedAttachments}
|
||||
cwd={cwd}
|
||||
attachmentMenuItems={attachmentMenuItems}
|
||||
onAttachButtonRef={handleAttachButtonRef}
|
||||
onAddImages={addImages}
|
||||
onPasteImages={handleNativePasteImages}
|
||||
client={client}
|
||||
isReadyForDictation={isDictationReady}
|
||||
placeholder={messagePlaceholder}
|
||||
autoFocus={messageInputAutoFocus}
|
||||
autoFocusKey={`${serverId}:${agentId}:${autoFocusKey ?? ""}`}
|
||||
disabled={isSubmitLoading}
|
||||
leftContent={leftContent}
|
||||
beforeVoiceContent={beforeVoiceContent}
|
||||
voiceModeContent={voiceModeContent}
|
||||
activeActionContent={activeActionContent}
|
||||
voiceServerId={serverId}
|
||||
voiceAgentId={agentId}
|
||||
isAgentRunning={isAgentRunning}
|
||||
defaultSendBehavior={activeSendBehavior}
|
||||
sendShortcut={appSettings.sendShortcut}
|
||||
onQueue={handleQueue}
|
||||
onSubmitLoadingPress={submitLoadingPressHandler}
|
||||
onKeyPress={handleCommandKeyPress}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
onFocusChange={handleFocusChange}
|
||||
onHeightChange={onComposerHeightChange}
|
||||
inputWrapperStyle={inputWrapperStyle}
|
||||
attachmentSlot={attachmentTray}
|
||||
inputMode={inputMode}
|
||||
readOnly={readOnly}
|
||||
textReplacement={textReplacement}
|
||||
submitLabel={submitLabel}
|
||||
/>
|
||||
{pluginAttachments.picker}
|
||||
</ComposerAutocompleteBinding>
|
||||
</ComposerInputCap>
|
||||
</RenderProfile>
|
||||
<Combobox
|
||||
options={githubSearchOptions}
|
||||
value=""
|
||||
onSelect={noop}
|
||||
keepOpenOnSelect
|
||||
searchable
|
||||
searchPlaceholder={t("composer.github.searchPlaceholder", {
|
||||
context: forgePresentation.changeRequestContext,
|
||||
})}
|
||||
title={t("composer.github.title", {
|
||||
context: forgePresentation.changeRequestContext,
|
||||
})}
|
||||
open={isGithubPickerOpen}
|
||||
onOpenChange={handleGithubPickerOpenChange}
|
||||
onSearchQueryChange={setGithubSearchQuery}
|
||||
desktopPlacement="top-start"
|
||||
anchorRef={attachButtonRef}
|
||||
emptyText={githubEmptyText}
|
||||
renderOption={renderGithubPickerOption}
|
||||
/>
|
||||
{pluginAttachments.picker}
|
||||
</ComposerAutocompleteBinding>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
@@ -2924,6 +3015,43 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
buttonDisabled: {
|
||||
opacity: 0.5,
|
||||
},
|
||||
queueTrack: {
|
||||
flexDirection: "column",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
queueItem: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
paddingVertical: theme.spacing[2],
|
||||
backgroundColor: theme.colors.surface1,
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
borderWidth: theme.borderWidth[1],
|
||||
borderColor: theme.colors.border,
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
queueText: {
|
||||
flex: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
queueActions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
queueActionButton: {
|
||||
width: 32,
|
||||
height: 32,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
queueSendButton: {
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
stagedSwitchBanner: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
@@ -2953,6 +3081,8 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
|
||||
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
|
||||
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||
const ThemedGitPullRequest = withUnistyles(GitPullRequest);
|
||||
const ThemedCircleDot = withUnistyles(CircleDot);
|
||||
const ThemedAudioLines = withUnistyles(AudioLines);
|
||||
@@ -2962,6 +3092,7 @@ const ThemedClipboardPaste = withUnistyles(ClipboardPaste);
|
||||
const ThemedFileText = withUnistyles(FileText);
|
||||
const iconForegroundMapping = (theme: Theme) => ({ color: theme.colors.foreground });
|
||||
const iconForegroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const iconAccentForegroundMapping = (theme: Theme) => ({ color: theme.colors.accentForeground });
|
||||
|
||||
function renderForgeAttachmentIcon(icon: string): ReactElement {
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import React, { act, useCallback, useMemo, useRef, useState, type FormEvent } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, it } from "vitest";
|
||||
import { useComposerHeight } from "./height.web";
|
||||
|
||||
it("keeps height measurement bounded when editing a long multiline draft", () => {
|
||||
function Composer() {
|
||||
const textarea = useRef<HTMLTextAreaElement>(null);
|
||||
const [renderedLines, setRenderedLines] = useState(1);
|
||||
const getText = useCallback(() => textarea.current?.value ?? "", []);
|
||||
const sizing = useComposerHeight({
|
||||
getText,
|
||||
textareaRef: textarea,
|
||||
minHeight: 24,
|
||||
maxHeight: 96,
|
||||
onRenderedLinesChange: setRenderedLines,
|
||||
});
|
||||
if (sizing.mode !== "measured") throw new Error("Expected web height measurement");
|
||||
|
||||
const { onTextChange } = sizing;
|
||||
const edit = useCallback(
|
||||
(event: FormEvent<HTMLTextAreaElement>) => onTextChange("", event.currentTarget.value),
|
||||
[onTextChange],
|
||||
);
|
||||
const style = useMemo(
|
||||
() => ({ height: Number(sizing.style.height), width: 400, lineHeight: "20px" }),
|
||||
[sizing.style.height],
|
||||
);
|
||||
|
||||
return (
|
||||
<textarea ref={textarea} onInput={edit} style={style} data-multiline={renderedLines > 2} />
|
||||
);
|
||||
}
|
||||
|
||||
const container = document.body.appendChild(document.createElement("div"));
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() => root.render(<Composer />));
|
||||
const editor = container.querySelector("textarea")!;
|
||||
const draft = "Review the resulting change.\n".repeat(9_000);
|
||||
|
||||
function replaceText(text: string) {
|
||||
act(() => {
|
||||
editor.value = text;
|
||||
editor.dispatchEvent(new InputEvent("input", { bubbles: true }));
|
||||
});
|
||||
}
|
||||
|
||||
replaceText(draft);
|
||||
replaceText(draft + "x");
|
||||
|
||||
expect(editor.value).toBe(draft + "x");
|
||||
expect(editor.style.height).toBe("96px");
|
||||
expect(editor.dataset.multiline).toBe("true");
|
||||
const measurement = document.querySelector<HTMLTextAreaElement>(
|
||||
'textarea[aria-hidden="true"]',
|
||||
)!;
|
||||
expect(measurement.value.length).toBeLessThan(400);
|
||||
|
||||
replaceText("Short draft");
|
||||
expect(editor.style.height).toBe("24px");
|
||||
expect(editor.dataset.multiline).toBe("false");
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
@@ -33,6 +33,15 @@ const COPIED_STYLES = [
|
||||
"paddingLeft",
|
||||
] as const;
|
||||
|
||||
function prefixThroughHardLines(text: string, lines: number): string {
|
||||
let lineEnd = -1;
|
||||
for (let line = 0; line < lines; line += 1) {
|
||||
lineEnd = text.indexOf("\n", lineEnd + 1);
|
||||
if (lineEnd === -1) return text;
|
||||
}
|
||||
return text.slice(0, lineEnd + 1);
|
||||
}
|
||||
|
||||
export function useComposerHeight({
|
||||
getText,
|
||||
textareaRef,
|
||||
@@ -68,15 +77,29 @@ export function useComposerHeight({
|
||||
mirror.style[property] = computedStyle[property];
|
||||
}
|
||||
mirror.style.width = `${sourceWidth}px`;
|
||||
mirror.value = text.endsWith("\n") ? `${text} ` : text;
|
||||
const padding =
|
||||
parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
|
||||
const lineHeight = parseFloat(computedStyle.lineHeight);
|
||||
if (lineHeight > 0)
|
||||
paramsRef.current.onRenderedLinesChange?.(
|
||||
Math.round((mirror.scrollHeight - padding) / lineHeight),
|
||||
);
|
||||
setBoundedHeight(mirror.scrollHeight);
|
||||
const { maxHeight: currentMax, onRenderedLinesChange: reportLines } = paramsRef.current;
|
||||
// Complete hard lines can prove the height cap and the three-line fullscreen threshold.
|
||||
// Keep measuring the whole draft when the prefix cannot prove both.
|
||||
const measuredText =
|
||||
Number.isFinite(currentMax) && lineHeight > 0
|
||||
? prefixThroughHardLines(
|
||||
text,
|
||||
Math.max(3, Math.ceil((currentMax - padding) / lineHeight)),
|
||||
)
|
||||
: text;
|
||||
mirror.value = measuredText.endsWith("\n") ? `${measuredText} ` : measuredText;
|
||||
let scrollHeight = mirror.scrollHeight;
|
||||
if (measuredText !== text && scrollHeight < currentMax) {
|
||||
mirror.value = text.endsWith("\n") ? `${text} ` : text;
|
||||
scrollHeight = mirror.scrollHeight;
|
||||
}
|
||||
if (lineHeight > 0) {
|
||||
reportLines?.(Math.round((scrollHeight - padding) / lineHeight));
|
||||
}
|
||||
setBoundedHeight(scrollHeight);
|
||||
},
|
||||
[setBoundedHeight, textareaRef],
|
||||
);
|
||||
|
||||
@@ -196,16 +196,9 @@ describe("dictation transcript behavior", () => {
|
||||
|
||||
describe("composer send behavior", () => {
|
||||
it("sends immediately when queue mode cannot advance past a permission", () => {
|
||||
expect(resolveActiveSendBehavior("queue", true, true)).toBe("interrupt");
|
||||
expect(resolveActiveSendBehavior("queue", false, true)).toBe("queue");
|
||||
expect(resolveActiveSendBehavior("steer", true, true)).toBe("steer");
|
||||
});
|
||||
|
||||
it("steers instead of queueing on a host without a message queue, keeping the turn", () => {
|
||||
expect(resolveActiveSendBehavior("queue", false, false)).toBe("steer");
|
||||
expect(resolveActiveSendBehavior("queue", true, false)).toBe("interrupt");
|
||||
expect(resolveActiveSendBehavior("steer", false, false)).toBe("steer");
|
||||
expect(resolveActiveSendBehavior("interrupt", false, false)).toBe("interrupt");
|
||||
expect(resolveActiveSendBehavior("queue", true)).toBe("interrupt");
|
||||
expect(resolveActiveSendBehavior("queue", false)).toBe("queue");
|
||||
expect(resolveActiveSendBehavior("steer", true)).toBe("steer");
|
||||
});
|
||||
|
||||
function actions() {
|
||||
|
||||
@@ -9,13 +9,8 @@ export type SendBehavior = ActiveTurnBehavior | "queue";
|
||||
export function resolveActiveSendBehavior(
|
||||
sendBehavior: SendBehavior,
|
||||
hasPendingPermission: boolean,
|
||||
hostHasMessageQueue: boolean,
|
||||
): SendBehavior {
|
||||
if (sendBehavior !== "queue") return sendBehavior;
|
||||
if (hasPendingPermission) return "interrupt";
|
||||
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
|
||||
// Steering keeps the running turn alive on a host that cannot hold the message.
|
||||
return hostHasMessageQueue ? "queue" : "steer";
|
||||
return sendBehavior === "queue" && hasPendingPermission ? "interrupt" : sendBehavior;
|
||||
}
|
||||
|
||||
interface ComposerSurfaceState {
|
||||
|
||||
@@ -9,7 +9,6 @@ export {
|
||||
isStagedProviderSwitchInFlight,
|
||||
settleCommittedProviderSwitch,
|
||||
settleStagedProviderSwitch,
|
||||
toStagedProviderSwitch,
|
||||
useFailedStartupSettings,
|
||||
useIsStagedProviderSwitchInFlight,
|
||||
useStagedProviderSwitch,
|
||||
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
clearStagedProviderSwitch,
|
||||
getFailedStartupSettings,
|
||||
getStagedProviderSwitch,
|
||||
settleCommittedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "./index";
|
||||
|
||||
@@ -402,115 +401,798 @@ describe("app provider switching integration", () => {
|
||||
expect(collapsed.tail.some((item) => item.kind === "provider_switch")).toBe(true);
|
||||
});
|
||||
|
||||
const sentDraft = {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3",
|
||||
thinkingOptionId: "low",
|
||||
modeId: "auto",
|
||||
providerOptions: { plan_mode: false },
|
||||
};
|
||||
it("blocks M2 drain while M1's staged provider switch is in-flight, then sends M2 normally to P2", async () => {
|
||||
const serverId = "srv_multi_queue_switch";
|
||||
let resolveSwitch!: (value: { agent: AgentSnapshotPayload }) => void;
|
||||
const switchPromise = new Promise<{ agent: AgentSnapshotPayload }>((resolve) => {
|
||||
resolveSwitch = resolve;
|
||||
});
|
||||
const switchedCalls: string[] = [];
|
||||
const sentCalls: string[] = [];
|
||||
const fakeClient = {
|
||||
switchAgentProvider: vi.fn(async (_agentId: string, opts: { text: string }) => {
|
||||
switchedCalls.push(opts.text);
|
||||
return await switchPromise;
|
||||
}),
|
||||
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
|
||||
sentCalls.push(text);
|
||||
}),
|
||||
uploadFile: vi.fn(),
|
||||
} as unknown as DaemonClient;
|
||||
|
||||
it("forwards target provider setting edits made during switch startup to the live agent", async () => {
|
||||
const serverId = "srv-startup-edits";
|
||||
const applied: unknown[] = [];
|
||||
const record =
|
||||
(setting: string) => async (_agentId: string, value: unknown, opts?: unknown) => {
|
||||
applied.push({ setting, value, opts });
|
||||
};
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", sentDraft);
|
||||
const runtime = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient,
|
||||
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
|
||||
getClientId: async () => "cid_multi_queue_switch",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(serverId, fakeClient, 1);
|
||||
useSessionStore.setState((state) => ({
|
||||
sessions: {
|
||||
...state.sessions,
|
||||
[serverId]: {
|
||||
...state.sessions[serverId]!,
|
||||
serverInfo: {
|
||||
serverId,
|
||||
hostname: "localhost",
|
||||
version: "0.18.0",
|
||||
features: { providerSwitching: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
sessionStore.setAgents(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
{
|
||||
...agentSnapshot("claude"),
|
||||
serverId,
|
||||
parentAgentId: null,
|
||||
createdAt: new Date(TS),
|
||||
updatedAt: new Date(TS),
|
||||
lastUserMessageAt: null,
|
||||
lastActivityAt: new Date(TS),
|
||||
attentionTimestamp: null,
|
||||
archivedAt: null,
|
||||
turn: { phase: "idle", cancellationRequestId: null },
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
sessionStore.setQueuedMessages(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
[
|
||||
{ id: "m1", text: "First queued switch prompt", attachments: [] },
|
||||
{ id: "m2", text: "Second queued follow-up", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
|
||||
// M1 begins switching
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(switchedCalls).toEqual(["First queued switch prompt"]);
|
||||
});
|
||||
|
||||
// Concurrent drain trigger while M1's switch is still running MUST NOT drain M2!
|
||||
sessionStore.setAgents(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
{
|
||||
...agentSnapshot("codex"),
|
||||
serverId,
|
||||
parentAgentId: null,
|
||||
createdAt: new Date(TS),
|
||||
updatedAt: new Date(TS),
|
||||
lastUserMessageAt: null,
|
||||
lastActivityAt: new Date(TS),
|
||||
attentionTimestamp: null,
|
||||
archivedAt: null,
|
||||
status: "running",
|
||||
turn: {
|
||||
phase: "open",
|
||||
turnId: "t1",
|
||||
startedAt: new Date(TS),
|
||||
cancellationRequestId: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
expect(sentCalls).toEqual([]);
|
||||
expect(switchedCalls).toHaveLength(1);
|
||||
expect(useSessionStore.getState().sessions[serverId]?.queuedMessages.get("agent-1")).toEqual([
|
||||
{ id: "m2", text: "Second queued follow-up", attachments: [] },
|
||||
]);
|
||||
|
||||
// M1 switch completes while P2 is still running -> staged switch clears, M2 stays queued until idle.
|
||||
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "running" } });
|
||||
await vi.waitFor(() => {
|
||||
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
|
||||
});
|
||||
expect(sentCalls).toEqual([]);
|
||||
|
||||
// Once P2 goes idle and triggers drain, M2 drains as a plain sendAgentMessage to Codex.
|
||||
sessionStore.setAgents(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
{
|
||||
...agentSnapshot("codex"),
|
||||
serverId,
|
||||
parentAgentId: null,
|
||||
createdAt: new Date(TS),
|
||||
updatedAt: new Date(TS),
|
||||
lastUserMessageAt: null,
|
||||
lastActivityAt: new Date(TS),
|
||||
attentionTimestamp: null,
|
||||
archivedAt: null,
|
||||
status: "idle",
|
||||
turn: { phase: "idle", cancellationRequestId: null },
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(sentCalls).toEqual(["Second queued follow-up"]);
|
||||
});
|
||||
expect(switchedCalls).toHaveLength(1);
|
||||
sessionStore.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("re-drains M2 automatically if a fast switch turn finishes before the switch RPC replies", async () => {
|
||||
const serverId = "srv-fast-queue-switch";
|
||||
const switchedCalls: string[] = [];
|
||||
const sentCalls: string[] = [];
|
||||
let resolveSwitch!: (value: { agent?: AgentSnapshotPayload }) => void;
|
||||
|
||||
const fakeClient = {
|
||||
switchAgentProvider: vi.fn(
|
||||
(_agentId: string, opts: { text: string }) =>
|
||||
new Promise<{ agent?: AgentSnapshotPayload }>((resolve) => {
|
||||
switchedCalls.push(opts.text);
|
||||
resolveSwitch = resolve;
|
||||
}),
|
||||
),
|
||||
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
|
||||
sentCalls.push(text);
|
||||
return { messageId: "m2-ack" };
|
||||
}),
|
||||
uploadFile: vi.fn(),
|
||||
} as unknown as DaemonClient;
|
||||
|
||||
const runtime = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient,
|
||||
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
|
||||
getClientId: async () => "cid_fast_queue_switch",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(serverId, fakeClient, 1);
|
||||
useSessionStore.setState((state) => ({
|
||||
sessions: {
|
||||
...state.sessions,
|
||||
[serverId]: {
|
||||
...state.sessions[serverId]!,
|
||||
serverInfo: {
|
||||
serverId,
|
||||
hostname: "localhost",
|
||||
version: "0.18.0",
|
||||
features: { providerSwitching: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
sessionStore.setAgents(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
{
|
||||
...agentSnapshot("claude"),
|
||||
serverId,
|
||||
parentAgentId: null,
|
||||
createdAt: new Date(TS),
|
||||
updatedAt: new Date(TS),
|
||||
lastUserMessageAt: null,
|
||||
lastActivityAt: new Date(TS),
|
||||
attentionTimestamp: null,
|
||||
archivedAt: null,
|
||||
status: "idle",
|
||||
turn: { phase: "idle", cancellationRequestId: null },
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
sessionStore.setQueuedMessages(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
[
|
||||
{ id: "m1", text: "Fast switch prompt", attachments: [] },
|
||||
{ id: "m2", text: "Follow-up after fast switch", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
|
||||
// M1 begins switching
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(switchedCalls).toEqual(["Fast switch prompt"]);
|
||||
});
|
||||
|
||||
// Fast provider completes M1's turn BEFORE switch RPC replies: status is idle and turn-end
|
||||
// calls drainQueuedAgentMessage while the lock is held.
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
expect(sentCalls).toEqual([]);
|
||||
|
||||
// Switch RPC replies with idle agent -> finally MUST automatically drain M2 without another trigger!
|
||||
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "idle" } });
|
||||
await vi.waitFor(() => {
|
||||
expect(sentCalls).toEqual(["Follow-up after fast switch"]);
|
||||
});
|
||||
expect(switchedCalls).toHaveLength(1);
|
||||
sessionStore.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("preserves a newer staged provider choice made while an earlier queued switch reply is pending", async () => {
|
||||
const serverId = "srv-newer-choice-queue";
|
||||
const switchedCalls: Array<{ provider: string; text: string }> = [];
|
||||
const sentCalls: string[] = [];
|
||||
let resolveFirstSwitch!: (value: { agent?: AgentSnapshotPayload }) => void;
|
||||
|
||||
const fakeClient = {
|
||||
switchAgentProvider: vi.fn((_agentId: string, opts: { provider: string; text: string }) => {
|
||||
switchedCalls.push({ provider: opts.provider, text: opts.text });
|
||||
if (switchedCalls.length === 1) {
|
||||
return new Promise<{ agent?: AgentSnapshotPayload }>((resolve) => {
|
||||
resolveFirstSwitch = resolve;
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
agent: { ...agentSnapshot(opts.provider), status: "running" },
|
||||
});
|
||||
}),
|
||||
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
|
||||
sentCalls.push(text);
|
||||
return { messageId: "unexpected-plain-send" };
|
||||
}),
|
||||
uploadFile: vi.fn(),
|
||||
} as unknown as DaemonClient;
|
||||
|
||||
const runtime = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient,
|
||||
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
|
||||
getClientId: async () => "cid_newer_choice_queue",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(serverId, fakeClient, 1);
|
||||
useSessionStore.setState((state) => ({
|
||||
sessions: {
|
||||
...state.sessions,
|
||||
[serverId]: {
|
||||
...state.sessions[serverId]!,
|
||||
serverInfo: {
|
||||
serverId,
|
||||
hostname: "localhost",
|
||||
version: "0.18.0",
|
||||
features: { providerSwitching: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
sessionStore.setAgents(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
{
|
||||
...agentSnapshot("claude"),
|
||||
serverId,
|
||||
parentAgentId: null,
|
||||
createdAt: new Date(TS),
|
||||
updatedAt: new Date(TS),
|
||||
lastUserMessageAt: null,
|
||||
lastActivityAt: new Date(TS),
|
||||
attentionTimestamp: null,
|
||||
archivedAt: null,
|
||||
status: "idle",
|
||||
turn: { phase: "idle", cancellationRequestId: null },
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
sessionStore.setQueuedMessages(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
[
|
||||
{ id: "m1", text: "First switch to Codex", attachments: [] },
|
||||
{ id: "m2", text: "Second switch to Copilot", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
|
||||
// M1 begins switching to Codex.
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(switchedCalls).toEqual([{ provider: "codex", text: "First switch to Codex" }]);
|
||||
});
|
||||
|
||||
// While Codex switch reply is still pending, user selects Copilot for the next prompt.
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
|
||||
provider: "copilot",
|
||||
model: "gpt-5",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
|
||||
// Codex switch reply arrives -> MUST NOT clear the newer Copilot draft!
|
||||
resolveFirstSwitch({ agent: { ...agentSnapshot("codex"), status: "running" } });
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
expect(getStagedProviderSwitch(serverId, "agent-1")?.provider).toBe("copilot");
|
||||
|
||||
// Once Codex goes idle and queue resumes, M2 MUST switch to Copilot (not send plainly to Codex).
|
||||
sessionStore.setAgents(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
{
|
||||
...agentSnapshot("codex"),
|
||||
serverId,
|
||||
parentAgentId: null,
|
||||
createdAt: new Date(TS),
|
||||
updatedAt: new Date(TS),
|
||||
lastUserMessageAt: null,
|
||||
lastActivityAt: new Date(TS),
|
||||
attentionTimestamp: null,
|
||||
archivedAt: null,
|
||||
status: "idle",
|
||||
turn: { phase: "idle", cancellationRequestId: null },
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(switchedCalls).toEqual([
|
||||
{ provider: "codex", text: "First switch to Codex" },
|
||||
{ provider: "copilot", text: "Second switch to Copilot" },
|
||||
]);
|
||||
});
|
||||
expect(sentCalls).toEqual([]);
|
||||
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
|
||||
sessionStore.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("forwards target provider setting edits made during switch startup to the live agent and surfaces failed automatic drain errors", async () => {
|
||||
const serverId = "srv-edited-and-failed-queue";
|
||||
let resolveSwitch!: (value: { agent?: AgentSnapshotPayload }) => void;
|
||||
const setAgentModel = vi.fn().mockResolvedValue(undefined);
|
||||
const setAgentMode = vi.fn().mockResolvedValue(null);
|
||||
const setAgentThinkingOption = vi.fn().mockResolvedValue(undefined);
|
||||
const setAgentOptions = vi.fn().mockResolvedValue(undefined);
|
||||
let failNextSwitch = false;
|
||||
|
||||
const fakeClient = {
|
||||
switchAgentProvider: vi.fn((_agentId: string, _opts: { provider: string; text: string }) => {
|
||||
if (failNextSwitch) {
|
||||
return Promise.reject(new Error("Codex CLI is not available"));
|
||||
}
|
||||
return new Promise<{ agent?: AgentSnapshotPayload }>((resolve) => {
|
||||
resolveSwitch = resolve;
|
||||
});
|
||||
}),
|
||||
sendAgentMessage: vi.fn(),
|
||||
setAgentModel,
|
||||
setAgentMode,
|
||||
setAgentThinkingOption,
|
||||
setAgentOptions,
|
||||
uploadFile: vi.fn(),
|
||||
} as unknown as DaemonClient;
|
||||
|
||||
const runtime = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient,
|
||||
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
|
||||
getClientId: async () => "cid_edited_and_failed_queue",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(serverId, fakeClient, 1);
|
||||
useSessionStore.setState((state) => ({
|
||||
sessions: {
|
||||
...state.sessions,
|
||||
[serverId]: {
|
||||
...state.sessions[serverId]!,
|
||||
serverInfo: {
|
||||
serverId,
|
||||
hostname: "localhost",
|
||||
version: "0.18.0",
|
||||
features: { providerSwitching: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
sessionStore.setAgents(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
{
|
||||
...agentSnapshot("claude"),
|
||||
serverId,
|
||||
parentAgentId: null,
|
||||
createdAt: new Date(TS),
|
||||
updatedAt: new Date(TS),
|
||||
lastUserMessageAt: null,
|
||||
lastActivityAt: new Date(TS),
|
||||
attentionTimestamp: null,
|
||||
archivedAt: null,
|
||||
status: "idle",
|
||||
turn: { phase: "idle", cancellationRequestId: null },
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
sessionStore.setQueuedMessages(
|
||||
serverId,
|
||||
new Map([["agent-1", [{ id: "m1", text: "Switch with startup edit", attachments: [] }]]]),
|
||||
);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3",
|
||||
thinkingOptionId: "low",
|
||||
modeId: "auto",
|
||||
providerOptions: { fast_mode: false },
|
||||
});
|
||||
|
||||
// 1. Pre-commit automatic drain failure restores queue item and exposes error in session store.
|
||||
failNextSwitch = true;
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
|
||||
"Codex CLI is not available",
|
||||
);
|
||||
});
|
||||
expect(useSessionStore.getState().sessions[serverId]?.queuedMessages.get("agent-1")).toEqual([
|
||||
{ id: "m1", text: "Switch with startup edit", attachments: [] },
|
||||
]);
|
||||
|
||||
// 2. Retry succeeds: while switch reply is pending, user edits Codex model/thinking/mode/options.
|
||||
failNextSwitch = false;
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(fakeClient.switchAgentProvider).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
|
||||
undefined,
|
||||
);
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
|
||||
...current,
|
||||
model: "gpt-5.4",
|
||||
modeId: "full-auto",
|
||||
thinkingOptionId: "high",
|
||||
providerOptions: { fast_mode: true },
|
||||
}));
|
||||
|
||||
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "running" } });
|
||||
await vi.waitFor(() => {
|
||||
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
|
||||
expect(setAgentModel).toHaveBeenCalledWith("agent-1", "gpt-5.4", {
|
||||
expectedProvider: "codex",
|
||||
});
|
||||
expect(setAgentMode).toHaveBeenCalledWith("agent-1", "full-auto", {
|
||||
expectedProvider: "codex",
|
||||
});
|
||||
expect(setAgentThinkingOption).toHaveBeenCalledWith("agent-1", "high", {
|
||||
expectedProvider: "codex",
|
||||
});
|
||||
expect(setAgentOptions).toHaveBeenCalledWith(
|
||||
"agent-1",
|
||||
{ fast_mode: true },
|
||||
{ expectedProvider: "codex" },
|
||||
);
|
||||
});
|
||||
|
||||
sessionStore.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("holds queued follow-up M2 until edited startup settings (including plan_mode) finish applying, and retains the draft if an edit rejects", async () => {
|
||||
const serverId = "srv-startup-edit-ordering";
|
||||
const callOrder: string[] = [];
|
||||
let resolveSwitch!: (value: { agent?: AgentSnapshotPayload }) => void;
|
||||
let resolveApplyConfig!: () => void;
|
||||
let rejectApplyConfig: ((err: Error) => void) | null = null;
|
||||
|
||||
const fakeClient = {
|
||||
switchAgentProvider: vi.fn((_agentId: string, _opts: { provider: string; text: string }) => {
|
||||
callOrder.push("switch:codex");
|
||||
return new Promise<{ agent?: AgentSnapshotPayload }>((resolve) => {
|
||||
resolveSwitch = resolve;
|
||||
});
|
||||
}),
|
||||
applyAgentConfig: vi.fn((_agentId: string, config: unknown, opts?: unknown) => {
|
||||
callOrder.push(`applyConfig:${JSON.stringify({ config, opts })}`);
|
||||
return new Promise<null>((resolve, reject) => {
|
||||
resolveApplyConfig = () => resolve(null);
|
||||
rejectApplyConfig = reject;
|
||||
});
|
||||
}),
|
||||
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
|
||||
callOrder.push(`send:${text}`);
|
||||
return { messageId: "m2-ack" };
|
||||
}),
|
||||
uploadFile: vi.fn(),
|
||||
} as unknown as DaemonClient;
|
||||
|
||||
const runtime = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient,
|
||||
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
|
||||
getClientId: async () => "cid_startup_edit_ordering",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(serverId, fakeClient, 1);
|
||||
useSessionStore.setState((state) => ({
|
||||
sessions: {
|
||||
...state.sessions,
|
||||
[serverId]: {
|
||||
...state.sessions[serverId]!,
|
||||
serverInfo: {
|
||||
serverId,
|
||||
hostname: "localhost",
|
||||
version: "0.18.0",
|
||||
features: { providerSwitching: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
sessionStore.setAgents(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
{
|
||||
...agentSnapshot("claude"),
|
||||
serverId,
|
||||
parentAgentId: null,
|
||||
createdAt: new Date(TS),
|
||||
updatedAt: new Date(TS),
|
||||
lastUserMessageAt: null,
|
||||
lastActivityAt: new Date(TS),
|
||||
attentionTimestamp: null,
|
||||
archivedAt: null,
|
||||
status: "idle",
|
||||
turn: { phase: "idle", cancellationRequestId: null },
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
sessionStore.setQueuedMessages(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
[
|
||||
{ id: "m1", text: "First prompt", attachments: [] },
|
||||
{ id: "m2", text: "Follow-up in Plan mode", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: { plan_mode: false },
|
||||
});
|
||||
|
||||
// M1 starts switching; while Codex opens, user changes model AND enables plan_mode.
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toEqual(["switch:codex"]);
|
||||
});
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
|
||||
...current,
|
||||
model: "gpt-5.4",
|
||||
providerOptions: { plan_mode: true },
|
||||
}));
|
||||
|
||||
const settled = await settleCommittedProviderSwitch({
|
||||
serverId,
|
||||
agentId: "agent-1",
|
||||
sentDraft,
|
||||
committedProvider: "codex",
|
||||
client: {
|
||||
setAgentModel: record("model"),
|
||||
setAgentMode: record("mode"),
|
||||
setAgentThinkingOption: record("thinking"),
|
||||
setAgentOptions: record("options"),
|
||||
},
|
||||
});
|
||||
// Fast turn finishes idle and triggers queue drain BEFORE switch + settings edits complete.
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "idle" } });
|
||||
|
||||
const opts = { expectedProvider: "codex" };
|
||||
expect(settled).toEqual({ applied: true });
|
||||
expect(applied).toEqual([
|
||||
{ setting: "model", value: "gpt-5.4", opts },
|
||||
{ setting: "mode", value: "full-auto", opts },
|
||||
{ setting: "thinking", value: "high", opts },
|
||||
{ setting: "options", value: { plan_mode: true }, opts },
|
||||
]);
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toHaveLength(2);
|
||||
});
|
||||
// M2 MUST NOT have sent yet while applyAgentConfig (model + plan_mode: true) is still pending!
|
||||
expect(callOrder.some((entry) => entry.startsWith("send:"))).toBe(false);
|
||||
|
||||
// Once applyAgentConfig completes, M2 drains strictly AFTER plan_mode: true took effect!
|
||||
resolveApplyConfig();
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toHaveLength(3);
|
||||
});
|
||||
expect(callOrder[1]).toContain('"plan_mode":true');
|
||||
expect(callOrder[1]).toContain('"modelId":"gpt-5.4"');
|
||||
expect(callOrder[1]).toContain('"expectedProvider":"codex"');
|
||||
expect(callOrder[2]).toBe("send:Follow-up in Plan mode");
|
||||
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps rejected startup settings until the user retries or dismisses them", async () => {
|
||||
const serverId = "srv-rejected-startup-edits";
|
||||
const configs: unknown[] = [];
|
||||
let rejection: Error | null = new Error("Plan mode rejected by provider");
|
||||
const client = {
|
||||
applyAgentConfig: async (_agentId: string, config: unknown, opts?: unknown) => {
|
||||
configs.push({ config, opts });
|
||||
if (rejection) throw rejection;
|
||||
return null;
|
||||
},
|
||||
} as unknown as DaemonClient;
|
||||
const runtime = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => client,
|
||||
connectToDaemon: async () => ({ client, serverId, hostname: null }),
|
||||
getClientId: async () => "cid_rejected_startup_edits",
|
||||
},
|
||||
// Case 2: If daemon rejects the edited settings, draft is RETAINED, error is surfaced, and M2 is HELD.
|
||||
callOrder.length = 0;
|
||||
sessionStore.setQueuedMessages(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
[
|
||||
{ id: "m3", text: "Switch with rejected edit", attachments: [] },
|
||||
{ id: "m4", text: "Must stay queued", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: { plan_mode: false },
|
||||
});
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toEqual(["switch:codex"]);
|
||||
});
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
|
||||
...current,
|
||||
providerOptions: { plan_mode: true },
|
||||
}));
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "idle" } });
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toHaveLength(2);
|
||||
});
|
||||
useSessionStore.getState().initializeSession(serverId, client, 1);
|
||||
const rejectEdit = async () => {
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", sentDraft);
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
|
||||
...current,
|
||||
providerOptions: { plan_mode: true },
|
||||
}));
|
||||
return await settleCommittedProviderSwitch({
|
||||
serverId,
|
||||
agentId: "agent-1",
|
||||
sentDraft,
|
||||
committedProvider: "codex",
|
||||
client,
|
||||
});
|
||||
};
|
||||
|
||||
expect(await rejectEdit()).toEqual({
|
||||
applied: false,
|
||||
errorMessage: "Plan mode rejected by provider",
|
||||
rejectApplyConfig!(new Error("Plan mode rejected by provider"));
|
||||
await vi.waitFor(() => {
|
||||
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
|
||||
"Plan mode rejected by provider",
|
||||
);
|
||||
});
|
||||
// The model picker clears the staged draft on a live change. The failure stays.
|
||||
clearStagedProviderSwitch(serverId, "agent-1");
|
||||
expect(getFailedStartupSettings(serverId, "agent-1")?.bundle).toEqual({
|
||||
options: { plan_mode: true },
|
||||
});
|
||||
|
||||
rejection = null;
|
||||
expect(await runtime.recoverFailedStartupSettings(serverId, "agent-1", "retry")).toBe(true);
|
||||
expect(configs).toEqual(
|
||||
Array(2).fill({
|
||||
config: { options: { plan_mode: true } },
|
||||
opts: { expectedProvider: "codex" },
|
||||
}),
|
||||
// Ordinary draft actions (like the model picker calling clearStagedProviderSwitch on a live
|
||||
// Codex model change) and later drain callbacks MUST leave failedStartupSettings and the queue
|
||||
// hold intact until the user explicitly chooses Retry or Dismiss!
|
||||
clearStagedProviderSwitch(serverId, "agent-1");
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
|
||||
"Plan mode rejected by provider",
|
||||
);
|
||||
expect(getFailedStartupSettings(serverId, "agent-1")?.bundle).toEqual({
|
||||
options: { plan_mode: true },
|
||||
});
|
||||
expect(callOrder.some((entry) => entry.startsWith("send:"))).toBe(false);
|
||||
expect(useSessionStore.getState().sessions[serverId]?.queuedMessages.get("agent-1")).toEqual([
|
||||
{ id: "m4", text: "Must stay queued", attachments: [] },
|
||||
]);
|
||||
|
||||
// Retrying via the single recovery action re-applies the exact failed bundle (plan_mode: true)
|
||||
// and automatically resumes the idle queue strictly AFTER the retry succeeds!
|
||||
const retryPromise = runtime.recoverFailedStartupSettings(serverId, "agent-1", "retry");
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toHaveLength(3);
|
||||
});
|
||||
expect(callOrder[2]).toContain('"plan_mode":true');
|
||||
// Still waiting for applyAgentConfig response -> M4 MUST NOT send yet!
|
||||
expect(callOrder.some((entry) => entry.startsWith("send:"))).toBe(false);
|
||||
resolveApplyConfig();
|
||||
expect(await retryPromise).toBe(true);
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toContain("send:Must stay queued");
|
||||
});
|
||||
expect(getFailedStartupSettings(serverId, "agent-1")).toBeNull();
|
||||
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
|
||||
undefined,
|
||||
);
|
||||
|
||||
// Case 3: Explicit discard clears the failed settings and resumes an idle queue immediately.
|
||||
callOrder.length = 0;
|
||||
sessionStore.setQueuedMessages(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
[
|
||||
{ id: "m5", text: "Switch with discarded edit", attachments: [] },
|
||||
{ id: "m6", text: "Send after explicit discard", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: { plan_mode: false },
|
||||
});
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toEqual(["switch:codex"]);
|
||||
});
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
|
||||
...current,
|
||||
providerOptions: { plan_mode: true },
|
||||
}));
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "idle" } });
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toHaveLength(2);
|
||||
});
|
||||
rejectApplyConfig!(new Error("Disconnected"));
|
||||
await vi.waitFor(() => {
|
||||
expect(getFailedStartupSettings(serverId, "agent-1")?.errorMessage).toBe("Disconnected");
|
||||
});
|
||||
expect(callOrder.some((entry) => entry.startsWith("send:"))).toBe(false);
|
||||
|
||||
rejection = new Error("Disconnected");
|
||||
await rejectEdit();
|
||||
expect(await runtime.recoverFailedStartupSettings(serverId, "agent-1", "discard")).toBe(true);
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toContain("send:Send after explicit discard");
|
||||
});
|
||||
expect(getFailedStartupSettings(serverId, "agent-1")).toBeNull();
|
||||
expect(configs).toHaveLength(3);
|
||||
|
||||
useSessionStore.getState().clearSession(serverId);
|
||||
sessionStore.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("places optimistic switch marker above submitted message, upgrades in place on commit, and handles failure and cache cleanly", async () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { create } from "zustand";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentConfigApply, QueuedProviderSwitch } from "@getpaseo/protocol/messages";
|
||||
import type { AgentConfigApply } from "@getpaseo/protocol/messages";
|
||||
|
||||
export interface StagedProviderSwitch {
|
||||
provider: AgentProvider;
|
||||
@@ -187,17 +187,6 @@ export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((s
|
||||
}),
|
||||
}));
|
||||
|
||||
/** A switch the host holds in its queue, as the composer stages it. */
|
||||
export function toStagedProviderSwitch(queued: QueuedProviderSwitch): StagedProviderSwitch {
|
||||
return {
|
||||
provider: queued.provider,
|
||||
model: queued.model ?? null,
|
||||
modeId: queued.modeId ?? null,
|
||||
thinkingOptionId: queued.thinkingOptionId ?? null,
|
||||
providerOptions: queued.providerOptions ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
export function getStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
import type { PaseoAgentQueueItem, PaseoAgentQueueWithdrawResult } from "@getpaseo/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createAgentQueueModel, type AgentQueuePort } from "@/agent-queue/model";
|
||||
import { cancelQueuedMessage, editQueuedMessage, sendQueuedMessageNow } from "./actions";
|
||||
|
||||
const upload = {
|
||||
type: "uploaded_file" as const,
|
||||
id: "upload-1",
|
||||
fileName: "photo.png",
|
||||
mimeType: "image/png",
|
||||
size: 1,
|
||||
path: "/tmp/photo.png",
|
||||
role: "image" as const,
|
||||
};
|
||||
|
||||
const queued: PaseoAgentQueueItem = {
|
||||
id: "a",
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T00:00:00.000Z",
|
||||
text: "look at this",
|
||||
attachments: [upload],
|
||||
sender: { kind: "user" },
|
||||
held: false,
|
||||
state: "queued",
|
||||
};
|
||||
|
||||
/** A real queue model over a host that already holds one message. */
|
||||
async function queueHolding(withdraw: PaseoAgentQueueWithdrawResult) {
|
||||
const promoted: string[] = [];
|
||||
const port: AgentQueuePort = {
|
||||
list: async () => ({ held: false, items: [queued] }),
|
||||
withdraw: async () => withdraw,
|
||||
promote: async (messageId, behavior) => {
|
||||
promoted.push(`${messageId}:${behavior}`);
|
||||
return { promoted: true };
|
||||
},
|
||||
observe: ({ update }) => {
|
||||
update({ held: false, items: [queued] });
|
||||
return () => {};
|
||||
},
|
||||
};
|
||||
const model = createAgentQueueModel(port);
|
||||
model.subscribe(() => {});
|
||||
|
||||
const restored: Array<{ text: string; attachments: unknown[] }> = [];
|
||||
let alreadySending = 0;
|
||||
return {
|
||||
model,
|
||||
promoted,
|
||||
restored,
|
||||
alreadySendingCount: () => alreadySending,
|
||||
composer: {
|
||||
restore: (message: { text: string; attachments: unknown[] }) => restored.push(message),
|
||||
alreadySending: () => {
|
||||
alreadySending += 1;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const withdrawn: PaseoAgentQueueWithdrawResult = { withdrawn: true, item: queued };
|
||||
|
||||
const dispatching: PaseoAgentQueueWithdrawResult = {
|
||||
withdrawn: false,
|
||||
reason: "already_dispatching",
|
||||
};
|
||||
|
||||
describe("editQueuedMessage", () => {
|
||||
it("puts the withdrawn text and attachments back in the composer", async () => {
|
||||
const queue = await queueHolding(withdrawn);
|
||||
|
||||
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
|
||||
|
||||
expect(queue.restored).toEqual([
|
||||
{
|
||||
text: "look at this",
|
||||
attachments: [{ kind: "agent_attachment", attachment: upload }],
|
||||
providerSwitch: null,
|
||||
},
|
||||
]);
|
||||
expect(queue.alreadySendingCount()).toBe(0);
|
||||
expect(queue.model.getSnapshot().items).toEqual([]);
|
||||
});
|
||||
|
||||
it("gives back the provider switch the message was queued with", async () => {
|
||||
const queue = await queueHolding({
|
||||
withdrawn: true,
|
||||
item: { ...queued, providerSwitch: { provider: "codex", model: "gpt-5.4" } },
|
||||
});
|
||||
|
||||
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
|
||||
|
||||
expect(queue.restored).toMatchObject([
|
||||
{
|
||||
providerSwitch: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
modeId: null,
|
||||
thinkingOptionId: null,
|
||||
providerOptions: {},
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves the composer alone when the message already started sending", async () => {
|
||||
const queue = await queueHolding(dispatching);
|
||||
|
||||
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
|
||||
|
||||
expect(queue.restored).toEqual([]);
|
||||
expect(queue.alreadySendingCount()).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cancelQueuedMessage", () => {
|
||||
it("withdraws the message without touching the composer", async () => {
|
||||
const queue = await queueHolding(withdrawn);
|
||||
|
||||
await cancelQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
|
||||
|
||||
expect(queue.model.getSnapshot().items).toEqual([]);
|
||||
expect(queue.restored).toEqual([]);
|
||||
expect(queue.alreadySendingCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("says so when the message already started sending", async () => {
|
||||
const queue = await queueHolding(dispatching);
|
||||
|
||||
await cancelQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
|
||||
|
||||
expect(queue.alreadySendingCount()).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendQueuedMessageNow", () => {
|
||||
it.each([
|
||||
["steer", "a:steer"],
|
||||
["interrupt", "a:interrupt"],
|
||||
["queue", "a:interrupt"],
|
||||
] as const)("with the %s send behavior promotes as %s", async (sendBehavior, expected) => {
|
||||
const queue = await queueHolding(withdrawn);
|
||||
|
||||
await sendQueuedMessageNow({ model: queue.model, messageId: "a", sendBehavior });
|
||||
|
||||
expect(queue.promoted).toEqual([expected]);
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
import type { AgentQueueModel } from "@/agent-queue";
|
||||
import type { UserComposerAttachment } from "@/attachments/types";
|
||||
import type { SendBehavior } from "@/composer/input/state";
|
||||
import { toStagedProviderSwitch, type StagedProviderSwitch } from "@/composer/provider-switch";
|
||||
|
||||
export interface RestoredQueuedMessage {
|
||||
text: string;
|
||||
attachments: UserComposerAttachment[];
|
||||
/** The switch the message was queued with, to stage again. */
|
||||
providerSwitch: StagedProviderSwitch | null;
|
||||
}
|
||||
|
||||
interface WithdrawInput {
|
||||
model: Pick<AgentQueueModel, "withdraw">;
|
||||
messageId: string;
|
||||
/** The message left the queue before the host got the request. */
|
||||
alreadySending: () => void;
|
||||
}
|
||||
|
||||
/** Moves a queued message back into the composer. Only the host can say it is still queued. */
|
||||
export async function editQueuedMessage(
|
||||
input: WithdrawInput & { restore: (message: RestoredQueuedMessage) => void },
|
||||
): Promise<void> {
|
||||
const result = await input.model.withdraw(input.messageId);
|
||||
if (!result) return;
|
||||
if (!result.withdrawn) {
|
||||
input.alreadySending();
|
||||
return;
|
||||
}
|
||||
input.restore({
|
||||
text: result.item.text,
|
||||
attachments: (result.item.attachments ?? []).map((attachment) => ({
|
||||
kind: "agent_attachment",
|
||||
attachment,
|
||||
})),
|
||||
providerSwitch: result.item.providerSwitch
|
||||
? toStagedProviderSwitch(result.item.providerSwitch)
|
||||
: null,
|
||||
});
|
||||
}
|
||||
|
||||
export async function cancelQueuedMessage(input: WithdrawInput): Promise<void> {
|
||||
const result = await input.model.withdraw(input.messageId);
|
||||
if (result && !result.withdrawn) input.alreadySending();
|
||||
}
|
||||
|
||||
export async function sendQueuedMessageNow(input: {
|
||||
model: Pick<AgentQueueModel, "promote">;
|
||||
messageId: string;
|
||||
sendBehavior: SendBehavior;
|
||||
}): Promise<void> {
|
||||
await input.model.promote(
|
||||
input.messageId,
|
||||
input.sendBehavior === "steer" ? "steer" : "interrupt",
|
||||
);
|
||||
}
|
||||
@@ -1,334 +0,0 @@
|
||||
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
ArrowUp,
|
||||
Bot,
|
||||
GitPullRequest,
|
||||
Paperclip,
|
||||
Pause,
|
||||
Pencil,
|
||||
X,
|
||||
} from "lucide-react-native";
|
||||
import type { PaseoAgentQueueItem } from "@getpaseo/client";
|
||||
import { useAgentQueue } from "@/agent-queue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-button-chrome";
|
||||
import { paneContentToolbarIconSize, ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import type { SendBehavior } from "@/composer/input/state";
|
||||
import { COMPOSER_PADDING_HORIZONTAL } from "@/composer/input/toolbar-rails";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import {
|
||||
cancelQueuedMessage,
|
||||
editQueuedMessage,
|
||||
sendQueuedMessageNow,
|
||||
type RestoredQueuedMessage,
|
||||
} from "./actions";
|
||||
import { presentQueue, type QueueRowView } from "./view";
|
||||
|
||||
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
|
||||
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||
const ThemedBot = withUnistyles(Bot);
|
||||
const ThemedGitPullRequest = withUnistyles(GitPullRequest);
|
||||
const ThemedPaperclip = withUnistyles(Paperclip);
|
||||
const ThemedPause = withUnistyles(Pause);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedX = withUnistyles(X);
|
||||
|
||||
/** A few rows and the top of the next, so a longer queue reads as scrollable. */
|
||||
const QUEUE_MAX_HEIGHT = 240;
|
||||
/** Keep ~2 rows readable on phones without crowding the conversation or composer. */
|
||||
const QUEUE_MAX_HEIGHT_COMPACT = 140;
|
||||
|
||||
interface ComposerQueueTrackProps {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
/** The user's send behavior setting. Send now steers or interrupts accordingly. */
|
||||
sendBehavior: SendBehavior;
|
||||
providerLabel: (provider: string) => string;
|
||||
onRestore: (message: RestoredQueuedMessage) => void;
|
||||
onAlreadySending: () => void;
|
||||
onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** The messages the host holds for this agent, in the order it will send them. */
|
||||
export function ComposerQueueTrack({
|
||||
serverId,
|
||||
agentId,
|
||||
sendBehavior,
|
||||
providerLabel,
|
||||
onRestore,
|
||||
onAlreadySending,
|
||||
onError,
|
||||
}: ComposerQueueTrackProps): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const { model, queue } = useAgentQueue(serverId, agentId);
|
||||
const titles = useSessionStore(useShallow(selectSenderTitles(queue.items, serverId)));
|
||||
const view = useMemo(
|
||||
() =>
|
||||
presentQueue(queue, {
|
||||
t,
|
||||
agentTitle: (senderId) => titles[senderId] ?? null,
|
||||
providerLabel,
|
||||
}),
|
||||
[providerLabel, queue, t, titles],
|
||||
);
|
||||
|
||||
const handleEdit = useCallback(
|
||||
(messageId: string) => {
|
||||
editQueuedMessage({
|
||||
model,
|
||||
messageId,
|
||||
restore: onRestore,
|
||||
alreadySending: onAlreadySending,
|
||||
}).catch(onError);
|
||||
},
|
||||
[model, onRestore, onAlreadySending, onError],
|
||||
);
|
||||
const handleCancel = useCallback(
|
||||
(messageId: string) => {
|
||||
cancelQueuedMessage({ model, messageId, alreadySending: onAlreadySending }).catch(onError);
|
||||
},
|
||||
[model, onAlreadySending, onError],
|
||||
);
|
||||
const handleSendNow = useCallback(
|
||||
(messageId: string) => {
|
||||
sendQueuedMessageNow({ model, messageId, sendBehavior }).catch(onError);
|
||||
},
|
||||
[model, sendBehavior, onError],
|
||||
);
|
||||
|
||||
const failedToLoad = queue.status === "error";
|
||||
if (view.rows.length === 0 && !failedToLoad) return null;
|
||||
|
||||
return (
|
||||
<View style={styles.track}>
|
||||
{failedToLoad ? (
|
||||
<View style={styles.status}>
|
||||
<Text style={styles.muted}>{t("composer.queue.loadFailed")}</Text>
|
||||
<Button variant="ghost" size="sm" onPress={model.retry}>
|
||||
{t("composer.queue.retry")}
|
||||
</Button>
|
||||
</View>
|
||||
) : null}
|
||||
{view.notice ? (
|
||||
<View style={styles.status}>
|
||||
<LineIcon>
|
||||
<ThemedPause size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
</LineIcon>
|
||||
<Text style={styles.muted}>{view.notice}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{/* The frame sizes the list: a style on this ScrollView is dropped on web. */}
|
||||
<View style={[styles.rowsFrame, isCompact && styles.rowsFrameCompact]}>
|
||||
<ScrollView keyboardShouldPersistTaps="handled" nestedScrollEnabled>
|
||||
<View style={styles.rows} role="list" aria-label={t("composer.queue.title")}>
|
||||
{view.rows.map((row) => (
|
||||
<QueueRow
|
||||
key={row.id}
|
||||
row={row}
|
||||
onEdit={handleEdit}
|
||||
onCancel={handleCancel}
|
||||
onSendNow={handleSendNow}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** An icon beside text that truncates keeps its size; the text gives up the width. */
|
||||
function LineIcon({ children }: { children: ReactNode }): ReactElement {
|
||||
return <View style={styles.lineIcon}>{children}</View>;
|
||||
}
|
||||
|
||||
function selectSenderTitles(items: PaseoAgentQueueItem[], hostId: string) {
|
||||
return (state: ReturnType<typeof useSessionStore.getState>): Record<string, string> => {
|
||||
const titles: Record<string, string> = {};
|
||||
for (const { sender } of items) {
|
||||
if (sender.kind !== "agent_message" && sender.kind !== "agent_notification") continue;
|
||||
const session = state.sessions[sender.serverId ?? hostId];
|
||||
const agent =
|
||||
session?.agents.get(sender.agentId) ?? session?.agentDetails.get(sender.agentId);
|
||||
if (agent?.title) titles[sender.agentId] = agent.title;
|
||||
}
|
||||
return titles;
|
||||
};
|
||||
}
|
||||
|
||||
function QueueRow({
|
||||
row,
|
||||
onEdit,
|
||||
onCancel,
|
||||
onSendNow,
|
||||
}: {
|
||||
row: QueueRowView;
|
||||
onEdit: (messageId: string) => void;
|
||||
onCancel: (messageId: string) => void;
|
||||
onSendNow: (messageId: string) => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const iconSize = paneContentToolbarIconSize(isCompact);
|
||||
const handleEdit = useCallback(() => onEdit(row.id), [onEdit, row.id]);
|
||||
const handleCancel = useCallback(() => onCancel(row.id), [onCancel, row.id]);
|
||||
const handleSendNow = useCallback(() => onSendNow(row.id), [onSendNow, row.id]);
|
||||
|
||||
return (
|
||||
<View style={styles.row} role="listitem">
|
||||
<View style={styles.body}>
|
||||
{row.label ? (
|
||||
<View style={styles.meta}>
|
||||
<LineIcon>
|
||||
{row.icon === "change_request" ? (
|
||||
<ThemedGitPullRequest size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
) : (
|
||||
<ThemedBot size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
)}
|
||||
</LineIcon>
|
||||
<Text style={styles.metaText} numberOfLines={1}>
|
||||
{row.label}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{row.preview ? (
|
||||
<Text style={styles.preview} numberOfLines={2} ellipsizeMode="tail">
|
||||
{row.preview}
|
||||
</Text>
|
||||
) : null}
|
||||
{row.attachmentLabel ? (
|
||||
<View style={styles.meta}>
|
||||
<LineIcon>
|
||||
<ThemedPaperclip size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
</LineIcon>
|
||||
<Text style={styles.metaText}>{row.attachmentLabel}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{row.switchLabel ? (
|
||||
<View style={styles.meta}>
|
||||
<LineIcon>
|
||||
<ThemedArrowRightLeft size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
</LineIcon>
|
||||
<Text style={styles.metaText} numberOfLines={1}>
|
||||
{row.switchLabel}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
<View style={styles.actions}>
|
||||
{row.canEdit ? (
|
||||
<ToolbarButton
|
||||
label={t("composer.queue.edit")}
|
||||
tooltipSide="top"
|
||||
compact={isCompact}
|
||||
disabled={row.disabled}
|
||||
onPress={handleEdit}
|
||||
>
|
||||
<ThemedPencil size={iconSize} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
) : null}
|
||||
<ToolbarButton
|
||||
label={t("composer.queue.sendNow")}
|
||||
tooltipSide="top"
|
||||
compact={isCompact}
|
||||
disabled={row.disabled}
|
||||
onPress={handleSendNow}
|
||||
>
|
||||
<ThemedArrowUp size={iconSize} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
label={t("composer.queue.cancel")}
|
||||
tooltipSide="top"
|
||||
compact={isCompact}
|
||||
disabled={row.disabled}
|
||||
onPress={handleCancel}
|
||||
>
|
||||
<ThemedX size={iconSize} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
// The composer's height is capped. When it runs out, the queue gives up height and its rows
|
||||
// scroll before the message input shrinks.
|
||||
track: {
|
||||
flexShrink: 1000,
|
||||
minHeight: 0,
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
// Rows put their text on the composer's text rail: the same border, then the same padding.
|
||||
// The status line carries a clear border to land there too.
|
||||
status: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
paddingHorizontal: COMPOSER_PADDING_HORIZONTAL,
|
||||
borderLeftWidth: theme.borderWidth[1],
|
||||
borderColor: "transparent",
|
||||
},
|
||||
muted: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
rowsFrame: {
|
||||
flexShrink: 1,
|
||||
minHeight: 0,
|
||||
maxHeight: QUEUE_MAX_HEIGHT,
|
||||
},
|
||||
rowsFrameCompact: {
|
||||
maxHeight: QUEUE_MAX_HEIGHT_COMPACT,
|
||||
},
|
||||
rows: {
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
paddingLeft: COMPOSER_PADDING_HORIZONTAL,
|
||||
paddingRight: theme.spacing[2],
|
||||
paddingVertical: theme.spacing[2],
|
||||
backgroundColor: theme.colors.surface1,
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
borderWidth: theme.borderWidth[1],
|
||||
borderColor: theme.colors.border,
|
||||
},
|
||||
body: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
meta: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
lineIcon: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
metaText: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
preview: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
}));
|
||||
@@ -1,156 +0,0 @@
|
||||
import type { PaseoAgentQueueItem } from "@getpaseo/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { presentQueue } from "./view";
|
||||
|
||||
function item(id: string, patch: Partial<PaseoAgentQueueItem> = {}): PaseoAgentQueueItem {
|
||||
return {
|
||||
id,
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T00:00:00.000Z",
|
||||
text: `message ${id}`,
|
||||
sender: { kind: "user" },
|
||||
held: false,
|
||||
state: "queued",
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function present(
|
||||
items: PaseoAgentQueueItem[],
|
||||
options: { held?: boolean; busy?: string[]; titles?: Record<string, string> } = {},
|
||||
) {
|
||||
return presentQueue(
|
||||
{
|
||||
status: "ready",
|
||||
held: options.held ?? false,
|
||||
items,
|
||||
busy: new Set(options.busy),
|
||||
},
|
||||
{
|
||||
t: i18n.t,
|
||||
agentTitle: (agentId) => options.titles?.[agentId] ?? null,
|
||||
providerLabel: (provider) => provider.toUpperCase(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
describe("presentQueue", () => {
|
||||
it("lists a user message with its attachments and lets it be edited", () => {
|
||||
const queue = present([
|
||||
item("a", {
|
||||
text: "line one\nline two",
|
||||
attachments: [
|
||||
{
|
||||
type: "uploaded_file",
|
||||
id: "upload-1",
|
||||
fileName: "photo.png",
|
||||
mimeType: "image/png",
|
||||
size: 1,
|
||||
path: "/tmp/photo.png",
|
||||
role: "image",
|
||||
},
|
||||
],
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(queue.rows).toEqual([
|
||||
{
|
||||
id: "a",
|
||||
icon: null,
|
||||
label: null,
|
||||
preview: "line one\nline two",
|
||||
attachmentLabel: "1 attachment",
|
||||
switchLabel: null,
|
||||
canEdit: true,
|
||||
disabled: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("says which provider a queued message switches the chat to", () => {
|
||||
const [row] = present([item("a", { providerSwitch: { provider: "codex" } })]).rows;
|
||||
|
||||
expect(row).toMatchObject({ switchLabel: "Switches to CODEX" });
|
||||
});
|
||||
|
||||
it("names the agent that sent a message and does not offer Edit", () => {
|
||||
const sender = { kind: "agent_message" as const, agentId: "child", title: "Old title" };
|
||||
const [row] = present([item("a", { sender })], { titles: { child: "Reviewer" } }).rows;
|
||||
|
||||
expect(row).toMatchObject({ icon: "agent", label: "Sent by Reviewer", canEdit: false });
|
||||
});
|
||||
|
||||
it("falls back to the title the host recorded, then to the agent id", () => {
|
||||
const rows = present([
|
||||
item("a", { sender: { kind: "agent_message", agentId: "one", title: "Recorded" } }),
|
||||
item("b", { sender: { kind: "agent_message", agentId: "two" } }),
|
||||
]).rows;
|
||||
|
||||
expect(rows.map((row) => row.label)).toEqual(["Sent by Recorded", "Sent by two"]);
|
||||
});
|
||||
|
||||
it("labels each agent notification with what happened", () => {
|
||||
const events = ["finished", "errored", "permission-required", "closed"] as const;
|
||||
const rows = present(
|
||||
events.map((event) =>
|
||||
item(event, {
|
||||
text: "Agent child (Builder) finished.\n\n<agent-response>\nDone\n</agent-response>",
|
||||
sender: { kind: "agent_notification", agentId: "child", title: "Builder", event },
|
||||
}),
|
||||
),
|
||||
).rows;
|
||||
|
||||
expect(rows.map((row) => row.label)).toEqual([
|
||||
"Builder finished",
|
||||
"Builder errored",
|
||||
"Builder needs permission",
|
||||
"Builder closed",
|
||||
]);
|
||||
expect(rows[0]).toMatchObject({
|
||||
icon: "agent",
|
||||
canEdit: false,
|
||||
preview: "Agent child (Builder) finished. <agent-response> Done </agent-response>",
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a change request update with its URL, named for the forge", () => {
|
||||
const rows = present([
|
||||
item("pr", {
|
||||
sender: { kind: "change_request_update", url: "https://github.com/acme/app/pull/4" },
|
||||
}),
|
||||
item("mr", {
|
||||
sender: {
|
||||
kind: "change_request_update",
|
||||
url: "https://gitlab.com/acme/app/-/merge_requests/4",
|
||||
},
|
||||
}),
|
||||
]).rows;
|
||||
|
||||
expect(rows).toMatchObject([
|
||||
{
|
||||
icon: "change_request",
|
||||
label: "PR update",
|
||||
preview: "https://github.com/acme/app/pull/4",
|
||||
canEdit: false,
|
||||
},
|
||||
{ icon: "change_request", label: "MR update" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("disables a row that is dispatching or already running a command", () => {
|
||||
const rows = present([item("a", { state: "dispatching" }), item("b"), item("c")], {
|
||||
busy: ["b"],
|
||||
}).rows;
|
||||
|
||||
expect(rows.map((row) => row.disabled)).toEqual([true, true, false]);
|
||||
});
|
||||
|
||||
it("says the queue is paused without naming a cause", () => {
|
||||
expect(present([item("a", { held: true })], { held: true }).notice).toBe(
|
||||
"Queue paused until you send a message",
|
||||
);
|
||||
expect(present([item("a")]).notice).toBeNull();
|
||||
expect(present([], { held: true }).notice).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,82 +0,0 @@
|
||||
import type { PaseoAgentQueueItem } from "@getpaseo/client";
|
||||
import type { TFunction } from "i18next";
|
||||
import type { AgentQueueSnapshot } from "@/agent-queue";
|
||||
|
||||
export interface QueueRowView {
|
||||
id: string;
|
||||
icon: "agent" | "change_request" | null;
|
||||
/** Who or what queued the message. Null for the user's own messages. */
|
||||
label: string | null;
|
||||
preview: string;
|
||||
attachmentLabel: string | null;
|
||||
/** Names the provider the chat moves to when this message is sent. */
|
||||
switchLabel: string | null;
|
||||
canEdit: boolean;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
export interface QueueView {
|
||||
/** In send order: the first row goes next. */
|
||||
rows: QueueRowView[];
|
||||
notice: string | null;
|
||||
}
|
||||
|
||||
interface PresentQueueContext {
|
||||
t: TFunction;
|
||||
/** The current title of an agent this app knows about. */
|
||||
agentTitle: (agentId: string, serverId?: string) => string | null;
|
||||
providerLabel: (provider: string) => string;
|
||||
}
|
||||
|
||||
export function presentQueue(queue: AgentQueueSnapshot, context: PresentQueueContext): QueueView {
|
||||
return {
|
||||
rows: queue.items.map((item) => ({
|
||||
id: item.id,
|
||||
...presentSender(item, context),
|
||||
attachmentLabel: item.attachments?.length
|
||||
? context.t("composer.queue.attachmentCount", { count: item.attachments.length })
|
||||
: null,
|
||||
switchLabel: item.providerSwitch
|
||||
? context.t("composer.queue.switchesTo", {
|
||||
provider: context.providerLabel(item.providerSwitch.provider),
|
||||
})
|
||||
: null,
|
||||
canEdit: item.sender.kind === "user",
|
||||
disabled: item.state === "dispatching" || queue.busy.has(item.id),
|
||||
})),
|
||||
notice: queue.held && queue.items.length > 0 ? context.t("composer.queue.paused") : null,
|
||||
};
|
||||
}
|
||||
|
||||
function presentSender(
|
||||
item: PaseoAgentQueueItem,
|
||||
{ t, agentTitle }: PresentQueueContext,
|
||||
): Pick<QueueRowView, "icon" | "label" | "preview"> {
|
||||
const { sender } = item;
|
||||
if (sender.kind === "user") {
|
||||
return { icon: null, label: null, preview: item.text };
|
||||
}
|
||||
if (sender.kind === "change_request_update") {
|
||||
const isMergeRequest = sender.url.includes("/merge_requests/");
|
||||
return {
|
||||
icon: "change_request",
|
||||
label: t("composer.queue.changeRequestUpdate", { context: isMergeRequest ? "mr" : "" }),
|
||||
preview: sender.url,
|
||||
};
|
||||
}
|
||||
const title = agentTitle(sender.agentId, sender.serverId) || sender.title || sender.agentId;
|
||||
// Messages written for agents open with blank lines and markup. Run them together so the
|
||||
// two preview lines carry text.
|
||||
const preview = item.text.replace(/\s+/g, " ").trim();
|
||||
if (sender.kind === "agent_message") {
|
||||
return { icon: "agent", label: t("composer.queue.sentBy", { title }), preview };
|
||||
}
|
||||
return { icon: "agent", label: t(NOTIFICATION_KEYS[sender.event], { title }), preview };
|
||||
}
|
||||
|
||||
const NOTIFICATION_KEYS = {
|
||||
finished: "composer.queue.agentFinished",
|
||||
errored: "composer.queue.agentErrored",
|
||||
"permission-required": "composer.queue.agentNeedsPermission",
|
||||
closed: "composer.queue.agentClosed",
|
||||
} as const;
|
||||
@@ -104,71 +104,41 @@ describe("submitAgentInput", () => {
|
||||
expect(clearDraft).toHaveBeenCalledWith("sent");
|
||||
});
|
||||
|
||||
function queueingComposer(queueMessage: () => Promise<void>) {
|
||||
const composer = {
|
||||
text: " queued message ",
|
||||
attachments: [{ id: "img-1" }],
|
||||
error: null as string | null,
|
||||
draft: "active",
|
||||
isProcessing: false,
|
||||
};
|
||||
const sent: string[] = [];
|
||||
const submit = () =>
|
||||
it("queues while the agent is running and clears the composer immediately", async () => {
|
||||
const queueMessage = vi.fn();
|
||||
const submitMessage = vi.fn();
|
||||
const clearDraft = vi.fn();
|
||||
const setUserInput = vi.fn();
|
||||
const setAttachments = vi.fn();
|
||||
const setSendError = vi.fn();
|
||||
const setIsProcessing = vi.fn();
|
||||
|
||||
await expect(
|
||||
submitAgentInput({
|
||||
message: composer.text,
|
||||
attachments: composer.attachments,
|
||||
message: " queued message ",
|
||||
attachments: [{ id: "img-1" }],
|
||||
isAgentRunning: true,
|
||||
canSubmit: true,
|
||||
queueMessage,
|
||||
submitMessage: async ({ message }) => {
|
||||
sent.push(message);
|
||||
},
|
||||
clearDraft: (lifecycle) => {
|
||||
composer.draft = lifecycle;
|
||||
},
|
||||
setUserInput: (text) => {
|
||||
composer.text = text;
|
||||
},
|
||||
setAttachments: (attachments) => {
|
||||
composer.attachments = attachments;
|
||||
},
|
||||
setSendError: (message) => {
|
||||
composer.error = message;
|
||||
},
|
||||
setIsProcessing: (isProcessing) => {
|
||||
composer.isProcessing = isProcessing;
|
||||
},
|
||||
});
|
||||
return { composer, sent, submit };
|
||||
}
|
||||
submitMessage,
|
||||
clearDraft,
|
||||
setUserInput,
|
||||
setAttachments,
|
||||
setSendError,
|
||||
setIsProcessing,
|
||||
}),
|
||||
).resolves.toBe("queued");
|
||||
|
||||
it("queues while the agent is running and stays busy until the host accepts", async () => {
|
||||
const accepted = createDeferredPromise<void>();
|
||||
const { composer, sent, submit } = queueingComposer(() => accepted.promise);
|
||||
|
||||
const result = submit();
|
||||
|
||||
expect(composer).toMatchObject({ text: "", attachments: [], isProcessing: true });
|
||||
accepted.resolve();
|
||||
await expect(result).resolves.toBe("queued");
|
||||
expect(composer).toMatchObject({ draft: "sent", isProcessing: false, error: null });
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it("restores the composer when the host does not accept a queued message", async () => {
|
||||
const { composer, submit } = queueingComposer(async () => {
|
||||
throw new Error("Host disconnected");
|
||||
});
|
||||
|
||||
await expect(submit()).resolves.toBe("failed");
|
||||
|
||||
expect(composer).toEqual({
|
||||
text: "queued message",
|
||||
expect(queueMessage).toHaveBeenCalledWith({
|
||||
message: "queued message",
|
||||
attachments: [{ id: "img-1" }],
|
||||
error: "Host disconnected",
|
||||
draft: "active",
|
||||
isProcessing: false,
|
||||
});
|
||||
expect(submitMessage).not.toHaveBeenCalled();
|
||||
expect(setUserInput).toHaveBeenCalledWith("");
|
||||
expect(setAttachments).toHaveBeenCalledWith([]);
|
||||
expect(setSendError).not.toHaveBeenCalled();
|
||||
expect(setIsProcessing).not.toHaveBeenCalled();
|
||||
expect(clearDraft).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("restores the composer when submit fails", async () => {
|
||||
|
||||
@@ -11,8 +11,7 @@ export interface AgentInputSubmitActionInput<TAttachment> {
|
||||
forceSend?: boolean;
|
||||
isAgentRunning: boolean;
|
||||
canSubmit: boolean;
|
||||
/** Resolves once the host has the message in its queue. */
|
||||
queueMessage: (input: { message: string; attachments: TAttachment[] }) => Promise<void>;
|
||||
queueMessage: (input: { message: string; attachments: TAttachment[] }) => void;
|
||||
submitMessage: (input: { message: string; attachments: TAttachment[] }) => Promise<void>;
|
||||
clearDraft: (lifecycle: "sent" | "abandoned") => void;
|
||||
setUserInput: (text: string) => void;
|
||||
@@ -43,7 +42,14 @@ export async function submitAgentInput<TAttachment>(
|
||||
return "noop";
|
||||
}
|
||||
|
||||
const shouldQueue = input.isAgentRunning && !input.forceSend;
|
||||
if (input.isAgentRunning && !input.forceSend) {
|
||||
input.queueMessage({ message: trimmedMessage, attachments });
|
||||
if (shouldClearOnSubmit) {
|
||||
input.setUserInput("");
|
||||
input.setAttachments([]);
|
||||
}
|
||||
return "queued";
|
||||
}
|
||||
|
||||
// Clear immediately so the submitted timeline row and composer state stay in sync.
|
||||
if (shouldClearOnSubmit) {
|
||||
@@ -54,11 +60,10 @@ export async function submitAgentInput<TAttachment>(
|
||||
input.setIsProcessing(true);
|
||||
|
||||
try {
|
||||
const deliver = shouldQueue ? input.queueMessage : input.submitMessage;
|
||||
await deliver({ message: trimmedMessage, attachments });
|
||||
await input.submitMessage({ message: trimmedMessage, attachments });
|
||||
input.clearDraft("sent");
|
||||
input.setIsProcessing(false);
|
||||
return shouldQueue ? "queued" : "submitted";
|
||||
return "submitted";
|
||||
} catch (error) {
|
||||
input.onSubmitError?.(error);
|
||||
if (shouldClearOnSubmit) {
|
||||
|
||||
@@ -366,6 +366,8 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
viewedTimelineSyncRef.current = sync;
|
||||
setViewedTimelineSync(serverId, sync);
|
||||
sync.setActive(getIsAppVisible(appStateRef.current));
|
||||
// An online client replacement leaves isConnected unchanged, so seed each new owner.
|
||||
sync.setConnected(client.getConnectionState().status === "connected");
|
||||
const stopObservingOpenChats = observeOpenWorkspaceAgentIds(serverId, (agentIds) =>
|
||||
sync.replaceOpenTabAgentIds(agentIds),
|
||||
);
|
||||
|
||||
@@ -173,26 +173,6 @@ export const ar: TranslationResources = {
|
||||
dictation: "الإملاء",
|
||||
interruptBeforeVoice: "قم بمقاطعة الوكيل قبل بدء الوضع الصوتي",
|
||||
},
|
||||
queue: {
|
||||
title: "الرسائل المنتظرة",
|
||||
edit: "تعديل الرسالة في قائمة الانتظار",
|
||||
sendNow: "إرسال الرسالة المنتظرة الآن",
|
||||
cancel: "إلغاء الرسالة المنتظرة",
|
||||
paused: "قائمة الانتظار متوقفة حتى ترسل رسالة",
|
||||
sentBy: "أُرسلت بواسطة {{title}}",
|
||||
agentFinished: "انتهى {{title}}",
|
||||
agentErrored: "حدث خطأ في {{title}}",
|
||||
agentNeedsPermission: "يحتاج {{title}} إلى إذن",
|
||||
agentClosed: "أُغلق {{title}}",
|
||||
changeRequestUpdate: "تحديث PR",
|
||||
changeRequestUpdate_mr: "تحديث MR",
|
||||
switchesTo: "ينتقل إلى {{provider}}",
|
||||
attachmentCount_one: "المرفقات: {{count}}",
|
||||
attachmentCount_other: "المرفقات: {{count}}",
|
||||
alreadySending: "الرسالة قيد الإرسال بالفعل",
|
||||
loadFailed: "تعذر تحميل قائمة الانتظار",
|
||||
retry: "إعادة المحاولة",
|
||||
},
|
||||
attachments: {
|
||||
addImage: "أضف صورة",
|
||||
pasteImage: "لصق صورة",
|
||||
@@ -201,8 +181,9 @@ export const ar: TranslationResources = {
|
||||
addIssueOrPr_mr: "أضف مشكلة أو MR",
|
||||
dropImagesHere: "إسقاط الصور هنا",
|
||||
dropFilesHere: "Drop files here",
|
||||
editQueuedMessage: "تحرير الرسالة في قائمة الانتظار",
|
||||
sendQueuedMessageNow: "إرسال رسالة في قائمة الانتظار الآن",
|
||||
openImage: "فتح مرفق الصورة",
|
||||
removeAttachment: "إزالة المرفق",
|
||||
removeImage: "إزالة مرفق الصورة",
|
||||
removeFile: "Remove file attachment",
|
||||
openGithub: "افتح {{kind}} {{number}}",
|
||||
|
||||
@@ -171,26 +171,6 @@ export const en = {
|
||||
dictation: "Dictation",
|
||||
interruptBeforeVoice: "Interrupt the agent before starting voice mode",
|
||||
},
|
||||
queue: {
|
||||
title: "Queued messages",
|
||||
edit: "Edit queued message",
|
||||
sendNow: "Send queued message now",
|
||||
cancel: "Cancel queued message",
|
||||
paused: "Queue paused until you send a message",
|
||||
sentBy: "Sent by {{title}}",
|
||||
agentFinished: "{{title}} finished",
|
||||
agentErrored: "{{title}} errored",
|
||||
agentNeedsPermission: "{{title}} needs permission",
|
||||
agentClosed: "{{title}} closed",
|
||||
changeRequestUpdate: "PR update",
|
||||
changeRequestUpdate_mr: "MR update",
|
||||
switchesTo: "Switches to {{provider}}",
|
||||
attachmentCount_one: "{{count}} attachment",
|
||||
attachmentCount_other: "{{count}} attachments",
|
||||
alreadySending: "Message is already sending",
|
||||
loadFailed: "Couldn't load the queue",
|
||||
retry: "Retry",
|
||||
},
|
||||
attachments: {
|
||||
addImage: "Add image",
|
||||
pasteImage: "Paste image",
|
||||
@@ -199,8 +179,9 @@ export const en = {
|
||||
addIssueOrPr_mr: "Add issue or MR",
|
||||
dropImagesHere: "Drop images here",
|
||||
dropFilesHere: "Drop files here",
|
||||
editQueuedMessage: "Edit queued message",
|
||||
sendQueuedMessageNow: "Send queued message now",
|
||||
openImage: "Open image attachment",
|
||||
removeAttachment: "Remove attachment",
|
||||
removeImage: "Remove image attachment",
|
||||
removeFile: "Remove file attachment",
|
||||
openGithub: "Open {{kind}} {{number}}",
|
||||
|
||||
@@ -174,26 +174,6 @@ export const es: TranslationResources = {
|
||||
dictation: "Dictado",
|
||||
interruptBeforeVoice: "Interrumpir al agente antes de iniciar el modo de voz.",
|
||||
},
|
||||
queue: {
|
||||
title: "Mensajes en cola",
|
||||
edit: "Editar mensaje en cola",
|
||||
sendNow: "Enviar ahora el mensaje en cola",
|
||||
cancel: "Cancelar mensaje en cola",
|
||||
paused: "Cola en pausa hasta que envíes un mensaje",
|
||||
sentBy: "Enviado por {{title}}",
|
||||
agentFinished: "{{title}} terminó",
|
||||
agentErrored: "{{title}} falló",
|
||||
agentNeedsPermission: "{{title}} necesita permiso",
|
||||
agentClosed: "{{title}} se cerró",
|
||||
changeRequestUpdate: "Actualización de PR",
|
||||
changeRequestUpdate_mr: "Actualización de MR",
|
||||
switchesTo: "Cambia a {{provider}}",
|
||||
attachmentCount_one: "{{count}} adjunto",
|
||||
attachmentCount_other: "{{count}} adjuntos",
|
||||
alreadySending: "El mensaje ya se está enviando",
|
||||
loadFailed: "No se pudo cargar la cola",
|
||||
retry: "Reintentar",
|
||||
},
|
||||
attachments: {
|
||||
addImage: "Agregar imagen",
|
||||
pasteImage: "Pegar imagen",
|
||||
@@ -202,8 +182,9 @@ export const es: TranslationResources = {
|
||||
addIssueOrPr_mr: "Agregar problema o MR",
|
||||
dropImagesHere: "Suelta imágenes aquí",
|
||||
dropFilesHere: "Drop files here",
|
||||
editQueuedMessage: "Editar mensaje en cola",
|
||||
sendQueuedMessageNow: "Enviar mensaje en cola ahora",
|
||||
openImage: "Abrir imagen adjunta",
|
||||
removeAttachment: "Quitar adjunto",
|
||||
removeImage: "Quitar imagen adjunta",
|
||||
removeFile: "Remove file attachment",
|
||||
openGithub: "Abrir {{kind}} {{number}}",
|
||||
|
||||
@@ -175,26 +175,6 @@ export const fr: TranslationResources = {
|
||||
dictation: "Dictée",
|
||||
interruptBeforeVoice: "Interrompez l’agent avant de démarrer le mode vocal",
|
||||
},
|
||||
queue: {
|
||||
title: "Messages en attente",
|
||||
edit: "Modifier le message en attente",
|
||||
sendNow: "Envoyer maintenant le message en attente",
|
||||
cancel: "Annuler le message en attente",
|
||||
paused: "File en pause jusqu'à l'envoi d'un message",
|
||||
sentBy: "Envoyé par {{title}}",
|
||||
agentFinished: "{{title}} a terminé",
|
||||
agentErrored: "{{title}} a échoué",
|
||||
agentNeedsPermission: "{{title}} demande une autorisation",
|
||||
agentClosed: "{{title}} s'est fermé",
|
||||
changeRequestUpdate: "Mise à jour de PR",
|
||||
changeRequestUpdate_mr: "Mise à jour de MR",
|
||||
switchesTo: "Passe à {{provider}}",
|
||||
attachmentCount_one: "{{count}} pièce jointe",
|
||||
attachmentCount_other: "{{count}} pièces jointes",
|
||||
alreadySending: "Le message est déjà en cours d'envoi",
|
||||
loadFailed: "Impossible de charger la file",
|
||||
retry: "Réessayer",
|
||||
},
|
||||
attachments: {
|
||||
addImage: "Ajouter une image",
|
||||
pasteImage: "Coller une image",
|
||||
@@ -203,8 +183,9 @@ export const fr: TranslationResources = {
|
||||
addIssueOrPr_mr: "Ajouter un ticket ou une MR",
|
||||
dropImagesHere: "Déposez des images ici",
|
||||
dropFilesHere: "Déposez des fichiers ici",
|
||||
editQueuedMessage: "Modifier le message en file d’attente",
|
||||
sendQueuedMessageNow: "Envoyer maintenant le message en file d’attente",
|
||||
openImage: "Ouvrir l’image jointe",
|
||||
removeAttachment: "Supprimer la pièce jointe",
|
||||
removeImage: "Retirer l’image jointe",
|
||||
removeFile: "Retirer le fichier joint",
|
||||
openGithub: "Ouvrir {{kind}} {{number}}",
|
||||
|
||||
@@ -174,26 +174,6 @@ export const ja: TranslationResources = {
|
||||
dictation: "音声入力",
|
||||
interruptBeforeVoice: "音声モードを開始する前にエージェントを中断してください",
|
||||
},
|
||||
queue: {
|
||||
title: "キュー内のメッセージ",
|
||||
edit: "キュー内のメッセージを編集",
|
||||
sendNow: "キュー内のメッセージを今すぐ送信",
|
||||
cancel: "キュー内のメッセージを取り消す",
|
||||
paused: "メッセージを送信するまでキューは一時停止します",
|
||||
sentBy: "{{title}} から送信",
|
||||
agentFinished: "{{title}} が完了",
|
||||
agentErrored: "{{title}} でエラー",
|
||||
agentNeedsPermission: "{{title}} に許可が必要",
|
||||
agentClosed: "{{title}} が終了",
|
||||
changeRequestUpdate: "PR の更新",
|
||||
changeRequestUpdate_mr: "MR の更新",
|
||||
switchesTo: "{{provider}} に切り替え",
|
||||
attachmentCount_one: "添付 {{count}} 件",
|
||||
attachmentCount_other: "添付 {{count}} 件",
|
||||
alreadySending: "メッセージはすでに送信中です",
|
||||
loadFailed: "キューを読み込めませんでした",
|
||||
retry: "再試行",
|
||||
},
|
||||
attachments: {
|
||||
addImage: "画像を追加",
|
||||
pasteImage: "画像を貼り付け",
|
||||
@@ -202,8 +182,9 @@ export const ja: TranslationResources = {
|
||||
addIssueOrPr_mr: "イシューまたはMRを追加",
|
||||
dropImagesHere: "ここに画像をドロップ",
|
||||
dropFilesHere: "ここにファイルをドロップ",
|
||||
editQueuedMessage: "キューに入れたメッセージを編集",
|
||||
sendQueuedMessageNow: "キューに入れたメッセージを今すぐ送信",
|
||||
openImage: "画像添付ファイルを開く",
|
||||
removeAttachment: "添付を削除",
|
||||
removeImage: "画像添付ファイルを削除",
|
||||
removeFile: "ファイル添付ファイルを削除",
|
||||
openGithub: "{{kind}} {{number}}を開く",
|
||||
|
||||
@@ -173,26 +173,6 @@ export const ko: TranslationResources = {
|
||||
dictation: "받아쓰기",
|
||||
interruptBeforeVoice: "음성 모드를 시작하기 전에 에이전트를 중단하세요",
|
||||
},
|
||||
queue: {
|
||||
title: "대기 중인 메시지",
|
||||
edit: "대기 중인 메시지 편집",
|
||||
sendNow: "대기 중인 메시지 지금 보내기",
|
||||
cancel: "대기 중인 메시지 취소",
|
||||
paused: "메시지를 보낼 때까지 대기열이 일시중지됩니다",
|
||||
sentBy: "{{title}}이(가) 보냄",
|
||||
agentFinished: "{{title}} 완료",
|
||||
agentErrored: "{{title}} 오류",
|
||||
agentNeedsPermission: "{{title}} 권한 필요",
|
||||
agentClosed: "{{title}} 종료됨",
|
||||
changeRequestUpdate: "PR 업데이트",
|
||||
changeRequestUpdate_mr: "MR 업데이트",
|
||||
switchesTo: "{{provider}}(으)로 전환",
|
||||
attachmentCount_one: "첨부 파일 {{count}}개",
|
||||
attachmentCount_other: "첨부 파일 {{count}}개",
|
||||
alreadySending: "메시지를 이미 보내는 중입니다",
|
||||
loadFailed: "대기열을 불러올 수 없습니다",
|
||||
retry: "다시 시도",
|
||||
},
|
||||
attachments: {
|
||||
addImage: "이미지 추가",
|
||||
pasteImage: "이미지 붙여넣기",
|
||||
@@ -201,8 +181,9 @@ export const ko: TranslationResources = {
|
||||
addIssueOrPr_mr: "이슈 또는 MR 추가",
|
||||
dropImagesHere: "여기에 이미지를 끌어다 놓으세요",
|
||||
dropFilesHere: "여기에 파일을 끌어다 놓으세요",
|
||||
editQueuedMessage: "대기 중인 메시지 편집",
|
||||
sendQueuedMessageNow: "대기 중인 메시지 지금 보내기",
|
||||
openImage: "이미지 첨부 열기",
|
||||
removeAttachment: "첨부 파일 삭제",
|
||||
removeImage: "이미지 첨부 제거",
|
||||
removeFile: "파일 첨부 제거",
|
||||
openGithub: "{{kind}} {{number}} 열기",
|
||||
|
||||
@@ -174,26 +174,6 @@ export const ptBR: TranslationResources = {
|
||||
dictation: "Ditado",
|
||||
interruptBeforeVoice: "Interrompa o agente antes de iniciar o modo de voz",
|
||||
},
|
||||
queue: {
|
||||
title: "Mensagens na fila",
|
||||
edit: "Editar mensagem na fila",
|
||||
sendNow: "Enviar agora a mensagem na fila",
|
||||
cancel: "Cancelar mensagem na fila",
|
||||
paused: "Fila pausada até você enviar uma mensagem",
|
||||
sentBy: "Enviada por {{title}}",
|
||||
agentFinished: "{{title}} concluiu",
|
||||
agentErrored: "{{title}} falhou",
|
||||
agentNeedsPermission: "{{title}} precisa de permissão",
|
||||
agentClosed: "{{title}} foi encerrado",
|
||||
changeRequestUpdate: "Atualização de PR",
|
||||
changeRequestUpdate_mr: "Atualização de MR",
|
||||
switchesTo: "Muda para {{provider}}",
|
||||
attachmentCount_one: "{{count}} anexo",
|
||||
attachmentCount_other: "{{count}} anexos",
|
||||
alreadySending: "A mensagem já está sendo enviada",
|
||||
loadFailed: "Não foi possível carregar a fila",
|
||||
retry: "Tentar novamente",
|
||||
},
|
||||
attachments: {
|
||||
addImage: "Adicionar imagem",
|
||||
pasteImage: "Colar imagem",
|
||||
@@ -202,8 +182,9 @@ export const ptBR: TranslationResources = {
|
||||
addIssueOrPr_mr: "Adicionar issue ou MR",
|
||||
dropImagesHere: "Solte imagens aqui",
|
||||
dropFilesHere: "Solte arquivos aqui",
|
||||
editQueuedMessage: "Editar mensagem na fila",
|
||||
sendQueuedMessageNow: "Enviar mensagem da fila agora",
|
||||
openImage: "Abrir anexo de imagem",
|
||||
removeAttachment: "Remover anexo",
|
||||
removeImage: "Remover anexo de imagem",
|
||||
removeFile: "Remover anexo de arquivo",
|
||||
openGithub: "Abrir {{kind}} {{number}}",
|
||||
|
||||
@@ -174,26 +174,6 @@ export const ru: TranslationResources = {
|
||||
dictation: "Диктовка",
|
||||
interruptBeforeVoice: "Остановите агента перед запуском голосового режима",
|
||||
},
|
||||
queue: {
|
||||
title: "Сообщения в очереди",
|
||||
edit: "Изменить сообщение в очереди",
|
||||
sendNow: "Отправить сообщение из очереди сейчас",
|
||||
cancel: "Отменить сообщение в очереди",
|
||||
paused: "Очередь приостановлена, пока вы не отправите сообщение",
|
||||
sentBy: "Отправитель: {{title}}",
|
||||
agentFinished: "{{title}}: готово",
|
||||
agentErrored: "{{title}}: ошибка",
|
||||
agentNeedsPermission: "{{title}}: нужно разрешение",
|
||||
agentClosed: "{{title}}: закрыт",
|
||||
changeRequestUpdate: "Обновление PR",
|
||||
changeRequestUpdate_mr: "Обновление MR",
|
||||
switchesTo: "Переключится на {{provider}}",
|
||||
attachmentCount_one: "Вложений: {{count}}",
|
||||
attachmentCount_other: "Вложений: {{count}}",
|
||||
alreadySending: "Сообщение уже отправляется",
|
||||
loadFailed: "Не удалось загрузить очередь",
|
||||
retry: "Повторить",
|
||||
},
|
||||
attachments: {
|
||||
addImage: "Добавить изображение",
|
||||
pasteImage: "Вставить изображение",
|
||||
@@ -202,8 +182,9 @@ export const ru: TranslationResources = {
|
||||
addIssueOrPr_mr: "Добавить проблему или MR",
|
||||
dropImagesHere: "Скиньте изображения сюда",
|
||||
dropFilesHere: "Переместите файлы сюда",
|
||||
editQueuedMessage: "Изменить сообщение из очереди",
|
||||
sendQueuedMessageNow: "Отправить сообщение из очереди сейчас",
|
||||
openImage: "Открыть прикрепленное изображение",
|
||||
removeAttachment: "Удалить вложение",
|
||||
removeImage: "Удалить прикрепленное изображение",
|
||||
removeFile: "Удалить прикрепленный файл",
|
||||
openGithub: "Открыть {{kind}} {{number}}",
|
||||
|
||||
@@ -173,26 +173,6 @@ export const zhCN: TranslationResources = {
|
||||
dictation: "听写",
|
||||
interruptBeforeVoice: "启动语音模式前请先中断 Agent",
|
||||
},
|
||||
queue: {
|
||||
title: "排队消息",
|
||||
edit: "编辑排队消息",
|
||||
sendNow: "立即发送排队消息",
|
||||
cancel: "取消排队消息",
|
||||
paused: "队列已暂停,发送消息后继续",
|
||||
sentBy: "由 {{title}} 发送",
|
||||
agentFinished: "{{title}} 已完成",
|
||||
agentErrored: "{{title}} 出错",
|
||||
agentNeedsPermission: "{{title}} 需要权限",
|
||||
agentClosed: "{{title}} 已关闭",
|
||||
changeRequestUpdate: "PR 更新",
|
||||
changeRequestUpdate_mr: "MR 更新",
|
||||
switchesTo: "切换到 {{provider}}",
|
||||
attachmentCount_one: "{{count}} 个附件",
|
||||
attachmentCount_other: "{{count}} 个附件",
|
||||
alreadySending: "消息正在发送",
|
||||
loadFailed: "无法加载队列",
|
||||
retry: "重试",
|
||||
},
|
||||
attachments: {
|
||||
addImage: "添加图片",
|
||||
pasteImage: "粘贴图片",
|
||||
@@ -201,8 +181,9 @@ export const zhCN: TranslationResources = {
|
||||
addIssueOrPr_mr: "添加 issue 或 MR",
|
||||
dropImagesHere: "将图片拖放到这里",
|
||||
dropFilesHere: "Drop files here",
|
||||
editQueuedMessage: "编辑排队消息",
|
||||
sendQueuedMessageNow: "立即发送排队消息",
|
||||
openImage: "打开图片附件",
|
||||
removeAttachment: "移除附件",
|
||||
removeImage: "移除图片附件",
|
||||
removeFile: "Remove file attachment",
|
||||
openGithub: "打开 {{kind}} {{number}}",
|
||||
|
||||
@@ -65,7 +65,11 @@ describe("AgentDirectoryReplica", () => {
|
||||
const serverId = `agent-replica-history-${removal}`;
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null);
|
||||
const replica = new AgentDirectoryReplica(serverId, () => undefined);
|
||||
const replica = new AgentDirectoryReplica(
|
||||
serverId,
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
const draftKey = buildDraftStoreKey({ serverId, agentId: "agent" });
|
||||
const draft = {
|
||||
text: "Keep this unsent draft",
|
||||
@@ -117,7 +121,11 @@ describe("AgentDirectoryReplica", () => {
|
||||
const serverId = "agent-replica-late-cache";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const replica = new AgentDirectoryReplica(serverId, () => undefined);
|
||||
const replica = new AgentDirectoryReplica(
|
||||
serverId,
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
replica.commitSnapshot([entry(payload("live"))], []);
|
||||
replica.applyTurnLiveness("agent", {
|
||||
type: "stream_open",
|
||||
@@ -136,7 +144,11 @@ describe("AgentDirectoryReplica", () => {
|
||||
const serverId = "agent-replica-cache-miss";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const replica = new AgentDirectoryReplica(serverId, () => undefined);
|
||||
const replica = new AgentDirectoryReplica(
|
||||
serverId,
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
|
||||
expect(replica.submitTimelineAgent(replica.captureTimeline("agent"), payload("network"))).toBe(
|
||||
true,
|
||||
@@ -152,8 +164,10 @@ describe("AgentDirectoryReplica", () => {
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const commits: DirectoryReplicaMutation[][] = [];
|
||||
const replica = new AgentDirectoryReplica(serverId, (mutations) =>
|
||||
commits.push([...mutations]),
|
||||
const replica = new AgentDirectoryReplica(
|
||||
serverId,
|
||||
() => undefined,
|
||||
(mutations) => commits.push([...mutations]),
|
||||
);
|
||||
replica.commitSnapshot([entry(payload("agent"))], []);
|
||||
commits.length = 0;
|
||||
@@ -185,11 +199,38 @@ describe("AgentDirectoryReplica", () => {
|
||||
store.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("notifies the queue owner exactly once when a stream turn closes", () => {
|
||||
const serverId = "agent-replica-stream-stop";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const stopped: string[] = [];
|
||||
const replica = new AgentDirectoryReplica(
|
||||
serverId,
|
||||
(agentId) => stopped.push(agentId),
|
||||
() => undefined,
|
||||
);
|
||||
replica.commitSnapshot([entry(payload("agent"))], []);
|
||||
replica.applyTurnLiveness("agent", {
|
||||
type: "stream_open",
|
||||
turn: { turnId: "turn-1", startedAt: null },
|
||||
});
|
||||
|
||||
replica.applyTurnLiveness("agent", { type: "stream_close", turnId: "turn-1" });
|
||||
replica.applyTurnLiveness("agent", { type: "stream_close", turnId: "turn-1" });
|
||||
|
||||
expect(stopped).toEqual(["agent"]);
|
||||
store.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("preserves cancellation state when the same active turn is snapshotted", () => {
|
||||
const serverId = "agent-replica-cancellation-snapshot";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const replica = new AgentDirectoryReplica(serverId, () => undefined);
|
||||
const replica = new AgentDirectoryReplica(
|
||||
serverId,
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
replica.commitSnapshot(
|
||||
[
|
||||
entry({
|
||||
@@ -233,11 +274,16 @@ describe("AgentDirectoryReplica", () => {
|
||||
store.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("follows turn liveness even when protocol status disagrees", () => {
|
||||
it("uses turn liveness for stopped transitions even when protocol status disagrees", () => {
|
||||
const serverId = "agent-replica-mismatched-status";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const replica = new AgentDirectoryReplica(serverId, () => undefined);
|
||||
const stopped: string[] = [];
|
||||
const replica = new AgentDirectoryReplica(
|
||||
serverId,
|
||||
(agentId) => stopped.push(agentId),
|
||||
() => undefined,
|
||||
);
|
||||
replica.commitSnapshot(
|
||||
[
|
||||
entry({
|
||||
@@ -268,6 +314,7 @@ describe("AgentDirectoryReplica", () => {
|
||||
status: "idle",
|
||||
turn: { phase: "idle" },
|
||||
});
|
||||
expect(stopped).toEqual(["agent"]);
|
||||
store.clearSession(serverId);
|
||||
});
|
||||
|
||||
@@ -275,7 +322,11 @@ describe("AgentDirectoryReplica", () => {
|
||||
const serverId = "agent-replica-catch-up";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const replica = new AgentDirectoryReplica(serverId, () => undefined);
|
||||
const replica = new AgentDirectoryReplica(
|
||||
serverId,
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
replica.commitSnapshot(
|
||||
[
|
||||
entry({
|
||||
@@ -302,7 +353,11 @@ describe("AgentDirectoryReplica", () => {
|
||||
const serverId = "agent-replica";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const replica = new AgentDirectoryReplica(serverId, () => undefined);
|
||||
const replica = new AgentDirectoryReplica(
|
||||
serverId,
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
replica.commitSnapshot([entry(payload("directory"))], []);
|
||||
const directoryPlacement = useSessionStore
|
||||
.getState()
|
||||
@@ -335,7 +390,11 @@ describe("AgentDirectoryReplica", () => {
|
||||
const serverId = "agent-replica-timeline-membership";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const replica = new AgentDirectoryReplica(serverId, () => undefined);
|
||||
const replica = new AgentDirectoryReplica(
|
||||
serverId,
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
|
||||
// A conversation opened from history arrives over its timeline, without the
|
||||
// project placement the directory carries, and is a member from then on.
|
||||
@@ -351,7 +410,11 @@ describe("AgentDirectoryReplica", () => {
|
||||
const serverId = "agent-replica-unchanged-fields";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const replica = new AgentDirectoryReplica(serverId, () => undefined);
|
||||
const replica = new AgentDirectoryReplica(
|
||||
serverId,
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
const agentInStore = () => useSessionStore.getState().sessions[serverId]?.agents.get("agent");
|
||||
replica.commitSnapshot([entry(payload("agent"))], []);
|
||||
const before = agentInStore();
|
||||
|
||||
@@ -36,6 +36,7 @@ export class AgentDirectoryReplica {
|
||||
|
||||
constructor(
|
||||
private readonly serverId: string,
|
||||
private readonly onStoppedRunning: (agentId: string) => void,
|
||||
private readonly persist: (mutations: readonly DirectoryReplicaMutation[]) => void,
|
||||
) {
|
||||
this.storeProjection = new AgentStoreProjection(serverId);
|
||||
@@ -106,6 +107,7 @@ export class AgentDirectoryReplica {
|
||||
this.members.add(delta.agent.id);
|
||||
if (!before) this.advance(delta.agent.id);
|
||||
}
|
||||
if (result.stoppedRunning) this.onStoppedRunning(result.agentId);
|
||||
this.persist(
|
||||
result.agent
|
||||
? [this.agentUpsert(result.agent)]
|
||||
@@ -144,6 +146,11 @@ export class AgentDirectoryReplica {
|
||||
this.pendingCacheReads.clear();
|
||||
for (const agentId of nextIds) this.members.add(agentId);
|
||||
const agents = this.storeProjection.replaceFetched(reconciled);
|
||||
for (const [agentId, previousAgent] of previous) {
|
||||
if (previousAgent.turn.phase === "open" && agents.get(agentId)?.turn.phase === "idle") {
|
||||
this.onStoppedRunning(agentId);
|
||||
}
|
||||
}
|
||||
if (persist) {
|
||||
this.persist([
|
||||
...Array.from(previous.keys())
|
||||
@@ -207,9 +214,11 @@ export class AgentDirectoryReplica {
|
||||
agentId: string,
|
||||
transition: TurnLivenessTransition | readonly TurnLivenessTransition[],
|
||||
): void {
|
||||
const wasRunning = this.storeProjection.get(agentId)?.turn.phase === "open";
|
||||
const accepted = this.storeProjection.applyTurn(agentId, transition);
|
||||
if (!accepted) return;
|
||||
this.persist([this.agentUpsert(accepted)]);
|
||||
if (wasRunning && accepted.turn.phase === "idle") this.onStoppedRunning(agentId);
|
||||
}
|
||||
|
||||
private agentUpsert(agent: Agent): DirectoryReplicaMutation {
|
||||
|
||||
@@ -222,6 +222,7 @@ function createDirectory(
|
||||
const client = new FakeDirectoryClient();
|
||||
client.supportsWorkspaceLabels = options?.workspaceLabels === true;
|
||||
const directory = new DirectorySync(serverId, {
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -301,6 +302,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -390,6 +392,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -445,6 +448,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -482,6 +486,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -778,6 +783,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -859,6 +865,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -918,6 +925,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -980,6 +988,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -1066,6 +1075,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -1110,6 +1120,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -1161,6 +1172,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -1285,6 +1297,7 @@ describe("DirectorySync session readiness", () => {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => undefined,
|
||||
markAgentLoading: () => undefined,
|
||||
markAgentReady: () => undefined,
|
||||
markAgentError: () => undefined,
|
||||
@@ -1668,6 +1681,7 @@ it("fills every cached workspace beneath live updates received during the SQLite
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => {},
|
||||
markAgentLoading: () => {},
|
||||
markAgentReady: () => {},
|
||||
markAgentError: () => {},
|
||||
@@ -1813,6 +1827,7 @@ async function createDamagedLegacyProjectDirectory(serverId: string, renameSeq:
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => {},
|
||||
markAgentLoading: () => {},
|
||||
markAgentReady: () => {},
|
||||
markAgentError: () => {},
|
||||
@@ -2100,6 +2115,7 @@ it.each(["before", "during", "before-metadata", "damaged"] as const)(
|
||||
};
|
||||
client.projectResult = projectResult;
|
||||
const callbacks = {
|
||||
onAgentStoppedRunning: () => {},
|
||||
markAgentLoading: () => {},
|
||||
markAgentReady: () => {},
|
||||
markAgentError: () => {},
|
||||
@@ -2210,6 +2226,7 @@ it("batches a burst of 200 workspace_update frames into one mergeWorkspaces comm
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => {},
|
||||
markAgentLoading: () => {},
|
||||
markAgentReady: () => {},
|
||||
markAgentError: () => {},
|
||||
@@ -2301,6 +2318,7 @@ it("coalesces duplicate upserts and removals within a single workspace_update ba
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => {},
|
||||
markAgentLoading: () => {},
|
||||
markAgentReady: () => {},
|
||||
markAgentError: () => {},
|
||||
|
||||
@@ -208,6 +208,7 @@ export class DirectorySync {
|
||||
constructor(
|
||||
private readonly serverId: string,
|
||||
private readonly callbacks: {
|
||||
onAgentStoppedRunning: (agentId: string) => void;
|
||||
markAgentLoading: () => void;
|
||||
markAgentReady: () => void;
|
||||
markAgentError: (error: string) => void;
|
||||
@@ -216,7 +217,7 @@ export class DirectorySync {
|
||||
) {
|
||||
const persist = (mutations: readonly DirectoryReplicaMutation[]) =>
|
||||
this.checkpoints?.commitDirectoryMutations(this.serverId, mutations);
|
||||
this.agents = new AgentDirectoryReplica(serverId, persist);
|
||||
this.agents = new AgentDirectoryReplica(serverId, callbacks.onAgentStoppedRunning, persist);
|
||||
this.workspaces = new WorkspaceDirectoryReplica(serverId);
|
||||
}
|
||||
|
||||
|
||||
@@ -97,11 +97,12 @@ export class AgentStoreProjection {
|
||||
|
||||
applyDelta(delta: AgentDirectoryDelta): {
|
||||
agentId: string;
|
||||
stoppedRunning: boolean;
|
||||
agent?: Agent;
|
||||
} {
|
||||
if (delta.kind === "remove") {
|
||||
this.removeFromDirectory(delta.agentId);
|
||||
return { agentId: delta.agentId };
|
||||
return { agentId: delta.agentId, stoppedRunning: false };
|
||||
}
|
||||
const normalized = normalizeAgentSnapshot(delta.agent, this.serverId);
|
||||
const session = useSessionStore.getState().sessions[this.serverId];
|
||||
@@ -127,6 +128,7 @@ export class AgentStoreProjection {
|
||||
useSessionStore.getState().setAgentLastActivity(accepted.id, accepted.lastActivityAt);
|
||||
return {
|
||||
agentId: accepted.id,
|
||||
stoppedRunning: previous?.turn.phase === "open" && accepted.turn.phase === "idle",
|
||||
agent: accepted,
|
||||
};
|
||||
}
|
||||
@@ -191,6 +193,7 @@ export class AgentStoreProjection {
|
||||
next.delete(agentId);
|
||||
return next;
|
||||
});
|
||||
store.setQueuedMessages(this.serverId, removeKey);
|
||||
store.setInitializingAgents(this.serverId, removeKey);
|
||||
store.setPendingPermissions(this.serverId, (current) => {
|
||||
const next = new Map(current);
|
||||
|
||||
@@ -76,11 +76,13 @@ class FakeDaemonClient {
|
||||
> = [];
|
||||
public sentAgentMessages: Array<Parameters<DaemonClient["sendAgentMessage"]>> = [];
|
||||
public sendAgentMessageFailures: Error[] = [];
|
||||
public sendAgentMessageResponses: Promise<void>[] = [];
|
||||
private agentUpdateListeners = new Set<
|
||||
(message: Extract<SessionOutboundMessage, { type: "agent_update" }>) => void
|
||||
>();
|
||||
private fetchWaiters = new Set<() => void>();
|
||||
private agentListenerWaiters = new Set<() => void>();
|
||||
private sentMessageWaiters = new Set<() => void>();
|
||||
|
||||
on(
|
||||
type: "agent_update",
|
||||
@@ -132,11 +134,26 @@ class FakeDaemonClient {
|
||||
...args: Parameters<DaemonClient["sendAgentMessage"]>
|
||||
): ReturnType<DaemonClient["sendAgentMessage"]> {
|
||||
this.sentAgentMessages.push(args);
|
||||
for (const waiter of this.sentMessageWaiters) waiter();
|
||||
const response = this.sendAgentMessageResponses.shift();
|
||||
if (response) await response;
|
||||
const failure = this.sendAgentMessageFailures.shift();
|
||||
if (failure) throw failure;
|
||||
return {};
|
||||
}
|
||||
|
||||
async waitForSentMessages(count: number): Promise<void> {
|
||||
if (this.sentAgentMessages.length >= count) return;
|
||||
await new Promise<void>((resolve) => {
|
||||
const waiter = () => {
|
||||
if (this.sentAgentMessages.length < count) return;
|
||||
this.sentMessageWaiters.delete(waiter);
|
||||
resolve();
|
||||
};
|
||||
this.sentMessageWaiters.add(waiter);
|
||||
});
|
||||
}
|
||||
|
||||
ensureConnected(options?: { verify?: boolean }): void {
|
||||
this.ensureConnectedCalls += 1;
|
||||
if (options?.verify) this.connectionVerifications += 1;
|
||||
@@ -3879,6 +3896,123 @@ describe("HostRuntimeStore", () => {
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("drains snapshot and buffered running transitions exactly once", async () => {
|
||||
const host = makeHost({
|
||||
serverId: "srv_legacy_transitions",
|
||||
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
|
||||
});
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
fakeClient.setConnectionState({ status: "connected" });
|
||||
const pageTwo = new Deferred<Awaited<ReturnType<DaemonClient["fetchAgents"]>>>();
|
||||
const snapshotAgent = makeFetchAgentsEntry({
|
||||
id: "legacy-snapshot",
|
||||
cwd: "/legacy/repo",
|
||||
updatedAt: "2026-07-12T10:00:00.000Z",
|
||||
});
|
||||
const bufferedAgent = makeFetchAgentsEntry({
|
||||
id: "legacy-buffered",
|
||||
cwd: "/legacy/repo",
|
||||
updatedAt: "2026-07-12T10:00:00.000Z",
|
||||
});
|
||||
fakeClient.fetchAgentsResponses.push(
|
||||
makeFetchAgentsPayload({
|
||||
entries: [
|
||||
{ ...snapshotAgent, agent: { ...snapshotAgent.agent, status: "idle" } },
|
||||
{ ...bufferedAgent, agent: { ...bufferedAgent.agent, status: "running" } },
|
||||
],
|
||||
hasMore: true,
|
||||
nextCursor: "legacy-page-two",
|
||||
}),
|
||||
pageTwo.promise,
|
||||
);
|
||||
const store = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async () => ({
|
||||
client: fakeClient as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
}),
|
||||
getClientId: async () => "cid_legacy_transitions",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(host.serverId, fakeClient as unknown as DaemonClient, 1);
|
||||
sessionStore.updateSessionServerInfo(host.serverId, {
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
version: "0.1.96",
|
||||
});
|
||||
sessionStore.setAgents(
|
||||
host.serverId,
|
||||
new Map([
|
||||
[
|
||||
"legacy-snapshot",
|
||||
{
|
||||
...replicaAgent(snapshotAgent.agent, host.serverId),
|
||||
turn: {
|
||||
phase: "open",
|
||||
turnId: null,
|
||||
startedAt: null,
|
||||
cancellationRequestId: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
"legacy-buffered",
|
||||
{
|
||||
...replicaAgent(bufferedAgent.agent, host.serverId),
|
||||
turn: {
|
||||
phase: "open",
|
||||
turnId: null,
|
||||
startedAt: null,
|
||||
cancellationRequestId: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
sessionStore.setQueuedMessages(
|
||||
host.serverId,
|
||||
new Map([
|
||||
["legacy-snapshot", [{ id: "legacy-snapshot-message", text: "snapshot", attachments: [] }]],
|
||||
["legacy-buffered", [{ id: "legacy-buffered-message", text: "buffered", attachments: [] }]],
|
||||
]),
|
||||
);
|
||||
store.syncHosts([host]);
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
const load = store.refreshAgentDirectory({
|
||||
serverId: host.serverId,
|
||||
subscribe: {},
|
||||
page: { limit: 200 },
|
||||
});
|
||||
await fakeClient.waitForFetches(2);
|
||||
fakeClient.agentUpdate({
|
||||
kind: "upsert",
|
||||
agent: { ...bufferedAgent.agent, status: "idle" },
|
||||
project: bufferedAgent.project,
|
||||
});
|
||||
pageTwo.resolve(makeFetchAgentsPayload({ entries: [] }));
|
||||
await load;
|
||||
await fakeClient.waitForSentMessages(2);
|
||||
|
||||
expect(fakeClient.sentAgentMessages.map(([agentId, text]) => [agentId, text])).toEqual([
|
||||
["legacy-snapshot", "snapshot"],
|
||||
["legacy-buffered", "buffered"],
|
||||
]);
|
||||
expect(
|
||||
Array.from(useSessionStore.getState().sessions[host.serverId]?.agents.values() ?? []).map(
|
||||
({ id, status, workspaceId }) => [id, status, workspaceId],
|
||||
),
|
||||
).toEqual([
|
||||
["legacy-snapshot", "idle", snapshotAgent.agent.workspaceId],
|
||||
["legacy-buffered", "idle", bufferedAgent.agent.workspaceId],
|
||||
]);
|
||||
|
||||
store.syncHosts([]);
|
||||
useSessionStore.getState().clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("fetches all pages during bootstrap within the active agent scope", async () => {
|
||||
const host = makeHost({
|
||||
serverId: "srv_paged",
|
||||
@@ -4323,6 +4457,362 @@ describe("HostRuntimeStore", () => {
|
||||
useSessionStore.getState().clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("drains queued messages once for snapshot and buffered running transitions", async () => {
|
||||
const host = makeHost({
|
||||
serverId: "srv_queued_transitions",
|
||||
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
|
||||
});
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
fakeClient.setConnectionState({ status: "connected" });
|
||||
const pageTwo = new Deferred<Awaited<ReturnType<DaemonClient["fetchAgents"]>>>();
|
||||
const snapshotAgent = makeFetchAgentsEntry({
|
||||
id: "snapshot-transition",
|
||||
cwd: "/repo",
|
||||
updatedAt: "2026-07-12T10:00:00.000Z",
|
||||
});
|
||||
const bufferedAgent = makeFetchAgentsEntry({
|
||||
id: "buffered-transition",
|
||||
cwd: "/repo",
|
||||
updatedAt: "2026-07-12T10:00:00.000Z",
|
||||
});
|
||||
fakeClient.fetchAgentsResponses.push(
|
||||
makeFetchAgentsPayload({
|
||||
entries: [
|
||||
{ ...snapshotAgent, agent: { ...snapshotAgent.agent, status: "idle" } },
|
||||
{ ...bufferedAgent, agent: { ...bufferedAgent.agent, status: "running" } },
|
||||
],
|
||||
hasMore: true,
|
||||
nextCursor: "page-two",
|
||||
}),
|
||||
pageTwo.promise,
|
||||
);
|
||||
const store = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async () => ({
|
||||
client: fakeClient as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
}),
|
||||
getClientId: async () => "cid_queued_transitions",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(host.serverId, fakeClient as unknown as DaemonClient, 1);
|
||||
sessionStore.setAgents(
|
||||
host.serverId,
|
||||
new Map([
|
||||
[
|
||||
"snapshot-transition",
|
||||
{
|
||||
...replicaAgent(snapshotAgent.agent, host.serverId),
|
||||
turn: {
|
||||
phase: "open",
|
||||
turnId: null,
|
||||
startedAt: null,
|
||||
cancellationRequestId: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
"buffered-transition",
|
||||
{
|
||||
...replicaAgent(bufferedAgent.agent, host.serverId),
|
||||
turn: {
|
||||
phase: "open",
|
||||
turnId: null,
|
||||
startedAt: null,
|
||||
cancellationRequestId: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
sessionStore.setQueuedMessages(
|
||||
host.serverId,
|
||||
new Map([
|
||||
[
|
||||
"snapshot-transition",
|
||||
[{ id: "message-snapshot", text: "snapshot queued", attachments: [] }],
|
||||
],
|
||||
[
|
||||
"buffered-transition",
|
||||
[{ id: "message-buffered", text: "buffered queued", attachments: [] }],
|
||||
],
|
||||
]),
|
||||
);
|
||||
store.syncHosts([host]);
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
const load = store.refreshAgentDirectory({ serverId: host.serverId, subscribe: {} });
|
||||
await fakeClient.waitForFetches(2);
|
||||
fakeClient.agentUpdate({
|
||||
kind: "upsert",
|
||||
agent: { ...bufferedAgent.agent, status: "idle" },
|
||||
project: bufferedAgent.project,
|
||||
});
|
||||
pageTwo.resolve(makeFetchAgentsPayload({ entries: [] }));
|
||||
await load;
|
||||
await fakeClient.waitForSentMessages(2);
|
||||
|
||||
expect(fakeClient.sentAgentMessages.map(([agentId, text]) => [agentId, text])).toEqual([
|
||||
["snapshot-transition", "snapshot queued"],
|
||||
["buffered-transition", "buffered queued"],
|
||||
]);
|
||||
expect(
|
||||
Array.from(useSessionStore.getState().sessions[host.serverId]?.queuedMessages.values() ?? []),
|
||||
).toEqual([[], []]);
|
||||
|
||||
store.syncHosts([]);
|
||||
useSessionStore.getState().clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("submits an automatically drained message through the submission producer", async () => {
|
||||
const host = makeHost({ serverId: "srv_drain_submission" });
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
const send = new Deferred<void>();
|
||||
fakeClient.sendAgentMessageResponses.push(send.promise);
|
||||
const store = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async () => ({
|
||||
client: fakeClient as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
}),
|
||||
getClientId: async () => "cid_drain_submission",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(host.serverId, fakeClient as unknown as DaemonClient, 1);
|
||||
sessionStore.updateSessionServerInfo(host.serverId, {
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
version: null,
|
||||
features: { canonicalSubmittedPrompts: true },
|
||||
});
|
||||
sessionStore.setQueuedMessages(
|
||||
host.serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent",
|
||||
[
|
||||
{
|
||||
id: "queued-with-attachment",
|
||||
text: "read this file",
|
||||
attachments: [
|
||||
{
|
||||
kind: "workspace_file" as const,
|
||||
path: "src/main.ts",
|
||||
selection: { kind: "whole_file" as const },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
store.drainQueuedAgentMessage(host.serverId, "agent");
|
||||
await fakeClient.waitForSentMessages(1);
|
||||
|
||||
// The row and the pending submission must exist while the RPC is still in flight —
|
||||
// the user sees their message and the working footer immediately, exactly as when
|
||||
// they press send.
|
||||
const session = useSessionStore.getState().sessions[host.serverId];
|
||||
const tail = session?.agentStreamTail.get("agent") ?? [];
|
||||
expect(tail).toHaveLength(1);
|
||||
expect(tail[0]).toMatchObject({
|
||||
kind: "user_message",
|
||||
text: "read this file",
|
||||
attachments: [{ type: "text", title: "main.ts", text: "Workspace file: src/main.ts" }],
|
||||
});
|
||||
expect(session?.messageSubmissions.get("agent")).toBeDefined();
|
||||
|
||||
send.resolve();
|
||||
useSessionStore.getState().clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("restores an automatically drained message when sending fails", async () => {
|
||||
const host = makeHost({ serverId: "srv_failed_queue_drain" });
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
fakeClient.sendAgentMessageFailures.push(new Error("connection lost"));
|
||||
const store = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async () => ({
|
||||
client: fakeClient as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
}),
|
||||
getClientId: async () => "cid_failed_queue_drain",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(host.serverId, fakeClient as unknown as DaemonClient, 1);
|
||||
sessionStore.setQueuedMessages(
|
||||
host.serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent",
|
||||
[
|
||||
{ id: "first", text: "retry me", attachments: [] },
|
||||
{ id: "second", text: "keep me behind", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
store.drainQueuedAgentMessage(host.serverId, "agent");
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(fakeClient.sentAgentMessages).toHaveLength(1);
|
||||
expect(
|
||||
useSessionStore.getState().sessions[host.serverId]?.queuedMessages.get("agent"),
|
||||
).toEqual([
|
||||
{ id: "first", text: "retry me", attachments: [] },
|
||||
{ id: "second", text: "keep me behind", attachments: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
useSessionStore.getState().clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("serializes queued-message drains for the same agent", async () => {
|
||||
const host = makeHost({ serverId: "srv_serialized_queue_drain" });
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
const send = new Deferred<void>();
|
||||
fakeClient.sendAgentMessageResponses.push(send.promise);
|
||||
const store = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async () => ({
|
||||
client: fakeClient as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
}),
|
||||
getClientId: async () => "cid_serialized_queue_drain",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(host.serverId, fakeClient as unknown as DaemonClient, 1);
|
||||
sessionStore.setQueuedMessages(
|
||||
host.serverId,
|
||||
new Map([["agent", [{ id: "first", text: "send once", attachments: [] }]]]),
|
||||
);
|
||||
|
||||
store.drainQueuedAgentMessage(host.serverId, "agent");
|
||||
store.drainQueuedAgentMessage(host.serverId, "agent");
|
||||
await fakeClient.waitForSentMessages(1);
|
||||
expect(fakeClient.sentAgentMessages).toHaveLength(1);
|
||||
|
||||
send.resolve();
|
||||
await vi.waitFor(() => {
|
||||
expect(
|
||||
useSessionStore.getState().sessions[host.serverId]?.queuedMessages.get("agent"),
|
||||
).toEqual([]);
|
||||
});
|
||||
useSessionStore.getState().clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("drains a queued message as a steer so a turn the agent just started is not interrupted", async () => {
|
||||
const host = makeHost({ serverId: "srv_steer_queue_drain" });
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
const store = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async () => ({
|
||||
client: fakeClient as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
}),
|
||||
getClientId: async () => "cid_steer_queue_drain",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(host.serverId, fakeClient as unknown as DaemonClient, 1);
|
||||
sessionStore.setQueuedMessages(
|
||||
host.serverId,
|
||||
new Map([["agent", [{ id: "queued", text: "next task", attachments: [] }]]]),
|
||||
);
|
||||
|
||||
store.drainQueuedAgentMessage(host.serverId, "agent");
|
||||
await fakeClient.waitForSentMessages(1);
|
||||
|
||||
expect(fakeClient.sentAgentMessages[0]?.[2]?.activeTurnBehavior).toBe("steer");
|
||||
sessionStore.clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("uses legacy GitHub attachments when draining a queue for an old daemon", async () => {
|
||||
const host = makeHost({ serverId: "srv_legacy_queue_attachment" });
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
const store = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async () => ({
|
||||
client: fakeClient as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
}),
|
||||
getClientId: async () => "cid_legacy_queue_attachment",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(host.serverId, fakeClient as unknown as DaemonClient, 1);
|
||||
sessionStore.updateSessionServerInfo(host.serverId, {
|
||||
serverId: host.serverId,
|
||||
hostname: null,
|
||||
version: "0.1.105",
|
||||
features: { forgeSearch: false },
|
||||
});
|
||||
sessionStore.setQueuedMessages(
|
||||
host.serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent",
|
||||
[
|
||||
{
|
||||
id: "queued-legacy-attachment",
|
||||
text: "review this",
|
||||
attachments: [
|
||||
{
|
||||
kind: "github_pr" as const,
|
||||
item: {
|
||||
kind: "change_request" as const,
|
||||
number: 42,
|
||||
title: "Compatibility fix",
|
||||
url: "https://github.com/acme/repo/pull/42",
|
||||
state: "open" as const,
|
||||
body: "Details",
|
||||
labels: [],
|
||||
baseRefName: "main",
|
||||
headRefName: "fix",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
store.drainQueuedAgentMessage(host.serverId, "agent");
|
||||
await fakeClient.waitForSentMessages(1);
|
||||
|
||||
expect(fakeClient.sentAgentMessages[0]?.[2]?.attachments).toEqual([
|
||||
{
|
||||
type: "github_pr",
|
||||
mimeType: "application/github-pr",
|
||||
number: 42,
|
||||
title: "Compatibility fix",
|
||||
url: "https://github.com/acme/repo/pull/42",
|
||||
body: "Details",
|
||||
baseRefName: "main",
|
||||
headRefName: "fix",
|
||||
},
|
||||
]);
|
||||
sessionStore.clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("applies buffered stale side effects from the accepted page agent", async () => {
|
||||
const host = makeHost({
|
||||
serverId: "srv_buffered_stale_side_effects",
|
||||
|
||||
@@ -82,10 +82,19 @@ import {
|
||||
mountBrowserAutomationDaemonClientHandler,
|
||||
} from "@/desktop/browser/automation/handler";
|
||||
import { schedulesQueryBaseKey } from "@/schedules/aggregated-schedules";
|
||||
import { dispatchComposerAgentMessage, sendQueuedComposerMessageNow } from "@/composer/actions";
|
||||
import {
|
||||
applyFailedStartupSettings,
|
||||
beginStagedProviderSwitch,
|
||||
discardFailedStartupSettings,
|
||||
endStagedProviderSwitch,
|
||||
getFailedStartupSettings,
|
||||
getStagedProviderSwitch,
|
||||
settleCommittedProviderSwitch,
|
||||
} from "@/composer/provider-switch";
|
||||
import { createMessageSubmissionWriter } from "@/composer/submission/writer";
|
||||
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { DirectorySync, type RefreshAgentDirectoryResult } from "@/runtime/directory-sync";
|
||||
import { ReplicaCache } from "@/runtime/replica-cache";
|
||||
import type { ReplicaRowStore } from "@/runtime/replica-cache/row-store";
|
||||
@@ -1917,6 +1926,8 @@ export class HostRuntimeStore {
|
||||
private lastConnectionStatusByServer = new Map<string, HostRuntimeConnectionStatus>();
|
||||
private lastOnlineEpochByServer = new Map<string, number>();
|
||||
private connectionStatusStartedAtByServer = new Map<string, number>();
|
||||
private queuedAgentDrainInFlight = new Set<string>();
|
||||
private queuedAgentDrainPending = new Set<string>();
|
||||
private directorySyncByServer = new Map<string, DirectorySync>();
|
||||
private nextCancellationRequestId = 0;
|
||||
private timelineReplicaByServer = new Map<string, TimelineReplica>();
|
||||
@@ -2160,6 +2171,7 @@ export class HostRuntimeStore {
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: (agentId) => this.drainQueuedAgentMessage(serverId, agentId),
|
||||
markAgentLoading: () => controller.markAgentDirectorySyncLoading(),
|
||||
markAgentReady: () => controller.markAgentDirectorySyncReady(),
|
||||
markAgentError: (error) => controller.markAgentDirectorySyncError(error),
|
||||
@@ -2866,7 +2878,24 @@ export class HostRuntimeStore {
|
||||
}
|
||||
}
|
||||
|
||||
/** Retries or discards the startup settings that failed to apply after a provider switch. */
|
||||
private resumeIdleQueueIfReady(serverId: string, agentId: string): void {
|
||||
const latestSession = useSessionStore.getState().sessions[serverId];
|
||||
const latestAgent = latestSession?.agents.get(agentId);
|
||||
const remainingQueue = latestSession?.queuedMessages.get(agentId);
|
||||
if (
|
||||
latestAgent?.status === "idle" &&
|
||||
remainingQueue &&
|
||||
remainingQueue.length > 0 &&
|
||||
latestSession?.initializingAgents.get(agentId) !== true
|
||||
) {
|
||||
this.drainQueuedAgentMessage(serverId, agentId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Explicitly retries or discards startup settings that failed after a provider switch,
|
||||
* then resumes automatic draining if the chat is idle with queued messages.
|
||||
*/
|
||||
async recoverFailedStartupSettings(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
@@ -2874,6 +2903,8 @@ export class HostRuntimeStore {
|
||||
): Promise<boolean> {
|
||||
if (action === "discard") {
|
||||
discardFailedStartupSettings(serverId, agentId);
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
this.resumeIdleQueueIfReady(serverId, agentId);
|
||||
return true;
|
||||
}
|
||||
const client = useSessionStore.getState().sessions[serverId]?.client;
|
||||
@@ -2881,7 +2912,124 @@ export class HostRuntimeStore {
|
||||
return false;
|
||||
}
|
||||
const result = await applyFailedStartupSettings({ serverId, agentId, client });
|
||||
return result.applied;
|
||||
if (!result.applied) {
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, result.errorMessage);
|
||||
return false;
|
||||
}
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
this.resumeIdleQueueIfReady(serverId, agentId);
|
||||
return true;
|
||||
}
|
||||
|
||||
drainQueuedAgentMessage(serverId: string, agentId: string): void {
|
||||
if (getFailedStartupSettings(serverId, agentId)) {
|
||||
return;
|
||||
}
|
||||
const drainKey = `${serverId}:${agentId}`;
|
||||
if (this.queuedAgentDrainInFlight.has(drainKey)) {
|
||||
this.queuedAgentDrainPending.add(drainKey);
|
||||
return;
|
||||
}
|
||||
const store = useSessionStore.getState();
|
||||
const session = store.sessions[serverId];
|
||||
const queue = session?.queuedMessages.get(agentId);
|
||||
const client = session?.client;
|
||||
if (!client || !queue?.length || session.initializingAgents.get(agentId) === true) {
|
||||
return;
|
||||
}
|
||||
this.queuedAgentDrainInFlight.add(drainKey);
|
||||
this.queuedAgentDrainPending.delete(drainKey);
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
const next = queue[0];
|
||||
let drainSent = false;
|
||||
let drainBlockedBySettingsError: string | null = null;
|
||||
void sendQueuedComposerMessageNow({
|
||||
agentId,
|
||||
messageId: next.id,
|
||||
queue: {
|
||||
read: (queuedAgentId) =>
|
||||
useSessionStore.getState().sessions[serverId]?.queuedMessages.get(queuedAgentId) ?? [],
|
||||
write: (update) => useSessionStore.getState().setQueuedMessages(serverId, update),
|
||||
},
|
||||
submitMessage: async ({ text, attachments }) => {
|
||||
const currentSession = useSessionStore.getState().sessions[serverId];
|
||||
const supportsForgeAttachments = currentSession?.serverInfo?.features?.forgeSearch === true;
|
||||
const supportsProviderSwitching =
|
||||
currentSession?.serverInfo?.features?.providerSwitching === true;
|
||||
const liveProvider = currentSession?.agents.get(agentId)?.provider;
|
||||
const rawStagedSwitch = supportsProviderSwitching
|
||||
? getStagedProviderSwitch(serverId, agentId)
|
||||
: null;
|
||||
const stagedProviderSwitch =
|
||||
rawStagedSwitch && rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
|
||||
if (stagedProviderSwitch) {
|
||||
beginStagedProviderSwitch(serverId, agentId);
|
||||
}
|
||||
try {
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId,
|
||||
text,
|
||||
attachments,
|
||||
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
|
||||
supportsForgeAttachments,
|
||||
}),
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
currentProvider: liveProvider ?? null,
|
||||
currentModel: currentSession?.agents.get(agentId)?.model ?? null,
|
||||
stagedProviderSwitch,
|
||||
onProviderSwitchCommitted: async (agent) => {
|
||||
if (agent) {
|
||||
this.tryAcceptAgentSnapshot(serverId, normalizeAgentSnapshot(agent, serverId));
|
||||
}
|
||||
if (stagedProviderSwitch) {
|
||||
const settled = await settleCommittedProviderSwitch({
|
||||
serverId,
|
||||
agentId,
|
||||
sentDraft: stagedProviderSwitch,
|
||||
committedProvider: agent?.provider ?? null,
|
||||
client,
|
||||
});
|
||||
if (!settled.applied) {
|
||||
drainBlockedBySettingsError = settled.errorMessage;
|
||||
}
|
||||
}
|
||||
},
|
||||
// The queue drains when the agent goes idle, but the agent can start a turn of its own
|
||||
// in that same moment (a wake-up after background work). Steering folds the message
|
||||
// into that turn instead of interrupting it; with no turn running, the daemon starts
|
||||
// a normal one.
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
} finally {
|
||||
if (stagedProviderSwitch) {
|
||||
endStagedProviderSwitch(serverId, agentId);
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
.then((result) => {
|
||||
if (result.status === "submitted") {
|
||||
drainSent = drainBlockedBySettingsError === null;
|
||||
useSessionStore
|
||||
.getState()
|
||||
.setQueuedSendError(serverId, agentId, drainBlockedBySettingsError);
|
||||
} else if (result.status === "failed") {
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, result.errorMessage);
|
||||
console.error("[HostRuntime] failed to drain queued agent message", {
|
||||
serverId,
|
||||
agentId,
|
||||
error: result.errorMessage,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
})
|
||||
.finally(() => {
|
||||
this.queuedAgentDrainInFlight.delete(drainKey);
|
||||
const hadPendingDrain = this.queuedAgentDrainPending.delete(drainKey);
|
||||
if (!drainSent || !hadPendingDrain) return;
|
||||
this.resumeIdleQueueIfReady(serverId, agentId);
|
||||
});
|
||||
}
|
||||
|
||||
applyAgentTurnLiveness(
|
||||
@@ -3106,6 +3254,7 @@ export class HostRuntimeStore {
|
||||
serverId,
|
||||
replica,
|
||||
replaceDemandedAgentIds: (agentIds) => directory.setAgentRouteDemand(agentIds),
|
||||
drainQueuedAgentMessage: (agentId) => this.drainQueuedAgentMessage(serverId, agentId),
|
||||
applyTurnLiveness: (agentId, transitions) =>
|
||||
directory.applyAgentTurnLiveness(agentId, transitions),
|
||||
ports: {
|
||||
|
||||
@@ -186,6 +186,7 @@ async function runAttachmentGc(): Promise<void> {
|
||||
|
||||
const sessions = useSessionStore.getState().sessions;
|
||||
for (const session of Object.values(sessions)) {
|
||||
collectQueuedMessageAttachmentIds(session, referencedIds);
|
||||
collectStreamUserImageIds(session.agentStreamTail, referencedIds);
|
||||
collectStreamUserImageIds(session.agentStreamHead, referencedIds);
|
||||
}
|
||||
@@ -209,6 +210,21 @@ async function runAttachmentGc(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
function collectQueuedMessageAttachmentIds(
|
||||
session: SessionState,
|
||||
referencedIds: Set<string>,
|
||||
): void {
|
||||
for (const queue of session.queuedMessages.values()) {
|
||||
for (const queuedMessage of queue) {
|
||||
for (const attachment of queuedMessage.attachments) {
|
||||
if (attachment.kind === "image") {
|
||||
referencedIds.add(attachment.metadata.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function collectStreamUserImageIds(
|
||||
streams: SessionState["agentStreamTail"],
|
||||
referencedIds: Set<string>,
|
||||
|
||||
@@ -148,30 +148,6 @@ describe("draft-store normalization", () => {
|
||||
).toEqual({ text: "Review this", attachments: [attachment] });
|
||||
});
|
||||
|
||||
it("preserves attachments restored from a queued message when hydrating a draft", () => {
|
||||
const attachment = {
|
||||
kind: "agent_attachment" as const,
|
||||
attachment: {
|
||||
type: "uploaded_file" as const,
|
||||
id: "upload-1",
|
||||
fileName: "photo.png",
|
||||
mimeType: "image/png",
|
||||
size: 42,
|
||||
path: "/tmp/photo.png",
|
||||
role: "image" as const,
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
toDraftInputIfReady({
|
||||
input: { text: "Look at this", attachments: [attachment] },
|
||||
lifecycle: "active",
|
||||
updatedAt: 1,
|
||||
version: 1,
|
||||
}),
|
||||
).toEqual({ text: "Look at this", attachments: [attachment] });
|
||||
});
|
||||
|
||||
it("preserves workspace file selections when hydrating a draft", () => {
|
||||
const attachment = {
|
||||
kind: "workspace_file" as const,
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
type UserComposerAttachment,
|
||||
} from "@/attachments/types";
|
||||
import { PluginResourceComposerAttachmentSchema } from "@/plugins/attachments";
|
||||
import { AgentAttachmentSchema } from "@getpaseo/protocol/messages";
|
||||
import { z } from "zod";
|
||||
|
||||
export const DRAFT_STORE_VERSION = 5;
|
||||
@@ -113,7 +112,6 @@ export const UserComposerAttachmentSchema: z.ZodType<UserComposerAttachment> = z
|
||||
z.strictObject({ kind: z.literal("forge_change_request"), item: ChangeRequestItemSchema }),
|
||||
z.strictObject({ kind: z.literal("github_issue"), item: IssueItemSchema }),
|
||||
PluginResourceComposerAttachmentSchema,
|
||||
z.strictObject({ kind: z.literal("agent_attachment"), attachment: AgentAttachmentSchema }),
|
||||
z.strictObject({
|
||||
kind: z.literal("github_pr"),
|
||||
item: ChangeRequestItemSchema,
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
type MessageSubmissionRejectionOutcome,
|
||||
} from "@/composer/submission/model";
|
||||
import type { PendingPermission } from "@/types/shared";
|
||||
import type { ComposerAttachment } from "@/attachments/types";
|
||||
import type { AgentLifecycleStatus } from "@getpaseo/protocol/agent-lifecycle";
|
||||
import type {
|
||||
AgentPermissionRequest,
|
||||
@@ -567,6 +568,13 @@ export interface SessionState {
|
||||
|
||||
// File explorer
|
||||
fileExplorer: Map<string, AgentFileExplorerState>;
|
||||
|
||||
// Queued messages
|
||||
queuedMessages: Map<
|
||||
string,
|
||||
Array<{ id: string; text: string; attachments: ComposerAttachment[] }>
|
||||
>;
|
||||
queuedSendErrors: Map<string, string>;
|
||||
}
|
||||
|
||||
// Global store state
|
||||
@@ -752,6 +760,17 @@ interface SessionStoreActions {
|
||||
| ((prev: Map<string, AgentFileExplorerState>) => Map<string, AgentFileExplorerState>),
|
||||
) => void;
|
||||
|
||||
// Queued messages
|
||||
setQueuedMessages: (
|
||||
serverId: string,
|
||||
value:
|
||||
| Map<string, Array<{ id: string; text: string; attachments: ComposerAttachment[] }>>
|
||||
| ((
|
||||
prev: Map<string, Array<{ id: string; text: string; attachments: ComposerAttachment[] }>>,
|
||||
) => Map<string, Array<{ id: string; text: string; attachments: ComposerAttachment[] }>>),
|
||||
) => void;
|
||||
setQueuedSendError: (serverId: string, agentId: string, error: string | null) => void;
|
||||
|
||||
// Hydration
|
||||
setHasHydratedAgents: (serverId: string, hydrated: boolean) => void;
|
||||
setHasHydratedWorkspaces: (serverId: string, hydrated: boolean) => void;
|
||||
@@ -809,6 +828,8 @@ function createInitialSessionState(
|
||||
restoringWorkspaces: new Map(),
|
||||
pendingPermissions: new Map(),
|
||||
fileExplorer: new Map(),
|
||||
queuedMessages: new Map(),
|
||||
queuedSendErrors: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2015,6 +2036,53 @@ export const useSessionStore = create<SessionStore>()(
|
||||
});
|
||||
},
|
||||
|
||||
// Queued messages
|
||||
setQueuedMessages: (serverId, value) => {
|
||||
set((prev) => {
|
||||
const session = prev.sessions[serverId];
|
||||
if (!session) {
|
||||
return prev;
|
||||
}
|
||||
const nextValue = typeof value === "function" ? value(session.queuedMessages) : value;
|
||||
if (session.queuedMessages === nextValue) {
|
||||
return prev;
|
||||
}
|
||||
return {
|
||||
...prev,
|
||||
sessions: {
|
||||
...prev.sessions,
|
||||
[serverId]: { ...session, queuedMessages: nextValue },
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
setQueuedSendError: (serverId, agentId, error) => {
|
||||
set((prev) => {
|
||||
const session = prev.sessions[serverId];
|
||||
if (!session) {
|
||||
return prev;
|
||||
}
|
||||
const existing = session.queuedSendErrors.get(agentId) ?? null;
|
||||
if (existing === error) {
|
||||
return prev;
|
||||
}
|
||||
const next = new Map(session.queuedSendErrors);
|
||||
if (error === null) {
|
||||
next.delete(agentId);
|
||||
} else {
|
||||
next.set(agentId, error);
|
||||
}
|
||||
return {
|
||||
...prev,
|
||||
sessions: {
|
||||
...prev.sessions,
|
||||
[serverId]: { ...session, queuedSendErrors: next },
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
// Hydration
|
||||
setHasHydratedAgents: (serverId, hydrated) => {
|
||||
set((prev) => {
|
||||
|
||||
@@ -86,6 +86,7 @@ function createOwner(
|
||||
serverId: SERVER_ID,
|
||||
replica,
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
drainQueuedAgentMessage: () => undefined,
|
||||
applyTurnLiveness,
|
||||
ports: {
|
||||
canCheckFreshness: () => checksFreshness,
|
||||
@@ -235,6 +236,7 @@ describe("viewed timeline persistence", () => {
|
||||
serverId: SERVER_ID,
|
||||
replica,
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
drainQueuedAgentMessage: () => undefined,
|
||||
applyTurnLiveness: () => undefined,
|
||||
ports: {
|
||||
canCheckFreshness: () => false,
|
||||
@@ -1733,6 +1735,7 @@ describe("create handoff lifetime", () => {
|
||||
serverId: SERVER_ID,
|
||||
replica,
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
drainQueuedAgentMessage: () => undefined,
|
||||
applyTurnLiveness: () => undefined,
|
||||
ports: {
|
||||
canCheckFreshness: () => false,
|
||||
@@ -1902,6 +1905,7 @@ describe("a chat that was empty when it went offline", () => {
|
||||
serverId: SERVER_ID,
|
||||
replica,
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
drainQueuedAgentMessage: () => undefined,
|
||||
applyTurnLiveness: () => undefined,
|
||||
ports: {
|
||||
canCheckFreshness: () => true,
|
||||
@@ -2313,7 +2317,11 @@ describe("archived timeline lifetime", () => {
|
||||
},
|
||||
) {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const directory = new AgentDirectoryReplica(SERVER_ID, () => undefined);
|
||||
const directory = new AgentDirectoryReplica(
|
||||
SERVER_ID,
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
const workspaces = new WorkspaceDirectoryReplica(SERVER_ID);
|
||||
workspaces.commitSnapshot(
|
||||
{
|
||||
@@ -2335,6 +2343,7 @@ describe("archived timeline lifetime", () => {
|
||||
serverId: SERVER_ID,
|
||||
replica,
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
drainQueuedAgentMessage: () => undefined,
|
||||
applyTurnLiveness: () => undefined,
|
||||
ports: {
|
||||
canCheckFreshness: () => false,
|
||||
|
||||
@@ -286,7 +286,9 @@ function finalizeProcessedTimeline(input: {
|
||||
agentId: string;
|
||||
initKey: string;
|
||||
result: ProcessTimelineResponseOutput;
|
||||
synchronized: boolean;
|
||||
recoverGap: (agentId: string, cursor: { epoch: string; endSeq: number }) => void;
|
||||
drainQueuedAgentMessage: (agentId: string) => void;
|
||||
}): void {
|
||||
for (const effect of input.result.sideEffects) {
|
||||
if (effect.type === "catch_up") input.recoverGap(input.agentId, effect.cursor);
|
||||
@@ -294,6 +296,11 @@ function finalizeProcessedTimeline(input: {
|
||||
if (input.result.clearInitializing) {
|
||||
clearAgentInitializingFlag(input.serverId, input.agentId);
|
||||
}
|
||||
if (input.synchronized) {
|
||||
const session = useSessionStore.getState().sessions[input.serverId];
|
||||
const agent = session?.agents.get(input.agentId) ?? session?.agentDetails.get(input.agentId);
|
||||
if (agent && agent.turn.phase === "idle") input.drainQueuedAgentMessage(input.agentId);
|
||||
}
|
||||
if (input.result.initResolution === "resolve") resolveInitDeferred(input.initKey);
|
||||
}
|
||||
|
||||
@@ -302,6 +309,7 @@ function applyAuthoritativeTimelineResponse(input: {
|
||||
payload: TimelineResponsePayload;
|
||||
cachedCursor?: AgentTimelineCursorState;
|
||||
recoverGap: (agentId: string, cursor: { epoch: string; endSeq: number }) => void;
|
||||
drainQueuedAgentMessage: (agentId: string) => void;
|
||||
}): boolean {
|
||||
const { serverId, payload } = input;
|
||||
const agentId = payload.agentId;
|
||||
@@ -339,7 +347,9 @@ function applyAuthoritativeTimelineResponse(input: {
|
||||
agentId,
|
||||
initKey,
|
||||
result,
|
||||
synchronized,
|
||||
recoverGap: input.recoverGap,
|
||||
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -527,6 +537,7 @@ export function createViewedTimelineOwner(input: {
|
||||
serverId: string;
|
||||
replica: TimelineReplica;
|
||||
replaceDemandedAgentIds: (agentIds: string[]) => void;
|
||||
drainQueuedAgentMessage: (agentId: string) => void;
|
||||
applyTurnLiveness: (agentId: string, transitions: readonly TurnLivenessTransition[]) => void;
|
||||
ports: ViewedTimelineOwnerPorts;
|
||||
}): ViewedTimelineOwner {
|
||||
@@ -563,6 +574,7 @@ export function createViewedTimelineOwner(input: {
|
||||
payload: buildCurrentTimelinePage(agentId, cursor),
|
||||
cachedCursor: input.replica.readRange(agentId),
|
||||
recoverGap: (id, gapCursor) => sync.recoverGap(id, gapCursor),
|
||||
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
|
||||
});
|
||||
if (accepted) input.replica.timelineUpdated(agentId);
|
||||
},
|
||||
@@ -620,6 +632,7 @@ export function createViewedTimelineOwner(input: {
|
||||
payload,
|
||||
cachedCursor: input.replica.readRange(payload.agentId),
|
||||
recoverGap: (agentId, cursor) => sync.recoverGap(agentId, cursor),
|
||||
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
|
||||
});
|
||||
if (accepted) input.replica.timelineUpdated(payload.agentId);
|
||||
return "applied";
|
||||
|
||||
@@ -206,6 +206,10 @@ describe("replaceFetchedAgentDirectory", () => {
|
||||
};
|
||||
store.setAgents(serverId, new Map([[agentId, agent]]));
|
||||
store.setAgentDetails(serverId, new Map([[agentId, agent]]));
|
||||
store.setQueuedMessages(
|
||||
serverId,
|
||||
new Map([[agentId, [{ id: "queued", text: "next", attachments: [] }]]]),
|
||||
);
|
||||
store.setAgentTimelineCursor(
|
||||
serverId,
|
||||
new Map([[agentId, { epoch: "epoch", startSeq: 1, endSeq: 2 }]]),
|
||||
@@ -225,6 +229,7 @@ describe("replaceFetchedAgentDirectory", () => {
|
||||
expect({
|
||||
agents: session?.agents.has(agentId),
|
||||
details: session?.agentDetails.has(agentId),
|
||||
queued: session?.queuedMessages.has(agentId),
|
||||
cursor: session?.agentTimelineCursor.has(agentId),
|
||||
permissions: session?.pendingPermissions.size,
|
||||
initializing: session?.initializingAgents.has(agentId),
|
||||
@@ -232,6 +237,7 @@ describe("replaceFetchedAgentDirectory", () => {
|
||||
}).toEqual({
|
||||
agents: false,
|
||||
details: false,
|
||||
queued: false,
|
||||
cursor: kind === "directory",
|
||||
permissions: 0,
|
||||
initializing: false,
|
||||
@@ -289,7 +295,7 @@ describe("replaceFetchedAgentDirectory", () => {
|
||||
store.flushAgentLastActivity();
|
||||
setAgentArchiving({ queryClient, serverId, agentId, isArchiving: true });
|
||||
|
||||
projection.applyDelta({
|
||||
const staleResult = projection.applyDelta({
|
||||
kind: "upsert",
|
||||
agent: {
|
||||
...current,
|
||||
@@ -311,6 +317,7 @@ describe("replaceFetchedAgentDirectory", () => {
|
||||
status: agent?.status,
|
||||
usage: agent?.lastUsage,
|
||||
workspaceId: agent?.workspaceId,
|
||||
stoppedRunning: staleResult.stoppedRunning,
|
||||
permissions: Array.from(state.sessions[serverId]?.pendingPermissions.values() ?? []).map(
|
||||
({ request }) => request.id,
|
||||
),
|
||||
@@ -321,6 +328,7 @@ describe("replaceFetchedAgentDirectory", () => {
|
||||
status: "running",
|
||||
usage: { inputTokens: 20, outputTokens: 8 },
|
||||
workspaceId: "legacy-workspace",
|
||||
stoppedRunning: false,
|
||||
permissions: ["current-permission"],
|
||||
archivePending: true,
|
||||
activity: "2026-07-12T11:00:00.000Z",
|
||||
|
||||
@@ -3,6 +3,13 @@ import { createAssistantMarkdownParser } from "./assistant-markdown-parser";
|
||||
const markdownRenderer = createAssistantMarkdownParser();
|
||||
// Disable linkify for selection HTML so text from unwrapped links stays unlinked.
|
||||
const unlinkedMarkdownRenderer = createAssistantMarkdownParser().set({ linkify: false });
|
||||
// Selection Markdown escapes every literal `<`, so a bare `<br>` is a table cell's line break.
|
||||
unlinkedMarkdownRenderer.inline.ruler.after("escape", "cell_line_break", (state, silent) => {
|
||||
if (!state.src.startsWith("<br>", state.pos)) return false;
|
||||
if (!silent) state.push("hardbreak", "br", 0);
|
||||
state.pos += "<br>".length;
|
||||
return true;
|
||||
});
|
||||
|
||||
type ClipboardMimeType = "text/plain" | "text/html";
|
||||
|
||||
|
||||
@@ -44,7 +44,6 @@ import type {
|
||||
RestartRequestedStatusPayloadSchema,
|
||||
ShutdownRequestedStatusPayloadSchema,
|
||||
DaemonUpdateResponseSchema,
|
||||
ActiveTurnBehavior,
|
||||
AgentActiveTurnBehavior,
|
||||
ServerInfoStatusPayload,
|
||||
TerminalDefaultColors,
|
||||
@@ -511,7 +510,6 @@ export interface AgentMessageReceipt {
|
||||
deliveryStatus?: "queued";
|
||||
activeTurnBehavior?: AgentActiveTurnBehavior;
|
||||
guidance?: string;
|
||||
messageId?: string;
|
||||
}
|
||||
|
||||
export interface SendMessageOptions {
|
||||
@@ -538,14 +536,6 @@ export interface SwitchAgentProviderOptions {
|
||||
messageId?: string;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments?: AgentProviderSwitchRequest["attachments"];
|
||||
/** Wait in the host's message queue and switch after the running turn ends. */
|
||||
activeTurnBehavior?: "queue";
|
||||
}
|
||||
|
||||
export interface SwitchAgentProviderResult {
|
||||
agent?: AgentSnapshotPayload;
|
||||
/** Set when the host queued the switch instead of running it. */
|
||||
deliveryStatus?: "queued";
|
||||
}
|
||||
|
||||
export class AgentProviderSwitchError extends Error {
|
||||
@@ -1149,20 +1139,6 @@ type CorrelatedResponsePayload<TType extends CorrelatedResponseType> =
|
||||
export type AgentBackgroundWorkListPayload =
|
||||
CorrelatedResponsePayload<"agent.background_work.list.response">;
|
||||
export type AgentBackgroundWorkItem = AgentBackgroundWorkListPayload["items"][number];
|
||||
export type AgentQueueListPayload = CorrelatedResponsePayload<"agent.queue.list.response">;
|
||||
export type AgentQueueItem = AgentQueueListPayload["items"][number];
|
||||
export interface AgentQueueListResult {
|
||||
held: boolean;
|
||||
items: AgentQueueItem[];
|
||||
}
|
||||
export type AgentQueueWithdrawPayload = CorrelatedResponsePayload<"agent.queue.withdraw.response">;
|
||||
export type AgentQueueWithdrawResult =
|
||||
| { withdrawn: true; item: AgentQueueItem }
|
||||
| { withdrawn: false; reason: "not_found" | "already_dispatching" };
|
||||
export type AgentQueuePromotePayload = CorrelatedResponsePayload<"agent.queue.promote.response">;
|
||||
export type AgentQueuePromoteResult =
|
||||
| { promoted: true }
|
||||
| { promoted: false; reason: "not_found" | "already_dispatching" };
|
||||
|
||||
type PluginCatalogResponseEntry =
|
||||
CorrelatedResponsePayload<"plugin.catalog.get.response">["plugins"][number];
|
||||
@@ -1810,6 +1786,8 @@ export class DaemonClientCore {
|
||||
// An endpoint security policy close cannot be fixed by retrying.
|
||||
const securityFailure = describeEndpointSecurityClose(event);
|
||||
if (securityFailure) this.setReconnectEnabled(false);
|
||||
// A transport error may already have scheduled this socket's retry before its close.
|
||||
if (this.reconnectTimeout && !securityFailure && !this.authFailureReasonValue) return;
|
||||
const reason = this.authFailureReasonValue
|
||||
? new DaemonAuthenticationError(this.authFailureReasonValue).message
|
||||
: (securityFailure ?? describeTransportClose(event));
|
||||
@@ -3288,6 +3266,8 @@ export class DaemonClientCore {
|
||||
listProjectSuggestions(options?: ProjectSuggestionsOptions): Promise<ProjectSuggestionsPayload> {
|
||||
return this.sendNamespacedCorrelatedSessionRequest<"project.suggestions.response">({
|
||||
requestId: options?.requestId,
|
||||
// Provider session discovery can take 90 seconds before the daemon resolves project roots.
|
||||
timeout: 120_000,
|
||||
message: {
|
||||
type: "project.suggestions.request",
|
||||
...(options?.providers ? { providers: options.providers } : {}),
|
||||
@@ -4267,79 +4247,6 @@ export class DaemonClientCore {
|
||||
}
|
||||
}
|
||||
|
||||
async listAgentQueue(
|
||||
agentId: string,
|
||||
options: { requestId?: string; timeout?: number } = {},
|
||||
): Promise<AgentQueueListResult> {
|
||||
this.assertAgentMessageQueueSupported();
|
||||
const payload = await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.list.response">({
|
||||
requestId: options.requestId,
|
||||
timeout: options.timeout,
|
||||
message: { type: "agent.queue.list.request", agentId },
|
||||
});
|
||||
if (payload.error) throw new Error(payload.error);
|
||||
return { held: payload.held, items: payload.items };
|
||||
}
|
||||
|
||||
async withdrawAgentQueueItem(
|
||||
agentId: string,
|
||||
messageId: string,
|
||||
options: { requestId?: string; timeout?: number } = {},
|
||||
): Promise<AgentQueueWithdrawResult> {
|
||||
this.assertAgentMessageQueueSupported();
|
||||
const payload =
|
||||
await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.withdraw.response">({
|
||||
requestId: options.requestId,
|
||||
timeout: options.timeout,
|
||||
message: { type: "agent.queue.withdraw.request", agentId, messageId },
|
||||
});
|
||||
if (payload.error) throw new Error(payload.error);
|
||||
if (payload.withdrawn) {
|
||||
if (!payload.item) throw new Error("Missing withdrawn queue item.");
|
||||
return { withdrawn: true, item: payload.item };
|
||||
}
|
||||
if (!payload.reason) throw new Error("Missing queue withdraw failure reason.");
|
||||
return { withdrawn: false, reason: payload.reason };
|
||||
}
|
||||
|
||||
async promoteAgentQueueItem(
|
||||
agentId: string,
|
||||
messageId: string,
|
||||
activeTurnBehavior: ActiveTurnBehavior,
|
||||
options: { requestId?: string; timeout?: number } = {},
|
||||
): Promise<AgentQueuePromoteResult> {
|
||||
this.assertAgentMessageQueueSupported();
|
||||
const payload =
|
||||
await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.promote.response">({
|
||||
requestId: options.requestId,
|
||||
timeout: options.timeout,
|
||||
message: {
|
||||
type: "agent.queue.promote.request",
|
||||
agentId,
|
||||
messageId,
|
||||
activeTurnBehavior,
|
||||
},
|
||||
});
|
||||
if (payload.error) throw new Error(payload.error);
|
||||
if (payload.promoted) return { promoted: true };
|
||||
if (!payload.reason) throw new Error("Missing queue promote failure reason.");
|
||||
return { promoted: false, reason: payload.reason };
|
||||
}
|
||||
|
||||
observeAgentQueue(
|
||||
options: { signal?: AbortSignal } = {},
|
||||
): OwnedSubscription<CorrelatedResponsePayload<"session.events.set_subscription.response">> {
|
||||
this.assertAgentMessageQueueSupported();
|
||||
return this.observeEvents(["agent.queue.update"], options);
|
||||
}
|
||||
|
||||
private assertAgentMessageQueueSupported(): void {
|
||||
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
|
||||
if (this.lastServerInfoMessage?.features?.agentMessageQueue !== true) {
|
||||
throw new Error("Update the host to view or manage an agent's message queue.");
|
||||
}
|
||||
}
|
||||
|
||||
async fetchProviderSubagentTimeline(
|
||||
parentAgentId: string,
|
||||
subagentId: string,
|
||||
@@ -4502,19 +4409,16 @@ export class DaemonClientCore {
|
||||
...(payload.deliveryStatus ? { deliveryStatus: payload.deliveryStatus } : {}),
|
||||
...(payload.activeTurnBehavior ? { activeTurnBehavior: payload.activeTurnBehavior } : {}),
|
||||
...(payload.guidance ? { guidance: payload.guidance } : {}),
|
||||
...(payload.messageId ? { messageId: payload.messageId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async switchAgentProvider(
|
||||
agentId: string,
|
||||
options: SwitchAgentProviderOptions,
|
||||
): Promise<SwitchAgentProviderResult> {
|
||||
): Promise<{ agent?: AgentSnapshotPayload }> {
|
||||
if (this.lastServerInfoMessage?.features?.providerSwitching !== true) {
|
||||
throw new Error("Update the Paseo host to switch providers in an existing chat.");
|
||||
}
|
||||
// An older host drops the field and switches right away, so require the queue.
|
||||
if (options.activeTurnBehavior === "queue") this.assertAgentMessageQueueSupported();
|
||||
const requestId = this.createRequestId();
|
||||
const messageId = options.messageId ?? crypto.randomUUID();
|
||||
const message = this.codec.parseInbound({
|
||||
@@ -4534,7 +4438,6 @@ export class DaemonClientCore {
|
||||
messageId,
|
||||
images: options.images,
|
||||
attachments: options.attachments,
|
||||
...(options.activeTurnBehavior ? { activeTurnBehavior: options.activeTurnBehavior } : {}),
|
||||
});
|
||||
const payload: AgentProviderSwitchResponseMessage["payload"] = await this.sendRequest({
|
||||
requestId,
|
||||
@@ -4556,10 +4459,7 @@ export class DaemonClientCore {
|
||||
payload.agent,
|
||||
);
|
||||
}
|
||||
return {
|
||||
...(payload.agent ? { agent: payload.agent } : {}),
|
||||
...(payload.deliveryStatus ? { deliveryStatus: payload.deliveryStatus } : {}),
|
||||
};
|
||||
return payload.agent ? { agent: payload.agent } : {};
|
||||
}
|
||||
|
||||
/** The behavior to put on the wire for this host. */
|
||||
|
||||
@@ -3020,6 +3020,34 @@ test("foreground keeps a connect attempt that just started", async () => {
|
||||
expect(client.getConnectionState().status).toBe("connected");
|
||||
});
|
||||
|
||||
test("a handshake error followed by a close consumes one reconnect attempt", async () => {
|
||||
useHeartbeatClock();
|
||||
const [first, failed, recovered] = [
|
||||
new FakeDaemon(),
|
||||
new FakeDaemon(),
|
||||
new FakeDaemon(),
|
||||
] as const;
|
||||
const { client, attempts } = connectThroughReplacements("error-and-close", [
|
||||
first,
|
||||
failed,
|
||||
recovered,
|
||||
]);
|
||||
const connection = client.connect();
|
||||
first.openConnection();
|
||||
await connection;
|
||||
first.daemonClosesWith("connection lost");
|
||||
await vi.advanceTimersByTimeAsync(1_500);
|
||||
expect(attempts()).toBe(2);
|
||||
failed.triggerError(new Error("read ECONNRESET"));
|
||||
failed.daemonClosesWith("abnormal closure");
|
||||
await vi.advanceTimersByTimeAsync(2_999);
|
||||
expect(attempts()).toBe(2);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(attempts()).toBe(3);
|
||||
recovered.openConnection();
|
||||
expect(client.getConnectionState().status).toBe("connected");
|
||||
});
|
||||
|
||||
test("foreground resets the retry delay after failed connections in the background", async () => {
|
||||
useHeartbeatClock();
|
||||
const daemons = Array.from({ length: 7 }, () => new FakeDaemon());
|
||||
@@ -9480,6 +9508,40 @@ test("rejects usage requests when the host has neither capability", async () =>
|
||||
expect(mock.sent).toEqual([]);
|
||||
});
|
||||
|
||||
test("project suggestions accept a slow provider response past the default deadline", async () => {
|
||||
useHeartbeatClock();
|
||||
const mock = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "slow-projects",
|
||||
logger: noopLogger,
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => mock.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
const connected = client.connect();
|
||||
mock.triggerOpen();
|
||||
await connected;
|
||||
const requestId = "slow-source";
|
||||
const payload = {
|
||||
requestId,
|
||||
suggestions: [
|
||||
{
|
||||
rootPath: "/repo",
|
||||
displayName: "repo",
|
||||
sessionCount: 1,
|
||||
providerIds: ["opencode"],
|
||||
lastActivityAt: "2026-11-01T00:00:00Z",
|
||||
},
|
||||
],
|
||||
providerErrors: [],
|
||||
};
|
||||
const result = client.listProjectSuggestions({ requestId }).catch((error: unknown) => error);
|
||||
await vi.advanceTimersByTimeAsync(65_000);
|
||||
mock.triggerMessage(wrapSessionMessage({ type: "project.suggestions.response", payload }));
|
||||
expect(await result).toEqual(payload);
|
||||
});
|
||||
|
||||
test("usage request timeout detaches its update listener", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
@@ -9661,7 +9723,6 @@ describe("agent sender active-turn behaviors", () => {
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "queue",
|
||||
guidance: "Queued, not delivered yet.",
|
||||
messageId: "msg-queued-1",
|
||||
});
|
||||
expect(request.activeTurnBehavior).toBe("queue");
|
||||
expect("sourceAgentId" in request).toBe(false);
|
||||
@@ -9669,7 +9730,6 @@ describe("agent sender active-turn behaviors", () => {
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "queue",
|
||||
guidance: "Queued, not delivered yet.",
|
||||
messageId: "msg-queued-1",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11327,198 +11387,3 @@ describe("findWorkspace", () => {
|
||||
await expect(finding).resolves.toMatchObject({ id: targetId });
|
||||
});
|
||||
});
|
||||
|
||||
describe("agent queue RPCs and observation", () => {
|
||||
const QUEUED_ITEM = {
|
||||
id: "msg-1",
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T08:00:00.000Z",
|
||||
text: "Check tests",
|
||||
sender: { kind: "user" as const },
|
||||
held: false,
|
||||
state: "queued" as const,
|
||||
};
|
||||
|
||||
async function connectQueueClient(features: Record<string, boolean>) {
|
||||
const transport = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "queue-client",
|
||||
transportFactory: () => transport.transport,
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
clients.push(client);
|
||||
const connecting = client.connect();
|
||||
transport.triggerOpen({ features });
|
||||
await connecting;
|
||||
return { client, transport };
|
||||
}
|
||||
|
||||
test("gates queue methods when host lacks agentMessageQueue", async () => {
|
||||
const { client, transport } = await connectQueueClient({ ownedSubscriptions: true });
|
||||
await expect(client.listAgentQueue("agent-a")).rejects.toThrow("Update the host");
|
||||
await expect(client.withdrawAgentQueueItem("agent-a", "msg-1")).rejects.toThrow(
|
||||
"Update the host",
|
||||
);
|
||||
await expect(client.promoteAgentQueueItem("agent-a", "msg-1", "steer")).rejects.toThrow(
|
||||
"Update the host",
|
||||
);
|
||||
expect(() => client.observeAgentQueue()).toThrow("Update the host");
|
||||
expect(transport.sent).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("lists, withdraws, promotes, and observes agent queue", async () => {
|
||||
const { client, transport } = await connectQueueClient({
|
||||
ownedSubscriptions: true,
|
||||
agentMessageQueue: true,
|
||||
});
|
||||
|
||||
const listPromise = client.listAgentQueue("agent-a");
|
||||
const listReq = parseSentFrame(transport.sent.at(-1));
|
||||
expect(listReq).toMatchObject({ type: "agent.queue.list.request", agentId: "agent-a" });
|
||||
transport.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "agent.queue.list.response",
|
||||
payload: {
|
||||
requestId: listReq.requestId,
|
||||
agentId: "agent-a",
|
||||
held: true,
|
||||
items: [QUEUED_ITEM],
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await expect(listPromise).resolves.toEqual({ held: true, items: [QUEUED_ITEM] });
|
||||
|
||||
const withdrawOk = client.withdrawAgentQueueItem("agent-a", "msg-1");
|
||||
const withdrawReq1 = parseSentFrame(transport.sent.at(-1));
|
||||
expect(withdrawReq1).toMatchObject({
|
||||
type: "agent.queue.withdraw.request",
|
||||
agentId: "agent-a",
|
||||
messageId: "msg-1",
|
||||
});
|
||||
transport.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "agent.queue.withdraw.response",
|
||||
payload: {
|
||||
requestId: withdrawReq1.requestId,
|
||||
agentId: "agent-a",
|
||||
messageId: "msg-1",
|
||||
withdrawn: true,
|
||||
item: QUEUED_ITEM,
|
||||
reason: null,
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await expect(withdrawOk).resolves.toEqual({ withdrawn: true, item: QUEUED_ITEM });
|
||||
|
||||
const withdrawMiss = client.withdrawAgentQueueItem("agent-a", "msg-2");
|
||||
const withdrawReq2 = parseSentFrame(transport.sent.at(-1));
|
||||
transport.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "agent.queue.withdraw.response",
|
||||
payload: {
|
||||
requestId: withdrawReq2.requestId,
|
||||
agentId: "agent-a",
|
||||
messageId: "msg-2",
|
||||
withdrawn: false,
|
||||
item: null,
|
||||
reason: "already_dispatching",
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await expect(withdrawMiss).resolves.toEqual({
|
||||
withdrawn: false,
|
||||
reason: "already_dispatching",
|
||||
});
|
||||
|
||||
const promoteOk = client.promoteAgentQueueItem("agent-a", "msg-1", "interrupt");
|
||||
const promoteReq1 = parseSentFrame(transport.sent.at(-1));
|
||||
expect(promoteReq1).toMatchObject({
|
||||
type: "agent.queue.promote.request",
|
||||
agentId: "agent-a",
|
||||
messageId: "msg-1",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
transport.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "agent.queue.promote.response",
|
||||
payload: {
|
||||
requestId: promoteReq1.requestId,
|
||||
agentId: "agent-a",
|
||||
messageId: "msg-1",
|
||||
promoted: true,
|
||||
reason: null,
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await expect(promoteOk).resolves.toEqual({ promoted: true });
|
||||
|
||||
const promoteMiss = client.promoteAgentQueueItem("agent-a", "msg-9", "steer");
|
||||
const promoteReq2 = parseSentFrame(transport.sent.at(-1));
|
||||
transport.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "agent.queue.promote.response",
|
||||
payload: {
|
||||
requestId: promoteReq2.requestId,
|
||||
agentId: "agent-a",
|
||||
messageId: "msg-9",
|
||||
promoted: false,
|
||||
reason: "not_found",
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await expect(promoteMiss).resolves.toEqual({ promoted: false, reason: "not_found" });
|
||||
|
||||
const updates: unknown[] = [];
|
||||
const observation = client.observeAgentQueue();
|
||||
observation.subscribe({
|
||||
snapshot: () => {},
|
||||
update: (message) => updates.push(message),
|
||||
error: () => {},
|
||||
});
|
||||
const subReq = parseSentFrame(transport.sent.at(-1));
|
||||
expect(subReq).toMatchObject({
|
||||
type: "session.events.set_subscription.request",
|
||||
events: ["agent.queue.update"],
|
||||
});
|
||||
transport.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "session.events.set_subscription.response",
|
||||
payload: { requestId: subReq.requestId, subscriptionId: "sub-q" },
|
||||
}),
|
||||
);
|
||||
transport.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "agent.queue.update",
|
||||
payload: {
|
||||
subscriptionId: "sub-q",
|
||||
agentId: "agent-a",
|
||||
held: false,
|
||||
items: [QUEUED_ITEM],
|
||||
},
|
||||
}),
|
||||
);
|
||||
await vi.waitFor(() => expect(updates).toHaveLength(1));
|
||||
expect(updates[0]).toMatchObject({
|
||||
type: "agent.queue.update",
|
||||
payload: { agentId: "agent-a", held: false, items: [QUEUED_ITEM] },
|
||||
});
|
||||
const releasing = observation.release();
|
||||
await vi.waitFor(() =>
|
||||
expect(parseSentFrame(transport.sent.at(-1)).type).toBe("subscription.release.request"),
|
||||
);
|
||||
const releaseReq = parseSentFrame(transport.sent.at(-1));
|
||||
transport.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "subscription.release.response",
|
||||
payload: { requestId: releaseReq.requestId, subscriptionId: "sub-q" },
|
||||
}),
|
||||
);
|
||||
await releasing;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2196,190 +2196,3 @@ test("background stop rejects when the host does not advertise the operation", a
|
||||
).rejects.toThrow("Update the host");
|
||||
await client.close();
|
||||
});
|
||||
|
||||
const AGENT_QUEUE_FEATURES = { ownedSubscriptions: true, agentMessageQueue: true };
|
||||
const QUEUED_ITEM = {
|
||||
id: "msg-1",
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T08:00:00.000Z",
|
||||
text: "Check logs",
|
||||
sender: { kind: "user" as const },
|
||||
held: false,
|
||||
state: "queued" as const,
|
||||
};
|
||||
|
||||
function answerQueueList(ws: FakeWebSocket, held: boolean, items: unknown[]): void {
|
||||
const request = parseSentSessionMessage(ws.sent.at(-1));
|
||||
expect(request).toMatchObject({ type: "agent.queue.list.request", agentId: "agent-a" });
|
||||
ws.message(
|
||||
sessionMessage({
|
||||
type: "agent.queue.list.response",
|
||||
payload: { requestId: request.requestId, agentId: "agent-a", held, items, error: null },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
test("agent handles list, withdraw, and promote queue items", async () => {
|
||||
const { client, ws } = await connectClient(AGENT_QUEUE_FEATURES);
|
||||
const queue = client.agents.ref("agent-a").queue;
|
||||
|
||||
const listed = queue.list();
|
||||
answerQueueList(ws, true, [QUEUED_ITEM]);
|
||||
await expect(listed).resolves.toEqual({ held: true, items: [QUEUED_ITEM] });
|
||||
|
||||
const withdrawn = queue.withdraw("msg-1");
|
||||
const withdrawReq = parseSentSessionMessage(ws.sent.at(-1));
|
||||
expect(withdrawReq).toMatchObject({
|
||||
type: "agent.queue.withdraw.request",
|
||||
agentId: "agent-a",
|
||||
messageId: "msg-1",
|
||||
});
|
||||
ws.message(
|
||||
sessionMessage({
|
||||
type: "agent.queue.withdraw.response",
|
||||
payload: {
|
||||
requestId: withdrawReq.requestId,
|
||||
agentId: "agent-a",
|
||||
messageId: "msg-1",
|
||||
withdrawn: true,
|
||||
item: QUEUED_ITEM,
|
||||
reason: null,
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await expect(withdrawn).resolves.toEqual({ withdrawn: true, item: QUEUED_ITEM });
|
||||
|
||||
const promoted = queue.promote("msg-1", "steer");
|
||||
const promoteReq = parseSentSessionMessage(ws.sent.at(-1));
|
||||
expect(promoteReq).toMatchObject({
|
||||
type: "agent.queue.promote.request",
|
||||
agentId: "agent-a",
|
||||
messageId: "msg-1",
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
ws.message(
|
||||
sessionMessage({
|
||||
type: "agent.queue.promote.response",
|
||||
payload: {
|
||||
requestId: promoteReq.requestId,
|
||||
agentId: "agent-a",
|
||||
messageId: "msg-1",
|
||||
promoted: false,
|
||||
reason: "already_dispatching",
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await expect(promoted).resolves.toEqual({ promoted: false, reason: "already_dispatching" });
|
||||
await client.close();
|
||||
});
|
||||
|
||||
test("agent queue subscriptions filter by agentId, re-list on reconnect, and keep overtaking updates", async () => {
|
||||
const { client, ws } = await connectClient(AGENT_QUEUE_FEATURES);
|
||||
const received: unknown[] = [];
|
||||
|
||||
const unsubscribe = client.agents.ref("agent-a").queue.subscribe((state) => received.push(state));
|
||||
expect(parseSentSessionMessage(ws.sent.at(-1))).toMatchObject({
|
||||
type: "session.events.set_subscription.request",
|
||||
events: ["agent.queue.update"],
|
||||
});
|
||||
acknowledgeObservation(ws, "queue-sdk");
|
||||
await vi.waitFor(() =>
|
||||
expect(parseSentSessionMessage(ws.sent.at(-1))).toMatchObject({
|
||||
type: "agent.queue.list.request",
|
||||
agentId: "agent-a",
|
||||
}),
|
||||
);
|
||||
const listReq = parseSentSessionMessage(ws.sent.at(-1));
|
||||
// An update overtakes the initial list response: the stale list is ignored.
|
||||
ws.message(
|
||||
sessionMessage({
|
||||
type: "agent.queue.update",
|
||||
payload: { subscriptionId: "queue-sdk", agentId: "agent-a", held: true, items: [] },
|
||||
}),
|
||||
);
|
||||
ws.message(
|
||||
sessionMessage({
|
||||
type: "agent.queue.list.response",
|
||||
payload: {
|
||||
requestId: listReq.requestId,
|
||||
agentId: "agent-a",
|
||||
held: false,
|
||||
items: [QUEUED_ITEM],
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await vi.waitFor(() => expect(received).toEqual([{ held: true, items: [] }]));
|
||||
|
||||
// Other agent updates are ignored.
|
||||
ws.message(
|
||||
sessionMessage({
|
||||
type: "agent.queue.update",
|
||||
payload: {
|
||||
subscriptionId: "queue-sdk",
|
||||
agentId: "agent-b",
|
||||
held: false,
|
||||
items: [QUEUED_ITEM],
|
||||
},
|
||||
}),
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(received).toEqual([{ held: true, items: [] }]);
|
||||
|
||||
// Reconnect re-subscribes and re-lists.
|
||||
ws.readyState = 3;
|
||||
ws.onclose?.({ code: 1006, reason: "Connection lost" });
|
||||
const reconnecting = client.connect();
|
||||
const next = FakeWebSocket.instances[1];
|
||||
next.open();
|
||||
next.message(
|
||||
sessionMessage({
|
||||
type: "status",
|
||||
payload: {
|
||||
status: "server_info",
|
||||
serverId: "srv_sdk_test",
|
||||
hostname: null,
|
||||
version: null,
|
||||
features: AGENT_QUEUE_FEATURES,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await reconnecting;
|
||||
await vi.waitFor(() =>
|
||||
expect(parseSentSessionMessage(next.sent.at(-1))).toMatchObject({
|
||||
type: "session.events.set_subscription.request",
|
||||
}),
|
||||
);
|
||||
acknowledgeObservation(next, "queue-sdk-2");
|
||||
answerQueueList(next, false, [QUEUED_ITEM]);
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(received).toEqual([
|
||||
{ held: true, items: [] },
|
||||
{ held: false, items: [QUEUED_ITEM] },
|
||||
]),
|
||||
);
|
||||
|
||||
unsubscribe();
|
||||
next.message(
|
||||
sessionMessage({
|
||||
type: "agent.queue.update",
|
||||
payload: { subscriptionId: "queue-sdk-2", agentId: "agent-a", held: false, items: [] },
|
||||
}),
|
||||
);
|
||||
expect(received).toHaveLength(2);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
test("agent queue asks for a host update when the daemon lacks agentMessageQueue", async () => {
|
||||
const { client } = await connectClient({ ownedSubscriptions: true });
|
||||
const handle = client.agents.ref("agent-a");
|
||||
|
||||
await expect(handle.queue.list()).rejects.toThrow("Update the host");
|
||||
await expect(handle.queue.withdraw("msg-1")).rejects.toThrow("Update the host");
|
||||
await expect(handle.queue.promote("msg-1", "steer")).rejects.toThrow("Update the host");
|
||||
expect(() => handle.queue.subscribe(() => {})).toThrow("Update the host");
|
||||
await client.close();
|
||||
});
|
||||
|
||||
+38
-106
@@ -11,7 +11,6 @@ export type { OwnedSubscription, SubscriptionObserver } from "./connection/index
|
||||
import type { DaemonClientConfig } from "./daemon-client.js";
|
||||
import type { AgentPermissionResponse, JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type {
|
||||
ActiveTurnBehavior,
|
||||
AgentSnapshotPayload,
|
||||
CreationSnapshot,
|
||||
CreateAgentRequestMessage,
|
||||
@@ -59,10 +58,6 @@ export type {
|
||||
import type { PluginTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
import type {
|
||||
AgentBackgroundWorkItem,
|
||||
AgentQueueItem,
|
||||
AgentQueueListResult,
|
||||
AgentQueuePromoteResult,
|
||||
AgentQueueWithdrawResult,
|
||||
FetchAgentsEntry,
|
||||
FetchAgentsOptions,
|
||||
FetchAgentsPageInfo,
|
||||
@@ -419,33 +414,6 @@ export interface PaseoAgentBackgroundWorkSubscribeOptions {
|
||||
onError?: (error: unknown) => void;
|
||||
}
|
||||
|
||||
export type PaseoAgentQueueItem = AgentQueueItem;
|
||||
export type PaseoAgentQueueState = AgentQueueListResult;
|
||||
export type PaseoAgentQueueWithdrawResult = AgentQueueWithdrawResult;
|
||||
export type PaseoAgentQueuePromoteResult = AgentQueuePromoteResult;
|
||||
|
||||
export interface PaseoAgentQueueSubscribeOptions {
|
||||
/** Receives the error when reading the agent's current queue fails. */
|
||||
onError?: (error: unknown) => void;
|
||||
}
|
||||
|
||||
export interface PaseoAgentQueueHandle {
|
||||
list(options?: { requestId?: string; timeout?: number }): Promise<PaseoAgentQueueState>;
|
||||
withdraw(
|
||||
messageId: string,
|
||||
options?: { requestId?: string; timeout?: number },
|
||||
): Promise<PaseoAgentQueueWithdrawResult>;
|
||||
promote(
|
||||
messageId: string,
|
||||
activeTurnBehavior: ActiveTurnBehavior,
|
||||
options?: { requestId?: string; timeout?: number },
|
||||
): Promise<PaseoAgentQueuePromoteResult>;
|
||||
subscribe(
|
||||
listener: (state: PaseoAgentQueueState) => void,
|
||||
options?: PaseoAgentQueueSubscribeOptions,
|
||||
): () => void;
|
||||
}
|
||||
|
||||
export interface PaseoAgentHandle {
|
||||
readonly id: string;
|
||||
readonly address: AgentAddress;
|
||||
@@ -477,7 +445,6 @@ export interface PaseoAgentHandle {
|
||||
readonly archivedAt: NonNullable<PaseoAgent["archivedAt"]> | null;
|
||||
readonly timeline: PaseoAgentTimelineHandle;
|
||||
readonly backgroundWork: PaseoAgentBackgroundWorkHandle;
|
||||
readonly queue: PaseoAgentQueueHandle;
|
||||
current(): PaseoAgent | null;
|
||||
refresh(requestId?: string): Promise<PaseoAgentRefetchResult | null>;
|
||||
/**
|
||||
@@ -746,7 +713,6 @@ export function createPaseoApi(
|
||||
listenAgents,
|
||||
(agentId, handler) => own(() => daemonClient.subscribeAgentTimeline(agentId, handler)),
|
||||
() => own(() => daemonClient.observeAgentBackgroundWork()),
|
||||
() => own(() => daemonClient.observeAgentQueue()),
|
||||
);
|
||||
const createAgent = async (
|
||||
options: PaseoAgentCreateOptions,
|
||||
@@ -1043,54 +1009,11 @@ function createWorkspaceHandleFactory(
|
||||
};
|
||||
}
|
||||
|
||||
function subscribeAgentObservation<T>(
|
||||
createObservation: () => OwnedSubscription<unknown>,
|
||||
fetchSnapshot: () => Promise<T>,
|
||||
extractUpdate: (message: SessionOutboundMessage) => T | null,
|
||||
listener: (value: T) => void,
|
||||
options: { onError?: (error: unknown) => void; label: string },
|
||||
): () => void {
|
||||
const observation = createObservation();
|
||||
// Bumped by every delivery so a list answered after a newer update is dropped.
|
||||
let sequence = 0;
|
||||
let released = false;
|
||||
const reportError = (error: unknown) => {
|
||||
if (released) return;
|
||||
if (options.onError) options.onError(error);
|
||||
else console.error(`${options.label} subscription failed`, error);
|
||||
};
|
||||
observation.subscribe({
|
||||
error: reportError,
|
||||
snapshot: () => {
|
||||
const listed = ++sequence;
|
||||
void fetchSnapshot()
|
||||
.then((value) => {
|
||||
if (!released && listed === sequence) listener(value);
|
||||
return undefined;
|
||||
})
|
||||
.catch(reportError);
|
||||
},
|
||||
update: (message) => {
|
||||
const value = extractUpdate(message);
|
||||
if (value === null) return;
|
||||
sequence++;
|
||||
listener(value);
|
||||
},
|
||||
});
|
||||
return () => {
|
||||
released = true;
|
||||
void observation
|
||||
.release()
|
||||
.catch((error) => console.error(`${options.label} subscription cleanup failed`, error));
|
||||
};
|
||||
}
|
||||
|
||||
function createAgentHandleFactory(
|
||||
daemonClient: DaemonClient,
|
||||
listen: (handler: PaseoAgentUpdateHandler) => () => void,
|
||||
subscribeTimeline: DaemonClient["subscribeAgentTimeline"],
|
||||
observeBackgroundWork: () => ReturnType<DaemonClient["observeAgentBackgroundWork"]>,
|
||||
observeAgentQueue: () => ReturnType<DaemonClient["observeAgentQueue"]>,
|
||||
): AgentHandleFactory {
|
||||
return (agent) => {
|
||||
const id = typeof agent === "string" ? agent : agent.id;
|
||||
@@ -1150,35 +1073,44 @@ function createAgentHandleFactory(
|
||||
backgroundWork: {
|
||||
stop: (item, options) => daemonClient.stopAgentBackgroundWork(id, item, options),
|
||||
list: (options) => daemonClient.listAgentBackgroundWork(id, options),
|
||||
subscribe: (listener, options) =>
|
||||
subscribeAgentObservation(
|
||||
observeBackgroundWork,
|
||||
() => daemonClient.listAgentBackgroundWork(id),
|
||||
(message) =>
|
||||
message.type === "agent.background_work.update" && message.payload.agentId === id
|
||||
? message.payload.items
|
||||
: null,
|
||||
listener,
|
||||
{ onError: options?.onError, label: "Background work" },
|
||||
),
|
||||
},
|
||||
queue: {
|
||||
list: (options) => daemonClient.listAgentQueue(id, options),
|
||||
withdraw: (messageId, options) =>
|
||||
daemonClient.withdrawAgentQueueItem(id, messageId, options),
|
||||
promote: (messageId, activeTurnBehavior, options) =>
|
||||
daemonClient.promoteAgentQueueItem(id, messageId, activeTurnBehavior, options),
|
||||
subscribe: (listener, options) =>
|
||||
subscribeAgentObservation(
|
||||
observeAgentQueue,
|
||||
() => daemonClient.listAgentQueue(id),
|
||||
(message) =>
|
||||
message.type === "agent.queue.update" && message.payload.agentId === id
|
||||
? { held: message.payload.held, items: message.payload.items }
|
||||
: null,
|
||||
listener,
|
||||
{ onError: options?.onError, label: "Agent queue" },
|
||||
),
|
||||
subscribe: (listener, options) => {
|
||||
const observation = observeBackgroundWork();
|
||||
// Bumped by every delivery so a list answered after a newer update is dropped.
|
||||
let sequence = 0;
|
||||
let released = false;
|
||||
const reportError = (error: unknown) => {
|
||||
if (released) return;
|
||||
if (options?.onError) options.onError(error);
|
||||
else console.error("Background work subscription failed", error);
|
||||
};
|
||||
observation.subscribe({
|
||||
error: reportError,
|
||||
snapshot: () => {
|
||||
const listed = ++sequence;
|
||||
void daemonClient
|
||||
.listAgentBackgroundWork(id)
|
||||
.then((items) => {
|
||||
if (!released && listed === sequence) listener(items);
|
||||
return undefined;
|
||||
})
|
||||
.catch(reportError);
|
||||
},
|
||||
update: (message) => {
|
||||
if (message.type !== "agent.background_work.update") return;
|
||||
if (message.payload.agentId !== id) return;
|
||||
sequence++;
|
||||
listener(message.payload.items);
|
||||
},
|
||||
});
|
||||
return () => {
|
||||
released = true;
|
||||
void observation
|
||||
.release()
|
||||
.catch((error) =>
|
||||
console.error("Background work subscription cleanup failed", error),
|
||||
);
|
||||
};
|
||||
},
|
||||
},
|
||||
get workspaceId() {
|
||||
return current?.workspaceId ?? null;
|
||||
|
||||
@@ -1,210 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
QueuedAgentMessagePayloadSchema,
|
||||
QueuedMessageSenderSchema,
|
||||
SendAgentMessageResponseMessageSchema,
|
||||
ServerInfoStatusPayloadSchema,
|
||||
SessionEventSubscriptionSchema,
|
||||
SessionInboundMessageSchema,
|
||||
SessionOutboundMessageSchema,
|
||||
} from "./messages.js";
|
||||
|
||||
const USER_ITEM = {
|
||||
id: "msg-1",
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T08:00:00.000Z",
|
||||
text: "Follow up on the build",
|
||||
sender: { kind: "user" as const },
|
||||
held: false,
|
||||
state: "queued" as const,
|
||||
};
|
||||
|
||||
const AGENT_ITEM = {
|
||||
id: "msg-2",
|
||||
seq: 2,
|
||||
enqueuedAt: "2026-11-30T08:00:01.000Z",
|
||||
text: "Worker finished",
|
||||
attachments: [
|
||||
{
|
||||
type: "uploaded_file" as const,
|
||||
id: "up-1",
|
||||
fileName: "shot.png",
|
||||
mimeType: "image/png",
|
||||
size: 123,
|
||||
path: "/tmp/uploads/up-1/shot.png",
|
||||
role: "image" as const,
|
||||
},
|
||||
],
|
||||
sender: {
|
||||
kind: "agent_message" as const,
|
||||
agentId: "agent-worker",
|
||||
serverId: "server-1",
|
||||
title: "Worker",
|
||||
},
|
||||
held: true,
|
||||
state: "dispatching" as const,
|
||||
};
|
||||
|
||||
describe("agent message queue protocol", () => {
|
||||
test("parses all queued message sender variants and payloads", () => {
|
||||
for (const sender of [
|
||||
{ kind: "user" },
|
||||
{ kind: "agent_message", agentId: "agent-1", serverId: "srv-1", title: "Worker" },
|
||||
{ kind: "agent_notification", agentId: "agent-2", event: "finished" },
|
||||
{ kind: "change_request_update", url: "https://github.com/org/repo/pull/42" },
|
||||
]) {
|
||||
expect(QueuedMessageSenderSchema.parse(sender)).toEqual(sender);
|
||||
}
|
||||
|
||||
expect(QueuedAgentMessagePayloadSchema.parse(USER_ITEM)).toEqual(USER_ITEM);
|
||||
expect(QueuedAgentMessagePayloadSchema.parse(AGENT_ITEM)).toEqual(AGENT_ITEM);
|
||||
});
|
||||
|
||||
test("accepts queue list, withdraw, and promote requests and responses", () => {
|
||||
expect(
|
||||
SessionInboundMessageSchema.parse({
|
||||
type: "agent.queue.list.request",
|
||||
agentId: "agent-1",
|
||||
requestId: "req-list",
|
||||
}),
|
||||
).toMatchObject({ agentId: "agent-1", requestId: "req-list" });
|
||||
|
||||
expect(
|
||||
SessionOutboundMessageSchema.parse({
|
||||
type: "agent.queue.list.response",
|
||||
payload: {
|
||||
requestId: "req-list",
|
||||
agentId: "agent-1",
|
||||
held: false,
|
||||
items: [USER_ITEM, AGENT_ITEM],
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ payload: { held: false, items: [USER_ITEM, AGENT_ITEM] } });
|
||||
|
||||
expect(
|
||||
SessionInboundMessageSchema.parse({
|
||||
type: "agent.queue.withdraw.request",
|
||||
agentId: "agent-1",
|
||||
messageId: "msg-1",
|
||||
requestId: "req-withdraw",
|
||||
}),
|
||||
).toMatchObject({ agentId: "agent-1", messageId: "msg-1", requestId: "req-withdraw" });
|
||||
|
||||
expect(
|
||||
SessionOutboundMessageSchema.parse({
|
||||
type: "agent.queue.withdraw.response",
|
||||
payload: {
|
||||
requestId: "req-withdraw",
|
||||
agentId: "agent-1",
|
||||
messageId: "msg-1",
|
||||
withdrawn: true,
|
||||
item: USER_ITEM,
|
||||
reason: null,
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ payload: { withdrawn: true, item: USER_ITEM } });
|
||||
|
||||
for (const reason of ["not_found", "already_dispatching"] as const) {
|
||||
expect(
|
||||
SessionOutboundMessageSchema.parse({
|
||||
type: "agent.queue.withdraw.response",
|
||||
payload: {
|
||||
requestId: "req-withdraw",
|
||||
agentId: "agent-1",
|
||||
messageId: "msg-1",
|
||||
withdrawn: false,
|
||||
item: null,
|
||||
reason,
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ payload: { withdrawn: false, reason } });
|
||||
}
|
||||
|
||||
expect(
|
||||
SessionInboundMessageSchema.parse({
|
||||
type: "agent.queue.promote.request",
|
||||
agentId: "agent-1",
|
||||
messageId: "msg-1",
|
||||
activeTurnBehavior: "steer",
|
||||
requestId: "req-promote",
|
||||
}),
|
||||
).toMatchObject({ activeTurnBehavior: "steer" });
|
||||
|
||||
expect(
|
||||
SessionInboundMessageSchema.safeParse({
|
||||
type: "agent.queue.promote.request",
|
||||
agentId: "agent-1",
|
||||
messageId: "msg-1",
|
||||
activeTurnBehavior: "queue",
|
||||
requestId: "req-promote",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
SessionOutboundMessageSchema.parse({
|
||||
type: "agent.queue.promote.response",
|
||||
payload: {
|
||||
requestId: "req-promote",
|
||||
agentId: "agent-1",
|
||||
messageId: "msg-1",
|
||||
promoted: true,
|
||||
reason: null,
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ payload: { promoted: true } });
|
||||
});
|
||||
|
||||
test("accepts queue updates with or without subscriptionId and registers subscription", () => {
|
||||
for (const payload of [
|
||||
{ agentId: "agent-1", held: false, items: [] },
|
||||
{ subscriptionId: "sub-1", agentId: "agent-1", held: true, items: [USER_ITEM] },
|
||||
]) {
|
||||
expect(
|
||||
SessionOutboundMessageSchema.parse({ type: "agent.queue.update", payload }),
|
||||
).toMatchObject({ payload });
|
||||
}
|
||||
|
||||
expect(SessionEventSubscriptionSchema.parse("agent.queue.update")).toBe("agent.queue.update");
|
||||
});
|
||||
|
||||
test("keeps send_agent_message_response.messageId and server_info.features.agentMessageQueue optional", () => {
|
||||
expect(
|
||||
SendAgentMessageResponseMessageSchema.parse({
|
||||
type: "send_agent_message_response",
|
||||
payload: {
|
||||
requestId: "req-1",
|
||||
agentId: "agent-1",
|
||||
accepted: true,
|
||||
deliveryStatus: "queued",
|
||||
messageId: "msg-1",
|
||||
error: null,
|
||||
},
|
||||
}).payload.messageId,
|
||||
).toBe("msg-1");
|
||||
|
||||
expect(
|
||||
SendAgentMessageResponseMessageSchema.parse({
|
||||
type: "send_agent_message_response",
|
||||
payload: {
|
||||
requestId: "req-1",
|
||||
agentId: "agent-1",
|
||||
accepted: true,
|
||||
error: null,
|
||||
},
|
||||
}).payload.messageId,
|
||||
).toBeUndefined();
|
||||
|
||||
expect(
|
||||
ServerInfoStatusPayloadSchema.parse({
|
||||
status: "server_info",
|
||||
serverId: "server-1",
|
||||
features: {},
|
||||
}).features?.agentMessageQueue,
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1426,16 +1426,6 @@ export type ActiveTurnBehavior = z.infer<typeof ActiveTurnBehaviorSchema>;
|
||||
export const AgentActiveTurnBehaviorSchema = z.enum(["interrupt", "steer", "queue"]);
|
||||
export type AgentActiveTurnBehavior = z.infer<typeof AgentActiveTurnBehaviorSchema>;
|
||||
|
||||
/** The provider a queued message moves its agent to, with the settings chosen for it. */
|
||||
export const QueuedProviderSwitchSchema = z.object({
|
||||
provider: AgentProviderSchema,
|
||||
model: z.string().nullable().optional(),
|
||||
modeId: z.string().nullable().optional(),
|
||||
thinkingOptionId: z.string().nullable().optional(),
|
||||
providerOptions: z.record(z.string(), z.unknown()).optional(),
|
||||
});
|
||||
export type QueuedProviderSwitch = z.infer<typeof QueuedProviderSwitchSchema>;
|
||||
|
||||
export const SendAgentMessageSchema = z.object({
|
||||
type: z.literal("send_agent_message"),
|
||||
agentId: z.string(),
|
||||
@@ -2224,27 +2214,6 @@ export const AgentBackgroundWorkStopRequestMessageSchema = z.object({
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const AgentQueueListRequestMessageSchema = z.object({
|
||||
type: z.literal("agent.queue.list.request"),
|
||||
agentId: z.string(),
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const AgentQueueWithdrawRequestMessageSchema = z.object({
|
||||
type: z.literal("agent.queue.withdraw.request"),
|
||||
agentId: z.string(),
|
||||
messageId: z.string(),
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const AgentQueuePromoteRequestMessageSchema = z.object({
|
||||
type: z.literal("agent.queue.promote.request"),
|
||||
agentId: z.string(),
|
||||
messageId: z.string(),
|
||||
activeTurnBehavior: ActiveTurnBehaviorSchema,
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const ProviderSubagentTimelineRequestMessageSchema = z.object({
|
||||
type: z.literal("agent.provider_subagents.timeline.get.request"),
|
||||
parentAgentId: z.string(),
|
||||
@@ -2416,9 +2385,6 @@ export const AgentProviderSwitchRequestSchema = z.object({
|
||||
messageId: z.string().min(1),
|
||||
images: z.array(ImageAttachmentSchema).optional(),
|
||||
attachments: AgentAttachmentsSchema,
|
||||
// Switch when the running turn ends instead of now. Hosts before `features.agentMessageQueue`
|
||||
// ignore it and refuse a running agent, so check the feature before sending it.
|
||||
activeTurnBehavior: z.literal("queue").optional(),
|
||||
});
|
||||
|
||||
export const UpdateAgentResponseMessageSchema = z.object({
|
||||
@@ -3671,7 +3637,6 @@ export const SessionEventSubscriptionSchema = z.enum([
|
||||
"workspace_setup_progress",
|
||||
"agent.provider_subagents.update",
|
||||
"agent.background_work.update",
|
||||
"agent.queue.update",
|
||||
"terminal_attention_required",
|
||||
"plugin.notification",
|
||||
"status.server_info",
|
||||
@@ -3845,9 +3810,6 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
ProviderSubagentListRequestMessageSchema,
|
||||
AgentBackgroundWorkListRequestMessageSchema,
|
||||
AgentBackgroundWorkStopRequestMessageSchema,
|
||||
AgentQueueListRequestMessageSchema,
|
||||
AgentQueueWithdrawRequestMessageSchema,
|
||||
AgentQueuePromoteRequestMessageSchema,
|
||||
ProviderSubagentTimelineRequestMessageSchema,
|
||||
SetAgentTimelineSubscriptionRequestMessageSchema,
|
||||
AgentForkContextRequestMessageSchema,
|
||||
@@ -4381,8 +4343,6 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
agentActiveTurnBehaviors: z.boolean().optional(),
|
||||
// COMPAT(nonAgentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
|
||||
nonAgentMessageQueue: z.boolean().optional(),
|
||||
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
|
||||
agentMessageQueue: z.boolean().optional(),
|
||||
// COMPAT(agentTurnIdentity): accept peers that observed pre-release v0.2.6 through 2027-01-31.
|
||||
agentTurnIdentity: z.boolean().optional(),
|
||||
// COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15.
|
||||
@@ -5520,95 +5480,6 @@ export const AgentBackgroundWorkUpdateMessageSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
export const QueuedMessageSenderSchema = z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("user") }),
|
||||
z.object({
|
||||
kind: z.literal("agent_message"),
|
||||
agentId: z.string(),
|
||||
serverId: z.string().optional(),
|
||||
title: z.string().optional(),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("agent_notification"),
|
||||
agentId: z.string(),
|
||||
serverId: z.string().optional(),
|
||||
title: z.string().optional(),
|
||||
event: z.enum(["finished", "errored", "permission-required", "closed"]),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("change_request_update"),
|
||||
url: z.string(),
|
||||
}),
|
||||
]);
|
||||
|
||||
export type QueuedMessageSender = z.infer<typeof QueuedMessageSenderSchema>;
|
||||
|
||||
export const QueuedAgentMessagePayloadSchema = z.object({
|
||||
id: z.string(),
|
||||
seq: z.number().int().positive(),
|
||||
enqueuedAt: z.string(),
|
||||
text: z.string(),
|
||||
attachments: z.array(AgentAttachmentSchema).optional(),
|
||||
sender: QueuedMessageSenderSchema,
|
||||
held: z.boolean(),
|
||||
state: z.enum(["queued", "dispatching"]),
|
||||
// The message moves the agent to this provider before it runs.
|
||||
providerSwitch: QueuedProviderSwitchSchema.optional(),
|
||||
});
|
||||
|
||||
export type QueuedAgentMessagePayload = z.infer<typeof QueuedAgentMessagePayloadSchema>;
|
||||
|
||||
export const AgentQueueMissReasonSchema = z.enum(["not_found", "already_dispatching"]);
|
||||
export type AgentQueueMissReason = z.infer<typeof AgentQueueMissReasonSchema>;
|
||||
|
||||
export const AgentQueueListResponseMessageSchema = z.object({
|
||||
type: z.literal("agent.queue.list.response"),
|
||||
payload: z.object({
|
||||
requestId: z.string(),
|
||||
agentId: z.string(),
|
||||
held: z.boolean(),
|
||||
items: z.array(QueuedAgentMessagePayloadSchema),
|
||||
error: z.string().nullable(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const AgentQueueWithdrawResponseMessageSchema = z.object({
|
||||
type: z.literal("agent.queue.withdraw.response"),
|
||||
payload: z.object({
|
||||
requestId: z.string(),
|
||||
agentId: z.string(),
|
||||
messageId: z.string(),
|
||||
withdrawn: z.boolean(),
|
||||
item: QueuedAgentMessagePayloadSchema.nullable().optional(),
|
||||
reason: AgentQueueMissReasonSchema.nullable().optional(),
|
||||
error: z.string().nullable(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const AgentQueuePromoteResponseMessageSchema = z.object({
|
||||
type: z.literal("agent.queue.promote.response"),
|
||||
payload: z.object({
|
||||
requestId: z.string(),
|
||||
agentId: z.string(),
|
||||
messageId: z.string(),
|
||||
promoted: z.boolean(),
|
||||
reason: AgentQueueMissReasonSchema.nullable().optional(),
|
||||
error: z.string().nullable(),
|
||||
}),
|
||||
});
|
||||
|
||||
// Event push delivered through session.events.set_subscription; it has no .request/.response pair.
|
||||
// Each update replaces the agent's whole queue list.
|
||||
export const AgentQueueUpdateMessageSchema = z.object({
|
||||
type: z.literal("agent.queue.update"),
|
||||
payload: z.object({
|
||||
subscriptionId: z.string().optional(),
|
||||
agentId: z.string(),
|
||||
held: z.boolean(),
|
||||
items: z.array(QueuedAgentMessagePayloadSchema),
|
||||
}),
|
||||
});
|
||||
|
||||
export const ProviderSubagentTimelineResponseMessageSchema = z.object({
|
||||
type: z.literal("agent.provider_subagents.timeline.get.response"),
|
||||
payload: z.object({
|
||||
@@ -5852,8 +5723,6 @@ export const SendAgentMessageResponseMessageSchema = z.object({
|
||||
agentId: z.string(),
|
||||
accepted: z.boolean(),
|
||||
deliveryStatus: z.literal("queued").optional(),
|
||||
/** The queued message ID when admitted to the daemon queue. */
|
||||
messageId: z.string().optional(),
|
||||
/** The behavior applied to a queued agent message. */
|
||||
activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional(),
|
||||
/** What happens to a queued agent message, and how the sender can change it. */
|
||||
@@ -5870,9 +5739,6 @@ export const AgentProviderSwitchResponseMessageSchema = z.object({
|
||||
accepted: z.boolean(),
|
||||
agent: AgentSnapshotPayloadSchema.optional(),
|
||||
error: z.string().nullable(),
|
||||
// Present when the switch was queued: it has not happened yet.
|
||||
deliveryStatus: z.literal("queued").optional(),
|
||||
messageId: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -8196,10 +8062,6 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
AgentBackgroundWorkListResponseMessageSchema,
|
||||
AgentBackgroundWorkStopResponseMessageSchema,
|
||||
AgentBackgroundWorkUpdateMessageSchema,
|
||||
AgentQueueListResponseMessageSchema,
|
||||
AgentQueueWithdrawResponseMessageSchema,
|
||||
AgentQueuePromoteResponseMessageSchema,
|
||||
AgentQueueUpdateMessageSchema,
|
||||
SetAgentTimelineSubscriptionResponseMessageSchema,
|
||||
AgentAttentionRequiredMessageSchema,
|
||||
AgentForkContextResponseMessageSchema,
|
||||
|
||||
@@ -857,28 +857,4 @@ describe("provider metrics", () => {
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("send_agent_message_response accepts messageId while older apps ignore it", () => {
|
||||
const withMessageId = {
|
||||
type: "send_agent_message_response",
|
||||
payload: {
|
||||
requestId: "req-1",
|
||||
agentId: "agent-1",
|
||||
accepted: true,
|
||||
deliveryStatus: "queued" as const,
|
||||
messageId: "msg-1",
|
||||
error: null,
|
||||
},
|
||||
};
|
||||
expect(SessionOutboundMessageSchema.parse(withMessageId)).toEqual(withMessageId);
|
||||
|
||||
const legacyPayload = z.object({
|
||||
requestId: z.string(),
|
||||
agentId: z.string(),
|
||||
accepted: z.boolean(),
|
||||
deliveryStatus: z.literal("queued").optional(),
|
||||
error: z.string().nullable(),
|
||||
});
|
||||
expect(legacyPayload.parse(withMessageId.payload)).not.toHaveProperty("messageId");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -198,45 +198,6 @@ describe("unknown list variants degrade to one skipped element", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("skips a queued message item with an unknown sender variant and keeps the update", () => {
|
||||
const knownItem = {
|
||||
id: "msg-1",
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T08:00:00.000Z",
|
||||
text: "Check logs",
|
||||
sender: { kind: "user" },
|
||||
held: false,
|
||||
state: "queued",
|
||||
};
|
||||
const futureItem = {
|
||||
id: "msg-2",
|
||||
seq: 2,
|
||||
enqueuedAt: "2026-11-30T08:00:01.000Z",
|
||||
text: "Future trigger",
|
||||
sender: { kind: "future_trigger", source: "cron" },
|
||||
held: false,
|
||||
state: "queued",
|
||||
};
|
||||
const envelope = session({
|
||||
type: "agent.queue.update",
|
||||
payload: {
|
||||
agentId: "agent-1",
|
||||
held: false,
|
||||
items: [knownItem, futureItem],
|
||||
},
|
||||
});
|
||||
|
||||
const generated = validateWSOutboundMessage(envelope);
|
||||
const zod = safeParseSkippingUnknownVariants(WSOutboundMessageSchema, envelope);
|
||||
|
||||
expect(generated).toMatchObject({
|
||||
success: true,
|
||||
data: { message: { payload: { agentId: "agent-1", held: false, items: [knownItem] } } },
|
||||
});
|
||||
expect(zod.success).toBe(true);
|
||||
expect(zod.success && zod.data).toEqual(generated.success && generated.data);
|
||||
});
|
||||
});
|
||||
|
||||
describe("what still fails", () => {
|
||||
|
||||
@@ -472,66 +472,3 @@ it("accepts omitted RPC output so the receiving client can apply schema defaults
|
||||
const message = { type: "plugin.rpc.invoke.response", payload: { requestId: "default-output" } };
|
||||
expect(PluginRpcInvokeResponseSchema.safeParse(message).success).toBe(true);
|
||||
});
|
||||
|
||||
it("validates agent.queue outbound responses and update events via zod-aot", () => {
|
||||
const item = {
|
||||
id: "msg-1",
|
||||
seq: 1,
|
||||
enqueuedAt: "2026-11-30T08:00:00.000Z",
|
||||
text: "Queued prompt",
|
||||
sender: { kind: "user" },
|
||||
held: false,
|
||||
state: "queued",
|
||||
};
|
||||
for (const message of [
|
||||
{
|
||||
type: "agent.queue.list.response",
|
||||
payload: { requestId: "req-1", agentId: "agent-1", held: false, items: [item], error: null },
|
||||
},
|
||||
{
|
||||
type: "agent.queue.withdraw.response",
|
||||
payload: {
|
||||
requestId: "req-2",
|
||||
agentId: "agent-1",
|
||||
messageId: "msg-1",
|
||||
withdrawn: true,
|
||||
item,
|
||||
reason: null,
|
||||
error: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "agent.queue.promote.response",
|
||||
payload: {
|
||||
requestId: "req-3",
|
||||
agentId: "agent-1",
|
||||
messageId: "msg-1",
|
||||
promoted: false,
|
||||
reason: "already_dispatching",
|
||||
error: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "agent.queue.update",
|
||||
payload: { subscriptionId: "sub-1", agentId: "agent-1", held: true, items: [item] },
|
||||
},
|
||||
{
|
||||
type: "send_agent_message_response",
|
||||
payload: {
|
||||
requestId: "req-4",
|
||||
agentId: "agent-1",
|
||||
accepted: true,
|
||||
deliveryStatus: "queued",
|
||||
messageId: "msg-1",
|
||||
error: null,
|
||||
},
|
||||
},
|
||||
]) {
|
||||
const envelope = { type: "session", message };
|
||||
expect(validateWSOutboundMessage(envelope)).toEqual({
|
||||
success: true,
|
||||
data: envelope,
|
||||
skipped: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
+7
-2
@@ -131,7 +131,7 @@ class TableContainerView(
|
||||
TableCellData(
|
||||
attributedText = renderCellNode(cell, isHeader, align),
|
||||
plainText = extractPlainText(cell),
|
||||
markdownText = MarkdownASTSerializer.serializeChildren(cell),
|
||||
markdownText = MarkdownASTSerializer.serializeTableCell(cell),
|
||||
isHeader = isHeader,
|
||||
alignment = align,
|
||||
)
|
||||
@@ -169,7 +169,12 @@ class TableContainerView(
|
||||
}
|
||||
}
|
||||
|
||||
private fun extractPlainText(node: MarkdownASTNode): String = node.content + node.children.joinToString("") { extractPlainText(it) }
|
||||
private fun extractPlainText(node: MarkdownASTNode): String =
|
||||
if (node.type == NodeType.LineBreak) {
|
||||
" "
|
||||
} else {
|
||||
node.content + node.children.joinToString("") { extractPlainText(it) }
|
||||
}
|
||||
|
||||
private fun textAlignmentFromString(align: String?): Layout.Alignment =
|
||||
when (align) {
|
||||
|
||||
+5
-6
@@ -12,12 +12,11 @@ object MarkdownASTSerializer {
|
||||
return buffer.toString()
|
||||
}
|
||||
|
||||
fun serializeChildren(node: MarkdownASTNode): String {
|
||||
/** A table row is one line, so a cell's line break goes back to `<br>`. */
|
||||
fun serializeTableCell(cell: MarkdownASTNode): String {
|
||||
val buffer = StringBuilder()
|
||||
for (child in node.children) {
|
||||
appendNode(child, buffer)
|
||||
}
|
||||
return buffer.toString()
|
||||
appendChildren(cell, buffer)
|
||||
return buffer.toString().replace("\\\n", "<br>")
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -184,7 +183,7 @@ object MarkdownASTSerializer {
|
||||
for (section in node.children) {
|
||||
for (row in section.children) {
|
||||
if (row.type != NodeType.TableRow) continue
|
||||
val cells = row.children.map { serializeChildren(it) }
|
||||
val cells = row.children.map { serializeTableCell(it) }
|
||||
buffer.append("| ")
|
||||
buffer.append(cells.joinToString(" | "))
|
||||
buffer.append(" |\n")
|
||||
|
||||
+15
@@ -24,6 +24,7 @@ import com.swmansion.enriched.markdown.test.TestAstFactory.paragraph
|
||||
import com.swmansion.enriched.markdown.test.TestAstFactory.taskListItem
|
||||
import com.swmansion.enriched.markdown.test.TestAstFactory.text
|
||||
import com.swmansion.enriched.markdown.test.TestAstFactory.unorderedList
|
||||
import com.swmansion.enriched.markdown.utils.common.serialization.MarkdownASTSerializer
|
||||
import com.swmansion.enriched.markdown.utils.text.view.SelectionMenuConfig
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
@@ -200,6 +201,20 @@ class BlockquoteCopyTest {
|
||||
assertEquals("Inner", clipboardText())
|
||||
}
|
||||
|
||||
@Test fun copyButtonKeepsAQuotedTableCellLineBreakInItsRow() {
|
||||
val table =
|
||||
node(
|
||||
NodeType.Table,
|
||||
node(NodeType.TableHead, node(NodeType.TableRow, node(NodeType.TableHeaderCell, text("Case")))),
|
||||
node(
|
||||
NodeType.TableBody,
|
||||
node(NodeType.TableRow, node(NodeType.TableCell, text("first"), node(NodeType.LineBreak), text("second"))),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals("| Case |\n| --- |\n| first<br>second |", MarkdownASTSerializer.serializeBlockquoteBody(quote(table)))
|
||||
}
|
||||
|
||||
@Test fun admonitionHasNoCopyButton() {
|
||||
val view = quoteView()
|
||||
view.applyBlockquoteNode(
|
||||
|
||||
@@ -22,6 +22,7 @@ public:
|
||||
std::string currentText;
|
||||
const char *inputText = nullptr;
|
||||
bool inHtmlBlock = false;
|
||||
bool inTableCell = false;
|
||||
std::string htmlBlockContent;
|
||||
|
||||
static const std::string ATTR_LEVEL;
|
||||
@@ -46,6 +47,7 @@ public:
|
||||
currentText.clear();
|
||||
currentText.reserve(256);
|
||||
inHtmlBlock = false;
|
||||
inTableCell = false;
|
||||
htmlBlockContent.clear();
|
||||
}
|
||||
|
||||
@@ -231,6 +233,7 @@ public:
|
||||
|
||||
case MD_BLOCK_TH:
|
||||
case MD_BLOCK_TD: {
|
||||
impl->inTableCell = true;
|
||||
auto node =
|
||||
std::make_shared<MarkdownASTNode>(type == MD_BLOCK_TH ? NodeType::TableHeaderCell : NodeType::TableCell);
|
||||
if (detail) {
|
||||
@@ -286,6 +289,10 @@ public:
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (type == MD_BLOCK_TH || type == MD_BLOCK_TD) {
|
||||
impl->inTableCell = false;
|
||||
}
|
||||
|
||||
if (type != MD_BLOCK_DOC && !impl->nodeStack.empty()) {
|
||||
impl->popNode();
|
||||
}
|
||||
@@ -431,6 +438,39 @@ public:
|
||||
}
|
||||
|
||||
// Handle text content (normal text, code text, LaTeX math, etc.)
|
||||
if (type == MD_TEXT_NORMAL && impl->inTableCell) {
|
||||
constexpr const char kLineSep[] = "\xE2\x80\xA8";
|
||||
constexpr MD_SIZE kLineSepLen = 3;
|
||||
MD_SIZE pos = 0;
|
||||
while (pos + kLineSepLen <= size) {
|
||||
MD_SIZE match = size;
|
||||
for (MD_SIZE i = pos; i + kLineSepLen <= size; ++i) {
|
||||
if (std::memcmp(text + i, kLineSep, kLineSepLen) == 0) {
|
||||
match = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match == size) {
|
||||
break;
|
||||
}
|
||||
if (match > pos) {
|
||||
impl->currentText.append(text + pos, match - pos);
|
||||
}
|
||||
if (!impl->currentText.empty() && impl->currentText.back() == ' ') {
|
||||
impl->currentText.pop_back();
|
||||
}
|
||||
impl->addInlineNode(std::make_shared<MarkdownASTNode>(NodeType::LineBreak));
|
||||
pos = match + kLineSepLen;
|
||||
if (pos < size && text[pos] == ' ') {
|
||||
++pos;
|
||||
}
|
||||
}
|
||||
if (pos < size) {
|
||||
impl->currentText.append(text + pos, size - pos);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (type == MD_TEXT_NORMAL || type == MD_TEXT_CODE || type == MD_TEXT_LATEXMATH) {
|
||||
impl->currentText.append(text, size);
|
||||
}
|
||||
|
||||
@@ -49,6 +49,8 @@ static NSString *ENRMTablePlainTextFromNode(MarkdownASTNode *node)
|
||||
{
|
||||
if (!node)
|
||||
return @"";
|
||||
if (node.type == MarkdownNodeTypeLineBreak)
|
||||
return @" ";
|
||||
NSMutableString *buffer = [node.content mutableCopy] ?: [NSMutableString string];
|
||||
for (MarkdownASTNode *child in node.children) {
|
||||
[buffer appendString:ENRMTablePlainTextFromNode(child)];
|
||||
@@ -163,7 +165,7 @@ static NSArray<NSArray<TableCellData *> *> *ENRMTableBuildRows(MarkdownASTNode *
|
||||
cell.isHeader = isSectionHead || (cellNode.type == MarkdownNodeTypeTableHeaderCell);
|
||||
cell.alignment = ENRMTableTextAlignmentFromString(cellNode.attributes[@"align"]);
|
||||
cell.plainText = ENRMTablePlainTextFromNode(cellNode);
|
||||
cell.markdownText = markdownFromASTNodeChildren(cellNode);
|
||||
cell.markdownText = markdownFromTableCell(cellNode);
|
||||
|
||||
StyleConfig *cellConfig = cell.isHeader ? headerCellConfig : bodyCellConfig;
|
||||
cell.attributedText =
|
||||
|
||||
@@ -13,9 +13,9 @@ extern "C" {
|
||||
/// Handles inline elements: strong, emphasis, strikethrough, underline, code, links, images.
|
||||
NSString *markdownFromASTNode(MarkdownASTNode *node);
|
||||
|
||||
/// Serializes only the children of a node to markdown (skipping the node itself).
|
||||
/// Useful for extracting the markdown content of a container node (e.g. a table cell).
|
||||
NSString *markdownFromASTNodeChildren(MarkdownASTNode *node);
|
||||
/// Serializes a table cell's content to markdown. A row is one line, so a cell's
|
||||
/// line break goes back to `<br>`.
|
||||
NSString *markdownFromTableCell(MarkdownASTNode *cell);
|
||||
|
||||
/// Serializes the blocks inside a Blockquote to markdown, without the quote's own
|
||||
/// `> ` prefix. A quote nested inside keeps its prefix.
|
||||
|
||||
@@ -142,7 +142,7 @@ static void appendTableMarkdown(MarkdownASTNode *node, NSMutableString *buffer)
|
||||
continue;
|
||||
NSMutableArray<NSString *> *cells = [NSMutableArray arrayWithCapacity:row.children.count];
|
||||
for (MarkdownASTNode *cell in row.children) {
|
||||
[cells addObject:markdownFromASTNodeChildren(cell)];
|
||||
[cells addObject:markdownFromTableCell(cell)];
|
||||
}
|
||||
[buffer appendFormat:@"| %@ |\n", [cells componentsJoinedByString:@" | "]];
|
||||
if (!headerDone) {
|
||||
@@ -321,13 +321,13 @@ NSString *markdownFromASTNode(MarkdownASTNode *node)
|
||||
return [buffer copy];
|
||||
}
|
||||
|
||||
NSString *markdownFromASTNodeChildren(MarkdownASTNode *node)
|
||||
NSString *markdownFromTableCell(MarkdownASTNode *cell)
|
||||
{
|
||||
if (!node)
|
||||
if (!cell)
|
||||
return @"";
|
||||
NSMutableString *buffer = [NSMutableString string];
|
||||
serializeChildren(node, buffer);
|
||||
return [buffer copy];
|
||||
serializeChildren(cell, buffer);
|
||||
return [buffer stringByReplacingOccurrencesOfString:@"\\\n" withString:@"<br>"];
|
||||
}
|
||||
|
||||
NSString *markdownFromBlockquoteBody(MarkdownASTNode *node)
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -39,10 +39,7 @@ import { buildStoredAgentPayload, toAgentPayload } from "./agent-projections.js"
|
||||
import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import { projectTimelineRows } from "./timeline-projection.js";
|
||||
import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
|
||||
import {
|
||||
createAgentMessageDelivery,
|
||||
createMemoryAgentMessageQueueStore,
|
||||
} from "./agent-messages/index.js";
|
||||
import { createAgentMessageDelivery } from "./agent-messages/index.js";
|
||||
import { AgentTurnBusyError, sendPreparedPromptToAgent, startAgentRun } from "./agent-prompt.js";
|
||||
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
|
||||
import { ensureAgentLoaded, ensureUnarchivedAgentLoaded } from "./agent-loading.js";
|
||||
@@ -17004,7 +17001,6 @@ test.each([
|
||||
});
|
||||
let tick = () => {};
|
||||
const delivery = createAgentMessageDelivery({
|
||||
store: createMemoryAgentMessageQueueStore(),
|
||||
isRunning: (id) => manager.hasInFlightRun(id),
|
||||
subscribe: (notify) =>
|
||||
manager.subscribe(
|
||||
@@ -17040,9 +17036,9 @@ test.each([
|
||||
try {
|
||||
await startAgentRun(manager, agent.id, "original", logger);
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
const receipt = await delivery.enqueue({
|
||||
const receipt = delivery.enqueue({
|
||||
recipientId: agent.id,
|
||||
text: "queued",
|
||||
prompt: "queued",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
tick();
|
||||
@@ -17085,7 +17081,6 @@ test.each(["turn_completed", "turn_failed", "turn_canceled"] as const)(
|
||||
let tick = () => {};
|
||||
const settledStates: boolean[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
store: createMemoryAgentMessageQueueStore(),
|
||||
isRunning: (id) => manager.hasInFlightRun(id),
|
||||
subscribe: (notify) =>
|
||||
manager.subscribe(
|
||||
@@ -17114,9 +17109,9 @@ test.each(["turn_completed", "turn_failed", "turn_canceled"] as const)(
|
||||
try {
|
||||
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "autonomous" });
|
||||
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(true));
|
||||
await delivery.enqueue({
|
||||
delivery.enqueue({
|
||||
recipientId: agent.id,
|
||||
text: "queued report",
|
||||
prompt: "queued report",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
tick();
|
||||
|
||||
@@ -236,14 +236,6 @@ export class AgentProviderSwitchStartError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** A provider switch named the provider the agent is already on. */
|
||||
export class AgentAlreadyOnProviderError extends Error {
|
||||
constructor(agentId: string, provider: AgentProvider) {
|
||||
super(`Agent ${agentId} is already using provider '${provider}'`);
|
||||
this.name = "AgentAlreadyOnProviderError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface SwitchAgentProviderInput {
|
||||
toProvider: AgentProvider;
|
||||
model?: string | null;
|
||||
@@ -252,11 +244,6 @@ export interface SwitchAgentProviderInput {
|
||||
providerOptions?: ProviderOptions | null;
|
||||
prompt: AgentPromptInput;
|
||||
messageId: string;
|
||||
/**
|
||||
* Cut a running turn for the switch instead of rejecting it. The cut is not a Stop. A target
|
||||
* that is disabled or unavailable leaves the turn running.
|
||||
*/
|
||||
interruptRunning?: boolean;
|
||||
/**
|
||||
* Optional hook invoked while the switch still holds exclusive admission on `agentId`,
|
||||
* after the target session is registered. Callers pass `switchReservationToken` into
|
||||
@@ -277,7 +264,7 @@ export interface SwitchAgentProviderResult {
|
||||
context: ProviderSwitchContextSummary;
|
||||
}
|
||||
|
||||
type RunCancellationCause = "reload" | "replace" | "rewind" | "stop" | "switch";
|
||||
type RunCancellationCause = "reload" | "replace" | "rewind" | "stop";
|
||||
|
||||
export class AgentRunCancellationError extends Error {
|
||||
constructor(agentId: string, action: RunCancellationCause) {
|
||||
@@ -2535,14 +2522,6 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** Cut a running turn for a switch, once the target is known to be usable. */
|
||||
private async interruptRunForSwitch(agentId: string, toProvider: AgentProvider): Promise<void> {
|
||||
if (!this.hasInFlightRun(agentId)) return;
|
||||
this.requireEnabledProvider(toProvider);
|
||||
await this.requireAvailableClient({ provider: toProvider });
|
||||
await this.cancelAgentRunBefore(agentId, "switch");
|
||||
}
|
||||
|
||||
private async ensureSourceAgentReadyForSwitch(
|
||||
agentId: string,
|
||||
scope: TimelineScope,
|
||||
@@ -2802,7 +2781,6 @@ export class AgentManager {
|
||||
|
||||
const scope: TimelineScope = { agentId };
|
||||
const storedRecord = this.registry ? await this.registry.get(agentId) : null;
|
||||
if (input.interruptRunning) await this.interruptRunForSwitch(agentId, input.toProvider);
|
||||
const existingLive = await this.ensureSourceAgentReadyForSwitch(agentId, scope, storedRecord);
|
||||
const source = await this.extractSwitchSourceContext(agentId, existingLive, storedRecord);
|
||||
if (input.toProvider === source.fromProvider) {
|
||||
@@ -2818,7 +2796,7 @@ export class AgentManager {
|
||||
if (resumed) {
|
||||
return resumed;
|
||||
}
|
||||
throw new AgentAlreadyOnProviderError(agentId, input.toProvider);
|
||||
throw new Error(`Agent ${agentId} is already using provider '${input.toProvider}'`);
|
||||
}
|
||||
|
||||
this.requireEnabledProvider(input.toProvider);
|
||||
@@ -5519,10 +5497,7 @@ export class AgentManager {
|
||||
return { status: "settled" };
|
||||
}
|
||||
|
||||
private async cancelAgentRunBefore(
|
||||
agentId: string,
|
||||
action: "reload" | "rewind" | "switch",
|
||||
): Promise<void> {
|
||||
private async cancelAgentRunBefore(agentId: string, action: "reload" | "rewind"): Promise<void> {
|
||||
const result = await this.cancelRun(agentId, action);
|
||||
if (result.status === "refused") {
|
||||
throw new AgentRunCancellationError(agentId, action);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user