Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 6c744f903d fix(server): clear dirty flag before reading in memory collection backend
Clear partition.dirty before awaiting options.read() (restoring it on error)
and loop in read() while dirty so a mutation arriving during an unsubscribed
read cannot leave the cached partition stale.

Also add a real-browser Playwright test in composer-queue.spec.ts verifying
that switching away from a retained agent tab and returning catches up on
queue changes made while hidden.
2026-11-30 16:59:24 +01:00
Mohamed Boudra fe99a08b9d refactor(protocol,server,client,app): replace synced-resource with storage-agnostic sync library
Replace the whole-snapshot synced-resource layer with a storage-agnostic
cursor-sync protocol and library across protocol, server, client, and app:

- protocol (src/sync/): zero-Zod descriptors (defineSyncStream,
  defineSyncCollection, AgentQueueCollection) and pure zod-aot schemas with
  nested args, { epoch, afterSeq } cursors, mode: snapshot | changes deltas,
  tail/after/before paging, and per-subscription prevSeq on updates.
- server (server/sync/): SyncBackend interface for in-memory or durable
  backends, handleSyncRequest (authorize, attach-before-read, live buffering,
  per-session projectResponse/projectLive, prevSeq stamping), shared
  VersionedCollection (reused by directory-sync), and bounded-LRU lazy-diff
  createMemoryCollectionBackend. Rewire agent.queue onto agent.queue.sync.*.
- client (src/sync/): SyncedStoreRegistry with single subscribe()->unsub API
  (no .release()), ref-counting, real delta merging, gap/epoch catch-up loops,
  backward loadOlder() paging, exponential backoff with reconnect recovery,
  and pluggable SyncPersistence.
- app (src/sync/): thin useSync / useSyncCollection hooks gated on
  useRetainedPanelActive() and host features; slim agent-queue to queue
  commands and busy guards.
- End-to-end proofs covering production agent.queue, a chat timeline over
  both memory and durable node:sqlite (restart epoch survival, paging, chunks,
  rewinds, gap recovery, cold-start persistence), and a filtered agent
  directory (normalized keys, tombstones, per-session filtering without false
  gaps, LRU eviction, backoff).
2026-11-30 16:48:12 +01:00
Mohamed Boudra 1999c5bddb fix(protocol,client): keep synced resource descriptors free of zod
Split the zero-Zod SyncedResourceDescriptor and AgentQueueResource descriptor
out of @getpaseo/protocol/messages so @getpaseo/client and thin CLI commands
do not pull messages.ts or zod into the static startup graph.
2026-11-30 14:43:04 +01:00
Mohamed Boudra 05af294572 refactor(protocol,server,client,app): add cursor-synced resource primitive for agent queue
Replace the daemon-wide agent.queue.update event subscription and separate
list fetch with a shared cursor-synced resource primitive:

- protocol: defineSyncedResource({ prefix, scope, value }) generates list
  request/response/update schemas with optional subscribe and generation/seq
  sync cursors; remove agent.queue.update from SessionEventSubscriptionSchema.
- server: daemon-scoped SyncedResourceSource + handleSyncedResourceListRequest
  track per-scope monotonic seq, answer matching cursors with mode: unchanged
  without reading, and emit scoped updates only to active subscribers.
- client: SyncedResourceRegistry ref-counts one server subscription per
  (prefix, scopeKey), retains cursors in a bounded LRU cache on release, and
  resumes with afterSeq on reconnect or re-focus.
- app: synced-resource model and useSyncedResource hook gate subscriptions on
  panel visibility and host features; agent-queue composes on top for withdraw,
  promote, and per-row busy guards.
2026-11-30 14:23:54 +01:00
Mohamed Boudra 91fd0a7685 fix(app): cap composer input independently of dock queue track
ComposerViewportContent previously applied the 0.6x inline editing cap to the entire composer slot, including ComposerQueueTrack. On compact phones after keyboard open/close, restoring an attachment pill grew MessageInput enough to collapse the queued message list to ~10px.

Bound the outer dock slot to the full viewport capacity, move the 0.6x inline cap onto ComposerInputCap around the input box, and cap compact queue rows at 140dp so ~2 queued rows stay usable alongside a restored image pill.
2026-11-30 12:49:40 +01:00
Mohamed Boudra 45be9ebe6c fix(app): steer instead of interrupting on a host without a message queue
A "queue" send behavior fell back to "interrupt" on an older host, which
killed the running turn the user meant to wait for.
2026-11-30 11:53:40 +01:00
Mohamed Boudra e771e671f9 feat(app): queue a staged provider switch with its message
A prompt sent mid-turn with a staged switch goes to the host's queue with
the switch. Its row names the target provider, and Edit stages the switch
again.

Edits to the target's settings after queuing apply to the next message,
not to the queued one.

Refs #8436, #9023
2026-11-30 11:53:40 +01:00
Mohamed Boudra 1f07c32cf9 test(server): cover a queued message the timeline already holds after a crash 2026-11-30 11:53:39 +01:00
Mohamed Boudra 071ea27448 feat(protocol,server,client): queue a provider switch behind a running turn
A switch staged mid-turn relied on the app holding the prompt until the
turn ended. The host owns the queue now, so the queued message carries the
target provider and settings and the host switches when its turn comes.

The queued switch divides the queue: nothing ahead of it moves to the new
provider and nothing behind it runs on the old one. A switch that fails
keeps the message and holds the queue.

The switch request's new fields are optional. The client refuses to send a
queued switch to a host without the message queue, which would otherwise
drop the field and switch at once.

Refs #8436, #9023
2026-11-30 11:53:39 +01:00
Mohamed Boudra 33e0a862d8 fix(server): set aside a corrupt agent queue file instead of failing startup
One unreadable file under agent-queues/ stopped the daemon from booting.
It is renamed so it can be inspected, a warning is logged, and every other
queue loads.
2026-11-30 11:53:39 +01:00
Mohamed Boudra c3ea1a90c0 fix(app): keep the composer on screen with a long message queue
The queue list had no height limit and could not shrink, so enough rows
pushed the message input and Stop past the bottom of the window with no way
to scroll back. The rows now scroll in a capped frame that gives up height
before the input does. The frame is a View because the web build drops
Unistyles styles on the shared ScrollView.

Also keeps row icons from being squashed by a long sender name, puts row
text on the composer's text rail, and focuses the input after Edit.
2026-11-30 11:05:42 +01:00
Mohamed Boudra 6c05edbc5d feat(app): show the host's message queue above the composer
The app kept its own queue and sent it when it saw the agent stop. A
reload lost the queued messages, nothing was sent with the app closed,
and other clients and agent senders could not be seen. The host now owns
the queue; the app only lists it and asks the host to withdraw or send a
row.

Behavior changes:
- Stop leaves queued messages paused instead of sending them.
- Sending a message directly (steer or interrupt) delivers the queued
  messages ahead of it.
- Hosts without the agent message queue have no Queue action, and a
  "queue" send behavior interrupts.

Edit restores uploads as references to the files the host holds, so it
works after a reload or from another device without uploading again.

Refs #8436, #9023
2026-11-30 11:05:42 +01:00
Mohamed Boudra 5bb8e4f77b feat(protocol,server,client): add agent message queue RPCs and client sync
Expose the daemon's durable per-agent message queue over the session protocol so clients can hydrate, observe live updates, withdraw, and promote queued messages without maintaining a local queue.

- Keep queue updates opt-in via session.events.set_subscription and legacyWantsEvent=false so older clients never receive unknown frames.
- Sequence per-agent queue broadcasts on the session so out-of-order storage reads cannot overwrite newer queue state, while still publishing empty lists when an archived or deleted agent's queue is cleared.
- Ignore AbortError on withdrawn queued dispatch promises so user or lifecycle withdrawals do not log spurious run errors.

Refs #8436, #9023
2026-11-30 11:02:36 +01:00
Mohamed Boudra 63d3fc3df3 feat(server): keep queued agent messages across daemon restarts
Queued messages lived in memory. A crash lost them, a restored finish
subscription then reported a child that never ran its task, and a clean
shutdown forced a flush into busy agents and swallowed the failures.

The daemon now saves a message before acknowledging it, leaves the queue
in place on shutdown, and checks the recipient's history after a crash
before sending an interrupted dispatch again.

Behavior changes:
- A provider that refuses to start a turn no longer drops the message. It
  stays queued and the queue is held, because retrying alone would be
  refused again and add the prompt to the history each time. The sender's
  finish notice waits until the message is delivered.
- Retrying a queued send with the same messageId is acknowledged at once
  instead of blocking until delivery.

Refs #8436
2026-11-30 11:02:31 +01:00
Mohamed Boudra 89826f0961 feat(server): add durable agent message queue store
Define the AgentMessageQueueStore interface along with atomic per-agent JSON and in-memory adapters and shared contract tests.

