Compare commits

...
Author SHA1 Message Date
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
108 changed files with 9331 additions and 3006 deletions
+77 -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,39 @@ that leaves the lifecycle at `error`, and replaces unread `finished` attention;
agent would show the green dot or none. Subagents track marks are the exception: they follow the
child's lifecycle, because the track is where a failed child stays visible.
## The queue track
The queue track is the list above the composer of the messages the host holds for the open agent
(`packages/app/src/composer/queue/`). One list covers every sender, in the order the host sends
them: your queued prompts, agent messages, finish notifications, and change-request updates.
The host owns the [queue](#relationships) and the app keeps no copy of it. `packages/app/src/agent-queue/`
reads the list on mount and after each reconnect, and replaces it on each `agent.queue.update`. A
queued message therefore survives a reload, is sent with every client closed, and shows on every
client that views the agent. Files upload to the host before the message is queued, so any device
can open a row's attachments.
Rows take these commands:
- **Send now** promotes the row with your send behavior setting: `steer`, otherwise `interrupt`.
- **Edit** is offered on your own messages only. It withdraws the row, then replaces the composer
draft with its text and attachments, and stages the row's provider switch again. If the host
already started sending the row, the draft stays as it is.
- **Cancel** withdraws the row.
A message you send directly (`steer` or `interrupt`) takes the queued rows with it, ahead of your
text.
A message sent mid-turn with a staged provider switch is queued whatever the send behavior, and its
row names the target.
A row the host is `dispatching` takes no command. A held queue shows a paused notice. The notice
does not name Stop, because a refused turn start holds the queue too.
A host without `server_info.features.agentMessageQueue` has no queue track. The composer offers no
Queue action there, and a `queue` send behavior sends as `steer`, so it does not cut the running
turn.
## The subagents track
The track is a pill at the foot of an agent's pane (`packages/app/src/subagents/track.tsx`): a count you can read at a glance, and a panel behind it — a popover on wide screens, a sheet on compact ones — holding the rows. It floats over the transcript rather than sitting in a band above the composer, so the timeline scrolls underneath it; `packages/app/src/panels/agent-tracks.tsx` owns that placement, and the pill frame is shared with the task list in `packages/app/src/composer/tracks.tsx`.
+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,288 @@
import { expect, test } from "../support/fixtures";
import { expectAgentIdle } from "../support/helpers/agent-stream";
import {
attachComposerTestImage,
cancelAgent,
composerLocator,
expectAttachmentPill,
expectComposerDraft,
expectComposerVisible,
fillComposerDraft,
sendDraftToQueue,
} from "../support/helpers/composer";
import {
cancelQueuedMessage,
editQueuedMessage,
expectDeliveredImage,
expectComposerOnScreen,
expectDeliveredOnce,
expectSenderIconUnsquashed,
openSecondClient,
queuedRow,
queuedRows,
queueMessage,
queuePausedNotice,
queueThroughHost,
reopenAgent,
scrollQueueFrom,
seedAgentWithOpenTurn,
sendQueuedMessageNow,
} from "../support/helpers/composer-queue";
import { openAgentRoute } from "../support/helpers/mock-agent";
test.describe("Composer queue", () => {
test("a queued image prompt can be edited, survives a reload, and is delivered once", async ({
page,
}) => {
const prompt = "Describe this screenshot.";
const revised = "Describe this screenshot in one line.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-edit-", title: "Queue edit" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await test.step("queue a prompt with an image", async () => {
await attachComposerTestImage(page);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await queueMessage(page, prompt);
await expect(queuedRow(page, prompt)).toContainText("1 attachment");
});
await test.step("Edit takes the text and image back into the composer", async () => {
await editQueuedMessage(page, prompt);
await expect(queuedRows(page)).toHaveCount(0);
await expectComposerDraft(page, prompt);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expect(composerLocator(page)).toBeFocused();
});
await test.step("queue the revised prompt with the same image", async () => {
await queueMessage(page, revised);
await expect(queuedRow(page, revised)).toContainText("1 attachment");
});
await test.step("the row is still there after a reload", async () => {
await page.reload();
await expect(queuedRow(page, revised)).toBeVisible({ timeout: 30_000 });
await expect(queuedRows(page)).toHaveCount(1);
});
await test.step("the prompt is delivered once when the turn ends", async () => {
await agent.finishTurn();
await expectDeliveredOnce(page, revised);
await expectDeliveredImage(page, revised);
await expect(queuedRows(page)).toHaveCount(0);
});
} finally {
await agent.cleanup();
}
});
test("Stop pauses the queue until the user sends a row", async ({ page }) => {
const prompt = "Run after I say so.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-held-", title: "Queue held" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueMessage(page, prompt);
await expect(queuePausedNotice(page)).toHaveCount(0);
await cancelAgent(page);
await expectAgentIdle(page);
await expect(queuePausedNotice(page)).toBeVisible();
await expect(queuedRow(page, prompt)).toBeVisible();
await sendQueuedMessageNow(page, prompt);
await expectDeliveredOnce(page, prompt);
await expect(queuePausedNotice(page)).toHaveCount(0);
} finally {
await agent.cleanup();
}
});
test("the host delivers a queued prompt with every client closed", async ({ page }) => {
const prompt = "Continue while I am away.";
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-closed-",
title: "Queue closed",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueMessage(page, prompt);
await page.close();
await agent.finishTurn();
await agent.client.waitForFinish(agent.agentId, 30_000);
const reopened = await reopenAgent(page, agent);
await expectDeliveredOnce(reopened, prompt);
await expect(queuedRows(reopened)).toHaveCount(0);
} finally {
await agent.cleanup();
}
});
test("two clients share one queue", async ({ browser, page }) => {
const unwanted = "Do not run this one.";
const urgent = "Run this one now.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-sync-", title: "Queue sync" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const second = await openSecondClient(browser, page, agent);
try {
await expectComposerVisible(second.page);
await test.step("a row queued on one client appears on the other", async () => {
await queueMessage(page, unwanted);
await expect(queuedRow(second.page, unwanted)).toBeVisible();
await fillComposerDraft(second.page, urgent);
await sendDraftToQueue(second.page);
await expect(queuedRows(page)).toContainText([unwanted, urgent]);
});
await test.step("Cancel on one client removes the row on the other", async () => {
await cancelQueuedMessage(second.page, unwanted);
await expect(queuedRow(page, unwanted)).toHaveCount(0);
});
await test.step("Send now on one client updates the other", async () => {
await sendQueuedMessageNow(page, urgent);
await expectDeliveredOnce(second.page, urgent);
await expect(
second.page.getByTestId("user-message").filter({ hasText: unwanted }),
).toHaveCount(0);
});
} finally {
await second.close();
}
} finally {
await agent.cleanup();
}
});
test("a long queue scrolls without pushing the composer off screen", async ({ page }) => {
const texts = Array.from({ length: 20 }, (_, index) => `Queued update ${index + 1}.`);
const first = "Queued update 1.";
const last = "Queued update 20.";
const agent = await seedAgentWithOpenTurn({ repoPrefix: "queue-long-", title: "Queue long" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await queueThroughHost(agent, texts);
await expect(queuedRows(page)).toHaveCount(20);
for (const viewport of [
{ width: 1280, height: 800 },
{ width: 390, height: 844 },
// A phone with its keyboard open.
{ width: 390, height: 500 },
]) {
await test.step(`${viewport.width}x${viewport.height}`, async () => {
await page.setViewportSize(viewport);
await expect(queuedRow(page, first)).toBeVisible();
await expectComposerOnScreen(page);
await scrollQueueFrom(page, first, 5000);
// Scrolled to the end, a fractional frame height can clip a sub-pixel of the row.
await expect(queuedRow(page, last)).toBeInViewport({ ratio: 0.99 });
await expectComposerOnScreen(page);
await scrollQueueFrom(page, last, -5000);
await expect(queuedRow(page, first)).toBeInViewport({ ratio: 1 });
});
}
} finally {
await agent.cleanup();
}
});
test("a message queued by another agent can be cancelled but not edited", async ({ page }) => {
const message = "The release notes are ready for review.";
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-sender-",
title: "Queue recipient",
});
try {
const sender = await agent.client.createAgent({
provider: "mock",
cwd: agent.cwd,
workspaceId: agent.workspaceId,
title: "Release coordination and changelog verification helper for the mobile team",
model: "e2e-fast-stream",
});
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await agent.client.sendAgentMessage(agent.agentId, message, {
sourceAgentId: sender.id,
activeTurnBehavior: "queue",
});
const row = queuedRow(page, message);
await expect(row).toContainText("Sent by Release coordination");
await expect(row.getByRole("button", { name: "Send queued message now" })).toBeEnabled();
await expect(row.getByRole("button", { name: "Cancel queued message" })).toBeEnabled();
await expect(row.getByRole("button", { name: "Edit queued message" })).toHaveCount(0);
await test.step("a long sender name truncates without squashing its icon", async () => {
await page.setViewportSize({ width: 390, height: 844 });
await expect(row).toBeInViewport();
await expectSenderIconUnsquashed(row);
});
await cancelQueuedMessage(page, message);
await expect(queuedRows(page)).toHaveCount(0);
} finally {
await agent.cleanup();
}
});
test("editing a queued image prompt on a short phone viewport keeps remaining queued rows visible", async ({
page,
}) => {
const withImage = "Describe this screenshot.";
const remaining = Array.from({ length: 4 }, (_, index) => `Remaining update ${index + 1}.`);
const agent = await seedAgentWithOpenTurn({
repoPrefix: "queue-compact-edit-",
title: "Queue compact edit",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await attachComposerTestImage(page);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await queueMessage(page, withImage);
await queueThroughHost(agent, remaining);
await expect(queuedRows(page)).toHaveCount(5);
await page.setViewportSize({ width: 390, height: 500 });
await editQueuedMessage(page, withImage);
await expectComposerDraft(page, withImage);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expect(composerLocator(page)).toBeInViewport({ ratio: 1 });
await expect(
page.getByRole("button", { name: "Send and steer", exact: true }),
).toBeInViewport({
ratio: 1,
});
// The queue scroll viewport must keep a readable slice (>= 90px) above the restored image pill,
// not collapse to a sliver inside a 0.6*viewport slot clamp.
const scrollFrameHeight = await page
.getByRole("list", { name: "Queued messages" })
.evaluate((list) => {
const scrollView = list.parentElement?.parentElement;
return scrollView ? scrollView.getBoundingClientRect().height : 0;
});
expect(scrollFrameHeight).toBeGreaterThanOrEqual(90);
} finally {
await agent.cleanup();
}
});
});
@@ -499,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;
+161
View File
@@ -0,0 +1,161 @@
import { expect, test } from "vitest";
import type { PaseoAgentQueueItem } from "@getpaseo/client";
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
import { createHostAgentQueueModel } from "./host";
interface Observer {
snapshot(): void;
update(message: SessionOutboundMessage): void;
error(error: unknown): void;
}
function item(id: string): PaseoAgentQueueItem {
return {
id,
seq: 1,
enqueuedAt: "2026-11-30T00:00:00.000Z",
text: `message ${id}`,
sender: { kind: "user" },
held: false,
state: "queued",
};
}
/** A host runtime plus the daemon client it hands out. */
function fakeHost(options: { supportsQueue: boolean }) {
let connected = false;
let notify = () => {};
const observers: Observer[] = [];
const calls: unknown[][] = [];
let releases = 0;
let queue = [item("a")];
const client = {
getLastServerInfoMessage: () =>
connected ? { features: { agentMessageQueue: options.supportsQueue } } : null,
listAgentQueue: async (agentId: string) => {
calls.push(["list", agentId]);
return { held: false, items: queue };
},
withdrawAgentQueueItem: async (agentId: string, messageId: string) => {
calls.push(["withdraw", agentId, messageId]);
return { withdrawn: true as const, item: item(messageId) };
},
promoteAgentQueueItem: async (agentId: string, messageId: string, behavior: string) => {
calls.push(["promote", agentId, messageId, behavior]);
return { promoted: true as const };
},
observeAgentQueue: () => ({
subscribe: (observer: Observer) => {
observers.push(observer);
},
release: async () => {
releases++;
},
}),
};
return {
host: {
getClient: () => client,
subscribe: (listener: () => void) => {
notify = listener;
return () => {};
},
},
observers,
calls,
releases: () => releases,
setQueue: (next: PaseoAgentQueueItem[]) => {
queue = next;
},
connect: () => {
connected = true;
notify();
},
disconnect: () => {
connected = false;
notify();
},
};
}
async function settle(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0));
}
function queueUpdate(agentId: string, items: PaseoAgentQueueItem[]): SessionOutboundMessage {
return { type: "agent.queue.update", payload: { agentId, held: false, items } };
}
test("lists on connect, follows its own agent's updates, and lists again on reconnect", async () => {
const runtime = fakeHost({ supportsQueue: true });
const model = createHostAgentQueueModel("host", "agent", runtime.host);
const unsubscribe = model.subscribe(() => {});
expect(runtime.observers).toHaveLength(0);
runtime.connect();
runtime.observers[0].snapshot();
await settle();
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [item("a")] });
runtime.observers[0].update(queueUpdate("other-agent", []));
expect(model.getSnapshot().items).toEqual([item("a")]);
runtime.observers[0].update(queueUpdate("agent", [item("a"), item("b")]));
expect(model.getSnapshot().items).toEqual([item("a"), item("b")]);
runtime.disconnect();
expect(model.getSnapshot()).toMatchObject({ status: "stale", items: [item("a"), item("b")] });
expect(runtime.releases()).toBe(1);
runtime.setQueue([]);
runtime.connect();
runtime.observers[1].snapshot();
await settle();
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
runtime.observers[0].update(queueUpdate("agent", [item("late")]));
expect(model.getSnapshot().items).toEqual([]);
unsubscribe();
});
test("sends withdraw and promote for the observed agent", async () => {
const runtime = fakeHost({ supportsQueue: true });
const model = createHostAgentQueueModel("host", "agent", runtime.host);
const unsubscribe = model.subscribe(() => {});
runtime.connect();
runtime.observers[0].update(queueUpdate("agent", [item("a"), item("b")]));
await model.promote("b", "interrupt");
await model.withdraw("a");
expect(runtime.calls).toEqual([
["promote", "agent", "b", "interrupt"],
["withdraw", "agent", "a"],
]);
unsubscribe();
});
test("rejects a command while the host is disconnected", async () => {
const runtime = fakeHost({ supportsQueue: true });
const model = createHostAgentQueueModel("host", "agent", runtime.host);
const unsubscribe = model.subscribe(() => {});
runtime.connect();
runtime.observers[0].update(queueUpdate("agent", [item("a")]));
runtime.disconnect();
await expect(model.withdraw("a")).rejects.toThrow("Host disconnected");
expect(runtime.calls).toEqual([]);
unsubscribe();
});
test("has no queue and asks nothing of a host without the feature", async () => {
const runtime = fakeHost({ supportsQueue: false });
const model = createHostAgentQueueModel("host", "agent", runtime.host);
const unsubscribe = model.subscribe(() => {});
runtime.connect();
await settle();
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
expect(runtime.observers).toHaveLength(0);
expect(runtime.calls).toEqual([]);
unsubscribe();
});
+118
View File
@@ -0,0 +1,118 @@
import type {
PaseoAgentQueuePromoteResult,
PaseoAgentQueueState,
PaseoAgentQueueWithdrawResult,
} from "@getpaseo/client";
import type { ActiveTurnBehavior, SessionOutboundMessage } from "@getpaseo/protocol/messages";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { createAgentQueueModel, type AgentQueueModel } from "./model";
interface AgentQueueClient {
getLastServerInfoMessage(): { features?: { agentMessageQueue?: boolean } | null } | null;
listAgentQueue(agentId: string): Promise<PaseoAgentQueueState>;
withdrawAgentQueueItem(
agentId: string,
messageId: string,
): Promise<PaseoAgentQueueWithdrawResult>;
promoteAgentQueueItem(
agentId: string,
messageId: string,
activeTurnBehavior: ActiveTurnBehavior,
): Promise<PaseoAgentQueuePromoteResult>;
observeAgentQueue(): {
subscribe(observer: {
snapshot(): void;
update(message: SessionOutboundMessage): void;
error(error: unknown): void;
}): unknown;
release(): Promise<void>;
};
}
interface AgentQueueHost {
getClient(): AgentQueueClient | null;
subscribe(listener: () => void): () => void;
}
function hostFor(serverId: string): AgentQueueHost {
const host = getHostRuntimeStore();
return {
getClient: () => host.getSnapshot(serverId)?.client ?? null,
subscribe: (listener) => host.subscribe(serverId, listener),
};
}
export function createHostAgentQueueModel(
serverId: string,
agentId: string,
host: AgentQueueHost = hostFor(serverId),
): AgentQueueModel {
let client: AgentQueueClient | null = null;
const connected = () => {
if (!client) throw new Error("Host disconnected");
return client;
};
return createAgentQueueModel({
list: async () => connected().listAgentQueue(agentId),
withdraw: async (messageId) => connected().withdrawAgentQueueItem(agentId, messageId),
promote: async (messageId, activeTurnBehavior) =>
connected().promoteAgentQueueItem(agentId, messageId, activeTurnBehavior),
observe: ({ snapshot, update, disconnected, failed }) => {
let release: (() => void) | undefined;
let currentObservation: ReturnType<AgentQueueClient["observeAgentQueue"]> | undefined;
const sync = () => {
const candidate = host.getClient();
// The runtime keeps the client across reconnects, but clears server info until handshake.
const next = candidate?.getLastServerInfoMessage() ? candidate : null;
if (next === client) return;
const previousRelease = release;
client = next;
release = undefined;
disconnected();
previousRelease?.();
if (!client) return;
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
if (client.getLastServerInfoMessage()?.features?.agentMessageQueue !== true) {
update({ held: false, items: [] });
return;
}
const observedClient = client;
const observation = client.observeAgentQueue();
currentObservation = observation;
const isCurrent = () => client === observedClient && currentObservation === observation;
observation.subscribe({
snapshot: () => {
if (isCurrent()) snapshot();
},
update: (message) => {
if (
isCurrent() &&
message.type === "agent.queue.update" &&
message.payload.agentId === agentId
) {
update({ held: message.payload.held, items: message.payload.items });
}
},
error: () => {
if (isCurrent()) failed();
},
});
release = () => {
if (currentObservation === observation) currentObservation = undefined;
void observation
.release()
.catch((error: unknown) =>
console.error("Agent queue subscription cleanup failed", error),
);
};
};
const unsubscribe = host.subscribe(sync);
sync();
return () => {
unsubscribe();
client = null;
release?.();
};
},
});
}
+15
View File
@@ -0,0 +1,15 @@
import { useMemo, useSyncExternalStore } from "react";
import { createHostAgentQueueModel } from "./host";
import type { AgentQueueModel, AgentQueueSnapshot } from "./model";
export type { AgentQueueModel, AgentQueueSnapshot } from "./model";
/** Observes one agent's queue for as long as the caller is mounted. */
export function useAgentQueue(
serverId: string,
agentId: string,
): { model: AgentQueueModel; queue: AgentQueueSnapshot } {
const model = useMemo(() => createHostAgentQueueModel(serverId, agentId), [serverId, agentId]);
const queue = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
return { model, queue };
}
+210
View File
@@ -0,0 +1,210 @@
import { expect, test } from "vitest";
import type {
PaseoAgentQueueItem,
PaseoAgentQueueState,
PaseoAgentQueueWithdrawResult,
} from "@getpaseo/client";
import { createAgentQueueModel, type AgentQueuePort } from "./model";
function item(id: string, patch: Partial<PaseoAgentQueueItem> = {}): PaseoAgentQueueItem {
return {
id,
seq: 1,
enqueuedAt: "2026-11-30T00:00:00.000Z",
text: `message ${id}`,
sender: { kind: "user" },
held: false,
state: "queued",
...patch,
};
}
interface Deferred<T> {
promise: Promise<T>;
resolve(value: T): void;
reject(error: Error): void;
}
function deferred<T>(): Deferred<T> {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((done, fail) => {
resolve = done;
reject = fail;
});
return { promise, resolve, reject };
}
/** A host queue the test drives: it records commands and answers them when told to. */
function fakeQueueHost() {
const lists: Deferred<PaseoAgentQueueState>[] = [];
const withdrawals: Array<{ messageId: string } & Deferred<PaseoAgentQueueWithdrawResult>> = [];
const promotions: Array<{ messageId: string; behavior: string }> = [];
let callbacks: Parameters<AgentQueuePort["observe"]>[0] | null = null;
const port: AgentQueuePort = {
list: () => {
const read = deferred<PaseoAgentQueueState>();
lists.push(read);
return read.promise;
},
withdraw: (messageId) => {
const request = deferred<PaseoAgentQueueWithdrawResult>();
withdrawals.push({ messageId, ...request });
return request.promise;
},
promote: async (messageId, behavior) => {
promotions.push({ messageId, behavior });
return { promoted: true };
},
observe: (next) => {
callbacks = next;
return () => {
callbacks = null;
};
},
};
return {
port,
lists,
withdrawals,
promotions,
isObserved: () => callbacks !== null,
connect: () => callbacks?.snapshot(),
disconnect: () => callbacks?.disconnected(),
fail: () => callbacks?.failed(),
publish: (queue: PaseoAgentQueueState) => callbacks?.update(queue),
};
}
async function settle(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0));
}
test("hydrates the queue the host holds when observation starts", async () => {
const host = fakeQueueHost();
const model = createAgentQueueModel(host.port);
const unsubscribe = model.subscribe(() => {});
expect(model.getSnapshot()).toMatchObject({ status: "loading", held: false, items: [] });
host.connect();
host.lists[0].resolve({ held: true, items: [item("a", { held: true })] });
await settle();
expect(model.getSnapshot()).toMatchObject({
status: "ready",
held: true,
items: [item("a", { held: true })],
});
unsubscribe();
expect(host.isObserved()).toBe(false);
});
test("replaces the whole queue with each live update, ahead of a slower list", async () => {
const host = fakeQueueHost();
const model = createAgentQueueModel(host.port);
const unsubscribe = model.subscribe(() => {});
host.connect();
host.publish({ held: false, items: [item("a"), item("b", { seq: 2 })] });
host.lists[0].resolve({ held: false, items: [] });
await settle();
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["a", "b"]);
host.publish({ held: false, items: [item("b", { seq: 2 })] });
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["b"]);
unsubscribe();
});
test("keeps the last rows while disconnected and reads the queue again on reconnect", async () => {
const host = fakeQueueHost();
const model = createAgentQueueModel(host.port);
const unsubscribe = model.subscribe(() => {});
host.connect();
host.lists[0].resolve({ held: false, items: [item("a")] });
await settle();
host.disconnect();
expect(model.getSnapshot()).toMatchObject({ status: "stale", items: [item("a")] });
host.connect();
host.lists[1].resolve({ held: false, items: [] });
await settle();
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [] });
unsubscribe();
});
test("offers a retry when the queue cannot be read", async () => {
const host = fakeQueueHost();
const model = createAgentQueueModel(host.port);
const unsubscribe = model.subscribe(() => {});
host.connect();
host.lists[0].reject(new Error("timeout"));
await settle();
expect(model.getSnapshot().status).toBe("error");
model.retry();
host.lists[1].resolve({ held: false, items: [item("a")] });
await settle();
expect(model.getSnapshot()).toMatchObject({ status: "ready", items: [item("a")] });
unsubscribe();
});
test("marks a row busy while it is withdrawn and returns the withdrawn message", async () => {
const host = fakeQueueHost();
const model = createAgentQueueModel(host.port);
const unsubscribe = model.subscribe(() => {});
host.publish({ held: false, items: [item("a"), item("b", { seq: 2 })] });
const first = model.withdraw("a");
const second = model.withdraw("a");
expect(model.getSnapshot().busy).toEqual(new Set(["a"]));
host.withdrawals[0].resolve({ withdrawn: true, item: item("a") });
expect(await first).toEqual({ withdrawn: true, item: item("a") });
expect(await second).toBeNull();
expect(host.withdrawals).toHaveLength(1);
expect(model.getSnapshot().busy).toEqual(new Set());
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["b"]);
unsubscribe();
});
test("keeps the row when the host already started sending it", async () => {
const host = fakeQueueHost();
const model = createAgentQueueModel(host.port);
const unsubscribe = model.subscribe(() => {});
host.publish({ held: false, items: [item("a")] });
const result = model.withdraw("a");
host.withdrawals[0].resolve({ withdrawn: false, reason: "already_dispatching" });
expect(await result).toEqual({ withdrawn: false, reason: "already_dispatching" });
expect(model.getSnapshot().items.map((entry) => entry.id)).toEqual(["a"]);
expect(model.getSnapshot().busy).toEqual(new Set());
unsubscribe();
});
test("releases the row and reports the error when a command fails", async () => {
const host = fakeQueueHost();
const model = createAgentQueueModel(host.port);
const unsubscribe = model.subscribe(() => {});
host.publish({ held: false, items: [item("a")] });
const result = model.withdraw("a");
host.withdrawals[0].reject(new Error("Host disconnected"));
await expect(result).rejects.toThrow("Host disconnected");
expect(model.getSnapshot().busy).toEqual(new Set());
unsubscribe();
});
test("promotes a row with the chosen send behavior", async () => {
const host = fakeQueueHost();
const model = createAgentQueueModel(host.port);
const unsubscribe = model.subscribe(() => {});
host.publish({ held: true, items: [item("a", { held: true })] });
expect(await model.promote("a", "steer")).toEqual({ promoted: true });
expect(host.promotions).toEqual([{ messageId: "a", behavior: "steer" }]);
unsubscribe();
});
+145
View File
@@ -0,0 +1,145 @@
import type {
PaseoAgentQueueItem,
PaseoAgentQueuePromoteResult,
PaseoAgentQueueState,
PaseoAgentQueueWithdrawResult,
} from "@getpaseo/client";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
export interface AgentQueuePort {
list(): Promise<PaseoAgentQueueState>;
withdraw(messageId: string): Promise<PaseoAgentQueueWithdrawResult>;
promote(
messageId: string,
activeTurnBehavior: ActiveTurnBehavior,
): Promise<PaseoAgentQueuePromoteResult>;
observe(callbacks: {
snapshot(): void;
disconnected(): void;
failed(): void;
update(queue: PaseoAgentQueueState): void;
}): () => void;
}
export interface AgentQueueSnapshot {
status: "loading" | "stale" | "ready" | "error";
/** The host waits for Send now or the next prompt before it sends these. */
held: boolean;
/** Admission order. The first row is sent next. */
items: PaseoAgentQueueItem[];
/** Rows with a command in flight. */
busy: ReadonlySet<string>;
}
/**
* One agent's queue as the host holds it. The host is the only writer: every update replaces
* the rows, and a command changes nothing here until the host answers it.
*/
export function createAgentQueueModel(port: AgentQueuePort) {
let state: AgentQueueSnapshot = {
status: "loading",
held: false,
items: [],
busy: new Set(),
};
let hasRead = false;
let sequence = 0;
let stop: (() => void) | undefined;
let observationFailed = false;
const listeners = new Set<() => void>();
const publish = (patch: Partial<AgentQueueSnapshot>) => {
state = { ...state, ...patch };
for (const listener of listeners) listener();
};
const replace = (queue: PaseoAgentQueueState) => {
hasRead = true;
publish({ status: "ready", held: queue.held, items: queue.items });
};
const pending = () => (hasRead ? "stale" : "loading");
const refresh = async () => {
const request = ++sequence;
publish({ status: pending() });
try {
const queue = await port.list();
if (request === sequence) replace(queue);
} catch {
if (request === sequence) publish({ status: "error" });
}
};
const start = () => {
observationFailed = false;
stop = port.observe({
snapshot: () => {
void refresh();
},
disconnected: () => {
sequence++;
publish({ status: pending() });
},
failed: () => {
observationFailed = true;
sequence++;
publish({ status: "error" });
},
update: (queue) => {
sequence++;
replace(queue);
},
});
};
/** Runs one command per row at a time. Returns null when the row cannot take one. */
const command = async <T>(messageId: string, run: () => Promise<T>): Promise<T | null> => {
const row = state.items.find((entry) => entry.id === messageId);
if (!row || row.state === "dispatching" || state.busy.has(messageId)) return null;
publish({ busy: new Set(state.busy).add(messageId) });
try {
return await run();
} finally {
const busy = new Set(state.busy);
busy.delete(messageId);
publish({ busy });
}
};
return {
getSnapshot: () => state,
withdraw: (messageId: string) =>
command(messageId, async () => {
const result = await port.withdraw(messageId);
// The host confirmed the removal. Drop the row now so it is not pressable again
// between this answer and the next update.
if (result.withdrawn) {
publish({ items: state.items.filter((entry) => entry.id !== messageId) });
}
return result;
}),
promote: (messageId: string, activeTurnBehavior: ActiveTurnBehavior) =>
command(messageId, () => port.promote(messageId, activeTurnBehavior)),
retry: () => {
if (observationFailed) {
stop?.();
stop = undefined;
publish({ status: pending() });
start();
} else {
void refresh();
}
},
subscribe(listener: () => void) {
listeners.add(listener);
if (!stop) start();
return () => {
listeners.delete(listener);
if (!listeners.size) {
sequence++;
stop?.();
stop = undefined;
}
};
},
};
}
export type AgentQueueModel = ReturnType<typeof createAgentQueueModel>;
+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,148 @@
import type { PaseoAgentQueueItem, PaseoAgentQueueWithdrawResult } from "@getpaseo/client";
import { describe, expect, it } from "vitest";
import { createAgentQueueModel, type AgentQueuePort } from "@/agent-queue/model";
import { cancelQueuedMessage, editQueuedMessage, sendQueuedMessageNow } from "./actions";
const upload = {
type: "uploaded_file" as const,
id: "upload-1",
fileName: "photo.png",
mimeType: "image/png",
size: 1,
path: "/tmp/photo.png",
role: "image" as const,
};
const queued: PaseoAgentQueueItem = {
id: "a",
seq: 1,
enqueuedAt: "2026-11-30T00:00:00.000Z",
text: "look at this",
attachments: [upload],
sender: { kind: "user" },
held: false,
state: "queued",
};
/** A real queue model over a host that already holds one message. */
async function queueHolding(withdraw: PaseoAgentQueueWithdrawResult) {
const promoted: string[] = [];
const port: AgentQueuePort = {
list: async () => ({ held: false, items: [queued] }),
withdraw: async () => withdraw,
promote: async (messageId, behavior) => {
promoted.push(`${messageId}:${behavior}`);
return { promoted: true };
},
observe: ({ update }) => {
update({ held: false, items: [queued] });
return () => {};
},
};
const model = createAgentQueueModel(port);
model.subscribe(() => {});
const restored: Array<{ text: string; attachments: unknown[] }> = [];
let alreadySending = 0;
return {
model,
promoted,
restored,
alreadySendingCount: () => alreadySending,
composer: {
restore: (message: { text: string; attachments: unknown[] }) => restored.push(message),
alreadySending: () => {
alreadySending += 1;
},
},
};
}
const withdrawn: PaseoAgentQueueWithdrawResult = { withdrawn: true, item: queued };
const dispatching: PaseoAgentQueueWithdrawResult = {
withdrawn: false,
reason: "already_dispatching",
};
describe("editQueuedMessage", () => {
it("puts the withdrawn text and attachments back in the composer", async () => {
const queue = await queueHolding(withdrawn);
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
expect(queue.restored).toEqual([
{
text: "look at this",
attachments: [{ kind: "agent_attachment", attachment: upload }],
providerSwitch: null,
},
]);
expect(queue.alreadySendingCount()).toBe(0);
expect(queue.model.getSnapshot().items).toEqual([]);
});
it("gives back the provider switch the message was queued with", async () => {
const queue = await queueHolding({
withdrawn: true,
item: { ...queued, providerSwitch: { provider: "codex", model: "gpt-5.4" } },
});
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
expect(queue.restored).toMatchObject([
{
providerSwitch: {
provider: "codex",
model: "gpt-5.4",
modeId: null,
thinkingOptionId: null,
providerOptions: {},
},
},
]);
});
it("leaves the composer alone when the message already started sending", async () => {
const queue = await queueHolding(dispatching);
await editQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
expect(queue.restored).toEqual([]);
expect(queue.alreadySendingCount()).toBe(1);
});
});
describe("cancelQueuedMessage", () => {
it("withdraws the message without touching the composer", async () => {
const queue = await queueHolding(withdrawn);
await cancelQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
expect(queue.model.getSnapshot().items).toEqual([]);
expect(queue.restored).toEqual([]);
expect(queue.alreadySendingCount()).toBe(0);
});
it("says so when the message already started sending", async () => {
const queue = await queueHolding(dispatching);
await cancelQueuedMessage({ model: queue.model, messageId: "a", ...queue.composer });
expect(queue.alreadySendingCount()).toBe(1);
});
});
describe("sendQueuedMessageNow", () => {
it.each([
["steer", "a:steer"],
["interrupt", "a:interrupt"],
["queue", "a:interrupt"],
] as const)("with the %s send behavior promotes as %s", async (sendBehavior, expected) => {
const queue = await queueHolding(withdrawn);
await sendQueuedMessageNow({ model: queue.model, messageId: "a", sendBehavior });
expect(queue.promoted).toEqual([expected]);
});
});
@@ -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: 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) => {
+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",
+106 -2
View File
@@ -44,6 +44,7 @@ import type {
RestartRequestedStatusPayloadSchema,
ShutdownRequestedStatusPayloadSchema,
DaemonUpdateResponseSchema,
ActiveTurnBehavior,
AgentActiveTurnBehavior,
ServerInfoStatusPayload,
TerminalDefaultColors,
@@ -510,6 +511,7 @@ export interface AgentMessageReceipt {
deliveryStatus?: "queued";
activeTurnBehavior?: AgentActiveTurnBehavior;
guidance?: string;
messageId?: string;
}
export interface SendMessageOptions {
@@ -536,6 +538,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 +1149,20 @@ type CorrelatedResponsePayload<TType extends CorrelatedResponseType> =
export type AgentBackgroundWorkListPayload =
CorrelatedResponsePayload<"agent.background_work.list.response">;
export type AgentBackgroundWorkItem = AgentBackgroundWorkListPayload["items"][number];
export type AgentQueueListPayload = CorrelatedResponsePayload<"agent.queue.list.response">;
export type AgentQueueItem = AgentQueueListPayload["items"][number];
export interface AgentQueueListResult {
held: boolean;
items: AgentQueueItem[];
}
export type AgentQueueWithdrawPayload = CorrelatedResponsePayload<"agent.queue.withdraw.response">;
export type AgentQueueWithdrawResult =
| { withdrawn: true; item: AgentQueueItem }
| { withdrawn: false; reason: "not_found" | "already_dispatching" };
export type AgentQueuePromotePayload = CorrelatedResponsePayload<"agent.queue.promote.response">;
export type AgentQueuePromoteResult =
| { promoted: true }
| { promoted: false; reason: "not_found" | "already_dispatching" };
type PluginCatalogResponseEntry =
CorrelatedResponsePayload<"plugin.catalog.get.response">["plugins"][number];
@@ -4243,6 +4267,79 @@ export class DaemonClientCore {
}
}
async listAgentQueue(
agentId: string,
options: { requestId?: string; timeout?: number } = {},
): Promise<AgentQueueListResult> {
this.assertAgentMessageQueueSupported();
const payload = await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.list.response">({
requestId: options.requestId,
timeout: options.timeout,
message: { type: "agent.queue.list.request", agentId },
});
if (payload.error) throw new Error(payload.error);
return { held: payload.held, items: payload.items };
}
async withdrawAgentQueueItem(
agentId: string,
messageId: string,
options: { requestId?: string; timeout?: number } = {},
): Promise<AgentQueueWithdrawResult> {
this.assertAgentMessageQueueSupported();
const payload =
await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.withdraw.response">({
requestId: options.requestId,
timeout: options.timeout,
message: { type: "agent.queue.withdraw.request", agentId, messageId },
});
if (payload.error) throw new Error(payload.error);
if (payload.withdrawn) {
if (!payload.item) throw new Error("Missing withdrawn queue item.");
return { withdrawn: true, item: payload.item };
}
if (!payload.reason) throw new Error("Missing queue withdraw failure reason.");
return { withdrawn: false, reason: payload.reason };
}
async promoteAgentQueueItem(
agentId: string,
messageId: string,
activeTurnBehavior: ActiveTurnBehavior,
options: { requestId?: string; timeout?: number } = {},
): Promise<AgentQueuePromoteResult> {
this.assertAgentMessageQueueSupported();
const payload =
await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.promote.response">({
requestId: options.requestId,
timeout: options.timeout,
message: {
type: "agent.queue.promote.request",
agentId,
messageId,
activeTurnBehavior,
},
});
if (payload.error) throw new Error(payload.error);
if (payload.promoted) return { promoted: true };
if (!payload.reason) throw new Error("Missing queue promote failure reason.");
return { promoted: false, reason: payload.reason };
}
observeAgentQueue(
options: { signal?: AbortSignal } = {},
): OwnedSubscription<CorrelatedResponsePayload<"session.events.set_subscription.response">> {
this.assertAgentMessageQueueSupported();
return this.observeEvents(["agent.queue.update"], options);
}
private assertAgentMessageQueueSupported(): void {
// COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01.
if (this.lastServerInfoMessage?.features?.agentMessageQueue !== true) {
throw new Error("Update the host to view or manage an agent's message queue.");
}
}
async fetchProviderSubagentTimeline(
parentAgentId: string,
subagentId: string,
@@ -4405,16 +4502,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 +4534,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 +4556,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. */
+197
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,198 @@ describe("findWorkspace", () => {
await expect(finding).resolves.toMatchObject({ id: targetId });
});
});
describe("agent queue RPCs and observation", () => {
const QUEUED_ITEM = {
id: "msg-1",
seq: 1,
enqueuedAt: "2026-11-30T08:00:00.000Z",
text: "Check tests",
sender: { kind: "user" as const },
held: false,
state: "queued" as const,
};
async function connectQueueClient(features: Record<string, boolean>) {
const transport = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "queue-client",
transportFactory: () => transport.transport,
reconnect: { enabled: false },
});
clients.push(client);
const connecting = client.connect();
transport.triggerOpen({ features });
await connecting;
return { client, transport };
}
test("gates queue methods when host lacks agentMessageQueue", async () => {
const { client, transport } = await connectQueueClient({ ownedSubscriptions: true });
await expect(client.listAgentQueue("agent-a")).rejects.toThrow("Update the host");
await expect(client.withdrawAgentQueueItem("agent-a", "msg-1")).rejects.toThrow(
"Update the host",
);
await expect(client.promoteAgentQueueItem("agent-a", "msg-1", "steer")).rejects.toThrow(
"Update the host",
);
expect(() => client.observeAgentQueue()).toThrow("Update the host");
expect(transport.sent).toHaveLength(0);
});
test("lists, withdraws, promotes, and observes agent queue", async () => {
const { client, transport } = await connectQueueClient({
ownedSubscriptions: true,
agentMessageQueue: true,
});
const listPromise = client.listAgentQueue("agent-a");
const listReq = parseSentFrame(transport.sent.at(-1));
expect(listReq).toMatchObject({ type: "agent.queue.list.request", agentId: "agent-a" });
transport.triggerMessage(
wrapSessionMessage({
type: "agent.queue.list.response",
payload: {
requestId: listReq.requestId,
agentId: "agent-a",
held: true,
items: [QUEUED_ITEM],
error: null,
},
}),
);
await expect(listPromise).resolves.toEqual({ held: true, items: [QUEUED_ITEM] });
const withdrawOk = client.withdrawAgentQueueItem("agent-a", "msg-1");
const withdrawReq1 = parseSentFrame(transport.sent.at(-1));
expect(withdrawReq1).toMatchObject({
type: "agent.queue.withdraw.request",
agentId: "agent-a",
messageId: "msg-1",
});
transport.triggerMessage(
wrapSessionMessage({
type: "agent.queue.withdraw.response",
payload: {
requestId: withdrawReq1.requestId,
agentId: "agent-a",
messageId: "msg-1",
withdrawn: true,
item: QUEUED_ITEM,
reason: null,
error: null,
},
}),
);
await expect(withdrawOk).resolves.toEqual({ withdrawn: true, item: QUEUED_ITEM });
const withdrawMiss = client.withdrawAgentQueueItem("agent-a", "msg-2");
const withdrawReq2 = parseSentFrame(transport.sent.at(-1));
transport.triggerMessage(
wrapSessionMessage({
type: "agent.queue.withdraw.response",
payload: {
requestId: withdrawReq2.requestId,
agentId: "agent-a",
messageId: "msg-2",
withdrawn: false,
item: null,
reason: "already_dispatching",
error: null,
},
}),
);
await expect(withdrawMiss).resolves.toEqual({
withdrawn: false,
reason: "already_dispatching",
});
const promoteOk = client.promoteAgentQueueItem("agent-a", "msg-1", "interrupt");
const promoteReq1 = parseSentFrame(transport.sent.at(-1));
expect(promoteReq1).toMatchObject({
type: "agent.queue.promote.request",
agentId: "agent-a",
messageId: "msg-1",
activeTurnBehavior: "interrupt",
});
transport.triggerMessage(
wrapSessionMessage({
type: "agent.queue.promote.response",
payload: {
requestId: promoteReq1.requestId,
agentId: "agent-a",
messageId: "msg-1",
promoted: true,
reason: null,
error: null,
},
}),
);
await expect(promoteOk).resolves.toEqual({ promoted: true });
const promoteMiss = client.promoteAgentQueueItem("agent-a", "msg-9", "steer");
const promoteReq2 = parseSentFrame(transport.sent.at(-1));
transport.triggerMessage(
wrapSessionMessage({
type: "agent.queue.promote.response",
payload: {
requestId: promoteReq2.requestId,
agentId: "agent-a",
messageId: "msg-9",
promoted: false,
reason: "not_found",
error: null,
},
}),
);
await expect(promoteMiss).resolves.toEqual({ promoted: false, reason: "not_found" });
const updates: unknown[] = [];
const observation = client.observeAgentQueue();
observation.subscribe({
snapshot: () => {},
update: (message) => updates.push(message),
error: () => {},
});
const subReq = parseSentFrame(transport.sent.at(-1));
expect(subReq).toMatchObject({
type: "session.events.set_subscription.request",
events: ["agent.queue.update"],
});
transport.triggerMessage(
wrapSessionMessage({
type: "session.events.set_subscription.response",
payload: { requestId: subReq.requestId, subscriptionId: "sub-q" },
}),
);
transport.triggerMessage(
wrapSessionMessage({
type: "agent.queue.update",
payload: {
subscriptionId: "sub-q",
agentId: "agent-a",
held: false,
items: [QUEUED_ITEM],
},
}),
);
await vi.waitFor(() => expect(updates).toHaveLength(1));
expect(updates[0]).toMatchObject({
type: "agent.queue.update",
payload: { agentId: "agent-a", held: false, items: [QUEUED_ITEM] },
});
const releasing = observation.release();
await vi.waitFor(() =>
expect(parseSentFrame(transport.sent.at(-1)).type).toBe("subscription.release.request"),
);
const releaseReq = parseSentFrame(transport.sent.at(-1));
transport.triggerMessage(
wrapSessionMessage({
type: "subscription.release.response",
payload: { requestId: releaseReq.requestId, subscriptionId: "sub-q" },
}),
);
await releasing;
});
});
+187
View File
@@ -2196,3 +2196,190 @@ test("background stop rejects when the host does not advertise the operation", a
).rejects.toThrow("Update the host");
await client.close();
});
const AGENT_QUEUE_FEATURES = { ownedSubscriptions: true, agentMessageQueue: true };
const QUEUED_ITEM = {
id: "msg-1",
seq: 1,
enqueuedAt: "2026-11-30T08:00:00.000Z",
text: "Check logs",
sender: { kind: "user" as const },
held: false,
state: "queued" as const,
};
function answerQueueList(ws: FakeWebSocket, held: boolean, items: unknown[]): void {
const request = parseSentSessionMessage(ws.sent.at(-1));
expect(request).toMatchObject({ type: "agent.queue.list.request", agentId: "agent-a" });
ws.message(
sessionMessage({
type: "agent.queue.list.response",
payload: { requestId: request.requestId, agentId: "agent-a", held, items, error: null },
}),
);
}
test("agent handles list, withdraw, and promote queue items", async () => {
const { client, ws } = await connectClient(AGENT_QUEUE_FEATURES);
const queue = client.agents.ref("agent-a").queue;
const listed = queue.list();
answerQueueList(ws, true, [QUEUED_ITEM]);
await expect(listed).resolves.toEqual({ held: true, items: [QUEUED_ITEM] });
const withdrawn = queue.withdraw("msg-1");
const withdrawReq = parseSentSessionMessage(ws.sent.at(-1));
expect(withdrawReq).toMatchObject({
type: "agent.queue.withdraw.request",
agentId: "agent-a",
messageId: "msg-1",
});
ws.message(
sessionMessage({
type: "agent.queue.withdraw.response",
payload: {
requestId: withdrawReq.requestId,
agentId: "agent-a",
messageId: "msg-1",
withdrawn: true,
item: QUEUED_ITEM,
reason: null,
error: null,
},
}),
);
await expect(withdrawn).resolves.toEqual({ withdrawn: true, item: QUEUED_ITEM });
const promoted = queue.promote("msg-1", "steer");
const promoteReq = parseSentSessionMessage(ws.sent.at(-1));
expect(promoteReq).toMatchObject({
type: "agent.queue.promote.request",
agentId: "agent-a",
messageId: "msg-1",
activeTurnBehavior: "steer",
});
ws.message(
sessionMessage({
type: "agent.queue.promote.response",
payload: {
requestId: promoteReq.requestId,
agentId: "agent-a",
messageId: "msg-1",
promoted: false,
reason: "already_dispatching",
error: null,
},
}),
);
await expect(promoted).resolves.toEqual({ promoted: false, reason: "already_dispatching" });
await client.close();
});
test("agent queue subscriptions filter by agentId, re-list on reconnect, and keep overtaking updates", async () => {
const { client, ws } = await connectClient(AGENT_QUEUE_FEATURES);
const received: unknown[] = [];
const unsubscribe = client.agents.ref("agent-a").queue.subscribe((state) => received.push(state));
expect(parseSentSessionMessage(ws.sent.at(-1))).toMatchObject({
type: "session.events.set_subscription.request",
events: ["agent.queue.update"],
});
acknowledgeObservation(ws, "queue-sdk");
await vi.waitFor(() =>
expect(parseSentSessionMessage(ws.sent.at(-1))).toMatchObject({
type: "agent.queue.list.request",
agentId: "agent-a",
}),
);
const listReq = parseSentSessionMessage(ws.sent.at(-1));
// An update overtakes the initial list response: the stale list is ignored.
ws.message(
sessionMessage({
type: "agent.queue.update",
payload: { subscriptionId: "queue-sdk", agentId: "agent-a", held: true, items: [] },
}),
);
ws.message(
sessionMessage({
type: "agent.queue.list.response",
payload: {
requestId: listReq.requestId,
agentId: "agent-a",
held: false,
items: [QUEUED_ITEM],
error: null,
},
}),
);
await vi.waitFor(() => expect(received).toEqual([{ held: true, items: [] }]));
// Other agent updates are ignored.
ws.message(
sessionMessage({
type: "agent.queue.update",
payload: {
subscriptionId: "queue-sdk",
agentId: "agent-b",
held: false,
items: [QUEUED_ITEM],
},
}),
);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(received).toEqual([{ held: true, items: [] }]);
// Reconnect re-subscribes and re-lists.
ws.readyState = 3;
ws.onclose?.({ code: 1006, reason: "Connection lost" });
const reconnecting = client.connect();
const next = FakeWebSocket.instances[1];
next.open();
next.message(
sessionMessage({
type: "status",
payload: {
status: "server_info",
serverId: "srv_sdk_test",
hostname: null,
version: null,
features: AGENT_QUEUE_FEATURES,
},
}),
);
await reconnecting;
await vi.waitFor(() =>
expect(parseSentSessionMessage(next.sent.at(-1))).toMatchObject({
type: "session.events.set_subscription.request",
}),
);
acknowledgeObservation(next, "queue-sdk-2");
answerQueueList(next, false, [QUEUED_ITEM]);
await vi.waitFor(() =>
expect(received).toEqual([
{ held: true, items: [] },
{ held: false, items: [QUEUED_ITEM] },
]),
);
unsubscribe();
next.message(
sessionMessage({
type: "agent.queue.update",
payload: { subscriptionId: "queue-sdk-2", agentId: "agent-a", held: false, items: [] },
}),
);
expect(received).toHaveLength(2);
await client.close();
});
test("agent queue asks for a host update when the daemon lacks agentMessageQueue", async () => {
const { client } = await connectClient({ ownedSubscriptions: true });
const handle = client.agents.ref("agent-a");
await expect(handle.queue.list()).rejects.toThrow("Update the host");
await expect(handle.queue.withdraw("msg-1")).rejects.toThrow("Update the host");
await expect(handle.queue.promote("msg-1", "steer")).rejects.toThrow("Update the host");
expect(() => handle.queue.subscribe(() => {})).toThrow("Update the host");
await client.close();
});
+106 -38
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,
@@ -58,6 +59,10 @@ export type {
import type { PluginTimelineItem } from "@getpaseo/protocol/agent-types";
import type {
AgentBackgroundWorkItem,
AgentQueueItem,
AgentQueueListResult,
AgentQueuePromoteResult,
AgentQueueWithdrawResult,
FetchAgentsEntry,
FetchAgentsOptions,
FetchAgentsPageInfo,
@@ -414,6 +419,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 +477,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 +746,7 @@ export function createPaseoApi(
listenAgents,
(agentId, handler) => own(() => daemonClient.subscribeAgentTimeline(agentId, handler)),
() => own(() => daemonClient.observeAgentBackgroundWork()),
() => own(() => daemonClient.observeAgentQueue()),
);
const createAgent = async (
options: PaseoAgentCreateOptions,
@@ -1009,11 +1043,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"]>,
observeAgentQueue: () => ReturnType<DaemonClient["observeAgentQueue"]>,
): AgentHandleFactory {
return (agent) => {
const id = typeof agent === "string" ? agent : agent.id;
@@ -1073,44 +1150,35 @@ function createAgentHandleFactory(
backgroundWork: {
stop: (item, options) => daemonClient.stopAgentBackgroundWork(id, item, options),
list: (options) => daemonClient.listAgentBackgroundWork(id, 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);
};
observation.subscribe({
error: reportError,
snapshot: () => {
const listed = ++sequence;
void daemonClient
.listAgentBackgroundWork(id)
.then((items) => {
if (!released && listed === sequence) listener(items);
return undefined;
})
.catch(reportError);
},
update: (message) => {
if (message.type !== "agent.background_work.update") return;
if (message.payload.agentId !== id) return;
sequence++;
listener(message.payload.items);
},
});
return () => {
released = true;
void observation
.release()
.catch((error) =>
console.error("Background work subscription cleanup failed", error),
);
};
},
subscribe: (listener, options) =>
subscribeAgentObservation(
observeBackgroundWork,
() => daemonClient.listAgentBackgroundWork(id),
(message) =>
message.type === "agent.background_work.update" && message.payload.agentId === id
? message.payload.items
: null,
listener,
{ onError: options?.onError, label: "Background work" },
),
},
queue: {
list: (options) => daemonClient.listAgentQueue(id, options),
withdraw: (messageId, options) =>
daemonClient.withdrawAgentQueueItem(id, messageId, options),
promote: (messageId, activeTurnBehavior, options) =>
daemonClient.promoteAgentQueueItem(id, messageId, activeTurnBehavior, options),
subscribe: (listener, options) =>
subscribeAgentObservation(
observeAgentQueue,
() => daemonClient.listAgentQueue(id),
(message) =>
message.type === "agent.queue.update" && message.payload.agentId === id
? { held: message.payload.held, items: message.payload.items }
: null,
listener,
{ onError: options?.onError, label: "Agent queue" },
),
},
get workspaceId() {
return current?.workspaceId ?? null;
@@ -0,0 +1,210 @@
import { describe, expect, test } from "vitest";
import {
QueuedAgentMessagePayloadSchema,
QueuedMessageSenderSchema,
SendAgentMessageResponseMessageSchema,
ServerInfoStatusPayloadSchema,
SessionEventSubscriptionSchema,
SessionInboundMessageSchema,
SessionOutboundMessageSchema,
} from "./messages.js";
const USER_ITEM = {
id: "msg-1",
seq: 1,
enqueuedAt: "2026-11-30T08:00:00.000Z",
text: "Follow up on the build",
sender: { kind: "user" as const },
held: false,
state: "queued" as const,
};
const AGENT_ITEM = {
id: "msg-2",
seq: 2,
enqueuedAt: "2026-11-30T08:00:01.000Z",
text: "Worker finished",
attachments: [
{
type: "uploaded_file" as const,
id: "up-1",
fileName: "shot.png",
mimeType: "image/png",
size: 123,
path: "/tmp/uploads/up-1/shot.png",
role: "image" as const,
},
],
sender: {
kind: "agent_message" as const,
agentId: "agent-worker",
serverId: "server-1",
title: "Worker",
},
held: true,
state: "dispatching" as const,
};
describe("agent message queue protocol", () => {
test("parses all queued message sender variants and payloads", () => {
for (const sender of [
{ kind: "user" },
{ kind: "agent_message", agentId: "agent-1", serverId: "srv-1", title: "Worker" },
{ kind: "agent_notification", agentId: "agent-2", event: "finished" },
{ kind: "change_request_update", url: "https://github.com/org/repo/pull/42" },
]) {
expect(QueuedMessageSenderSchema.parse(sender)).toEqual(sender);
}
expect(QueuedAgentMessagePayloadSchema.parse(USER_ITEM)).toEqual(USER_ITEM);
expect(QueuedAgentMessagePayloadSchema.parse(AGENT_ITEM)).toEqual(AGENT_ITEM);
});
test("accepts queue list, withdraw, and promote requests and responses", () => {
expect(
SessionInboundMessageSchema.parse({
type: "agent.queue.list.request",
agentId: "agent-1",
requestId: "req-list",
}),
).toMatchObject({ agentId: "agent-1", requestId: "req-list" });
expect(
SessionOutboundMessageSchema.parse({
type: "agent.queue.list.response",
payload: {
requestId: "req-list",
agentId: "agent-1",
held: false,
items: [USER_ITEM, AGENT_ITEM],
error: null,
},
}),
).toMatchObject({ payload: { held: false, items: [USER_ITEM, AGENT_ITEM] } });
expect(
SessionInboundMessageSchema.parse({
type: "agent.queue.withdraw.request",
agentId: "agent-1",
messageId: "msg-1",
requestId: "req-withdraw",
}),
).toMatchObject({ agentId: "agent-1", messageId: "msg-1", requestId: "req-withdraw" });
expect(
SessionOutboundMessageSchema.parse({
type: "agent.queue.withdraw.response",
payload: {
requestId: "req-withdraw",
agentId: "agent-1",
messageId: "msg-1",
withdrawn: true,
item: USER_ITEM,
reason: null,
error: null,
},
}),
).toMatchObject({ payload: { withdrawn: true, item: USER_ITEM } });
for (const reason of ["not_found", "already_dispatching"] as const) {
expect(
SessionOutboundMessageSchema.parse({
type: "agent.queue.withdraw.response",
payload: {
requestId: "req-withdraw",
agentId: "agent-1",
messageId: "msg-1",
withdrawn: false,
item: null,
reason,
error: null,
},
}),
).toMatchObject({ payload: { withdrawn: false, reason } });
}
expect(
SessionInboundMessageSchema.parse({
type: "agent.queue.promote.request",
agentId: "agent-1",
messageId: "msg-1",
activeTurnBehavior: "steer",
requestId: "req-promote",
}),
).toMatchObject({ activeTurnBehavior: "steer" });
expect(
SessionInboundMessageSchema.safeParse({
type: "agent.queue.promote.request",
agentId: "agent-1",
messageId: "msg-1",
activeTurnBehavior: "queue",
requestId: "req-promote",
}).success,
).toBe(false);
expect(
SessionOutboundMessageSchema.parse({
type: "agent.queue.promote.response",
payload: {
requestId: "req-promote",
agentId: "agent-1",
messageId: "msg-1",
promoted: true,
reason: null,
error: null,
},
}),
).toMatchObject({ payload: { promoted: true } });
});
test("accepts queue updates with or without subscriptionId and registers subscription", () => {
for (const payload of [
{ agentId: "agent-1", held: false, items: [] },
{ subscriptionId: "sub-1", agentId: "agent-1", held: true, items: [USER_ITEM] },
]) {
expect(
SessionOutboundMessageSchema.parse({ type: "agent.queue.update", payload }),
).toMatchObject({ payload });
}
expect(SessionEventSubscriptionSchema.parse("agent.queue.update")).toBe("agent.queue.update");
});
test("keeps send_agent_message_response.messageId and server_info.features.agentMessageQueue optional", () => {
expect(
SendAgentMessageResponseMessageSchema.parse({
type: "send_agent_message_response",
payload: {
requestId: "req-1",
agentId: "agent-1",
accepted: true,
deliveryStatus: "queued",
messageId: "msg-1",
error: null,
},
}).payload.messageId,
).toBe("msg-1");
expect(
SendAgentMessageResponseMessageSchema.parse({
type: "send_agent_message_response",
payload: {
requestId: "req-1",
agentId: "agent-1",
accepted: true,
error: null,
},
}).payload.messageId,
).toBeUndefined();
expect(
ServerInfoStatusPayloadSchema.parse({
status: "server_info",
serverId: "server-1",
features: {},
}).features?.agentMessageQueue,
).toBeUndefined();
});
});
+138
View File
@@ -1426,6 +1426,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 +2224,27 @@ export const AgentBackgroundWorkStopRequestMessageSchema = z.object({
requestId: z.string(),
});
export const AgentQueueListRequestMessageSchema = z.object({
type: z.literal("agent.queue.list.request"),
agentId: z.string(),
requestId: z.string(),
});
export const AgentQueueWithdrawRequestMessageSchema = z.object({
type: z.literal("agent.queue.withdraw.request"),
agentId: z.string(),
messageId: z.string(),
requestId: z.string(),
});
export const AgentQueuePromoteRequestMessageSchema = z.object({
type: z.literal("agent.queue.promote.request"),
agentId: z.string(),
messageId: z.string(),
activeTurnBehavior: ActiveTurnBehaviorSchema,
requestId: z.string(),
});
export const ProviderSubagentTimelineRequestMessageSchema = z.object({
type: z.literal("agent.provider_subagents.timeline.get.request"),
parentAgentId: z.string(),
@@ -2385,6 +2416,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({
@@ -3637,6 +3671,7 @@ export const SessionEventSubscriptionSchema = z.enum([
"workspace_setup_progress",
"agent.provider_subagents.update",
"agent.background_work.update",
"agent.queue.update",
"terminal_attention_required",
"plugin.notification",
"status.server_info",
@@ -3810,6 +3845,9 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
ProviderSubagentListRequestMessageSchema,
AgentBackgroundWorkListRequestMessageSchema,
AgentBackgroundWorkStopRequestMessageSchema,
AgentQueueListRequestMessageSchema,
AgentQueueWithdrawRequestMessageSchema,
AgentQueuePromoteRequestMessageSchema,
ProviderSubagentTimelineRequestMessageSchema,
SetAgentTimelineSubscriptionRequestMessageSchema,
AgentForkContextRequestMessageSchema,
@@ -4343,6 +4381,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 +5520,95 @@ export const AgentBackgroundWorkUpdateMessageSchema = z.object({
}),
});
export const QueuedMessageSenderSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("user") }),
z.object({
kind: z.literal("agent_message"),
agentId: z.string(),
serverId: z.string().optional(),
title: z.string().optional(),
}),
z.object({
kind: z.literal("agent_notification"),
agentId: z.string(),
serverId: z.string().optional(),
title: z.string().optional(),
event: z.enum(["finished", "errored", "permission-required", "closed"]),
}),
z.object({
kind: z.literal("change_request_update"),
url: z.string(),
}),
]);
export type QueuedMessageSender = z.infer<typeof QueuedMessageSenderSchema>;
export const QueuedAgentMessagePayloadSchema = z.object({
id: z.string(),
seq: z.number().int().positive(),
enqueuedAt: z.string(),
text: z.string(),
attachments: z.array(AgentAttachmentSchema).optional(),
sender: QueuedMessageSenderSchema,
held: z.boolean(),
state: z.enum(["queued", "dispatching"]),
// The message moves the agent to this provider before it runs.
providerSwitch: QueuedProviderSwitchSchema.optional(),
});
export type QueuedAgentMessagePayload = z.infer<typeof QueuedAgentMessagePayloadSchema>;
export const AgentQueueMissReasonSchema = z.enum(["not_found", "already_dispatching"]);
export type AgentQueueMissReason = z.infer<typeof AgentQueueMissReasonSchema>;
export const AgentQueueListResponseMessageSchema = z.object({
type: z.literal("agent.queue.list.response"),
payload: z.object({
requestId: z.string(),
agentId: z.string(),
held: z.boolean(),
items: z.array(QueuedAgentMessagePayloadSchema),
error: z.string().nullable(),
}),
});
export const AgentQueueWithdrawResponseMessageSchema = z.object({
type: z.literal("agent.queue.withdraw.response"),
payload: z.object({
requestId: z.string(),
agentId: z.string(),
messageId: z.string(),
withdrawn: z.boolean(),
item: QueuedAgentMessagePayloadSchema.nullable().optional(),
reason: AgentQueueMissReasonSchema.nullable().optional(),
error: z.string().nullable(),
}),
});
export const AgentQueuePromoteResponseMessageSchema = z.object({
type: z.literal("agent.queue.promote.response"),
payload: z.object({
requestId: z.string(),
agentId: z.string(),
messageId: z.string(),
promoted: z.boolean(),
reason: AgentQueueMissReasonSchema.nullable().optional(),
error: z.string().nullable(),
}),
});
// Event push delivered through session.events.set_subscription; it has no .request/.response pair.
// Each update replaces the agent's whole queue list.
export const AgentQueueUpdateMessageSchema = z.object({
type: z.literal("agent.queue.update"),
payload: z.object({
subscriptionId: z.string().optional(),
agentId: z.string(),
held: z.boolean(),
items: z.array(QueuedAgentMessagePayloadSchema),
}),
});
export const ProviderSubagentTimelineResponseMessageSchema = z.object({
type: z.literal("agent.provider_subagents.timeline.get.response"),
payload: z.object({
@@ -5723,6 +5852,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 +5870,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 +8196,10 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
AgentBackgroundWorkListResponseMessageSchema,
AgentBackgroundWorkStopResponseMessageSchema,
AgentBackgroundWorkUpdateMessageSchema,
AgentQueueListResponseMessageSchema,
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");
});
});
@@ -198,6 +198,45 @@ describe("unknown list variants degrade to one skipped element", () => {
},
});
});
it("skips a queued message item with an unknown sender variant and keeps the update", () => {
const knownItem = {
id: "msg-1",
seq: 1,
enqueuedAt: "2026-11-30T08:00:00.000Z",
text: "Check logs",
sender: { kind: "user" },
held: false,
state: "queued",
};
const futureItem = {
id: "msg-2",
seq: 2,
enqueuedAt: "2026-11-30T08:00:01.000Z",
text: "Future trigger",
sender: { kind: "future_trigger", source: "cron" },
held: false,
state: "queued",
};
const envelope = session({
type: "agent.queue.update",
payload: {
agentId: "agent-1",
held: false,
items: [knownItem, futureItem],
},
});
const generated = validateWSOutboundMessage(envelope);
const zod = safeParseSkippingUnknownVariants(WSOutboundMessageSchema, envelope);
expect(generated).toMatchObject({
success: true,
data: { message: { payload: { agentId: "agent-1", held: false, items: [knownItem] } } },
});
expect(zod.success).toBe(true);
expect(zod.success && zod.data).toEqual(generated.success && generated.data);
});
});
describe("what still fails", () => {
@@ -472,3 +472,66 @@ it("accepts omitted RPC output so the receiving client can apply schema defaults
const message = { type: "plugin.rpc.invoke.response", payload: { requestId: "default-output" } };
expect(PluginRpcInvokeResponseSchema.safeParse(message).success).toBe(true);
});
it("validates agent.queue outbound responses and update events via zod-aot", () => {
const item = {
id: "msg-1",
seq: 1,
enqueuedAt: "2026-11-30T08:00:00.000Z",
text: "Queued prompt",
sender: { kind: "user" },
held: false,
state: "queued",
};
for (const message of [
{
type: "agent.queue.list.response",
payload: { requestId: "req-1", agentId: "agent-1", held: false, items: [item], error: null },
},
{
type: "agent.queue.withdraw.response",
payload: {
requestId: "req-2",
agentId: "agent-1",
messageId: "msg-1",
withdrawn: true,
item,
reason: null,
error: null,
},
},
{
type: "agent.queue.promote.response",
payload: {
requestId: "req-3",
agentId: "agent-1",
messageId: "msg-1",
promoted: false,
reason: "already_dispatching",
error: null,
},
},
{
type: "agent.queue.update",
payload: { subscriptionId: "sub-1", agentId: "agent-1", held: true, items: [item] },
},
{
type: "send_agent_message_response",
payload: {
requestId: "req-4",
agentId: "agent-1",
accepted: true,
deliveryStatus: "queued",
messageId: "msg-1",
error: null,
},
},
]) {
const envelope = { type: "session", message };
expect(validateWSOutboundMessage(envelope)).toEqual({
success: true,
data: envelope,
skipped: [],
});
}
});
@@ -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,
@@ -5,13 +5,17 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, test } from "vitest";
import { formatAgentMessage, parseAgentMessage } from "../agent-messages/envelope.js";
import {
createAgentMessageDelivery,
createMemoryAgentMessageQueueStore,
} from "../agent-messages/index.js";
import type { WaitForFinishResult } from "@getpaseo/client/internal/daemon-client";
import type { AgentMessageDelivery } from "../agent-messages/index.js";
import { buildStoredAgentPayload } from "../agent-projections.js";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import {
createFinishSubscriptions,
createJsonFinishSubscriptionStore,
type FinishMessages,
type FinishObservation,
type FinishSubscription,
type FinishSubscriptions,
@@ -61,18 +65,18 @@ class Observation implements FinishObservation {
return this.permission.promise;
}
}
class Delivery implements AgentMessageDelivery {
class Delivery implements FinishMessages {
prompts: string[] = [];
/** Prompts as the recipient's provider receives them, inside their envelope. */
enqueued: string[] = [];
acknowledgments: Array<ReturnType<typeof deferred<"steered">>> = [];
enqueue(message: Parameters<AgentMessageDelivery["enqueue"]>[0]) {
this.prompts.push(String(message.prompt));
async enqueue(message: Parameters<FinishMessages["enqueue"]>[0]) {
this.prompts.push(message.text);
this.enqueued.push(
formatAgentMessage({
id: "notification",
source: message.source ?? null,
text: String(message.prompt),
text: message.text,
}),
);
const acknowledgment = deferred<"steered">();
@@ -80,10 +84,17 @@ class Delivery implements AgentMessageDelivery {
return {
status: "queued" as const,
messageId: "notification",
activeTurnBehavior: "queue" as const,
guidance: "",
dispatched: acknowledgment.promise,
};
}
async close() {}
dispatchOf() {
return undefined;
}
hasPending() {
return false;
}
async waitForDispatch() {}
}
const homes: string[] = [];
@@ -808,3 +819,73 @@ describe("a child that ends its turn with work pending", () => {
await expect.poll(async () => (await state.store.list()).length).toBe(0);
});
});
test("withdrawing a queued message after a restart cancels its completion notice", async () => {
const first = await scenario();
await first.service.register({ ...intent, messageId: "queued-prompt" });
await first.service.close();
const second = await scenario(first.home);
await until(() => second.observation.waits.length === 1);
await second.service.withdraw("queued-prompt");
expect(await second.store.list()).toEqual([]);
expect(second.observation.waits[0]!.signal.aborted).toBe(true);
expect(second.service.hasPendingForCaller("parent")).toBe(false);
expect(second.delivery.prompts).toEqual([]);
});
test("daemon-level agentMessages.withdraw cancels a pending FinishSubscription via onWithdrawn", async () => {
const home = await mkdtemp(join(tmpdir(), "finish-withdraw-"));
homes.push(home);
const store = createJsonFinishSubscriptionStore(home);
const observation = new Observation();
const agentMessages = createAgentMessageDelivery({
store: createMemoryAgentMessageQueueStore(),
isRunning: () => true,
dispatch: async () => "turn_started",
onError: (error) => {
throw error;
},
});
const finishSubscriptions = createFinishSubscriptions({
store,
messages: () => agentMessages,
callerIsActive: async () => true,
serverId: "server-1",
logger: createTestLogger(),
retryDelayMs: 1,
open: (record, signal) => observation.open(record, signal),
pendingWork: (record) => observation.pendingWork(record),
});
services.push(finishSubscriptions);
const unsubscribeWithdrawn = agentMessages.onWithdrawn(({ id }) =>
finishSubscriptions.withdraw(id),
);
try {
await finishSubscriptions.start();
const messageId = "queued-child-msg";
await finishSubscriptions.register({ ...intent, messageId }, true);
await agentMessages.enqueue({
recipientId: intent.childAgentId,
messageId,
text: "Investigate failure",
source: { kind: "agent-message", agentId: intent.callerAgentId, title: "Parent" },
activeTurnBehavior: "queue",
});
expect(await store.list()).toHaveLength(1);
expect(finishSubscriptions.hasPendingForCaller(intent.callerAgentId)).toBe(true);
const withdrawn = await agentMessages.withdraw(intent.childAgentId, messageId);
expect(withdrawn.status).toBe("withdrawn");
await expect.poll(async () => (await store.list()).length).toBe(0);
expect(finishSubscriptions.hasPendingForCaller(intent.callerAgentId)).toBe(false);
expect(observation.waits).toEqual([]);
} finally {
unsubscribeWithdrawn();
await agentMessages.close();
}
});
@@ -32,6 +32,8 @@ export interface FinishSubscription {
* subscription then follows the child silently until it settles or the follow limit passes.
*/
followingSince?: string;
/** The agent message whose completion this reports. Withdrawing it ends the subscription. */
messageId?: string;
}
/**
* Work that will start the child's next turn without a new prompt from the caller.
@@ -47,6 +49,11 @@ export interface FinishObservationSession {
next(): Promise<FinishObservationResult>;
close(): Promise<void>;
}
/** What finish subscriptions need from message delivery. */
export type FinishMessages = Pick<
AgentMessageDelivery,
"dispatchOf" | "enqueue" | "hasPending" | "waitForDispatch"
>;
export interface FinishObservation {
open(subscription: FinishSubscription, signal: AbortSignal): Promise<FinishObservationSession>;
/** The child's own pending work. Empty when its host cannot tell, as for remote children. */
@@ -54,7 +61,7 @@ export interface FinishObservation {
}
interface Dependencies extends FinishObservation {
store: FinishSubscriptionStore;
messages(): AgentMessageDelivery;
messages(): FinishMessages;
callerIsActive(agentId: string): Promise<boolean>;
serverId: string;
logger: Logger;
@@ -76,6 +83,8 @@ export interface FinishSubscriptions {
input: Omit<FinishSubscription, "id">,
pendingDispatch?: boolean,
): Promise<FinishRegistration>;
/** The message was withdrawn before delivery, so there is no completion to report. */
withdraw(messageId: string): Promise<void>;
close(): Promise<void>;
}
interface Watch {
@@ -149,6 +158,48 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
// Only IDs captured by this observer are eligible; newer registrations survive.
for (const record of watch.records) await deps.store.remove(record.id);
}
/** A watch that supersedes its group's older ones once its prompt is dispatched. */
function attachPending(record: FinishSubscription): FinishRegistration {
const predecessors = [...(watches.get(key(record)) ?? [])];
const watch = attach([record], true);
const group = watches.get(key(record))!;
return {
accept() {
if (!watch.pending || closed) return;
watch.pending = false;
for (const prior of predecessors) stop(prior, group);
watch.decide(true);
void serialize(async () => {
for (const prior of predecessors) await remove(prior);
}).catch((error) =>
deps.logger.error({ err: error }, "Failed to remove superseded finish subscriptions"),
);
},
reject: () =>
serialize(async () => {
await remove(watch);
stop(watch, group);
}),
};
}
/** A subscription whose prompt is still queued waits for it, as it did before the restart. */
function restore(records: FinishSubscription[]): void {
const queued = records.flatMap((record) => {
if (record.serverId || !record.messageId) return [];
const dispatched = deps.messages().dispatchOf(record.childAgentId, record.messageId);
return dispatched ? [{ record, dispatched }] : [];
});
const accepted = records.filter((record) => !queued.some((entry) => entry.record === record));
if (accepted.length) attach(accepted, false);
for (const { record, dispatched } of queued) {
const registration = attachPending(record);
void dispatched
.then(registration.accept, registration.reject)
.catch((error) =>
deps.logger.error({ err: error }, "Failed to remove rejected finish subscription"),
);
}
}
async function delay(signal: AbortSignal, attempt: number): Promise<void> {
try {
await pause(
@@ -203,6 +254,15 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
if (result.status === "permission") return "needs permission";
return result.reason ?? "finished";
}
/** Interim notices repeat, so each is its own message. */
function noticeId(
record: FinishSubscription,
notice: Notice,
permissionId: string | undefined,
): string | undefined {
if (permissionId) return `${record.id}:permission:${permissionId}`;
return notice.pendingWork ? undefined : `${record.id}:final`;
}
async function deliver(
record: FinishSubscription,
notice: Notice,
@@ -218,9 +278,12 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
if (signal.aborted) return;
if (request && permissions.has(request.id)) continue;
const title = result?.final?.title ?? record.childAgentId;
const receipt = deps.messages().enqueue({
const receipt = await deps.messages().enqueue({
recipientId: record.callerAgentId,
prompt: formatFinishNotificationBody({
// A restart can observe the same outcome again while its notice is still queued.
// Naming the notice after the outcome makes that the same message.
messageId: noticeId(record, notice, request?.id),
text: formatFinishNotificationBody({
childAgentId: record.childAgentId,
serverId: record.serverId ?? deps.serverId,
title,
@@ -241,10 +304,14 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
activeTurnBehavior: "queue",
unarchive: false,
});
const acknowledge = () => {
if (request) permissions.add(request.id);
};
acknowledgments.push(
receipt.dispatched.then(() => {
if (request) permissions.add(request.id);
return undefined;
receipt.dispatched.then(acknowledge, (error) => {
// A withdrawn notice was removed on purpose. Sending it again would undo that.
if (!(error instanceof DOMException) || error.name !== "AbortError") throw error;
acknowledge();
}),
);
}
@@ -416,7 +483,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
records.push(record);
groups.set(key(record), records);
}
for (const records of groups.values()) attach(records, false);
for (const records of groups.values()) restore(records);
recovering = false;
}),
register: (input, pendingDispatch = false) => {
@@ -429,28 +496,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
id: randomUUID(),
};
await deps.store.put(record);
const group = watches.get(key(record)) ?? new Set<Watch>();
const predecessors = [...group];
const watch = attach([record], true);
const actualGroup = watches.get(key(record))!;
const registration: FinishRegistration = {
accept() {
if (!watch.pending || closed) return;
watch.pending = false;
for (const prior of predecessors) stop(prior, actualGroup);
watch.decide(true);
void serialize(async () => {
for (const prior of predecessors) await remove(prior);
}).catch((error) =>
deps.logger.error({ err: error }, "Failed to remove superseded finish subscriptions"),
);
},
reject: () =>
serialize(async () => {
await remove(watch);
stop(watch, actualGroup);
}),
};
const registration = attachPending(record);
if (!pendingDispatch) registration.accept();
return registration;
}).finally(() => {
@@ -459,6 +505,22 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
else registering.delete(input.callerAgentId);
});
},
withdraw: (messageId) =>
serialize(async () => {
for (const record of await deps.store.list())
if (record.messageId === messageId) await deps.store.remove(record.id);
for (const group of watches.values())
for (const watch of group) {
const kept = watch.records.filter((record) => record.messageId !== messageId);
if (kept.length === watch.records.length) continue;
if (kept.length) {
watch.records.splice(0, watch.records.length, ...kept);
continue;
}
stop(watch, group);
recheckCallerOf(watch);
}
}),
async close() {
closed = true;
await mutations;
@@ -12,6 +12,7 @@ const recordsSchema = z.array(
serverId: z.string().min(1).optional(),
requireParentOwnership: z.boolean().optional(),
followingSince: z.iso.datetime().optional(),
messageId: z.string().min(1).optional(),
}),
);
@@ -1,21 +1,20 @@
import type { Logger } from "pino";
import type { AgentManager } from "../../agent-manager.js";
import type { AgentStorage } from "../../agent-storage.js";
import type { AgentMessageDelivery } from "../../agent-messages/index.js";
import { buildStoredAgentPayload, toAgentPayload } from "../../agent-projections.js";
import { serializeSnapshotWithMetadata } from "../../mcp-shared.js";
import { createHostObservationResolver, type ToolHosts } from "../../host-operations/index.js";
import { openFinishObservation } from "./observation-stream.js";
import type { AgentStreamEvent } from "../../agent-sdk-types.js";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import type { FinishObservation, PendingWork } from "../index.js";
import type { FinishMessages, FinishObservation, PendingWork } from "../index.js";
export function createFinishObservation(input: {
agentManager: AgentManager;
agentStorage: AgentStorage;
/** A child chosen for restart recovery reports its state only after its resume was sent. */
waitForResume(agentId: string, signal: AbortSignal): Promise<void>;
messages(): AgentMessageDelivery;
messages(): FinishMessages;
hosts(): ToolHosts;
serverId: string;
logger: Logger;
@@ -105,7 +104,8 @@ export function createFinishObservation(input: {
type: "turn_started",
provider: current.provider,
});
else
// An agent with messages still queued has not settled: its next turn is on the way.
else if (!input.messages().hasPending(agentId))
publish(
stored
? buildStoredAgentPayload(stored, [stored.provider], (provider, own) =>
@@ -4351,27 +4351,33 @@ describe("send_agent_prompt MCP tool", () => {
const dispatch = serverDeliveries
.get(server)!
.waitForDispatch(child.id, new AbortController().signal);
const rejectedDispatch = rejected
? expect(dispatch).rejects.toThrow("Start rejected")
: null;
expect(client.sessions[0]!.prompts).toHaveLength(0);
session.finishTurn();
await vi.waitFor(() => expect(session.prompts).toHaveLength(2));
expect(client.sessions[0]!.prompts).toHaveLength(0);
release();
if (rejectedDispatch) await rejectedDispatch;
else await dispatch;
if (!rejected || priorNotification) {
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1), {
timeout: 5000,
});
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
});
} else {
await serverSubscriptions.get(server)!.close();
// A refused turn start keeps the message and holds it, which ends the wait.
await dispatch;
await expect(serverDeliveries.get(server)!.list(child.id)).resolves.toMatchObject(
rejected
? { held: true, items: [{ text: "New message", state: "queued" }] }
: { items: [] },
);
if (rejected) {
// The sender's report waits until the held message reaches the child.
expect(client.sessions[0]!.prompts).toHaveLength(0);
await sendMcpAndAwaitDispatch(mcpClient, server, {
agentId: child.id,
prompt: "Recovery",
notifyOnFinish: false,
});
}
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1), {
timeout: 5000,
});
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
});
} finally {
await mcpClient?.close();
await removeAgentStateDir(manager, storage, workdir);
@@ -4750,22 +4756,26 @@ describe("send_agent_prompt MCP tool", () => {
});
} else {
childClient.sessions[0]!.rejectNextTurnStart(new Error("Requested turn could not start"));
await expect(
invokeToolWithParsedInput(tool, {
agentId: child.id,
prompt: "Replacement task",
activeTurnBehavior: "interrupt",
}),
).rejects.toThrow("Requested turn could not start");
// A later real turn must not inherit a subscription from the rejected dispatch.
await invokeToolWithParsedInput(tool, {
agentId: child.id,
prompt: "Replacement task",
activeTurnBehavior: "interrupt",
});
await expect(serverDeliveries.get(server)!.list(child.id)).resolves.toMatchObject({
held: true,
items: [{ text: "Replacement task", state: "queued" }],
});
expect(parentClient.sessions[0]!.prompts).toHaveLength(0);
// The next message carries the held one, so its sender hears about that turn.
await invokeToolWithParsedInput(tool, {
agentId: child.id,
prompt: "Recovery",
notifyOnFinish: false,
});
expect(String(childClient.sessions[0]!.prompts.at(-1))).toContain("Replacement task");
expect(String(childClient.sessions[0]!.prompts.at(-1))).toContain("Recovery");
childClient.sessions[0]!.finishTurn("Recovered");
await vi.waitFor(() => expect(agentManager.getAgent(child.id)?.lifecycle).toBe("idle"));
expect(parentClient.sessions[0]!.prompts).toHaveLength(0);
await vi.waitFor(() => expect(parentClient.sessions[0]!.prompts).toHaveLength(1));
}
} finally {
await removeAgentStateDir(agentManager, storage, workdir);
@@ -5718,10 +5728,10 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
const activeTurnId = agentManager.getAgent(childId)?.activeTurnId;
const delivery = toolDeliveries.get(tool)!;
let ordinaryBeforeDispatch = 0;
const ordinary = delivery.enqueue({
const ordinary = await delivery.enqueue({
recipientId: childId,
source: { kind: "agent-message", agentId: "parent" },
prompt: "ordinary follow-up",
text: "ordinary follow-up",
beforeDispatch: () => {
ordinaryBeforeDispatch++;
},
@@ -0,0 +1,145 @@
import type { UploadedImage } from "@getpaseo/protocol/agent-types";
import type { QueuedProviderSwitch } from "@getpaseo/protocol/messages";
import type { Logger } from "pino";
import {
AgentAlreadyOnProviderError,
AgentProviderSwitchStartError,
type AgentManager,
type ManagedAgent,
} from "./agent-manager.js";
import {
AgentTurnBusyError,
AgentTurnStartRejectedError,
sendPreparedPromptToAgent,
startAgentRun,
type PromptDispatchResult,
type SendPromptToAgentParams,
} from "./agent-prompt.js";
import type { AgentPromptInput } from "./agent-sdk-types.js";
export interface ProviderSwitchTurn {
agentManager: AgentManager;
logger: Logger;
agentId: string;
providerSwitch: QueuedProviderSwitch;
prompt: AgentPromptInput;
uploadedImages?: readonly UploadedImage[];
messageId: string;
/** Cut a running turn for the switch. Otherwise the switch is rejected while one runs. */
interruptRunning?: boolean;
/** Runs once the target provider is committed, before its first turn starts. */
beforeDispatch?: () => Promise<void>;
/** Claims the prompt when the target provider admits it. */
admit?: () => boolean;
}
/**
* Move a chat to another provider and start the first turn there with `prompt`. A failure after
* the move is an `AgentProviderSwitchStartError`: the chat stays on the target.
*/
export async function startProviderSwitchTurn(
turn: ProviderSwitchTurn,
): Promise<PromptDispatchResult & { agent: ManagedAgent }> {
const { agentManager, agentId, providerSwitch, messageId } = turn;
let dispatch: PromptDispatchResult | undefined;
const switched = await agentManager.switchAgentProvider(agentId, {
toProvider: providerSwitch.provider,
model: providerSwitch.model,
modeId: providerSwitch.modeId,
thinkingOptionId: providerSwitch.thinkingOptionId,
providerOptions: providerSwitch.providerOptions,
prompt: turn.prompt,
messageId,
interruptRunning: turn.interruptRunning,
admitFirstTurn: async (result, switchReservationToken) => {
try {
await turn.beforeDispatch?.();
dispatch = await startAgentRun(agentManager, agentId, result.handoffPrompt, turn.logger, {
idleOnly: true,
skipPluginReload: true,
switchReservationToken,
admit: turn.admit,
runOptions: {
clientMessageId: messageId,
...(turn.uploadedImages?.length ? { uploadedImages: turn.uploadedImages } : {}),
},
});
} catch (error) {
throw new AgentProviderSwitchStartError(
agentManager.getAgent(agentId) ?? result.agent,
error,
);
}
},
});
if (!dispatch) throw new Error(`Provider switch for agent ${agentId} started no turn`);
return { ...dispatch, agent: switched.agent };
}
type QueuedSwitchDispatch = Pick<
SendPromptToAgentParams,
| "agentManager"
| "agentStorage"
| "agentId"
| "prompt"
| "uploadedImages"
| "activeTurnBehavior"
| "clearPendingPermissions"
| "unarchive"
| "logger"
> & {
providerSwitch: QueuedProviderSwitch;
messageId: string;
/** Wait for the running turn to end. Otherwise the switch replaces it. */
idleOnly: boolean;
admit: () => boolean;
};
/**
* Run a provider switch that waited in the message queue. A chat that already moved to the target
* takes the prompt and the chosen settings. A switch that fails is a rejected turn start, so the
* queue keeps the message and holds.
*/
export async function runQueuedProviderSwitch(
queued: QueuedSwitchDispatch,
): Promise<PromptDispatchResult> {
const { providerSwitch, messageId, ...send } = queued;
try {
return await startProviderSwitchTurn({
agentManager: queued.agentManager,
logger: queued.logger,
agentId: queued.agentId,
providerSwitch,
prompt: queued.prompt,
uploadedImages: queued.uploadedImages,
messageId,
interruptRunning: !queued.idleOnly,
admit: queued.admit,
});
} catch (error) {
if (error instanceof AgentAlreadyOnProviderError) {
return sendPreparedPromptToAgent({
...send,
runOptions: { clientMessageId: messageId },
beforeDispatch: () => applySettings(queued.agentManager, queued.agentId, providerSwitch),
});
}
if (error instanceof AgentTurnBusyError && queued.idleOnly) throw error;
const cause = error instanceof AgentProviderSwitchStartError ? error.cause : error;
throw new AgentTurnStartRejectedError(cause instanceof Error ? cause.message : String(cause), {
cause,
});
}
}
async function applySettings(
agentManager: AgentManager,
agentId: string,
{ model, modeId, thinkingOptionId, providerOptions }: QueuedProviderSwitch,
): Promise<void> {
if (model) await agentManager.setAgentModel(agentId, model);
if (modeId) await agentManager.setAgentMode(agentId, modeId);
if (thinkingOptionId) await agentManager.setAgentThinkingOption(agentId, thinkingOptionId);
if (providerOptions && Object.keys(providerOptions).length > 0)
await agentManager.setAgentOptions(agentId, providerOptions);
}
@@ -11,6 +11,7 @@ import {
type ToolHosts,
} from "../host-operations/index.js";
import { AgentDirectory } from "../directory.js";
import { randomUUID } from "node:crypto";
import { stat } from "node:fs/promises";
import { z } from "zod";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
@@ -2085,6 +2086,8 @@ function createToolCatalog(
throw new PaseoToolInputError(`Agent ${agentId} not found`);
}
const notifying = Boolean(callerAgentId && notifyOnFinish);
// Named before it is queued, so the subscription can follow this message across restarts.
const messageId = callerAgentId ? randomUUID() : undefined;
const notification =
notifying && callerAgentId
? await (() => {
@@ -2092,7 +2095,7 @@ function createToolCatalog(
throw new Error("Finish subscriptions are not configured");
return options
.finishSubscriptions()
.register({ childAgentId: agentId, callerAgentId }, true);
.register({ childAgentId: agentId, callerAgentId, messageId }, true);
})()
: undefined;
function confirmDispatch(_disposition: PromptDispatchDisposition): void {
@@ -2110,25 +2113,24 @@ function createToolCatalog(
}
if (callerAgentId) {
const receipt = (() => {
try {
return agentMessages().enqueue({
recipientId: agentId,
prompt,
source: {
kind: "agent-message",
agentId: callerAgentId,
title: resolveCallerAgent()?.config.title ?? undefined,
},
sessionMode,
activeTurnBehavior,
onDispatch: confirmDispatch,
});
} catch (error) {
const receipt = await agentMessages()
.enqueue({
recipientId: agentId,
messageId,
text: prompt,
source: {
kind: "agent-message",
agentId: callerAgentId,
title: resolveCallerAgent()?.config.title ?? undefined,
},
sessionMode,
activeTurnBehavior,
onDispatch: confirmDispatch,
})
.catch((error) => {
rejectNotification();
throw error;
}
})();
});
void receipt.dispatched.catch(() => {
rejectNotification();
});
@@ -149,4 +149,27 @@ describe("SessionAuthorization", () => {
expect(parseDaemonPermissions(["hub.execute", "hub.execute"])).toEqual(["hub.execute"]);
expect(() => parseDaemonPermissions(["hub.execution.*"])).toThrow("Invalid daemon permission");
});
test("authorizes agent.queue operations with workspace.read, workspace.write, and hub.execute", () => {
const readOnly = new SessionAuthorization(["workspace.read"]);
expect(readOnly.allowsInbound(inboundMessage("agent.queue.list.request"))).toBe(true);
expect(readOnly.allowsInbound(inboundMessage("agent.queue.withdraw.request"))).toBe(false);
expect(readOnly.allowsInbound(inboundMessage("agent.queue.promote.request"))).toBe(false);
expect(readOnly.allowsOutbound(outboundMessage("agent.queue.list.response"))).toBe(true);
expect(readOnly.allowsOutbound(outboundMessage("agent.queue.update"))).toBe(true);
expect(readOnly.allowsOutbound(outboundMessage("agent.queue.withdraw.response"))).toBe(false);
expect(readOnly.allowsOutbound(outboundMessage("agent.queue.promote.response"))).toBe(false);
const writer = new SessionAuthorization(["workspace.write"]);
expect(writer.allowsInbound(inboundMessage("agent.queue.withdraw.request"))).toBe(true);
expect(writer.allowsInbound(inboundMessage("agent.queue.promote.request"))).toBe(true);
expect(writer.allowsOutbound(outboundMessage("agent.queue.withdraw.response"))).toBe(true);
expect(writer.allowsOutbound(outboundMessage("agent.queue.promote.response"))).toBe(true);
const hub = new SessionAuthorization(["hub.execute"]);
expect(hub.allowsInbound(inboundMessage("agent.queue.withdraw.request"))).toBe(true);
expect(hub.allowsInbound(inboundMessage("agent.queue.promote.request"))).toBe(true);
expect(hub.allowsOutbound(outboundMessage("agent.queue.withdraw.response"))).toBe(true);
expect(hub.allowsOutbound(outboundMessage("agent.queue.promote.response"))).toBe(true);
});
});
@@ -26,6 +26,9 @@ const INBOUND_PERMISSION = {
"agent.provider_subagents.list.request": "workspace.read",
"agent.background_work.list.request": "workspace.read",
"agent.background_work.stop.request": ["workspace.write", "hub.execute"],
"agent.queue.list.request": "workspace.read",
"agent.queue.withdraw.request": ["workspace.write", "hub.execute"],
"agent.queue.promote.request": ["workspace.write", "hub.execute"],
"agent.provider_subagents.timeline.get.request": "workspace.read",
"agent.provider.switch.request": "workspace.write",
"agent.rewind.request": "workspace.write",
@@ -283,6 +286,10 @@ const OUTBOUND_PERMISSION = {
"agent.background_work.stop.response": ["workspace.write", "hub.execute"],
"agent.background_work.update": "workspace.read",
"agent.provider.switch.response": "workspace.write",
"agent.queue.list.response": "workspace.read",
"agent.queue.withdraw.response": ["workspace.write", "hub.execute"],
"agent.queue.promote.response": ["workspace.write", "hub.execute"],
"agent.queue.update": "workspace.read",
"agent.rewind.response": "workspace.write",
"agent.skills.get_status.response": "daemon.read",
"agent.skills.import_legacy_selection.response": "daemon.manage",
+35 -1
View File
@@ -8,6 +8,7 @@ import {
createFinishObservation,
createJsonFinishSubscriptionStore,
} from "./agent/finish-subscriptions/index.js";
import type { AgentMessageDelivery } from "./agent/agent-messages/index.js";
import { createWorkspaceRuntimeStore } from "./workspace-runtime-store/index.js";
import type { PluginRegistries } from "@getpaseo/protocol/plugin-registry";
import { describeHookWorkspace } from "./plugins/lifecycle/index.js";
@@ -1102,6 +1103,7 @@ async function assemblePaseoDaemon({
agentStorage,
logger,
unarchive: false,
resumesTurn: true,
});
},
report: (agentId, err) => logger.error({ agentId, err }, "Agent restart recovery failed"),
@@ -1540,6 +1542,9 @@ async function assemblePaseoDaemon({
});
agentManager.setAgentArchivedCallback(async (agentId) => {
await wsServer?.agentMessages
.clearRecipient(agentId)
.catch((err) => logger.warn({ err, agentId }, "Could not clear archived agent's queue"));
await changeRequestWatches
.archive(agentId)
.catch((err) =>
@@ -1593,6 +1598,22 @@ async function assemblePaseoDaemon({
}),
});
/** A deleted agent's queue goes with it, and a withdrawn message has no completion to report. */
function connectAgentMessageLifecycle(agentMessages: AgentMessageDelivery): void {
agentManager.subscribe(
(event) => {
if (event.type !== "agent_removed") return;
void agentMessages
.clearRecipient(event.agentId)
.catch((err) =>
logger.warn({ err, agentId: event.agentId }, "Could not clear deleted agent's queue"),
);
},
{ replayState: false, includeInternal: true },
);
agentMessages.onWithdrawn(({ id }) => finishSubscriptions.withdraw(id));
}
const idleRuntimeCleanup = createIdleRuntimeCleanup({
enabled: daemonConfigStore.get().idleRuntimeCleanup !== false,
runtimes: () => agentManager.getRuntimeCleanupCandidates(),
@@ -2028,6 +2049,12 @@ async function assemblePaseoDaemon({
pluginRuntime.bindPaseoSessionHost(wsServer);
await pluginRuntime.start();
providerSnapshotManager.settlePluginProviders();
connectAgentMessageLifecycle(wsServer.agentMessages);
// Queues are restored before anything can prompt an agent or observe it as finished.
await wsServer.agentMessages.start({
waitForResume: (agentId) =>
restartRecovery.waitForResume(agentId, new AbortController().signal),
});
restartRecovery.resumePending();
await finishSubscriptions.start();
await changeRequestWatches.start();
@@ -2130,7 +2157,14 @@ async function assemblePaseoDaemon({
wsServer?.prepareForShutdown();
await changeRequestWatches.close();
await finishSubscriptions.close();
await wsServer?.agentMessages.close();
// Queued messages stay saved. Only a dispatch already in flight is given time to commit.
await withTimeout({
promise: wsServer?.agentMessages.close() ?? Promise.resolve(),
timeoutMs: AGENT_CLOSE_TIMEOUT_MS,
label: "finish agent message dispatches",
}).catch((error) =>
logger.warn({ err: error }, "Agent message dispatches did not finish before shutdown"),
);
agentManager.prepareForShutdown();
await restartRecovery.captureRunningAgents();
await closeAllAgents(logger, agentManager);
@@ -70,7 +70,7 @@ describe("daemon restart resume", () => {
// These run in separate OS processes so SIGKILL cannot invoke daemon shutdown hooks.
import { fork, type ChildProcess } from "node:child_process";
import { once } from "node:events";
import { readFile, mkdtemp, rm } from "node:fs/promises";
import { readFile, mkdtemp, rm, mkdir, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
@@ -359,3 +359,279 @@ test("a provider that is slow to reopen does not hold daemon startup", async ()
await rm(root, { recursive: true, force: true });
}
}, 30000);
/** Real daemon processes: state reaches disk asynchronously. */
const SETTLE = { timeout: 15000 };
async function connectClient(port: number): Promise<DaemonClient> {
const client = new DaemonClient({ url: `ws://127.0.0.1:${port}/ws`, appVersion: "0.13.0" });
await client.connect();
await client.fetchAgents({ subscribe: {} });
return client;
}
async function readSavedQueue(
paseoHome: string,
agentId: string,
): Promise<Array<{ text: string; held: boolean; attachments: unknown[] }>> {
try {
const file = path.join(paseoHome, "agent-queues", `${agentId}.json`);
return JSON.parse(await readFile(file, "utf8")).items;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
throw error;
}
}
async function readAllPrompts(root: string): Promise<string[]> {
return (await readFile(path.join(root, "all-prompts.jsonl"), "utf8"))
.trim()
.split("\n")
.map((line) => JSON.stringify(JSON.parse(line).prompt));
}
async function promptsContaining(root: string, text: string): Promise<string[]> {
return (await readAllPrompts(root)).filter((prompt) => prompt.includes(text));
}
/** An agent whose turn stays open until the daemon process goes away. */
async function createBusyAgent(client: DaemonClient, paseoHome: string, cwd: string) {
const agent = await client.createAgent({ provider: "claude", cwd, modeId: "full-access" });
await client.sendMessage(agent.id, "HOLD_CHILD");
const storage = new AgentStorage(path.join(paseoHome, "agents"), createTestLogger());
await expect.poll(async () => (await storage.get(agent.id))?.lastStatus, SETTLE).toBe("running");
return agent.id;
}
async function withDaemons(
run: (daemons: {
root: string;
start(): ReturnType<typeof restartFixture>;
connect(port: number): Promise<DaemonClient>;
}) => Promise<void>,
): Promise<void> {
const root = await mkdtemp(path.join(tmpdir(), "durable-queue-process-"));
const processes: ChildProcess[] = [];
const clients: DaemonClient[] = [];
try {
await run({
root,
async start() {
const fixture = await restartFixture(root);
processes.push(fixture.child);
return fixture;
},
async connect(port) {
const client = await connectClient(port);
clients.push(client);
return client;
},
});
} catch (error) {
console.error(
await readFile(path.join(root, "fixture.log"), "utf8").catch(() => "No fixture log"),
);
throw error;
} finally {
for (const client of clients) await client.close();
for (const child of processes.toReversed()) await stopFixture(child, true);
await rm(root, { recursive: true, force: true });
}
}
test.each([false, true])(
"a queued agent message survives a restart and runs before its finish notice (abrupt=%s)",
async (abrupt) => {
await withDaemons(async ({ root, start, connect }) => {
const first = await start();
const client = await connect(first.port);
const parent = await client.createAgent({
provider: "claude",
cwd: first.cwd,
modeId: "full-access",
});
const childId = await createBusyAgent(client, first.paseoHome, first.cwd);
const mcp = new Client({ name: "queue-parent", version: "1" });
await mcp.connect(
new StreamableHTTPClientTransport(
new URL(`http://127.0.0.1:${first.port}/mcp/agents?callerAgentId=${parent.id}`),
),
);
const sent = await mcp.callTool({
name: "send_agent_prompt",
arguments: { agentId: childId, prompt: "QUEUED_FOLLOW_UP", notifyOnFinish: true },
});
expect(sent.structuredContent).toMatchObject({ deliveryStatus: "queued" });
expect(await readSavedQueue(first.paseoHome, childId)).toMatchObject([
{ text: "QUEUED_FOLLOW_UP", held: false },
]);
await mcp.close();
await client.close();
await stopFixture(first.child, abrupt);
await start();
await expect.poll(() => readPrompts(root), SETTLE).toHaveLength(1);
const prompts = await readAllPrompts(root);
const followUp = prompts.findIndex(
(prompt) => prompt.includes("QUEUED_FOLLOW_UP") && !prompt.includes("agent-notification"),
);
const notice = prompts.findIndex((prompt) => prompt.includes("agent-notification"));
expect(followUp).toBeGreaterThanOrEqual(0);
expect(notice).toBeGreaterThan(followUp);
expect(prompts[notice]).toContain("finished.");
expect(prompts[notice]).not.toContain("was closed");
});
},
60000,
);
test("Stop holds the queue and its finish notice across a restart until the next prompt", async () => {
await withDaemons(async ({ root, start, connect }) => {
const first = await start();
const client = await connect(first.port);
const parent = await client.createAgent({
provider: "claude",
cwd: first.cwd,
modeId: "full-access",
});
const agentId = await createBusyAgent(client, first.paseoHome, first.cwd);
const mcp = new Client({ name: "held-parent", version: "1" });
await mcp.connect(
new StreamableHTTPClientTransport(
new URL(`http://127.0.0.1:${first.port}/mcp/agents?callerAgentId=${parent.id}`),
),
);
await mcp.callTool({
name: "send_agent_prompt",
arguments: { agentId, prompt: "HELD_NOTE", notifyOnFinish: true },
});
await mcp.close();
await client.cancelAgent(agentId);
await expect
.poll(() => readSavedQueue(first.paseoHome, agentId), SETTLE)
.toMatchObject([{ text: "HELD_NOTE", held: true }]);
await client.close();
await stopFixture(first.child, false);
const second = await start();
const restarted = await connect(second.port);
expect(await readSavedQueue(second.paseoHome, agentId)).toMatchObject([{ held: true }]);
await restarted.sendMessage(agentId, "NEXT_PROMPT respond with exactly: FOLLOW_UP_DONE");
// The only notice is for the turn that carried the held message.
await expect.poll(() => readPrompts(root), SETTLE).toHaveLength(1);
await expect.poll(() => readSavedQueue(second.paseoHome, agentId), SETTLE).toEqual([]);
const prompts = await readAllPrompts(root);
const carried = prompts.findIndex((prompt) => prompt.includes("NEXT_PROMPT"));
expect(prompts[carried]).toContain("HELD_NOTE");
expect((await readPrompts(root))[0]).toContain("FOLLOW_UP_DONE");
});
}, 60000);
test("archive and delete drop a recipient's queue, and shutdown keeps it", async () => {
await withDaemons(async ({ root, start, connect }) => {
const first = await start();
const client = await connect(first.port);
const archived = await createBusyAgent(client, first.paseoHome, first.cwd);
const deleted = await createBusyAgent(client, first.paseoHome, first.cwd);
const kept = await createBusyAgent(client, first.paseoHome, first.cwd);
for (const agentId of [archived, deleted, kept])
await client.sendMessage(agentId, `NOTE_FOR_${agentId}`, { activeTurnBehavior: "queue" });
await client.archiveAgent(archived);
await client.deleteAgent(deleted);
await expect.poll(() => readSavedQueue(first.paseoHome, archived), SETTLE).toEqual([]);
await expect.poll(() => readSavedQueue(first.paseoHome, deleted), SETTLE).toEqual([]);
await client.close();
await stopFixture(first.child, false);
expect(await readSavedQueue(first.paseoHome, kept)).toMatchObject([
{ text: `NOTE_FOR_${kept}`, held: false },
]);
expect(await promptsContaining(root, `NOTE_FOR_${archived}`)).toEqual([]);
expect(await promptsContaining(root, `NOTE_FOR_${deleted}`)).toEqual([]);
expect(await promptsContaining(root, `NOTE_FOR_${kept}`)).toEqual([]);
});
}, 60000);
test("a retried queued message is delivered once across a restart, with its image in uploads", async () => {
await withDaemons(async ({ root, start, connect }) => {
const first = await start();
const client = await connect(first.port);
const agentId = await createBusyAgent(client, first.paseoHome, first.cwd);
const imageData = Buffer.from("queued image bytes").toString("base64");
const options = {
messageId: "retried-message",
activeTurnBehavior: "queue" as const,
images: [{ data: imageData, mimeType: "image/png" }],
};
await client.sendMessage(agentId, "RETRIED_NOTE", options);
await client.sendMessage(agentId, "RETRIED_NOTE", options);
const saved = await readSavedQueue(first.paseoHome, agentId);
expect(saved).toMatchObject([
{ text: "RETRIED_NOTE", attachments: [{ type: "uploaded_file", role: "image" }] },
]);
expect(JSON.stringify(saved)).not.toContain(imageData);
await client.close();
await stopFixture(first.child, true);
const second = await start();
await expect.poll(() => promptsContaining(root, "RETRIED_NOTE"), SETTLE).toHaveLength(1);
await expect.poll(() => readSavedQueue(second.paseoHome, agentId), SETTLE).toEqual([]);
const restarted = await connect(second.port);
await restarted.sendMessage(agentId, "RETRIED_NOTE", options);
await restarted.sendMessage(agentId, "AFTER_RETRY", { activeTurnBehavior: "queue" });
await expect.poll(() => promptsContaining(root, "AFTER_RETRY"), SETTLE).toHaveLength(1);
const delivered = await promptsContaining(root, "RETRIED_NOTE");
expect(delivered).toHaveLength(1);
expect(delivered[0]).toContain(imageData);
});
}, 60000);
test("a message the saved timeline holds is not sent again after a crash mid-dispatch", async () => {
await withDaemons(async ({ root, start, connect }) => {
const first = await start();
const client = await connect(first.port);
const agent = await client.createAgent({
provider: "claude",
cwd: first.cwd,
modeId: "full-access",
});
const text = "DELIVERED_ONCE respond with exactly: OK";
await client.sendMessage(agent.id, text, { messageId: "crashed-delivery" });
expect((await client.waitForFinish(agent.id, 15000)).status).toBe("idle");
await client.close();
await stopFixture(first.child, false);
// What a daemon leaves when it dies after the provider took a queued message.
const queuesDir = path.join(first.paseoHome, "agent-queues");
await mkdir(queuesDir, { recursive: true });
await writeFile(
path.join(queuesDir, `${agent.id}.json`),
JSON.stringify({
version: 1,
nextSeq: 2,
items: [
{
id: "crashed-delivery",
recipientId: agent.id,
seq: 1,
enqueuedAt: new Date().toISOString(),
text,
attachments: [],
source: null,
unarchive: true,
clearPendingPermissions: false,
urgency: null,
held: false,
state: "dispatching",
},
],
}),
);
const second = await start();
const restarted = await connect(second.port);
await expect.poll(() => readSavedQueue(second.paseoHome, agent.id), SETTLE).toEqual([]);
expect(await promptsContaining(root, "DELIVERED_ONCE")).toHaveLength(1);
// Reading the saved timeline opened no provider session.
expect((await restarted.fetchAgent(agent.id))?.agent.status).toBe("closed");
});
}, 60000);
@@ -5,7 +5,7 @@ import { basename, extname, isAbsolute, join, relative, sep } from "node:path";
import { FileTransferOpcode, type FileTransferFrame } from "@getpaseo/protocol/binary-frames/index";
import { getErrorMessage } from "@getpaseo/protocol/error-utils";
import type { UploadedImage } from "@getpaseo/protocol/messages";
import type { UploadedFileAttachment, UploadedImage } from "@getpaseo/protocol/messages";
import type { FileUploadRequest, FileUploadResponse } from "../messages.js";
export const MAX_UPLOADED_IMAGE_BYTES = 50 * 1024 * 1024;
@@ -75,6 +75,31 @@ export async function readUploadedImageFile(input: {
}
}
/** Saves an image a client sent inline, so records can name the file instead of its bytes. */
export async function writeUploadedImage(input: {
paseoHome: string;
data: string;
mimeType: string;
}): Promise<UploadedFileAttachment & { role: "image" }> {
const bytes = Buffer.from(input.data, "base64");
const id = `upload_${randomUUID()}`;
const subtype = input.mimeType.split("/")[1]?.replace(/[^a-z0-9]/gi, "") || "bin";
const fileName = `image.${subtype}`;
const directory = join(input.paseoHome, "uploads", id);
const path = join(directory, fileName);
await mkdir(directory, { recursive: true });
await writeFile(path, bytes);
return {
type: "uploaded_file",
role: "image",
id,
fileName,
mimeType: input.mimeType,
size: bytes.byteLength,
path,
};
}
interface FileUploadStoreOptions {
paseoHome: string;
staleUploadTimeoutMs?: number;
@@ -20,18 +20,53 @@ interface SendMessageInput {
send: (beforeDispatch: () => Promise<void>) => Promise<void>;
}
interface AcceptMessageInput {
agentId: string;
messageId: string;
request: unknown;
/** Saves the message with its new owner. */
admit: () => Promise<void>;
}
/** The identity `send` and `accept` compare a retried request against. */
export function fingerprintRequest(request: unknown): string {
return digest(request);
}
/** Owns message delivery receipts; creation is owned by CreationService. */
export class MessageReceipts {
private readonly pending = new Map<string, Promise<void>>();
constructor(private readonly directory: string) {}
send(input: SendMessageInput): Promise<void> {
// Preserve the existing on-disk identity and shape across daemon upgrades.
const key = digest(["send", input.agentId, input.messageId]);
const previous = this.pending.get(key);
const result = (previous ? previous.catch(() => undefined) : Promise.resolve()).then(() =>
this.sendOnce(key, input),
const key = receiptKey(input);
return this.exclusive(key, () => this.sendOnce(key, input));
}
/**
* Hands a message to an owner that delivers it later. A delivered message is not handed over
* again, and no receipt is written until that owner calls `complete`.
*/
accept(input: AcceptMessageInput): Promise<void> {
const key = receiptKey(input);
return this.exclusive(key, async () => {
if (!(await this.isDelivered(key, digest(input.request)))) await input.admit();
});
}
/** Records the delivery of an accepted message, so a client's retry reads as done. */
complete(input: { agentId: string; messageId: string; fingerprint: string }): Promise<void> {
const { agentId, fingerprint } = input;
const key = receiptKey(input);
return this.exclusive(key, () =>
writeJsonFileAtomic(this.file(key), { fingerprint, agentId, state: "completed" }),
);
}
/** One operation per message at a time. */
private exclusive(key: string, action: () => Promise<void>): Promise<void> {
const previous = this.pending.get(key);
const result = (previous ? previous.catch(() => undefined) : Promise.resolve()).then(action);
this.pending.set(key, result);
void result
.finally(() => {
@@ -41,16 +76,23 @@ export class MessageReceipts {
return result;
}
private file(key: string): string {
return path.join(this.directory, `${key}.json`);
}
private async isDelivered(key: string, fingerprint: string): Promise<boolean> {
const existing = await readReceipt(this.file(key));
if (!existing) return false;
if (existing.fingerprint !== fingerprint) throw new Error("agent_request_key_conflict");
if (existing.state === "completed") return true;
// A provider may have accepted the message before its receipt was committed.
throw new Error("agent_request_outcome_unknown");
}
private async sendOnce(key: string, input: SendMessageInput): Promise<void> {
const file = path.join(this.directory, `${key}.json`);
const file = this.file(key);
const fingerprint = digest(input.request);
const existing = await readReceipt(file);
if (existing) {
if (existing.fingerprint !== fingerprint) throw new Error("agent_request_key_conflict");
if (existing.state === "completed") return;
// A provider may have accepted the message before its receipt was committed.
throw new Error("agent_request_outcome_unknown");
}
if (await this.isDelivered(key, fingerprint)) return;
const receipt = { fingerprint, agentId: input.agentId };
let pending: Promise<void> | null = null;
await input.send(() => {
@@ -61,6 +103,11 @@ export class MessageReceipts {
}
}
// Preserve the existing on-disk identity and shape across daemon upgrades.
function receiptKey(input: { agentId: string; messageId: string }): string {
return digest(["send", input.agentId, input.messageId]);
}
async function readReceipt(file: string): Promise<z.infer<typeof ReceiptSchema> | null> {
try {
return ReceiptSchema.parse(JSON.parse(await readFile(file, "utf8")));

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