This is the persistence foundation for unifying human and agent message queues behind a SQLite-ready store boundary. Withdraw and promote return atomic discriminated outcomes inside the per-recipient lock so callers avoid racy pre-reads against active dispatches.
2026-11-30 11:00:20 +01:00
135 changed files with 14274 additions and 3015 deletions
+79 -13
View File
@@ -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. 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.
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.
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,33 +170,64 @@ 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.
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.
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.
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. Recovery coalesces registrations for the same
caller, child, and host into one watch.
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.
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. Archived or deleted parents suppress delivery;
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;
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 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.
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.
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
@@ -397,6 +428,41 @@ 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). `packages/app/src/agent-queue/` reads it as the open
agent's `agent.queue` synced collection through `packages/app/src/sync/`, subscribed while the
agent's panel is visible. A hidden panel keeps its last rows and releases the subscription. When you
return or the host reconnects, the client sends its cursor and gets back only the rows added,
changed, or removed since. 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`.
+3
View File
@@ -60,6 +60,9 @@ $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
View File
@@ -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 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".
- **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".
- **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).
@@ -18,6 +18,7 @@ import {
expectComposerVisible,
cancelAgent,
composerLocator,
configureComposerInterruptSend,
expectQueuedMessageButton,
fillComposerDraft,
holdSendButton,
@@ -404,15 +405,6 @@ 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);
@@ -431,14 +423,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 page.getByRole("button", { name: "Send queued message now" }).click();
await submitMessage(page, prompt);
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(promptRow).toBeVisible();
await gate.waitForServerMessage("send_agent_message_response");
@@ -659,14 +651,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 page.getByRole("button", { name: "Send queued message now" }).click();
await submitMessage(page, prompt);
const promptRow = page.getByTestId("user-message").filter({ hasText: prompt });
const replacementAnswer = page.getByText("(end of synthetic stream)", { exact: true }).last();
await expect(promptRow).toBeVisible();
@@ -1098,6 +1090,7 @@ 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,
@@ -1343,6 +1336,8 @@ 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);
@@ -1351,19 +1346,22 @@ test.describe("Agent message submission", () => {
).toHaveCount(0);
});
await test.step("tapping Send still steers", async () => {
await test.step("tapping Send still steers and takes the queued row along", 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();
const request = await gate.waitForRequest(2);
expect(request.text).toBe(steeredPrompt);
expect(request.activeTurnBehavior).toBe("steer");
gate.accept();
gate.accept(1);
await expect(
page.getByTestId("user-message").filter({ hasText: steeredPrompt }),
).toHaveCount(1);
await expectQueuedMessageButton(page);
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(0);
await expect(
page.getByTestId("user-message").filter({ hasText: queuedPrompt }),
).toHaveCount(1);
});
} finally {
await agent.cleanup();
@@ -1380,26 +1378,21 @@ test.describe("Agent message submission", () => {
await replaySteeredSleepTurnInBrowser(page, testInfo, "codex");
});
test("restores overlapping queued sends when their connection fails", async ({
page,
}, testInfo) => {
test("restores the draft when queueing loses the connection", async ({ page }, testInfo) => {
test.setTimeout(120_000);
const gate = await gateNextAgentMessage(page);
const agent = await startRunningMockAgent(page, {
prefix: `overlapping-queued-send-${testInfo.workerIndex}-`,
prefix: `queue-connection-lost-${testInfo.workerIndex}-`,
model: "one-minute-stream",
prompt: "Keep the agent running while messages queue.",
prompt: "Keep the agent running while a message queues.",
});
const prompts = ["Restore the first queued send.", "Restore the second queued send."];
const prompt = "Keep this draft if queueing fails.";
try {
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 fillComposerDraft(page, prompt);
await sendDraftToQueue(page);
await gate.waitForRequest();
await gate.disconnect();
await expectQueuedSendFailuresRestored(page, prompts);
await expectFailedSubmissionRestored(page, prompt);
} finally {
await agent.cleanup();
}
@@ -0,0 +1,320 @@
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("switching away from a retained agent tab and returning catches up on queue changes", async ({
page,
}) => {
const initial = "Initial queued row.";
const hidden = "Arrived while hidden.";
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-hidden-",
title: "Queue first",
});
try {
await agent.client.createAgent({
provider: "mock",
cwd: agent.cwd,
workspaceId: agent.workspaceId,
title: "Queue second",
modeId: "load-test",
model: "e2e-fast-stream",
});
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueMessage(page, initial);
await page.getByRole("button", { name: "Queue second", exact: true }).click();
await queueThroughHost(agent, [hidden]);
await page.getByRole("button", { name: "Queue first", exact: true }).click();
await expect(queuedRows(page)).toContainText([initial, hidden]);
} 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,6 +499,56 @@ 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,
}) => {
@@ -1,5 +1,6 @@
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");
@@ -14,7 +15,7 @@ export async function awaitToolCall(page: Page, toolName: string | RegExp): Prom
}
export async function expectAgentIdle(page: Page, timeout = 30_000): Promise<void> {
await expect(page.getByRole("button", { name: /stop|cancel/i })).toHaveCount(0, { timeout });
await expect(agentStopButton(page)).toHaveCount(0, { timeout });
}
// The working indicator is an animated spinner View — no semantic ARIA role, testId is correct.
@@ -0,0 +1,141 @@
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() };
}
+13 -4
View File
@@ -103,8 +103,13 @@ 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 = page.getByRole("button", { name: /stop|cancel/i }).first();
const stopButton = agentStopButton(page).first();
await expect(stopButton).toBeVisible({ timeout: 10_000 });
await stopButton.click();
}
@@ -300,9 +305,7 @@ export async function startRunningMockAgent(
await page.goto(agentUrl);
await expectComposerVisible(page);
await client.sendAgentMessage(agent.id, opts.prompt);
await expect(page.getByRole("button", { name: /stop|cancel/i }).first()).toBeVisible({
timeout: 30_000,
});
await expect(agentStopButton(page).first()).toBeVisible({ timeout: 30_000 });
return {
client,
repo,
@@ -467,6 +470,12 @@ 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,6 +168,11 @@ 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,
@@ -182,9 +187,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 } } | null>;
fetchAgent(options: { agentId: string }): Promise<{
agent: { id: string; archivedAt?: string | null; pendingPermissions: Array<{ id: string }> };
} | null>;
getLastServerInfoMessage(): {
features?: {
projectAdd?: boolean;
+15
View File
@@ -0,0 +1,15 @@
import { useActivatedStore } from "@/sync";
import { createAgentQueueModel, type AgentQueueModel, type AgentQueueSnapshot } from "./model";
export type { AgentQueueModel, AgentQueueSnapshot } from "./model";
/** Observes one agent's queue while the caller is mounted in a visible panel. */
export function useAgentQueue(
serverId: string,
agentId: string,
): { model: AgentQueueModel; queue: AgentQueueSnapshot } {
const { store, snapshot } = useActivatedStore(JSON.stringify([serverId, agentId]), (active) =>
createAgentQueueModel({ serverId, agentId, initialActive: active }),
);
return { model: store, queue: snapshot };
}
+165
View File
@@ -0,0 +1,165 @@
import { afterEach, expect, test } from "vitest";
import {
queuedItem,
queueOf,
startAgentQueueDaemon,
type AgentQueueDaemon,
} from "@/test/agent-queue-daemon";
import { createAgentQueueModel } from "./model";
const daemons: AgentQueueDaemon[] = [];
afterEach(async () => {
await Promise.all(daemons.splice(0).map((daemon) => daemon.close()));
});
/** An observed queue model over a daemon that already holds the given rows. */
async function observeQueue(
queue = queueOf("a", "b"),
options?: Parameters<typeof startAgentQueueDaemon>[0],
) {
const daemon = await startAgentQueueDaemon(options);
daemons.push(daemon);
await daemon.publish("agent", queue);
const model = createAgentQueueModel({ serverId: "host", agentId: "agent", host: daemon.host });
model.subscribe(() => {});
await daemon.settle();
const rowIds = () => model.getSnapshot().items.map((entry) => entry.id);
return { daemon, model, rowIds };
}
test("shows the queue the host holds and follows its changes", async () => {
const held = { held: true, items: [queuedItem("a", { held: true })] };
const { daemon, model, rowIds } = await observeQueue(held);
expect(model.getSnapshot()).toEqual({ status: "ready", ...held, busy: new Set() });
expect(model.getSnapshot()).toBe(model.getSnapshot());
await daemon.publish("agent", queueOf("b"));
await daemon.settle();
expect(rowIds()).toEqual(["b"]);
expect(model.getSnapshot().held).toBe(false);
});
test("releases the host subscription while inactive and catches up on its changes", async () => {
const { daemon, model, rowIds } = await observeQueue();
model.setActive(false);
await daemon.settle();
expect(daemon.liveSubscriptions()).toEqual([]);
expect(model.getSnapshot().status).toBe("stale");
expect(rowIds()).toEqual(["a", "b"]);
await daemon.publish("agent", queueOf("b", "c"));
model.setActive(true);
await daemon.settle();
expect(daemon.syncAnswers()).toEqual(["snapshot", "changes"]);
expect(model.getSnapshot().status).toBe("ready");
expect(rowIds()).toEqual(["b", "c"]);
});
test("offers a retry when the queue cannot be read", async () => {
const daemon = await startAgentQueueDaemon();
daemons.push(daemon);
await daemon.publish("agent", queueOf("a"));
daemon.failNextSync("queue unavailable");
const model = createAgentQueueModel({ serverId: "host", agentId: "agent", host: daemon.host });
model.subscribe(() => {});
await daemon.settle();
expect(model.getSnapshot().status).toBe("error");
model.retry();
expect(model.getSnapshot().status).toBe("retrying");
await daemon.settle();
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [queuedItem("a")] });
});
test("marks a row busy while it is withdrawn, then hides it ahead of the host update", async () => {
const { daemon, model, rowIds } = await observeQueue();
const first = model.withdraw("a");
const second = model.withdraw("a");
expect(model.getSnapshot().busy).toEqual(new Set(["a"]));
expect(await first).toEqual({ withdrawn: true, item: queuedItem("a") });
expect(await second).toBeNull();
expect(daemon.commands()).toHaveLength(1);
expect(model.getSnapshot().busy).toEqual(new Set());
expect(rowIds()).toEqual(["b"]);
expect(await model.withdraw("a")).toBeNull();
// A later change to the row is the host's truth again.
await daemon.publish("agent", {
held: false,
items: [queuedItem("a", { text: "edited" }), queuedItem("b", { seq: 2 })],
});
await daemon.settle();
expect(rowIds()).toEqual(["a", "b"]);
});
test("hides a withdrawn row even when an older update overtakes the answer", async () => {
const { daemon, model, rowIds } = await observeQueue();
const result = model.withdraw("a");
await daemon.publish("agent", queueOf("a", "b", "c"));
await result;
await daemon.settle();
expect(rowIds()).toEqual(["b", "c"]);
});
test("keeps the row when the host already started sending it", async () => {
const { daemon, model, rowIds } = await observeQueue();
daemon.refuseWithdrawals("already_dispatching");
expect(await model.withdraw("a")).toEqual({ withdrawn: false, reason: "already_dispatching" });
expect(rowIds()).toEqual(["a", "b"]);
expect(model.getSnapshot().busy).toEqual(new Set());
});
test("takes no command for a dispatching or absent row", async () => {
const { daemon, model } = await observeQueue({
held: false,
items: [queuedItem("a", { state: "dispatching" })],
});
expect(await model.withdraw("a")).toBeNull();
expect(await model.promote("missing", "steer")).toBeNull();
expect(daemon.commands()).toEqual([]);
});
test("promotes a row with the chosen send behavior", async () => {
const { daemon, model } = await observeQueue();
expect(await model.promote("b", "interrupt")).toEqual({ promoted: true });
expect(daemon.commands()).toMatchObject([
{
type: "agent.queue.promote.request",
agentId: "agent",
messageId: "b",
activeTurnBehavior: "interrupt",
},
]);
});
test("rejects a command and releases the row while the host is disconnected", async () => {
const { daemon, model, rowIds } = await observeQueue();
await daemon.disconnect();
await daemon.settle();
await expect(model.withdraw("a")).rejects.toThrow("Host disconnected");
expect(daemon.commands()).toEqual([]);
expect(model.getSnapshot()).toMatchObject({ status: "stale", busy: new Set() });
expect(rowIds()).toEqual(["a", "b"]);
});
test("has no queue and asks nothing of a host without the feature", async () => {
const { daemon, model } = await observeQueue(queueOf("a"), { features: {} });
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
expect(daemon.requestCount()).toBe(0);
});
+128
View File
@@ -0,0 +1,128 @@
import { AgentQueueCollection, type PaseoAgentQueueItem, type SyncStatus } from "@getpaseo/client";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
import {
createHostSyncStore,
type HostSyncConnection,
hostRuntimeSyncHost,
type SyncClient,
} from "@/sync";
type AgentQueueClient = SyncClient &
Pick<DaemonClient, "withdrawAgentQueueItem" | "promoteAgentQueueItem">;
export interface AgentQueueSnapshot {
status: SyncStatus;
/** 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: readonly 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: a command changes
* nothing here until the host answers it.
*/
export function createAgentQueueModel({
serverId,
agentId,
initialActive,
host = hostRuntimeSyncHost(serverId),
}: {
serverId: string;
agentId: string;
initialActive?: boolean;
host?: HostSyncConnection<AgentQueueClient>;
}) {
const store = createHostSyncStore({
host,
resource: AgentQueueCollection,
args: { agentId },
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
feature: "agentMessageQueue",
active: initialActive,
});
let busy: ReadonlySet<string> = new Set();
// Rows the host confirmed it removed. A later change to a row arrives as a new row object.
const withdrawn = new WeakSet<PaseoAgentQueueItem>();
let view: { source: unknown; snapshot: AgentQueueSnapshot } | null = null;
const listeners = new Set<() => void>();
const getSnapshot = (): AgentQueueSnapshot => {
const source = store.getSnapshot();
if (view?.source !== source) {
view = {
source,
snapshot: {
status: source.status,
held: source.data?.meta.held ?? false,
items: source.data?.items.filter((item) => !withdrawn.has(item)) ?? [],
busy,
},
};
}
return view.snapshot;
};
const changed = () => {
view = null;
for (const listener of listeners) listener();
};
const connected = (): AgentQueueClient => {
const client = host.getClient();
if (!client?.getLastServerInfoMessage()) throw new Error("Host disconnected");
return client;
};
// The row as the host last sent it, which an update during a command may have replaced.
const hide = (messageId: string) => {
const row = store.getSnapshot().data?.items.find((entry) => entry.id === messageId);
if (row) withdrawn.add(row);
};
/** 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 = getSnapshot().items.find((entry) => entry.id === messageId);
if (!row || row.state === "dispatching" || busy.has(messageId)) return null;
busy = new Set(busy).add(messageId);
changed();
try {
return await run();
} finally {
const next = new Set(busy);
next.delete(messageId);
busy = next;
changed();
}
};
return {
getSnapshot,
subscribe(listener: () => void) {
listeners.add(listener);
const unsubscribe = store.subscribe(listener);
return () => {
listeners.delete(listener);
unsubscribe();
};
},
setActive: store.setActive,
retry: store.retry,
withdraw: (messageId: string) =>
command(messageId, async () => {
const result = await connected().withdrawAgentQueueItem(agentId, messageId);
// The host confirmed the removal. Hide the row now so it is not pressable again
// between this answer and the next update.
if (result.withdrawn) hide(messageId);
return result;
}),
promote: (messageId: string, activeTurnBehavior: ActiveTurnBehavior) =>
command(messageId, async () =>
connected().promoteAgentQueueItem(agentId, messageId, activeTurnBehavior),
),
};
}
export type AgentQueueModel = ReturnType<typeof createAgentQueueModel>;
+2
View File
@@ -108,6 +108,8 @@ 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,13 +131,18 @@ 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 <View style={styles.thumbnailPlaceholder} />;
return <AttachmentThumbnailPlaceholder />;
}
return <Image source={source} style={styles.thumbnail} />;
}
+156 -134
View File
@@ -25,22 +25,18 @@ import {
uploadFileAttachments,
cancelComposerAgent,
dispatchComposerAgentMessage,
editQueuedComposerMessage,
enqueueComposerAgentMessage,
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 = {
@@ -184,7 +180,7 @@ interface FakeSendCall {
text: string;
options: {
messageId: string;
activeTurnBehavior?: "interrupt" | "steer";
activeTurnBehavior?: "interrupt" | "steer" | "queue";
images?: Array<{ data: string; mimeType: string }>;
attachments: AgentAttachment[];
};
@@ -306,19 +302,6 @@ 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[]> =>
@@ -755,147 +738,186 @@ describe("dispatchComposerAgentMessage", () => {
});
});
describe("queueComposerMessage", () => {
it("queues a trimmed message under the agent id and returns the new entry", () => {
const queue = createFakeQueue();
const result = queueComposerMessage({
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,
agentId: "agent",
text: " draft ",
attachments: [],
queue,
text: " queue this ",
attachments: [{ kind: "image", metadata: imageWithId("img-queue") }, review],
uploadImages: passthroughUploadImages,
});
expect(result.queued?.text).toBe("draft");
expect(queue.state.get("agent")).toEqual([
{ id: result.queued?.id, text: "draft", attachments: [] },
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",
}),
],
},
},
]);
});
it("does not queue an empty message with no attachments", () => {
const queue = createFakeQueue();
const result = queueComposerMessage({
agentId: "agent",
text: " ",
attachments: [],
queue,
});
expect(result.queued).toBeNull();
expect(queue.state.get("agent")).toBeUndefined();
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("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,
});
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;
expect(queue.state.get("agent")?.[0]?.attachments).toEqual([
{ kind: "image", metadata: image },
review,
const input: Parameters<typeof enqueueComposerAgentMessage>[0] = {
client: {
...client,
switchAgentProvider: async (agentId, options) => {
switches.push({ agentId, options });
return {};
},
},
agentId: "agent",
text: "do Z",
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: [],
},
},
]);
});
});
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("rejects when the host refuses the message", async () => {
const rejection = new Error("Agent not found");
const client = createFakeSendClient({ rejection });
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],
},
],
],
]),
);
const result = editQueuedComposerMessage({ agentId: "agent", messageId: "msg-1", queue });
expect(result).toEqual({
text: "queued draft",
attachments: [{ kind: "image", metadata: image }],
});
expect(queue.state.get("agent")).toEqual([]);
await expect(
enqueueComposerAgentMessage({ client, agentId: "agent", text: "hello", attachments: [] }),
).rejects.toBe(rejection);
});
});
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({
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,
},
};
it("queues the same uploaded image again without uploading it", async () => {
const client = createFakeSendClient();
await enqueueComposerAgentMessage({
client,
agentId: "agent",
messageId: "msg-1",
queue,
submitMessage: async (input) => {
submitted.push(input);
},
text: "again",
attachments: [restoredImage],
});
expect(result).toEqual({ status: "missing" });
expect(submitted).toEqual([]);
expect(client.uploadCalls).toEqual([]);
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
});
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({
it("shows a sent uploaded image as an image on the optimistic message", async () => {
const client = createFakeSendClient();
const stream = createFakeStream();
await dispatchComposerAgentMessage({
client,
agentId: "agent",
messageId: "msg-1",
queue,
submitMessage: async (input) => {
submitted.push(input);
},
text: "look",
attachments: [restoredImage],
submission: stream,
});
expect(result).toEqual({ status: "submitted" });
expect(queue.state.get("agent")).toEqual([]);
expect(submitted).toEqual([{ text: "send me", attachments: [review] }]);
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("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");
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");
},
openWorkspaceAttachment: () => false,
openExternalUrl: (url) => urls.push(url),
});
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"]);
expect(urls).toEqual([issueItem.url]);
});
});
+83 -155
View File
@@ -4,6 +4,8 @@ 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,
@@ -15,10 +17,8 @@ import type {
ComposerAttachment,
UserComposerAttachment,
} from "@/attachments/types";
import {
isWorkspaceAttachment,
userAttachmentsOnly,
} from "@/attachments/workspace-attachment-utils";
import { isWorkspaceAttachment } from "@/attachments/workspace-attachment-utils";
import { forgeItemKey } from "@/composer/attachments/forge-item-key";
import {
splitComposerAttachmentsForSubmit,
type ComposerAttachmentSubmitFormat,
@@ -27,6 +27,7 @@ import {
createPendingProviderSwitchItem,
createUserMessage,
generateMessageId,
toDaemonUploadedImageAttachments,
type ProviderSwitchItem,
type UserMessageItem,
} from "@/types/stream";
@@ -34,12 +35,6 @@ 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;
@@ -65,7 +60,7 @@ export interface ComposerSendClient {
text: string,
options: {
messageId: string;
activeTurnBehavior?: ActiveTurnBehavior;
activeTurnBehavior?: AgentActiveTurnBehavior;
images?: Array<{ data: string; mimeType: string }>;
attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
},
@@ -82,6 +77,7 @@ 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<{
@@ -106,13 +102,6 @@ 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<
@@ -258,12 +247,13 @@ 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,
attachments: wirePayload.attachments,
images: [...wirePayload.images, ...sent.images],
attachments: sent.attachments,
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
? { turnId: input.activeTurnId }
: {}),
@@ -275,12 +265,7 @@ export async function dispatchComposerAgentMessage(
pendingProviderSwitch ? { providerSwitch: pendingProviderSwitch } : undefined,
);
try {
const imagePayload = input.uploadImages
? { attachments: await input.uploadImages(wirePayload.images) }
: await prepareImageAttachmentsForSend({
client: input.client,
images: wirePayload.images,
});
const imagePayload = await prepareImagePayload(input, wirePayload.images);
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
const result = await input.client.switchAgentProvider(input.agentId, {
provider: input.stagedProviderSwitch.provider,
@@ -313,108 +298,70 @@ export async function dispatchComposerAgentMessage(
}
}
export interface QueueComposerMessageInput {
agentId: string;
text: string;
attachments: ComposerAttachment[];
queue: QueueWriter;
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 QueueComposerMessageResult {
queued: QueuedComposerMessage | null;
}
export function queueComposerMessage(input: QueueComposerMessageInput): QueueComposerMessageResult {
const trimmed = input.text.trim();
if (!trimmed && input.attachments.length === 0) {
return { queued: null };
/** 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);
}
}
const item: QueuedComposerMessage = {
id: generateMessageId(),
text: trimmed,
attachments: input.attachments,
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 ?? [])],
};
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;
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
await input.client.switchAgentProvider(input.agentId, {
...input.stagedProviderSwitch,
...queued,
text,
});
return {
status: "failed",
errorMessage:
error instanceof Error
? error.message
: (input.failedToSendMessage ?? i18n.t("composer.errors.failedToSend")),
};
input.onProviderSwitchQueued?.();
return;
}
await input.client.sendAgentMessage(input.agentId, text, queued);
}
export interface OpenComposerAttachmentInput {
@@ -432,6 +379,13 @@ 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;
@@ -445,31 +399,11 @@ 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) =>
isForgeAttachment(attachment) &&
attachment.item.kind === item.kind &&
attachment.item.number === item.number;
const matches = (attachment: UserComposerAttachment) => isSameForgeItem(attachment, item);
if (current.some(matches)) {
return current.filter((attachment) => !matches(attachment));
}
@@ -487,12 +421,7 @@ export function toggleForgeAttachmentFromPicker({
item,
markForgeAttachmentRemoved,
}: ToggleForgeAttachmentFromPickerInput): UserComposerAttachment[] {
const existingAttachment = current.find(
(attachment) =>
isForgeAttachment(attachment) &&
attachment.item.kind === item.kind &&
attachment.item.number === item.number,
);
const existingAttachment = current.find((attachment) => isSameForgeItem(attachment, item));
if (existingAttachment) {
markForgeAttachmentRemoved(existingAttachment);
}
@@ -510,10 +439,9 @@ export function isAttachmentSelectedForForgeItem(
current: readonly ComposerAttachment[],
item: ForgeSearchItem,
): boolean {
return userAttachmentsOnly(current).some(
(attachment) =>
isForgeAttachment(attachment) &&
attachment.item.kind === item.kind &&
attachment.item.number === item.number,
);
return current.some((attachment) => isSameForgeItem(attachment, item));
}
function isSameForgeItem(attachment: ComposerAttachment, item: ForgeSearchItem): boolean {
return forgeItemKey(attachment) === `${item.kind}:${item.number}`;
}
@@ -0,0 +1,33 @@
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;
}
}
@@ -0,0 +1,102 @@
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,6 +55,11 @@ 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") {
if (result === "submitted" || result === "queued") {
clearSentAttachments(outgoingAttachments);
}
if (result === "queued" || result === "submitted" || result === "failed") {
@@ -82,9 +82,8 @@ function ComposerViewport({
);
}
/** Bound the complete composer (including its controls), not just the text input. */
/** Bound the complete composer slot (tracks and input) to the visible viewport capacity. */
function ComposerViewportContent({ style, ...props }: ViewProps) {
const compact = useIsCompactFormFactor();
const sizing = useContext(ViewportSizing);
if (!sizing) throw new Error("ComposerViewportContent requires ComposerViewport");
const constraint = useAnimatedStyle(() => ({
@@ -93,7 +92,7 @@ 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: resolveInlineComposerCapacity(sizing.value?.capacity, compact),
maxHeight: sizing.value?.capacity,
}));
return (
@@ -101,6 +100,55 @@ function ComposerViewportContent({ style, ...props }: ViewProps) {
);
}
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>
);
}
/**
* The keyboard only needs to move a centered form once it reaches the form's resting bottom.
* Fullscreen keeps the inline measurements: it does not translate, and re-measuring the
@@ -294,6 +342,7 @@ 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.
+65 -24
View File
@@ -1,14 +1,25 @@
export { ComposerDockBackground } from "./internal/background";
export { ComposerFullscreenBody, ComposerFullscreenFooter } from "./internal/fullscreen";
import { ScrollView } from "@/components/ui/scroll-view";
import { useState, useCallback, useMemo, useRef, type ReactNode } from "react";
import {
createContext,
useCallback,
useContext,
useMemo,
useRef,
useState,
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;
@@ -21,40 +32,39 @@ 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(
() => ({ maxHeight: resolveInlineComposerCapacity(surfaceSize?.height, compact) }),
[surfaceSize?.height, compact],
() =>
surfaceSize?.height !== undefined
? inlineUnistylesStyle({ maxHeight: surfaceSize.height })
: undefined,
[surfaceSize?.height],
);
const measureViewport = useCallback((event: import("react-native").LayoutChangeEvent) => {
const { width, height } = event.nativeEvent.layout;
if (height > 0) setSurfaceSize({ width, height });
}, []);
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}
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}
</View>
{overlay}
</View>
);
}
return (
</View>
) : (
<View ref={surfaceRef} style={styles.surface} onLayout={measureViewport}>
<View style={styles.content}>{content}</View>
<View
@@ -67,12 +77,43 @@ 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.
+3 -14
View File
@@ -14,6 +14,7 @@ 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;
@@ -148,7 +149,7 @@ export function useComposerForgeAutoAttach(
]);
const markForgeAttachmentRemoved = useCallback((attachment: ComposerAttachment | undefined) => {
const key = attachmentKey(attachment);
const key = forgeItemKey(attachment);
if (key) {
removedRefKeysRef.current.add(key);
}
@@ -505,7 +506,7 @@ function isSameLookupTarget(
}
function hasForgeAttachment(attachments: UserComposerAttachment[], ref: ForgeRef): boolean {
return attachments.some((attachment) => attachmentKey(attachment) === forgeRefKey(ref));
return attachments.some((attachment) => forgeItemKey(attachment) === forgeRefKey(ref));
}
function forgeItemMatchesRef(item: ForgeSearchItem, ref: ForgeRef): boolean {
@@ -519,15 +520,3 @@ 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}`;
}
+186 -317
View File
@@ -17,16 +17,17 @@ 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,
@@ -64,9 +65,7 @@ import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { useShallow } from "zustand/shallow";
import {
ArrowRightLeft,
ArrowUp,
Square,
Pencil,
AudioLines,
CircleDot,
FileText,
@@ -106,19 +105,15 @@ import { focusWithRetries } from "@/utils/web-focus";
import {
cancelComposerAgent,
dispatchComposerAgentMessage,
editQueuedComposerMessage,
enqueueComposerAgentMessage,
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";
@@ -178,6 +173,12 @@ 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";
@@ -220,8 +221,6 @@ const composerImageAttachmentPersister: Pick<
persistFromFileUri: persistAttachmentFromFileUri,
};
type QueuedMessage = QueuedComposerMessage;
type AttachmentListUpdater =
| UserComposerAttachment[]
| ((prev: UserComposerAttachment[]) => UserComposerAttachment[]);
@@ -435,34 +434,6 @@ 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;
@@ -522,6 +493,22 @@ 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
@@ -725,54 +712,6 @@ 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;
@@ -1055,7 +994,6 @@ interface ComposerProps {
error?: string | null;
}
const EMPTY_ARRAY: readonly QueuedMessage[] = [];
const StableMessageInput = memo(MessageInput);
interface ComposerAutocompleteHandle {
@@ -1398,6 +1336,10 @@ function ComposerContentImpl({
const stagedProviderLabel = stagedSwitch
? resolveProviderLabel(stagedSwitch.provider, providerSnapshotEntries)
: null;
const providerLabel = useCallback(
(provider: string) => resolveProviderLabel(provider, providerSnapshotEntries),
[providerSnapshotEntries],
);
useEffect(() => {
if (
@@ -1413,7 +1355,6 @@ function ComposerContentImpl({
const handleCancelStagedSwitch = useCallback(() => {
clearStagedProviderSwitch(serverId, agentId);
setSendError(null);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
}, [agentId, serverId]);
const handleRetryFailedStartupSettings = useCallback(() => {
@@ -1426,16 +1367,6 @@ 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);
@@ -1453,7 +1384,6 @@ function ComposerContentImpl({
removeAttachment,
openAttachment,
beginSubmit,
clearSentAttachments,
completeSubmit,
resetSuppression,
} = composerWorkspaceAttachment.useBinding({
@@ -1801,7 +1731,6 @@ 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);
}
@@ -1877,43 +1806,37 @@ 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 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,
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,
attachments: queuedAttachments,
queue: queueWriter,
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);
},
});
if (!result.queued) return;
replaceUserInput("");
setSelectedAttachments([]);
resetSuppression();
clearSentAttachments(queuedAttachments);
},
[
agentId,
clearSentAttachments,
queueWriter,
resetSuppression,
setSelectedAttachments,
replaceUserInput,
],
[client, serverId, stagedSwitch, supportsForgeSearch, t],
);
const sendMessageWithContent = useCallback(
@@ -1929,12 +1852,15 @@ function ComposerContentImpl({
allowEmptySubmit,
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
submitBehavior,
isAgentRunning,
isAgentRunning: isAgentRunning && supportsQueue,
// 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: ({ message: queuedText, attachments: queuedAttachments }) => {
queueMessage(queuedText, queuedAttachments);
queueMessage: async ({ message: queuedText, attachments: queuedAttachments }) => {
if (submitBehavior !== "preserve-and-lock") {
beginSubmit(queuedAttachments);
}
await enqueueMessage(queuedText, queuedAttachments);
},
submitMessage: async ({ message: submitText, attachments: submitAttachments }) => {
if (submitBehavior !== "preserve-and-lock") {
@@ -1964,9 +1890,10 @@ function ComposerContentImpl({
beginSubmit,
clearDraft,
completeSubmit,
enqueueMessage,
hasExternalContent,
isAgentRunning,
queueMessage,
supportsQueue,
setSelectedAttachments,
replaceUserInput,
stagedSwitch,
@@ -2214,39 +2141,25 @@ function ComposerContentImpl({
});
}, [agentId, hasAgent, isConnected, serverId, voice]);
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, queueWriter, replaceUserInput, serverId, setSelectedAttachments],
);
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);
const handleRestoreQueuedMessage = useCallback(
(message: RestoredQueuedMessage) => {
replaceUserInput(message.text);
setSelectedAttachments(message.attachments);
if (message.providerSwitch) {
useStagedProviderSwitchStore.getState().stage(serverId, agentId, message.providerSwitch);
}
focusInput();
},
[agentId, queueWriter, serverId, submitMessage, t],
[agentId, focusInput, 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"));
},
[t],
);
const handleQueue = useCallback(
@@ -2265,15 +2178,15 @@ function ComposerContentImpl({
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
queueMessage(payload.text, outgoingAttachments);
void sendMessageWithContent(payload.text, outgoingAttachments);
},
[
attachments,
buildOutgoingAttachments,
pluginClientSlashCommands,
queueMessage,
runClientSlashCommand,
runPluginClientSlashCommand,
sendMessageWithContent,
],
);
@@ -2392,14 +2305,7 @@ function ComposerContentImpl({
);
const hasGithubAttachment = useMemo(
() =>
selectedAttachments.some(
(attachment) =>
attachment.kind === "forge_change_request" ||
attachment.kind === "forge_issue" ||
attachment.kind === "github_pr" ||
attachment.kind === "github_issue",
),
() => selectedAttachments.some((attachment) => forgeItemKey(attachment) !== null),
[selectedAttachments],
);
// Composer stays mounted for each focused agent, so avoid a forge CLI call
@@ -2645,18 +2551,6 @@ 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,
@@ -2699,8 +2593,7 @@ 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 || queuedSendError;
const displayError = externalError || sendError || failedStartupSettings?.errorMessage;
const sendErrorNode = useMemo(
() =>
displayError ? (
@@ -2771,6 +2664,60 @@ 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
@@ -2795,101 +2742,63 @@ function ComposerContentImpl({
dataSet={isFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
>
<View style={inputAreaContentStyle}>
{isFullscreen ? null : queueList}
{!isFullscreen && hasAgent && supportsQueue ? (
<ComposerQueueTrack
serverId={serverId}
agentId={agentId}
sendBehavior={appSettings.sendBehavior}
providerLabel={providerLabel}
onRestore={handleRestoreQueuedMessage}
onAlreadySending={handleQueuedMessageAlreadySending}
onError={handleQueueError}
/>
) : null}
{isFullscreen ? null : stagedSwitchBannerNode}
{!isFullscreen && sendErrorNode}
<ComposerAutocompleteBinding
text={textSource}
cursor={cursor}
recall={recall}
inputRef={messageInputRef}
anchorStyle={messageInputContainerStyle}
show={mode.showAutocomplete && !isFullscreen && !isComposerLocked}
ref={autocompleteRef}
configuration={autocompleteConfiguration}
>
<ComposerForgeBinding
<ComposerInputCap fullscreen={isFullscreen}>
<ComposerAutocompleteBinding
text={textSource}
configuration={forgeConfiguration}
ref={forgeAutoAttachRef}
onResolvingChange={setIsForgeResolving}
/>
{/* 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}
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}
/>
</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>
{/* 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}
/>
{pluginAttachments.picker}
</ComposerAutocompleteBinding>
</ComposerInputCap>
</View>
</View>
</View>
@@ -3015,43 +2924,6 @@ 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",
@@ -3081,8 +2953,6 @@ 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);
@@ -3092,7 +2962,6 @@ 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 (
+10 -3
View File
@@ -196,9 +196,16 @@ describe("dictation transcript behavior", () => {
describe("composer send behavior", () => {
it("sends immediately when queue mode cannot advance past a permission", () => {
expect(resolveActiveSendBehavior("queue", true)).toBe("interrupt");
expect(resolveActiveSendBehavior("queue", false)).toBe("queue");
expect(resolveActiveSendBehavior("steer", true)).toBe("steer");
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");
});
function actions() {
+6 -1
View File
@@ -9,8 +9,13 @@ export type SendBehavior = ActiveTurnBehavior | "queue";
export function resolveActiveSendBehavior(
sendBehavior: SendBehavior,
hasPendingPermission: boolean,
hostHasMessageQueue: boolean,
): SendBehavior {
return sendBehavior === "queue" && hasPendingPermission ? "interrupt" : 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";
}
interface ComposerSurfaceState {
@@ -9,6 +9,7 @@ export {
isStagedProviderSwitchInFlight,
settleCommittedProviderSwitch,
settleStagedProviderSwitch,
toStagedProviderSwitch,
useFailedStartupSettings,
useIsStagedProviderSwitchInFlight,
useStagedProviderSwitch,
@@ -27,6 +27,7 @@ import {
clearStagedProviderSwitch,
getFailedStartupSettings,
getStagedProviderSwitch,
settleCommittedProviderSwitch,
useStagedProviderSwitchStore,
} from "./index";
@@ -401,798 +402,115 @@ describe("app provider switching integration", () => {
expect(collapsed.tail.some((item) => item.kind === "provider_switch")).toBe(true);
});
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;
const sentDraft = {
provider: "codex",
model: "gpt-5.3",
thinkingOptionId: "low",
modeId: "auto",
providerOptions: { plan_mode: false },
};
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,
);
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);
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
...current,
model: "gpt-5.4",
modeId: "full-auto",
thinkingOptionId: "high",
providerOptions: { fast_mode: true },
providerOptions: { plan_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" },
);
const settled = await settleCommittedProviderSwitch({
serverId,
agentId: "agent-1",
sentDraft,
committedProvider: "codex",
client: {
setAgentModel: record("model"),
setAgentMode: record("mode"),
setAgentThinkingOption: record("thinking"),
setAgentOptions: record("options"),
},
});
sessionStore.clearSession(serverId);
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 },
]);
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
});
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(),
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: () => fakeClient,
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
getClientId: async () => "cid_startup_edit_ordering",
createClient: () => client,
connectToDaemon: async () => ({ client, serverId, hostname: null }),
getClientId: async () => "cid_rejected_startup_edits",
},
});
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 },
});
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,
});
};
// 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"]);
expect(await rejectEdit()).toEqual({
applied: false,
errorMessage: "Plan mode rejected by provider",
});
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
...current,
model: "gpt-5.4",
providerOptions: { plan_mode: true },
}));
// Fast turn finishes idle and triggers queue drain BEFORE switch + settings edits complete.
runtime.drainQueuedAgentMessage(serverId, "agent-1");
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "idle" } });
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();
// 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);
});
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",
);
});
expect(getFailedStartupSettings(serverId, "agent-1")?.bundle).toEqual({
options: { plan_mode: true },
});
// 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!
// The model picker clears the staged draft on a live change. The failure stays.
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");
});
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" },
}),
);
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);
sessionStore.clearSession(serverId);
useSessionStore.getState().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 } from "@getpaseo/protocol/messages";
import type { AgentConfigApply, QueuedProviderSwitch } from "@getpaseo/protocol/messages";
export interface StagedProviderSwitch {
provider: AgentProvider;
@@ -187,6 +187,17 @@ 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,
@@ -0,0 +1,144 @@
import type { PaseoAgentQueueItem } from "@getpaseo/client";
import { afterEach, describe, expect, it } from "vitest";
import { createAgentQueueModel } from "@/agent-queue/model";
import { startAgentQueueDaemon, type AgentQueueDaemon } from "@/test/agent-queue-daemon";
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",
};
const daemons: AgentQueueDaemon[] = [];
afterEach(async () => {
await Promise.all(daemons.splice(0).map((daemon) => daemon.close()));
});
/** A real queue model over a host that already holds one message. */
async function queueHolding(
message: PaseoAgentQueueItem,
options: { refuse?: "already_dispatching" } = {},
) {
const daemon = await startAgentQueueDaemon();
daemons.push(daemon);
await daemon.publish("agent", { held: false, items: [message] });
if (options.refuse) daemon.refuseWithdrawals(options.refuse);
const model = createAgentQueueModel({ serverId: "host", agentId: "agent", host: daemon.host });
model.subscribe(() => {});
await daemon.settle();
const restored: Array<{ text: string; attachments: unknown[] }> = [];
let alreadySending = 0;
return {
model,
promoted: () =>
daemon.commands().map((command) => `${command.messageId}:${command.activeTurnBehavior}`),
restored,
alreadySendingCount: () => alreadySending,
composer: {
restore: (value: { text: string; attachments: unknown[] }) => restored.push(value),
alreadySending: () => {
alreadySending += 1;
},
},
};
}
describe("editQueuedMessage", () => {
it("puts the withdrawn text and attachments back in the composer", async () => {
const queue = await queueHolding(queued);
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({
...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(queued, { refuse: "already_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(queued);
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(queued, { refuse: "already_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(queued);
await sendQueuedMessageNow({ model: queue.model, messageId: "a", sendBehavior });
expect(queue.promoted()).toEqual([expected]);
});
});
@@ -0,0 +1,56 @@
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",
);
}
+334
View File
@@ -0,0 +1,334 @@
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: readonly 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],
},
}));
@@ -0,0 +1,156 @@
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();
});
});
+82
View File
@@ -0,0 +1,82 @@
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;
+58 -28
View File
@@ -104,41 +104,71 @@ describe("submitAgentInput", () => {
expect(clearDraft).toHaveBeenCalledWith("sent");
});
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(
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 = () =>
submitAgentInput({
message: " queued message ",
attachments: [{ id: "img-1" }],
message: composer.text,
attachments: composer.attachments,
isAgentRunning: true,
canSubmit: true,
queueMessage,
submitMessage,
clearDraft,
setUserInput,
setAttachments,
setSendError,
setIsProcessing,
}),
).resolves.toBe("queued");
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 };
}
expect(queueMessage).toHaveBeenCalledWith({
message: "queued message",
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",
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 () => {
+6 -11
View File
@@ -11,7 +11,8 @@ export interface AgentInputSubmitActionInput<TAttachment> {
forceSend?: boolean;
isAgentRunning: boolean;
canSubmit: boolean;
queueMessage: (input: { message: string; attachments: TAttachment[] }) => void;
/** Resolves once the host has the message in its queue. */
queueMessage: (input: { message: string; attachments: TAttachment[] }) => Promise<void>;
submitMessage: (input: { message: string; attachments: TAttachment[] }) => Promise<void>;
clearDraft: (lifecycle: "sent" | "abandoned") => void;
setUserInput: (text: string) => void;
@@ -42,14 +43,7 @@ export async function submitAgentInput<TAttachment>(
return "noop";
}
if (input.isAgentRunning && !input.forceSend) {
input.queueMessage({ message: trimmedMessage, attachments });
if (shouldClearOnSubmit) {
input.setUserInput("");
input.setAttachments([]);
}
return "queued";
}
const shouldQueue = input.isAgentRunning && !input.forceSend;
// Clear immediately so the submitted timeline row and composer state stay in sync.
if (shouldClearOnSubmit) {
@@ -60,10 +54,11 @@ export async function submitAgentInput<TAttachment>(
input.setIsProcessing(true);
try {
await input.submitMessage({ message: trimmedMessage, attachments });
const deliver = shouldQueue ? input.queueMessage : input.submitMessage;
await deliver({ message: trimmedMessage, attachments });
input.clearDraft("sent");
input.setIsProcessing(false);
return "submitted";
return shouldQueue ? "queued" : "submitted";
} catch (error) {
input.onSubmitError?.(error);
if (shouldClearOnSubmit) {
+21 -2
View File
@@ -173,6 +173,26 @@ 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: "لصق صورة",
@@ -181,9 +201,8 @@ export const ar: TranslationResources = {
addIssueOrPr_mr: "أضف مشكلة أو MR",
dropImagesHere: "إسقاط الصور هنا",
dropFilesHere: "Drop files here",
editQueuedMessage: "تحرير الرسالة في قائمة الانتظار",
sendQueuedMessageNow: "إرسال رسالة في قائمة الانتظار الآن",
openImage: "فتح مرفق الصورة",
removeAttachment: "إزالة المرفق",
removeImage: "إزالة مرفق الصورة",
removeFile: "Remove file attachment",
openGithub: "افتح {{kind}} {{number}}",
+21 -2
View File
@@ -171,6 +171,26 @@ 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",
@@ -179,9 +199,8 @@ 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}}",
+21 -2
View File
@@ -174,6 +174,26 @@ 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",
@@ -182,9 +202,8 @@ 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}}",
+21 -2
View File
@@ -175,6 +175,26 @@ 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",
@@ -183,9 +203,8 @@ 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}}",
+21 -2
View File
@@ -174,6 +174,26 @@ 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: "画像を貼り付け",
@@ -182,9 +202,8 @@ export const ja: TranslationResources = {
addIssueOrPr_mr: "イシューまたはMRを追加",
dropImagesHere: "ここに画像をドロップ",
dropFilesHere: "ここにファイルをドロップ",
editQueuedMessage: "キューに入れたメッセージを編集",
sendQueuedMessageNow: "キューに入れたメッセージを今すぐ送信",
openImage: "画像添付ファイルを開く",
removeAttachment: "添付を削除",
removeImage: "画像添付ファイルを削除",
removeFile: "ファイル添付ファイルを削除",
openGithub: "{{kind}} {{number}}を開く",
+21 -2
View File
@@ -173,6 +173,26 @@ 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: "이미지 붙여넣기",
@@ -181,9 +201,8 @@ export const ko: TranslationResources = {
addIssueOrPr_mr: "이슈 또는 MR 추가",
dropImagesHere: "여기에 이미지를 끌어다 놓으세요",
dropFilesHere: "여기에 파일을 끌어다 놓으세요",
editQueuedMessage: "대기 중인 메시지 편집",
sendQueuedMessageNow: "대기 중인 메시지 지금 보내기",
openImage: "이미지 첨부 열기",
removeAttachment: "첨부 파일 삭제",
removeImage: "이미지 첨부 제거",
removeFile: "파일 첨부 제거",
openGithub: "{{kind}} {{number}} 열기",
+21 -2
View File
@@ -174,6 +174,26 @@ 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",
@@ -182,9 +202,8 @@ 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}}",
+21 -2
View File
@@ -174,6 +174,26 @@ 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: "Вставить изображение",
@@ -182,9 +202,8 @@ export const ru: TranslationResources = {
addIssueOrPr_mr: "Добавить проблему или MR",
dropImagesHere: "Скиньте изображения сюда",
dropFilesHere: "Переместите файлы сюда",
editQueuedMessage: "Изменить сообщение из очереди",
sendQueuedMessageNow: "Отправить сообщение из очереди сейчас",
openImage: "Открыть прикрепленное изображение",
removeAttachment: "Удалить вложение",
removeImage: "Удалить прикрепленное изображение",
removeFile: "Удалить прикрепленный файл",
openGithub: "Открыть {{kind}} {{number}}",
+21 -2
View File
@@ -173,6 +173,26 @@ 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: "粘贴图片",
@@ -181,9 +201,8 @@ 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,11 +65,7 @@ describe("AgentDirectoryReplica", () => {
const serverId = `agent-replica-history-${removal}`;
const store = useSessionStore.getState();
store.initializeSession(serverId, null);
const replica = new AgentDirectoryReplica(
serverId,
() => undefined,
() => undefined,
);
const replica = new AgentDirectoryReplica(serverId, () => undefined);
const draftKey = buildDraftStoreKey({ serverId, agentId: "agent" });
const draft = {
text: "Keep this unsent draft",
@@ -121,11 +117,7 @@ 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,
() => undefined,
);
const replica = new AgentDirectoryReplica(serverId, () => undefined);
replica.commitSnapshot([entry(payload("live"))], []);
replica.applyTurnLiveness("agent", {
type: "stream_open",
@@ -144,11 +136,7 @@ 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,
() => undefined,
);
const replica = new AgentDirectoryReplica(serverId, () => undefined);
expect(replica.submitTimelineAgent(replica.captureTimeline("agent"), payload("network"))).toBe(
true,
@@ -164,10 +152,8 @@ describe("AgentDirectoryReplica", () => {
const store = useSessionStore.getState();
store.initializeSession(serverId, null as unknown as DaemonClient);
const commits: DirectoryReplicaMutation[][] = [];
const replica = new AgentDirectoryReplica(
serverId,
() => undefined,
(mutations) => commits.push([...mutations]),
const replica = new AgentDirectoryReplica(serverId, (mutations) =>
commits.push([...mutations]),
);
replica.commitSnapshot([entry(payload("agent"))], []);
commits.length = 0;
@@ -199,38 +185,11 @@ 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,
() => undefined,
);
const replica = new AgentDirectoryReplica(serverId, () => undefined);
replica.commitSnapshot(
[
entry({
@@ -274,16 +233,11 @@ describe("AgentDirectoryReplica", () => {
store.clearSession(serverId);
});
it("uses turn liveness for stopped transitions even when protocol status disagrees", () => {
it("follows turn liveness even when protocol status disagrees", () => {
const serverId = "agent-replica-mismatched-status";
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,
);
const replica = new AgentDirectoryReplica(serverId, () => undefined);
replica.commitSnapshot(
[
entry({
@@ -314,7 +268,6 @@ describe("AgentDirectoryReplica", () => {
status: "idle",
turn: { phase: "idle" },
});
expect(stopped).toEqual(["agent"]);
store.clearSession(serverId);
});
@@ -322,11 +275,7 @@ 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,
() => undefined,
);
const replica = new AgentDirectoryReplica(serverId, () => undefined);
replica.commitSnapshot(
[
entry({
@@ -353,11 +302,7 @@ describe("AgentDirectoryReplica", () => {
const serverId = "agent-replica";
const store = useSessionStore.getState();
store.initializeSession(serverId, null as unknown as DaemonClient);
const replica = new AgentDirectoryReplica(
serverId,
() => undefined,
() => undefined,
);
const replica = new AgentDirectoryReplica(serverId, () => undefined);
replica.commitSnapshot([entry(payload("directory"))], []);
const directoryPlacement = useSessionStore
.getState()
@@ -390,11 +335,7 @@ 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,
() => undefined,
);
const replica = new AgentDirectoryReplica(serverId, () => undefined);
// A conversation opened from history arrives over its timeline, without the
// project placement the directory carries, and is a member from then on.
@@ -410,11 +351,7 @@ 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,
() => undefined,
);
const replica = new AgentDirectoryReplica(serverId, () => undefined);
const agentInStore = () => useSessionStore.getState().sessions[serverId]?.agents.get("agent");
replica.commitSnapshot([entry(payload("agent"))], []);
const before = agentInStore();
@@ -36,7 +36,6 @@ 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);
@@ -107,7 +106,6 @@ 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)]
@@ -146,11 +144,6 @@ 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())
@@ -214,11 +207,9 @@ 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,7 +222,6 @@ function createDirectory(
const client = new FakeDirectoryClient();
client.supportsWorkspaceLabels = options?.workspaceLabels === true;
const directory = new DirectorySync(serverId, {
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -302,7 +301,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -392,7 +390,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -448,7 +445,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -486,7 +482,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -783,7 +778,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -865,7 +859,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -925,7 +918,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -988,7 +980,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -1075,7 +1066,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -1120,7 +1110,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -1172,7 +1161,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -1297,7 +1285,6 @@ describe("DirectorySync session readiness", () => {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
@@ -1681,7 +1668,6 @@ it("fills every cached workspace beneath live updates received during the SQLite
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => {},
markAgentLoading: () => {},
markAgentReady: () => {},
markAgentError: () => {},
@@ -1827,7 +1813,6 @@ async function createDamagedLegacyProjectDirectory(serverId: string, renameSeq:
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => {},
markAgentLoading: () => {},
markAgentReady: () => {},
markAgentError: () => {},
@@ -2115,7 +2100,6 @@ it.each(["before", "during", "before-metadata", "damaged"] as const)(
};
client.projectResult = projectResult;
const callbacks = {
onAgentStoppedRunning: () => {},
markAgentLoading: () => {},
markAgentReady: () => {},
markAgentError: () => {},
@@ -2226,7 +2210,6 @@ it("batches a burst of 200 workspace_update frames into one mergeWorkspaces comm
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => {},
markAgentLoading: () => {},
markAgentReady: () => {},
markAgentError: () => {},
@@ -2318,7 +2301,6 @@ it("coalesces duplicate upserts and removals within a single workspace_update ba
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => {},
markAgentLoading: () => {},
markAgentReady: () => {},
markAgentError: () => {},
@@ -208,7 +208,6 @@ export class DirectorySync {
constructor(
private readonly serverId: string,
private readonly callbacks: {
onAgentStoppedRunning: (agentId: string) => void;
markAgentLoading: () => void;
markAgentReady: () => void;
markAgentError: (error: string) => void;
@@ -217,7 +216,7 @@ export class DirectorySync {
) {
const persist = (mutations: readonly DirectoryReplicaMutation[]) =>
this.checkpoints?.commitDirectoryMutations(this.serverId, mutations);
this.agents = new AgentDirectoryReplica(serverId, callbacks.onAgentStoppedRunning, persist);
this.agents = new AgentDirectoryReplica(serverId, persist);
this.workspaces = new WorkspaceDirectoryReplica(serverId);
}
@@ -97,12 +97,11 @@ export class AgentStoreProjection {
applyDelta(delta: AgentDirectoryDelta): {
agentId: string;
stoppedRunning: boolean;
agent?: Agent;
} {
if (delta.kind === "remove") {
this.removeFromDirectory(delta.agentId);
return { agentId: delta.agentId, stoppedRunning: false };
return { agentId: delta.agentId };
}
const normalized = normalizeAgentSnapshot(delta.agent, this.serverId);
const session = useSessionStore.getState().sessions[this.serverId];
@@ -128,7 +127,6 @@ 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,
};
}
@@ -193,7 +191,6 @@ 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,13 +76,11 @@ 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",
@@ -134,26 +132,11 @@ 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;
@@ -3896,123 +3879,6 @@ 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",
@@ -4457,362 +4323,6 @@ 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",
+2 -151
View File
@@ -82,19 +82,10 @@ 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";
@@ -1926,8 +1917,6 @@ 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>();
@@ -2171,7 +2160,6 @@ 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),
@@ -2878,24 +2866,7 @@ export class HostRuntimeStore {
}
}
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.
*/
/** Retries or discards the startup settings that failed to apply after a provider switch. */
async recoverFailedStartupSettings(
serverId: string,
agentId: string,
@@ -2903,8 +2874,6 @@ 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;
@@ -2912,124 +2881,7 @@ export class HostRuntimeStore {
return false;
}
const result = await applyFailedStartupSettings({ serverId, agentId, client });
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);
});
return result.applied;
}
applyAgentTurnLiveness(
@@ -3254,7 +3106,6 @@ 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,7 +186,6 @@ 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);
}
@@ -210,21 +209,6 @@ 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,6 +148,30 @@ 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,6 +4,7 @@ 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;
@@ -112,6 +113,7 @@ 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,
-68
View File
@@ -24,7 +24,6 @@ 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,
@@ -568,13 +567,6 @@ 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
@@ -760,17 +752,6 @@ 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;
@@ -828,8 +809,6 @@ function createInitialSessionState(
restoringWorkspaces: new Map(),
pendingPermissions: new Map(),
fileExplorer: new Map(),
queuedMessages: new Map(),
queuedSendErrors: new Map(),
};
}
@@ -2036,53 +2015,6 @@ 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) => {
+195
View File
@@ -0,0 +1,195 @@
import type {
CollectionState,
SyncCollectionDescriptor,
SyncReducer,
SyncSnapshot,
SyncStore,
SyncStreamDescriptor,
} from "@getpaseo/client";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ServerInfoStatusPayload } from "@getpaseo/protocol/messages";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
export type SyncFeature = keyof NonNullable<ServerInfoStatusPayload["features"]>;
export type SyncClient = Pick<DaemonClient, "getLastServerInfoMessage" | "sync">;
/** The client of one host, and word of when the client or its connection changes. */
export interface HostSyncConnection<Client extends SyncClient = SyncClient> {
getClient(): Client | null;
subscribe(listener: () => void): () => void;
}
export function hostRuntimeSyncHost(serverId: string): HostSyncConnection<DaemonClient> {
const runtime = getHostRuntimeStore();
return {
getClient: () => runtime.getClient(serverId),
subscribe: (listener) => runtime.subscribe(serverId, listener),
};
}
interface HostSyncStoreBaseOptions {
host: HostSyncConnection;
/** A host without this feature is never asked, and the resource reads `ready` with no data. */
feature?: SyncFeature;
/** Whether the store starts active. Default `true`. */
active?: boolean;
/** Entries per page, for streams that page. */
pageSize?: number;
}
export interface HostSyncCollectionOptions<TArgs, TItem, TMeta> extends HostSyncStoreBaseOptions {
resource: SyncCollectionDescriptor<string, TArgs, TItem, TMeta>;
args: TArgs;
}
export interface HostSyncStreamOptions<
TArgs,
TSnapshot,
TDelta,
TLive,
TState,
> extends HostSyncStoreBaseOptions {
resource: SyncStreamDescriptor<string, TArgs, TSnapshot, TDelta, TLive>;
args: TArgs;
/** Keep it stable: every store of one partition must fold with the same reducer. */
reducer: SyncReducer<TSnapshot, TDelta, TLive, TState>;
}
/** One synced partition on one host, as the app shows it. */
export interface HostSyncStore<TState> {
getSnapshot(): SyncSnapshot<TState>;
subscribe(listener: () => void): () => void;
/** An inactive store holds nothing on the host and keeps its last data as `stale`. */
setActive(active: boolean): void;
retry(): void;
loadOlder(): Promise<void>;
}
const LOADING: SyncSnapshot<never> = Object.freeze({
status: "loading",
data: null,
hasOlder: false,
loadingOlder: false,
error: null,
});
const UNSUPPORTED: SyncSnapshot<never> = Object.freeze({ ...LOADING, status: "ready" });
/**
* Follows a host's client for one partition. The client store owns the sync itself; this store
* only decides whether to hold it: while somebody listens, the store is active, and the connected
* host supports the resource. Whatever it showed last stays on screen as `stale` meanwhile.
*/
export function createHostSyncStore<TArgs, TItem, TMeta>(
options: HostSyncCollectionOptions<TArgs, TItem, TMeta>,
): HostSyncStore<CollectionState<TItem, TMeta>>;
export function createHostSyncStore<TArgs, TSnapshot, TDelta, TLive, TState>(
options: HostSyncStreamOptions<TArgs, TSnapshot, TDelta, TLive, TState>,
): HostSyncStore<TState>;
export function createHostSyncStore(
options: HostSyncStoreBaseOptions & {
resource: unknown;
args: unknown;
reducer?: unknown;
},
): HostSyncStore<unknown> {
const { host, feature, resource, args } = options;
const storeOptions = {
...(options.reducer ? { reducer: options.reducer } : {}),
...(options.pageSize !== undefined ? { pageSize: options.pageSize } : {}),
};
// `sync` is overloaded per resource kind; the public overloads above keep callers typed.
const open = (client: SyncClient) =>
(client.sync as (...input: unknown[]) => SyncStore<unknown>)(resource, args, storeOptions);
let active = options.active ?? true;
let snapshot: SyncSnapshot<unknown> = LOADING;
let attached: { client: SyncClient; store: SyncStore<unknown>; release: () => void } | null =
null;
let unsubscribeHost: (() => void) | null = null;
const listeners = new Set<() => void>();
const publish = (next: SyncSnapshot<unknown>) => {
if (
next.status === snapshot.status &&
next.data === snapshot.data &&
next.hasOlder === snapshot.hasOlder &&
next.loadingOlder === snapshot.loadingOlder &&
next.error === snapshot.error
) {
return;
}
snapshot = next;
for (const listener of Array.from(listeners)) listener();
};
const keepLast = (): SyncSnapshot<unknown> =>
snapshot.data === null
? LOADING
: { ...snapshot, status: "stale", loadingOlder: false, error: null };
// A client store that starts over has no data yet. Keep what is on screen until it does.
const forward = (store: SyncStore<unknown>) => {
const next = store.getSnapshot();
publish(next.status === "loading" && snapshot.data !== null ? keepLast() : next);
};
const attach = (client: SyncClient) => {
const store = open(client);
const entry = { client, store, release: () => {} };
attached = entry;
entry.release = store.subscribe(() => {
if (attached === entry) forward(store);
});
};
const detach = () => {
const previous = attached;
attached = null;
previous?.release();
};
const update = () => {
const client = listeners.size > 0 ? host.getClient() : null;
const serverInfo = client?.getLastServerInfoMessage() ?? null;
const unsupported =
serverInfo !== null && feature !== undefined && serverInfo.features?.[feature] !== true;
// The runtime keeps a client across reconnects but clears server info until the handshake.
// Meanwhile the client store restores its own subscription, so an attached store stays.
const handshaking = serverInfo === null && client !== null && attached?.client === client;
const target = active && !unsupported && (serverInfo !== null || handshaking) ? client : null;
if (target !== (attached?.client ?? null)) {
detach();
if (target) attach(target);
}
if (attached) forward(attached.store);
else publish(unsupported ? UNSUPPORTED : keepLast());
};
return {
getSnapshot: () => snapshot,
subscribe(listener) {
listeners.add(listener);
unsubscribeHost ??= host.subscribe(update);
update();
return () => {
if (!listeners.delete(listener) || listeners.size > 0) return;
unsubscribeHost?.();
unsubscribeHost = null;
update();
};
},
setActive(next) {
if (next === active) return;
active = next;
update();
},
retry() {
if (attached) attached.store.retry();
else update();
},
loadOlder: () => attached?.store.loadOlder() ?? Promise.resolve(),
};
}
+19
View File
@@ -0,0 +1,19 @@
export {
createHostSyncStore,
type HostSyncCollectionOptions,
type HostSyncConnection,
type HostSyncStore,
type HostSyncStreamOptions,
hostRuntimeSyncHost,
type SyncClient,
type SyncFeature,
} from "./host-store";
export {
type SyncCollectionResult,
type SyncResult,
type UseSyncOptions,
type UseSyncStreamOptions,
useActivatedStore,
useSync,
useSyncCollection,
} from "./react";
+144
View File
@@ -0,0 +1,144 @@
import type {
CollectionState,
SyncCollectionDescriptor,
SyncReducer,
SyncSnapshot,
SyncStatus,
SyncStreamDescriptor,
} from "@getpaseo/client";
import { useEffect, useMemo, useSyncExternalStore } from "react";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { createHostSyncStore, hostRuntimeSyncHost, type SyncFeature } from "./host-store";
export interface UseSyncOptions {
/** A host without this feature is never asked, and the resource reads `ready` with no data. */
feature?: SyncFeature;
/** `false` holds nothing on the host and keeps the last data as `stale`. Default `true`. */
enabled?: boolean;
/**
* Release the host subscription while the retained panel is hidden, and catch up from the
* cursor when it shows again. Default `true`.
*/
pauseWhenHidden?: boolean;
/** Entries per page, for streams that page. The host chooses when omitted. */
pageSize?: number;
}
export interface UseSyncStreamOptions<TSnapshot, TDelta, TLive, TState> extends UseSyncOptions {
/** Define it once at module level: every store of one partition folds with the same reducer. */
reducer: SyncReducer<TSnapshot, TDelta, TLive, TState>;
}
export interface SyncResult<TState> extends SyncSnapshot<TState> {
/** Retries now after an error. */
retry: () => void;
/** Loads the page before the oldest loaded entry, for streams that page backwards. */
loadOlder: () => Promise<void>;
}
interface ActivatableStore {
getSnapshot(): unknown;
subscribe(listener: () => void): () => void;
setActive(active: boolean): void;
}
/**
* Mounts a store that pauses while the retained panel it renders in is hidden. `key` names what
* the store observes: a new key builds a new store, and nothing else does.
*/
export function useActivatedStore<Store extends ActivatableStore>(
key: string,
create: (active: boolean) => Store,
options: Pick<UseSyncOptions, "enabled" | "pauseWhenHidden"> = {},
): { store: Store; snapshot: ReturnType<Store["getSnapshot"]> } {
const panelActive = useRetainedPanelActive();
const active = (options.enabled ?? true) && (panelActive || options.pauseWhenHidden === false);
// `create` and `active` are new on most renders. Only the key may replace the store.
// eslint-disable-next-line react-hooks/exhaustive-deps
const store = useMemo(() => create(active), [key]);
useEffect(() => {
store.setActive(active);
}, [store, active]);
const getSnapshot = store.getSnapshot as () => ReturnType<Store["getSnapshot"]>;
const snapshot = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
return { store, snapshot };
}
/** Observes a synced resource on a host while the caller is mounted in a visible panel. */
export function useSync<TArgs, TItem, TMeta>(
serverId: string,
resource: SyncCollectionDescriptor<string, TArgs, TItem, TMeta>,
args: TArgs,
options?: UseSyncOptions,
): SyncResult<CollectionState<TItem, TMeta>>;
export function useSync<TArgs, TSnapshot, TDelta, TLive, TState>(
serverId: string,
resource: SyncStreamDescriptor<string, TArgs, TSnapshot, TDelta, TLive>,
args: TArgs,
options: UseSyncStreamOptions<TSnapshot, TDelta, TLive, TState>,
): SyncResult<TState>;
export function useSync(
serverId: string,
resource:
| SyncCollectionDescriptor<string, unknown, unknown, unknown>
| SyncStreamDescriptor<string, unknown, unknown, unknown, unknown>,
args: unknown,
options: UseSyncOptions & { reducer?: SyncReducer<unknown, unknown, unknown, unknown> } = {},
): SyncResult<unknown> {
const { feature, pageSize, reducer } = options;
// Callers pass `args` inline, so the partition key names the store, not the object's identity.
const key = JSON.stringify([serverId, resource.prefix, resource.key(args), feature, pageSize]);
const { store, snapshot } = useActivatedStore(
key,
(active) =>
createHostSyncStore({
host: hostRuntimeSyncHost(serverId),
resource: resource as SyncStreamDescriptor<string, unknown, unknown, unknown, unknown>,
args,
reducer: reducer as SyncReducer<unknown, unknown, unknown, unknown>,
feature,
pageSize,
active,
}),
options,
);
return useMemo(
() => ({ ...snapshot, retry: store.retry, loadOlder: store.loadOlder }),
[snapshot, store],
);
}
export interface SyncCollectionResult<TItem, TMeta> {
status: SyncStatus;
error: Error | null;
/** In the resource's order. Empty until the host answers. */
items: readonly TItem[];
byId: ReadonlyMap<string, TItem>;
/** `null` until the host answers. */
meta: TMeta | null;
retry: () => void;
}
const NO_ITEMS: readonly never[] = [];
const NO_ITEMS_BY_ID: ReadonlyMap<string, never> = new Map<string, never>();
/** `useSync` for a collection, with its items and metadata at hand. */
export function useSyncCollection<TArgs, TItem, TMeta>(
serverId: string,
resource: SyncCollectionDescriptor<string, TArgs, TItem, TMeta>,
args: TArgs,
options?: Omit<UseSyncOptions, "pageSize">,
): SyncCollectionResult<TItem, TMeta> {
const { status, error, data, retry } = useSync(serverId, resource, args, options);
return useMemo(
() => ({
status,
error,
items: data?.items ?? NO_ITEMS,
byId: data?.byId ?? NO_ITEMS_BY_ID,
meta: data?.meta ?? null,
retry,
}),
[status, error, data, retry],
);
}
+407
View File
@@ -0,0 +1,407 @@
// @vitest-environment jsdom
import { AgentQueueCollection } from "@getpaseo/client";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { act, cleanup, renderHook } from "@testing-library/react";
import type { ReactNode } from "react";
import { afterEach, describe, expect, test } from "vitest";
import { RetainedPanelActivity } from "@/components/retained-panel";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { queuedItem, queueOf, startAgentQueueDaemon } from "@/test/agent-queue-daemon";
import {
connectDaemonClient,
createDirectoryBackend,
createDirectorySource,
createMemoryTimelineStore,
createSyncTestHost,
createTimelineBackend,
settle,
syncAnswers,
syncRequests,
syncRoute,
type SyncTestHost,
TestDirectory,
TestTimeline,
timelineReducer,
} from "@/test/sync-host";
import { useSync, useSyncCollection } from ".";
// The id the in-memory host announces in its server info.
const SERVER_ID = "sync-test-host";
const cleanups: Array<() => void | Promise<void>> = [];
afterEach(async () => {
cleanup();
for (const step of cleanups.splice(0).toReversed()) await step();
});
/** Puts `client` behind the app's host runtime, as a paired host would be. */
async function addHost(client: DaemonClient): Promise<void> {
const runtime = getHostRuntimeStore();
await runtime.upsertDirectConnection({
serverId: SERVER_ID,
endpoint: "localhost:1",
existingClient: client,
});
cleanups.push(() => runtime.removeHost(SERVER_ID));
}
async function startQueueDaemon(options?: Parameters<typeof startAgentQueueDaemon>[0]) {
const daemon = await startAgentQueueDaemon(options);
cleanups.push(() => daemon.close());
await addHost(daemon.client);
return daemon;
}
/** A host serving resources that exist only in tests. */
async function startTestHost(host: SyncTestHost<undefined>): Promise<DaemonClient> {
cleanups.push(() => host.close());
const client = await connectDaemonClient(host, undefined, { validate: false });
cleanups.push(() => client.close());
await addHost(client);
return client;
}
/** A retained panel a test shows and hides. Changes land on the next `rerender`. */
function retainedPanel(initiallyActive = true) {
const panel = {
active: initiallyActive,
wrapper: ({ children }: { children: ReactNode }) => (
<RetainedPanelActivity active={panel.active}>{children}</RetainedPanelActivity>
),
};
return panel;
}
const flush = () => act(settle);
/** The payloads of every message of `type` the host sent. */
function sentPayloads<T>(host: SyncTestHost<undefined>, type: string): T[] {
return host.connections.flatMap((connection) =>
connection.sent
.filter((message) => message.type === type)
.map((message) => (message as unknown as { payload: T }).payload),
);
}
describe("agent queue through useSyncCollection", () => {
function renderQueue(panel = retainedPanel()) {
const rendered = renderHook(
// A new args object every render, as an inline `{ agentId }` is.
({ agentId }: { agentId: string }) =>
useSyncCollection(
SERVER_ID,
AgentQueueCollection,
{ agentId },
{ feature: "agentMessageQueue" },
),
{ initialProps: { agentId: "agent" }, wrapper: panel.wrapper },
);
const rows = () =>
rendered.result.current.items.map((item) => `${item.id}:${item.state}`).join(" ");
return { ...rendered, panel, rows };
}
test("loads the queue, then follows its changes in FIFO order", async () => {
const daemon = await startQueueDaemon();
await daemon.publish("agent", queueOf("a", "b"));
const queue = renderQueue();
await flush();
expect(queue.result.current).toMatchObject({ status: "ready", meta: { held: false } });
expect(queue.rows()).toBe("a:queued b:queued");
await daemon.publish("agent", {
held: true,
items: [queuedItem("a", { state: "dispatching" }), queuedItem("b", { seq: 2 })],
});
await flush();
expect(queue.rows()).toBe("a:dispatching b:queued");
expect(queue.result.current.meta).toEqual({ held: true });
expect(queue.result.current.byId.get("a")?.state).toBe("dispatching");
await daemon.publish("agent", { held: true, items: [queuedItem("c", { seq: 3 })] });
await flush();
expect(queue.rows()).toBe("c:queued");
expect(daemon.updates()).toEqual([
{
upserts: [{ seq: expect.any(Number), value: queuedItem("a", { state: "dispatching" }) }],
removals: [],
meta: { held: true },
},
{
upserts: [{ seq: expect.any(Number), value: queuedItem("c", { seq: 3 }) }],
removals: [
{ id: "a", seq: expect.any(Number) },
{ id: "b", seq: expect.any(Number) },
],
},
]);
expect(daemon.syncRequests()).toHaveLength(1);
});
test("holds nothing while its panel is hidden and catches up with changes when shown", async () => {
const daemon = await startQueueDaemon();
await daemon.publish("agent", queueOf("a", "b"));
const queue = renderQueue(retainedPanel(false));
await flush();
expect(daemon.syncRequests()).toEqual([]);
expect(queue.result.current.status).toBe("loading");
queue.panel.active = true;
queue.rerender({ agentId: "agent" });
await flush();
expect(queue.rows()).toBe("a:queued b:queued");
expect(daemon.liveSubscriptions()).toEqual(["agent"]);
queue.panel.active = false;
queue.rerender({ agentId: "agent" });
await flush();
expect(daemon.liveSubscriptions()).toEqual([]);
expect(queue.result.current.status).toBe("stale");
expect(queue.rows()).toBe("a:queued b:queued");
await daemon.publish("agent", { held: false, items: [queuedItem("b", { seq: 2 })] });
queue.panel.active = true;
queue.rerender({ agentId: "agent" });
expect(queue.result.current.status).toBe("stale");
await flush();
expect(queue.result.current.status).toBe("ready");
expect(queue.rows()).toBe("b:queued");
expect(daemon.syncAnswers()).toEqual(["snapshot", "changes"]);
expect(daemon.syncRequests().at(-1)?.sync).toEqual({
epoch: expect.any(String),
afterSeq: expect.any(Number),
});
});
test("reads as empty and asks nothing of a host without the feature", async () => {
const daemon = await startQueueDaemon({ features: {} });
await daemon.publish("agent", queueOf("a"));
const queue = renderQueue();
await flush();
act(() => queue.result.current.retry());
await flush();
expect(queue.result.current).toMatchObject({ status: "ready", items: [], meta: null });
expect(daemon.syncRequests()).toEqual([]);
});
test("retries after an error", async () => {
const daemon = await startQueueDaemon();
await daemon.publish("agent", queueOf("a"));
daemon.failNextSync("queue unavailable");
const queue = renderQueue();
await flush();
expect(queue.result.current.status).toBe("error");
expect(queue.result.current.error?.message).toBe("queue unavailable");
act(() => queue.result.current.retry());
expect(queue.result.current.status).toBe("retrying");
await flush();
expect(queue.result.current).toMatchObject({ status: "ready", error: null });
expect(queue.rows()).toBe("a:queued");
});
test("recovers on reconnect, even after an error, without a retry", async () => {
const daemon = await startQueueDaemon();
await daemon.publish("agent", queueOf("a"));
const queue = renderQueue();
await flush();
await act(() => daemon.disconnect());
await flush();
expect(queue.result.current.status).toBe("stale");
expect(queue.rows()).toBe("a:queued");
await daemon.publish("agent", queueOf("a", "b"));
await act(() => daemon.reconnect());
await flush();
expect(queue.result.current.status).toBe("ready");
expect(queue.rows()).toBe("a:queued b:queued");
expect(daemon.syncAnswers()).toEqual(["snapshot", "changes"]);
daemon.failNextSync("queue unavailable");
await act(() => daemon.disconnect());
await act(() => daemon.reconnect());
await flush();
expect(queue.result.current.status).toBe("error");
await act(() => daemon.disconnect());
await act(() => daemon.reconnect());
await flush();
expect(queue.result.current.status).toBe("ready");
expect(queue.rows()).toBe("a:queued b:queued");
});
});
describe("agent directory through useSyncCollection", () => {
function startDirectory() {
const source = createDirectorySource([
{ id: "a1", title: "Alpha", provider: "claude" },
{ id: "b1", title: "Beta", provider: "codex" },
{ id: "z1", title: "Zeta", provider: "codex", background: true },
]);
const backend = createDirectoryBackend(source);
cleanups.push(() => backend.close());
const host = createSyncTestHost<undefined>({
routes: [syncRoute({ resource: TestDirectory, backend })],
});
return { source, host };
}
function renderTwoPanes(panel = retainedPanel()) {
const rendered = renderHook(
() => ({
// Both panes ask for foreground agents; the resource keys them the same.
sidebar: useSyncCollection(SERVER_ID, TestDirectory, {}),
switcher: useSyncCollection(SERVER_ID, TestDirectory, { includeBackground: false }),
}),
{ wrapper: panel.wrapper },
);
const titles = () => rendered.result.current.sidebar.items.map((agent) => agent.title);
return { ...rendered, panel, titles };
}
test("two panes with equal keys share one host subscription across re-renders", async () => {
const { host } = startDirectory();
await startTestHost(host);
const panes = renderTwoPanes();
await flush();
expect(panes.titles()).toEqual(["Alpha", "Beta"]);
expect(panes.result.current.switcher.items).toBe(panes.result.current.sidebar.items);
panes.rerender();
panes.rerender();
await flush();
expect(syncRequests(host, TestDirectory.prefix)).toHaveLength(1);
expect(host.received("subscription.release.request")).toEqual([]);
});
test("catches up with upserts and removals after being hidden or disconnected", async () => {
const { source, host } = startDirectory();
const client = await startTestHost(host);
const panes = renderTwoPanes();
await flush();
panes.panel.active = false;
panes.rerender();
await flush();
expect(host.received("subscription.release.request")).toHaveLength(1);
source.set({ id: "c1", title: "Gamma", provider: "claude" });
source.delete("a1");
expect(panes.result.current.sidebar.status).toBe("stale");
expect(panes.titles()).toEqual(["Alpha", "Beta"]);
panes.panel.active = true;
panes.rerender();
await flush();
expect(panes.titles()).toEqual(["Beta", "Gamma"]);
const shown = sentPayloads<{ sync: { mode: string }; delta: unknown }>(
host,
"test.directory.sync.response",
).at(-1);
expect(shown?.sync.mode).toBe("changes");
expect(shown?.delta).toEqual({
upserts: [
{ seq: expect.any(Number), value: { id: "c1", title: "Gamma", provider: "claude" } },
],
removals: [{ id: "a1", seq: expect.any(Number) }],
});
await act(() => host.connections.at(-1)!.drop());
source.delete("b1");
await act(() => client.connect());
await flush();
expect(panes.titles()).toEqual(["Gamma"]);
expect(syncAnswers(host, TestDirectory.prefix)).toEqual(["snapshot", "changes", "changes"]);
expect(panes.result.current.sidebar.status).toBe("ready");
});
});
describe("chat timeline through useSync", () => {
function startTimeline() {
const backend = createTimelineBackend(createMemoryTimelineStore());
const host = createSyncTestHost<undefined>({
routes: [syncRoute({ resource: TestTimeline, backend })],
});
return { backend, host };
}
function renderTimeline() {
const rendered = renderHook(() =>
useSync(
SERVER_ID,
TestTimeline,
{ agentId: "agent-1" },
{ reducer: timelineReducer, pageSize: 10 },
),
);
const rows = () => rendered.result.current.data?.rows ?? [];
const ids = () => rows().map((row) => row.id);
const text = (id: string) => rows().find((row) => row.id === id)?.text;
return { ...rendered, rows, ids, text };
}
const range = (from: number, to: number) =>
Array.from({ length: to - from + 1 }, (_, index) => `r${from + index}`);
test("loads the tail, then pages back to the start", async () => {
const { backend, host } = startTimeline();
for (let index = 1; index <= 25; index += 1) backend.append(`r${index}`, `row ${index}`);
await startTestHost(host);
const timeline = renderTimeline();
await flush();
expect(timeline.result.current).toMatchObject({ status: "ready", hasOlder: true });
expect(timeline.ids()).toEqual(range(16, 25));
let loading: Promise<void> = Promise.resolve();
act(() => {
loading = timeline.result.current.loadOlder();
});
expect(timeline.result.current.loadingOlder).toBe(true);
await act(() => loading);
expect(timeline.result.current.loadingOlder).toBe(false);
expect(timeline.ids()).toEqual(range(6, 25));
expect(timeline.result.current.hasOlder).toBe(true);
await act(() => timeline.result.current.loadOlder());
expect(timeline.ids()).toEqual(range(1, 25));
expect(timeline.result.current.hasOlder).toBe(false);
});
test("follows streamed chunks and rewinds, and closes a gap from a dropped frame", async () => {
const { backend, host } = startTimeline();
backend.append("r1", "first");
await startTestHost(host);
const timeline = renderTimeline();
await flush();
expect(timeline.ids()).toEqual(["r1"]);
backend.append("r2", "partial");
backend.update("r2", "partial answer");
backend.append("r3", "tool call");
await flush();
expect(timeline.text("r2")).toBe("partial answer");
expect(timeline.ids()).toEqual(range(1, 3));
backend.retire(timeline.rows()[1]!.seq);
backend.append("r4", "after the rewind");
await flush();
expect(timeline.ids()).toEqual(["r1", "r4"]);
const connection = host.connections.at(-1)!;
connection.rewriteNext(
(message: { type: string }) => message.type === TestTimeline.updateType,
() => null,
);
for (let index = 5; index <= 20; index += 1) backend.append(`r${index}`, `row ${index}`);
await flush();
expect(timeline.ids()).toEqual(["r1", ...range(4, 20)]);
expect(timeline.result.current.status).toBe("ready");
const catchUp = syncRequests(host, TestTimeline.prefix).filter(
(request) => request.page?.direction === "after",
);
expect(catchUp).toHaveLength(2);
});
});
+157
View File
@@ -0,0 +1,157 @@
import {
AgentQueueCollection,
type PaseoAgentQueueItem,
type PaseoAgentQueueState,
} from "@getpaseo/client";
import {
connectDaemonClient,
createMemoryCollectionBackend,
createSyncTestHost,
settle,
syncAnswers,
syncRequests,
syncRoute,
type SyncTestRoute,
} from "./sync-host";
export function queuedItem(
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,
};
}
export function queueOf(...ids: string[]): PaseoAgentQueueState {
return { held: false, items: ids.map((id, index) => queuedItem(id, { seq: index + 1 })) };
}
type Respond = Parameters<SyncTestRoute<undefined>["handle"]>[0]["respond"];
interface CommandRequest {
requestId: string;
agentId: string;
messageId: string;
}
/** Answers one command type. The host's queue only changes through `publish`. */
function commandRoute(
type: "withdraw" | "promote",
answer: (request: CommandRequest) => object,
): SyncTestRoute<undefined> {
return {
requestType: `agent.queue.${type}.request`,
handle: async ({ request, respond }) => {
const command = request as unknown as CommandRequest;
const { requestId, agentId, messageId } = command;
respond({
type: `agent.queue.${type}.response`,
payload: { requestId, agentId, messageId, error: null, ...answer(command) },
} as unknown as Parameters<Respond>[0]);
},
};
}
/**
* A daemon that holds agent queues in memory, behind a real `DaemonClient`. The queue resource
* is the server's own collection backend and sync handler, so tests exercise cursor catch-up,
* deltas and subscription lifetimes end to end. Commands are only answered: `publish` is what
* changes a queue.
*/
export async function startAgentQueueDaemon(options: { features?: Record<string, boolean> } = {}) {
const queues = new Map<string, PaseoAgentQueueState>();
const subscribed = new Set<string>();
let syncFailure: string | null = null;
let withdrawRefusal: "not_found" | "already_dispatching" | null = null;
const backend = createMemoryCollectionBackend({
resource: AgentQueueCollection,
read: async ({ agentId }) => {
const { held, items } = queues.get(agentId) ?? queueOf();
return { items, meta: { held } };
},
onActiveChange: ({ agentId }, active) => {
if (active) subscribed.add(agentId);
else subscribed.delete(agentId);
},
});
const host = createSyncTestHost({
features: options.features ?? { agentMessageQueue: true },
routes: [
syncRoute({
resource: AgentQueueCollection,
backend: {
...backend,
read: (...input) => {
const failure = syncFailure;
syncFailure = null;
return failure ? Promise.reject(new Error(failure)) : backend.read(...input);
},
},
}),
commandRoute("withdraw", ({ agentId, messageId }) => {
const item = queues.get(agentId)?.items.find((entry) => entry.id === messageId);
const reason = withdrawRefusal ?? (item ? null : "not_found");
return { withdrawn: reason === null, item: reason === null ? item : null, reason };
}),
commandRoute("promote", () => ({ promoted: true, reason: null })),
],
});
const client = await connectDaemonClient(host, undefined);
const commandTypes = new Set(["agent.queue.withdraw.request", "agent.queue.promote.request"]);
const received = () => host.connections.flatMap((connection) => connection.received);
return {
client,
/** The host an app model takes, backed by the one client above. */
host: {
getClient: () => client,
subscribe: (listener: () => void) => client.subscribeConnectionStatus(() => listener()),
},
settle,
syncRequests: () => syncRequests(host, AgentQueueCollection.prefix),
/** How each sync request was answered: `snapshot`, `changes` or `error`. */
syncAnswers: () => syncAnswers(host, AgentQueueCollection.prefix),
/** The events of every live update the host sent, in order. */
updates: () =>
host.connections.flatMap((connection) =>
connection.sent
.filter((message) => message.type === AgentQueueCollection.updateType)
.map((message) => (message as unknown as { payload: { event: unknown } }).payload.event),
),
commands: () =>
received().filter((message) => commandTypes.has(message.type)) as unknown as Array<
CommandRequest & { type: string; activeTurnBehavior?: string }
>,
requestCount: () => received().length,
/** Agents whose queue some client holds a live subscription to. */
liveSubscriptions: () => [...subscribed],
/** Replaces an agent's queue. Subscribers get only what changed. */
async publish(agentId: string, state: PaseoAgentQueueState) {
queues.set(agentId, state);
await backend.notifyChanged({ agentId });
},
failNextSync(message: string) {
syncFailure = message;
},
refuseWithdrawals(reason: "not_found" | "already_dispatching") {
withdrawRefusal = reason;
},
disconnect: () => host.connections.at(-1)?.drop(),
reconnect: () => client.connect(),
async close() {
await client.close();
await host.close();
backend.close();
},
};
}
export type AgentQueueDaemon = Awaited<ReturnType<typeof startAgentQueueDaemon>>;
+84
View File
@@ -0,0 +1,84 @@
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { DaemonClientCore } from "@getpaseo/client/internal/daemon-client-core";
import type { SyncTestHost } from "../../../server/src/server/sync/test-utils/host";
// The daemon side of app sync tests is the server's own sync code: `handleSyncRequest` and its
// backends, served over the in-memory transport a real `DaemonClient` connects to.
export { createMemoryCollectionBackend } from "../../../server/src/server/sync";
export {
createDirectoryBackend,
createDirectorySource,
type DirectoryAgent,
TestDirectory,
} from "../../../server/src/server/sync/test-utils/directory";
export {
createSyncTestHost,
type SyncTestConnection,
type SyncTestHost,
type SyncTestRoute,
syncRoute,
} from "../../../server/src/server/sync/test-utils/host";
export {
createMemoryTimelineStore,
createTimelineBackend,
TestTimeline,
type TimelineBackend,
timelineReducer,
} from "../../../server/src/server/sync/test-utils/timeline";
const silent = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} };
/**
* A real client of `host`. It reconnects only when a test calls `connect()` again. By default it
* validates messages against the daemon's schemas, as the app does; resources that exist only in
* tests are not in them, so their clients pass `validate: false`.
*/
export async function connectDaemonClient<TSession>(
host: SyncTestHost<TSession>,
session: TSession,
options: { validate?: boolean } = {},
): Promise<DaemonClient> {
const Client = options.validate === false ? DaemonClientCore : DaemonClient;
const client = new Client({
url: "ws://sync-test.invalid",
clientId: "app-sync-test",
transportFactory: host.transportFactory(session),
reconnect: { enabled: false },
livenessHeartbeat: false,
logger: silent,
syncBackoff: { initialMs: 20, maxMs: 40 },
});
await client.connect();
return client;
}
/** Lets requests, answers and live updates already in flight land. */
export async function settle(): Promise<void> {
for (let turn = 0; turn < 5; turn += 1) {
await new Promise<void>((resolve) => setTimeout(resolve, 0));
}
}
/** The `sync` metadata of every `<prefix>.sync.response` the host sent, in order. */
export function syncAnswers<TSession>(host: SyncTestHost<TSession>, prefix: string) {
return host.connections.flatMap((connection) =>
connection.sent
.filter((message) => message.type === `${prefix}.sync.response`)
.map((message) => {
const { sync, error } = (
message as unknown as { payload: { sync?: { mode: string }; error: string | null } }
).payload;
return error ? "error" : (sync?.mode ?? "none");
}),
);
}
/** Every `<prefix>.sync.request` the host received, in order. */
export function syncRequests<TSession>(host: SyncTestHost<TSession>, prefix: string) {
return host.received(`${prefix}.sync.request`) as unknown as Array<{
args: unknown;
subscribe?: object;
sync?: { epoch: string; afterSeq: number };
page?: { direction: string; cursor?: number; limit?: number };
}>;
}
+1 -10
View File
@@ -86,7 +86,6 @@ function createOwner(
serverId: SERVER_ID,
replica,
replaceDemandedAgentIds: () => undefined,
drainQueuedAgentMessage: () => undefined,
applyTurnLiveness,
ports: {
canCheckFreshness: () => checksFreshness,
@@ -236,7 +235,6 @@ describe("viewed timeline persistence", () => {
serverId: SERVER_ID,
replica,
replaceDemandedAgentIds: () => undefined,
drainQueuedAgentMessage: () => undefined,
applyTurnLiveness: () => undefined,
ports: {
canCheckFreshness: () => false,
@@ -1735,7 +1733,6 @@ describe("create handoff lifetime", () => {
serverId: SERVER_ID,
replica,
replaceDemandedAgentIds: () => undefined,
drainQueuedAgentMessage: () => undefined,
applyTurnLiveness: () => undefined,
ports: {
canCheckFreshness: () => false,
@@ -1905,7 +1902,6 @@ describe("a chat that was empty when it went offline", () => {
serverId: SERVER_ID,
replica,
replaceDemandedAgentIds: () => undefined,
drainQueuedAgentMessage: () => undefined,
applyTurnLiveness: () => undefined,
ports: {
canCheckFreshness: () => true,
@@ -2317,11 +2313,7 @@ describe("archived timeline lifetime", () => {
},
) {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const directory = new AgentDirectoryReplica(
SERVER_ID,
() => undefined,
() => undefined,
);
const directory = new AgentDirectoryReplica(SERVER_ID, () => undefined);
const workspaces = new WorkspaceDirectoryReplica(SERVER_ID);
workspaces.commitSnapshot(
{
@@ -2343,7 +2335,6 @@ describe("archived timeline lifetime", () => {
serverId: SERVER_ID,
replica,
replaceDemandedAgentIds: () => undefined,
drainQueuedAgentMessage: () => undefined,
applyTurnLiveness: () => undefined,
ports: {
canCheckFreshness: () => false,
@@ -286,9 +286,7 @@ 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);
@@ -296,11 +294,6 @@ 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);
}
@@ -309,7 +302,6 @@ 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;
@@ -347,9 +339,7 @@ function applyAuthoritativeTimelineResponse(input: {
agentId,
initKey,
result,
synchronized,
recoverGap: input.recoverGap,
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
});
return true;
}
@@ -537,7 +527,6 @@ 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 {
@@ -574,7 +563,6 @@ 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);
},
@@ -632,7 +620,6 @@ 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,10 +206,6 @@ 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 }]]),
@@ -229,7 +225,6 @@ 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),
@@ -237,7 +232,6 @@ describe("replaceFetchedAgentDirectory", () => {
}).toEqual({
agents: false,
details: false,
queued: false,
cursor: kind === "directory",
permissions: 0,
initializing: false,
@@ -295,7 +289,7 @@ describe("replaceFetchedAgentDirectory", () => {
store.flushAgentLastActivity();
setAgentArchiving({ queryClient, serverId, agentId, isArchiving: true });
const staleResult = projection.applyDelta({
projection.applyDelta({
kind: "upsert",
agent: {
...current,
@@ -317,7 +311,6 @@ 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,
),
@@ -328,7 +321,6 @@ 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",
+173 -3
View File
@@ -27,7 +27,18 @@ import {
type TimelineSubscription,
} from "./connection/index.js";
import { CreationClient } from "./creation/index.js";
import type { CreationSnapshot } from "@getpaseo/protocol/messages";
import type { CreationSnapshot, QueuedAgentMessagePayload } from "@getpaseo/protocol/messages";
import { AgentQueueCollection } from "@getpaseo/protocol/sync/resources";
import {
type CollectionState,
SyncedStoreRegistry,
type SyncBackoff,
type SyncPersistence,
type SyncRequestOptions,
type SyncResponse,
SyncRpcError,
type SyncStore,
} from "./sync/index.js";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { z } from "zod";
import type { SessionEventSubscription, WSOutboundMessage } from "@getpaseo/protocol/messages";
@@ -44,6 +55,7 @@ import type {
RestartRequestedStatusPayloadSchema,
ShutdownRequestedStatusPayloadSchema,
DaemonUpdateResponseSchema,
ActiveTurnBehavior,
AgentActiveTurnBehavior,
ServerInfoStatusPayload,
TerminalDefaultColors,
@@ -497,6 +509,10 @@ export interface DaemonClientConfig {
* processes a wakeup per client every 10 s.
*/
livenessHeartbeat?: boolean;
/** Keeps synced resource state between subscriptions. Defaults to 64 entries in memory. */
syncPersistence?: SyncPersistence;
/** Retry delays after a synced resource fails. Defaults to 1 s doubling up to 30 s. */
syncBackoff?: Partial<SyncBackoff>;
}
export interface DaemonClientTrace {
@@ -510,6 +526,7 @@ export interface AgentMessageReceipt {
deliveryStatus?: "queued";
activeTurnBehavior?: AgentActiveTurnBehavior;
guidance?: string;
messageId?: string;
}
export interface SendMessageOptions {
@@ -536,6 +553,14 @@ 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 {
@@ -1139,6 +1164,20 @@ type CorrelatedResponsePayload<TType extends CorrelatedResponseType> =
export type AgentBackgroundWorkListPayload =
CorrelatedResponsePayload<"agent.background_work.list.response">;
export type AgentBackgroundWorkItem = AgentBackgroundWorkListPayload["items"][number];
export type AgentQueueItem = QueuedAgentMessagePayload;
export interface AgentQueueListResult {
held: boolean;
items: AgentQueueItem[];
}
export type AgentQueueStore = SyncStore<CollectionState<AgentQueueItem, { held: boolean }>>;
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];
@@ -1517,6 +1556,14 @@ export class DaemonClientCore {
},
failed: (error) => this.logger.error({ err: error }, "Subscription failed"),
});
private readonly syncStores: SyncedStoreRegistry;
/**
* A synced resource partition. Collections fold themselves; streams take a reducer. The store is
* inert until subscribed and shares one host subscription with every store of the same key.
*/
readonly sync: SyncedStoreRegistry["store"];
/** The current state of a synced resource partition, without keeping a subscription. */
readonly readSync: SyncedStoreRegistry["read"];
private transport: DaemonTransport | null = null;
private chunkedTransport: ChunkedTransport | null = null;
private helloAuth: HelloAuth;
@@ -1594,6 +1641,23 @@ export class DaemonClientCore {
constructor(private config: DaemonClientConfig) {
this.codec = config.protocolCodec ?? leanProtocolCodec;
this.syncStores = new SyncedStoreRegistry({
host: {
// Synced resources are generic over their message names; their wire schemas validate them.
request: (message, responseType, options) =>
this.sendCorrelatedSessionRequest({
requestId: options?.requestId,
timeout: options?.timeout,
message: message as unknown as SessionInboundMessage,
responseType: responseType as CorrelatedResponseType,
}) as unknown as Promise<SyncResponse>,
observe: (request) => this.observeSync(request),
},
persistence: config.syncPersistence,
backoff: config.syncBackoff,
});
this.sync = this.syncStores.store.bind(this.syncStores);
this.readSync = this.syncStores.read.bind(this.syncStores);
this.logger = config.logger ?? consoleLogger;
this.relaySecurityFloorValue = config.e2ee?.minimumMode;
this.logConnectionPath = isRelayClientWebSocketUrl(this.config.url) ? "relay" : "direct";
@@ -1906,6 +1970,7 @@ export class DaemonClientCore {
this.providerSnapshotUpdates.clear();
this.clearWaiters(new Error("Daemon client closed"));
await this.diffStreams.close();
this.syncStores.clear();
await this.owned.close();
this.creations.close();
this.rejectPendingSendQueue(new Error("Daemon client closed"));
@@ -4243,6 +4308,101 @@ export class DaemonClientCore {
}
}
async listAgentQueue(
agentId: string,
options: SyncRequestOptions = {},
): Promise<AgentQueueListResult> {
this.assertAgentMessageQueueSupported();
const { items, meta } = await this.readSync(AgentQueueCollection, { agentId }, options);
return { held: meta.held, items: [...items] };
}
/** The agent's queue, kept current while subscribed. */
agentQueue(agentId: string): AgentQueueStore {
this.assertAgentMessageQueueSupported();
return this.sync(AgentQueueCollection, { agentId });
}
// A failed subscription request that is not a host answer means the connection is unusable.
private observeSync<T extends { subscriptionId: string }>(
request: (accept: (value: T) => void) => Promise<T>,
): OwnedSubscription<T> {
let resetSource = false;
return this.owned.observe(
async (accept) => {
resetSource = false;
try {
return await request(accept);
} catch (error) {
resetSource =
!(error instanceof DaemonRpcError) &&
!(error instanceof SyncRpcError) &&
this.isConnected;
throw error;
}
},
undefined,
() => {
if (resetSource) {
this.disposeTransport(1001, "Subscription request failed");
this.scheduleReconnect({ reason: "Subscription request failed" });
}
},
);
}
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 };
}
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,
@@ -4405,16 +4565,19 @@ 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<{ agent?: AgentSnapshotPayload }> {
): Promise<SwitchAgentProviderResult> {
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({
@@ -4434,6 +4597,7 @@ export class DaemonClientCore {
messageId,
images: options.images,
attachments: options.attachments,
...(options.activeTurnBehavior ? { activeTurnBehavior: options.activeTurnBehavior } : {}),
});
const payload: AgentProviderSwitchResponseMessage["payload"] = await this.sendRequest({
requestId,
@@ -4455,7 +4619,10 @@ export class DaemonClientCore {
payload.agent,
);
}
return payload.agent ? { agent: payload.agent } : {};
return {
...(payload.agent ? { agent: payload.agent } : {}),
...(payload.deliveryStatus ? { deliveryStatus: payload.deliveryStatus } : {}),
};
}
/** The behavior to put on the wire for this host. */
@@ -7787,6 +7954,7 @@ export class DaemonClientCore {
this.chunkedTransport?.close();
this.chunkedTransport = null;
this.owned.disconnected();
this.syncStores.disconnected();
this.diffStreams.disconnected();
this.providerSnapshotUpdates.clear();
this.stopLivenessHeartbeat();
@@ -8210,6 +8378,7 @@ export class DaemonClientCore {
}
this.owned.disconnected();
this.syncStores.disconnected();
this.diffStreams.disconnected();
this.providerSnapshotUpdates.clear();
@@ -8394,6 +8563,7 @@ export class DaemonClientCore {
...DEFAULT_CLIENT_CAPABILITIES,
...this.config.capabilities,
});
this.syncStores.connected();
this.creations.reconnect();
this.flushPendingSendQueue();
this.resolveConnect();
+223
View File
@@ -9661,6 +9661,7 @@ 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);
@@ -9668,6 +9669,7 @@ describe("agent sender active-turn behaviors", () => {
deliveryStatus: "queued",
activeTurnBehavior: "queue",
guidance: "Queued, not delivered yet.",
messageId: "msg-queued-1",
});
});
@@ -11325,3 +11327,224 @@ 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.agentQueue("agent-a")).toThrow("Update the host");
expect(transport.sent).toHaveLength(0);
});
test("lists, withdraws, promotes, and syncs the agent queue", async () => {
const { client, transport } = await connectQueueClient({
ownedSubscriptions: true,
agentMessageQueue: true,
});
const listPromise = client.listAgentQueue("agent-a");
const listReq = await vi.waitFor(() => {
const sent = parseSentFrame(transport.sent.at(-1));
expect(sent).toEqual({
type: "agent.queue.sync.request",
requestId: expect.any(String),
args: { agentId: "agent-a" },
});
return sent;
});
transport.triggerMessage(
wrapSessionMessage({
type: "agent.queue.sync.response",
payload: {
requestId: listReq.requestId,
sync: { mode: "snapshot", epoch: "epoch-1", headSeq: 2, reason: "no_cursor" },
snapshot: { items: [{ seq: 1, value: QUEUED_ITEM }], meta: { held: true } },
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" });
// The store starts from what the list cached and asks only for what changed since.
const store = client.agentQueue("agent-a");
const unsubscribe = store.subscribe(() => {});
expect(store.getSnapshot()).toMatchObject({
status: "stale",
data: { items: [QUEUED_ITEM], meta: { held: true } },
});
const subReq = await vi.waitFor(() => {
const sent = parseSentFrame(transport.sent.at(-1));
expect(sent).toEqual({
type: "agent.queue.sync.request",
requestId: expect.any(String),
args: { agentId: "agent-a" },
subscribe: {},
sync: { epoch: "epoch-1", afterSeq: 2 },
});
return sent;
});
transport.triggerMessage(
wrapSessionMessage({
type: "agent.queue.sync.response",
payload: {
requestId: subReq.requestId,
subscriptionId: "sub-q",
sync: { mode: "changes", epoch: "epoch-1", headSeq: 3 },
delta: { upserts: [], removals: [{ id: "msg-1", seq: 3 }] },
error: null,
},
}),
);
await vi.waitFor(() =>
expect(store.getSnapshot()).toMatchObject({
status: "ready",
data: { items: [], meta: { held: true } },
error: null,
}),
);
transport.triggerMessage(
wrapSessionMessage({
type: "agent.queue.update",
payload: {
subscriptionId: "sub-q",
epoch: "epoch-1",
prevSeq: 3,
seq: 4,
event: {
upserts: [{ seq: 4, value: { ...QUEUED_ITEM, state: "dispatching" } }],
removals: [],
meta: { held: false },
},
},
}),
);
await vi.waitFor(() =>
expect(store.getSnapshot()).toMatchObject({
status: "ready",
data: { items: [{ ...QUEUED_ITEM, state: "dispatching" }], meta: { held: false } },
}),
);
unsubscribe();
await vi.waitFor(() =>
expect(parseSentFrame(transport.sent.at(-1))).toMatchObject({
type: "subscription.release.request",
subscriptionId: "sub-q",
}),
);
});
});
+250
View File
@@ -2196,3 +2196,253 @@ 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,
};
async function answerQueueList(ws: FakeWebSocket, held: boolean, items: unknown[]): Promise<void> {
// The list consults the client's cache before it asks the host.
const request = await vi.waitFor(() => {
const sent = parseSentSessionMessage(ws.sent.at(-1));
expect(sent).toEqual({
type: "agent.queue.sync.request",
requestId: expect.any(String),
args: { agentId: "agent-a" },
});
return sent;
});
ws.message(
sessionMessage({
type: "agent.queue.sync.response",
payload: {
requestId: request.requestId,
sync: { mode: "snapshot", epoch: "epoch-1", headSeq: items.length, reason: "no_cursor" },
snapshot: {
items: items.map((value, index) => ({ seq: index + 1, value })),
meta: { held },
},
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();
await 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 sync with cursor, drop stale updates, and resync on reconnect", 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));
const subscribeReq = await vi.waitFor(() => {
const sent = parseSentSessionMessage(ws.sent.at(-1));
expect(sent).toEqual({
type: "agent.queue.sync.request",
requestId: expect.any(String),
args: { agentId: "agent-a" },
subscribe: {},
});
return sent;
});
ws.message(
sessionMessage({
type: "agent.queue.sync.response",
payload: {
requestId: subscribeReq.requestId,
subscriptionId: "queue-sdk",
sync: { mode: "snapshot", epoch: "epoch-1", headSeq: 2, reason: "no_cursor" },
snapshot: { items: [], meta: { held: true } },
error: null,
},
}),
);
await vi.waitFor(() => expect(received).toEqual([{ held: true, items: [] }]));
// A frame the snapshot already covers is a duplicate and changes nothing.
ws.message(
sessionMessage({
type: "agent.queue.update",
payload: {
subscriptionId: "queue-sdk",
epoch: "epoch-1",
prevSeq: 1,
seq: 2,
event: { upserts: [{ seq: 2, value: QUEUED_ITEM }], removals: [], meta: { held: false } },
},
}),
);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(received).toEqual([{ held: true, items: [] }]);
ws.message(
sessionMessage({
type: "agent.queue.update",
payload: {
subscriptionId: "queue-sdk",
epoch: "epoch-1",
prevSeq: 2,
seq: 3,
event: { upserts: [{ seq: 3, value: QUEUED_ITEM }], removals: [], meta: { held: false } },
},
}),
);
await vi.waitFor(() =>
expect(received).toEqual([
{ held: true, items: [] },
{ held: false, items: [QUEUED_ITEM] },
]),
);
// Reconnect resubscribes from the cursor; an empty catch-up delivers nothing new.
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: "agent.queue.sync.request",
args: { agentId: "agent-a" },
subscribe: {},
sync: { epoch: "epoch-1", afterSeq: 3 },
}),
);
const reconnectReq = parseSentSessionMessage(next.sent.at(-1));
next.message(
sessionMessage({
type: "agent.queue.sync.response",
payload: {
requestId: reconnectReq.requestId,
subscriptionId: "queue-sdk-2",
sync: { mode: "changes", epoch: "epoch-1", headSeq: 3 },
delta: { upserts: [], removals: [] },
error: null,
},
}),
);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(received).toHaveLength(2);
next.message(
sessionMessage({
type: "agent.queue.update",
payload: {
subscriptionId: "queue-sdk-2",
epoch: "epoch-1",
prevSeq: 3,
seq: 4,
event: { upserts: [], removals: [{ id: "msg-1", seq: 4 }] },
},
}),
);
await vi.waitFor(() =>
expect(received).toEqual([
{ held: true, items: [] },
{ held: false, items: [QUEUED_ITEM] },
{ held: false, items: [] },
]),
);
unsubscribe();
next.message(
sessionMessage({
type: "agent.queue.update",
payload: {
subscriptionId: "queue-sdk-2",
epoch: "epoch-1",
prevSeq: 4,
seq: 5,
event: { upserts: [{ seq: 5, value: QUEUED_ITEM }], removals: [], meta: { held: true } },
},
}),
);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(received).toHaveLength(3);
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();
});
+142 -32
View File
@@ -11,6 +11,7 @@ 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,
@@ -39,6 +40,29 @@ import type {
WorkspaceCreateRequest,
} from "@getpaseo/protocol/messages";
import { DaemonClient, type CreateAgentRequestOptions } from "./daemon-client.js";
export { AgentQueueCollection } from "@getpaseo/protocol/sync/resources";
export type {
SyncCollectionDescriptor,
SyncCursor,
SyncPageRequest,
SyncResponseMeta,
SyncStreamDescriptor,
SyncUpdatePayload,
} from "@getpaseo/protocol/sync/descriptor";
export {
type CollectionState,
type PersistedSyncState,
type SyncBackoff,
type SyncPersistence,
type SyncReducer,
type SyncRequestOptions,
SyncRpcError,
type SyncSnapshot,
type SyncStatus,
type SyncStore,
type SyncStoreOptions,
type SyncStreamStoreOptions,
} from "./sync/index.js";
import {
createTerminalActions,
type PaseoTerminalActions,
@@ -58,6 +82,10 @@ export type {
import type { PluginTimelineItem } from "@getpaseo/protocol/agent-types";
import type {
AgentBackgroundWorkItem,
AgentQueueItem,
AgentQueueListResult,
AgentQueuePromoteResult,
AgentQueueWithdrawResult,
FetchAgentsEntry,
FetchAgentsOptions,
FetchAgentsPageInfo,
@@ -414,6 +442,33 @@ 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;
@@ -445,6 +500,7 @@ 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>;
/**
@@ -713,6 +769,7 @@ export function createPaseoApi(
listenAgents,
(agentId, handler) => own(() => daemonClient.subscribeAgentTimeline(agentId, handler)),
() => own(() => daemonClient.observeAgentBackgroundWork()),
own,
);
const createAgent = async (
options: PaseoAgentCreateOptions,
@@ -1009,11 +1066,54 @@ 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"]>,
own: <T extends { release(): Promise<void> }>(create: () => T) => T,
): AgentHandleFactory {
return (agent) => {
const id = typeof agent === "string" ? agent : agent.id;
@@ -1073,42 +1173,52 @@ 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) => {
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);
const store = daemonClient.agentQueue(id);
let lastDelivered: unknown = null;
let lastReportedError: Error | null = null;
const deliver = () => {
const snapshot = store.getSnapshot();
if (snapshot.status === "error") {
if (snapshot.error && snapshot.error !== lastReportedError) {
lastReportedError = snapshot.error;
if (options?.onError) options.onError(snapshot.error);
else console.error("Agent queue subscription failed", snapshot.error);
}
return;
}
lastReportedError = null;
if (snapshot.status !== "ready" || !snapshot.data || snapshot.data === lastDelivered) {
return;
}
lastDelivered = snapshot.data;
listener({ held: snapshot.data.meta.held, items: [...snapshot.data.items] });
};
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);
},
const subscription = own(() => {
const unsubscribe = store.subscribe(deliver);
return { release: async () => unsubscribe() };
});
deliver();
return () => {
released = true;
void observation
.release()
.catch((error) =>
console.error("Background work subscription cleanup failed", error),
);
void subscription.release();
};
},
},
@@ -0,0 +1,80 @@
import type {
SyncCollectionDelta,
SyncCollectionDescriptor,
SyncCollectionSnapshot,
} from "@getpaseo/protocol/sync/descriptor";
import type { SyncReducer } from "./reducer.js";
/** A synced collection as callers read it. `items` follows the resource's `compare`. */
export interface CollectionState<TItem, TMeta> {
readonly items: readonly TItem[];
readonly byId: ReadonlyMap<string, TItem>;
readonly meta: TMeta;
}
export type CollectionReducer<TItem, TMeta> = SyncReducer<
SyncCollectionSnapshot<TItem, TMeta>,
SyncCollectionDelta<TItem, TMeta>,
SyncCollectionDelta<TItem, TMeta>,
CollectionState<TItem, TMeta>
>;
/**
* Folds collection snapshots and deltas into `CollectionState`. A change older than the one already
* applied to an item is ignored, so replays and overlapping catch-up pages are harmless.
*/
export function createCollectionReducer<TItem, TMeta>(
resource: SyncCollectionDescriptor<string, never, TItem, TMeta>,
): CollectionReducer<TItem, TMeta> {
// The sequence of the last change applied to each id, removals included. Private to the reducer
// so `CollectionState` stays plain data.
const versions = new WeakMap<CollectionState<TItem, TMeta>, ReadonlyMap<string, number>>();
const build = (
byId: Map<string, TItem>,
seqById: Map<string, number>,
meta: TMeta,
): CollectionState<TItem, TMeta> => {
const items = Array.from(byId.values());
if (resource.compare) items.sort(resource.compare);
const state: CollectionState<TItem, TMeta> = { items, byId, meta };
versions.set(state, seqById);
return state;
};
const applyChanges = (
state: CollectionState<TItem, TMeta>,
delta: SyncCollectionDelta<TItem, TMeta>,
): CollectionState<TItem, TMeta> => {
const byId = new Map(state.byId);
const seqById = new Map(versions.get(state));
let changed = false;
const isNewer = (id: string, seq: number) => seq > (seqById.get(id) ?? 0);
for (const removal of delta.removals) {
if (!isNewer(removal.id, removal.seq)) continue;
seqById.set(removal.id, removal.seq);
changed = byId.delete(removal.id) || changed;
}
for (const { seq, value } of delta.upserts) {
const id = resource.itemId(value);
if (!isNewer(id, seq)) continue;
seqById.set(id, seq);
byId.set(id, value);
changed = true;
}
const meta = delta.meta === undefined ? state.meta : delta.meta;
if (!changed && meta === state.meta) return state;
return build(byId, seqById, meta);
};
return {
applySnapshot: (snapshot) =>
build(
new Map(snapshot.items.map(({ value }) => [resource.itemId(value), value])),
new Map(snapshot.items.map(({ seq, value }) => [resource.itemId(value), seq])),
snapshot.meta,
),
applyDelta: (state, delta) => applyChanges(state, delta),
applyLive: (state, event) => applyChanges(state, event),
};
}
+24
View File
@@ -0,0 +1,24 @@
export {
type CollectionState,
type CollectionReducer,
createCollectionReducer,
} from "./collection-reducer.js";
export type { SyncReducer } from "./reducer.js";
export {
createMemorySyncPersistence,
type PersistedSyncState,
type SyncBackoff,
SyncedStoreRegistry,
type SyncedStoreRegistryOptions,
type SyncHost,
type SyncPersistence,
type SyncRequestMessage,
type SyncRequestOptions,
type SyncResponse,
SyncRpcError,
type SyncSnapshot,
type SyncStatus,
type SyncStore,
type SyncStoreOptions,
type SyncStreamStoreOptions,
} from "./registry.js";
+13
View File
@@ -0,0 +1,13 @@
import type { SyncResponseMeta, SyncUpdatePayload } from "@getpaseo/protocol/sync/descriptor";
/**
* Folds a resource's wire shapes into the state callers read. Every method returns a new state, or
* the same state when nothing changed, and never mutates its input.
*/
export interface SyncReducer<TSnapshot, TDelta, TLive, TState> {
applySnapshot(snapshot: TSnapshot, meta: SyncResponseMeta): TState;
applyDelta(state: TState, delta: TDelta, meta: SyncResponseMeta): TState;
applyLive(state: TState, event: TLive, frame: SyncUpdatePayload<TLive>): TState;
/** Prepends a `before` page. Resources without backward paging omit it. */
applyOlderPage?(state: TState, page: TSnapshot, meta: SyncResponseMeta): TState;
}
+641
View File
@@ -0,0 +1,641 @@
import type {
SyncCollectionDescriptor,
SyncCursor,
SyncDescriptor,
SyncPageRequest,
SyncResponseMeta,
SyncResponsePayload,
SyncStreamDescriptor,
SyncUpdatePayload,
} from "@getpaseo/protocol/sync/descriptor";
import type { OwnedSubscription } from "../connection/owned.js";
import { type CollectionState, createCollectionReducer } from "./collection-reducer.js";
import type { SyncReducer } from "./reducer.js";
export type SyncStatus = "loading" | "stale" | "ready" | "retrying" | "error";
export interface SyncSnapshot<TState> {
/**
* `loading`: no data yet. `stale`: data from a cache or an interrupted connection. `ready`:
* current. `retrying`: a retry is in flight. `error`: the last attempt failed.
*/
readonly status: SyncStatus;
readonly data: TState | null;
readonly hasOlder: boolean;
readonly loadingOlder: boolean;
readonly error: Error | null;
}
export interface SyncRequestOptions {
requestId?: string;
timeout?: number;
}
/**
* One synced resource partition. Creating a store has no effect; the first `subscribe` opens the
* host subscription and the last unsubscribe closes it. Stores for equal keys share one entry.
*/
export interface SyncStore<TState> {
getSnapshot(): SyncSnapshot<TState>;
subscribe(listener: () => void): () => void;
/** Retries now after an error. */
retry(): void;
/** Loads the page before the oldest loaded entry, for resources that page backwards. */
loadOlder(): Promise<void>;
/** The current state, from the live subscription when it is ready, otherwise one request. */
read(options?: SyncRequestOptions): Promise<TState>;
}
export interface SyncStoreOptions {
/** Entries per page for streams that page. The host chooses when omitted. */
pageSize?: number;
}
export interface SyncStreamStoreOptions<TSnapshot, TDelta, TLive, TState> extends SyncStoreOptions {
reducer: SyncReducer<TSnapshot, TDelta, TLive, TState>;
}
/** What a cache keeps for a partition between subscriptions and across restarts. */
export interface PersistedSyncState<TState> {
cursor: SyncCursor;
state: TState;
hasOlder: boolean;
startSeq?: number;
}
/** Stores state between subscriptions. Loads may be synchronous so cached data shows at once. */
export interface SyncPersistence<TState = unknown> {
load(key: string): PersistedSyncState<TState> | null | Promise<PersistedSyncState<TState> | null>;
save(key: string, value: PersistedSyncState<TState>): void | Promise<void>;
delete(key: string): void | Promise<void>;
}
export interface SyncBackoff {
initialMs: number;
maxMs: number;
}
/** A request message the host answers with `<prefix>.sync.response`. */
export interface SyncRequestMessage {
type: string;
args: unknown;
subscribe?: Record<string, never>;
sync?: SyncCursor;
page?: SyncPageRequest;
}
export type SyncResponse = SyncResponsePayload<unknown, unknown>;
type SubscribedResponse = SyncResponse & { subscriptionId: string };
/** The connection a registry runs on. */
export interface SyncHost {
request(
message: SyncRequestMessage,
responseType: string,
options?: SyncRequestOptions,
): Promise<SyncResponse>;
observe<T extends { subscriptionId: string }>(
request: (accept: (value: T) => void) => Promise<T>,
): OwnedSubscription<T>;
}
export interface SyncedStoreRegistryOptions {
host: SyncHost;
/** Defaults to an in-memory cache of the 64 most recently saved partitions. */
persistence?: SyncPersistence;
backoff?: Partial<SyncBackoff>;
}
/** The host answered the request with an error. Retrying without a change will not help. */
export class SyncRpcError extends Error {
constructor(message: string) {
super(message);
this.name = "SyncRpcError";
}
}
type AnyReducer = SyncReducer<unknown, unknown, unknown, unknown>;
/** What a partition holds once it has data. */
interface SyncView {
cursor: SyncCursor;
state: unknown;
hasOlder: boolean;
startSeq?: number;
}
interface Partition {
key: string;
resource: SyncDescriptor;
args: unknown;
reducer: AnyReducer;
pageSize?: number;
}
interface Entry extends Partition {
listeners: Set<() => void>;
snapshot: SyncSnapshot<unknown>;
view: SyncView | null;
sub: OwnedSubscription<SubscribedResponse> | null;
unobserve: (() => void) | null;
/** Live frames held while a catch-up read runs; `null` when none runs. */
pending: SyncUpdatePayload<unknown>[] | null;
/** Bumped on disconnect and teardown so late results of older reads are dropped. */
generation: number;
backoffMs: number;
retryTimer: ReturnType<typeof setTimeout> | null;
}
const DEFAULT_BACKOFF: SyncBackoff = { initialMs: 1_000, maxMs: 30_000 };
const DEFAULT_CACHE_ENTRIES = 64;
const LOADING: SyncSnapshot<never> = Object.freeze({
status: "loading",
data: null,
hasOlder: false,
loadingOlder: false,
error: null,
});
/**
* Keeps synced resources current over one daemon connection: one host subscription per partition,
* cursor catch-up after reconnects and gaps, backoff after failures and a cache between uses.
*/
export class SyncedStoreRegistry {
private readonly host: SyncHost;
private readonly persistence: SyncPersistence;
private readonly backoff: SyncBackoff;
private readonly entries = new Map<string, Entry>();
private readonly collectionReducers = new WeakMap<SyncDescriptor, AnyReducer>();
constructor(options: SyncedStoreRegistryOptions) {
this.host = options.host;
this.persistence = options.persistence ?? createMemorySyncPersistence(DEFAULT_CACHE_ENTRIES);
this.backoff = { ...DEFAULT_BACKOFF, ...options.backoff };
}
store<TArgs, TItem, TMeta>(
resource: SyncCollectionDescriptor<string, TArgs, TItem, TMeta>,
args: TArgs,
options?: SyncStoreOptions,
): SyncStore<CollectionState<TItem, TMeta>>;
store<TArgs, TSnapshot, TDelta, TLive, TState>(
resource: SyncStreamDescriptor<string, TArgs, TSnapshot, TDelta, TLive, SyncPageRequest>,
args: TArgs,
options: SyncStreamStoreOptions<TSnapshot, TDelta, TLive, TState>,
): SyncStore<TState>;
store(
resource: SyncDescriptor,
args: unknown,
options: SyncStoreOptions & { reducer?: AnyReducer } = {},
): SyncStore<unknown> {
return this.open(resource, args, options);
}
/** The current state of a partition, without keeping a subscription. */
read<TArgs, TItem, TMeta>(
resource: SyncCollectionDescriptor<string, TArgs, TItem, TMeta>,
args: TArgs,
options?: SyncStoreOptions & SyncRequestOptions,
): Promise<CollectionState<TItem, TMeta>>;
read<TArgs, TSnapshot, TDelta, TLive, TState>(
resource: SyncStreamDescriptor<string, TArgs, TSnapshot, TDelta, TLive, SyncPageRequest>,
args: TArgs,
options: SyncStreamStoreOptions<TSnapshot, TDelta, TLive, TState> & SyncRequestOptions,
): Promise<TState>;
read(
resource: SyncDescriptor,
args: unknown,
options: SyncStoreOptions & SyncRequestOptions & { reducer?: AnyReducer } = {},
): Promise<unknown> {
const { requestId, timeout, ...storeOptions } = options;
return this.open(resource, args, storeOptions).read({
...(requestId !== undefined ? { requestId } : {}),
...(timeout !== undefined ? { timeout } : {}),
});
}
private open(
resource: SyncDescriptor,
args: unknown,
options: SyncStoreOptions & { reducer?: AnyReducer },
): SyncStore<unknown> {
const partition: Partition = {
key: JSON.stringify([resource.prefix, (resource.key as (args: unknown) => string)(args)]),
resource,
args,
reducer: options.reducer ?? this.collectionReducer(resource),
...(options.pageSize !== undefined ? { pageSize: options.pageSize } : {}),
};
return {
getSnapshot: () => this.entries.get(partition.key)?.snapshot ?? LOADING,
subscribe: (listener) => this.subscribe(partition, listener),
retry: () => {
const entry = this.entries.get(partition.key);
if (entry) this.retry(entry);
},
loadOlder: () => {
const entry = this.entries.get(partition.key);
return entry ? this.loadOlder(entry) : Promise.resolve();
},
read: (requestOptions) => this.readPartition(partition, requestOptions),
};
}
/** The connection dropped: data is now stale until the subscriptions are restored. */
disconnected(): void {
for (const entry of this.entries.values()) {
entry.generation += 1;
entry.pending = null;
this.clearRetry(entry);
if (entry.snapshot.status === "error" && !entry.sub) continue;
this.setSnapshot(entry, { status: entry.view ? "stale" : "loading", loadingOlder: false });
}
}
/** The connection is back. Subscriptions restore themselves; failed entries start again. */
connected(): void {
for (const entry of this.entries.values()) {
entry.backoffMs = this.backoff.initialMs;
if (entry.sub) continue;
this.clearRetry(entry);
this.setSnapshot(entry, { status: "retrying", error: null });
this.start(entry);
}
}
/** Drops every subscription and cached entry, for a client that is closing. */
clear(): void {
for (const entry of Array.from(this.entries.values())) this.teardown(entry);
}
private collectionReducer(resource: SyncDescriptor): AnyReducer {
if (resource.kind !== "collection") {
throw new Error(`Synced stream '${resource.prefix}' needs a reducer`);
}
let reducer = this.collectionReducers.get(resource);
if (!reducer) {
reducer = createCollectionReducer(resource) as unknown as AnyReducer;
this.collectionReducers.set(resource, reducer);
}
return reducer;
}
private subscribe(partition: Partition, listener: () => void): () => void {
let entry = this.entries.get(partition.key);
if (entry && entry.reducer !== partition.reducer) {
throw new Error(`Synced resource '${partition.key}' is already open with another reducer`);
}
const created = !entry;
if (!entry) {
entry = this.createEntry(partition);
this.entries.set(partition.key, entry);
}
const subscribed = entry;
subscribed.listeners.add(listener);
// Starting needs a listener, so the entry starts only once this one is in.
if (created) this.hydrateAndStart(subscribed);
return () => {
if (!subscribed.listeners.delete(listener) || subscribed.listeners.size > 0) return;
this.teardown(subscribed);
};
}
private createEntry(partition: Partition): Entry {
return {
...partition,
listeners: new Set(),
snapshot: LOADING,
view: null,
sub: null,
unobserve: null,
pending: null,
generation: 0,
backoffMs: this.backoff.initialMs,
retryTimer: null,
};
}
private hydrateAndStart(entry: Entry): void {
const generation = entry.generation;
const loaded = this.persistence.load(entry.key);
if (!(loaded instanceof Promise)) {
this.hydrate(entry, loaded);
this.start(entry);
return;
}
void loaded
.catch(() => null)
.then((value) => {
if (generation !== entry.generation || this.entries.get(entry.key) !== entry) return;
if (!entry.view) this.hydrate(entry, value);
this.start(entry);
return undefined;
});
}
private hydrate(entry: Entry, persisted: PersistedSyncState<unknown> | null): void {
if (!persisted) return;
entry.view = { ...persisted };
this.setSnapshot(entry, {
status: "stale",
data: persisted.state,
hasOlder: persisted.hasOlder,
});
}
private start(entry: Entry): void {
if (entry.sub || entry.listeners.size === 0) return;
const sub = this.host.observe<SubscribedResponse>(async (accept) => {
const payload = await this.request(entry, entry.view, { subscribe: true });
if (!payload.subscriptionId) {
throw new Error(`Host omitted subscriptionId for ${entry.resource.responseType}`);
}
const subscribed = payload as SubscribedResponse;
accept(subscribed);
return subscribed;
});
entry.sub = sub;
entry.unobserve = sub.subscribe({
snapshot: (payload) => {
if (entry.sub === sub) this.receiveResponse(entry, payload);
},
update: (message) => {
if (entry.sub !== sub || message.type !== entry.resource.updateType) return;
this.receiveFrame(entry, message.payload as SyncUpdatePayload<unknown>);
},
error: (error) => {
if (entry.sub === sub) this.fail(entry, error);
},
});
}
private receiveResponse(entry: Entry, payload: SyncResponse): void {
let view: SyncView;
try {
view = fold(entry, entry.view, payload);
} catch (error) {
this.fail(entry, error);
return;
}
entry.backoffMs = this.backoff.initialMs;
this.commit(entry, view, { status: payload.sync?.hasNewer ? "stale" : "ready", error: null });
if (payload.sync?.hasNewer) void this.catchUp(entry);
}
private receiveFrame(entry: Entry, frame: SyncUpdatePayload<unknown>): void {
if (entry.pending) {
entry.pending.push(frame);
return;
}
const view = entry.view;
if (!view) return;
const { cursor } = view;
if (frame.epoch === cursor.epoch && frame.seq <= cursor.afterSeq) return;
if (frame.epoch !== cursor.epoch || frame.prevSeq > cursor.afterSeq) {
entry.pending = [frame];
void this.catchUp(entry);
return;
}
this.commit(
entry,
{
...view,
cursor: { epoch: cursor.epoch, afterSeq: frame.seq },
state: entry.reducer.applyLive(view.state, frame.event, frame),
},
{},
);
}
/** Reads `after` pages until the host has nothing newer, then replays held live frames. */
private async catchUp(entry: Entry): Promise<void> {
entry.pending ??= [];
const generation = entry.generation;
try {
let view = entry.view;
let payload: SyncResponse;
do {
payload = await this.request(entry, view, {});
if (generation !== entry.generation) return;
view = fold(entry, view, payload);
this.commit(entry, view, {});
} while (payload.sync?.hasNewer);
const held = entry.pending ?? [];
entry.pending = null;
this.setSnapshot(entry, { status: "ready", error: null });
for (const frame of held) {
if (frame.epoch === view.cursor.epoch) this.receiveFrame(entry, frame);
}
} catch (error) {
if (generation === entry.generation) this.fail(entry, error);
}
}
private async loadOlder(entry: Entry): Promise<void> {
const view = entry.view;
const applyOlderPage = entry.reducer.applyOlderPage;
if (!view || !applyOlderPage || !view.hasOlder || view.startSeq === undefined) return;
if (entry.snapshot.loadingOlder) return;
const generation = entry.generation;
this.setSnapshot(entry, { loadingOlder: true });
try {
const payload = await this.request(entry, null, {
page: {
direction: "before",
cursor: view.startSeq,
...(entry.pageSize !== undefined ? { limit: entry.pageSize } : {}),
},
});
if (generation !== entry.generation) return;
const current = entry.view;
const meta = requireMeta(entry, payload);
if (!current || meta.epoch !== current.cursor.epoch || payload.snapshot === undefined) {
// The history was replaced while the page was in flight; catch up instead.
this.setSnapshot(entry, { loadingOlder: false });
if (current) void this.catchUp(entry);
return;
}
this.commit(
entry,
{
...current,
state: applyOlderPage(current.state, payload.snapshot, meta),
hasOlder: meta.hasOlder ?? false,
...(meta.startSeq !== undefined ? { startSeq: meta.startSeq } : {}),
},
{ loadingOlder: false },
);
} catch (error) {
if (generation === entry.generation) this.setSnapshot(entry, { loadingOlder: false });
throw error;
}
}
private async readPartition(
partition: Partition,
options?: SyncRequestOptions,
): Promise<unknown> {
const active = this.entries.get(partition.key);
if (active?.snapshot.status === "ready" && active.view) return active.view.state;
let view: SyncView | null = (await this.persistence.load(partition.key)) ?? null;
let payload: SyncResponse;
do {
payload = await this.request(partition, view, {}, options);
view = fold(partition, view, payload);
} while (payload.sync?.hasNewer);
await this.persistence.save(partition.key, view);
return view.state;
}
private retry(entry: Entry): void {
if (entry.sub) return;
this.clearRetry(entry);
this.setSnapshot(entry, { status: "retrying", error: null });
this.start(entry);
}
private fail(entry: Entry, error: unknown): void {
const sub = entry.sub;
entry.sub = null;
entry.unobserve?.();
entry.unobserve = null;
entry.pending = null;
entry.generation += 1;
void sub?.release().catch(() => undefined);
const failure = error instanceof Error ? error : new Error(String(error));
this.setSnapshot(entry, { status: "error", error: failure, loadingOlder: false });
if (error instanceof SyncRpcError) {
// The host refused this partition; whatever was cached no longer describes it.
entry.view = null;
void Promise.resolve(this.persistence.delete(entry.key)).catch(() => undefined);
return;
}
const delay = entry.backoffMs;
entry.backoffMs = Math.min(entry.backoffMs * 2, this.backoff.maxMs);
entry.retryTimer = setTimeout(() => {
entry.retryTimer = null;
this.retry(entry);
}, delay);
}
private teardown(entry: Entry): void {
if (this.entries.get(entry.key) === entry) this.entries.delete(entry.key);
entry.generation += 1;
entry.listeners.clear();
entry.pending = null;
this.clearRetry(entry);
entry.unobserve?.();
entry.unobserve = null;
const sub = entry.sub;
entry.sub = null;
void sub?.release().catch(() => undefined);
}
private clearRetry(entry: Entry): void {
if (entry.retryTimer) clearTimeout(entry.retryTimer);
entry.retryTimer = null;
}
private request(
partition: Partition,
view: SyncView | null,
options: { subscribe?: boolean; page?: SyncPageRequest },
requestOptions?: SyncRequestOptions,
): Promise<SyncResponse> {
const page = options.page ?? defaultPage(partition, view);
const message: SyncRequestMessage = {
type: partition.resource.requestType,
args: partition.args,
...(options.subscribe ? { subscribe: {} } : {}),
...(view ? { sync: view.cursor } : {}),
...(page ? { page } : {}),
};
return this.host
.request(message, partition.resource.responseType, requestOptions)
.then((payload) => {
if (payload.error) throw new SyncRpcError(payload.error);
return payload;
});
}
/** Applies a new view, saves it and tells listeners. */
private commit(entry: Entry, view: SyncView, patch: Partial<SyncSnapshot<unknown>>): void {
entry.view = view;
this.setSnapshot(entry, { ...patch, data: view.state, hasOlder: view.hasOlder });
void Promise.resolve(this.persistence.save(entry.key, view)).catch(() => undefined);
}
private setSnapshot(entry: Entry, patch: Partial<SyncSnapshot<unknown>>): void {
const next = { ...entry.snapshot, ...patch };
const current = entry.snapshot;
if (
next.status === current.status &&
next.data === current.data &&
next.hasOlder === current.hasOlder &&
next.loadingOlder === current.loadingOlder &&
next.error === current.error
) {
return;
}
entry.snapshot = next;
for (const listener of Array.from(entry.listeners)) {
if (entry.listeners.has(listener)) listener();
}
}
}
/** Folds one response into a view. A `changes` response always extends the view it was asked for. */
function fold(partition: Partition, view: SyncView | null, payload: SyncResponse): SyncView {
const meta = requireMeta(partition, payload);
const cursor = { epoch: meta.epoch, afterSeq: meta.headSeq };
if (meta.mode === "snapshot") {
if (payload.snapshot === undefined) {
throw new Error(`Missing snapshot in ${partition.resource.responseType}`);
}
return {
cursor,
state: partition.reducer.applySnapshot(payload.snapshot, meta),
hasOlder: meta.hasOlder ?? false,
...(meta.startSeq !== undefined ? { startSeq: meta.startSeq } : {}),
};
}
if (!view || payload.delta === undefined) {
throw new Error(`Unexpected changes in ${partition.resource.responseType}`);
}
return { ...view, cursor, state: partition.reducer.applyDelta(view.state, payload.delta, meta) };
}
function requireMeta(partition: Partition, payload: SyncResponse): SyncResponseMeta {
if (!payload.sync) throw new Error(`Missing sync metadata in ${partition.resource.responseType}`);
return payload.sync;
}
function defaultPage(partition: Partition, view: SyncView | null): SyncPageRequest | undefined {
if (partition.resource.kind !== "stream") return undefined;
const limit = partition.pageSize !== undefined ? { limit: partition.pageSize } : {};
if (view) return { direction: "after", cursor: view.cursor.afterSeq, ...limit };
// Without a page size the host picks how much of the tail to send.
return partition.pageSize !== undefined ? { direction: "tail", ...limit } : undefined;
}
/** Keeps the most recently saved partitions in memory. */
export function createMemorySyncPersistence<TState = unknown>(
maxEntries: number,
): SyncPersistence<TState> {
const saved = new Map<string, PersistedSyncState<TState>>();
return {
load: (key) => saved.get(key) ?? null,
save: (key, value) => {
saved.delete(key);
saved.set(key, value);
while (saved.size > maxEntries) {
const oldest = saved.keys().next().value;
if (oldest === undefined) return;
saved.delete(oldest);
}
},
delete: (key) => {
saved.delete(key);
},
};
}
+522
View File
@@ -0,0 +1,522 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { SyncResponsePayload } from "@getpaseo/protocol/sync/descriptor";
import { AgentQueueCollection } from "@getpaseo/protocol/sync/resources";
import { afterEach, describe, expect, test } from "vitest";
// The daemon side of these proofs is the server's own sync code; the client never ships it.
import type { PersistedQueuedMessage } from "../../../server/src/server/agent/agent-messages/store.js";
import { createAgentQueueBackend } from "../../../server/src/server/session/agent-queue-source.js";
import {
createDirectoryBackend,
createDirectorySource,
type DirectoryAgent,
directoryProjection,
TestDirectory,
} from "../../../server/src/server/sync/test-utils/directory.js";
import {
createSyncTestHost,
type SyncTestConnection,
type SyncTestHost,
type SyncTestRoute,
syncRoute,
} from "../../../server/src/server/sync/test-utils/host.js";
import {
createMemoryTimelineStore,
createTimelineBackend,
TestTimeline,
type TimelineStore,
timelineReducer,
} from "../../../server/src/server/sync/test-utils/timeline.js";
import { openSqliteTimelineStore } from "../../../server/src/server/sync/test-utils/sqlite-timeline.js";
import { DaemonClientCore, type Logger } from "../daemon-client-core.js";
import {
createMemorySyncPersistence,
type SyncPersistence,
type SyncSnapshot,
type SyncStatus,
type SyncStore,
} from "./index.js";
const cleanups: Array<() => void | Promise<void>> = [];
afterEach(async () => {
for (const cleanup of cleanups.splice(0).toReversed()) await cleanup();
});
const silent: Logger = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} };
function startHost<TSession>(
routes: SyncTestRoute<TSession>[],
features: Record<string, boolean> = {},
): SyncTestHost<TSession> {
const host = createSyncTestHost<TSession>({ routes, features });
cleanups.push(() => host.close());
return host;
}
async function connect<TSession>(
host: SyncTestHost<TSession>,
session: TSession,
options: { persistence?: SyncPersistence } = {},
): Promise<DaemonClientCore> {
const client = new DaemonClientCore({
url: "ws://sync-test.invalid",
clientId: "sync-test-client",
transportFactory: host.transportFactory(session),
reconnect: { enabled: true, baseDelayMs: 5, maxDelayMs: 20 },
livenessHeartbeat: false,
logger: silent,
syncBackoff: { initialMs: 20, maxMs: 40 },
...(options.persistence ? { syncPersistence: options.persistence } : {}),
});
cleanups.push(() => client.close());
await client.connect();
return client;
}
/** Subscribes to a store and records every status it passes through. */
function watch<T>(store: SyncStore<T>) {
const statuses: SyncStatus[] = [];
const timestamps: number[] = [];
const unsubscribe = store.subscribe(() => {
const { status } = store.getSnapshot();
if (statuses.at(-1) === status) return;
statuses.push(status);
timestamps.push(performance.now());
});
cleanups.push(unsubscribe);
return {
store,
statuses,
timestamps,
unsubscribe,
snapshot: (): SyncSnapshot<T> => store.getSnapshot(),
ready: () => expect.poll(() => store.getSnapshot().status).toBe("ready"),
};
}
type AnyResponse = SyncResponsePayload<unknown, unknown>;
/** Matches messages by type, including the test resources the daemon's union does not name. */
const ofType =
(type: string) =>
(message: { type: string }): boolean =>
message.type === type;
function responses(connection: SyncTestConnection, type: string): AnyResponse[] {
return connection.sent
.filter(ofType(type))
.map((message) => (message as unknown as { payload: AnyResponse }).payload);
}
function currentConnection<TSession>(host: SyncTestHost<TSession>): SyncTestConnection {
const connection = host.connections.at(-1);
if (!connection) throw new Error("No connection");
return connection;
}
describe("agent queue", () => {
function createQueueSource() {
const records = new Map<string, PersistedQueuedMessage>();
const listeners = new Set<(agentId: string) => void>();
let held = false;
let seq = 0;
const changed = () => {
for (const listener of Array.from(listeners)) listener("agent-1");
};
return {
enqueue(id: string, text: string) {
seq += 1;
records.set(id, {
id,
recipientId: "agent-1",
seq,
enqueuedAt: `2026-11-30T08:00:0${seq}.000Z`,
text,
attachments: [],
source: null,
unarchive: false,
clearPendingPermissions: false,
urgency: null,
held: false,
state: "queued",
});
changed();
},
dispatch(id: string) {
records.set(id, { ...records.get(id)!, state: "dispatching" });
changed();
},
remove(id: string) {
records.delete(id);
changed();
},
hold(value: boolean) {
held = value;
changed();
},
agentMessages: {
list: async () => ({ held, items: Array.from(records.values()) }),
onChange: (listener: (agentId: string) => void) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
},
};
}
function startQueueHost(source: ReturnType<typeof createQueueSource>) {
const backend = createAgentQueueBackend({ agentMessages: source.agentMessages });
cleanups.push(() => backend.close());
return startHost([syncRoute({ resource: AgentQueueCollection, backend })], {
agentMessageQueue: true,
});
}
test("keeps FIFO order and held state live, and catches up with changes after a reconnect", async () => {
const source = createQueueSource();
source.enqueue("m1", "first");
source.enqueue("m2", "second");
const host = startQueueHost(source);
const client = await connect(host, undefined);
const queue = watch(client.agentQueue("agent-1"));
await queue.ready();
const ids = () => queue.snapshot().data?.items.map((item) => `${item.id}:${item.state}`);
expect(ids()).toEqual(["m1:queued", "m2:queued"]);
// m1 changes after m2 did, yet it still runs first: the queue orders by enqueue sequence.
source.dispatch("m1");
await expect.poll(ids).toEqual(["m1:dispatching", "m2:queued"]);
const fresh = await connect(host, undefined);
await expect(fresh.listAgentQueue("agent-1")).resolves.toMatchObject({
held: false,
items: [{ id: "m1" }, { id: "m2" }],
});
source.hold(true);
await expect.poll(() => queue.snapshot().data?.meta).toEqual({ held: true });
await host.connections[0]!.drop();
await expect.poll(() => queue.snapshot().status).toBe("stale");
source.remove("m1");
source.enqueue("m3", "third");
await expect.poll(() => host.connections.length).toBe(3);
await queue.ready();
expect(ids()).toEqual(["m2:queued", "m3:queued"]);
expect(queue.snapshot().data?.meta).toEqual({ held: true });
const [resumed] = responses(currentConnection(host), "agent.queue.sync.response");
expect(resumed?.sync).toMatchObject({ mode: "changes" });
expect(resumed?.delta).toMatchObject({
upserts: [{ value: { id: "m3" } }],
removals: [{ id: "m1" }],
});
});
});
describe.each([
{ name: "memory", open: () => createMemoryTimelineStore() },
{
name: "sqlite",
open: () => {
const dir = mkdtempSync(join(tmpdir(), "paseo-client-sync-"));
const store = openSqliteTimelineStore(join(dir, "timeline.db"));
cleanups.push(() => {
store.close();
rmSync(dir, { recursive: true, force: true });
});
return store;
},
},
])("chat timeline over $name storage", ({ open }) => {
function startTimeline(store: TimelineStore) {
const backend = createTimelineBackend(store);
const host = startHost([syncRoute({ resource: TestTimeline, backend })]);
return { backend, host };
}
function timelineStore(client: DaemonClientCore) {
return watch(
client.sync(TestTimeline, { agentId: "agent-1" }, { reducer: timelineReducer, pageSize: 10 }),
);
}
test("loads the tail, pages back to the start, then follows chunks, tool updates and rewinds", async () => {
const store = open();
const { backend, host } = startTimeline(store);
for (let index = 1; index <= 25; index += 1) backend.append(`r${index}`, `row ${index}`);
const client = await connect(host, undefined);
const timeline = timelineStore(client);
await timeline.ready();
const rows = () => timeline.snapshot().data?.rows ?? [];
const ids = () => rows().map((row) => row.id);
const text = (id: string) => rows().find((row) => row.id === id)?.text;
expect(ids()).toEqual(Array.from({ length: 10 }, (_, index) => `r${index + 16}`));
expect(timeline.snapshot().hasOlder).toBe(true);
while (timeline.snapshot().hasOlder) await timeline.store.loadOlder();
expect(ids()).toEqual(Array.from({ length: 25 }, (_, index) => `r${index + 1}`));
backend.append("r26", "partial");
backend.update("r26", "partial answer");
backend.update("r20", "tool finished");
await expect.poll(() => text("r26")).toBe("partial answer");
expect(text("r20")).toBe("tool finished");
const r24 = rows().find((row) => row.id === "r24")!;
backend.retire(r24.seq);
backend.append("r27", "after the rewind");
await expect.poll(() => ids().at(-1)).toBe("r27");
expect(ids().slice(-3)).toEqual(["r22", "r23", "r27"]);
});
test("a dropped frame is a gap the client closes with a paged catch-up", async () => {
const store = open();
const { backend, host } = startTimeline(store);
backend.append("r1", "first");
const client = await connect(host, undefined);
const timeline = timelineStore(client);
await timeline.ready();
const connection = currentConnection(host);
connection.rewriteNext(ofType("test.timeline.update"), () => null);
for (let index = 2; index <= 16; index += 1) backend.append(`r${index}`, `row ${index}`);
const ids = () => timeline.snapshot().data?.rows.map((row) => row.id);
await expect.poll(ids).toEqual(Array.from({ length: 16 }, (_, index) => `r${index + 1}`));
const catchUp = connection.received
.filter(ofType("test.timeline.sync.request"))
.filter(
(message) => (message as { page?: { direction: string } }).page?.direction === "after",
);
expect(catchUp).toHaveLength(2);
expect(timeline.snapshot().status).toBe("ready");
});
});
describe("chat timeline restart", () => {
test("a cold client resumes from its persisted cursor and the restarted daemon answers with changes", async () => {
const dir = mkdtempSync(join(tmpdir(), "paseo-client-sync-"));
cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
const path = join(dir, "timeline.db");
const persistence = createMemorySyncPersistence(8);
const before = openSqliteTimelineStore(path);
const first = createTimelineBackend(before);
first.append("r1", "first");
first.append("r2", "second");
const firstHost = createSyncTestHost({
routes: [syncRoute({ resource: TestTimeline, backend: first })],
});
const firstClient = await connect(firstHost, undefined, { persistence });
const firstTimeline = watch(
firstClient.sync(TestTimeline, { agentId: "agent-1" }, { reducer: timelineReducer }),
);
await firstTimeline.ready();
firstTimeline.unsubscribe();
await firstClient.close();
await firstHost.close();
before.close();
const after = openSqliteTimelineStore(path);
cleanups.push(() => after.close());
const second = createTimelineBackend(after);
second.append("r3", "written while the client was away");
const host = startHost([syncRoute({ resource: TestTimeline, backend: second })]);
const client = await connect(host, undefined, { persistence });
const timeline = watch(
client.sync(TestTimeline, { agentId: "agent-1" }, { reducer: timelineReducer }),
);
// The cache shows at once, before the daemon answers.
expect(timeline.snapshot()).toMatchObject({ status: "stale" });
expect(timeline.snapshot().data?.rows.map((row) => row.id)).toEqual(["r1", "r2"]);
await timeline.ready();
expect(timeline.snapshot().data?.rows.map((row) => row.id)).toEqual(["r1", "r2", "r3"]);
const [resumed] = responses(currentConnection(host), "test.timeline.sync.response");
expect(resumed?.sync).toMatchObject({ mode: "changes", epoch: after.epoch });
});
});
describe("agent directory", () => {
interface Session {
providers: ReadonlySet<string>;
}
const agent = (id: string, provider: string, extra: Partial<DirectoryAgent> = {}) => ({
id,
title: id,
provider,
...extra,
});
function startDirectory(
initial: DirectoryAgent[],
options: Parameters<typeof createDirectoryBackend>[1] = {},
) {
const source = createDirectorySource(initial);
const backend = createDirectoryBackend(source, options);
cleanups.push(() => backend.close());
const host = startHost<Session>([
syncRoute({
resource: TestDirectory,
backend,
project: (session) => directoryProjection(session.providers),
}),
]);
return { source, backend, host };
}
const titles = (store: { snapshot: () => SyncSnapshot<{ items: readonly DirectoryAgent[] }> }) =>
store.snapshot().data?.items.map((item) => item.id);
test("equivalent args share one subscription, and each session sees only its providers without false gaps", async () => {
const active: Array<[string, boolean]> = [];
const { source, host } = startDirectory(
[agent("a", "claude"), agent("b", "codex"), agent("z", "claude", { background: true })],
{ onActiveChange: (args, value) => active.push([TestDirectory.key(args), value]) },
);
const client = await connect(host, { providers: new Set(["claude"]) });
const plain = watch(client.sync(TestDirectory, {}));
const explicit = watch(client.sync(TestDirectory, { includeBackground: false }));
await plain.ready();
await explicit.ready();
expect(host.received("test.directory.sync.request")).toHaveLength(1);
expect(titles(plain)).toEqual(["a"]);
expect(active).toEqual([["foreground", true]]);
// Changes this session may not see advance the sequence but send nothing, so no gap.
source.set(agent("c", "codex"));
await expect.poll(() => source.reads).toBe(2);
source.set(agent("b", "codex", { title: "b2" }));
await expect.poll(() => source.reads).toBe(3);
source.set(agent("d", "claude"));
await expect.poll(() => titles(plain)).toEqual(["a", "d"]);
expect(host.received("test.directory.sync.request")).toHaveLength(1);
expect(titles(explicit)).toEqual(["a", "d"]);
plain.unsubscribe();
explicit.unsubscribe();
await expect
.poll(() => active)
.toEqual([
["foreground", true],
["foreground", false],
]);
});
test("a reconnect catches up with upserts and removals", async () => {
const { source, host } = startDirectory([agent("a", "claude"), agent("b", "claude")]);
const client = await connect(host, { providers: new Set(["claude"]) });
const directory = watch(client.sync(TestDirectory, {}));
await directory.ready();
await currentConnection(host).drop();
source.delete("a");
source.set(agent("c", "claude"));
await expect.poll(() => host.connections.length).toBe(2);
await expect.poll(() => titles(directory)).toEqual(["b", "c"]);
const [resumed] = responses(currentConnection(host), "test.directory.sync.response");
expect(resumed?.sync).toMatchObject({ mode: "changes" });
expect(resumed?.delta).toMatchObject({
upserts: [{ value: { id: "c" } }],
removals: [{ id: "a" }],
});
});
test("a partition the daemon evicted comes back as a snapshot in a new epoch", async () => {
const { host } = startDirectory(
[agent("a", "claude"), agent("bg", "claude", { background: true })],
{ maxRetainedPartitions: 1 },
);
const client = await connect(host, { providers: new Set(["claude"]) });
const all = watch(client.sync(TestDirectory, { includeBackground: true }));
await all.ready();
all.unsubscribe();
const foreground = watch(client.sync(TestDirectory, {}));
await foreground.ready();
foreground.unsubscribe();
// The daemon now retains only the foreground partition and has dropped the other.
await expect
.poll(
() => currentConnection(host).sent.filter(ofType("subscription.release.response")).length,
)
.toBe(2);
const again = watch(client.sync(TestDirectory, { includeBackground: true }));
expect(again.snapshot().status).toBe("stale");
await again.ready();
expect(titles(again)).toEqual(["a", "bg"]);
const reread = responses(currentConnection(host), "test.directory.sync.response").at(-1);
expect(reread?.sync).toMatchObject({ mode: "snapshot", reason: "epoch_changed" });
});
test("a broken response backs off and retries until the store is ready", async () => {
const { host } = startDirectory([agent("a", "claude")]);
const client = await connect(host, { providers: new Set(["claude"]) });
const connection = currentConnection(host);
const stripSync: Parameters<SyncTestConnection["rewriteNext"]>[1] = (message) =>
({
...message,
payload: { ...(message as { payload: object }).payload, sync: undefined },
}) as typeof message;
for (let index = 0; index < 3; index += 1) {
connection.rewriteNext(ofType("test.directory.sync.response"), stripSync);
}
const directory = watch(client.sync(TestDirectory, {}));
await directory.ready();
expect(directory.statuses).toEqual([
"error",
"retrying",
"error",
"retrying",
"error",
"retrying",
"ready",
]);
// Waits of 20ms, 40ms, then 40ms again at the cap.
const { timestamps } = directory;
const waits = [1, 3, 5].map((index) => timestamps[index]! - timestamps[index - 1]!);
expect(waits[0]).toBeGreaterThanOrEqual(18);
expect(waits[1]).toBeGreaterThanOrEqual(38);
expect(waits[2]).toBeGreaterThanOrEqual(38);
expect(titles(directory)).toEqual(["a"]);
});
test("a refused partition waits for a manual retry", async () => {
const source = createDirectorySource([agent("a", "claude")]);
const backend = createDirectoryBackend(source);
cleanups.push(() => backend.close());
let allowed = false;
const host = startHost<Session>([
syncRoute({
resource: TestDirectory,
backend,
authorize: () => {
if (!allowed) throw new Error("Not allowed");
},
}),
]);
const client = await connect(host, { providers: new Set(["claude"]) });
const store = client.sync(TestDirectory, {});
const directory = watch(store);
await expect.poll(() => directory.snapshot().status).toBe("error");
expect(directory.snapshot().error?.message).toBe("Not allowed");
await new Promise((resolve) => setTimeout(resolve, 60));
expect(host.received("test.directory.sync.request")).toHaveLength(1);
allowed = true;
store.retry();
expect(directory.snapshot().status).toBe("retrying");
await directory.ready();
expect(directory.statuses).toEqual(["error", "retrying", "ready"]);
expect(titles(directory)).toEqual(["a"]);
});
});
@@ -0,0 +1,273 @@
import { describe, expect, test } from "vitest";
import {
AgentQueueCollection,
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 sync, withdraw, and promote requests and responses", () => {
expect(
SessionInboundMessageSchema.parse({
type: "agent.queue.sync.request",
requestId: "req-sync",
args: { agentId: "agent-1" },
subscribe: {},
sync: { epoch: "epoch-1", afterSeq: 2 },
}),
).toMatchObject({
args: { agentId: "agent-1" },
requestId: "req-sync",
subscribe: {},
sync: { epoch: "epoch-1", afterSeq: 2 },
});
expect(
SessionInboundMessageSchema.safeParse({
type: "agent.queue.sync.request",
requestId: "req-flat",
agentId: "agent-1",
}).success,
).toBe(false);
expect(
SessionOutboundMessageSchema.parse({
type: "agent.queue.sync.response",
payload: {
requestId: "req-sync",
subscriptionId: "sub-1",
sync: { mode: "snapshot", epoch: "epoch-1", headSeq: 3, reason: "no_cursor" },
snapshot: {
items: [
{ seq: 1, value: USER_ITEM },
{ seq: 3, value: AGENT_ITEM },
],
meta: { held: false },
},
error: null,
},
}),
).toMatchObject({
payload: {
sync: { mode: "snapshot", epoch: "epoch-1", headSeq: 3 },
snapshot: { items: [{ value: USER_ITEM }, { value: AGENT_ITEM }], meta: { held: false } },
},
});
expect(
SessionOutboundMessageSchema.parse({
type: "agent.queue.sync.response",
payload: {
requestId: "req-changes",
subscriptionId: "sub-1",
sync: { mode: "changes", epoch: "epoch-1", headSeq: 5 },
delta: { upserts: [], removals: [{ id: "msg-1", seq: 5 }] },
error: null,
},
}),
).toMatchObject({
payload: { delta: { upserts: [], removals: [{ id: "msg-1", seq: 5 }] }, error: null },
});
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 synced queue updates and excludes agent.queue.update from session events", () => {
expect(AgentQueueCollection).toMatchObject({
kind: "collection",
prefix: "agent.queue",
requestType: "agent.queue.sync.request",
responseType: "agent.queue.sync.response",
updateType: "agent.queue.update",
});
expect(AgentQueueCollection.key({ agentId: "agent-1" })).toBe("agent-1");
expect(AgentQueueCollection.itemId(USER_ITEM)).toBe("msg-1");
expect(AgentQueueCollection.compare?.(AGENT_ITEM, USER_ITEM)).toBeGreaterThan(0);
for (const payload of [
{
epoch: "epoch-1",
prevSeq: 0,
seq: 1,
event: { upserts: [{ seq: 1, value: USER_ITEM }], removals: [] },
},
{
subscriptionId: "sub-1",
epoch: "epoch-1",
prevSeq: 1,
seq: 2,
event: { upserts: [], removals: [{ id: "msg-1", seq: 2 }], meta: { held: true } },
},
]) {
expect(
SessionOutboundMessageSchema.parse({ type: "agent.queue.update", payload }),
).toMatchObject({ payload });
}
expect(SessionEventSubscriptionSchema.safeParse("agent.queue.update").success).toBe(false);
});
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();
});
});
+123
View File
@@ -1,4 +1,5 @@
import { AgentMessageSchema } from "./agent-message.js";
import { AgentQueueCollection } from "./sync/resources.js";
import {
HostsListRequestSchema,
HostsAddRequestSchema,
@@ -68,6 +69,7 @@ export {
type NotificationPreferencesInput,
} from "./notification-preferences.js";
import { z } from "zod";
import { defineSyncCollectionSchemas } from "./sync/schemas.js";
import { TerminalActivitySchema } from "./terminal-activity.js";
import { CLIENT_CAPS } from "./client-capabilities.js";
import { AGENT_LIFECYCLE_STATUSES } from "./agent-lifecycle.js";
@@ -1426,6 +1428,16 @@ 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(),
@@ -2214,6 +2226,72 @@ export const AgentBackgroundWorkStopRequestMessageSchema = z.object({
requestId: z.string(),
});
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 { AgentQueueCollection };
const AgentQueueSyncSchemas = defineSyncCollectionSchemas({
resource: AgentQueueCollection,
args: z.object({ agentId: z.string() }),
item: QueuedAgentMessagePayloadSchema,
meta: z.object({ held: z.boolean() }),
});
export const AgentQueueSyncRequestMessageSchema = AgentQueueSyncSchemas.request;
export const AgentQueueSyncResponseMessageSchema = AgentQueueSyncSchemas.response;
export const AgentQueueUpdateMessageSchema = AgentQueueSyncSchemas.update;
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(),
@@ -2385,6 +2463,9 @@ 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({
@@ -3810,6 +3891,9 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
ProviderSubagentListRequestMessageSchema,
AgentBackgroundWorkListRequestMessageSchema,
AgentBackgroundWorkStopRequestMessageSchema,
AgentQueueSyncRequestMessageSchema,
AgentQueueWithdrawRequestMessageSchema,
AgentQueuePromoteRequestMessageSchema,
ProviderSubagentTimelineRequestMessageSchema,
SetAgentTimelineSubscriptionRequestMessageSchema,
AgentForkContextRequestMessageSchema,
@@ -4343,6 +4427,8 @@ 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.
@@ -5480,6 +5566,34 @@ export const AgentBackgroundWorkUpdateMessageSchema = z.object({
}),
});
export const AgentQueueMissReasonSchema = z.enum(["not_found", "already_dispatching"]);
export type AgentQueueMissReason = z.infer<typeof AgentQueueMissReasonSchema>;
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(),
}),
});
export const ProviderSubagentTimelineResponseMessageSchema = z.object({
type: z.literal("agent.provider_subagents.timeline.get.response"),
payload: z.object({
@@ -5723,6 +5837,8 @@ 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. */
@@ -5739,6 +5855,9 @@ 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(),
}),
});
@@ -8062,6 +8181,10 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
AgentBackgroundWorkListResponseMessageSchema,
AgentBackgroundWorkStopResponseMessageSchema,
AgentBackgroundWorkUpdateMessageSchema,
AgentQueueSyncResponseMessageSchema,
AgentQueueWithdrawResponseMessageSchema,
AgentQueuePromoteResponseMessageSchema,
AgentQueueUpdateMessageSchema,
SetAgentTimelineSubscriptionResponseMessageSchema,
AgentAttentionRequiredMessageSchema,
AgentForkContextResponseMessageSchema,
@@ -857,4 +857,28 @@ 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");
});
});
+214
View File
@@ -0,0 +1,214 @@
// Zero-Zod sync contract. @getpaseo/client and thin CLI commands import this module at startup,
// so it must never import zod or ../messages.js at runtime. Wire schemas live in ./schemas.ts.
/** Where a subscriber left off: the partition's epoch and the last sequence it applied. */
export interface SyncCursor {
epoch: string;
afterSeq: number;
}
/** Present on a request that also opens a live subscription. The host assigns the ID. */
export interface SyncSubscribe {
subscriptionId?: string;
}
export type SyncPageDirection = "tail" | "after" | "before";
/** Paging for streams whose history is too large to send at once. Collections ignore it. */
export interface SyncPageRequest {
direction: SyncPageDirection;
/** Sequence the page starts after (`after`) or ends before (`before`). */
cursor?: number;
limit?: number;
/** Extend the page so it never splits an agent turn. */
wholeTurns?: boolean;
}
/** Why the host answered with a snapshot instead of the changes since the cursor. */
export type SyncSnapshotReason =
| "no_cursor"
| "epoch_changed"
| "cursor_expired"
| "changes_too_large";
export interface SyncResponseMeta {
mode: "snapshot" | "changes";
epoch: string;
/** The response reflects every change through this sequence. */
headSeq: number;
/** Oldest sequence the response covers, for streams that page backwards. */
startSeq?: number;
hasOlder?: boolean;
/** More changes follow `headSeq`; ask for the next `after` page. */
hasNewer?: boolean;
reason?: SyncSnapshotReason;
}
export interface VersionedItem<T> {
seq: number;
value: T;
}
export interface VersionedRemoval {
id: string;
seq: number;
}
export interface SyncCollectionSnapshot<TItem, TMeta = null> {
items: VersionedItem<TItem>[];
meta: TMeta;
}
/** Changes to a collection. Live updates carry the same shape as catch-up responses. */
export interface SyncCollectionDelta<TItem, TMeta = null> {
upserts: VersionedItem<TItem>[];
removals: VersionedRemoval[];
/** Present only when the collection's metadata changed. */
meta?: TMeta;
}
export interface SyncRequest<TArgs, TPage = SyncPageRequest> {
requestId: string;
args: TArgs;
subscribe?: SyncSubscribe;
sync?: SyncCursor;
page?: TPage;
}
export interface SyncResponsePayload<TSnapshot, TDelta> {
requestId: string;
subscriptionId?: string;
sync?: SyncResponseMeta;
snapshot?: TSnapshot;
delta?: TDelta;
error: string | null;
}
export interface SyncUpdatePayload<TLive> {
subscriptionId?: string;
epoch: string;
/**
* Sequence of the previous update this subscription received, or the response's `headSeq`.
* A subscriber whose cursor is behind `prevSeq` missed an update and must catch up.
*/
prevSeq: number;
seq: number;
event: TLive;
}
/** Type-only record of what a resource carries on the wire. Never present at runtime. */
export interface SyncWireTypes<TArgs, TSnapshot, TDelta, TLive, TPage> {
args: TArgs;
snapshot: TSnapshot;
delta: TDelta;
live: TLive;
page: TPage;
}
/** What every synced resource shares: its message names, its partition key and its wire types. */
export interface SyncResource<
TPrefix extends string = string,
TArgs = unknown,
TSnapshot = unknown,
TDelta = unknown,
TLive = unknown,
TPage = SyncPageRequest,
> {
readonly prefix: TPrefix;
readonly requestType: `${TPrefix}.sync.request`;
readonly responseType: `${TPrefix}.sync.response`;
readonly updateType: `${TPrefix}.update`;
/** Identifies one partition. Equal keys share one host subscription and one client cache entry. */
key(args: TArgs): string;
/**
* Never present at runtime. A method so its type is bivariant, like `key`: a resource stays
* assignable to the `SyncDescriptor` union that generic code accepts.
*/
__wire?(wire: SyncWireTypes<TArgs, TSnapshot, TDelta, TLive, TPage>): void;
}
/** A resource whose state and event shapes are its own; clients fold it with a reducer. */
export interface SyncStreamDescriptor<
TPrefix extends string = string,
TArgs = unknown,
TSnapshot = unknown,
TDelta = unknown,
TLive = unknown,
TPage = SyncPageRequest,
> extends SyncResource<TPrefix, TArgs, TSnapshot, TDelta, TLive, TPage> {
readonly kind: "stream";
}
/** A keyed set of items plus optional metadata. Clients fold it without a custom reducer. */
export interface SyncCollectionDescriptor<
TPrefix extends string = string,
TArgs = unknown,
TItem = unknown,
TMeta = null,
> extends SyncResource<
TPrefix,
TArgs,
SyncCollectionSnapshot<TItem, TMeta>,
SyncCollectionDelta<TItem, TMeta>,
SyncCollectionDelta<TItem, TMeta>,
SyncPageRequest
> {
readonly kind: "collection";
itemId(item: TItem): string;
/** Client-side order of `items`. Without it, items keep the order the host first sent them. */
compare?(left: TItem, right: TItem): number;
}
export type SyncDescriptor =
| SyncStreamDescriptor<string, never, unknown, unknown, unknown, unknown>
| SyncCollectionDescriptor<string, never, unknown, unknown>;
type WireOf<TResource> = TResource extends { __wire?(wire: infer TWire): void } ? TWire : never;
export type SyncArgsOf<TResource> = WireOf<TResource> extends { args: infer T } ? T : never;
export type SyncSnapshotOf<TResource> = WireOf<TResource> extends { snapshot: infer T } ? T : never;
export type SyncDeltaOf<TResource> = WireOf<TResource> extends { delta: infer T } ? T : never;
export type SyncLiveOf<TResource> = WireOf<TResource> extends { live: infer T } ? T : never;
export type SyncPageOf<TResource> = WireOf<TResource> extends { page: infer T } ? T : never;
function messageTypes<const TPrefix extends string>(prefix: TPrefix) {
return {
prefix,
requestType: `${prefix}.sync.request` as const,
responseType: `${prefix}.sync.response` as const,
updateType: `${prefix}.update` as const,
};
}
export function defineSyncStream<
const TPrefix extends string,
TArgs,
TSnapshot,
TDelta,
TLive,
TPage = SyncPageRequest,
>(options: {
prefix: TPrefix;
key: (args: TArgs) => string;
}): SyncStreamDescriptor<TPrefix, TArgs, TSnapshot, TDelta, TLive, TPage> {
return { kind: "stream", ...messageTypes(options.prefix), key: options.key };
}
export function defineSyncCollection<
const TPrefix extends string,
TArgs,
TItem,
TMeta = null,
>(options: {
prefix: TPrefix;
key: (args: TArgs) => string;
itemId: (item: TItem) => string;
compare?: (left: TItem, right: TItem) => number;
}): SyncCollectionDescriptor<TPrefix, TArgs, TItem, TMeta> {
return {
kind: "collection",
...messageTypes(options.prefix),
key: options.key,
itemId: options.itemId,
...(options.compare ? { compare: options.compare } : {}),
};
}
+16
View File
@@ -0,0 +1,16 @@
// Zero-Zod descriptors for the resources the daemon ships. Only type imports from messages.ts.
import type { QueuedAgentMessagePayload } from "../messages.js";
import { defineSyncCollection } from "./descriptor.js";
/** One agent's message queue, in delivery order, plus whether it waits for the next prompt. */
export const AgentQueueCollection = defineSyncCollection<
"agent.queue",
{ agentId: string },
QueuedAgentMessagePayload,
{ held: boolean }
>({
prefix: "agent.queue",
key: ({ agentId }) => agentId,
itemId: (item) => item.id,
compare: (left, right) => left.seq - right.seq,
});
+161
View File
@@ -0,0 +1,161 @@
import { z } from "zod";
import type {
SyncCollectionDescriptor,
SyncPageRequest,
SyncStreamDescriptor,
} from "./descriptor.js";
// Wire schemas stay structural (no transform/catch/preprocess) so zod-aot can compile them.
// See docs/protocol-validation.md.
const seq = () => z.number().int().nonnegative();
export const SyncCursorSchema = z.object({
epoch: z.string(),
afterSeq: seq(),
});
export const SyncSubscribeSchema = z.object({
subscriptionId: z.string().optional(),
});
export const SyncPageRequestSchema = z.object({
direction: z.enum(["tail", "after", "before"]),
cursor: seq().optional(),
limit: z.number().int().positive().optional(),
wholeTurns: z.boolean().optional(),
});
export const SyncResponseMetaSchema = z.object({
mode: z.enum(["snapshot", "changes"]),
epoch: z.string(),
headSeq: seq(),
startSeq: seq().optional(),
hasOlder: z.boolean().optional(),
hasNewer: z.boolean().optional(),
reason: z.enum(["no_cursor", "epoch_changed", "cursor_expired", "changes_too_large"]).optional(),
});
export const VersionedRemovalSchema = z.object({
id: z.string(),
seq: seq(),
});
export function versionedItemSchema<TItem extends z.ZodType>(item: TItem) {
return z.object({ seq: seq(), value: item });
}
interface SyncMessageNames<TPrefix extends string> {
readonly requestType: `${TPrefix}.sync.request`;
readonly responseType: `${TPrefix}.sync.response`;
readonly updateType: `${TPrefix}.update`;
}
function buildSyncSchemas<
TPrefix extends string,
TArgs extends z.ZodType,
TSnapshot extends z.ZodType,
TDelta extends z.ZodType,
TLive extends z.ZodType,
TPage extends z.ZodType,
>(options: {
resource: SyncMessageNames<TPrefix>;
args: TArgs;
snapshot: TSnapshot;
delta: TDelta;
live: TLive;
page: TPage;
}) {
const { resource, args, snapshot, delta, live, page } = options;
return {
request: z.object({
type: z.literal(resource.requestType),
requestId: z.string(),
args,
subscribe: SyncSubscribeSchema.optional(),
sync: SyncCursorSchema.optional(),
page: page.optional(),
}),
response: z.object({
type: z.literal(resource.responseType),
payload: z.object({
requestId: z.string(),
subscriptionId: z.string().optional(),
sync: SyncResponseMetaSchema.optional(),
snapshot: snapshot.optional(),
delta: delta.optional(),
error: z.string().nullable(),
}),
}),
update: z.object({
type: z.literal(resource.updateType),
payload: z.object({
subscriptionId: z.string().optional(),
epoch: z.string(),
prevSeq: seq(),
seq: seq(),
event: live,
}),
}),
};
}
/** Request, response and update schemas for a stream resource. */
export function defineSyncStreamSchemas<
TPrefix extends string,
TArgs extends z.ZodType,
TSnapshot extends z.ZodType,
TDelta extends z.ZodType,
TLive extends z.ZodType,
TPage extends z.ZodType = typeof SyncPageRequestSchema,
>(options: {
resource: SyncStreamDescriptor<
TPrefix,
z.output<TArgs>,
z.output<TSnapshot>,
z.output<TDelta>,
z.output<TLive>,
z.output<TPage>
>;
args: TArgs;
snapshot: TSnapshot;
delta: TDelta;
live: TLive;
page?: TPage;
}) {
return buildSyncSchemas({
...options,
page: options.page ?? (SyncPageRequestSchema as z.ZodType as TPage),
});
}
/** Request, response and update schemas for a collection resource. Updates carry deltas. */
export function defineSyncCollectionSchemas<
TPrefix extends string,
TArgs extends z.ZodType,
TItem extends z.ZodType,
TMeta extends z.ZodType = z.ZodNull,
>(options: {
resource: SyncCollectionDescriptor<TPrefix, z.output<TArgs>, z.output<TItem>, z.output<TMeta>>;
args: TArgs;
item: TItem;
/** Collections without metadata send `meta: null`. */
meta?: TMeta;
}) {
const { resource, args, item } = options;
const meta = options.meta ?? (z.null() as z.ZodType as TMeta);
const upserts = z.array(versionedItemSchema(item));
const delta = z.object({
upserts,
removals: z.array(VersionedRemovalSchema),
meta: meta.optional(),
});
return buildSyncSchemas({
resource,
args,
snapshot: z.object({ items: upserts, meta }),
delta,
live: delta,
page: SyncPageRequestSchema satisfies z.ZodType<SyncPageRequest>,
});
}
+217
View File
@@ -0,0 +1,217 @@
import { readFileSync } from "node:fs";
import { describe, expect, test } from "vitest";
import { z } from "zod";
import { defineSyncCollection, defineSyncStream } from "./descriptor.js";
import { AgentQueueCollection } from "./resources.js";
import { defineSyncCollectionSchemas, defineSyncStreamSchemas } from "./schemas.js";
interface Row {
seq: number;
text: string;
}
const Timeline = defineSyncStream<
"test.timeline",
{ agentId: string },
{ rows: Row[] },
{ rows: Row[]; retireFromSeq?: number },
{ kind: "row"; row: Row } | { kind: "retire"; fromSeq: number }
>({ prefix: "test.timeline", key: ({ agentId }) => agentId });
const RowSchema = z.object({ seq: z.number(), text: z.string() });
const TimelineSchemas = defineSyncStreamSchemas({
resource: Timeline,
args: z.object({ agentId: z.string() }),
snapshot: z.object({ rows: z.array(RowSchema) }),
delta: z.object({ rows: z.array(RowSchema), retireFromSeq: z.number().optional() }),
live: z.discriminatedUnion("kind", [
z.object({ kind: z.literal("row"), row: RowSchema }),
z.object({ kind: z.literal("retire"), fromSeq: z.number() }),
]),
});
const Directory = defineSyncCollection<
"test.directory",
{ includeBackground?: boolean },
{ id: string; title: string }
>({
prefix: "test.directory",
key: ({ includeBackground }) => (includeBackground ? "all" : "foreground"),
itemId: (item) => item.id,
});
const DirectorySchemas = defineSyncCollectionSchemas({
resource: Directory,
args: z.object({ includeBackground: z.boolean().optional() }),
item: z.object({ id: z.string(), title: z.string() }),
});
describe("sync descriptors", () => {
test("derive message types from the prefix and keep args nested", () => {
expect(Timeline).toMatchObject({
kind: "stream",
prefix: "test.timeline",
requestType: "test.timeline.sync.request",
responseType: "test.timeline.sync.response",
updateType: "test.timeline.update",
});
expect(Timeline.key({ agentId: "a" })).toBe("a");
expect(Directory.key({})).toBe(Directory.key({ includeBackground: false }));
expect(Directory.itemId({ id: "x", title: "X" })).toBe("x");
expect("compare" in Directory).toBe(false);
expect(AgentQueueCollection.kind).toBe("collection");
});
test("descriptor modules import neither zod nor messages.ts at runtime", () => {
for (const file of ["descriptor.ts", "resources.ts"]) {
const source = readFileSync(new URL(`./${file}`, import.meta.url), "utf8");
const runtimeImports = [...source.matchAll(/^import\s+(?!type\b)[^;]*?from\s+"([^"]+)"/gm)];
expect(runtimeImports.map((match) => match[1])).not.toContain("zod");
expect(runtimeImports.map((match) => match[1])).not.toContain("../messages.js");
}
});
});
describe("sync schemas", () => {
test("requests carry nested args, an optional cursor, subscription and page", () => {
const request = {
type: "test.timeline.sync.request",
requestId: "r1",
args: { agentId: "a" },
subscribe: {},
sync: { epoch: "e1", afterSeq: 4 },
page: { direction: "before", cursor: 10, limit: 50, wholeTurns: true },
};
expect(TimelineSchemas.request.parse(request)).toEqual(request);
expect(
TimelineSchemas.request.safeParse({ ...request, args: undefined, agentId: "a" }).success,
).toBe(false);
expect(
TimelineSchemas.request.safeParse({ ...request, page: { direction: "sideways" } }).success,
).toBe(false);
expect(
TimelineSchemas.request.safeParse({ ...request, sync: { epoch: "e1", afterSeq: -1 } })
.success,
).toBe(false);
});
test("responses carry sync metadata with either a snapshot or a delta", () => {
const snapshot = {
type: "test.timeline.sync.response",
payload: {
requestId: "r1",
subscriptionId: "s1",
sync: {
mode: "snapshot",
epoch: "e1",
headSeq: 9,
startSeq: 5,
hasOlder: true,
reason: "epoch_changed",
},
snapshot: { rows: [{ seq: 5, text: "hi" }] },
error: null,
},
};
expect(TimelineSchemas.response.parse(snapshot)).toEqual(snapshot);
const changes = {
type: "test.timeline.sync.response",
payload: {
requestId: "r2",
sync: { mode: "changes", epoch: "e1", headSeq: 12, hasNewer: true },
delta: { rows: [{ seq: 10, text: "next" }], retireFromSeq: 7 },
error: null,
},
};
expect(TimelineSchemas.response.parse(changes)).toEqual(changes);
const failure = {
type: "test.timeline.sync.response",
payload: { requestId: "r3", error: "Agent not found" },
};
expect(TimelineSchemas.response.parse(failure)).toEqual(failure);
expect(
TimelineSchemas.response.safeParse({
...changes,
payload: { ...changes.payload, sync: { ...changes.payload.sync, mode: "unchanged" } },
}).success,
).toBe(false);
});
test("updates require epoch, prevSeq and seq around the live event", () => {
const update = {
type: "test.timeline.update",
payload: {
subscriptionId: "s1",
epoch: "e1",
prevSeq: 9,
seq: 10,
event: { kind: "retire", fromSeq: 3 },
},
};
expect(TimelineSchemas.update.parse(update)).toEqual(update);
const { prevSeq: _prevSeq, ...withoutPrevSeq } = update.payload;
expect(TimelineSchemas.update.safeParse({ ...update, payload: withoutPrevSeq }).success).toBe(
false,
);
});
test("collections send versioned items, tombstones and null metadata by default", () => {
const response = {
type: "test.directory.sync.response",
payload: {
requestId: "r1",
sync: { mode: "changes", epoch: "e1", headSeq: 3 },
delta: {
upserts: [{ seq: 2, value: { id: "a", title: "A" } }],
removals: [{ id: "b", seq: 3 }],
},
error: null,
},
};
expect(DirectorySchemas.response.parse(response)).toEqual(response);
expect(
DirectorySchemas.response.parse({
type: "test.directory.sync.response",
payload: {
requestId: "r2",
sync: { mode: "snapshot", epoch: "e1", headSeq: 3 },
snapshot: { items: [], meta: null },
error: null,
},
}).payload.snapshot,
).toEqual({ items: [], meta: null });
expect(
DirectorySchemas.update.parse({
type: "test.directory.update",
payload: {
epoch: "e1",
prevSeq: 3,
seq: 4,
event: { upserts: [], removals: [{ id: "a", seq: 4 }] },
},
}).payload.event,
).toEqual({ upserts: [], removals: [{ id: "a", seq: 4 }] });
});
test("schemas stay structural so zod-aot can compile them", () => {
const forbidden = new Set(["transform", "pipe", "catch", "preprocess"]);
const visit = (schema: z.ZodType, path: string): void => {
const def = (schema as unknown as { _zod: { def: Record<string, unknown> } })._zod.def;
expect(forbidden.has(String(def.type)), path).toBe(false);
for (const value of Object.values(def)) {
if (value instanceof z.ZodType) visit(value, path);
if (value && typeof value === "object" && !(value instanceof z.ZodType)) {
for (const [key, child] of Object.entries(value)) {
if (child instanceof z.ZodType) visit(child, `${path}.${key}`);
}
}
}
};
for (const schemas of [TimelineSchemas, DirectorySchemas]) {
visit(schemas.request, "request");
visit(schemas.response, "response");
visit(schemas.update, "update");
}
});
});
@@ -198,6 +198,61 @@ 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: {
epoch: "epoch-1",
prevSeq: 1,
seq: 3,
event: {
upserts: [
{ seq: 2, value: knownItem },
{ seq: 3, value: futureItem },
],
removals: [],
},
},
});
const generated = validateWSOutboundMessage(envelope);
const zod = safeParseSkippingUnknownVariants(WSOutboundMessageSchema, envelope);
expect(generated).toMatchObject({
success: true,
data: {
message: {
payload: {
epoch: "epoch-1",
prevSeq: 1,
seq: 3,
event: { upserts: [{ seq: 2, value: knownItem }], removals: [] },
},
},
},
});
expect(zod.success).toBe(true);
expect(zod.success && zod.data).toEqual(generated.success && generated.data);
});
});
describe("what still fails", () => {
@@ -472,3 +472,88 @@ 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.sync.response",
payload: {
requestId: "req-1",
subscriptionId: "sub-1",
sync: { mode: "snapshot", epoch: "epoch-1", headSeq: 1, reason: "no_cursor" },
snapshot: { items: [{ seq: 1, value: item }], meta: { held: false } },
error: null,
},
},
{
type: "agent.queue.sync.response",
payload: {
requestId: "req-1b",
subscriptionId: "sub-1",
sync: { mode: "changes", epoch: "epoch-1", headSeq: 4 },
delta: { upserts: [], removals: [{ id: "msg-0", seq: 4 }], meta: { held: true } },
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",
epoch: "epoch-1",
prevSeq: 4,
seq: 5,
event: { upserts: [{ seq: 5, value: item }], removals: [] },
},
},
{
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: [],
});
}
});
@@ -39,7 +39,10 @@ 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 } from "./agent-messages/index.js";
import {
createAgentMessageDelivery,
createMemoryAgentMessageQueueStore,
} 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";
@@ -17001,6 +17004,7 @@ test.each([
});
let tick = () => {};
const delivery = createAgentMessageDelivery({
store: createMemoryAgentMessageQueueStore(),
isRunning: (id) => manager.hasInFlightRun(id),
subscribe: (notify) =>
manager.subscribe(
@@ -17036,9 +17040,9 @@ test.each([
try {
await startAgentRun(manager, agent.id, "original", logger);
await manager.waitForAgentRunStart(agent.id);
const receipt = delivery.enqueue({
const receipt = await delivery.enqueue({
recipientId: agent.id,
prompt: "queued",
text: "queued",
source: { kind: "agent-message", agentId: "child" },
});
tick();
@@ -17081,6 +17085,7 @@ 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(
@@ -17109,9 +17114,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));
delivery.enqueue({
await delivery.enqueue({
recipientId: agent.id,
prompt: "queued report",
text: "queued report",
source: { kind: "agent-message", agentId: "child" },
});
tick();
@@ -236,6 +236,14 @@ 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;
@@ -244,6 +252,11 @@ 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
@@ -264,7 +277,7 @@ export interface SwitchAgentProviderResult {
context: ProviderSwitchContextSummary;
}
type RunCancellationCause = "reload" | "replace" | "rewind" | "stop";
type RunCancellationCause = "reload" | "replace" | "rewind" | "stop" | "switch";
export class AgentRunCancellationError extends Error {
constructor(agentId: string, action: RunCancellationCause) {
@@ -2522,6 +2535,14 @@ 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,
@@ -2781,6 +2802,7 @@ 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) {
@@ -2796,7 +2818,7 @@ export class AgentManager {
if (resumed) {
return resumed;
}
throw new Error(`Agent ${agentId} is already using provider '${input.toProvider}'`);
throw new AgentAlreadyOnProviderError(agentId, input.toProvider);
}
this.requireEnabledProvider(input.toProvider);
@@ -5497,7 +5519,10 @@ export class AgentManager {
return { status: "settled" };
}
private async cancelAgentRunBefore(agentId: string, action: "reload" | "rewind"): Promise<void> {
private async cancelAgentRunBefore(
agentId: string,
action: "reload" | "rewind" | "switch",
): 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
@@ -0,0 +1,445 @@
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, onTestFinished, test } from "vitest";
import { AgentTurnStartRejectedError } from "../agent-prompt.js";
import type { AgentPromptInput, AgentTimelineItem } from "../agent-sdk-types.js";
import {
createAgentMessageDelivery,
createJsonAgentMessageQueueStore,
MAX_AGENT_QUEUE_DEPTH,
projectAgentMessages,
type AgentMessageDelivery,
type AgentMessageQueueStore,
} from "./index.js";
const peer = { kind: "agent-message" as const, agentId: "worker" };
async function createHome(): Promise<string> {
const paseoHome = await mkdtemp(join(tmpdir(), "paseo-queue-durability-"));
onTestFinished(() => rm(paseoHome, { recursive: true, force: true }));
return paseoHome;
}
interface DaemonOptions {
running?: boolean;
/** The provider takes the prompt and the daemon dies before hearing back. */
neverAnswers?: boolean;
refuseStart?: () => boolean;
history?: Record<string, AgentTimelineItem[]>;
status?: Record<string, "active" | "archived" | "deleted">;
}
/** The real store, with a way to wait until every write the delivery asked for has finished. */
function trackWrites(store: AgentMessageQueueStore) {
let started = 0;
const inFlight = new Set<Promise<unknown>>();
const tracked = new Proxy(store, {
get: (target, name: keyof AgentMessageQueueStore) => {
const operation = target[name] as (...args: unknown[]) => Promise<unknown>;
return (...args: unknown[]) => {
const result = operation.apply(target, args);
started++;
inFlight.add(result);
void result.finally(() => inFlight.delete(result)).catch(() => undefined);
return result;
};
},
});
/** Done once nothing is in flight and nothing new started for a few turns of the event loop. */
async function settle(): Promise<void> {
for (let quiet = 0, seen = started; quiet < 5; ) {
await Promise.allSettled(inFlight);
await new Promise((resolve) => setTimeout(resolve, 2));
quiet = inFlight.size === 0 && seen === started ? quiet + 1 : 0;
seen = started;
}
}
return { store: tracked, settle };
}
/** One daemon process over the queue files in `paseoHome`. Open another to restart it. */
function openDaemon(paseoHome: string, options: DaemonOptions = {}) {
const { store, settle } = trackWrites(createJsonAgentMessageQueueStore(paseoHome));
const sent: Array<{ ids: readonly string[]; behavior: string; prompt: AgentPromptInput }> = [];
const withdrawn: string[] = [];
const errors: unknown[] = [];
const timers = new Set<() => void>();
const settleListeners = new Set<(recipientId: string) => void>();
const stopListeners = new Set<(recipientId: string) => void>();
let running = options.running ?? false;
const delivery = createAgentMessageDelivery({
store,
paseoHome,
schedule: (_delayMs, callback) => {
timers.add(callback);
return () => timers.delete(callback);
},
isRunning: () => running,
subscribe: (listener) => {
settleListeners.add(listener);
return () => settleListeners.delete(listener);
},
onStop: (listener) => {
stopListeners.add(listener);
return () => stopListeners.delete(listener);
},
recipientStatus: async (recipientId) => options.status?.[recipientId] ?? "active",
readHistory: async (recipientId) => options.history?.[recipientId] ?? [],
dispatch: async (request) => {
if (!request.admit()) throw new Error("The prompt was not admitted");
if (options.refuseStart?.()) throw new AgentTurnStartRejectedError("no turn");
sent.push({
ids: request.messageIds,
behavior: request.activeTurnBehavior,
prompt: request.prompt,
});
if (options.neverAnswers) await new Promise<never>(() => {});
running = true;
return "turn_started";
},
onError: (error) => {
errors.push(error);
},
});
delivery.onWithdrawn(({ id }) => {
withdrawn.push(id);
});
return {
delivery,
store,
errors,
sent,
withdrawn,
settle,
ids: () => sent.map((dispatch) => dispatch.ids),
saved: async (recipientId: string) =>
(await store.listByRecipient(recipientId)).map(({ id, state, held }) => ({
id,
state,
held,
})),
/** Every scheduled quiet window and retry comes due. */
async tick() {
const due = Array.from(timers);
timers.clear();
for (const callback of due) callback();
await settle();
},
async stop() {
for (const listener of stopListeners) listener("parent");
running = false;
await settle();
},
async endTurn() {
running = false;
for (const listener of settleListeners) listener("parent");
await settle();
},
};
}
function queue(
delivery: AgentMessageDelivery,
messageId: string,
extra: Partial<Parameters<AgentMessageDelivery["enqueue"]>[0]> = {},
) {
return delivery.enqueue({
recipientId: "parent",
messageId,
source: peer,
text: messageId,
...extra,
});
}
test("admission refuses an empty message and a full queue, and saves neither", async () => {
const daemon = openDaemon(await createHome(), { running: true });
await expect(queue(daemon.delivery, "empty", { text: " " })).rejects.toThrow("empty");
expect(await daemon.saved("parent")).toEqual([]);
for (let index = 0; index < MAX_AGENT_QUEUE_DEPTH; index++)
await queue(daemon.delivery, `m${index}`);
await expect(queue(daemon.delivery, "overflow")).rejects.toThrow(
`already has ${MAX_AGENT_QUEUE_DEPTH} queued messages`,
);
expect(await daemon.saved("parent")).toHaveLength(MAX_AGENT_QUEUE_DEPTH);
await daemon.delivery.close();
});
test("a retried admission is the same message, and a reused id for another request is refused", async () => {
const home = await createHome();
const first = openDaemon(home, { running: true });
await queue(first.delivery, "report", { fingerprint: "a" });
await queue(first.delivery, "report", { fingerprint: "a" });
await expect(queue(first.delivery, "report", { fingerprint: "b" })).rejects.toThrow(
"agent_request_key_conflict",
);
await first.delivery.close();
const second = openDaemon(home, { running: true });
await second.delivery.start();
await queue(second.delivery, "report", { fingerprint: "a" });
await expect(queue(second.delivery, "report", { fingerprint: "b" })).rejects.toThrow(
"agent_request_key_conflict",
);
expect(await second.saved("parent")).toMatchObject([{ id: "report" }]);
await second.endTurn();
expect(second.ids()).toEqual([["report"]]);
await second.delivery.close();
});
test("a dispatch the crash interrupted is removed if the history shows it, and sent again if not", async () => {
const home = await createHome();
const crashed = openDaemon(home, { neverAnswers: true });
await queue(crashed.delivery, "seen", { recipientId: "received", activeTurnBehavior: "steer" });
await queue(crashed.delivery, "unseen", { recipientId: "lost", activeTurnBehavior: "steer" });
await crashed.settle();
expect(await crashed.saved("received")).toMatchObject([{ id: "seen", state: "dispatching" }]);
expect(await crashed.saved("lost")).toMatchObject([{ id: "unseen", state: "dispatching" }]);
const received = crashed.sent.find((dispatch) => dispatch.ids[0] === "seen")!;
const restarted = openDaemon(home, {
history: {
received: projectAgentMessages({ type: "user_message", text: String(received.prompt) }),
},
});
await restarted.delivery.start();
await restarted.settle();
await restarted.tick();
expect(restarted.ids()).toEqual([["unseen"]]);
expect(await restarted.saved("received")).toEqual([]);
expect(await restarted.saved("lost")).toEqual([]);
await restarted.delivery.close();
});
test("a person's lone prompt counts as received when the history ends with its exact text", async () => {
const home = await createHome();
const crashed = openDaemon(home, { neverAnswers: true });
await queue(crashed.delivery, "decision", { source: undefined, text: "Approve D4" });
await crashed.settle();
const restarted = openDaemon(home, {
history: { parent: [{ type: "user_message", text: "Approve D4" }] },
});
await restarted.delivery.start();
await restarted.settle();
await restarted.tick();
expect(restarted.ids()).toEqual([]);
expect(await restarted.saved("parent")).toEqual([]);
await restarted.delivery.close();
});
test("a queued message survives a restart and waits for the recipient's restart resume", async () => {
const home = await createHome();
const first = openDaemon(home, { running: true });
await queue(first.delivery, "report");
await first.delivery.close();
const second = openDaemon(home);
let resumed!: () => void;
const resume = new Promise<void>((resolve) => {
resumed = resolve;
});
await second.delivery.start({ waitForResume: () => resume });
await second.tick();
await second.endTurn();
expect(second.ids()).toEqual([]);
expect(second.delivery.hasPending("parent")).toBe(true);
resumed();
await second.settle();
expect(second.ids()).toEqual([["report"]]);
expect(await second.saved("parent")).toEqual([]);
await second.delivery.close();
});
test("Stop holds the queue across a restart until it is promoted", async () => {
const home = await createHome();
const first = openDaemon(home, { running: true });
await queue(first.delivery, "one");
await queue(first.delivery, "two", { activeTurnBehavior: "queue" });
await first.stop();
await first.delivery.close();
expect(await first.saved("parent")).toEqual([
{ id: "one", state: "queued", held: true },
{ id: "two", state: "queued", held: true },
]);
const second = openDaemon(home);
await second.delivery.start();
await second.tick();
await second.endTurn();
expect(second.ids()).toEqual([]);
expect(await second.delivery.list("parent")).toMatchObject({
held: true,
items: [{ id: "one" }, { id: "two" }],
});
await expect(second.delivery.promote("parent", "two", "steer")).resolves.toBe("promoted");
await second.settle();
expect(second.sent).toMatchObject([{ ids: ["one", "two"], behavior: "steer" }]);
await second.delivery.close();
});
test("a prompt sent after a restart carries the held messages", async () => {
const home = await createHome();
const first = openDaemon(home, { running: true });
await queue(first.delivery, "held");
await first.stop();
await first.delivery.close();
const second = openDaemon(home);
await second.delivery.start();
let prompt: AgentPromptInput = "";
await second.delivery.sendDirect(
{ recipientId: "parent", prompt: "continue", messageId: "next" },
async (joined) => {
prompt = joined.prompt;
return { disposition: "turn_started" as const, started: Promise.resolve() };
},
);
await second.settle();
expect(String(prompt)).toContain('message-id="held"');
expect(await second.saved("parent")).toEqual([]);
await second.delivery.close();
});
test("promoting releases the message and everything admitted before it, and nothing after", async () => {
const daemon = openDaemon(await createHome(), { running: true });
await queue(daemon.delivery, "one");
await queue(daemon.delivery, "two");
await queue(daemon.delivery, "three");
await expect(daemon.delivery.promote("parent", "two", "interrupt")).resolves.toBe("promoted");
await daemon.settle();
expect(daemon.sent).toMatchObject([{ ids: ["one", "two"], behavior: "interrupt" }]);
expect(await daemon.saved("parent")).toMatchObject([{ id: "three", state: "queued" }]);
await expect(daemon.delivery.promote("parent", "one", "steer")).resolves.toBe("not_found");
await daemon.delivery.close();
});
test("a withdrawn message is never sent, in this daemon or after a restart", async () => {
const home = await createHome();
const first = openDaemon(home, { running: true });
const live = await queue(first.delivery, "live");
await queue(first.delivery, "restored");
await queue(first.delivery, "kept");
const changes: string[] = [];
first.delivery.onChange((recipientId) => changes.push(recipientId));
await expect(first.delivery.withdraw("parent", "live")).resolves.toMatchObject({
status: "withdrawn",
});
await expect(live.dispatched).rejects.toMatchObject({ name: "AbortError" });
expect(first.withdrawn).toEqual(["live"]);
expect(changes).toContain("parent");
await first.delivery.close();
const second = openDaemon(home, { running: true });
await second.delivery.start();
await expect(second.delivery.withdraw("parent", "restored")).resolves.toMatchObject({
status: "withdrawn",
});
expect(second.withdrawn).toEqual(["restored"]);
await second.endTurn();
expect(second.ids()).toEqual([["kept"]]);
await second.delivery.close();
});
test("a message the provider is receiving can no longer be withdrawn or promoted", async () => {
const daemon = openDaemon(await createHome(), { neverAnswers: true });
await queue(daemon.delivery, "going", { activeTurnBehavior: "steer" });
await daemon.settle();
await expect(daemon.delivery.withdraw("parent", "going")).resolves.toEqual({
status: "already_dispatching",
});
await expect(daemon.delivery.promote("parent", "going", "interrupt")).resolves.toBe(
"already_dispatching",
);
expect(daemon.withdrawn).toEqual([]);
});
test("clearing a recipient drops its queue and rejects whoever is waiting on it", async () => {
const daemon = openDaemon(await createHome(), { running: true });
const receipt = await queue(daemon.delivery, "report");
await queue(daemon.delivery, "other", { recipientId: "sibling" });
await daemon.delivery.clearRecipient("parent");
await expect(receipt.dispatched).rejects.toMatchObject({ name: "AbortError" });
expect(daemon.withdrawn).toEqual(["report"]);
expect(daemon.delivery.hasPending("parent")).toBe(false);
expect(await daemon.saved("parent")).toEqual([]);
expect(await daemon.saved("sibling")).toMatchObject([{ id: "other" }]);
await daemon.delivery.close();
});
test("startup drops what a deleted agent, or an archived one it may not reopen, had queued", async () => {
const home = await createHome();
const first = openDaemon(home, { running: true });
await queue(first.delivery, "gone", { recipientId: "deleted" });
await queue(first.delivery, "silent", { recipientId: "archived", unarchive: false });
await queue(first.delivery, "reopens", { recipientId: "archived" });
await first.delivery.close();
const second = openDaemon(home, {
running: true,
status: { deleted: "deleted", archived: "archived" },
});
await second.delivery.start();
expect(second.withdrawn.sort()).toEqual(["gone", "silent"]);
expect(await second.saved("deleted")).toEqual([]);
expect(await second.saved("archived")).toMatchObject([{ id: "reopens" }]);
await second.delivery.close();
});
test("a provider that refuses to start the turn leaves the queue held, not retried", async () => {
let refuse = true;
const daemon = openDaemon(await createHome(), { refuseStart: () => refuse });
const receipt = await queue(daemon.delivery, "report", { activeTurnBehavior: "steer" });
await daemon.settle();
await daemon.tick();
await daemon.endTurn();
expect(await daemon.saved("parent")).toEqual([{ id: "report", state: "queued", held: true }]);
expect(daemon.errors).toHaveLength(1);
// A caller waiting for the recipient is not left waiting for a held message.
await daemon.delivery.waitForDispatch("parent", new AbortController().signal);
refuse = false;
await daemon.delivery.promote("parent", "report", "steer");
await expect(receipt.dispatched).resolves.toBe("turn_started");
await daemon.delivery.close();
});
test("a message that cannot be read is dropped instead of blocking the ones behind it", async () => {
const daemon = openDaemon(await createHome(), { running: true });
const broken = await queue(daemon.delivery, "broken", {
attachments: [
{
type: "uploaded_file",
role: "image",
id: "upload_missing",
fileName: "missing.png",
mimeType: "image/png",
size: 1,
path: "/nowhere/missing.png",
},
],
});
await queue(daemon.delivery, "fine");
await daemon.endTurn();
await daemon.tick();
await expect(broken.dispatched).rejects.toThrow("Uploaded image");
expect(daemon.ids()).toEqual([["fine"]]);
expect(await daemon.saved("parent")).toEqual([]);
await daemon.delivery.close();
});
@@ -26,7 +26,7 @@ const agentNotificationSourceSchema = z.object({
event: z.enum(["finished", "errored", "permission-required", "closed"]),
});
/** Senders a delivery names. A schedule fire is marked by the schedule module alone. */
const promptSourceSchema = z.discriminatedUnion("kind", [
export const agentPromptSourceSchema = z.discriminatedUnion("kind", [
changeRequestSourceSchema,
agentMessageSourceSchema,
agentNotificationSourceSchema,
@@ -37,7 +37,7 @@ const markedSourceSchema = z.discriminatedUnion("kind", [
agentNotificationSourceSchema,
z.object({ kind: z.literal("schedule") }),
]);
export type AgentPromptSource = z.infer<typeof promptSourceSchema>;
export type AgentPromptSource = z.infer<typeof agentPromptSourceSchema>;
type MarkedSource = z.infer<typeof markedSourceSchema>;
type AgentNotificationEvent = z.infer<typeof agentNotificationSourceSchema>["event"];
@@ -280,6 +280,19 @@ export function projectAgentMessages(item: AgentTimelineItem): AgentTimelineItem
return messages ? messages.map((message) => projectAgentMessage(item, message)) : [item];
}
const AGENT_MESSAGE_CALL = "paseo-agent-message:";
const CHANGE_REQUEST_CALL = "paseo-change-request:";
/** The delivery ids a timeline item stands for, as the projection below names them. */
export function projectedMessageIds(item: AgentTimelineItem): string[] {
if (item.type === "user_message")
return [item.clientMessageId, item.messageId].filter((id) => id !== undefined);
if (item.type !== "tool_call") return [];
return [AGENT_MESSAGE_CALL, CHANGE_REQUEST_CALL]
.filter((prefix) => item.callId.startsWith(prefix))
.map((prefix) => item.callId.slice(prefix.length));
}
/**
* The daemon decides how each delivered message reads: a person's text and peer messages are
* messages, and everything the daemon reports is a completed plain-text tool call.
@@ -303,7 +316,7 @@ function projectAgentMessage(
case "change-request-update":
return {
type: "tool_call",
callId: `paseo-change-request:${message.id}`,
callId: `${CHANGE_REQUEST_CALL}${message.id}`,
name: "change_request_update",
status: "completed",
error: null,
@@ -312,7 +325,7 @@ function projectAgentMessage(
case "agent-notification":
return {
type: "tool_call",
callId: `paseo-agent-message:${message.id}`,
callId: `${AGENT_MESSAGE_CALL}${message.id}`,
name: NOTIFICATION_TOOL_NAMES[source.event],
status: "completed",
error: null,
@@ -326,7 +339,7 @@ function projectAgentMessage(
case "agent-message":
return {
type: "tool_call",
callId: `paseo-agent-message:${message.id}`,
callId: `${AGENT_MESSAGE_CALL}${message.id}`,
// The wire has no sender on a user message, so clients render this as a "Sent by"
// bubble. Older clients that predate the bubble expand the plain-text body.
agentMessage: {
@@ -9,3 +9,16 @@ export {
} from "./envelope.js";
export { createAgentMessageDelivery, type AgentMessageDelivery } from "./delivery.js";
export type { AgentMessageBehavior } from "./guidance.js";
export {
MAX_AGENT_QUEUE_DEPTH,
type AgentMessageQueueStore,
type EnqueueStoreInput,
type EnqueueStoreResult,
type PersistedQueuedMessage,
type PromoteStoreResult,
type QueuedMessageState,
type QueuedMessageUrgency,
type WithdrawStoreResult,
} from "./store.js";
export { createJsonAgentMessageQueueStore, type CorruptQueueFile } from "./internal/json-store.js";
export { createMemoryAgentMessageQueueStore } from "./internal/memory-store.js";
@@ -0,0 +1,220 @@
import { readdir, readFile, rename, rm } from "node:fs/promises";
import { basename, dirname, join, resolve } from "node:path";
import { AgentAttachmentSchema, QueuedProviderSwitchSchema } from "@getpaseo/protocol/messages";
import { z } from "zod";
import { writeJsonFileAtomic } from "../../../atomic-file.js";
import { agentPromptSourceSchema } from "../envelope.js";
import type { AgentMessageQueueStore } from "../store.js";
import {
assertValidRecipientId,
clearQueue,
cloneQueuedMessage,
createEmptyRecipientQueueState,
createKeyedSerializer,
enqueueIntoQueue,
markDispatchingInQueue,
markHeldInQueue,
promoteInQueue,
removeFromQueue,
revertDispatchingInQueue,
sortAllQueuedMessages,
sortQueuedMessages,
withdrawFromQueue,
type RecipientQueueState,
type TransitionOutcome,
} from "./queue-state.js";
const PersistedQueuedMessageSchema = z.object({
id: z.string().min(1),
recipientId: z.string().min(1),
seq: z.number().int().positive(),
enqueuedAt: z.string().min(1),
text: z.string(),
attachments: z.array(AgentAttachmentSchema),
source: agentPromptSourceSchema.nullable(),
sessionMode: z.string().min(1).optional(),
providerSwitch: QueuedProviderSwitchSchema.optional(),
unarchive: z.boolean(),
clearPendingPermissions: z.boolean(),
urgency: z.enum(["steer", "interrupt"]).nullable(),
held: z.boolean(),
state: z.enum(["queued", "dispatching"]),
dispatchAttemptedAt: z.string().min(1).optional(),
fingerprint: z.string().optional(),
});
const PersistedRecipientQueueFileSchema = z.object({
version: z.literal(1),
nextSeq: z.number().int().positive(),
items: z.array(PersistedQueuedMessageSchema),
});
/** The file is there and readable, but does not hold this recipient's queue. */
class CorruptQueueFileError extends Error {
constructor(
readonly filePath: string,
cause: unknown,
) {
super(cause instanceof Error ? cause.message : String(cause), { cause });
this.name = "CorruptQueueFileError";
}
}
/** A queue file that could not be read, and where it was moved to. */
export interface CorruptQueueFile {
recipientId: string;
movedTo: string;
error: unknown;
}
/** Creates a per-agent atomic JSON file `AgentMessageQueueStore` under `$PASEO_HOME/agent-queues/`. */
export function createJsonAgentMessageQueueStore(
paseoHome: string,
options: { onCorruptFile?: (file: CorruptQueueFile) => void } = {},
): AgentMessageQueueStore {
const queuesDir = resolve(join(paseoHome, "agent-queues"));
const cache = new Map<string, RecipientQueueState>();
const serializer = createKeyedSerializer();
function recipientFilePath(recipientId: string): string {
assertValidRecipientId(recipientId);
const filePath = resolve(queuesDir, `${recipientId}.json`);
if (dirname(filePath) !== queuesDir || basename(filePath) !== `${recipientId}.json`) {
throw new Error(`Invalid agent queue recipient id: ${recipientId}`);
}
return filePath;
}
async function loadRecipient(recipientId: string): Promise<RecipientQueueState> {
const cached = cache.get(recipientId);
if (cached) {
return cached;
}
const filePath = recipientFilePath(recipientId);
let raw: string;
try {
raw = await readFile(filePath, "utf8");
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return createEmptyRecipientQueueState();
}
throw error;
}
let parsed: z.infer<typeof PersistedRecipientQueueFileSchema>;
try {
parsed = PersistedRecipientQueueFileSchema.parse(JSON.parse(raw));
for (const item of parsed.items) {
if (item.recipientId !== recipientId) {
throw new Error(
`Mismatched recipientId in ${filePath}: expected ${recipientId}, found ${item.recipientId}`,
);
}
}
} catch (error) {
throw new CorruptQueueFileError(filePath, error);
}
const items = sortQueuedMessages(parsed.items.map(cloneQueuedMessage));
const maxItemSeq = items.reduce((max, item) => Math.max(max, item.seq), 0);
const state: RecipientQueueState = {
nextSeq: Math.max(parsed.nextSeq, maxItemSeq + 1),
items,
};
cache.set(recipientId, state);
return state;
}
/** Keeps the unreadable file for inspection and frees its name for new messages. */
async function setAside(recipientId: string, error: CorruptQueueFileError): Promise<void> {
const movedTo = `${error.filePath}.corrupt.${Date.now()}`;
await rename(error.filePath, movedTo);
options.onCorruptFile?.({ recipientId, movedTo, error: error.cause });
}
async function persistRecipient(recipientId: string, state: RecipientQueueState): Promise<void> {
const filePath = recipientFilePath(recipientId);
if (state.items.length === 0) {
await rm(filePath, { force: true });
return;
}
await writeJsonFileAtomic(filePath, {
version: 1,
nextSeq: state.nextSeq,
items: state.items,
});
}
async function mutate<Result>(
recipientId: string,
transition: (current: RecipientQueueState) => TransitionOutcome<Result>,
): Promise<Result> {
assertValidRecipientId(recipientId);
return serializer.run(recipientId, async () => {
const current = await loadRecipient(recipientId);
const outcome = transition(current);
if (outcome.changed) {
await persistRecipient(recipientId, outcome.nextState);
cache.set(recipientId, outcome.nextState);
}
return outcome.result;
});
}
return {
async listAll() {
await serializer.drainAll();
let entries;
try {
entries = await readdir(queuesDir, { withFileTypes: true });
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return [];
}
throw error;
}
const recipientIds = entries
.filter(
(entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.startsWith("."),
)
.map((entry) => entry.name.slice(0, -".json".length));
const lists = await Promise.all(
recipientIds.map((recipientId) =>
serializer.run(recipientId, async () => {
try {
const state = await loadRecipient(recipientId);
return state.items.map(cloneQueuedMessage);
} catch (error) {
// One bad file must not keep the daemon from starting.
if (!(error instanceof CorruptQueueFileError)) throw error;
await setAside(recipientId, error);
return [];
}
}),
),
);
return sortAllQueuedMessages(lists.flat());
},
async listByRecipient(recipientId) {
assertValidRecipientId(recipientId);
return serializer.run(recipientId, async () => {
const state = await loadRecipient(recipientId);
return state.items.map(cloneQueuedMessage);
});
},
enqueue: (input) => mutate(input.recipientId, (current) => enqueueIntoQueue(current, input)),
markDispatching: (recipientId, ids, attemptedAt) =>
mutate(recipientId, (current) => markDispatchingInQueue(current, ids, attemptedAt)),
revertDispatching: (recipientId, ids) =>
mutate(recipientId, (current) => revertDispatchingInQueue(current, ids)),
markHeld: (recipientId) => mutate(recipientId, (current) => markHeldInQueue(current)),
promote: (recipientId, targetId, urgency) =>
mutate(recipientId, (current) => promoteInQueue(current, targetId, urgency)),
withdraw: (recipientId, id) => mutate(recipientId, (current) => withdrawFromQueue(current, id)),
remove: (recipientId, ids) => mutate(recipientId, (current) => removeFromQueue(current, ids)),
clearRecipient: (recipientId) => mutate(recipientId, (current) => clearQueue(current)),
};
}
@@ -0,0 +1,70 @@
import type { AgentMessageQueueStore, PersistedQueuedMessage } from "../store.js";
import {
assertValidRecipientId,
clearQueue,
cloneQueuedMessage,
createEmptyRecipientQueueState,
createKeyedSerializer,
enqueueIntoQueue,
markDispatchingInQueue,
markHeldInQueue,
promoteInQueue,
removeFromQueue,
revertDispatchingInQueue,
sortAllQueuedMessages,
withdrawFromQueue,
type RecipientQueueState,
type TransitionOutcome,
} from "./queue-state.js";
/** Creates an in-memory `AgentMessageQueueStore` for fast deterministic unit tests. */
export function createMemoryAgentMessageQueueStore(): AgentMessageQueueStore {
const queues = new Map<string, RecipientQueueState>();
const serializer = createKeyedSerializer();
async function mutate<Result>(
recipientId: string,
transition: (current: RecipientQueueState) => TransitionOutcome<Result>,
): Promise<Result> {
assertValidRecipientId(recipientId);
return serializer.run(recipientId, async () => {
const current = queues.get(recipientId) ?? createEmptyRecipientQueueState();
const outcome = transition(current);
if (outcome.changed) {
queues.set(recipientId, outcome.nextState);
}
return outcome.result;
});
}
return {
async listAll() {
await serializer.drainAll();
const all: PersistedQueuedMessage[] = [];
for (const state of queues.values()) {
for (const item of state.items) {
all.push(cloneQueuedMessage(item));
}
}
return sortAllQueuedMessages(all);
},
async listByRecipient(recipientId) {
assertValidRecipientId(recipientId);
return serializer.run(recipientId, async () => {
const state = queues.get(recipientId);
return state ? state.items.map(cloneQueuedMessage) : [];
});
},
enqueue: (input) => mutate(input.recipientId, (current) => enqueueIntoQueue(current, input)),
markDispatching: (recipientId, ids, attemptedAt) =>
mutate(recipientId, (current) => markDispatchingInQueue(current, ids, attemptedAt)),
revertDispatching: (recipientId, ids) =>
mutate(recipientId, (current) => revertDispatchingInQueue(current, ids)),
markHeld: (recipientId) => mutate(recipientId, (current) => markHeldInQueue(current)),
promote: (recipientId, targetId, urgency) =>
mutate(recipientId, (current) => promoteInQueue(current, targetId, urgency)),
withdraw: (recipientId, id) => mutate(recipientId, (current) => withdrawFromQueue(current, id)),
remove: (recipientId, ids) => mutate(recipientId, (current) => removeFromQueue(current, ids)),
clearRecipient: (recipientId) => mutate(recipientId, (current) => clearQueue(current)),
};
}
@@ -0,0 +1,372 @@
import {
MAX_AGENT_QUEUE_DEPTH,
type EnqueueStoreInput,
type EnqueueStoreResult,
type PersistedQueuedMessage,
type PromoteStoreResult,
type QueuedMessageUrgency,
type WithdrawStoreResult,
} from "../store.js";
const RECIPIENT_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
export interface RecipientQueueState {
nextSeq: number;
items: PersistedQueuedMessage[];
}
export interface TransitionOutcome<Result> {
nextState: RecipientQueueState;
changed: boolean;
result: Result;
}
export function assertValidRecipientId(recipientId: string): void {
if (!RECIPIENT_ID_PATTERN.test(recipientId)) {
throw new Error(`Invalid agent queue recipient id: ${recipientId}`);
}
}
export function createEmptyRecipientQueueState(nextSeq = 1): RecipientQueueState {
return { nextSeq, items: [] };
}
export function cloneQueuedMessage(record: PersistedQueuedMessage): PersistedQueuedMessage {
const cloned: PersistedQueuedMessage = {
id: record.id,
recipientId: record.recipientId,
seq: record.seq,
enqueuedAt: record.enqueuedAt,
text: record.text,
attachments: structuredClone(record.attachments),
source: record.source ? structuredClone(record.source) : null,
unarchive: record.unarchive,
clearPendingPermissions: record.clearPendingPermissions,
urgency: record.urgency,
held: record.held,
state: record.state,
};
if (record.sessionMode !== undefined) {
cloned.sessionMode = record.sessionMode;
}
if (record.providerSwitch !== undefined) {
cloned.providerSwitch = structuredClone(record.providerSwitch);
}
if (record.dispatchAttemptedAt !== undefined) {
cloned.dispatchAttemptedAt = record.dispatchAttemptedAt;
}
if (record.fingerprint !== undefined) {
cloned.fingerprint = record.fingerprint;
}
return cloned;
}
export function sortQueuedMessages(items: PersistedQueuedMessage[]): PersistedQueuedMessage[] {
return items.sort((left, right) => left.seq - right.seq);
}
export function sortAllQueuedMessages(items: PersistedQueuedMessage[]): PersistedQueuedMessage[] {
return items.sort((left, right) => {
if (left.recipientId < right.recipientId) return -1;
if (left.recipientId > right.recipientId) return 1;
return left.seq - right.seq;
});
}
/** Runs async operations sequentially per key while cleaning up idle queue tails. */
export function createKeyedSerializer() {
const pending = new Map<string, Promise<void>>();
async function run<T>(key: string, action: () => Promise<T>): Promise<T> {
const previous = pending.get(key) ?? Promise.resolve();
const result = previous.then(action);
const tail = result.then(
() => undefined,
() => undefined,
);
pending.set(key, tail);
try {
return await result;
} finally {
if (pending.get(key) === tail) {
pending.delete(key);
}
}
}
async function drainAll(): Promise<void> {
while (pending.size > 0) {
await Promise.all(Array.from(pending.values()));
}
}
return { run, drainAll };
}
export function enqueueIntoQueue(
current: RecipientQueueState,
input: EnqueueStoreInput,
): TransitionOutcome<EnqueueStoreResult> {
if (!input.id) {
throw new Error("Queued message id must be non-empty");
}
if (!input.enqueuedAt) {
throw new Error("Queued message enqueuedAt must be non-empty");
}
const existing = current.items.find((item) => item.id === input.id);
if (existing) {
if (existing.fingerprint !== input.fingerprint) {
return { nextState: current, changed: false, result: { status: "conflict" } };
}
return {
nextState: current,
changed: false,
result: { status: "duplicate", record: cloneQueuedMessage(existing) },
};
}
if (current.items.length >= MAX_AGENT_QUEUE_DEPTH) {
return {
nextState: current,
changed: false,
result: { status: "full", limit: MAX_AGENT_QUEUE_DEPTH },
};
}
const record: PersistedQueuedMessage = {
id: input.id,
recipientId: input.recipientId,
seq: current.nextSeq,
enqueuedAt: input.enqueuedAt,
text: input.text,
attachments: structuredClone(input.attachments),
source: input.source ? structuredClone(input.source) : null,
unarchive: input.unarchive,
clearPendingPermissions: input.clearPendingPermissions,
urgency: input.urgency,
held: input.held,
state: "queued",
...(input.sessionMode !== undefined ? { sessionMode: input.sessionMode } : {}),
...(input.providerSwitch !== undefined
? { providerSwitch: structuredClone(input.providerSwitch) }
: {}),
...(input.fingerprint !== undefined ? { fingerprint: input.fingerprint } : {}),
};
return {
nextState: {
nextSeq: current.nextSeq + 1,
items: sortQueuedMessages([...current.items.map(cloneQueuedMessage), record]),
},
changed: true,
result: { status: "inserted", record: cloneQueuedMessage(record) },
};
}
export function markDispatchingInQueue(
current: RecipientQueueState,
ids: readonly string[],
attemptedAt: string,
): TransitionOutcome<PersistedQueuedMessage[]> {
if (ids.length === 0 || current.items.length === 0) {
return { nextState: current, changed: false, result: [] };
}
if (!attemptedAt) {
throw new Error("attemptedAt must be non-empty");
}
const targetIds = new Set(ids);
const transitioned: PersistedQueuedMessage[] = [];
let changed = false;
const nextItems = current.items.map((item) => {
const copy = cloneQueuedMessage(item);
if (targetIds.has(copy.id) && copy.state === "queued") {
copy.state = "dispatching";
copy.dispatchAttemptedAt = attemptedAt;
changed = true;
transitioned.push(cloneQueuedMessage(copy));
}
return copy;
});
if (!changed) {
return { nextState: current, changed: false, result: [] };
}
return {
nextState: { nextSeq: current.nextSeq, items: nextItems },
changed: true,
result: sortQueuedMessages(transitioned),
};
}
export function revertDispatchingInQueue(
current: RecipientQueueState,
ids: readonly string[],
): TransitionOutcome<void> {
if (ids.length === 0 || current.items.length === 0) {
return { nextState: current, changed: false, result: undefined };
}
const targetIds = new Set(ids);
let changed = false;
const nextItems = current.items.map((item) => {
const copy = cloneQueuedMessage(item);
if (targetIds.has(copy.id) && copy.state === "dispatching") {
copy.state = "queued";
delete copy.dispatchAttemptedAt;
changed = true;
}
return copy;
});
if (!changed) {
return { nextState: current, changed: false, result: undefined };
}
return {
nextState: { nextSeq: current.nextSeq, items: nextItems },
changed: true,
result: undefined,
};
}
export function markHeldInQueue(
current: RecipientQueueState,
): TransitionOutcome<PersistedQueuedMessage[]> {
if (current.items.length === 0) {
return { nextState: current, changed: false, result: [] };
}
let changed = false;
const nextItems = current.items.map((item) => {
const copy = cloneQueuedMessage(item);
if (!copy.held || copy.urgency !== null) {
copy.held = true;
copy.urgency = null;
changed = true;
}
return copy;
});
if (!changed) {
return {
nextState: current,
changed: false,
result: current.items.map(cloneQueuedMessage),
};
}
return {
nextState: { nextSeq: current.nextSeq, items: nextItems },
changed: true,
result: nextItems.map(cloneQueuedMessage),
};
}
export function promoteInQueue(
current: RecipientQueueState,
targetId: string,
urgency: QueuedMessageUrgency,
): TransitionOutcome<PromoteStoreResult> {
const targetIndex = current.items.findIndex((item) => item.id === targetId);
if (targetIndex === -1) {
return { nextState: current, changed: false, result: { status: "not_found" } };
}
if (current.items[targetIndex]!.state === "dispatching") {
return { nextState: current, changed: false, result: { status: "already_dispatching" } };
}
let changed = false;
const promoted: PersistedQueuedMessage[] = [];
const nextItems = current.items.map((item, index) => {
const copy = cloneQueuedMessage(item);
// Prefix 0..targetIndex advances in FIFO admission order; items already
// dispatching stay in flight untouched while queued items are released.
if (index <= targetIndex && copy.state === "queued") {
if (copy.held || copy.urgency !== urgency) {
copy.held = false;
copy.urgency = urgency;
changed = true;
}
promoted.push(cloneQueuedMessage(copy));
}
return copy;
});
return {
nextState: changed ? { nextSeq: current.nextSeq, items: nextItems } : current,
changed,
result: {
status: "promoted",
promoted,
items: nextItems.map(cloneQueuedMessage),
},
};
}
export function withdrawFromQueue(
current: RecipientQueueState,
id: string,
): TransitionOutcome<WithdrawStoreResult> {
const index = current.items.findIndex((item) => item.id === id);
if (index === -1) {
return { nextState: current, changed: false, result: { status: "not_found" } };
}
const candidate = current.items[index]!;
if (candidate.state === "dispatching") {
return { nextState: current, changed: false, result: { status: "already_dispatching" } };
}
const nextItems = current.items
.filter((item) => item.id !== id)
.map((item) => cloneQueuedMessage(item));
return {
nextState: { nextSeq: current.nextSeq, items: nextItems },
changed: true,
result: { status: "withdrawn", item: cloneQueuedMessage(candidate) },
};
}
export function removeFromQueue(
current: RecipientQueueState,
ids: readonly string[],
): TransitionOutcome<void> {
if (ids.length === 0 || current.items.length === 0) {
return { nextState: current, changed: false, result: undefined };
}
const targetIds = new Set(ids);
const nextItems = current.items.filter((item) => !targetIds.has(item.id)).map(cloneQueuedMessage);
if (nextItems.length === current.items.length) {
return { nextState: current, changed: false, result: undefined };
}
return {
nextState: { nextSeq: current.nextSeq, items: nextItems },
changed: true,
result: undefined,
};
}
export function clearQueue(
current: RecipientQueueState,
): TransitionOutcome<PersistedQueuedMessage[]> {
if (current.items.length === 0) {
return { nextState: current, changed: false, result: [] };
}
const removed = current.items.map(cloneQueuedMessage);
return {
nextState: createEmptyRecipientQueueState(current.nextSeq),
changed: true,
result: removed,
};
}
@@ -0,0 +1,722 @@
import { access, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, test } from "vitest";
import {
MAX_AGENT_QUEUE_DEPTH,
createJsonAgentMessageQueueStore,
createMemoryAgentMessageQueueStore,
type AgentMessageQueueStore,
type EnqueueStoreInput,
} from "../index.js";
const temporaryHomes: string[] = [];
afterEach(async () => {
await Promise.all(
temporaryHomes.splice(0).map((home) => rm(home, { recursive: true, force: true })),
);
});
async function createTempHome(): Promise<string> {
const home = await mkdtemp(join(tmpdir(), "paseo-agent-queue-store-"));
temporaryHomes.push(home);
return home;
}
async function fileExists(filePath: string): Promise<boolean> {
try {
await access(filePath);
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return false;
}
throw error;
}
}
function makeInput(overrides: Partial<EnqueueStoreInput> = {}): EnqueueStoreInput {
return {
id: overrides.id ?? "msg-1",
recipientId: overrides.recipientId ?? "agent-1",
enqueuedAt: overrides.enqueuedAt ?? "2026-11-30T07:00:00.000Z",
text: overrides.text ?? "hello world",
attachments: overrides.attachments ?? [],
source: overrides.source === undefined ? null : overrides.source,
...(overrides.sessionMode !== undefined ? { sessionMode: overrides.sessionMode } : {}),
...(overrides.providerSwitch ? { providerSwitch: overrides.providerSwitch } : {}),
unarchive: overrides.unarchive ?? true,
clearPendingPermissions: overrides.clearPendingPermissions ?? false,
urgency: overrides.urgency === undefined ? null : overrides.urgency,
held: overrides.held ?? false,
...(overrides.fingerprint !== undefined ? { fingerprint: overrides.fingerprint } : {}),
};
}
interface AdapterFactory {
name: string;
create(): Promise<{ store: AgentMessageQueueStore; home?: string }>;
}
const adapters: AdapterFactory[] = [
{
name: "memory",
create: async () => ({ store: createMemoryAgentMessageQueueStore() }),
},
{
name: "json",
create: async () => {
const home = await createTempHome();
return { store: createJsonAgentMessageQueueStore(home), home };
},
},
];
describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) => {
test("keeps the provider switch a message carries", async () => {
const { store } = await adapter.create();
const providerSwitch = {
provider: "codex",
model: "gpt-5.4",
modeId: "auto",
thinkingOptionId: null,
providerOptions: { fast_mode: true },
};
await store.enqueue(makeInput({ id: "m1", providerSwitch }));
await store.markDispatching("agent-1", ["m1"], "2026-11-30T07:00:01.000Z");
await store.revertDispatching("agent-1", ["m1"]);
expect((await store.listAll()).map((item) => item.providerSwitch)).toEqual([providerSwitch]);
});
test("enqueues items with monotonic per-recipient seq and lists them in order", async () => {
const { store } = await adapter.create();
expect(await store.listAll()).toEqual([]);
expect(await store.listByRecipient("agent-1")).toEqual([]);
expect(MAX_AGENT_QUEUE_DEPTH).toBe(100);
const first = await store.enqueue(
makeInput({
id: "msg-1",
recipientId: "agent-1",
text: "first",
attachments: [
{
type: "uploaded_file",
id: "up-1",
fileName: "screen.png",
mimeType: "image/png",
size: 1234,
path: "/tmp/uploads/up-1/screen.png",
role: "image",
},
],
sessionMode: "code",
fingerprint: "fp-1",
}),
);
const second = await store.enqueue(
makeInput({
id: "msg-2",
recipientId: "agent-1",
text: "second",
source: { kind: "agent-message", agentId: "sender-1", title: "Worker" },
urgency: "steer",
}),
);
const other = await store.enqueue(
makeInput({
id: "msg-other",
recipientId: "agent-2",
text: "other recipient",
}),
);
expect(first).toEqual({
status: "inserted",
record: {
id: "msg-1",
recipientId: "agent-1",
seq: 1,
enqueuedAt: "2026-11-30T07:00:00.000Z",
text: "first",
attachments: [
{
type: "uploaded_file",
id: "up-1",
fileName: "screen.png",
mimeType: "image/png",
size: 1234,
path: "/tmp/uploads/up-1/screen.png",
role: "image",
},
],
source: null,
sessionMode: "code",
unarchive: true,
clearPendingPermissions: false,
urgency: null,
held: false,
state: "queued",
fingerprint: "fp-1",
},
});
expect(second).toMatchObject({ status: "inserted", record: { id: "msg-2", seq: 2 } });
expect(other).toMatchObject({
status: "inserted",
record: { id: "msg-other", recipientId: "agent-2", seq: 1 },
});
const list1 = await store.listByRecipient("agent-1");
expect(list1.map((item) => item.id)).toEqual(["msg-1", "msg-2"]);
expect(list1.map((item) => item.seq)).toEqual([1, 2]);
const all = await store.listAll();
expect(all.map((item) => `${item.recipientId}:${item.id}:${item.seq}`)).toEqual([
"agent-1:msg-1:1",
"agent-1:msg-2:2",
"agent-2:msg-other:1",
]);
});
test("clones inputs and returned records so external mutations cannot corrupt store state", async () => {
const { store } = await adapter.create();
const attachments: EnqueueStoreInput["attachments"] = [
{
type: "text",
fileName: "note.txt",
mimeType: "text/plain",
size: 5,
text: "hello",
},
];
const source: EnqueueStoreInput["source"] = {
kind: "agent-notification",
agentId: "child-1",
event: "finished",
};
const inserted = await store.enqueue(makeInput({ attachments, source }));
expect(inserted.status).toBe("inserted");
attachments.push({
type: "text",
fileName: "mutated.txt",
mimeType: "text/plain",
size: 3,
text: "bad",
});
source.agentId = "tampered";
if (inserted.status === "inserted") {
inserted.record.text = "tampered";
inserted.record.attachments.length = 0;
}
const listed = await store.listByRecipient("agent-1");
expect(listed).toHaveLength(1);
expect(listed[0]!.text).toBe("hello world");
expect(listed[0]!.attachments).toHaveLength(1);
expect(listed[0]!.source).toEqual({
kind: "agent-notification",
agentId: "child-1",
event: "finished",
});
listed[0]!.text = "mutated-after-list";
expect((await store.listByRecipient("agent-1"))[0]!.text).toBe("hello world");
});
test("enqueue is idempotent on matching fingerprint and reports conflict on mismatch", async () => {
const { store } = await adapter.create();
const first = await store.enqueue(makeInput({ id: "k1", text: "one", fingerprint: "fp-1" }));
expect(first).toMatchObject({ status: "inserted", record: { id: "k1", seq: 1 } });
const duplicate = await store.enqueue(
makeInput({ id: "k1", text: "ignored duplicate payload", fingerprint: "fp-1" }),
);
expect(duplicate).toEqual({
status: "duplicate",
record: first.status === "inserted" ? first.record : undefined,
});
const conflict = await store.enqueue(
makeInput({ id: "k1", text: "different", fingerprint: "fp-2" }),
);
expect(conflict).toEqual({ status: "conflict" });
const undefFirst = await store.enqueue(makeInput({ id: "k2", text: "no-fp" }));
expect(undefFirst).toMatchObject({ status: "inserted", record: { id: "k2", seq: 2 } });
const undefDup = await store.enqueue(makeInput({ id: "k2", text: "retry" }));
expect(undefDup).toMatchObject({ status: "duplicate", record: { id: "k2", seq: 2 } });
const undefConflict = await store.enqueue(
makeInput({ id: "k2", text: "added-fp", fingerprint: "fp-added" }),
);
expect(undefConflict).toEqual({ status: "conflict" });
const items = await store.listByRecipient("agent-1");
expect(items.map((item) => item.id)).toEqual(["k1", "k2"]);
});
test("enforces per-recipient depth cap while still allowing idempotent retries", async () => {
const { store } = await adapter.create();
for (let i = 1; i <= MAX_AGENT_QUEUE_DEPTH; i++) {
const res = await store.enqueue(
makeInput({ id: `m-${i}`, text: `msg ${i}`, fingerprint: `fp-${i}` }),
);
expect(res.status).toBe("inserted");
}
const overflow = await store.enqueue(
makeInput({ id: "m-overflow", text: "too many", fingerprint: "fp-overflow" }),
);
expect(overflow).toEqual({ status: "full", limit: MAX_AGENT_QUEUE_DEPTH });
const retryAtCap = await store.enqueue(
makeInput({ id: "m-1", text: "msg 1", fingerprint: "fp-1" }),
);
expect(retryAtCap).toMatchObject({ status: "duplicate", record: { id: "m-1", seq: 1 } });
const conflictAtCap = await store.enqueue(
makeInput({ id: "m-1", text: "changed", fingerprint: "fp-other" }),
);
expect(conflictAtCap).toEqual({ status: "conflict" });
// Other recipients have independent caps.
const otherRecipient = await store.enqueue(
makeInput({ id: "other-1", recipientId: "agent-2", text: "separate queue" }),
);
expect(otherRecipient.status).toBe("inserted");
// Removing one frees capacity and keeps seq monotonic.
await store.remove("agent-1", ["m-50"]);
const afterRemoval = await store.enqueue(
makeInput({ id: "m-101", text: "msg 101", fingerprint: "fp-101" }),
);
expect(afterRemoval).toMatchObject({
status: "inserted",
record: { id: "m-101", seq: MAX_AGENT_QUEUE_DEPTH + 1 },
});
});
test("keeps seq strictly monotonic across removals and withdrawals", async () => {
const { store } = await adapter.create();
await store.enqueue(makeInput({ id: "a" }));
await store.enqueue(makeInput({ id: "b" }));
await store.enqueue(makeInput({ id: "c" }));
const withdrawn = await store.withdraw("agent-1", "c");
expect(withdrawn.status).toBe("withdrawn");
await store.remove("agent-1", ["a"]);
const fourth = await store.enqueue(makeInput({ id: "d" }));
expect(fourth).toMatchObject({ status: "inserted", record: { id: "d", seq: 4 } });
await store.clearRecipient("agent-1");
const fifth = await store.enqueue(makeInput({ id: "e" }));
expect(fifth).toMatchObject({ status: "inserted", record: { id: "e", seq: 5 } });
});
test("markDispatching and revertDispatching preserve seq, held, and urgency", async () => {
const { store } = await adapter.create();
await store.enqueue(makeInput({ id: "m1", held: true, urgency: "steer" }));
await store.enqueue(makeInput({ id: "m2", held: false, urgency: null }));
await store.enqueue(makeInput({ id: "m3" }));
const marked = await store.markDispatching(
"agent-1",
["m2", "m1", "missing"],
"2026-11-30T07:05:00.000Z",
);
expect(marked.map((item) => item.id)).toEqual(["m1", "m2"]);
expect(marked.every((item) => item.state === "dispatching")).toBe(true);
expect(marked.every((item) => item.dispatchAttemptedAt === "2026-11-30T07:05:00.000Z")).toBe(
true,
);
// Re-marking an already dispatching item does not overwrite its dispatchAttemptedAt.
const remark = await store.markDispatching("agent-1", ["m1", "m3"], "2026-11-30T07:06:00.000Z");
expect(remark.map((item) => item.id)).toEqual(["m3"]);
expect(remark[0]!.dispatchAttemptedAt).toBe("2026-11-30T07:06:00.000Z");
await store.revertDispatching("agent-1", ["m1", "m3", "nonexistent"]);
const items = await store.listByRecipient("agent-1");
expect(items).toEqual([
expect.objectContaining({
id: "m1",
seq: 1,
held: true,
urgency: "steer",
state: "queued",
}),
expect.objectContaining({
id: "m2",
seq: 2,
held: false,
urgency: null,
state: "dispatching",
dispatchAttemptedAt: "2026-11-30T07:05:00.000Z",
}),
expect.objectContaining({
id: "m3",
seq: 3,
state: "queued",
}),
]);
expect("dispatchAttemptedAt" in items[0]!).toBe(false);
expect("dispatchAttemptedAt" in items[2]!).toBe(false);
});
test("markHeld marks all items held and clears urgency while preserving state", async () => {
const { store } = await adapter.create();
expect(await store.markHeld("agent-1")).toEqual([]);
await store.enqueue(makeInput({ id: "m1", urgency: "interrupt", held: false }));
await store.enqueue(makeInput({ id: "m2", urgency: "steer", held: false }));
await store.markDispatching("agent-1", ["m1"], "2026-11-30T07:05:00.000Z");
const held = await store.markHeld("agent-1");
expect(held).toEqual([
expect.objectContaining({
id: "m1",
seq: 1,
held: true,
urgency: null,
state: "dispatching",
}),
expect.objectContaining({
id: "m2",
seq: 2,
held: true,
urgency: null,
state: "queued",
}),
]);
});
test("promote promotes FIFO prefix 0..k, clears held, and reports not_found / already_dispatching", async () => {
const { store } = await adapter.create();
expect(await store.promote("agent-1", "missing", "steer")).toEqual({ status: "not_found" });
await store.enqueue(makeInput({ id: "m1", held: true, urgency: null }));
await store.enqueue(makeInput({ id: "m2", held: true, urgency: null }));
await store.enqueue(makeInput({ id: "m3", held: true, urgency: null }));
// Promote middle item m2 -> promotes prefix [m1, m2], leaves m3 untouched.
const promotedPrefix = await store.promote("agent-1", "m2", "interrupt");
expect(promotedPrefix.status).toBe("promoted");
if (promotedPrefix.status === "promoted") {
expect(promotedPrefix.promoted.map((item) => item.id)).toEqual(["m1", "m2"]);
expect(
promotedPrefix.promoted.every((item) => !item.held && item.urgency === "interrupt"),
).toBe(true);
expect(promotedPrefix.items.map((item) => [item.id, item.held, item.urgency])).toEqual([
["m1", false, "interrupt"],
["m2", false, "interrupt"],
["m3", true, null],
]);
}
// Target itself is dispatching -> already_dispatching without mutating anything.
await store.markDispatching("agent-1", ["m1"], "2026-11-30T07:05:00.000Z");
expect(await store.promote("agent-1", "m1", "steer")).toEqual({
status: "already_dispatching",
});
// Earlier item m1 is dispatching while target m3 is queued -> leaves m1 dispatching, promotes queued prefix [m2, m3].
const promotePastDispatching = await store.promote("agent-1", "m3", "steer");
expect(promotePastDispatching.status).toBe("promoted");
if (promotePastDispatching.status === "promoted") {
expect(promotePastDispatching.promoted.map((item) => item.id)).toEqual(["m2", "m3"]);
expect(
promotePastDispatching.items.map((item) => ({
id: item.id,
state: item.state,
held: item.held,
urgency: item.urgency,
})),
).toEqual([
{ id: "m1", state: "dispatching", held: false, urgency: "interrupt" },
{ id: "m2", state: "queued", held: false, urgency: "steer" },
{ id: "m3", state: "queued", held: false, urgency: "steer" },
]);
}
});
test("withdraw atomically distinguishes withdrawn, not_found, and already_dispatching", async () => {
const { store } = await adapter.create();
expect(await store.withdraw("agent-1", "missing")).toEqual({ status: "not_found" });
await store.enqueue(makeInput({ id: "m1", text: "first" }));
await store.enqueue(makeInput({ id: "m2", text: "second" }));
await store.markDispatching("agent-1", ["m1"], "2026-11-30T07:05:00.000Z");
expect(await store.withdraw("agent-1", "m1")).toEqual({ status: "already_dispatching" });
expect((await store.listByRecipient("agent-1")).map((item) => item.id)).toEqual(["m1", "m2"]);
const withdrawn = await store.withdraw("agent-1", "m2");
expect(withdrawn).toEqual({
status: "withdrawn",
item: expect.objectContaining({ id: "m2", seq: 2, text: "second", state: "queued" }),
});
expect(await store.withdraw("agent-1", "m2")).toEqual({ status: "not_found" });
expect((await store.listByRecipient("agent-1")).map((item) => item.id)).toEqual(["m1"]);
});
test("remove and clearRecipient delete items regardless of state without affecting other recipients", async () => {
const { store } = await adapter.create();
await store.enqueue(makeInput({ id: "a1", recipientId: "agent-1" }));
await store.enqueue(makeInput({ id: "a2", recipientId: "agent-1" }));
await store.enqueue(makeInput({ id: "a3", recipientId: "agent-1" }));
await store.enqueue(makeInput({ id: "b1", recipientId: "agent-2" }));
await store.markDispatching("agent-1", ["a1"], "2026-11-30T07:05:00.000Z");
await store.remove("agent-1", ["a1", "missing"]);
expect((await store.listByRecipient("agent-1")).map((item) => item.id)).toEqual(["a2", "a3"]);
await store.markDispatching("agent-1", ["a2"], "2026-11-30T07:05:01.000Z");
const cleared = await store.clearRecipient("agent-1");
expect(cleared.map((item) => item.id)).toEqual(["a2", "a3"]);
expect(await store.listByRecipient("agent-1")).toEqual([]);
expect(await store.clearRecipient("agent-1")).toEqual([]);
expect((await store.listByRecipient("agent-2")).map((item) => item.id)).toEqual(["b1"]);
});
test("serializes concurrent mutations on the same recipient without lost updates", async () => {
const { store } = await adapter.create();
const enqueueResults = await Promise.all(
Array.from({ length: 20 }, (_, index) =>
store.enqueue(makeInput({ id: `concurrent-${index}`, text: `msg ${index}` })),
),
);
expect(enqueueResults.every((result) => result.status === "inserted")).toBe(true);
const listed = await store.listByRecipient("agent-1");
expect(listed).toHaveLength(20);
expect(listed.map((item) => item.seq)).toEqual(
Array.from({ length: 20 }, (_, index) => index + 1),
);
// Racing withdraw vs markDispatching on the same item allows only one winner.
const [withdrawOutcome, markOutcome] = await Promise.all([
store.withdraw("agent-1", "concurrent-0"),
store.markDispatching("agent-1", ["concurrent-0"], "2026-11-30T07:05:00.000Z"),
]);
if (withdrawOutcome.status === "withdrawn") {
expect(markOutcome).toEqual([]);
} else {
expect(withdrawOutcome).toEqual({ status: "already_dispatching" });
expect(markOutcome.map((item) => item.id)).toEqual(["concurrent-0"]);
}
});
test("rejects path traversal and invalid recipient ids on every recipient-scoped operation", async () => {
const { store } = await adapter.create();
const invalidIds = ["", ".", "..", "../escape", "a/b", "a\\b", "a\0b", "agent.json"];
for (const badId of invalidIds) {
await expect(store.listByRecipient(badId)).rejects.toThrow(/Invalid agent queue recipient/);
await expect(store.enqueue(makeInput({ recipientId: badId }))).rejects.toThrow(
/Invalid agent queue recipient/,
);
await expect(
store.markDispatching(badId, ["msg-1"], "2026-11-30T07:05:00.000Z"),
).rejects.toThrow(/Invalid agent queue recipient/);
await expect(store.revertDispatching(badId, ["msg-1"])).rejects.toThrow(
/Invalid agent queue recipient/,
);
await expect(store.markHeld(badId)).rejects.toThrow(/Invalid agent queue recipient/);
await expect(store.promote(badId, "msg-1", "steer")).rejects.toThrow(
/Invalid agent queue recipient/,
);
await expect(store.withdraw(badId, "msg-1")).rejects.toThrow(/Invalid agent queue recipient/);
await expect(store.remove(badId, ["msg-1"])).rejects.toThrow(/Invalid agent queue recipient/);
await expect(store.clearRecipient(badId)).rejects.toThrow(/Invalid agent queue recipient/);
}
});
});
describe("createJsonAgentMessageQueueStore persistence & file hygiene", () => {
test("persists items, states, and monotonic nextSeq across store restarts", async () => {
const home = await createTempHome();
const store1 = createJsonAgentMessageQueueStore(home);
await store1.enqueue(
makeInput({
id: "m1",
text: "first",
source: { kind: "change-request-update", url: "https://github.com/getpaseo/paseo/pull/1" },
fingerprint: "fp-1",
}),
);
await store1.enqueue(makeInput({ id: "m2", text: "second", held: true }));
await store1.enqueue(makeInput({ id: "m3", text: "third" }));
await store1.markDispatching("agent-1", ["m1"], "2026-11-30T07:10:00.000Z");
await store1.withdraw("agent-1", "m3");
const restarted = createJsonAgentMessageQueueStore(home);
expect(await restarted.listAll()).toEqual([
expect.objectContaining({
id: "m1",
seq: 1,
state: "dispatching",
dispatchAttemptedAt: "2026-11-30T07:10:00.000Z",
fingerprint: "fp-1",
}),
expect.objectContaining({
id: "m2",
seq: 2,
held: true,
state: "queued",
}),
]);
const afterRestartEnqueue = await restarted.enqueue(makeInput({ id: "m4", text: "fourth" }));
expect(afterRestartEnqueue).toMatchObject({ status: "inserted", record: { id: "m4", seq: 4 } });
});
test("deletes empty recipient queue files and avoids creating files for empty operations", async () => {
const home = await createTempHome();
const store = createJsonAgentMessageQueueStore(home);
const queueFile = join(home, "agent-queues", "agent-1.json");
expect(await store.listByRecipient("agent-1")).toEqual([]);
expect(await store.markHeld("agent-1")).toEqual([]);
expect(await store.withdraw("agent-1", "missing")).toEqual({ status: "not_found" });
expect(await store.promote("agent-1", "missing", "steer")).toEqual({ status: "not_found" });
await store.remove("agent-1", ["missing"]);
expect(await store.clearRecipient("agent-1")).toEqual([]);
expect(await fileExists(queueFile)).toBe(false);
await store.enqueue(makeInput({ id: "m1" }));
expect(await fileExists(queueFile)).toBe(true);
await store.withdraw("agent-1", "m1");
expect(await fileExists(queueFile)).toBe(false);
await store.enqueue(makeInput({ id: "m2" }));
expect(await fileExists(queueFile)).toBe(true);
await store.remove("agent-1", ["m2"]);
expect(await fileExists(queueFile)).toBe(false);
await store.enqueue(makeInput({ id: "m3" }));
expect(await fileExists(queueFile)).toBe(true);
await store.clearRecipient("agent-1");
expect(await fileExists(queueFile)).toBe(false);
// Re-enqueuing in the same store instance still preserves monotonic seq after file deletion.
const next = await store.enqueue(makeInput({ id: "m4" }));
expect(next).toMatchObject({ status: "inserted", record: { id: "m4", seq: 4 } });
});
test("ignores hidden temp files in agent-queues directory during listAll", async () => {
const home = await createTempHome();
const queuesDir = join(home, "agent-queues");
await mkdir(queuesDir, { recursive: true });
await writeFile(join(queuesDir, ".agent-1.json.123.tmp"), "{not json", "utf8");
const store = createJsonAgentMessageQueueStore(home);
await store.enqueue(makeInput({ id: "m1" }));
expect((await store.listAll()).map((item) => item.id)).toEqual(["m1"]);
});
test("fails visibly on invalid persisted JSON, invalid schema, or recipientId mismatch", async () => {
const home = await createTempHome();
const queuesDir = join(home, "agent-queues");
await mkdir(queuesDir, { recursive: true });
await writeFile(join(queuesDir, "bad-json.json"), "{broken", "utf8");
await expect(
createJsonAgentMessageQueueStore(home).listByRecipient("bad-json"),
).rejects.toThrow();
await writeFile(
join(queuesDir, "bad-schema.json"),
JSON.stringify({ version: 1, nextSeq: 1, items: [{ id: 42 }] }),
"utf8",
);
await expect(
createJsonAgentMessageQueueStore(home).listByRecipient("bad-schema"),
).rejects.toThrow();
await writeFile(
join(queuesDir, "wrong-recipient.json"),
JSON.stringify({
version: 1,
nextSeq: 2,
items: [
{
id: "m1",
recipientId: "other-agent",
seq: 1,
enqueuedAt: "2026-11-30T07:00:00.000Z",
text: "hi",
attachments: [],
source: null,
unarchive: true,
clearPendingPermissions: false,
urgency: null,
held: false,
state: "queued",
},
],
}),
"utf8",
);
await expect(
createJsonAgentMessageQueueStore(home).listByRecipient("wrong-recipient"),
).rejects.toThrow(/Mismatched recipientId/);
});
test("listAll sets one bad queue file aside and still loads every valid queue", async () => {
const home = await createTempHome();
const queuesDir = join(home, "agent-queues");
const writer = createJsonAgentMessageQueueStore(home);
await writer.enqueue(makeInput({ id: "m1", recipientId: "agent-1" }));
await writer.enqueue(makeInput({ id: "m2", recipientId: "agent-2" }));
await writeFile(join(queuesDir, "bad-agent.json"), "{broken", "utf8");
const corrupted: Array<{ recipientId: string; movedTo: string }> = [];
const store = createJsonAgentMessageQueueStore(home, {
onCorruptFile: ({ recipientId, movedTo }) => corrupted.push({ recipientId, movedTo }),
});
expect((await store.listAll()).map((item) => item.id)).toEqual(["m1", "m2"]);
const left = (await readdir(queuesDir)).filter((name) => name.startsWith("bad-agent"));
expect(left).toHaveLength(1);
const aside = left[0];
expect(aside).toMatch(/^bad-agent\.json\.corrupt\.\d+$/);
expect(await readFile(join(queuesDir, aside!), "utf8")).toBe("{broken");
expect(corrupted).toEqual([{ recipientId: "bad-agent", movedTo: join(queuesDir, aside!) }]);
// The recipient starts over with an empty queue.
await store.enqueue(makeInput({ id: "m3", recipientId: "bad-agent" }));
expect((await store.listByRecipient("bad-agent")).map((item) => item.id)).toEqual(["m3"]);
});
test("write failure rejects enqueue and does not pollute in-memory cache", async () => {
const home = await createTempHome();
const store = createJsonAgentMessageQueueStore(home);
expect(await store.listByRecipient("agent-1")).toEqual([]);
// Obstruct the target file path with a directory so rename fails.
await mkdir(join(home, "agent-queues", "agent-1.json"), { recursive: true });
await expect(store.enqueue(makeInput({ id: "m1" }))).rejects.toThrow();
await rm(join(home, "agent-queues", "agent-1.json"), { recursive: true, force: true });
expect(await store.listByRecipient("agent-1")).toEqual([]);
});
});
@@ -0,0 +1,32 @@
import type { AgentTimelineItem } from "../../agent-sdk-types.js";
import { projectedMessageIds, type AgentPromptSource } from "../envelope.js";
interface Candidate {
id: string;
text: string;
source: AgentPromptSource | null;
}
/** The ids of the messages a recipient's history shows it already received. */
export function findSubmitted(
history: readonly AgentTimelineItem[],
candidates: readonly Candidate[],
): Set<string> {
const projected = new Set(history.flatMap(projectedMessageIds));
const submitted = new Set(
candidates.filter(({ id }) => projected.has(id)).map((candidate) => candidate.id),
);
// A person's prompt sent alone carries no marker, and not every provider keeps its
// clientMessageId. The history's last user message being that exact text is the evidence left.
const [only] = candidates;
const last = history.findLast((item) => item.type === "user_message");
if (
candidates.length === 1 &&
only!.source === null &&
last &&
!last.clientMessageId &&
last.text.trim() === only!.text.trim()
)
submitted.add(only!.id);
return submitted;
}
@@ -0,0 +1,81 @@
import type { AgentAttachment, QueuedProviderSwitch } from "@getpaseo/protocol/messages";
import type { AgentPromptSource } from "./envelope.js";
/** Maximum number of persisted queued/dispatching messages allowed per recipient. */
export const MAX_AGENT_QUEUE_DEPTH = 100;
export type QueuedMessageState = "queued" | "dispatching";
export type QueuedMessageUrgency = "steer" | "interrupt";
export interface PersistedQueuedMessage {
id: string;
recipientId: string;
seq: number;
enqueuedAt: string;
text: string;
attachments: AgentAttachment[];
source: AgentPromptSource | null;
sessionMode?: string;
/** The recipient moves to this provider before the message runs there, alone. */
providerSwitch?: QueuedProviderSwitch;
unarchive: boolean;
clearPendingPermissions: boolean;
urgency: QueuedMessageUrgency | null;
held: boolean;
state: QueuedMessageState;
dispatchAttemptedAt?: string;
fingerprint?: string;
}
export type EnqueueStoreInput = Omit<
PersistedQueuedMessage,
"seq" | "state" | "dispatchAttemptedAt"
>;
export type EnqueueStoreResult =
| { status: "inserted"; record: PersistedQueuedMessage }
| { status: "duplicate"; record: PersistedQueuedMessage }
| { status: "conflict" }
| { status: "full"; limit: number };
export type PromoteStoreResult =
| {
status: "promoted";
/** Queued items in prefix `0..k` that were promoted, in ascending `seq` order. */
promoted: PersistedQueuedMessage[];
/** Full recipient queue after promotion, in ascending `seq` order. */
items: PersistedQueuedMessage[];
}
| { status: "not_found" }
| { status: "already_dispatching" };
export type WithdrawStoreResult =
| { status: "withdrawn"; item: PersistedQueuedMessage }
| { status: "not_found" }
| { status: "already_dispatching" };
/**
* Durable persistence boundary for per-recipient queued messages.
* Implementations serialize mutations per recipient and own sequence assignment,
* idempotency/conflict checks, capacity enforcement, and atomic state transitions.
*/
export interface AgentMessageQueueStore {
listAll(): Promise<PersistedQueuedMessage[]>;
listByRecipient(recipientId: string): Promise<PersistedQueuedMessage[]>;
enqueue(input: EnqueueStoreInput): Promise<EnqueueStoreResult>;
markDispatching(
recipientId: string,
ids: readonly string[],
attemptedAt: string,
): Promise<PersistedQueuedMessage[]>;
revertDispatching(recipientId: string, ids: readonly string[]): Promise<void>;
markHeld(recipientId: string): Promise<PersistedQueuedMessage[]>;
promote(
recipientId: string,
targetId: string,
urgency: QueuedMessageUrgency,
): Promise<PromoteStoreResult>;
withdraw(recipientId: string, id: string): Promise<WithdrawStoreResult>;
remove(recipientId: string, ids: readonly string[]): Promise<void>;
clearRecipient(recipientId: string): Promise<PersistedQueuedMessage[]>;
}
@@ -34,6 +34,9 @@ export class AgentTurnBusyError extends Error {}
/** The turn a steer targeted ended or changed before the provider took the steer. */
export class AgentTurnChangedError extends Error {}
/** The provider took a queued prompt and then refused to start a turn with it. */
export class AgentTurnStartRejectedError extends Error {}
export interface StartAgentRunOptions {
idleOnly?: boolean;
/** Skip plugin-reload lifecycle checks when caller already holds the agent lifecycle lock. */
@@ -338,6 +341,8 @@ export interface SendPromptToAgentParams {
/** A prompt that does not wait its turn. Messages queued for the agent go with it. */
export interface SendDirectPromptParams extends SendPromptToAgentParams {
agentMessages: Pick<AgentMessageDelivery, "sendDirect">;
/** Resumes a turn the daemon's restart cut off, so queued messages stay behind it. */
resumesTurn?: boolean;
}
export interface StartCreatedAgentInitialPromptParams {
@@ -399,6 +404,23 @@ export async function waitForAgentRunStartWithTimeout(
}
}
/**
* The start wait for a queued prompt. A refused start means the prompt was not delivered; a
* timed out one stays an abort, since the provider may still run it.
*/
export async function waitForQueuedRunStart(
agentManager: Pick<AgentManager, "getAgent">,
agentId: string,
started: Promise<void>,
): Promise<void> {
try {
await waitForAgentRunStartWithTimeout(agentManager, agentId, started);
} catch (error) {
if (!(error instanceof Error) || error.name === "AbortError") throw error;
throw new AgentTurnStartRejectedError(error.message, { cause: error });
}
}
function createStartAbortError(reason: unknown): Error {
let message = "wait_for_agent_start aborted";
if (typeof reason === "string") message = reason;
@@ -435,7 +457,7 @@ async function resolvePromptSource(
export async function sendPromptToAgent(
params: SendDirectPromptParams,
): Promise<PromptDispatchResult> {
const { agentMessages, source, messageId, ...send } = params;
const { agentMessages, source, messageId, resumesTurn, ...send } = params;
return agentMessages.sendDirect(
{
recipientId: params.agentId,
@@ -445,6 +467,7 @@ export async function sendPromptToAgent(
messageId,
sessionMode: params.sessionMode,
unarchive: params.unarchive,
resumesTurn,
},
(joined) =>
sendPreparedPromptToAgent({
@@ -117,12 +117,18 @@ export function createChangeRequestWatches(deps: Dependencies) {
windows.delete(url);
clearTimeout(window.timer);
for (const [recipientId, events] of window.recipients) {
deps.messages().enqueue({
recipientId,
source: { kind: "change-request-update", url },
prompt: [`Paseo change request update for ${url}`, ...events].join("\n"),
unarchive: false,
});
// Admission takes the digest's place in line now; the save is not awaited here.
void deps
.messages()
.enqueue({
recipientId,
source: { kind: "change-request-update", url },
text: [`Paseo change request update for ${url}`, ...events].join("\n"),
unarchive: false,
})
.catch((err) =>
deps.logger.warn({ err, url, recipientId }, "Could not enqueue change request update"),
);
}
}
@@ -4,7 +4,11 @@ import pino from "pino";
import { afterEach, expect, test, vi } from "vitest";
import { createChangeRequestWatches } from "./index.js";
import { AgentBackgroundWorkStore } from "../background-work/index.js";
import { createAgentMessageDelivery, parseAgentMessages } from "../agent-messages/index.js";
import {
createAgentMessageDelivery,
createMemoryAgentMessageQueueStore,
parseAgentMessages,
} from "../agent-messages/index.js";
import type { ChangeRequestRouter } from "../../../services/change-request-router.js";
import type {
ChangeRequestSnapshot,
@@ -47,6 +51,7 @@ function createHarness(
const listeners = new Set<(id: string) => void>();
const resolveCalls: string[] = [];
const messages = createAgentMessageDelivery({
store: createMemoryAgentMessageQueueStore(),
isRunning: (id) => busy.has(id),
subscribe(listener) {
listeners.add(listener);
@@ -189,10 +194,10 @@ test.each([false, true])(
await h.watches.start();
await h.watches.subscribe("parent", url);
h.busy.add("parent");
const report = h.messages.enqueue({
const report = await h.messages.enqueue({
recipientId: "parent",
source: { kind: "agent-message", agentId: "child" },
prompt: "Child report",
text: "Child report",
});
await h.observations.get(url)!.snapshot({
...initial,

Some files were not shown because too many files have changed in this diff Show More