Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(agent): server-side prompt queueing for agent sessions (#6134)

Wolf Mermelsteinf9b208632510
diff --git a/Cargo.lock b/Cargo.lock
index ab48be1426..9bbee1e59b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -361,6 +361,7 @@ dependencies = [
"macro_uuid",
"memory",
"prompt",
+ "rig-agent",
"serde",
"serde_json",
"sqlx",
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsx
index d0894108cd..32540d8817 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx
@@ -1,17 +1,19 @@
/**
* The block's composer container: reads the composer controller from the
- * session context and drives the dumb `AgentInput` and `QueuedPromptList`
- * with derived props. All block-level state stays on this side of the
- * boundary.
+ * session context and drives the dumb `AgentInput` with derived props. All
+ * block-level state stays on this side of the boundary.
*/
+import { useUserId } from '@core/context/user';
+import { idToDisplayName } from '@core/user/util';
import { Show } from 'solid-js';
import { useAgentSession } from '../context/AgentSessionContext';
import {
AgentInput,
AgentModelSelector,
ComposerNotice,
- QueuedPromptList,
+ type QueuedPromptItem,
+ QueuedPrompts,
} from '../ui';
export function AgentComposer() {
@@ -20,9 +22,32 @@ export function AgentComposer() {
loadFailed,
metadata,
pending,
+ queue,
resuming,
registerQuoteInsert,
} = useAgentSession();
+ const userId = useUserId();
+
+ // Focus plumbing between the input and the queue list above it: Up at the
+ // start of the input lands on the bottom (next-to-dispatch) queue row, and
+ // Down past that row comes back. Plain variables, read only at call time.
+ let focusQueueBottom: (() => void) | undefined;
+ let focusInput: (() => void) | undefined;
+
+ // The server queue's entries, shaped for display: prompt text as-is, and
+ // attribution only when somebody other than the current user queued it —
+ // one's own waiting prompts need no byline.
+ const queuedItems = (): QueuedPromptItem[] =>
+ queue.entries().map((entry) => {
+ const actor = entry.actorUserId ?? undefined;
+ return {
+ actionId: entry.actionId,
+ kind: entry.kind,
+ prompt: entry.prompt ?? undefined,
+ queuedBy:
+ actor && actor !== userId() ? idToDisplayName(actor) : undefined,
+ };
+ });
// A session still being created was created by this user, one action ago,
// and has an empty transcript: the only thing to do with it is type. The
@@ -31,24 +56,43 @@ export function AgentComposer() {
return (
<>
+ <Show when={queuedItems().length > 0}>
+ <div class="pb-1.5">
+ <QueuedPrompts
+ items={queuedItems()}
+ onEdit={(actionId, prompt) => void queue.edit(actionId, prompt)}
+ onRemove={(actionId) => void queue.remove(actionId)}
+ onNavigateBelow={() => focusInput?.()}
+ registerFocusFromBelow={(focus) => {
+ focusQueueBottom = focus;
+ }}
+ />
+ </div>
+ </Show>
<Show when={resuming()}>
<ComposerNotice text="Waking the agent's sandbox…" active />
</Show>
- <QueuedPromptList
- prompts={composer.queue()}
- sendingId={composer.sendingId()}
- failed={composer.sendFailed()}
- onRetry={composer.retry}
- onRemove={composer.remove}
- />
<AgentInput
placeholder="Message the agent, @mention anything"
autofocus={autofocus}
busy={composer.busy()}
- disabled={loadFailed()}
+ // Prompts go straight to the service, so sending needs a session to
+ // post to — a block whose create is still on the wire can be typed
+ // into, but not sent from, until the id lands.
+ disabled={loadFailed() || pending()}
commands={() => metadata()?.availableCommands ?? []}
onSend={composer.send}
onStop={composer.stop}
+ // Installed only while a queue row exists to land on: an installed
+ // handler claims the keys (Up, and the shared plugin's other
+ // leave-at-start keys), which must keep their defaults when there is
+ // nowhere to go.
+ onNavigateUp={
+ queuedItems().length > 0 ? () => focusQueueBottom?.() : undefined
+ }
+ registerFocus={(focus) => {
+ focusInput = focus;
+ }}
registerQuoteInsert={registerQuoteInsert}
modelControl={
<AgentModelSelector
diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
index c4285bb413..7dc5cfe604 100644
--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
@@ -34,6 +34,10 @@ import {
type ComposerController,
createComposerController,
} from './create-composer-controller';
+import {
+ createQueueController,
+ type QueueController,
+} from './create-queue-controller';
import {
createSessionStatusController,
isDisconnected,
@@ -87,6 +91,12 @@ export type AgentSessionState = {
*/
resuming: Accessor<boolean>;
composer: ComposerController;
+ /**
+ * The session's server-side action queue: prompts sent mid-turn wait
+ * there and dispatch one per turn end. The server is the only truth —
+ * nothing is queued client-side.
+ */
+ queue: QueueController;
/**
* Quote selected transcript text into the composer as a referenced paste
* chip. No-op until the composer editor has mounted.
@@ -122,6 +132,10 @@ export function AgentSessionProvider(
// status stream knows when the runtime disconnected without closing it.
// Combining them here is what keeps "working" a single truth.
const working = () => feed.working() && !isDisconnected(status.status());
+ const queue = createQueueController({
+ sessionId,
+ messages: feed.messages,
+ });
const composer = createComposerController({
sessionId,
working,
@@ -141,8 +155,7 @@ export function AgentSessionProvider(
// Anything the service can only deliver over a live transport: a prompt on
// the wire, or a model change waiting to be seen in the fold.
const awaitingRuntime = () =>
- composer.sendingId() !== undefined ||
- composer.changingModel() !== undefined;
+ composer.sending() || composer.changingModel() !== undefined;
const resuming = () => isDisconnected(status.status()) && awaitingRuntime();
return (
@@ -175,6 +188,7 @@ export function AgentSessionProvider(
status: status.status,
resuming,
composer,
+ queue,
quoteSelection,
registerQuoteInsert,
}}
diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.test.ts b/apps/web/src/features/block-agent/context/create-composer-controller.test.ts
index a44de0bc4c..87bf4aea74 100644
--- a/apps/web/src/features/block-agent/context/create-composer-controller.test.ts
+++ b/apps/web/src/features/block-agent/context/create-composer-controller.test.ts
@@ -1,19 +1,15 @@
/**
* @vitest-environment jsdom
*
- * The controller end to end against a mocked harness client: the drain
- * sends, failures latch and retry, prompts queue behind a running turn and
- * flush when it settles, and `awaiting_turn` cannot wedge — it frees on the
- * fold's signal or on the timeout, whichever comes first.
+ * The controller against a mocked harness client: prompts post immediately
+ * (the service owns queueing), failures surface as a toast, stop is latched
+ * per turn, and a pending model change resolves only through the fold.
*/
import { createRoot, createSignal } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ControlOutcome } from '../state/control-message';
-import {
- createComposerController,
- TURN_OBSERVE_TIMEOUT_MS,
-} from './create-composer-controller';
+import { createComposerController } from './create-composer-controller';
const control = vi.hoisted(() => ({
calls: [] as { sessionId: string; action: unknown }[],
@@ -28,19 +24,22 @@ vi.mock('@service-agent-harness/client', () => ({
if (control.outcome === 'reject') throw new Error('network');
return {
isErr: () => control.outcome === 'err',
- // The action id the endpoint returns — the fold's `requestId` for
- // the folded message this action derives. One per call, in order.
- value: `action-${control.calls.length - 1}`,
+ // The control response — the action id is the fold's `requestId`
+ // for the folded message this action derives. One per call, in
+ // order; always `sent` here, queueing is the server's business.
+ value: {
+ actionId: `action-${control.calls.length - 1}`,
+ status: 'sent',
+ },
};
}),
},
}));
-vi.mock('@core/component/Toast/Toast', () => ({
- toast: { failure: vi.fn(), success: vi.fn() },
-}));
+const toast = vi.hoisted(() => ({ failure: vi.fn(), success: vi.fn() }));
+vi.mock('@core/component/Toast/Toast', () => ({ toast }));
-/** Let the drain effect and the awaited POST settle. */
+/** Let the awaited POST settle. */
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
const prompts = () =>
@@ -86,91 +85,50 @@ function setup(options?: {
beforeEach(() => {
control.calls = [];
control.outcome = 'ok';
- vi.useRealTimers();
+ toast.failure.mockClear();
});
-describe('sending while idle', () => {
- it('posts immediately and empties the queue', async () => {
+describe('sending', () => {
+ it('posts immediately', async () => {
const { controller, dispose } = setup();
controller.send('hello');
await flush();
expect(prompts()).toEqual(['hello']);
- expect(controller.queue()).toEqual([]);
+ expect(controller.sending()).toBe(false);
dispose();
});
-});
-describe('failure', () => {
- it('keeps the failed prompt visible at the head and latches the drain', async () => {
- const { controller, dispose } = setup();
- control.outcome = 'err';
- controller.send('doomed');
+ it('posts immediately even while a turn is running — the service queues', async () => {
+ const { controller, dispose } = setup({ working: true });
+ controller.send('one');
+ controller.send('two');
await flush();
- expect(controller.queue().map((p) => p.markdown)).toEqual(['doomed']);
- expect(controller.sendFailed()).toBe(true);
- // The latch holds: no second attempt without user action.
- expect(prompts()).toEqual(['doomed']);
+ expect(prompts()).toEqual(['one', 'two']);
dispose();
});
- it('retry() releases the latch and posts the same prompt again', async () => {
+ it('reports sending while the POST is on the wire', async () => {
const { controller, dispose } = setup();
- control.outcome = 'err';
- controller.send('doomed');
- await flush();
-
- control.outcome = 'ok';
- controller.retry();
- await flush();
-
- expect(prompts()).toEqual(['doomed', 'doomed']);
- expect(controller.queue()).toEqual([]);
- expect(controller.sendFailed()).toBe(false);
- dispose();
- });
-
- it('a new send also releases the latch, and order is preserved', async () => {
- const { controller, setWorking, dispose } = setup();
- control.outcome = 'err';
- controller.send('first');
- await flush();
-
- control.outcome = 'ok';
- controller.send('second');
- await flush();
- // The retried 'first' is awaiting its turn; 'second' correctly holds.
- expect(prompts()).toEqual(['first', 'first']);
+ controller.send('hello');
- setWorking(true); // the fold shows first's turn
- await flush();
- setWorking(false); // ...and it settles
+ expect(controller.sending()).toBe(true);
+ expect(controller.busy()).toBe(true);
await flush();
-
- expect(prompts()).toEqual(['first', 'first', 'second']);
+ expect(controller.sending()).toBe(false);
+ expect(controller.busy()).toBe(false);
dispose();
});
- it('removing the failed prompt clears the failure and unblocks the rest', async () => {
+ it('surfaces a failed POST as a toast', async () => {
const { controller, dispose } = setup();
control.outcome = 'err';
- controller.send('bad');
- await flush();
- control.outcome = 'ok';
- controller.send('good');
- // 'good' releases the latch; make 'bad' fail once more so it latches
- // again with 'good' waiting behind it.
- control.outcome = 'err';
- await flush();
-
- control.outcome = 'ok';
- const failedId = controller.queue()[0]!.id;
- controller.remove(failedId);
+ controller.send('doomed');
await flush();
- expect(prompts().at(-1)).toBe('good');
- expect(controller.queue()).toEqual([]);
+ expect(toast.failure).toHaveBeenCalledWith('Message could not be sent');
+ expect(controller.sending()).toBe(false);
dispose();
});
@@ -180,75 +138,8 @@ describe('failure', () => {
controller.send('offline');
await flush();
- expect(controller.sendFailed()).toBe(true);
- expect(controller.queue().map((p) => p.markdown)).toEqual(['offline']);
- dispose();
- });
-});
-
-describe('queueing behind a running turn', () => {
- it('holds while working and sends when the turn settles', async () => {
- const { controller, setWorking, dispose } = setup({ working: true });
- controller.send('queued');
- await flush();
-
- expect(prompts()).toEqual([]);
- expect(controller.queue().map((p) => p.markdown)).toEqual(['queued']);
-
- setWorking(false);
- await flush();
-
- expect(prompts()).toEqual(['queued']);
- expect(controller.queue()).toEqual([]);
- dispose();
- });
-
- it('sends queued prompts one at a time, in order, across turns', async () => {
- const { controller, setWorking, dispose } = setup({ working: true });
- controller.send('one');
- controller.send('two');
- await flush();
-
- setWorking(false);
- await flush();
- // 'one' posted; the slot is awaiting_turn, so 'two' holds.
- expect(prompts()).toEqual(['one']);
-
- setWorking(true); // the fold shows one's turn
- await flush();
- setWorking(false); // ...and it settles
- await flush();
-
- expect(prompts()).toEqual(['one', 'two']);
- dispose();
- });
-});
-
-describe('awaiting_turn cannot wedge', () => {
- it('frees when the fold reports the turn', async () => {
- const { controller, setWorking, dispose } = setup();
- controller.send('hello');
- await flush();
- expect(controller.busy()).toBe(true); // awaiting_turn
-
- setWorking(true);
- await flush();
- expect(controller.busy()).toBe(true); // now because working
- setWorking(false);
- await flush();
- expect(controller.busy()).toBe(false); // fully idle — no wedge
- dispose();
- });
-
- it('frees on the timeout when no turn ever appears', async () => {
- vi.useFakeTimers();
- const { controller, dispose } = setup();
- controller.send('hello');
- await vi.advanceTimersByTimeAsync(0);
- expect(controller.busy()).toBe(true);
-
- await vi.advanceTimersByTimeAsync(TURN_OBSERVE_TIMEOUT_MS);
- expect(controller.busy()).toBe(false);
+ expect(toast.failure).toHaveBeenCalledWith('Message could not be sent');
+ expect(controller.sending()).toBe(false);
dispose();
});
});
@@ -298,39 +189,9 @@ describe('stop', () => {
});
describe('a session that does not exist yet', () => {
- it('queues prompts typed before the create lands, then drains them in order', async () => {
- const { controller, setWorking, setSessionId, dispose } = setup({
- sessionId: undefined,
- });
- controller.send('first');
- controller.send('second');
- await flush();
-
- // Nothing on the wire: there is nowhere to post to.
- expect(prompts()).toEqual([]);
- expect(controller.queue().map((p) => p.markdown)).toEqual([
- 'first',
- 'second',
- ]);
-
- setSessionId('session-1');
- await flush();
- // The queue survived acquiring the id, and its head went out against it.
- expect(prompts()).toEqual(['first']);
- expect(control.calls.every((c) => c.sessionId === 'session-1')).toBe(true);
-
- setWorking(true); // the fold shows first's turn
- await flush();
- setWorking(false); // ...and it settles
- await flush();
-
- expect(prompts()).toEqual(['first', 'second']);
- expect(controller.queue()).toEqual([]);
- dispose();
- });
-
- it('does not post stop or setModel before there is a session', async () => {
+ it('does not post anything before there is a session', async () => {
const { controller, dispose } = setup({ sessionId: undefined });
+ controller.send('too early');
controller.stop();
controller.setModel('opus');
await flush();
@@ -449,16 +310,16 @@ describe('a model change in flight', () => {
});
describe('session switch', () => {
- it('drops the queue — prompts never leak into another session', async () => {
- const { controller, setSessionId, dispose } = setup({ working: true });
- controller.send('for session-1');
+ it('drops a pending model change — it never leaks into another session', async () => {
+ const { controller, setSessionId, dispose } = setup({ model: 'old-model' });
+ controller.setModel('new-model');
await flush();
+ expect(controller.changingModel()).toBe('new-model');
setSessionId('session-2');
await flush();
- expect(controller.queue()).toEqual([]);
- expect(prompts()).toEqual([]);
+ expect(controller.changingModel()).toBeUndefined();
dispose();
});
});
diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.ts b/apps/web/src/features/block-agent/context/create-composer-controller.ts
index 275f1cb82a..47ef989a51 100644
--- a/apps/web/src/features/block-agent/context/create-composer-controller.ts
+++ b/apps/web/src/features/block-agent/context/create-composer-controller.ts
@@ -1,39 +1,25 @@
/**
- * The Solid shell around the composer model (`state/composer-state.ts`).
+ * The composer's send/stop/model controls.
*
- * One store holds the two facts the controller owns — the prompt queue and
- * the single in-flight POST's phase. The heart is one effect, the drain: on
- * any change it asks `nextAction` what to do and does it. There are no
- * transition events and no phase that waits for a specific event to exit.
- * The one bridge state, `awaiting_turn` (POST accepted, turn not yet visible
- * in the fold), is bounded by a timeout so a turn that never appears cannot
- * wedge the composer.
- *
- * `send` only enqueues. Whether the prompt goes out now or waits for the
- * running turn to settle is entirely the drain's call — the same code path
- * either way, so queueing is not a special case.
+ * Prompt ordering lives in the service: every control POST joins the
+ * session's per-command queue there, so a prompt sent mid-turn waits its
+ * turn on the server, not in the client. `send` therefore posts
+ * immediately, and the only state kept here is what the UI needs to show —
+ * a prompt POST on the wire, a stop underway, a model change waiting to be
+ * seen in the fold.
*/
import { toast } from '@core/component/Toast/Toast';
import { agentHarnessServiceClient } from '@service-agent-harness/client';
-import { type Accessor, batch, createEffect, onCleanup } from 'solid-js';
+import { type Accessor, batch, createEffect } from 'solid-js';
import { createStore } from 'solid-js/store';
-import {
- isBusy,
- nextAction,
- type PostPhase,
- type QueuedPrompt,
-} from '../state/composer-state';
import type { ControlOutcome } from '../state/control-message';
export type ComposerController = {
- /** Prompts waiting to be sent, oldest first. The head sends next. */
- queue: Accessor<QueuedPrompt[]>;
- /** The prompt currently on the wire or awaiting its turn, if any. */
- sendingId: Accessor<string | undefined>;
- /** The head prompt failed to post and is held for retry. */
- sendFailed: Accessor<boolean>;
- /** A turn is running or a post is starting one — the stop affordance shows. */
+ /** A prompt POST is on the wire. */
+ sending: Accessor<boolean>;
+ /** A turn is running or a prompt is on its way to start one — the stop
+ * affordance shows. */
busy: Accessor<boolean>;
/**
* A model change is on the wire: the id requested, until the fold shows the
@@ -46,33 +32,19 @@ export type ComposerController = {
* evidence anything is happening at all.
*/
changingModel: Accessor<string | undefined>;
+ /** Post the prompt. No-op without a session — the input disables until
+ * there is one. */
send: (markdown: string) => void;
- /** Release a failed head so the drain tries it again. */
- retry: () => void;
- /** Drop a queued prompt. Dropping the failed head clears the failure. */
- remove: (promptId: string) => void;
stop: () => void;
/** Ask the agent to run on a different model from here on. */
setModel: (model: string) => void;
};
-/**
- * How long `awaiting_turn` waits for the fold to show the posted turn before
- * giving up and freeing the post slot. Normally the prompt frame echoes back
- * within milliseconds of the POST ack; this only fires when the runtime or
- * the socket has genuinely gone quiet.
- */
-export const TURN_OBSERVE_TIMEOUT_MS = 10_000;
-
export function createComposerController(options: {
/** The fold's current model, which is how a model change is seen to land. */
model?: Accessor<string | null | undefined>;
- /**
- * Absent until a just-created session's `POST` lands
- * (`context/pending-session.ts`). Prompts typed before then queue and
- * drain themselves when it arrives — that is the whole point of `send`
- * only enqueueing.
- */
+ /** Absent until a just-created session's `POST` lands
+ * (`context/pending-session.ts`). */
sessionId: Accessor<string | undefined>;
/** The block's one working signal — see `AgentSessionContext`. */
working: Accessor<boolean>;
@@ -86,8 +58,8 @@ export function createComposerController(options: {
controlOutcome?: (requestId: string) => ControlOutcome | undefined;
}): ComposerController {
const [state, setState] = createStore<{
- queue: QueuedPrompt[];
- post: PostPhase;
+ /** Prompt POSTs on the wire. A count, not a flag: sends can overlap. */
+ inflightPrompts: number;
/** The model a `setModel` is currently asking for. */
requestedModel: string | undefined;
/**
@@ -103,30 +75,26 @@ export function createComposerController(options: {
*/
stopping: boolean;
}>({
- queue: [],
- post: { type: 'idle' },
+ inflightPrompts: 0,
requestedModel: undefined,
requestedActionId: undefined,
stopping: false,
});
- const postHead = async (sessionId: string, prompt: QueuedPrompt) => {
- setState('post', { type: 'posting', promptId: prompt.id });
+ const postPrompt = async (sessionId: string, markdown: string) => {
+ setState('inflightPrompts', (count) => count + 1);
const result = await agentHarnessServiceClient
- .control(sessionId, { type: 'prompt', prompt: prompt.markdown })
+ .control(sessionId, { type: 'prompt', prompt: markdown })
.catch(() => undefined);
-
+ // Floored: a session switch resets the count while this POST is still
+ // out, and its settle must not drive the new session's count negative.
+ setState('inflightPrompts', (count) => Math.max(0, count - 1));
if (result === undefined || result.isErr()) {
- // The prompt stays at the head of the queue — visible and retryable,
- // never dropped. The latch stops the drain until the user acts.
- setState('post', { type: 'failed', promptId: prompt.id });
toast.failure('Message could not be sent');
- return;
}
- batch(() => {
- setState('queue', (queue) => queue.filter((p) => p.id !== prompt.id));
- setState('post', { type: 'awaiting_turn', promptId: prompt.id });
- });
+ // A 200 with status `queued` means the prompt waits in the session's
+ // server-side queue; the gateway publishes the queue, so nothing more
+ // to do here.
};
const postSetModel = async (sessionId: string, model: string) => {
@@ -148,7 +116,7 @@ export function createComposerController(options: {
// `model`, a rejected one resolves this id's control outcome, and the
// effects below watch for whichever comes.
if (state.requestedModel === model) {
- setState('requestedActionId', result.value);
+ setState('requestedActionId', result.value.actionId);
}
};
@@ -161,26 +129,10 @@ export function createComposerController(options: {
toast.failure('The agent could not be stopped');
}
// Success is observed through the fold: the turn settles and `working`
- // flips false, which re-runs the drain and releases the latch.
+ // flips false, which releases the latch.
};
- // The drain: whenever any fact changes, ask the model what to do and do
- // it. Deciding from present facts — rather than reacting to event edges —
- // is what makes this wedge-proof: there is no exit event to miss.
- createEffect(() => {
- const sessionId = options.sessionId();
- const action = nextAction({
- post: state.post,
- head: state.queue[0],
- agentWorking: options.working(),
- sessionExists: sessionId !== undefined,
- });
- // `sessionExists` is what makes the id below sound: the drain cannot
- // choose to post without one.
- if (action.type === 'post_head' && sessionId) {
- void postHead(sessionId, action.prompt);
- }
- });
+ const busy = () => options.working() || state.inflightPrompts > 0;
// A model change is done when the fold says the runtime moved, not when
// the POST returns. Also clears when the runtime settles somewhere else
@@ -216,22 +168,6 @@ export function createComposerController(options: {
toast.failure(`Couldn't switch to ${requested}`);
});
- // `awaiting_turn` resolves on whichever comes first: the fold reports the
- // turn (`working` flips true), or the timeout gives up. Either way the
- // post slot frees and the drain re-decides from there.
- createEffect(() => {
- if (state.post.type !== 'awaiting_turn') return;
- if (options.working()) {
- setState('post', { type: 'idle' });
- return;
- }
- const timer = setTimeout(
- () => setState('post', { type: 'idle' }),
- TURN_OBSERVE_TIMEOUT_MS
- );
- onCleanup(() => clearTimeout(timer));
- });
-
// The stop is done when the fold says the turn is no longer running. The
// release is read off `working` rather than off the POST returning, because
// the POST only means the cancel was accepted, not that the turn is over.
@@ -239,16 +175,14 @@ export function createComposerController(options: {
if (!options.working()) setState('stopping', false);
});
- // A session switch resets the composer: queued prompts belong to the
- // session they were typed in, never the next one.
+ // A session switch resets the composer: a pending model change or stop
+ // belongs to the session it was issued in, never the next one.
//
// Acquiring an id is not a switch. A block that opened on a placeholder
- // goes `undefined -> id` when its create lands, and everything typed
- // during the wait was typed for exactly that session — wiping it there is
- // the one thing that would make typing early pointless. The previous id is
- // tracked by hand rather than read from `on`'s `prevInput`, which a
- // deferred `on` leaves undefined through the first change and so cannot
- // tell the two apart.
+ // goes `undefined -> id` when its create lands. The previous id is tracked
+ // by hand rather than read from `on`'s `prevInput`, which a deferred `on`
+ // leaves undefined through the first change and so cannot tell the two
+ // apart.
let previousSessionId = options.sessionId();
createEffect(() => {
const sessionId = options.sessionId();
@@ -257,8 +191,9 @@ export function createComposerController(options: {
previousSessionId = sessionId;
if (acquired) return;
setState({
- queue: [],
- post: { type: 'idle' },
+ // A send still on the wire belongs to the previous session; its
+ // eventual settle must not keep this one's stop control up.
+ inflightPrompts: 0,
requestedModel: undefined,
requestedActionId: undefined,
stopping: false,
@@ -266,41 +201,18 @@ export function createComposerController(options: {
});
return {
- queue: () => state.queue,
- sendingId: () =>
- state.post.type === 'posting' || state.post.type === 'awaiting_turn'
- ? state.post.promptId
- : undefined,
- sendFailed: () => state.post.type === 'failed',
- busy: () => isBusy(state.post, options.working()),
+ sending: () => state.inflightPrompts > 0,
+ busy,
changingModel: () => state.requestedModel,
send: (markdown) => {
- batch(() => {
- setState('queue', (queue) => [
- ...queue,
- { id: crypto.randomUUID(), markdown },
- ]);
- // A new message is intent to continue: release a failed head so the
- // drain retries it (in order) rather than holding everything behind
- // a stale failure.
- if (state.post.type === 'failed') setState('post', { type: 'idle' });
- });
- },
- retry: () => {
- if (state.post.type === 'failed') setState('post', { type: 'idle' });
- },
- remove: (promptId) => {
- batch(() => {
- setState('queue', (queue) => queue.filter((p) => p.id !== promptId));
- if (state.post.type === 'failed' && state.post.promptId === promptId) {
- setState('post', { type: 'idle' });
- }
- });
+ const sessionId = options.sessionId();
+ if (!sessionId) return;
+ void postPrompt(sessionId, markdown);
},
stop: () => {
const sessionId = options.sessionId();
if (!sessionId) return;
- if (!isBusy(state.post, options.working()) || state.stopping) return;
+ if (!busy() || state.stopping) return;
setState('stopping', true);
void postStop(sessionId);
},
diff --git a/apps/web/src/features/block-agent/context/create-queue-controller.ts b/apps/web/src/features/block-agent/context/create-queue-controller.ts
new file mode 100644
index 0000000000..260302cea3
--- /dev/null
+++ b/apps/web/src/features/block-agent/context/create-queue-controller.ts
@@ -0,0 +1,152 @@
+/**
+ * The composer's view of the session's server-side action queue.
+ *
+ * The queue is the server's: prompts and compacts sent while a turn runs
+ * wait there and dispatch one per turn end. Nothing is queued or predicted
+ * client-side, and nothing polls. The gateway publishes the whole queue on
+ * every mutation (`agent_session_queue`), so the controller reads the REST
+ * endpoint exactly once per socket session as a baseline — on load and again
+ * on websocket reconnect — and after the first event arrives on the current
+ * socket the socket is the only writer: any GET still in flight is
+ * discarded, no further GETs are issued (own mutations included — the server
+ * publishes for those too), and the last event wins unconditionally.
+ */
+
+import { toast } from '@core/component/Toast/Toast';
+import {
+ subscribeAgentSessionQueue,
+ subscribeSocketSessionStarted,
+} from '@queries/agent-session/queue-sync';
+import type { FoldedMessage } from '@service-agent-fold/generated/types';
+import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import type { QueuedActionDto } from '@service-agent-harness/generated/schemas';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onCleanup,
+ untrack,
+} from 'solid-js';
+
+export type QueueController = {
+ /**
+ * The actions still waiting, oldest first, minus any the fold already
+ * shows. An entry whose `actionId` matches a folded message's `requestId`
+ * has dispatched — the transcript renders it, so the queue must not.
+ */
+ entries: Accessor<QueuedActionDto[]>;
+ /** Replace a queued prompt's text. A 404 means it already dispatched —
+ * the gateway's snapshot reconciles it, not an error. */
+ edit: (actionId: string, prompt: string) => Promise<void>;
+ /** Remove a queued action. Same 404 semantics as `edit`. */
+ remove: (actionId: string) => Promise<void>;
+};
+
+export function createQueueController(options: {
+ /** Absent until a just-created session's `POST` lands. */
+ sessionId: Accessor<string | undefined>;
+ /** The folded transcript: the dedupe source for dispatched entries. */
+ messages: Accessor<FoldedMessage[]>;
+}): QueueController {
+ const [queued, setQueued] = createSignal<QueuedActionDto[]>([]);
+
+ // Whether an `agent_session_queue` event has arrived for this session on
+ // the current socket session. Once true the socket is the only writer:
+ // baseline responses are discarded and no further GETs go out. Reset when
+ // the socket reopens (events may have been missed) or the session changes.
+ //
+ // The one latch is the whole reconciliation. An event is always the full
+ // queue, so events need no ordering among themselves, and a baseline
+ // response identifies itself by the session it was fetched for.
+ let socketAuthoritative = false;
+
+ const baseline = async () => {
+ const sessionId = untrack(options.sessionId);
+ if (!sessionId) return;
+ const result = await agentHarnessServiceClient
+ .queue(sessionId)
+ .catch(() => undefined);
+ // Discarded when an event beat it here, or when it answers for a session
+ // this block no longer shows. A failed baseline keeps the last known
+ // entries; the next socket event or reconnect supersedes it anyway.
+ if (socketAuthoritative || sessionId !== untrack(options.sessionId)) return;
+ if (result === undefined || result.isErr()) return;
+ setQueued(result.value.entries);
+ };
+
+ // A session switch drops the old session's entries immediately — they were
+ // never this session's — then baselines the new one.
+ createEffect(
+ on(options.sessionId, () => {
+ socketAuthoritative = false;
+ setQueued([]);
+ void baseline();
+ })
+ );
+
+ // The gateway always wins: every event is the full queue, last one in is
+ // the truth, and hearing anything on this socket retires the baseline GET.
+ onCleanup(
+ subscribeAgentSessionQueue((event) => {
+ if (event.agentSessionId !== untrack(options.sessionId)) return;
+ socketAuthoritative = true;
+ setQueued(event.entries);
+ })
+ );
+
+ // A reopened socket is a new socket session: events may have been missed
+ // while it was down, so re-baseline once and let events take over again.
+ onCleanup(
+ subscribeSocketSessionStarted(() => {
+ socketAuthoritative = false;
+ baseline();
+ })
+ );
+
+ const dispatchedIds = createMemo(() => {
+ const ids = new Set<string>();
+ for (const message of options.messages()) {
+ if (message.requestId != null) ids.add(message.requestId);
+ }
+ return ids;
+ });
+
+ const isDispatched = (
+ result: Awaited<ReturnType<typeof agentHarnessServiceClient.removeQueued>>
+ ) =>
+ result.isErr() && result.error.some((error) => error.code === 'NOT_FOUND');
+
+ // No refetch after either mutation: the server publishes a snapshot for
+ // every accepted change, and a 404 means the entry dispatched — the
+ // dispatch's own snapshot (and the fold dedupe) already retire the row.
+ const edit = async (actionId: string, prompt: string) => {
+ const sessionId = untrack(options.sessionId);
+ if (!sessionId) return;
+ const result = await agentHarnessServiceClient
+ .editQueued(sessionId, actionId, prompt)
+ .catch(() => undefined);
+ if (result === undefined || (result.isErr() && !isDispatched(result))) {
+ toast.failure('The queued message could not be edited');
+ }
+ };
+
+ const remove = async (actionId: string) => {
+ const sessionId = untrack(options.sessionId);
+ if (!sessionId) return;
+ const result = await agentHarnessServiceClient
+ .removeQueued(sessionId, actionId)
+ .catch(() => undefined);
+ if (result === undefined || (result.isErr() && !isDispatched(result))) {
+ toast.failure('The queued message could not be removed');
+ }
+ };
+
+ return {
+ entries: () =>
+ queued().filter((entry) => !dispatchedIds().has(entry.actionId)),
+ edit,
+ remove,
+ };
+}
diff --git a/apps/web/src/features/block-agent/debug/replay/driver.ts b/apps/web/src/features/block-agent/debug/replay/driver.ts
index 6d7ed1bffd..aa875e3026 100644
--- a/apps/web/src/features/block-agent/debug/replay/driver.ts
+++ b/apps/web/src/features/block-agent/debug/replay/driver.ts
@@ -168,9 +168,10 @@ export function createReplayDriver(options: ReplayDriverOptions): ReplayDriver {
}
// Every other action — stop, permissions — acks and does nothing:
// their observable effects come from frames, which playback owns. The
- // id is what the real endpoint returns; replay frames never carry it,
- // so nothing correlates against it.
- return ok(`replay-action-${cursor()}`);
+ // response is what the real endpoint returns; replay frames never
+ // carry the id, so nothing correlates against it, and replay has no
+ // queue, so everything is `sent`.
+ return ok({ actionId: `replay-action-${cursor()}`, status: 'sent' });
},
};
diff --git a/apps/web/src/features/block-agent/debug/replay/interceptor.ts b/apps/web/src/features/block-agent/debug/replay/interceptor.ts
index f83f0c93e8..eb2be00ac5 100644
--- a/apps/web/src/features/block-agent/debug/replay/interceptor.ts
+++ b/apps/web/src/features/block-agent/debug/replay/interceptor.ts
@@ -10,6 +10,7 @@
import { agentHarnessServiceClient } from '@service-agent-harness/client';
import type { ControlRequest } from '@service-agent-harness/generated/schemas';
+import { ok } from 'neverthrow';
type Client = typeof agentHarnessServiceClient;
@@ -37,6 +38,11 @@ function ensurePatched(): void {
if (backend) return backend.control(request);
return real.control(sessionId, request);
};
+ // Replay has no server-side queue: every control acks as `sent`, so the
+ // queue is always empty rather than a fall-through to a session the
+ // service has never heard of.
+ agentHarnessServiceClient.queue = async (sessionId) =>
+ backends.has(sessionId) ? ok({ entries: [] }) : real.queue(sessionId);
// `delete` stays real: a replay session has nothing behind it to delete.
}
diff --git a/apps/web/src/features/block-agent/state/composer-state.test.ts b/apps/web/src/features/block-agent/state/composer-state.test.ts
deleted file mode 100644
index c6e598c4d5..0000000000
--- a/apps/web/src/features/block-agent/state/composer-state.test.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- type ComposerFacts,
- isBusy,
- nextAction,
- type QueuedPrompt,
-} from './composer-state';
-
-const prompt = (id: string): QueuedPrompt => ({ id, markdown: `p-${id}` });
-
-const facts = (overrides: Partial<ComposerFacts>): ComposerFacts => ({
- post: { type: 'idle' },
- head: undefined,
- agentWorking: false,
- sessionExists: true,
- ...overrides,
-});
-
-describe('nextAction: before the session exists', () => {
- it('holds the head until the create lands', () => {
- const waiting = facts({ head: prompt('a'), sessionExists: false });
- expect(nextAction(waiting).type).toBe('hold');
- expect(nextAction(facts({ head: prompt('a') }))).toEqual({
- type: 'post_head',
- prompt: prompt('a'),
- });
- });
-
- it('outranks every other hold — nothing can post to nowhere', () => {
- const action = nextAction(
- facts({
- head: prompt('a'),
- sessionExists: false,
- post: { type: 'failed', promptId: 'a' },
- agentWorking: true,
- })
- );
- expect(action.type).toBe('hold');
- });
-});
-
-describe('nextAction: when the head sends', () => {
- it('idle, agent idle, something queued → post the head', () => {
- const action = nextAction(facts({ head: prompt('a') }));
- expect(action).toEqual({ type: 'post_head', prompt: prompt('a') });
- });
-
- it('nothing queued → hold', () => {
- expect(nextAction(facts({})).type).toBe('hold');
- });
-});
-
-describe('nextAction: every hold, by priority', () => {
- it('a post on the wire holds, even with a head and an idle agent', () => {
- const action = nextAction(
- facts({ post: { type: 'posting', promptId: 'a' }, head: prompt('b') })
- );
- expect(action).toMatchObject({
- type: 'hold',
- reason: 'a post is on the wire',
- });
- });
-
- it('awaiting the turn holds — the drain must not fire into the same turn', () => {
- const action = nextAction(
- facts({
- post: { type: 'awaiting_turn', promptId: 'a' },
- head: prompt('b'),
- })
- );
- expect(action.type).toBe('hold');
- });
-
- it('a failed head holds everything behind it — order is preserved', () => {
- const action = nextAction(
- facts({ post: { type: 'failed', promptId: 'a' }, head: prompt('a') })
- );
- expect(action.type).toBe('hold');
- });
-
- it('a running turn holds a queued prompt until it settles', () => {
- const action = nextAction(facts({ head: prompt('a'), agentWorking: true }));
- expect(action).toMatchObject({
- type: 'hold',
- reason: 'the agent is mid-turn',
- });
- });
-});
-
-describe('nextAction: the wedges the old machine allowed', () => {
- it('a prompt queued while idle sends — nothing waits for a turn_settled that will never come', () => {
- // Old bug: post_failed returned to idle with the prompt re-queued, but
- // only working+turn_settled ever flushed the queue.
- const action = nextAction(facts({ head: prompt('stranded') }));
- expect(action.type).toBe('post_head');
- });
-
- it('the decision is memoryless: the same facts always produce the same action', () => {
- const same = facts({ head: prompt('a') });
- expect(nextAction(same)).toEqual(nextAction(same));
- });
-});
-
-describe('isBusy', () => {
- it('working, posting, and awaiting_turn are busy', () => {
- expect(isBusy({ type: 'idle' }, true)).toBe(true);
- expect(isBusy({ type: 'posting', promptId: 'a' }, false)).toBe(true);
- expect(isBusy({ type: 'awaiting_turn', promptId: 'a' }, false)).toBe(true);
- });
-
- it('idle and failed are not — a failure hands the send button back', () => {
- expect(isBusy({ type: 'idle' }, false)).toBe(false);
- expect(isBusy({ type: 'failed', promptId: 'a' }, false)).toBe(false);
- });
-});
diff --git a/apps/web/src/features/block-agent/state/composer-state.ts b/apps/web/src/features/block-agent/state/composer-state.ts
deleted file mode 100644
index 92fff44b15..0000000000
--- a/apps/web/src/features/block-agent/state/composer-state.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-/**
- * The composer's queue-and-send model, as pure decisions over present facts.
- *
- * The previous machine (`session-state.ts`) accumulated a phase from events
- * (`turn_started`, `post_succeeded`, ...) and could wedge in a phase whose
- * exit event never arrived. This model keeps no event history. Two facts are
- * owned — the prompt queue and the lifecycle of the single in-flight POST —
- * and `nextAction` derives the one thing to do from what is true *right
- * now*. The Solid shell (`context/create-composer-controller.ts`) re-runs it
- * whenever any fact changes, so nothing can get stuck: if a fact changes,
- * the decision changes. This is opencode's followup-drain shape
- * (`pages/session.tsx` — a guard list, not a transition table).
- *
- * Sending is one prompt at a time, head of the queue first. A failed head
- * stays in the queue behind a `failed` latch — visible, retryable, never
- * silently dropped — and holds everything queued behind it so order is
- * preserved.
- */
-
-import { match, P } from 'ts-pattern';
-
-/** A prompt waiting to be sent. Client-minted id, so rows are stable. */
-export type QueuedPrompt = {
- id: string;
- markdown: string;
-};
-
-/**
- * The lifecycle of the single in-flight POST. At most one prompt is ever on
- * the wire; everything else waits in the queue.
- */
-export type PostPhase =
- /** Nothing on the wire. The drain may send the queue's head. */
- | { type: 'idle' }
- /** The head prompt's POST is on the wire. */
- | { type: 'posting'; promptId: string }
- /**
- * The POST was accepted but the fold has not yet shown the turn it
- * starts. Held so the drain does not fire again into the same turn; freed
- * by the fold reporting the turn — or by a timeout, so a turn that never
- * appears cannot wedge the composer.
- */
- | { type: 'awaiting_turn'; promptId: string }
- /**
- * The head prompt's POST failed. It stays at the head of the queue; this
- * latch stops the drain until the user retries, removes it, or sends a
- * new message (which also retries).
- */
- | { type: 'failed'; promptId: string };
-
-/** Everything `nextAction` is allowed to look at. */
-export type ComposerFacts = {
- post: PostPhase;
- /** The queue's head — the only prompt that can send next. */
- head: QueuedPrompt | undefined;
- /** The block's one working signal (fold ∧ not disconnected). */
- agentWorking: boolean;
- /**
- * There is a session to post to. False on a just-created block whose
- * `POST /agent-sessions` has not answered yet: the user can type and queue
- * from the first frame, and the queue drains itself the moment the session
- * exists. Absence of a session is a hold like any other, not a special
- * case the composer has to be told about.
- */
- sessionExists: boolean;
-};
-
-export type ComposerAction =
- | { type: 'post_head'; prompt: QueuedPrompt }
- | { type: 'hold'; reason: string };
-
-const hold = (reason: string): ComposerAction => ({ type: 'hold', reason });
-
-/**
- * The drain decision: given the facts, either send the queue's head or name
- * the reason not to. Every guard is one line; the order is the priority.
- */
-export function nextAction(facts: ComposerFacts): ComposerAction {
- return match(facts)
- .with({ sessionExists: false }, () =>
- hold('the session has not been created yet')
- )
- .with({ post: { type: 'posting' } }, () => hold('a post is on the wire'))
- .with({ post: { type: 'awaiting_turn' } }, () =>
- hold('posted; the fold has not shown the turn yet')
- )
- .with({ post: { type: 'failed' } }, () =>
- hold('the head prompt failed; waiting for retry, edit, or a new send')
- )
- .with({ agentWorking: true }, () => hold('the agent is mid-turn'))
- .with({ head: P.select(P.nonNullable) }, (head) => ({
- type: 'post_head' as const,
- prompt: head,
- }))
- .otherwise(() => hold('nothing queued'));
-}
-
-/**
- * Whether the stop affordance shows: a turn is running, or a post is in the
- * middle of starting one. A failed post is *not* busy — the user needs the
- * send button back to retry.
- */
-export function isBusy(post: PostPhase, agentWorking: boolean): boolean {
- return (
- agentWorking || post.type === 'posting' || post.type === 'awaiting_turn'
- );
-}
diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsx
index 081dc0ed94..155a200496 100644
--- a/apps/web/src/features/block-agent/ui/AgentInput.tsx
+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx
@@ -39,6 +39,16 @@ export interface AgentInputProps {
* chip can quote selected text into this composer.
*/
registerQuoteInsert?: (insert: QuoteInsert | undefined) => void;
+ /**
+ * Up (or Shift+Tab/Left, the app's focus-leave convention) at the very
+ * start of the input: focus moves to whatever sits above — the queued
+ * prompt about to dispatch. Ordinary in-text cursor movement never
+ * triggers it.
+ */
+ onNavigateUp?: () => void;
+ /** Ref-style: how the queue's Down-past-the-end refocuses this input;
+ * `undefined` again on unmount. */
+ registerFocus?: (focus: (() => void) | undefined) => void;
}
/** Past this height the controls drop below the text instead of overlaying it. */
@@ -48,8 +58,8 @@ export function AgentInput(props: AgentInputProps) {
const [markdown, setMarkdown] = createSignal('');
let bodyRef: HTMLDivElement | undefined;
- // Sending while busy is allowed — the block queues prompts and flushes
- // them when the running turn settles.
+ // Sending while busy is allowed — the service queues prompts behind the
+ // running turn.
const canSend = () => markdown().trim().length > 0 && !props.disabled;
// Same content-driven switch as ChatInput: once the editor body wraps past
@@ -83,9 +93,20 @@ export function AgentInput(props: AgentInputProps) {
send();
return true;
})
+ .onFocusLeave({
+ onStart: (event) => {
+ if (!props.onNavigateUp) return;
+ event.preventDefault();
+ props.onNavigateUp();
+ },
+ // Nothing sits below the input; the key keeps its default behavior.
+ onEnd: () => {},
+ })
.onChange(setMarkdown);
onMount(() => {
+ props.registerFocus?.(() => editor.controls.focus());
+ onCleanup(() => props.registerFocus?.(undefined));
props.registerQuoteInsert?.((text) => {
// Discrete so the chip is committed to the DOM before focus moves in.
editor.lexical.update(() => $insertReferencedPaste(text), {
diff --git a/apps/web/src/features/block-agent/ui/QueuedPromptList.tsx b/apps/web/src/features/block-agent/ui/QueuedPromptList.tsx
deleted file mode 100644
index d856ee9f95..0000000000
--- a/apps/web/src/features/block-agent/ui/QueuedPromptList.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * Prompts waiting to be sent, shown above the composer so a queued message
- * is never invisible: the user can see it, remove it, and — when the send
- * failed — retry it. Pure component: props in, JSX out.
- */
-
-import ArrowClockwise from '@phosphor/arrow-clockwise.svg';
-import X from '@phosphor/x.svg';
-import { Button } from '@ui';
-import { For, Show } from 'solid-js';
-
-export interface QueuedPromptListProps {
- prompts: { id: string; markdown: string }[];
- /** The prompt currently on the wire — its row reads "Sending". */
- sendingId?: string;
- /** The head prompt failed to send — its row reads "Failed" with a retry. */
- failed?: boolean;
- onRetry?: () => void;
- onRemove?: (id: string) => void;
-}
-
-/** The first non-empty line, for a one-line preview of a markdown prompt. */
-function firstLine(markdown: string): string {
- return (
- markdown
- .split('\n')
- .map((line) => line.trim())
- .find((line) => line.length > 0) ?? markdown
- );
-}
-
-export function QueuedPromptList(props: QueuedPromptListProps) {
- return (
- <Show when={props.prompts.length > 0}>
- <div class="flex flex-col gap-1 pb-2">
- <For each={props.prompts}>
- {(prompt, index) => {
- const failed = () => props.failed === true && index() === 0;
- const sending = () => props.sendingId === prompt.id;
- return (
- <div class="flex items-center gap-2 rounded-lg border border-edge-muted bg-hover px-3 py-1.5 text-sm">
- <span class="min-w-0 flex-1 truncate text-ink-muted">
- {firstLine(prompt.markdown)}
- </span>
- <Show when={sending()}>
- <span class="shrink-0 text-xs text-ink-extra-muted">
- Sending
- </span>
- </Show>
- <Show when={failed()}>
- <span class="shrink-0 text-xs text-ink">Failed</span>
- <Button
- variant="ghost"
- size="icon-xs"
- label="Retry"
- onClick={() => props.onRetry?.()}
- >
- <ArrowClockwise />
- </Button>
- </Show>
- <Show when={!sending()}>
- <Button
- variant="ghost"
- size="icon-xs"
- label="Remove"
- onClick={() => props.onRemove?.(prompt.id)}
- >
- <X />
- </Button>
- </Show>
- </div>
- );
- }}
- </For>
- </div>
- </Show>
- );
-}
diff --git a/apps/web/src/features/block-agent/ui/QueuedPrompts.tsx b/apps/web/src/features/block-agent/ui/QueuedPrompts.tsx
new file mode 100644
index 0000000000..8dc7cae991
--- /dev/null
+++ b/apps/web/src/features/block-agent/ui/QueuedPrompts.tsx
@@ -0,0 +1,266 @@
+/**
+ * The list of actions waiting in the session's server-side queue, rendered
+ * between the transcript and the input.
+ *
+ * Rendered newest-at-top: the next prompt to dispatch (the oldest) sits at
+ * the bottom, immediately above the composer, so Up from the input lands on
+ * "the one about to be sent" and further Up presses walk toward the newest.
+ *
+ * Each prompt row is a live Lexical surface, always editable in place —
+ * edits debounce and autosave through `onEdit`, with a flush on blur; there
+ * are no save/cancel affordances. Non-prompt entries (compact) are
+ * read-only text but keep their remove affordance, which is always visible.
+ */
+
+import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
+import XIcon from '@phosphor-icons/core/regular/x.svg?component-solid';
+import { Button, Surface } from '@ui';
+import {
+ createEffect,
+ createMemo,
+ For,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
+
+export type QueuedPromptItem = {
+ /** The id the action was accepted under — the row's identity. */
+ actionId: string;
+ /** `prompt` or `compact`; only prompts carry text and can be edited. */
+ kind: string;
+ /** The prompt's raw text, absent for a compact. */
+ prompt?: string;
+ /** Who queued it, when it was somebody other than the current user. */
+ queuedBy?: string;
+};
+
+export interface QueuedPromptsProps {
+ /** In dispatch order — oldest (next to send) first, as the server reports. */
+ items: QueuedPromptItem[];
+ /** Autosave a queued prompt's replacement text. The rows debounce. */
+ onEdit: (actionId: string, prompt: string) => void;
+ /** Remove a queued action before it dispatches. */
+ onRemove: (actionId: string) => void;
+ /** Down past the bottom (next-to-send) row — focus returns to the composer. */
+ onNavigateBelow?: () => void;
+ /**
+ * Ref-style: receives a function that focuses the bottom row (the next
+ * prompt to dispatch) — the composer's Up-at-start target — and
+ * `undefined` again on unmount.
+ */
+ registerFocusFromBelow?: (focus: (() => void) | undefined) => void;
+}
+
+/** How long typing pauses before the row autosaves. */
+const AUTOSAVE_DEBOUNCE_MS = 400;
+
+export function QueuedPrompts(props: QueuedPromptsProps) {
+ // Reversed for render: newest at the top, next-to-dispatch at the bottom.
+ // `For` keys on the id strings, so a snapshot that only re-orders or edits
+ // never remounts a row (and never drops an editor mid-keystroke).
+ const orderedIds = createMemo(() =>
+ props.items.map((item) => item.actionId).reverse()
+ );
+ const itemById = (id: string) =>
+ props.items.find((item) => item.actionId === id);
+
+ const focusFns = new Map<string, () => void>();
+ const focusAt = (index: number) => {
+ const id = orderedIds()[index];
+ if (id) focusFns.get(id)?.();
+ };
+ /** Walk focus up (-1, toward newest) or down (+1, toward the composer). */
+ const moveFocus = (id: string, delta: 1 | -1) => {
+ const ids = orderedIds();
+ const index = ids.indexOf(id);
+ if (index < 0) return;
+ const next = index + delta;
+ if (next >= ids.length) {
+ props.onNavigateBelow?.();
+ return;
+ }
+ if (next >= 0) focusAt(next);
+ };
+
+ onMount(() => {
+ props.registerFocusFromBelow?.(() => focusAt(orderedIds().length - 1));
+ onCleanup(() => props.registerFocusFromBelow?.(undefined));
+ });
+
+ return (
+ <div class="flex flex-col gap-1" data-testid="agent-queued-prompts">
+ <For each={orderedIds()}>
+ {(id) => (
+ <Show when={itemById(id)}>
+ {(item) => (
+ <QueuedRow
+ item={item()}
+ registerFocus={(focus) => {
+ if (focus) focusFns.set(id, focus);
+ else focusFns.delete(id);
+ }}
+ onMoveUp={() => moveFocus(id, -1)}
+ onMoveDown={() => moveFocus(id, 1)}
+ onEdit={(prompt) => props.onEdit(id, prompt)}
+ onRemove={() => props.onRemove(id)}
+ />
+ )}
+ </Show>
+ )}
+ </For>
+ </div>
+ );
+}
+
+type QueuedRowProps = {
+ item: QueuedPromptItem;
+ /** Ref-style: how navigation focuses this row; `undefined` on unmount. */
+ registerFocus: (focus: (() => void) | undefined) => void;
+ onMoveUp: () => void;
+ onMoveDown: () => void;
+ onEdit: (prompt: string) => void;
+ onRemove: () => void;
+};
+
+function QueuedRow(props: QueuedRowProps) {
+ onMount(() => {
+ onCleanup(() => props.registerFocus(undefined));
+ });
+
+ return (
+ <Surface class="rounded-lg" depth={1} solid>
+ <div class="flex items-start gap-2 px-3 py-1.5">
+ <div class="min-w-0 flex-1">
+ <Show
+ when={props.item.kind === 'prompt'}
+ fallback={<CompactBody {...props} />}
+ >
+ <PromptBody {...props} />
+ </Show>
+ <div class="text-xs text-ink-extra-muted">
+ Queued
+ <Show when={props.item.queuedBy}>
+ {(name) => <> by {name()}</>}
+ </Show>
+ </div>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label="Remove queued message"
+ onClick={() => props.onRemove()}
+ class="shrink-0"
+ >
+ <XIcon class="size-3.5" />
+ </Button>
+ </div>
+ </Surface>
+ );
+}
+
+/**
+ * The always-editable body of a prompt row: the same Lexical markdown
+ * surface as the composer's input, minus its send machinery. Edits debounce
+ * into `onEdit` and flush when focus leaves the row.
+ */
+function PromptBody(props: QueuedRowProps) {
+ // The last text this row and the server agree on: what was mounted,
+ // applied from a server snapshot, or handed to `onEdit`. Both the autosave
+ // and the anti-clobber check compare against it.
+ let synced = props.item.prompt ?? '';
+ let saveTimer: ReturnType<typeof setTimeout> | undefined;
+
+ const flush = () => {
+ if (saveTimer !== undefined) {
+ clearTimeout(saveTimer);
+ saveTimer = undefined;
+ }
+ const text = editor.controls.getMarkdown();
+ // An emptied row is not an edit to send — the server refuses empty
+ // prompts and "delete the text" has the remove affordance for it.
+ if (text === synced || text.trim().length === 0) return;
+ synced = text;
+ props.onEdit(text);
+ };
+
+ const scheduleSave = (markdown: string) => {
+ if (markdown === synced) return;
+ if (saveTimer !== undefined) clearTimeout(saveTimer);
+ saveTimer = setTimeout(flush, AUTOSAVE_DEBOUNCE_MS);
+ };
+
+ const editor = buildConfig('chat')
+ .namespace('agent-queued-prompt')
+ .withHistory({ timeGap: 400 })
+ .onChange(scheduleSave)
+ .onFocusLeave({
+ onStart: (event) => {
+ event.preventDefault();
+ flush();
+ props.onMoveUp();
+ },
+ onEnd: (event) => {
+ event.preventDefault();
+ flush();
+ props.onMoveDown();
+ },
+ });
+
+ onMount(() => {
+ props.registerFocus(() => editor.controls.focus());
+ onCleanup(() => {
+ if (saveTimer !== undefined) clearTimeout(saveTimer);
+ });
+ });
+
+ // A server snapshot may carry someone else's edit. Apply it only while
+ // this row is
+ // untouched — never over a focused editor or unsaved local changes, which
+ // are about to become the server's text anyway.
+ createEffect(() => {
+ const server = props.item.prompt ?? '';
+ if (server === synced) return;
+ const root = editor.lexical.getRootElement();
+ const focused = root?.contains(document.activeElement) ?? false;
+ const dirty =
+ saveTimer !== undefined || editor.controls.getMarkdown() !== synced;
+ if (focused || dirty) return;
+ editor.controls.setMarkdown(server);
+ synced = server;
+ });
+
+ return (
+ <div class="text-sm text-ink" onFocusOut={flush}>
+ <MarkdownShell config={editor} initialValue={props.item.prompt} />
+ </div>
+ );
+}
+
+/** A compact stays read-only: there is no text of the user's to rewrite. */
+function CompactBody(props: QueuedRowProps) {
+ let element: HTMLDivElement | undefined;
+ onMount(() => {
+ props.registerFocus(() => element?.focus());
+ });
+ return (
+ <div
+ ref={element}
+ tabindex="-1"
+ class="text-sm text-ink outline-none"
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowUp') {
+ event.preventDefault();
+ props.onMoveUp();
+ }
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ props.onMoveDown();
+ }
+ }}
+ >
+ Compact the conversation
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.ts
index a8aeffecfa..e9eb8d4150 100644
--- a/apps/web/src/features/block-agent/ui/index.ts
+++ b/apps/web/src/features/block-agent/ui/index.ts
@@ -27,9 +27,10 @@ export { FoldedTerminal } from './FoldedTerminal';
export { PierreDiff } from './PierreDiff';
export { QuestionAnswers, type QuestionAnswersProps } from './QuestionAnswers';
export {
- QueuedPromptList,
- type QueuedPromptListProps,
-} from './QueuedPromptList';
+ type QueuedPromptItem,
+ QueuedPrompts,
+ type QueuedPromptsProps,
+} from './QueuedPrompts';
export {
type SessionStatusLike,
SessionStatusPill,
diff --git a/apps/web/src/lib/queries/agent-session/queue-sync.ts b/apps/web/src/lib/queries/agent-session/queue-sync.ts
new file mode 100644
index 0000000000..c10fb2fef5
--- /dev/null
+++ b/apps/web/src/lib/queries/agent-session/queue-sync.ts
@@ -0,0 +1,43 @@
+/**
+ * Fan-out for `agent_session_queue` websocket events, mirroring
+ * `session-metadata-sync.ts`: the websocket dispatch calls the handler once
+ * per event, and every mounted session view that cares follows through a
+ * subscription, filtering by session id itself.
+ *
+ * Also exposes the socket-session boundary: a queue consumer baselines from
+ * `GET .../queue` once per socket session and treats the socket as the only
+ * writer after its first event, so it needs to know when a new socket
+ * session begins.
+ */
+
+import { WebsocketEvent } from '@macro-inc/collaboration/websocket';
+import { ws } from '@service-connection/websocket';
+import type { AgentSessionQueueEvent } from './realtime-protocol';
+
+const queueListeners = new Set<(event: AgentSessionQueueEvent) => void>();
+
+/** Deliver one queue snapshot to every subscribed session view. */
+export function handleAgentSessionQueue(event: AgentSessionQueueEvent): void {
+ for (const listener of queueListeners) listener(event);
+}
+
+/** Follow queue snapshots while a session-scoped view is mounted. */
+export function subscribeAgentSessionQueue(
+ listener: (event: AgentSessionQueueEvent) => void
+): () => void {
+ queueListeners.add(listener);
+ return () => queueListeners.delete(listener);
+}
+
+/**
+ * Fires whenever the gateway websocket (re)opens — the start of a new socket
+ * session, after which events may have been missed and a fresh baseline is
+ * needed.
+ */
+export function subscribeSocketSessionStarted(
+ listener: () => void
+): () => void {
+ const handler = () => listener();
+ ws.addEventListener(WebsocketEvent.Open, handler);
+ return () => ws.removeEventListener(WebsocketEvent.Open, handler);
+}
diff --git a/apps/web/src/lib/queries/agent-session/realtime-protocol.ts b/apps/web/src/lib/queries/agent-session/realtime-protocol.ts
index 56d759af14..4674b49d69 100644
--- a/apps/web/src/lib/queries/agent-session/realtime-protocol.ts
+++ b/apps/web/src/lib/queries/agent-session/realtime-protocol.ts
@@ -4,7 +4,16 @@ export const AGENT_SESSION_LOG_EVENT = 'agent_session_log';
/** The Connection Gateway event type for a persisted session-name change. */
export const AGENT_SESSION_RENAMED_EVENT = 'agent_session_renamed';
-import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';
+/**
+ * The Connection Gateway event type carrying a session's whole action queue
+ * after any change (enqueue, edit, remove, dispatch, turn-end drain).
+ */
+export const AGENT_SESSION_QUEUE_EVENT = 'agent_session_queue';
+
+import type {
+ AgentSessionLogEntryDto,
+ QueuedActionDto,
+} from '@service-agent-harness/generated/schemas';
/**
* One persisted log entry, addressed by session for realtime delivery.
@@ -22,6 +31,20 @@ export type AgentSessionRenamedEvent = {
name: string;
};
+/**
+ * A session's action queue after a change. Mirrors `AgentSessionQueueEvent`
+ * in `crates/agent_session/src/outbound/connection_gateway_realtime.rs`.
+ *
+ * Always the full queue, never a delta — `entries` are the exact rows
+ * `GET /agent-sessions/{id}/queue` serves, oldest (next to dispatch) first —
+ * so any one event is a complete, self-sufficient truth and the last one to
+ * arrive wins unconditionally.
+ */
+export type AgentSessionQueueEvent = {
+ agentSessionId: string;
+ entries: QueuedActionDto[];
+};
+
/** Remove the realtime address, leaving the exact persisted entry shape. */
export function entryOf(event: AgentSessionLogEvent): AgentSessionLogEntryDto {
const { agentSessionId: _agentSessionId, ...entry } = event;
diff --git a/apps/web/src/lib/queries/sync/SyncProvider.tsx b/apps/web/src/lib/queries/sync/SyncProvider.tsx
index 53dbdc0389..58e4728e0b 100644
--- a/apps/web/src/lib/queries/sync/SyncProvider.tsx
+++ b/apps/web/src/lib/queries/sync/SyncProvider.tsx
@@ -1,8 +1,11 @@
import { ENABLE_GRAPHQL_SOUP } from '@core/constant/featureFlags';
+import { handleAgentSessionQueue } from '@queries/agent-session/queue-sync';
import {
AGENT_SESSION_LOG_EVENT,
+ AGENT_SESSION_QUEUE_EVENT,
AGENT_SESSION_RENAMED_EVENT,
type AgentSessionLogEvent,
+ type AgentSessionQueueEvent,
type AgentSessionRenamedEvent,
} from '@queries/agent-session/realtime-protocol';
import { handleAgentSessionLog } from '@queries/agent-session/session-fold';
@@ -76,6 +79,16 @@ export function QuerySyncProvider(props: SyncProviderProps) {
handleAgentSessionRenamed
);
})
+ // A session's whole action queue after a change. Full snapshot every
+ // time: once one has arrived on this socket, the socket is the queue's
+ // only writer and the last event wins unconditionally.
+ .with({ type: AGENT_SESSION_QUEUE_EVENT }, () => {
+ withParsedWebsocketPayload<AgentSessionQueueEvent>(
+ data.type,
+ data.data,
+ handleAgentSessionQueue
+ );
+ })
.with({ type: 'comms_reaction' }, () => {
withParsedWebsocketPayload(data.type, data.data, handleCommsReaction);
})
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
index 9324106452..81ed632377 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
@@ -1,10 +1,11 @@
import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
import type {
- AgentActionId,
AgentSessionLogResponse,
+ AgentSessionQueueResponse,
AgentSessionResponse,
ControlRequest,
+ ControlResponse,
CreateAgentSessionRequest,
CreateAgentSessionResponse,
SandboxSize,
@@ -54,22 +55,54 @@ export const agentHarnessServiceClient = {
},
/**
- * Returns the accepted action's id, which the fold stamps as `requestId`
- * on the folded message the action derives — the correlation handle for
- * watching that action's outcome.
+ * Returns the accepted action's id — which the fold stamps as `requestId`
+ * on the folded message the action derives — plus whether the action went
+ * out (`sent`) or waits in the session's queue (`queued`).
*/
control(sessionId: string, request: ControlRequest) {
- // The endpoint answers with a bare JSON string (`AgentActionId`), which
- // `fetchWithToken`'s object-or-bytes constraint cannot name; the cast is
- // the whole accommodation.
- return fetchWithToken<Record<string, never>>(
+ return fetchWithToken<ControlResponse>(
`${agentHarnessHost}/agent-sessions/${sessionId}/control`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
}
- ).then((result) => result.map((id) => id as unknown as AgentActionId));
+ );
+ },
+
+ /** The actions waiting to dispatch in this session, oldest first. */
+ queue(sessionId: string) {
+ return fetchWithToken<AgentSessionQueueResponse>(
+ `${agentHarnessHost}/agent-sessions/${sessionId}/queue`,
+ { method: 'GET' }
+ );
+ },
+
+ /**
+ * Replace a queued prompt's text before it dispatches. Answers 404
+ * (`NOT_FOUND`) once the action has dispatched, 422 if the queued action
+ * is not a prompt.
+ */
+ editQueued(sessionId: string, actionId: string, prompt: string) {
+ return fetchWithToken<Record<string, never>>(
+ `${agentHarnessHost}/agent-sessions/${sessionId}/queue/${actionId}`,
+ {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ prompt }),
+ }
+ ).then((result) => result.map(() => undefined));
+ },
+
+ /**
+ * Remove a queued action before it dispatches. Answers 404 (`NOT_FOUND`)
+ * once the action has dispatched — there is no un-sending.
+ */
+ removeQueued(sessionId: string, actionId: string) {
+ return fetchWithToken<Record<string, never>>(
+ `${agentHarnessHost}/agent-sessions/${sessionId}/queue/${actionId}`,
+ { method: 'DELETE' }
+ ).then((result) => result.map(() => undefined));
},
delete(sessionId: string) {
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
index e7b163514d..ee51050968 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
@@ -5,12 +5,14 @@
* OpenAPI spec version: 0.1.0
*/
import type {
- AgentActionId,
AgentSessionLogResponse,
+ AgentSessionQueueResponse,
AgentSessionResponse,
ControlRequest,
+ ControlResponse,
CreateAgentSessionRequest,
CreateAgentSessionResponse,
+ EditQueuedActionRequest,
RenameAgentSessionRequest,
SandboxSizeBody,
} from './schemas';
@@ -337,10 +339,12 @@ export const deleteAgentSession = async (
};
/**
+ * Edit access suffices: whoever can prompt the bot through its thread can
+prompt it here.
* @summary Perform a control operation on a live agent session.
*/
export type controlAgentSessionResponse200 = {
- data: AgentActionId;
+ data: ControlResponse;
status: 200;
};
@@ -354,6 +358,11 @@ export type controlAgentSessionResponse403 = {
status: 403;
};
+export type controlAgentSessionResponse422 = {
+ data: string;
+ status: 422;
+};
+
export type controlAgentSessionResponse500 = {
data: string;
status: 500;
@@ -366,6 +375,7 @@ export type controlAgentSessionResponseSuccess =
export type controlAgentSessionResponseError = (
| controlAgentSessionResponse401
| controlAgentSessionResponse403
+ | controlAgentSessionResponse422
| controlAgentSessionResponse500
) & {
headers: Headers;
@@ -542,6 +552,220 @@ export const renameAgentSession = async (
} as renameAgentSessionResponse;
};
+/**
+ * @summary The actions waiting to dispatch in this session, oldest first.
+ */
+export type getAgentSessionQueueResponse200 = {
+ data: AgentSessionQueueResponse;
+ status: 200;
+};
+
+export type getAgentSessionQueueResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type getAgentSessionQueueResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type getAgentSessionQueueResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type getAgentSessionQueueResponseSuccess =
+ getAgentSessionQueueResponse200 & {
+ headers: Headers;
+ };
+export type getAgentSessionQueueResponseError = (
+ | getAgentSessionQueueResponse401
+ | getAgentSessionQueueResponse403
+ | getAgentSessionQueueResponse500
+) & {
+ headers: Headers;
+};
+
+export type getAgentSessionQueueResponse =
+ | getAgentSessionQueueResponseSuccess
+ | getAgentSessionQueueResponseError;
+
+export const getGetAgentSessionQueueUrl = (sessionId: string) => {
+ return `/agent-sessions/${sessionId}/queue`;
+};
+
+export const getAgentSessionQueue = async (
+ sessionId: string,
+ options?: RequestInit
+): Promise<getAgentSessionQueueResponse> => {
+ const res = await fetch(getGetAgentSessionQueueUrl(sessionId), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getAgentSessionQueueResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getAgentSessionQueueResponse;
+};
+
+/**
+ * @summary Replace a queued prompt's text before it dispatches.
+ */
+export type editQueuedActionResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type editQueuedActionResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type editQueuedActionResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type editQueuedActionResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type editQueuedActionResponse422 = {
+ data: string;
+ status: 422;
+};
+
+export type editQueuedActionResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type editQueuedActionResponseSuccess = editQueuedActionResponse204 & {
+ headers: Headers;
+};
+export type editQueuedActionResponseError = (
+ | editQueuedActionResponse401
+ | editQueuedActionResponse403
+ | editQueuedActionResponse404
+ | editQueuedActionResponse422
+ | editQueuedActionResponse500
+) & {
+ headers: Headers;
+};
+
+export type editQueuedActionResponse =
+ | editQueuedActionResponseSuccess
+ | editQueuedActionResponseError;
+
+export const getEditQueuedActionUrl = (sessionId: string, actionId: string) => {
+ return `/agent-sessions/${sessionId}/queue/${actionId}`;
+};
+
+export const editQueuedAction = async (
+ sessionId: string,
+ actionId: string,
+ editQueuedActionRequest: EditQueuedActionRequest,
+ options?: RequestInit
+): Promise<editQueuedActionResponse> => {
+ const res = await fetch(getEditQueuedActionUrl(sessionId, actionId), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(editQueuedActionRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: editQueuedActionResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as editQueuedActionResponse;
+};
+
+/**
+ * @summary Remove a queued action before it dispatches. There is no un-sending: an
+action that already went out answers 404.
+ */
+export type removeQueuedActionResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type removeQueuedActionResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type removeQueuedActionResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type removeQueuedActionResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type removeQueuedActionResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type removeQueuedActionResponseSuccess =
+ removeQueuedActionResponse204 & {
+ headers: Headers;
+ };
+export type removeQueuedActionResponseError = (
+ | removeQueuedActionResponse401
+ | removeQueuedActionResponse403
+ | removeQueuedActionResponse404
+ | removeQueuedActionResponse500
+) & {
+ headers: Headers;
+};
+
+export type removeQueuedActionResponse =
+ | removeQueuedActionResponseSuccess
+ | removeQueuedActionResponseError;
+
+export const getRemoveQueuedActionUrl = (
+ sessionId: string,
+ actionId: string
+) => {
+ return `/agent-sessions/${sessionId}/queue/${actionId}`;
+};
+
+export const removeQueuedAction = async (
+ sessionId: string,
+ actionId: string,
+ options?: RequestInit
+): Promise<removeQueuedActionResponse> => {
+ const res = await fetch(getRemoveQueuedActionUrl(sessionId, actionId), {
+ ...options,
+ method: 'DELETE',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: removeQueuedActionResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as removeQueuedActionResponse;
+};
+
/**
* @summary Resize this session's sandbox and remember the size as the owner's default.
*/
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionId.ts
index b19e3824d3..b14e2d1e62 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionId.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionId.ts
@@ -9,10 +9,12 @@
* Identifies one accepted [`AgentAction`] end to end: returned by the
control endpoint, written as the JSON-RPC request id on the action's wire
frame, and read back off that frame as `request_id` on the folded message
-it derives. Correlation is string equality; the value is opaque.
+it derives.
-Minted only by the server at accept time, as `agent_session:{uuid}` - the
-prefix is what lets [`Self::from_request_id`] tell our ids from ones other
-clients picked.
+Minted only by the server at accept time, as a v7 uuid so ids sort by mint
+time. On the wire and in JSON it is the bare uuid, and a uuid-shaped
+request id is the whole ownership test: the server is the only writer of
+runtime-bound frames. The machine's own handshake request ids
+(`agent_session:{session}:{n}`) are not uuids and stay `None`.
*/
export type AgentActionId = string;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionQueueResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionQueueResponse.ts
new file mode 100644
index 0000000000..0522c01b0e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionQueueResponse.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { QueuedActionDto } from './queuedActionDto';
+
+/**
+ * Response body for a session's queue: everything waiting, oldest first.
+
+A wrapper rather than a bare array so that anything which is about the
+response rather than about an entry has somewhere to go later without
+breaking every client.
+ */
+export interface AgentSessionQueueResponse {
+ /** The waiting actions, in dispatch order. */
+ entries: QueuedActionDto[];
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlResponse.ts
new file mode 100644
index 0000000000..bf24936e68
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlResponse.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentActionId } from './agentActionId';
+import type { ControlStatusDto } from './controlStatusDto';
+
+/**
+ * Response body for a control operation.
+
+Clients deserialize this, so both derives are used.
+ */
+export interface ControlResponse {
+ /** Matches `requestId` on the folded message this action derives once it
+dispatches, and names the queue entry until then. */
+ actionId: AgentActionId;
+ /** Whether the action went out or waits in the queue. */
+ status: ControlStatusDto;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlStatusDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlStatusDto.ts
new file mode 100644
index 0000000000..579c056cc0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlStatusDto.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * What accepting a control operation did with it, on the wire.
+ */
+export type ControlStatusDto =
+ (typeof ControlStatusDto)[keyof typeof ControlStatusDto];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ControlStatusDto = {
+ sent: 'sent',
+ queued: 'queued',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/editQueuedActionRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/editQueuedActionRequest.ts
new file mode 100644
index 0000000000..362104b570
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/editQueuedActionRequest.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request body for editing a queued prompt.
+ */
+export interface EditQueuedActionRequest {
+ /**
+ * The new raw prompt text, replacing the old wholesale. Never blank: a
+prompt with nothing to say is a removal, and there is an endpoint for
+that.
+ * @minLength 1
+ */
+ prompt: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index 8727742c87..7a4feaf8ad 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -22,6 +22,7 @@ export * from './agentSessionLogEntryDto';
export * from './agentSessionLogEntryDtoAllOf';
export * from './agentSessionLogEntryDtoAllOfUserId';
export * from './agentSessionLogResponse';
+export * from './agentSessionQueueResponse';
export * from './agentSessionResponse';
export * from './agentSessionResponseAcpSessionId';
export * from './agentSessionResponseExternal';
@@ -33,6 +34,8 @@ export * from './agentSessionResponseThreadId';
export * from './agentSetModelAction';
export * from './botId';
export * from './controlRequest';
+export * from './controlResponse';
+export * from './controlStatusDto';
export * from './createAgentSessionRequest';
export * from './createAgentSessionRequestBotId';
export * from './createAgentSessionRequestInstructions';
@@ -44,12 +47,16 @@ export * from './createAgentSessionRequestWorkspace';
export * from './createAgentSessionResponse';
export * from './createSessionThread';
export * from './createSessionThreadThreadId';
+export * from './editQueuedActionRequest';
export * from './externalSessionResponse';
export * from './externalSessionResponseName';
export * from './externalSessionResponseUrl';
export * from './logDirectionDto';
export * from './logFrameDto';
export * from './logFrameDtoContent';
+export * from './queuedActionDto';
+export * from './queuedActionDtoActorUserId';
+export * from './queuedActionDtoPrompt';
export * from './renameAgentSessionRequest';
export * from './sandboxSize';
export * from './sandboxSizeBody';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/queuedActionDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/queuedActionDto.ts
new file mode 100644
index 0000000000..17e2552273
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/queuedActionDto.ts
@@ -0,0 +1,29 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentActionId } from './agentActionId';
+import type { QueuedActionDtoActorUserId } from './queuedActionDtoActorUserId';
+import type { QueuedActionDtoPrompt } from './queuedActionDtoPrompt';
+
+/**
+ * One action waiting in a session's queue.
+
+Clients deserialize this, so both derives are used.
+ */
+export interface QueuedActionDto {
+ /** The id the action was accepted under. */
+ actionId: AgentActionId;
+ /** The user who queued it, absent when a bot acted on nobody's behalf. */
+ actorUserId?: QueuedActionDtoActorUserId;
+ /** When it was accepted. */
+ createdAt: string;
+ /** What kind of action waits - `prompt` or `compact`; only
+turn-occupying actions are ever queued. */
+ kind: string;
+ /** The prompt's raw text, present for prompts only. What an edit
+replaces. */
+ prompt?: QueuedActionDtoPrompt;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/queuedActionDtoActorUserId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/queuedActionDtoActorUserId.ts
new file mode 100644
index 0000000000..41df98f674
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/queuedActionDtoActorUserId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The user who queued it, absent when a bot acted on nobody's behalf.
+ */
+export type QueuedActionDtoActorUserId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/queuedActionDtoPrompt.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/queuedActionDtoPrompt.ts
new file mode 100644
index 0000000000..e21346dc11
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/queuedActionDtoPrompt.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The prompt's raw text, present for prompts only. What an edit
+replaces.
+ */
+export type QueuedActionDtoPrompt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index e261a2ebfc..39f203e4bc 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -293,6 +293,7 @@
"post": {
"tags": ["agent-sessions"],
"summary": "Perform a control operation on a live agent session.",
+ "description": "Edit access suffices: whoever can prompt the bot through its thread can\nprompt it here.",
"operationId": "control_agent_session",
"parameters": [
{
@@ -318,11 +319,11 @@
},
"responses": {
"200": {
- "description": "Accepted; matches `requestId` on the folded message this action derives",
+ "description": "Accepted. `sent` reached the runtime; `queued` waits for the running turn to end and can be edited or removed meanwhile.",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/AgentActionId"
+ "$ref": "#/components/schemas/ControlResponse"
}
}
}
@@ -347,6 +348,16 @@
}
}
},
+ "422": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -496,6 +507,233 @@
}
}
},
+ "/agent-sessions/{session_id}/queue": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "The actions waiting to dispatch in this session, oldest first.",
+ "operationId": "get_agent_session_queue",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentSessionQueueResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/agent-sessions/{session_id}/queue/{action_id}": {
+ "put": {
+ "tags": ["agent-sessions"],
+ "summary": "Replace a queued prompt's text before it dispatches.",
+ "operationId": "edit_queued_action",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "action_id",
+ "in": "path",
+ "description": "ID the action was accepted under",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/EditQueuedActionRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Already dispatched or never queued",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "The queued action carries no text",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["agent-sessions"],
+ "summary": "Remove a queued action before it dispatches. There is no un-sending: an\naction that already went out answers 404.",
+ "operationId": "remove_queued_action",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "action_id",
+ "in": "path",
+ "description": "ID the action was accepted under",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Already dispatched or never queued",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions/{session_id}/sandbox-size": {
"put": {
"tags": ["agent-sessions"],
@@ -637,7 +875,8 @@
},
"AgentActionId": {
"type": "string",
- "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives. Correlation is string equality; the value is opaque.\n\nMinted only by the server at accept time, as `agent_session:{uuid}` - the\nprefix is what lets [`Self::from_request_id`] tell our ids from ones other\nclients picked."
+ "format": "uuid",
+ "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nMinted only by the server at accept time, as a v7 uuid so ids sort by mint\ntime. On the wire and in JSON it is the bare uuid, and a uuid-shaped\nrequest id is the whole ownership test: the server is the only writer of\nruntime-bound frames. The machine's own handshake request ids\n(`agent_session:{session}:{n}`) are not uuids and stay `None`."
},
"AgentPromptAction": {
"type": "object",
@@ -692,6 +931,20 @@
}
}
},
+ "AgentSessionQueueResponse": {
+ "type": "object",
+ "description": "Response body for a session's queue: everything waiting, oldest first.\n\nA wrapper rather than a bare array so that anything which is about the\nresponse rather than about an entry has somewhere to go later without\nbreaking every client.",
+ "required": ["entries"],
+ "properties": {
+ "entries": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/QueuedActionDto"
+ },
+ "description": "The waiting actions, in dispatch order."
+ }
+ }
+ },
"AgentSessionResponse": {
"type": "object",
"description": "Response body describing an agent session.\n\nClients deserialize this, so both derives are used.",
@@ -820,6 +1073,26 @@
],
"description": "Request body for a control operation on a live session.\n\nA wrapper around the operation rather than the bare enum so that fields\nwhich are about the request rather than the operation have somewhere to go.\nThe acting user is deliberately not one of them: it comes from the caller's\ncredentials, so that a caller cannot attribute an operation to someone else.\n\nClients serialize this, so both derives are used."
},
+ "ControlResponse": {
+ "type": "object",
+ "description": "Response body for a control operation.\n\nClients deserialize this, so both derives are used.",
+ "required": ["actionId", "status"],
+ "properties": {
+ "actionId": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "Matches `requestId` on the folded message this action derives once it\ndispatches, and names the queue entry until then."
+ },
+ "status": {
+ "$ref": "#/components/schemas/ControlStatusDto",
+ "description": "Whether the action went out or waits in the queue."
+ }
+ }
+ },
+ "ControlStatusDto": {
+ "type": "string",
+ "description": "What accepting a control operation did with it, on the wire.",
+ "enum": ["sent", "queued"]
+ },
"CreateAgentSessionRequest": {
"type": "object",
"description": "Request body for `POST /agent-sessions`.\n\nCarries two shapes, told apart by `workspace`. Naming one asks for an\nexternal session: the runtime is the bot operator's, so the caller has to\nsay which bot and which directory, and must own that bot. Omitting it asks\nfor a managed session, whose sandbox this deployment provisions from its\nown configuration - which is why the fields describing someone else's\nruntime must be omitted along with it rather than quietly ignored. Mixing\nthe two is refused rather than guessed at, so that no request can reach the\nmanaged path carrying a bot the caller was never entitled to name.\n\nClients serialize this, so both derives are used.",
@@ -899,6 +1172,18 @@
}
}
},
+ "EditQueuedActionRequest": {
+ "type": "object",
+ "description": "Request body for editing a queued prompt.",
+ "required": ["prompt"],
+ "properties": {
+ "prompt": {
+ "type": "string",
+ "description": "The new raw prompt text, replacing the old wholesale. Never blank: a\nprompt with nothing to say is a removal, and there is an endpoint for\nthat.",
+ "minLength": 1
+ }
+ }
+ },
"ExternalSessionResponse": {
"type": "object",
"description": "The provider-side identity of an externally-served session.",
@@ -938,6 +1223,34 @@
}
}
},
+ "QueuedActionDto": {
+ "type": "object",
+ "description": "One action waiting in a session's queue.\n\nClients deserialize this, so both derives are used.",
+ "required": ["actionId", "kind", "createdAt"],
+ "properties": {
+ "actionId": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The id the action was accepted under."
+ },
+ "actorUserId": {
+ "type": ["string", "null"],
+ "description": "The user who queued it, absent when a bot acted on nobody's behalf."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When it was accepted."
+ },
+ "kind": {
+ "type": "string",
+ "description": "What kind of action waits - `prompt` or `compact`; only\nturn-occupying actions are ever queued."
+ },
+ "prompt": {
+ "type": ["string", "null"],
+ "description": "The prompt's raw text, present for prompts only. What an edit\nreplaces."
+ }
+ }
+ },
"RenameAgentSessionRequest": {
"type": "object",
"description": "Request body for renaming an agent session.",
diff --git a/crates/agent_fold/src/domain/test/fold.rs b/crates/agent_fold/src/domain/test/fold.rs
index 1135942ed0..26b823cf9d 100644
--- a/crates/agent_fold/src/domain/test/fold.rs
+++ b/crates/agent_fold/src/domain/test/fold.rs
@@ -283,16 +283,16 @@ fn a_stop_after_the_agent_speaks_stamps_the_message_it_has() {
#[test]
fn a_rejected_control_reports_the_runtime_error() {
let log = parse_log(concat!(
- r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"agent_session:m1","method":"session/set_config_option","params":{"sessionId":"s","configId":"model","value":"claude-fable-5"}}}"#,
+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"01920000-0000-7000-8000-0000000000a1","method":"session/set_config_option","params":{"sessionId":"s","configId":"model","value":"claude-fable-5"}}}"#,
"\n",
- r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"agent_session:m1","error":{"code":-32602,"message":"Invalid params: model not found: claude-fable-5"}}}"#,
+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"01920000-0000-7000-8000-0000000000a1","error":{"code":-32602,"message":"Invalid params: model not found: claude-fable-5"}}}"#,
));
let messages = fold(log);
assert_eq!(messages.len(), 1);
assert_eq!(
- messages[0].request_id.as_ref().map(|id| id.as_str()),
- Some("agent_session:m1"),
+ messages[0].request_id.as_ref().map(ToString::to_string),
+ Some("01920000-0000-7000-8000-0000000000a1".to_owned()),
"a control-plane id is surfaced for correlation"
);
let [MessagePart::Control { outcome, .. }] = messages[0].parts.as_slice() else {
@@ -309,9 +309,9 @@ fn a_rejected_control_reports_the_runtime_error() {
#[test]
fn an_accepted_control_resolves_and_the_same_frame_moves_the_metadata() {
let log = parse_log(concat!(
- r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"agent_session:m1","method":"session/set_config_option","params":{"sessionId":"s","configId":"model","value":"opus"}}}"#,
+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"01920000-0000-7000-8000-0000000000a1","method":"session/set_config_option","params":{"sessionId":"s","configId":"model","value":"opus"}}}"#,
"\n",
- r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"agent_session:m1","result":{"configOptions":[{"id":"model","name":"Model","type":"select","currentValue":"opus","options":[{"value":"opus","name":"Opus"}]}]}}}"#,
+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"01920000-0000-7000-8000-0000000000a1","result":{"configOptions":[{"id":"model","name":"Model","type":"select","currentValue":"opus","options":[{"value":"opus","name":"Opus"}]}]}}}"#,
));
let messages = fold(log);
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap
index 8cfebf7dd6..1f9745128f 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap
@@ -1,6 +1,5 @@
---
source: crates/agent_fold/src/domain/test/real_recordings.rs
-assertion_line: 258
expression: messages
input_file: crates/agent_fold/fixtures/real/command_invocation.jsonl
---
@@ -12,7 +11,11 @@ input_file: crates/agent_fold/fixtures/real/command_invocation.jsonl
author: User {
user_id: None,
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ b544d9a7-b4f6-4452-b797-dc15b0ee442e,
+ ),
+ ),
parts: NonEmpty {
inner: [
Control {
@@ -34,7 +37,11 @@ input_file: crates/agent_fold/fixtures/real/command_invocation.jsonl
),
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ 813ea7f3-b8e1-4af3-b2f4-44f4f445637a,
+ ),
+ ),
parts: NonEmpty {
inner: [
Text {
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap
index a3a7464d0e..66cb3a878b 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap
@@ -1,6 +1,5 @@
---
source: crates/agent_fold/src/domain/test/real_recordings.rs
-assertion_line: 258
expression: messages
input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl
---
@@ -12,7 +11,11 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl
author: User {
user_id: None,
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ 826d1392-b8c8-4208-8f79-856aa3c17b0b,
+ ),
+ ),
parts: NonEmpty {
inner: [
Control {
@@ -34,7 +37,11 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl
),
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ 415b0c72-3eb8-43bd-b58c-ca2a40ad1ec1,
+ ),
+ ),
parts: NonEmpty {
inner: [
Text {
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap
index 14281ae3d7..f5894fa269 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap
@@ -1,6 +1,5 @@
---
source: crates/agent_fold/src/domain/test/real_recordings.rs
-assertion_line: 258
expression: messages
input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
---
@@ -14,7 +13,11 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
),
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ 656abeab-6cd2-4042-8b68-e29bbd247673,
+ ),
+ ),
parts: NonEmpty {
inner: [
Text {
@@ -139,7 +142,11 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
),
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ 24df345f-2d57-4071-a748-4421cbcc5bf3,
+ ),
+ ),
parts: NonEmpty {
inner: [
Text {
@@ -933,7 +940,11 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
author: User {
user_id: None,
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ 27e3ed1d-3814-4805-abd6-92bbc9bcf3cc,
+ ),
+ ),
parts: NonEmpty {
inner: [
Control {
@@ -955,7 +966,11 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
),
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ 47b3c2d1-4da4-4820-a008-3d9f2f092b64,
+ ),
+ ),
parts: NonEmpty {
inner: [
Text {
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snap
index cdcfe33816..47ef4b7efb 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snap
@@ -1,6 +1,5 @@
---
source: crates/agent_fold/src/domain/test/real_recordings.rs
-assertion_line: 258
expression: messages
input_file: crates/agent_fold/fixtures/real/real_single_turn.jsonl
---
@@ -14,7 +13,11 @@ input_file: crates/agent_fold/fixtures/real/real_single_turn.jsonl
),
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ 7346b5a4-ae32-46b2-b957-6ba3aad7d474,
+ ),
+ ),
parts: NonEmpty {
inner: [
Text {
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
index 9af51e4591..0b10a2b6bc 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
@@ -1,6 +1,5 @@
---
source: crates/agent_fold/src/domain/test/real_recordings.rs
-assertion_line: 258
expression: messages
input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
---
@@ -343,7 +342,11 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
),
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ fbefdda8-5491-4637-b779-7a1306244dd5,
+ ),
+ ),
parts: NonEmpty {
inner: [
Text {
@@ -379,7 +382,11 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
),
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ ff0bdaa9-c499-4c83-bb76-8c8091a70cbf,
+ ),
+ ),
parts: NonEmpty {
inner: [
Text {
@@ -472,7 +479,11 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
),
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ aa3ba9dc-3357-4814-9f46-3e3f2cd48ee7,
+ ),
+ ),
parts: NonEmpty {
inner: [
Text {
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap
index 640683edac..e11451718b 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap
@@ -1,6 +1,5 @@
---
source: crates/agent_fold/src/domain/test/real_recordings.rs
-assertion_line: 258
expression: messages
input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
---
@@ -4695,7 +4694,11 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
author: User {
user_id: None,
},
- request_id: None,
+ request_id: Some(
+ AgentActionId(
+ 482c3d39-c381-4809-874c-fe00bc757345,
+ ),
+ ),
parts: NonEmpty {
inner: [
Control {
diff --git a/crates/agent_harness/src/domain/mod.rs b/crates/agent_harness/src/domain/mod.rs
index 8c5d7a981e..3d1e9d8b0a 100644
--- a/crates/agent_harness/src/domain/mod.rs
+++ b/crates/agent_harness/src/domain/mod.rs
@@ -1,6 +1,8 @@
pub mod error;
pub mod model;
pub mod ports;
+/// The per-session queue of turn-occupying actions awaiting their turn.
+pub mod queue;
/// Compute resources for a sandbox size.
pub mod sandbox;
/// The harness orchestrator: containers, announcements, and trigger commands.
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index b5e1ba289d..79b56f709d 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -132,6 +132,11 @@ pub struct AgentRuntimeConfig {
pub instructions: String,
}
+/// Whether a user belongs to the Macro staff domain - the egress crate's
+/// predicate, reused so the harness's staff gates and the proxy's can never
+/// disagree about who staff is.
+pub(crate) use agent_egress::domain::model::is_macro_staff;
+
/// Where a prompt came from, when it came from somewhere the session should
/// answer back into.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -186,12 +191,49 @@ pub enum HarnessCommand {
Open(OpenSession),
/// Act on a session that already exists.
Deliver(DeliverAction),
+ /// Replace a queued prompt's text before it dispatches.
+ EditQueued {
+ /// The queue entry to edit.
+ action_id: AgentActionId,
+ /// The new raw prompt text.
+ prompt: String,
+ /// The user responsible, judged by the same gates as sending: whoever
+ /// may not prompt a session may not rewrite what it is about to be
+ /// prompted with.
+ actor: Option<MacroUserIdStr<'static>>,
+ },
+ /// Remove a queued action before it dispatches.
+ RemoveQueued {
+ /// The queue entry to remove.
+ action_id: AgentActionId,
+ /// The user responsible, as on [`Self::EditQueued`].
+ actor: Option<MacroUserIdStr<'static>>,
+ },
+ /// The session's runtime answered its in-flight turn: clear the busy
+ /// mark and dispatch the next queued action. Internal - enqueued by the
+ /// turn observer on the managing replica, never forwarded.
+ TurnEnded,
+ /// The session's live actor stopped: clear the busy mark and nothing
+ /// more - resuming a dead runtime stays the next user action's job.
+ /// Internal, like [`Self::TurnEnded`].
+ SessionStopped,
/// Change the session's sandbox size and the owner's default.
SetSandboxSize(SandboxSize),
/// Release a session's live resources and delete it.
Delete,
}
+/// What executing a command did with it, beyond succeeding.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum CommandOutcome {
+ /// The command ran to completion - for a deliver, the action reached the
+ /// runtime.
+ Completed,
+ /// The action waits in the session's queue for the running turn to end.
+ Queued,
+}
+
impl DeliverAction {
/// A prompt from a user, arriving from a channel that may need answering.
pub fn prompt(
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index 2c948584b3..0f8416259b 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -14,8 +14,8 @@ use macro_user_id::user_id::MacroUserIdStr;
use super::error::{HarnessError, Result};
use super::model::{
- AgentRuntimeConfig, HarnessCommand, PriorChannelMessage, ProvisionedEgress, SandboxEgress,
- SessionAnnouncement, SpawnContainer,
+ AgentRuntimeConfig, CommandOutcome, HarnessCommand, PriorChannelMessage, ProvisionedEgress,
+ SandboxEgress, SessionAnnouncement, SpawnContainer,
};
use super::sandbox::SandboxResizeEffect;
@@ -28,13 +28,14 @@ use super::sandbox::SandboxResizeEffect;
/// caller that awaited a forward has the same guarantee as one that executed
/// locally.
pub trait CommandForwarder: Send + Sync + 'static {
- /// Run `command` for `session` on the replica at `target`.
+ /// Run `command` for `session` on the replica at `target`, reporting
+ /// what that replica's execution did with it.
fn forward(
&self,
target: &ReplicaAddress,
session: AgentSessionId,
command: HarnessCommand,
- ) -> impl Future<Output = Result<()>> + Send;
+ ) -> impl Future<Output = Result<CommandOutcome>> + Send;
}
/// A forwarder for deployments with exactly one replica, where a live peer
@@ -49,7 +50,7 @@ impl CommandForwarder for NoPeers {
target: &ReplicaAddress,
session: AgentSessionId,
_command: HarnessCommand,
- ) -> Result<()> {
+ ) -> Result<CommandOutcome> {
Err(HarnessError::Forward(rootcause::report!(
"this deployment has no command forwarding, yet {target} manages session {session}"
)))
diff --git a/crates/agent_harness/src/domain/queue.rs b/crates/agent_harness/src/domain/queue.rs
new file mode 100644
index 0000000000..efa903fb06
--- /dev/null
+++ b/crates/agent_harness/src/domain/queue.rs
@@ -0,0 +1,195 @@
+//! The per-session queue of turn-occupying actions.
+//!
+//! Prompts (and compaction) occupy a whole agent turn, and ACP runs one turn
+//! at a time - so while a turn runs, further turn-occupying actions wait here
+//! rather than interleaving on the wire. Entries hold the *raw* user text:
+//! composition and announcement happen at dispatch, which is what makes a
+//! queued prompt editable and gives it fresh channel context when it actually
+//! runs.
+//!
+//! In-memory on purpose. The queue lives beside the session's live actor on
+//! the replica that manages it, and dies with the process - a restart loses
+//! whatever was waiting, exactly like it always lost an in-flight turn.
+//!
+//! Callers mutate this only from the session's command worker, which is what
+//! serializes an edit against the dispatch that might be claiming the same
+//! entry. The structure itself only promises per-call consistency.
+
+use std::collections::VecDeque;
+
+use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
+use agent_session::domain::model::AgentSessionId;
+use agent_session::domain::ports::QueuedControl;
+use chrono::{DateTime, Utc};
+use dashmap::DashMap;
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::model::AnnounceOrigin;
+
+#[cfg(test)]
+mod test;
+
+/// How many actions one session may hold queued. Far above any real
+/// conversation; a backstop against a runaway bot caller, not a product
+/// limit.
+const QUEUE_CAP: usize = 50;
+
+/// One action waiting to dispatch.
+#[derive(Debug, Clone)]
+pub struct QueuedEntry {
+ /// The id the action was accepted under - the queue's key, the wire's
+ /// request id, and the folded message's `request_id` once dispatched.
+ pub action_id: AgentActionId,
+ /// What to deliver, carrying raw prompt text (see module docs).
+ pub action: AgentAction,
+ /// The user who queued it, absent when a bot acted on nobody's behalf.
+ pub actor: Option<MacroUserIdStr<'static>>,
+ /// Where to announce the prompt at dispatch, when it came from somewhere
+ /// the session should answer back into.
+ pub announce: Option<AnnounceOrigin>,
+ /// Whether the chip has been posted. Set by the dispatch that posts it,
+ /// and carried through a requeue, so a dispatch that fails *after*
+ /// announcing retries without posting a second chip.
+ pub announced: bool,
+ /// When it was accepted.
+ pub created_at: DateTime<Utc>,
+}
+
+impl From<&QueuedEntry> for QueuedControl {
+ fn from(entry: &QueuedEntry) -> Self {
+ Self {
+ action_id: entry.action_id,
+ action: entry.action.clone(),
+ actor: entry.actor.clone(),
+ created_at: entry.created_at,
+ }
+ }
+}
+
+/// Why the queue refused a mutation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum QueueError {
+ /// No entry under this id - it dispatched, was removed, or never existed.
+ /// One answer for all three: the caller's entry is not waiting anymore,
+ /// and which way it left is not knowable from here.
+ NotFound,
+ /// The entry exists but carries no editable text.
+ NotEditable,
+ /// The session already holds [`QUEUE_CAP`] entries.
+ Full,
+}
+
+/// Every session's waiting actions, FIFO per session.
+#[derive(Debug, Default)]
+pub struct SessionQueues {
+ queues: DashMap<AgentSessionId, VecDeque<QueuedEntry>>,
+}
+
+impl SessionQueues {
+ /// An empty set of queues.
+ #[must_use]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Append an entry to its session's queue.
+ pub fn enqueue(&self, session: AgentSessionId, entry: QueuedEntry) -> Result<(), QueueError> {
+ let mut queue = self.queues.entry(session).or_default();
+ if queue.len() >= QUEUE_CAP {
+ return Err(QueueError::Full);
+ }
+ queue.push_back(entry);
+ Ok(())
+ }
+
+ /// Take the oldest waiting entry, if any.
+ pub fn claim_next(&self, session: AgentSessionId) -> Option<QueuedEntry> {
+ let mut queue = self.queues.get_mut(&session)?;
+ let entry = queue.pop_front();
+ if queue.is_empty() {
+ drop(queue);
+ // Second look under the map's own lock: an enqueue may have
+ // landed between the drop and the removal, and `remove_if` is
+ // what keeps this from discarding it.
+ self.queues.remove_if(&session, |_, queue| queue.is_empty());
+ }
+ entry
+ }
+
+ /// Put a claimed entry back at the front, for a dispatch that failed
+ /// with nobody waiting on it - the entry stays next in line.
+ pub fn requeue_front(&self, session: AgentSessionId, entry: QueuedEntry) {
+ self.queues.entry(session).or_default().push_front(entry);
+ }
+
+ /// Everything waiting for this session, oldest first.
+ #[must_use]
+ pub fn list(&self, session: AgentSessionId) -> Vec<QueuedControl> {
+ self.queues
+ .get(&session)
+ .map(|queue| queue.iter().map(QueuedControl::from).collect())
+ .unwrap_or_default()
+ }
+
+ /// Whether this entry is still waiting.
+ #[must_use]
+ pub fn contains(&self, session: AgentSessionId, action_id: AgentActionId) -> bool {
+ self.queues
+ .get(&session)
+ .is_some_and(|queue| queue.iter().any(|entry| entry.action_id == action_id))
+ }
+
+ /// Replace a queued prompt's text. The entry keeps its place and its id.
+ ///
+ /// `actor` becomes the entry's actor: the user who rewrote the text is
+ /// who later dispatch announces and logs as, so an edit cannot keep
+ /// someone else's name on words they did not type.
+ pub fn edit_prompt(
+ &self,
+ session: AgentSessionId,
+ action_id: AgentActionId,
+ prompt: String,
+ actor: Option<MacroUserIdStr<'static>>,
+ ) -> Result<(), QueueError> {
+ let mut queue = self.queues.get_mut(&session).ok_or(QueueError::NotFound)?;
+ let entry = queue
+ .iter_mut()
+ .find(|entry| entry.action_id == action_id)
+ .ok_or(QueueError::NotFound)?;
+ match &mut entry.action {
+ AgentAction::Prompt(action) => {
+ action.prompt = prompt;
+ entry.actor = actor;
+ Ok(())
+ }
+ AgentAction::SetModel(_) | AgentAction::Compact | AgentAction::Stop => {
+ Err(QueueError::NotEditable)
+ }
+ }
+ }
+
+ /// Forget a session's queue wholesale - for a session that is being
+ /// deleted, whose entries will never dispatch.
+ pub fn drop_session(&self, session: AgentSessionId) {
+ self.queues.remove(&session);
+ }
+
+ /// Remove a waiting entry.
+ pub fn remove(
+ &self,
+ session: AgentSessionId,
+ action_id: AgentActionId,
+ ) -> Result<(), QueueError> {
+ let mut queue = self.queues.get_mut(&session).ok_or(QueueError::NotFound)?;
+ let position = queue
+ .iter()
+ .position(|entry| entry.action_id == action_id)
+ .ok_or(QueueError::NotFound)?;
+ queue.remove(position);
+ if queue.is_empty() {
+ drop(queue);
+ self.queues.remove_if(&session, |_, queue| queue.is_empty());
+ }
+ Ok(())
+ }
+}
diff --git a/crates/agent_harness/src/domain/queue/test.rs b/crates/agent_harness/src/domain/queue/test.rs
new file mode 100644
index 0000000000..48d21ea488
--- /dev/null
+++ b/crates/agent_harness/src/domain/queue/test.rs
@@ -0,0 +1,195 @@
+use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
+use agent_session::domain::model::AgentSessionId;
+
+use super::*;
+
+fn prompt_entry(text: &str) -> QueuedEntry {
+ QueuedEntry {
+ action_id: AgentActionId::mint(),
+ action: AgentAction::prompt(text),
+ actor: None,
+ announce: None,
+ announced: false,
+ created_at: Utc::now(),
+ }
+}
+
+fn prompt_text(action: &AgentAction) -> &str {
+ match action {
+ AgentAction::Prompt(prompt) => &prompt.prompt,
+ other => panic!("expected a prompt, got {other:?}"),
+ }
+}
+
+#[test]
+fn entries_come_back_out_oldest_first() {
+ let queues = SessionQueues::new();
+ let session = AgentSessionId::TEST_A;
+ let first = prompt_entry("first");
+ let second = prompt_entry("second");
+ queues.enqueue(session, first.clone()).unwrap();
+ queues.enqueue(session, second.clone()).unwrap();
+
+ assert_eq!(
+ queues
+ .list(session)
+ .iter()
+ .map(|entry| entry.action_id)
+ .collect::<Vec<_>>(),
+ [first.action_id, second.action_id]
+ );
+ assert_eq!(
+ queues.claim_next(session).unwrap().action_id,
+ first.action_id
+ );
+ assert_eq!(
+ queues.claim_next(session).unwrap().action_id,
+ second.action_id
+ );
+ assert!(queues.claim_next(session).is_none());
+ assert!(queues.list(session).is_empty());
+}
+
+#[test]
+fn sessions_do_not_share_a_queue() {
+ let queues = SessionQueues::new();
+ queues
+ .enqueue(AgentSessionId::TEST_A, prompt_entry("a's work"))
+ .unwrap();
+
+ assert!(queues.claim_next(AgentSessionId::TEST_B).is_none());
+ assert!(queues.list(AgentSessionId::TEST_B).is_empty());
+ assert_eq!(queues.list(AgentSessionId::TEST_A).len(), 1);
+}
+
+#[test]
+fn editing_replaces_the_text_and_keeps_the_place() {
+ let queues = SessionQueues::new();
+ let session = AgentSessionId::TEST_A;
+ let first = prompt_entry("first");
+ let second = prompt_entry("second");
+ queues.enqueue(session, first.clone()).unwrap();
+ queues.enqueue(session, second.clone()).unwrap();
+
+ queues
+ .edit_prompt(session, first.action_id, "rewritten".to_owned(), None)
+ .unwrap();
+
+ let claimed = queues.claim_next(session).unwrap();
+ assert_eq!(claimed.action_id, first.action_id);
+ assert_eq!(prompt_text(&claimed.action), "rewritten");
+}
+
+#[test]
+fn editing_reattributes_the_entry_to_the_editor() {
+ let queues = SessionQueues::new();
+ let session = AgentSessionId::TEST_A;
+ let mut first = prompt_entry("first");
+ first.actor = Some(MacroUserIdStr::try_from_email("[email protected]").unwrap());
+ queues.enqueue(session, first.clone()).unwrap();
+
+ let editor = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ queues
+ .edit_prompt(
+ session,
+ first.action_id,
+ "rewritten".to_owned(),
+ Some(editor.clone()),
+ )
+ .unwrap();
+
+ let claimed = queues.claim_next(session).unwrap();
+ assert_eq!(claimed.actor.as_ref(), Some(&editor));
+ assert_eq!(prompt_text(&claimed.action), "rewritten");
+}
+
+#[test]
+fn a_claimed_entry_is_gone_for_editing_and_removal() {
+ let queues = SessionQueues::new();
+ let session = AgentSessionId::TEST_A;
+ let entry = prompt_entry("work");
+ queues.enqueue(session, entry.clone()).unwrap();
+ queues.claim_next(session).unwrap();
+
+ assert_eq!(
+ queues.edit_prompt(session, entry.action_id, "late".to_owned(), None),
+ Err(QueueError::NotFound)
+ );
+ assert_eq!(
+ queues.remove(session, entry.action_id),
+ Err(QueueError::NotFound)
+ );
+}
+
+#[test]
+fn only_prompts_are_editable() {
+ let queues = SessionQueues::new();
+ let session = AgentSessionId::TEST_A;
+ let compact = QueuedEntry {
+ action_id: AgentActionId::mint(),
+ action: AgentAction::Compact,
+ actor: None,
+ announce: None,
+ announced: false,
+ created_at: Utc::now(),
+ };
+ queues.enqueue(session, compact.clone()).unwrap();
+
+ assert_eq!(
+ queues.edit_prompt(session, compact.action_id, "text".to_owned(), None),
+ Err(QueueError::NotEditable)
+ );
+ // Still removable.
+ queues.remove(session, compact.action_id).unwrap();
+}
+
+#[test]
+fn removal_skips_the_removed_entry_at_dispatch() {
+ let queues = SessionQueues::new();
+ let session = AgentSessionId::TEST_A;
+ let first = prompt_entry("first");
+ let second = prompt_entry("second");
+ queues.enqueue(session, first.clone()).unwrap();
+ queues.enqueue(session, second.clone()).unwrap();
+
+ queues.remove(session, first.action_id).unwrap();
+
+ assert_eq!(
+ queues.claim_next(session).unwrap().action_id,
+ second.action_id
+ );
+}
+
+#[test]
+fn a_requeued_entry_is_next_in_line() {
+ let queues = SessionQueues::new();
+ let session = AgentSessionId::TEST_A;
+ let first = prompt_entry("first");
+ let second = prompt_entry("second");
+ queues.enqueue(session, first.clone()).unwrap();
+ queues.enqueue(session, second.clone()).unwrap();
+
+ let claimed = queues.claim_next(session).unwrap();
+ queues.requeue_front(session, claimed);
+
+ assert_eq!(
+ queues.claim_next(session).unwrap().action_id,
+ first.action_id
+ );
+}
+
+#[test]
+fn the_cap_refuses_the_overflowing_entry() {
+ let queues = SessionQueues::new();
+ let session = AgentSessionId::TEST_A;
+ for n in 0..QUEUE_CAP {
+ queues
+ .enqueue(session, prompt_entry(&format!("{n}")))
+ .unwrap();
+ }
+
+ assert_eq!(
+ queues.enqueue(session, prompt_entry("one too many")),
+ Err(QueueError::Full)
+ );
+}
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 6925106e0f..6a5eb9bf45 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -10,7 +10,10 @@ use agent_session::domain::model::SessionManagement;
use agent_session::domain::model::{
AgentSession, AgentSessionId, AuthorKind, CreateAgentSessionParams, MessageId, SandboxSize,
};
-use agent_session::domain::ports::{AgentSessionNotificationRecipient, ControlEvent};
+use agent_session::domain::ports::{
+ AcceptedControl, AgentSessionNotificationRecipient, AgentSessionQueueChanged,
+ ControlDisposition, ControlEvent, QueuedControl,
+};
use agent_session::domain::service::AgentSessionService;
use bot_id::BotId;
use dashmap::DashMap;
@@ -22,20 +25,21 @@ use tracing::instrument::WithSubscriber as _;
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::{
- AgentKind, AnnounceOrigin, AnnouncePrompt, DeliverAction, HarnessCommand, HarnessDefaults,
- OpenSession, SessionAnnouncement, SpawnContainer,
+ AgentKind, AnnounceOrigin, AnnouncePrompt, CommandOutcome, DeliverAction, HarnessCommand,
+ HarnessDefaults, OpenSession, SessionAnnouncement, SpawnContainer, is_macro_staff,
};
use crate::domain::ports::{
AgentPromptComposer, ChannelPromptContext, CommandForwarder, ContainerManager,
RuntimeConnections, SandboxEgressProvisioner, SessionAnnouncer,
};
+use crate::domain::queue::{QueueError, QueuedEntry, SessionQueues};
use crate::domain::sandbox::SandboxResizeEffect;
type SessionWorkers = DashMap<AgentSessionId, mpsc::UnboundedSender<QueuedCommand>>;
struct QueuedCommand {
command: HarnessCommand,
- completed: oneshot::Sender<Result<()>>,
+ completed: oneshot::Sender<Result<CommandOutcome>>,
/// The caller's span, carried across the queue so the work the worker does
/// on its own task still hangs off whatever triggered it.
span: tracing::Span,
@@ -58,7 +62,7 @@ trait ErasedForwarder: Send + Sync + 'static {
target: &'a agent_session::domain::model::ReplicaAddress,
session: AgentSessionId,
command: HarnessCommand,
- ) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
+ ) -> std::pin::Pin<Box<dyn Future<Output = Result<CommandOutcome>> + Send + 'a>>;
}
impl<F: CommandForwarder> ErasedForwarder for F {
@@ -67,7 +71,7 @@ impl<F: CommandForwarder> ErasedForwarder for F {
target: &'a agent_session::domain::model::ReplicaAddress,
session: AgentSessionId,
command: HarnessCommand,
- ) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
+ ) -> std::pin::Pin<Box<dyn Future<Output = Result<CommandOutcome>> + Send + 'a>> {
Box::pin(CommandForwarder::forward(self, target, session, command))
}
}
@@ -90,6 +94,14 @@ struct AgentHarnessInner<
egress: Egress,
forwarder: Box<dyn ErasedForwarder>,
defaults: HarnessDefaults,
+ /// Turn-occupying actions waiting for their session's running turn to
+ /// end. In-memory beside the live actors this replica manages.
+ queues: SessionQueues,
+ /// The sessions with a turn in flight. Marked when a turn-occupying
+ /// action reaches the runtime, cleared by `TurnEnded`/`SessionStopped`.
+ /// Only ever touched from the session's own command worker, which is
+ /// what serializes it against dispatch.
+ busy: DashMap<AgentSessionId, ()>,
}
/// Turns trigger commands into running, announced agent sessions.
@@ -116,6 +128,29 @@ pub struct AgentHarnessService<
workers: Arc<SessionWorkers>,
}
+// Manual Clone impl so the port types don't need to be Clone (both fields
+// are behind Arcs). A clone is another handle on the same workers and queues,
+// which is what lets the service be bound as its own session services' turn
+// observer.
+impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress> Clone
+ for AgentHarnessService<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >
+{
+ fn clone(&self) -> Self {
+ Self {
+ inner: Arc::clone(&self.inner),
+ workers: Arc::clone(&self.workers),
+ }
+ }
+}
+
impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
AgentHarnessService<
Sessions,
@@ -162,6 +197,8 @@ where
egress,
forwarder: Box::new(forwarder),
defaults: defaults.into(),
+ queues: SessionQueues::new(),
+ busy: DashMap::new(),
}),
workers: Arc::new(DashMap::new()),
}
@@ -177,7 +214,7 @@ where
&self,
session_id: AgentSessionId,
command: HarnessCommand,
- ) -> impl Future<Output = Result<()>> + Send + 'static {
+ ) -> impl Future<Output = Result<CommandOutcome>> + Send + 'static {
self.enqueue(session_id, command, true)
}
@@ -193,7 +230,7 @@ where
&self,
session_id: AgentSessionId,
command: HarnessCommand,
- ) -> impl Future<Output = Result<()>> + Send + 'static {
+ ) -> impl Future<Output = Result<CommandOutcome>> + Send + 'static {
self.enqueue(session_id, command, false)
}
@@ -202,7 +239,7 @@ where
session_id: AgentSessionId,
mut command: HarnessCommand,
route: bool,
- ) -> impl Future<Output = Result<()>> + Send + 'static {
+ ) -> impl Future<Output = Result<CommandOutcome>> + Send + 'static {
let caller = tracing::Span::current();
let result = loop {
let commands = self.commands(session_id);
@@ -308,7 +345,7 @@ pub trait ForwardedCommands: Send + Sync + 'static {
&self,
session_id: AgentSessionId,
command: HarnessCommand,
- ) -> impl Future<Output = Result<()>> + Send;
+ ) -> impl Future<Output = Result<CommandOutcome>> + Send;
}
impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
@@ -335,7 +372,7 @@ where
&self,
session_id: AgentSessionId,
command: HarnessCommand,
- ) -> Result<()> {
+ ) -> Result<CommandOutcome> {
self.execute_here(session_id, command).await
}
}
@@ -370,6 +407,7 @@ where
) -> agent_session::domain::error::Result<()> {
self.execute(id, HarnessCommand::Delete)
.await
+ .map(drop)
.map_err(into_session_error)
}
@@ -377,15 +415,64 @@ where
&self,
id: AgentSessionId,
event: ControlEvent,
- ) -> agent_session::domain::error::Result<AgentActionId> {
+ ) -> agent_session::domain::error::Result<AcceptedControl> {
let action_id = AgentActionId::mint();
+ let outcome = self
+ .execute(
+ id,
+ HarnessCommand::Deliver(DeliverAction::control(action_id, event)),
+ )
+ .await
+ .map_err(into_session_error)?;
+ Ok(AcceptedControl {
+ action_id,
+ disposition: match outcome {
+ CommandOutcome::Completed => ControlDisposition::Sent,
+ CommandOutcome::Queued => ControlDisposition::Queued,
+ },
+ })
+ }
+
+ /// A local read on purpose: the queue lives beside the session's live
+ /// actor, and this replica answers for what it holds. A reader landing on
+ /// a non-managing replica sees an empty queue rather than an error.
+ async fn queued_controls(
+ &self,
+ id: AgentSessionId,
+ ) -> agent_session::domain::error::Result<Vec<QueuedControl>> {
+ Ok(self.inner.queues.list(id))
+ }
+
+ async fn edit_queued_control(
+ &self,
+ id: AgentSessionId,
+ action_id: AgentActionId,
+ prompt: String,
+ actor: Option<MacroUserIdStr<'static>>,
+ ) -> agent_session::domain::error::Result<()> {
self.execute(
id,
- HarnessCommand::Deliver(DeliverAction::control(action_id.clone(), event)),
+ HarnessCommand::EditQueued {
+ action_id,
+ prompt,
+ actor,
+ },
)
.await
- .map_err(into_session_error)?;
- Ok(action_id)
+ .map(drop)
+ .map_err(into_session_error)
+ }
+
+ async fn remove_queued_control(
+ &self,
+ id: AgentSessionId,
+ action_id: AgentActionId,
+ actor: Option<MacroUserIdStr<'static>>,
+ ) -> agent_session::domain::error::Result<()> {
+ self.execute(id, HarnessCommand::RemoveQueued { action_id, actor })
+ .await
+ .map(drop)
+ .map_err(into_session_error)
}
async fn set_sandbox_size(
@@ -395,6 +482,7 @@ where
) -> agent_session::domain::error::Result<()> {
self.execute(id, HarnessCommand::SetSandboxSize(size))
.await
+ .map(drop)
.map_err(into_session_error)
}
@@ -414,6 +502,39 @@ where
}
}
+/// The queue drains on the session's own command worker, so both signals
+/// only admit an internal command there and return. Admission is synchronous
+/// inside [`AgentHarnessService::execute_here`]; the returned future only
+/// awaits the completion, which nothing here needs.
+impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
+ agent_session::domain::ports::SessionTurnObserver
+ for AgentHarnessService<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: ChannelPromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+{
+ fn turn_ended(&self, id: AgentSessionId) {
+ drop(self.execute_here(id, HarnessCommand::TurnEnded));
+ }
+
+ fn session_stopped(&self, id: AgentSessionId) {
+ drop(self.execute_here(id, HarnessCommand::SessionStopped));
+ }
+}
+
/// External sessions create the row and announce - the magic-chip message
/// the session's bot posts into the mention's thread, which is where the
/// app renders the session's replies. No sandbox (the runtime dials in) and
@@ -504,22 +625,6 @@ where
request: agent_session::domain::ports::OpenManagedSession,
) -> agent_session::domain::error::Result<AgentSession> {
let defaults = self.inner.defaults.managed();
- let initial_prompt = if let Some(raw_prompt) = request.prompt.as_deref() {
- let composed_prompt = self
- .inner
- .prompt_composer
- .compose(raw_prompt, None)
- .await
- .map_err(into_session_error)?;
- let mut action = AgentAction::prompt(composed_prompt);
- let AgentAction::Prompt(prompt) = &mut action else {
- unreachable!("a prompt constructor always returns a prompt action");
- };
- prompt.set_name_source(raw_prompt.to_owned());
- Some(action)
- } else {
- None
- };
let sandbox_size = self
.inner
.sessions
@@ -595,16 +700,21 @@ where
)
.await?;
- if let Some(prompt) = initial_prompt {
- self.inner
- .sessions
- .send_action(
- session.id,
- Some(request.owner),
- prompt,
- AgentActionId::mint(),
- )
- .await?;
+ // Raw, through the session's own command worker: dispatch is where a
+ // prompt is composed, and the worker is what serializes this first
+ // prompt against any control prompt racing the session's birth.
+ if let Some(raw_prompt) = request.prompt {
+ self.execute_here(
+ session.id,
+ HarnessCommand::Deliver(DeliverAction {
+ id: AgentActionId::mint(),
+ action: AgentAction::prompt(raw_prompt),
+ actor: Some(request.owner),
+ announce: None,
+ }),
+ )
+ .await
+ .map_err(into_session_error)?;
}
Ok(session)
@@ -629,6 +739,21 @@ where
}
}
+/// Map a queue refusal into the session vocabulary, which is where the
+/// control surface's callers read their errors from.
+fn queue_result<T>(
+ result: std::result::Result<T, QueueError>,
+ session_id: AgentSessionId,
+) -> Result<T> {
+ result.map_err(|error| {
+ HarnessError::Session(match error {
+ QueueError::NotFound => AgentSessionError::QueuedControlNotFound,
+ QueueError::NotEditable => AgentSessionError::QueuedControlNotEditable,
+ QueueError::Full => AgentSessionError::ControlQueueFull(session_id),
+ })
+ })
+}
+
/// Collapse a harness failure back into the session vocabulary the port speaks.
///
/// A harness error that started life as a session error is unwrapped rather
@@ -686,7 +811,7 @@ where
&self,
session_id: AgentSessionId,
command: HarnessCommand,
- ) -> Result<()> {
+ ) -> Result<CommandOutcome> {
let span = tracing::Span::current();
// Open never routes: it is what creates the session row this routing
// would read, and a fresh id has no manager to defer to.
@@ -726,7 +851,7 @@ where
.forward(&address, session_id, command.clone())
.await
{
- Ok(()) => Ok(()),
+ Ok(outcome) => Ok(outcome),
Err(forward_error) => match self.sessions.management(session_id).await? {
SessionManagement::Unmanaged | SessionManagement::Ours => {
// Worth aggregating rather than only logging: routine
@@ -745,12 +870,242 @@ where
}
}
- async fn execute(&self, session_id: AgentSessionId, command: HarnessCommand) -> Result<()> {
+ async fn execute(
+ &self,
+ session_id: AgentSessionId,
+ command: HarnessCommand,
+ ) -> Result<CommandOutcome> {
+ match &command {
+ HarnessCommand::Open(open)
+ if AgentKind::of(open.bot_id) == AgentKind::SandboxedCoder
+ && !is_macro_staff(&open.origin.sender) =>
+ {
+ return Err(AgentSessionError::Forbidden.into());
+ }
+ // The queue mutations sit behind the same staff gate as delivery:
+ // an edited entry is delivered later under its original identity,
+ // so rewriting (or dropping) what a Daytona session is about to
+ // run is the same privilege as prompting it.
+ HarnessCommand::Deliver(DeliverAction { actor, .. })
+ | HarnessCommand::EditQueued { actor, .. }
+ | HarnessCommand::RemoveQueued { actor, .. } => {
+ let session = self.sessions.get_session(session_id).await?;
+ if AgentKind::of(session.bot_id) == AgentKind::SandboxedCoder
+ && !actor.as_ref().is_some_and(is_macro_staff)
+ {
+ return Err(AgentSessionError::Forbidden.into());
+ }
+ }
+ HarnessCommand::Open(_)
+ | HarnessCommand::TurnEnded
+ | HarnessCommand::SessionStopped
+ | HarnessCommand::SetSandboxSize(_)
+ | HarnessCommand::Delete => {}
+ }
+
match command {
- HarnessCommand::Open(command) => self.open(session_id, command).await,
- HarnessCommand::Deliver(command) => self.deliver(session_id, command).await,
- HarnessCommand::SetSandboxSize(size) => self.apply_sandbox_size(session_id, size).await,
- HarnessCommand::Delete => self.delete(session_id).await,
+ HarnessCommand::Open(command) => {
+ self.open(session_id, command).await?;
+ Ok(CommandOutcome::Completed)
+ }
+ // Turn-occupying actions go through the queue - the running
+ // turn's end is what dispatches them. Everything else delivers
+ // now: a stop rides alongside the turn it cancels, and that
+ // turn's cancelled answer is an ordinary turn end.
+ HarnessCommand::Deliver(command) if command.action.occupies_turn() => {
+ self.enqueue_then_dispatch(session_id, command).await
+ }
+ HarnessCommand::Deliver(command) => {
+ self.deliver(session_id, command).await?;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::EditQueued {
+ action_id,
+ prompt,
+ actor,
+ } => {
+ queue_result(
+ self.queues
+ .edit_prompt(session_id, action_id, prompt, actor),
+ session_id,
+ )?;
+ self.publish_queue(session_id).await;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::RemoveQueued { action_id, .. } => {
+ queue_result(self.queues.remove(session_id, action_id), session_id)?;
+ self.publish_queue(session_id).await;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::TurnEnded => {
+ self.busy.remove(&session_id);
+ let dispatched = self.dispatch_next(session_id).await;
+ // Published whatever dispatching did: a claim, a requeued
+ // failure, and an emptied queue are all changes a viewer is
+ // watching for.
+ self.publish_queue(session_id).await;
+ dispatched?;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::SessionStopped => {
+ self.busy.remove(&session_id);
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::SetSandboxSize(size) => {
+ self.apply_sandbox_size(session_id, size).await?;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::Delete => {
+ self.delete(session_id).await?;
+ // The queue and busy mark die with the session: a deleted
+ // session's entries will never dispatch, and leaving them
+ // would leak them for the life of the process. The published
+ // empty snapshot is the viewers' goodbye.
+ self.busy.remove(&session_id);
+ self.queues.drop_session(session_id);
+ self.publish_queue(session_id).await;
+ Ok(CommandOutcome::Completed)
+ }
+ }
+ }
+
+ /// Queue a turn-occupying action, and dispatch the head of the queue
+ /// right away when no turn is running.
+ ///
+ /// The dispatched entry is usually the one just queued, but not
+ /// necessarily: entries can linger from a drain that failed, and FIFO
+ /// order holds regardless. The outcome reports what happened to *this*
+ /// action - still waiting, or on the wire.
+ async fn enqueue_then_dispatch(
+ &self,
+ session_id: AgentSessionId,
+ command: DeliverAction,
+ ) -> Result<CommandOutcome> {
+ let action_id = command.id;
+ queue_result(
+ self.queues.enqueue(
+ session_id,
+ QueuedEntry {
+ action_id,
+ action: command.action,
+ actor: command.actor,
+ announce: command.announce,
+ announced: false,
+ created_at: chrono::Utc::now(),
+ },
+ ),
+ session_id,
+ )?;
+
+ let dispatched = if self.busy.contains_key(&session_id) {
+ Ok(())
+ } else {
+ self.dispatch_next(session_id).await
+ };
+ self.publish_queue(session_id).await;
+ dispatched?;
+
+ Ok(if self.queues.contains(session_id, action_id) {
+ CommandOutcome::Queued
+ } else {
+ CommandOutcome::Completed
+ })
+ }
+
+ /// Push the queue as it now stands to the session's viewers.
+ ///
+ /// Best-effort, like every realtime publish: a dropped snapshot costs a
+ /// viewer liveness until the next change, and the queue itself is intact -
+ /// so this logs and never fails the command it rides on.
+ async fn publish_queue(&self, session_id: AgentSessionId) {
+ let _ = self
+ .sessions
+ .publish_queue_changed(AgentSessionQueueChanged {
+ agent_session_id: session_id,
+ entries: self.queues.list(session_id),
+ })
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(
+ error = ?error,
+ %session_id,
+ "failed to publish an agent session queue change"
+ );
+ });
+ }
+
+ /// Deliver the oldest queued action, marking the session busy on success.
+ ///
+ /// Composition runs first so a lexical failure never posts a chip for a
+ /// prompt that will not reach the agent. The chip is then announced
+ /// (from the raw text) before delivery, so it exists to anchor the turn
+ /// the agent streams into - and it is announced *at most once* per
+ /// entry: the claimed entry remembers a successful announce, so a
+ /// dispatch that fails after the chip posted retries without posting a
+ /// second one.
+ ///
+ /// A failed dispatch puts the entry back at the front: it stays next in
+ /// line for the next turn end or the next prompt, and stays visible in
+ /// the queue meanwhile. The error still propagates, so a caller whose
+ /// own action triggered this dispatch hears about it.
+ #[tracing::instrument(err, skip(self), fields(%session_id))]
+ async fn dispatch_next(&self, session_id: AgentSessionId) -> Result<()> {
+ let Some(mut entry) = self.queues.claim_next(session_id) else {
+ return Ok(());
+ };
+
+ // Compose a copy: the queued entry stays raw so a retry still edits
+ // and re-composes the user's text, and the chip (below) still shows
+ // what they typed rather than the composed payload.
+ let mut composed = entry.action.clone();
+ if let Err(error) = self
+ .compose_action(&mut composed, entry.actor.as_ref(), entry.announce.as_ref())
+ .await
+ {
+ self.queues.requeue_front(session_id, entry);
+ return Err(error);
+ }
+
+ if !entry.announced {
+ let announcement = match self
+ .announcement(
+ session_id,
+ &entry.action,
+ entry.actor.as_ref(),
+ entry.announce.clone(),
+ )
+ .await
+ {
+ Ok(announcement) => announcement,
+ Err(error) => {
+ self.queues.requeue_front(session_id, entry);
+ return Err(error);
+ }
+ };
+ if let Some(announcement) = announcement {
+ if let Err(error) = self.announcer.announce(announcement).await {
+ self.queues.requeue_front(session_id, entry);
+ return Err(error);
+ }
+ entry.announced = true;
+ }
+ }
+
+ let command = DeliverAction {
+ id: entry.action_id,
+ action: composed,
+ actor: entry.actor.clone(),
+ announce: entry.announce.clone(),
+ };
+ match self.deliver(session_id, command).await {
+ Ok(()) => {
+ self.busy.insert(session_id, ());
+ Ok(())
+ }
+ Err(error) => {
+ self.queues.requeue_front(session_id, entry);
+ Err(error)
+ }
}
}
@@ -855,13 +1210,6 @@ where
let defaults = self.defaults.for_bot(bot_id);
let repo_url = defaults.repo_url.clone();
let sandbox_size = self.sessions.user_sandbox_size(&origin.sender).await?;
- let prior_messages = self
- .load_prompt_context(origin.channel_id, origin.message_id, Some(&origin.sender))
- .await;
- let composed_prompt = self
- .prompt_composer
- .compose(&origin.content, Some(&prior_messages))
- .await?;
// Provisioned before the session exists, because the row is what makes
// the token mean anything: it carries the hash the proxy recognises.
@@ -895,19 +1243,6 @@ where
})
.await?;
- self.announcer
- .announce(SessionAnnouncement {
- session_id,
- bot_id,
- origin_channel_id: origin.channel_id,
- origin_thread_id: origin.thread_id,
- origin_message_id: origin.message_id,
- prompted_message_id: MessageId::first(AuthorKind::User),
- prompted_content: origin.content.clone(),
- triggered_by: origin.sender.clone(),
- })
- .await?;
-
let mcp_servers = egress.sandbox.acp_servers();
let container = match self
.containers
@@ -941,69 +1276,46 @@ where
RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
)
.await?;
- let mut action = AgentAction::prompt(composed_prompt);
- let AgentAction::Prompt(prompt) = &mut action else {
- unreachable!("a prompt constructor always returns a prompt action");
- };
- prompt.set_name_source(origin.content);
- self.sessions
- .send_action(
- session_id,
- Some(origin.sender),
- action,
- AgentActionId::mint(),
- )
- .await?;
+ // The first prompt goes through the same door as every later one:
+ // queued raw, then dispatched - which is where it is composed with
+ // channel context and announced as the chip the replies render into.
+ // One door is what holds the one-turn-in-flight invariant from the
+ // session's very first action.
+ self.enqueue_then_dispatch(
+ session_id,
+ DeliverAction {
+ id: AgentActionId::mint(),
+ action: AgentAction::prompt(origin.content),
+ actor: Some(origin.sender),
+ announce: Some(AnnounceOrigin {
+ channel_id: origin.channel_id,
+ thread_id: origin.thread_id,
+ message_id: origin.message_id,
+ }),
+ },
+ )
+ .await?;
Ok(())
}
- /// Do one thing in a session that already exists.
+ /// Deliver one already-composed action to the session's runtime.
///
- /// Three steps, in this order: persist whatever the action changes about
- /// the session, work out whether anyone needs telling, then deliver it.
- /// Announcing before delivery means the chip exists to anchor the turn
- /// the agent streams into.
+ /// Announcing and composition are not this function's business: both
+ /// belong to dispatch (see [`Self::dispatch_next`]), which is the only
+ /// path a turn-occupying prompt travels. Non-turn-occupying actions
+ /// (set-model, stop) arrive here directly and need neither.
#[tracing::instrument(err, skip(self, command), fields(agent.session.id = %session_id))]
async fn deliver(&self, session_id: AgentSessionId, command: DeliverAction) -> Result<()> {
let DeliverAction {
id,
- mut action,
+ action,
actor,
- announce,
+ announce: _,
} = command;
- let raw_action = action.clone();
- if let AgentAction::Prompt(prompt) = &mut action {
- let raw_prompt = prompt.prompt.clone();
- let prior_messages = if let Some(origin) = announce.as_ref() {
- Some(
- self.load_prompt_context(origin.channel_id, origin.message_id, actor.as_ref())
- .await,
- )
- } else {
- None
- };
- prompt.prompt = self
- .prompt_composer
- .compose(&raw_prompt, prior_messages.as_deref())
- .await?;
- prompt.set_name_source(raw_prompt);
- }
-
- let announcement = self
- .announcement(session_id, &raw_action, actor.as_ref(), announce)
- .await?;
-
- // Announced before the prompt is delivered, as `open` does: the chip
- // anchors the turn the agent is about to stream into, so it has to
- // exist before the response can arrive.
- if let Some(announcement) = announcement {
- self.announcer.announce(announcement).await?;
- }
-
match self
.sessions
- .send_action(session_id, actor.clone(), action.clone(), id.clone())
+ .send_action(session_id, actor.clone(), action.clone(), id)
.await
{
Ok(()) => {}
@@ -1049,6 +1361,37 @@ where
Ok(())
}
+ /// Compose a prompt in place. Compact and other actions are left as-is.
+ ///
+ /// Channel context is loaded when the prompt named an origin; a lookup
+ /// failure still composes, with empty history, so a transient context
+ /// outage cannot eat the prompt.
+ async fn compose_action(
+ &self,
+ action: &mut AgentAction,
+ actor: Option<&MacroUserIdStr<'static>>,
+ announce: Option<&AnnounceOrigin>,
+ ) -> Result<()> {
+ let AgentAction::Prompt(prompt) = action else {
+ return Ok(());
+ };
+ let raw_prompt = prompt.prompt.clone();
+ let prior_messages = if let Some(origin) = announce {
+ Some(
+ self.load_prompt_context(origin.channel_id, origin.message_id, actor)
+ .await,
+ )
+ } else {
+ None
+ };
+ prompt.prompt = self
+ .prompt_composer
+ .compose(&raw_prompt, prior_messages.as_deref())
+ .await?;
+ prompt.set_name_source(raw_prompt);
+ Ok(())
+ }
+
async fn load_prompt_context(
&self,
channel_id: macro_uuid::Uuid,
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 261e5af89f..90ef3edf5c 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -28,12 +28,14 @@ use agent_session::testing::InMemoryAgentSessionRepo;
use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
+use tokio::sync::mpsc;
use super::AgentHarnessService;
use crate::domain::error::HarnessError;
use crate::domain::model::{
- AgentKind, AgentRuntimeConfig, AnnounceOrigin, DeliverAction, HarnessCommand, HarnessDefaults,
- MentionOrigin, OpenSession, PriorChannelMessage, SessionDefaults, SpawnContainer,
+ AgentKind, AgentRuntimeConfig, AnnounceOrigin, CommandOutcome, DeliverAction, HarnessCommand,
+ HarnessDefaults, MentionOrigin, OpenSession, PriorChannelMessage, SessionDefaults,
+ SpawnContainer,
};
use crate::domain::ports::{
AgentPromptComposer, ChannelPromptContext, ContainerManager as _, NoPeers,
@@ -52,6 +54,12 @@ fn sender() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")
}
+/// A sender whose email domain is `is_macro_staff` - the identity the
+/// Daytona staff gate admits.
+fn staff_sender() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")
+}
+
fn open_command() -> OpenSession {
let thread_id = macro_uuid::generate_uuid_v7();
OpenSession {
@@ -75,9 +83,11 @@ fn open_command() -> OpenSession {
/// A prompt arriving from a channel that is not the session's own, so it is
/// the announcing case.
fn forward_message(content: &str) -> DeliverAction {
+ // Staff: `disconnected_session` is a Daytona coder bot, and the
+ // execute() gate admits only macro.com actors onto those.
DeliverAction::prompt(
content,
- Some(sender()),
+ Some(staff_sender()),
Some(AnnounceOrigin {
channel_id: macro_uuid::Uuid::from_u128(0xf0),
thread_id: macro_uuid::Uuid::from_u128(0xf1),
@@ -206,26 +216,79 @@ fn harness_for_bot(bot: BotId) -> harness_id::HarnessId {
type TestConnections =
crate::outbound::runtime_registry::HarnessKeyedConnections<MirrorBindings, ContainerSender>;
-fn harness_with_edges(
- prompt_context: PromptContextMock,
- prompt_composer: PromptComposerMock,
-) -> (
+/// Forwards turn events to the harness, then reports them to the test.
+///
+/// The order is the point: `turn_ended` admits the harness's internal
+/// `TurnEnded` command onto the session's FIFO worker *synchronously*, so by
+/// the time the test hears the signal, anything it does next is admitted -
+/// and therefore executed - after the turn end. That is what lets a test
+/// answer a prompt and then act on an idle session without polling.
+struct SignallingTurnObserver {
+ harness: TestHarness,
+ ended: mpsc::UnboundedSender<AgentSessionId>,
+}
+
+impl agent_session::domain::ports::SessionTurnObserver for SignallingTurnObserver {
+ fn turn_ended(&self, id: AgentSessionId) {
+ agent_session::domain::ports::SessionTurnObserver::turn_ended(&self.harness, id);
+ let _ = self.ended.send(id);
+ }
+
+ fn session_stopped(&self, id: AgentSessionId) {
+ agent_session::domain::ports::SessionTurnObserver::session_stopped(&self.harness, id);
+ }
+}
+
+/// The test's half of [`SignallingTurnObserver`].
+struct TurnSignals {
+ ended: mpsc::UnboundedReceiver<AgentSessionId>,
+}
+
+impl TurnSignals {
+ /// Wait until `id`'s running turn has ended *and* the harness has been
+ /// told - after this, the session is idle and the next turn-occupying
+ /// action dispatches instead of queueing.
+ async fn settled(&mut self, id: AgentSessionId) {
+ loop {
+ let ended = self
+ .ended
+ .recv()
+ .await
+ .expect("the turn observer outlives the test");
+ if ended == id {
+ return;
+ }
+ }
+ }
+}
+
+/// Everything a test drives: the service under test and its edges.
+type TestBench = (
TestHarness,
InMemoryAgentSessionRepo,
MockContainerManager,
AnnouncerMock,
Arc<RuntimeRegistry<ContainerSender>>,
-) {
+);
+
+fn harness_with_signals(
+ prompt_context: PromptContextMock,
+ prompt_composer: PromptComposerMock,
+) -> (TestBench, TurnSignals) {
let repo = InMemoryAgentSessionRepo::new();
let containers = MockContainerManager::new();
let announcer = AnnouncerMock::new();
let runtimes = RuntimeRegistry::new();
+ // Same knot as production wiring: the harness is built from the session
+ // service and is also its turn observer, so the observer binds late.
+ let turn_observer = Arc::new(agent_session::domain::ports::LateBoundTurnObserver::new());
let service = AgentHarnessService::new(
AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
NoOpRealtime,
- ),
+ )
+ .with_turn_observer(turn_observer.clone()),
containers.clone(),
announcer.clone(),
TestConnections::new(MirrorBindings, Arc::clone(&runtimes)),
@@ -240,28 +303,32 @@ fn harness_with_edges(
repo_url: "https://github.com/macro-inc/macro".to_owned(),
},
);
- (service, repo, containers, announcer, runtimes)
+ let (ended, ended_rx) = mpsc::unbounded_channel();
+ turn_observer.bind(SignallingTurnObserver {
+ harness: service.clone(),
+ ended,
+ });
+ (
+ (service, repo, containers, announcer, runtimes),
+ TurnSignals { ended: ended_rx },
+ )
}
-fn harness_with_context(
+fn harness_with_edges(
prompt_context: PromptContextMock,
-) -> (
- TestHarness,
- InMemoryAgentSessionRepo,
- MockContainerManager,
- AnnouncerMock,
- Arc<RuntimeRegistry<ContainerSender>>,
-) {
+ prompt_composer: PromptComposerMock,
+) -> TestBench {
+ // Dropping the receiver is fine: sends to a closed channel are ignored,
+ // and a test that never waits on turns does not need the signal.
+ let (bench, _signals) = harness_with_signals(prompt_context, prompt_composer);
+ bench
+}
+
+fn harness_with_context(prompt_context: PromptContextMock) -> TestBench {
harness_with_edges(prompt_context, PromptComposerMock::default())
}
-fn harness() -> (
- TestHarness,
- InMemoryAgentSessionRepo,
- MockContainerManager,
- AnnouncerMock,
- Arc<RuntimeRegistry<ContainerSender>>,
-) {
+fn harness() -> TestBench {
harness_with_context(PromptContextMock::default())
}
@@ -451,7 +518,7 @@ async fn context_failure_still_calls_composer_with_empty_messages_and_delivers()
}
#[tokio::test]
-async fn composer_failure_stops_open_before_announcement_or_delivery() {
+async fn composer_failure_stops_open_delivery_and_keeps_the_prompt_queued() {
let composer = PromptComposerMock::failing("lexical unavailable");
let (service, repo, containers, announcer, _runtimes) =
harness_with_edges(PromptContextMock::default(), composer.clone());
@@ -461,11 +528,25 @@ async fn composer_failure_stops_open_before_announcement_or_delivery() {
.execute(id, HarnessCommand::Open(open_command()))
.await;
+ // Composition happens at dispatch, after the session and its sandbox
+ // exist - so those stand, while the chip is never posted and the prompt
+ // never reaches the agent. The raw prompt stays queued: composition is
+ // retried when the queue next drains, so a transient lexical outage does
+ // not eat the mention.
assert!(matches!(result, Err(HarnessError::PromptComposition(_))));
assert_eq!(composer.calls().len(), 1);
- assert!(repo.get(id).await.is_err());
- assert_eq!(containers.spawned(), 0);
+ assert!(repo.get(id).await.is_ok());
+ assert_eq!(containers.spawned(), 1);
assert!(announcer.announced().is_empty());
+ let queued = service
+ .queued_controls(id)
+ .await
+ .expect("queue is listable");
+ assert_eq!(queued.len(), 1);
+ assert!(matches!(
+ &queued[0].action,
+ AgentAction::Prompt(action) if action.prompt == "@claude fix the failing test"
+ ));
}
#[tokio::test]
@@ -636,10 +717,13 @@ async fn forward_to_a_live_session_reuses_the_transport() {
#[tokio::test]
async fn composer_failure_stops_follow_up_announcement_and_delivery() {
let composer = PromptComposerMock::default();
- let (service, _repo, containers, announcer, _runtimes) =
- harness_with_edges(PromptContextMock::default(), composer.clone());
+ let ((service, _repo, containers, announcer, _runtimes), mut turns) =
+ harness_with_signals(PromptContextMock::default(), composer.clone());
let id = AgentSessionId::new();
let container = live_session(&service, &containers, id).await;
+ // Idle first, so the follow-up dispatches - and fails - rather than
+ // queueing behind the opening turn.
+ turns.settled(id).await;
*composer.failure.lock().unwrap() = Some("lexical unavailable".to_owned());
let prompts_before = prompts(&container.agent()).len();
let announcements_before = announcer.announced().len();
@@ -662,7 +746,8 @@ async fn composer_failure_stops_follow_up_announcement_and_delivery() {
#[tokio::test]
async fn forward_announces_before_delivering_the_prompt() {
- let (service, _repo, containers, announcer, _runtimes) = harness();
+ let ((service, _repo, containers, announcer, _runtimes), mut turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
let id = AgentSessionId::new();
let open = service.execute(id, HarnessCommand::Open(open_command()));
let drive = async {
@@ -681,6 +766,7 @@ async fn forward_announces_before_delivering_the_prompt() {
let (opened, container) = tokio::join!(open, drive);
opened.expect("open should succeed");
assert_eq!(prompts(&container.agent()).len(), 1);
+ turns.settled(id).await;
// A chip that cannot be posted has nothing to anchor the response, so the
// prompt must not reach the agent at all.
@@ -702,7 +788,8 @@ async fn forward_announces_before_delivering_the_prompt() {
#[tokio::test]
async fn a_delivery_failure_is_not_automatically_resumed() {
- let (service, _repo, containers, _announcer, _runtimes) = harness();
+ let ((service, _repo, containers, _announcer, _runtimes), mut turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
let command = open_command();
let id = AgentSessionId::new();
let open = service.execute(id, HarnessCommand::Open(command));
@@ -721,6 +808,7 @@ async fn a_delivery_failure_is_not_automatically_resumed() {
};
let (opened, container) = tokio::join!(open, drive);
opened.expect("open should succeed");
+ turns.settled(id).await;
container.fails_sends_after(0);
let result = service
@@ -914,16 +1002,29 @@ async fn an_admitted_command_survives_caller_cancellation() {
}
#[tokio::test]
-async fn a_failed_announce_surfaces_and_does_not_start_the_agent() {
+async fn a_failed_announce_surfaces_and_keeps_the_prompt_queued() {
let (service, repo, containers, announcer, _runtimes) = harness();
announcer.fails("comms is down");
+ let id = AgentSessionId::new();
let result = service
- .execute(AgentSessionId::new(), HarnessCommand::Open(open_command()))
+ .execute(id, HarnessCommand::Open(open_command()))
.await;
+ // Announcement happens at dispatch, after the sandbox exists - so the
+ // spawn stands, while the prompt never reaches the agent (the chip
+ // anchors the reply, so no chip means no delivery) and stays queued for
+ // the next drain.
assert!(matches!(result, Err(HarnessError::Announce(_))));
- assert_eq!(containers.spawned(), 0);
+ assert_eq!(containers.spawned(), 1);
+ assert_eq!(
+ service
+ .queued_controls(id)
+ .await
+ .expect("queue is listable")
+ .len(),
+ 1
+ );
drop(repo);
}
@@ -961,16 +1062,16 @@ async fn live_session(
container
}
-async fn live_cursor_session(
+/// Open a Daytona-backed (sandboxed coder) session with a staff opener - the
+/// only identity the gate in `execute` lets past `Open`.
+async fn live_sandboxed_coder_session(
service: &TestHarness,
containers: &MockContainerManager,
id: AgentSessionId,
) -> ContainerMock {
let mut command = open_command();
- command.bot_id = bot_id::CURSOR_BOT_ID;
- command.runtime.kind = AgentKind::Cursor;
- command.runtime.harness = "cursor".to_owned();
- command.origin.sender = sender();
+ command.bot_id = bot_id::MACRO_CODER_BOT_ID;
+ command.origin.sender = staff_sender();
let open = service.execute(id, HarnessCommand::Open(command));
let drive = async {
loop {
@@ -986,7 +1087,7 @@ async fn live_cursor_session(
container
};
let (opened, container) = tokio::join!(open, drive);
- opened.expect("cursor session should open");
+ opened.expect("sandboxed coder session should open");
container
}
@@ -1088,25 +1189,277 @@ async fn a_prompt_through_control_reaches_the_agent_without_announcing() {
}
#[tokio::test]
-async fn a_user_control_event_can_drive_their_cursor_session() {
+async fn a_non_staff_control_event_cannot_drive_a_sandboxed_coder_session() {
let (service, _repo, containers, _announcer, _runtimes) = harness();
let id = AgentSessionId::new();
- let container = live_cursor_session(&service, &containers, id).await;
+ let container = live_sandboxed_coder_session(&service, &containers, id).await;
+
+ let error = service
+ .control_event(
+ id,
+ ControlEvent {
+ action: AgentAction::prompt("spend daytona credits"),
+ actor: Some(sender()),
+ },
+ )
+ .await
+ .expect_err("non-staff must not control sandboxed coder sessions");
+
+ assert!(matches!(error, AgentSessionError::Forbidden));
+ assert_eq!(prompts(&container.agent()).len(), 1);
+}
+
+#[tokio::test]
+async fn a_staff_control_event_can_drive_a_sandboxed_coder_session() {
+ let ((service, _repo, containers, _announcer, _runtimes), mut turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = live_sandboxed_coder_session(&service, &containers, id).await;
+ turns.settled(id).await;
service
.control_event(
id,
ControlEvent {
action: AgentAction::prompt("continue"),
- actor: Some(sender()),
+ actor: Some(staff_sender()),
},
)
.await
- .expect("the session owner may control cursor sessions");
+ .expect("macro staff may control sandboxed coder sessions");
assert_eq!(prompts(&container.agent()).len(), 2);
}
+/// Open a session and finish the handshake, but leave the opening prompt's
+/// turn running: the agent has received it and not answered.
+async fn session_with_a_running_turn(
+ service: &TestHarness,
+ containers: &MockContainerManager,
+ id: AgentSessionId,
+) -> ContainerMock {
+ let open = service.execute(id, HarnessCommand::Open(open_command()));
+ let drive = async {
+ loop {
+ if containers.spawned() == 1 {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ let container = containers
+ .container(session_of(containers))
+ .expect("the spawned container is findable");
+ complete_session_handshake(&container).await;
+ // initialize, session/new, and the opening prompt.
+ container.agent().wait_for_requests(3).await;
+ container
+ };
+ let (opened, container) = tokio::join!(open, drive);
+ opened.expect("open should succeed");
+ container
+}
+
+#[tokio::test]
+async fn a_prompt_during_a_running_turn_queues_and_dispatches_when_it_ends() {
+ let ((service, _repo, containers, _announcer, _runtimes), mut turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = session_with_a_running_turn(&service, &containers, id).await;
+ let agent = container.agent();
+
+ let accepted = service
+ .control_event(
+ id,
+ ControlEvent {
+ action: AgentAction::prompt("and then this"),
+ actor: Some(sender()),
+ },
+ )
+ .await
+ .expect("a mid-turn prompt is accepted");
+
+ assert_eq!(
+ accepted.disposition,
+ agent_session::domain::ports::ControlDisposition::Queued
+ );
+ let queued = service.queued_controls(id).await.expect("queue lists");
+ assert_eq!(queued.len(), 1);
+ assert_eq!(queued[0].action_id, accepted.action_id);
+ assert_eq!(prompts(&agent).len(), 1, "nothing reached the agent yet");
+
+ // The running turn ends; the queued prompt dispatches with no user action.
+ agent.completes_prompt().await;
+ agent.wait_for_requests(4).await;
+ turns.settled(id).await;
+
+ assert_eq!(
+ prompts(&agent)[1],
+ // No announce origin, so no channel context: the raw text composes
+ // to itself in the mock.
+ vec![ContentBlock::from("and then this")]
+ );
+ assert!(
+ service
+ .queued_controls(id)
+ .await
+ .expect("queue lists")
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn a_stop_cancels_the_turn_and_the_queue_keeps_draining() {
+ let ((service, _repo, containers, _announcer, _runtimes), _turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = session_with_a_running_turn(&service, &containers, id).await;
+ let agent = container.agent();
+
+ let queued = service
+ .control_event(
+ id,
+ ControlEvent {
+ action: AgentAction::prompt("still wanted after the stop"),
+ actor: Some(sender()),
+ },
+ )
+ .await
+ .expect("a mid-turn prompt is accepted");
+ assert_eq!(
+ queued.disposition,
+ agent_session::domain::ports::ControlDisposition::Queued
+ );
+
+ // The stop bypasses the queue - it cancels the running turn, nothing else.
+ let stopped = service
+ .control_event(
+ id,
+ ControlEvent {
+ action: AgentAction::Stop,
+ actor: Some(sender()),
+ },
+ )
+ .await
+ .expect("a stop is accepted");
+ assert_eq!(
+ stopped.disposition,
+ agent_session::domain::ports::ControlDisposition::Sent
+ );
+ assert_eq!(
+ service
+ .queued_controls(id)
+ .await
+ .expect("queue lists")
+ .len(),
+ 1,
+ "a stop never clears the queue"
+ );
+
+ // The cancelled turn's answer is an ordinary turn end: the queued prompt
+ // dispatches right away.
+ agent.completes_prompt().await;
+ agent.wait_for_requests(4).await;
+
+ assert_eq!(
+ prompts(&agent)[1],
+ vec![ContentBlock::from("still wanted after the stop")]
+ );
+}
+
+#[tokio::test]
+async fn queued_prompts_are_editable_and_removable_until_dispatch() {
+ let ((service, _repo, containers, _announcer, _runtimes), _turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = session_with_a_running_turn(&service, &containers, id).await;
+ let agent = container.agent();
+
+ let prompt = |text: &str| ControlEvent {
+ action: AgentAction::prompt(text),
+ actor: Some(sender()),
+ };
+ let second = service.control_event(id, prompt("second")).await.unwrap();
+ let third = service.control_event(id, prompt("third")).await.unwrap();
+
+ service
+ .edit_queued_control(
+ id,
+ second.action_id,
+ "second, rewritten".to_owned(),
+ Some(staff_sender()),
+ )
+ .await
+ .expect("a waiting prompt is editable");
+ let queued = service.queued_controls(id).await.expect("queue lists");
+ let rewritten = queued
+ .iter()
+ .find(|entry| entry.action_id == second.action_id)
+ .expect("the edited entry is still queued");
+ assert_eq!(
+ rewritten.actor.as_ref(),
+ Some(&staff_sender()),
+ "an edit is attributed to the editor, not the original queuer"
+ );
+ service
+ .remove_queued_control(id, third.action_id, Some(sender()))
+ .await
+ .expect("a waiting prompt is removable");
+
+ agent.completes_prompt().await;
+ agent.wait_for_requests(4).await;
+ assert_eq!(
+ prompts(&agent)[1],
+ vec![ContentBlock::from("second, rewritten")],
+ "the edit lands because dispatch is where the text is read"
+ );
+
+ // Dispatched means gone: there is no un-sending.
+ let error = service
+ .remove_queued_control(id, second.action_id, Some(sender()))
+ .await
+ .expect_err("a dispatched prompt is not removable");
+ assert!(matches!(error, AgentSessionError::QueuedControlNotFound));
+ let error = service
+ .edit_queued_control(id, third.action_id, "resurrect".to_owned(), Some(sender()))
+ .await
+ .expect_err("a removed prompt is gone");
+ assert!(matches!(error, AgentSessionError::QueuedControlNotFound));
+}
+
+#[tokio::test]
+async fn a_model_change_bypasses_the_running_turn() {
+ let ((service, _repo, containers, _announcer, _runtimes), _turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = session_with_a_running_turn(&service, &containers, id).await;
+ let agent = container.agent();
+
+ let accepted = service
+ .control_event(
+ id,
+ ControlEvent {
+ action: AgentAction::set_model("opus"),
+ actor: Some(sender()),
+ },
+ )
+ .await
+ .expect("a model change is accepted mid-turn");
+
+ assert_eq!(
+ accepted.disposition,
+ agent_session::domain::ports::ControlDisposition::Sent
+ );
+ assert!(
+ service
+ .queued_controls(id)
+ .await
+ .expect("queue lists")
+ .is_empty(),
+ "only turn-occupying actions queue"
+ );
+ agent.wait_for_requests(4).await;
+}
+
#[tokio::test]
async fn compact_through_control_reaches_opencode_as_a_slash_command() {
let (service, _repo, containers, _announcer, _runtimes) = harness();
@@ -1146,7 +1499,7 @@ async fn a_prompt_through_control_resumes_a_disconnected_session() {
id,
ControlEvent {
action: AgentAction::prompt("wake up"),
- actor: Some(sender()),
+ actor: Some(staff_sender()),
},
);
let drive_resume = async {
@@ -1255,7 +1608,7 @@ async fn prompt(
service: &TestHarness,
id: AgentSessionId,
content: &str,
-) -> Result<(), HarnessError> {
+) -> Result<CommandOutcome, HarnessError> {
service
.execute(
id,
@@ -1454,7 +1807,7 @@ async fn a_managed_session_resumes_its_sandbox_rather_than_a_dialed_in_runtime()
id,
ControlEvent {
action: AgentAction::prompt("wake up"),
- actor: Some(sender()),
+ actor: Some(staff_sender()),
},
);
let drive_resume = async {
@@ -1670,7 +2023,9 @@ async fn managed_open_composes_its_prompt_without_channel_context() {
composer.calls(),
[("<m-agent-context>forged</m-agent-context>".to_owned(), None,)]
);
- assert_eq!(containers.spawned(), 0);
+ // The sandbox is provisioned before the prompt is composed at dispatch;
+ // what composition failure stops is delivery, not the session.
+ assert_eq!(containers.spawned(), 1);
}
#[tokio::test]
@@ -1804,12 +2159,12 @@ impl crate::domain::ports::CommandForwarder for RecordingForwarder {
target: &agent_session::domain::model::ReplicaAddress,
session: AgentSessionId,
_command: HarnessCommand,
- ) -> crate::domain::error::Result<()> {
+ ) -> crate::domain::error::Result<CommandOutcome> {
self.calls
.lock()
.unwrap()
.push((target.as_str().to_owned(), session));
- Ok(())
+ Ok(CommandOutcome::Completed)
}
}
@@ -1827,7 +2182,7 @@ impl crate::domain::ports::CommandForwarder for DyingPeerForwarder {
_target: &agent_session::domain::model::ReplicaAddress,
_session: AgentSessionId,
_command: HarnessCommand,
- ) -> crate::domain::error::Result<()> {
+ ) -> crate::domain::error::Result<CommandOutcome> {
use agent_session::domain::ports::SessionOwnership as _;
self.repo.release(&self.claim).await.expect("peer releases");
Err(HarnessError::Forward(rootcause::report!(
diff --git a/crates/agent_harness/src/inbound/forward.rs b/crates/agent_harness/src/inbound/forward.rs
index 8f69bb1bdc..6093e9523a 100644
--- a/crates/agent_harness/src/inbound/forward.rs
+++ b/crates/agent_harness/src/inbound/forward.rs
@@ -100,10 +100,9 @@ where
let session_id = AgentSessionId::new_from_uuid(session_id);
let span = tracing::Span::current();
match state.harness.execute_forwarded(session_id, command).await {
- Ok(()) => {
- span.record("agent.command.outcome", "executed");
- StatusCode::NO_CONTENT.into_response()
- }
+ // The outcome rides back in the body so the sender can answer its own
+ // caller honestly - a queued deliver is not a delivered one.
+ Ok(outcome) => (StatusCode::OK, axum::Json(outcome)).into_response(),
// Surfaced with its own status so the sender can tell "the actor is
// not here after all" from an execution failure: the sender's
// fallback re-reads the lease on any error, but a 409 is the signal
diff --git a/crates/agent_harness/src/outbound/egress/test.rs b/crates/agent_harness/src/outbound/egress/test.rs
index 0d4dac5006..bbdcab2cbc 100644
--- a/crates/agent_harness/src/outbound/egress/test.rs
+++ b/crates/agent_harness/src/outbound/egress/test.rs
@@ -151,7 +151,8 @@ fn egress(slugs: &[&str]) -> SandboxEgress {
fn points_every_acp_server_at_the_proxy() {
let servers = egress(&["datadog", "linear"]).acp_servers();
- let rendered: Vec<(String, String, Vec<(String, String)>)> = servers
+ type RenderedServer = (String, String, Vec<(String, String)>);
+ let rendered: Vec<RenderedServer> = servers
.into_iter()
.map(|server| match server {
agent_client_protocol::schema::v1::McpServer::Http(http) => (
diff --git a/crates/agent_harness/src/outbound/forward.rs b/crates/agent_harness/src/outbound/forward.rs
index 17f307107a..a408d9ce5f 100644
--- a/crates/agent_harness/src/outbound/forward.rs
+++ b/crates/agent_harness/src/outbound/forward.rs
@@ -9,7 +9,7 @@ use agent_session::domain::model::{AgentSessionId, ReplicaAddress};
use reqwest::StatusCode;
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::HarnessCommand;
+use crate::domain::model::{CommandOutcome, HarnessCommand};
use crate::domain::ports::CommandForwarder;
/// Header carrying the deployment's shared internal key, as
@@ -57,7 +57,7 @@ impl CommandForwarder for HttpCommandForwarder {
target: &ReplicaAddress,
session: AgentSessionId,
command: HarnessCommand,
- ) -> Result<()> {
+ ) -> Result<CommandOutcome> {
let url = format!(
"{}/internal/agent-sessions/{}/command",
target.as_str().trim_end_matches('/'),
@@ -81,7 +81,12 @@ impl CommandForwarder for HttpCommandForwarder {
let status = response.status();
tracing::Span::current().record("http.response.status_code", status.as_u16());
if status.is_success() {
- return Ok(());
+ // A body-less success (an older peer's 204, mid-deploy) reads as
+ // completed: that was the only outcome such a peer could produce.
+ return Ok(response
+ .json::<CommandOutcome>()
+ .await
+ .unwrap_or(CommandOutcome::Completed));
}
let body = response.text().await.unwrap_or_default();
// 409 is the peer saying "not attached here after all" - the caller's
diff --git a/crates/agent_inmem/Cargo.toml b/crates/agent_inmem/Cargo.toml
index 7ed40ad249..36bf9c041b 100644
--- a/crates/agent_inmem/Cargo.toml
+++ b/crates/agent_inmem/Cargo.toml
@@ -31,4 +31,5 @@ agent_fold = { path = "../agent_fold" }
agent_session = { path = "../agent_session", features = ["test-utils"] }
bot_id = { path = "../bot_id", features = ["test-utils"] }
futures = { workspace = true }
+rig-agent = "0.41.0"
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] }
diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rs
index eabf8f27c2..0ad028634a 100644
--- a/crates/agent_inmem/src/domain/agent.rs
+++ b/crates/agent_inmem/src/domain/agent.rs
@@ -304,6 +304,7 @@ async fn run_turn(
let mut accumulator = StreamAccumulator::new();
let mut failure = None;
+ let mut was_cancelled = false;
loop {
match tokio::time::timeout(TURN_IDLE_TIMEOUT, parts.recv()).await {
Ok(Some(Ok(part))) => {
@@ -318,7 +319,11 @@ async fn run_turn(
accumulator.push(part);
}
Ok(Some(Err(error))) => {
- failure = Some(error.to_string());
+ if error.was_cancelled() {
+ was_cancelled = true;
+ } else {
+ failure = Some(error.to_string());
+ }
break;
}
Ok(None) => break,
@@ -353,7 +358,7 @@ async fn run_turn(
}
state.push_turn(prompt, turn_parts);
- if cancel.is_cancelled() {
+ if was_cancelled || cancel.is_cancelled() {
StopReason::Cancelled
} else {
StopReason::EndTurn
diff --git a/crates/agent_inmem/src/domain/agent/test.rs b/crates/agent_inmem/src/domain/agent/test.rs
index aa7e18e357..8f64075914 100644
--- a/crates/agent_inmem/src/domain/agent/test.rs
+++ b/crates/agent_inmem/src/domain/agent/test.rs
@@ -7,6 +7,8 @@ use agent_client_protocol::schema::v1::{
TextContent,
};
use agent_client_protocol::{Client, ConnectionTo};
+use rig_agent::agent::StreamingError;
+use rig_agent::completion::PromptError;
use super::*;
use crate::domain::engine::TurnEngine;
@@ -16,6 +18,27 @@ struct Harness {
notifications: std::sync::Mutex<Vec<SessionNotification>>,
}
+struct CancelledEngine;
+
+impl TurnEngine for CancelledEngine {
+ fn run_turn(
+ &self,
+ _request: TurnRequest,
+ ) -> tokio::sync::mpsc::Receiver<Result<StreamPart, agent::AgentError>> {
+ let (parts, receiver) = tokio::sync::mpsc::channel(1);
+ tokio::spawn(async move {
+ let cancellation = PromptError::PromptCancelled {
+ chat_history: Vec::new(),
+ reason: "user cancelled".to_owned(),
+ };
+ let error =
+ agent::AgentError::Streaming(StreamingError::Prompt(Box::new(cancellation)));
+ let _ = parts.send(Err(error)).await;
+ });
+ receiver
+ }
+}
+
/// Drive the served agent as a scripted ACP client: initialize, open a
/// session, then hand the connection to `scenario`.
async fn with_agent<Engine, Out>(
@@ -231,6 +254,22 @@ async fn cancel_stops_the_turn_with_the_cancelled_stop_reason() {
assert_eq!(response.stop_reason, StopReason::Cancelled);
}
+#[tokio::test]
+async fn engine_cancellation_is_not_rendered_as_an_error_message() {
+ let (notifications, response) =
+ with_agent(Arc::new(CancelledEngine), async |connection, session| {
+ connection
+ .send_request(text_prompt(&session, "cancel me"))
+ .block_task()
+ .await
+ .expect("a cancelled prompt still completes")
+ })
+ .await;
+
+ assert_eq!(response.stop_reason, StopReason::Cancelled);
+ assert!(notifications.is_empty());
+}
+
#[tokio::test]
async fn a_prompt_for_an_unknown_session_is_refused() {
let engine = Arc::new(ScriptedEngine::new(vec![]));
diff --git a/crates/agent_runtime_protocol/src/domain/action.rs b/crates/agent_runtime_protocol/src/domain/action.rs
index 80f30b3955..2d5ef94f51 100644
--- a/crates/agent_runtime_protocol/src/domain/action.rs
+++ b/crates/agent_runtime_protocol/src/domain/action.rs
@@ -8,6 +8,7 @@ use agent_client_protocol::schema::v1::{
SetSessionConfigOptionRequest,
};
use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage};
+use macro_uuid::Uuid;
use serde::{Deserialize, Serialize};
use crate::domain::schema::v0::{AcpMessage, ToRuntimeMessage};
@@ -21,57 +22,58 @@ pub const MODEL_CONFIG_ID: &str = "model";
/// Identifies one accepted [`AgentAction`] end to end: returned by the
/// control endpoint, written as the JSON-RPC request id on the action's wire
/// frame, and read back off that frame as `request_id` on the folded message
-/// it derives. Correlation is string equality; the value is opaque.
+/// it derives.
///
-/// Minted only by the server at accept time, as `agent_session:{uuid}` - the
-/// prefix is what lets [`Self::from_request_id`] tell our ids from ones other
-/// clients picked.
-#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+/// Minted only by the server at accept time, as a v7 uuid so ids sort by mint
+/// time. On the wire and in JSON it is the bare uuid, and a uuid-shaped
+/// request id is the whole ownership test: the server is the only writer of
+/// runtime-bound frames. The machine's own handshake request ids
+/// (`agent_session:{session}:{n}`) are not uuids and stay `None`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
-pub struct AgentActionId(String);
+pub struct AgentActionId(Uuid);
impl AgentActionId {
- /// What every id this side mints starts with.
- const PREFIX: &'static str = "agent_session:";
-
- /// Mint a fresh id for an action being accepted. v7 so ids sort by mint
- /// time.
+ /// Mint a fresh id for an action being accepted.
#[must_use]
pub fn mint() -> Self {
- Self(format!(
- "{}{}",
- Self::PREFIX,
- macro_uuid::generate_uuid_v7()
- ))
+ Self(macro_uuid::generate_uuid_v7())
}
- /// The same string as the transport's request id type.
+ /// The same id as the transport's request id type.
#[must_use]
pub fn to_request_id(&self) -> RequestId {
- RequestId::Str(self.0.clone())
+ RequestId::Str(self.0.to_string())
}
/// Read an id back off a logged frame. `None` for ids this side did not
/// mint.
#[must_use]
pub fn from_request_id(id: &RequestId) -> Option<Self> {
- match id {
- RequestId::Str(id) if id.starts_with(Self::PREFIX) => Some(Self(id.to_string())),
- _ => None,
- }
+ let RequestId::Str(id) = id else {
+ return None;
+ };
+ id.parse().ok().map(Self)
+ }
+
+ /// The raw uuid, for callers that key on it.
+ #[must_use]
+ pub fn as_uuid(&self) -> Uuid {
+ self.0
}
- /// The id as the string a caller correlates with.
+ /// Rebuild an id a caller was handed earlier, e.g. a queue route's path
+ /// parameter.
#[must_use]
- pub fn as_str(&self) -> &str {
- &self.0
+ pub fn from_uuid(id: Uuid) -> Self {
+ Self(id)
}
}
impl std::fmt::Display for AgentActionId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.write_str(&self.0)
+ self.0.fmt(f)
}
}
@@ -212,15 +214,16 @@ impl AgentAction {
}
}
- /// Whether accepting this action voids the actions queued ahead of it.
+ /// Whether this action occupies a whole agent turn once sent.
///
- /// A stop means "not the work you are about to start either", so the
- /// machine drops what it has queued rather than sending it and then
- /// cancelling it. Every other action is additive and answers `false`.
- pub fn supersedes_queued(&self) -> bool {
+ /// Both prompts and compaction travel as `session/prompt`, and ACP runs
+ /// one prompt at a time - so these are the actions the harness holds in
+ /// its queue while a turn is running, and the ones whose response ends a
+ /// turn. A stop and a model change ride alongside a running turn freely.
+ pub fn occupies_turn(&self) -> bool {
match self {
- Self::Stop => true,
- Self::Prompt(_) | Self::SetModel(_) | Self::Compact => false,
+ Self::Prompt(_) | Self::Compact => true,
+ Self::SetModel(_) | Self::Stop => false,
}
}
diff --git a/crates/agent_runtime_protocol/src/domain/action/test.rs b/crates/agent_runtime_protocol/src/domain/action/test.rs
index 0058833ff5..a0afffda40 100644
--- a/crates/agent_runtime_protocol/src/domain/action/test.rs
+++ b/crates/agent_runtime_protocol/src/domain/action/test.rs
@@ -119,33 +119,29 @@ fn compact_becomes_opencodes_compact_prompt() {
}
#[test]
-fn action_ids_survive_the_trip_through_a_request_id() {
- let id = AgentActionId::mint();
+fn non_uuid_request_ids_are_not_action_ids() {
+ // The harness's own handshake counters and numeric ids were not minted by
+ // the control plane. (A foreign client's bare uuid is indistinguishable
+ // from ours by design: only this side writes ToRuntime frames in
+ // production, so uuid-shaped is treated as ours.)
+ let handshake = RequestId::Str(format!(
+ "agent_session:{}:0",
+ macro_uuid::generate_uuid_v7()
+ ));
+ assert_eq!(AgentActionId::from_request_id(&handshake), None);
assert_eq!(
- AgentActionId::from_request_id(&id.to_request_id()),
- Some(id)
+ AgentActionId::from_request_id(&RequestId::Number(7)),
+ None,
+ "numeric ids are never ours"
);
+ let counter = RequestId::Str("harness:prompt:0".to_owned());
+ assert_eq!(AgentActionId::from_request_id(&counter), None);
}
#[test]
-fn foreign_request_ids_are_not_action_ids() {
- // Zed's bare uuids, the harness's own counters, numeric ids: none of
- // them were minted by the control plane.
- let foreign = RequestId::Str("813ea7f3-b8e1-4af3-b2f4-44f4f445637a".to_owned());
- assert_eq!(AgentActionId::from_request_id(&foreign), None);
-}
-
-#[test]
-fn action_ids_serialize_as_their_bare_string() {
- let id = AgentActionId::mint();
- let json = serde_json::to_string(&id).unwrap();
- assert_eq!(json, format!("\"{id}\""));
-}
-
-#[test]
-fn only_stop_supersedes_what_is_already_queued() {
- assert!(AgentAction::Stop.supersedes_queued());
- assert!(!AgentAction::prompt("keep going").supersedes_queued());
- assert!(!AgentAction::set_model("opus").supersedes_queued());
- assert!(!AgentAction::Compact.supersedes_queued());
+fn only_prompt_shaped_actions_occupy_a_turn() {
+ assert!(AgentAction::prompt("keep going").occupies_turn());
+ assert!(AgentAction::Compact.occupies_turn());
+ assert!(!AgentAction::set_model("opus").occupies_turn());
+ assert!(!AgentAction::Stop.occupies_turn());
}
diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rs
index 3f79166aa6..07f8674f69 100644
--- a/crates/agent_session/src/domain/error.rs
+++ b/crates/agent_session/src/domain/error.rs
@@ -24,6 +24,14 @@ pub enum AgentSessionError {
InvalidName(&'static str),
#[error("the caller may not control this agent session")]
Forbidden,
+ #[error("no queued action with this id; it may already have been dispatched")]
+ QueuedControlNotFound,
+ #[error("only queued prompts can be edited")]
+ QueuedControlNotEditable,
+ #[error("a queued prompt cannot be edited to say nothing; remove it instead")]
+ EmptyQueuedPrompt,
+ #[error("agent session {0} has too many queued actions")]
+ ControlQueueFull(AgentSessionId),
#[error(
"agent session {0} cannot be restored because the agent supports neither session/resume nor session/load"
)]
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index a3021121e4..aa9624855e 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -278,6 +278,47 @@ pub struct SessionBot {
pub avatar_url: Option<String>,
}
+/// One action waiting in a session's queue.
+///
+/// Clients deserialize this, so both derives are used.
+// Domain-owned because the queue GET endpoint and the realtime snapshot
+// serialize this type byte-identically; that identity is the client contract.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct QueuedActionDto {
+ /// The id the action was accepted under.
+ pub action_id: agent_runtime_protocol::domain::action::AgentActionId,
+ /// What kind of action waits - `prompt` or `compact`; only
+ /// turn-occupying actions are ever queued.
+ pub kind: String,
+ /// The prompt's raw text, present for prompts only. What an edit
+ /// replaces.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub prompt: Option<String>,
+ /// The user who queued it, absent when a bot acted on nobody's behalf.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub actor_user_id: Option<String>,
+ /// When it was accepted.
+ pub created_at: DateTime<Utc>,
+}
+
+impl From<super::ports::QueuedControl> for QueuedActionDto {
+ fn from(queued: super::ports::QueuedControl) -> Self {
+ use agent_runtime_protocol::domain::action::AgentAction;
+ let prompt = match &queued.action {
+ AgentAction::Prompt(action) => Some(action.prompt.clone()),
+ _ => None,
+ };
+ Self {
+ action_id: queued.action_id,
+ kind: queued.action.as_ref().to_owned(),
+ prompt,
+ actor_user_id: queued.actor.map(|actor| actor.to_string()),
+ created_at: queued.created_at,
+ }
+ }
+}
+
/// One frame appended to a live session's log, for anyone watching.
///
/// The streaming counterpart of [`SessionLog`]: that is the whole log
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index 6edbc9a85c..bfcd3ac657 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -370,6 +370,18 @@ pub trait AgentSessionLogWriter: Send + 'static {
fn append(&mut self, log: AgentSessionLog) -> impl Future<Output = Result<()>> + Send;
}
+/// A session's queue changed; this is the whole queue as it stands now.
+///
+/// A snapshot rather than a delta so that any one event is self-sufficient:
+/// a viewer applies the newest one it has seen and needs nothing else.
+#[derive(Debug, Clone)]
+pub struct AgentSessionQueueChanged {
+ /// The session whose queue this is.
+ pub agent_session_id: AgentSessionId,
+ /// Everything waiting, oldest (next to dispatch) first.
+ pub entries: Vec<QueuedControl>,
+}
+
/// Pushing a live session's frames to whoever is watching it.
///
/// Separate from the durable log: that is what a reader arriving late fetches
@@ -393,6 +405,95 @@ pub trait AgentSessionRealtime {
) -> impl Future<Output = Result<(), rootcause::Report>> + Send {
async { Ok(()) }
}
+
+ /// Publish a session's changed queue - the whole queue, every time - to
+ /// its viewers.
+ fn publish_queue_changed(
+ &self,
+ _event: AgentSessionQueueChanged,
+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send {
+ async { Ok(()) }
+ }
+}
+
+/// Told when a session's turn ends and when its live actor stops.
+///
+/// What the harness gates its prompt queue on: a turn ending means the agent
+/// can take the next queued prompt, an actor stopping means no turn is in
+/// flight anymore however the last one looked. Both fire from the actor's own
+/// task, so implementations must only hand the fact off - enqueue, notify -
+/// never do the resulting work inline.
+///
+/// Object-safe and synchronous on purpose: the service stores it erased so
+/// wiring it is not another type parameter, and the one production
+/// implementation admits work to a queue synchronously.
+pub trait SessionTurnObserver: Send + Sync + 'static {
+ /// The runtime answered the session's in-flight turn.
+ fn turn_ended(&self, id: AgentSessionId);
+
+ /// The session's live actor is gone - disconnect, teardown, or crash. Any
+ /// in-flight turn went with it, without [`Self::turn_ended`] firing.
+ fn session_stopped(&self, id: AgentSessionId);
+}
+
+impl<T: SessionTurnObserver + ?Sized> SessionTurnObserver for std::sync::Arc<T> {
+ fn turn_ended(&self, id: AgentSessionId) {
+ (**self).turn_ended(id);
+ }
+
+ fn session_stopped(&self, id: AgentSessionId) {
+ (**self).session_stopped(id);
+ }
+}
+
+/// A [`SessionTurnObserver`] for services with no queue above them: tests,
+/// offline tooling, and replay.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct NoOpTurnObserver;
+
+impl SessionTurnObserver for NoOpTurnObserver {
+ fn turn_ended(&self, _id: AgentSessionId) {}
+
+ fn session_stopped(&self, _id: AgentSessionId) {}
+}
+
+/// A [`SessionTurnObserver`] bound after construction, for the composition
+/// root's chicken-and-egg: the session service wants its observer at build
+/// time, and the observer (the harness) is built *from* the session service.
+///
+/// Events before `bind` are dropped. That window is the instants between the
+/// two constructions, before anything serves traffic - nothing turns then.
+#[derive(Default)]
+pub struct LateBoundTurnObserver {
+ observer: std::sync::OnceLock<Box<dyn SessionTurnObserver>>,
+}
+
+impl LateBoundTurnObserver {
+ /// An observer awaiting its target.
+ #[must_use]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Attach the real observer. A second bind is a wiring bug; the first
+ /// stays authoritative and the duplicate is dropped.
+ pub fn bind(&self, observer: impl SessionTurnObserver) {
+ let _ = self.observer.set(Box::new(observer));
+ }
+}
+
+impl SessionTurnObserver for LateBoundTurnObserver {
+ fn turn_ended(&self, id: AgentSessionId) {
+ if let Some(observer) = self.observer.get() {
+ observer.turn_ended(id);
+ }
+ }
+
+ fn session_stopped(&self, id: AgentSessionId) {
+ if let Some(observer) = self.observer.get() {
+ observer.session_stopped(id);
+ }
+ }
}
/// Generates a concise display name from a session's first prompt.
@@ -446,6 +547,42 @@ pub struct ControlEvent {
pub actor: Option<MacroUserIdStr<'static>>,
}
+/// What accepting a control operation did with it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ControlDisposition {
+ /// The action reached the agent's runtime.
+ Sent,
+ /// A turn was running, so the action waits in the session's queue and
+ /// dispatches when that turn ends. Until then it can be listed, edited,
+ /// and removed under its action id.
+ Queued,
+}
+
+/// A control operation the recipient accepted: the id a caller correlates
+/// with, and what became of it.
+#[derive(Debug, Clone)]
+pub struct AcceptedControl {
+ /// Matches `requestId` on the folded message the action derives once it
+ /// dispatches, and names the queue entry until then.
+ pub action_id: AgentActionId,
+ /// Whether it went out or waits.
+ pub disposition: ControlDisposition,
+}
+
+/// One action waiting in a session's queue, as a reader sees it.
+#[derive(Debug, Clone)]
+pub struct QueuedControl {
+ /// The id the action was accepted under.
+ pub action_id: AgentActionId,
+ /// What will be delivered - a prompt's text is the raw user text, which
+ /// is what editing replaces.
+ pub action: AgentAction,
+ /// The user who queued it, absent when a bot acted on nobody's behalf.
+ pub actor: Option<MacroUserIdStr<'static>>,
+ /// When it was accepted.
+ pub created_at: chrono::DateTime<chrono::Utc>,
+}
+
/// Whoever holds a session's live resources, told when the durable session
/// changes in a way those resources have to follow.
///
@@ -459,12 +596,44 @@ pub trait AgentSessionNotificationRecipient: Send + Sync + 'static {
fn session_deleted(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;
/// A control operation the live connection has to be told about. Returns
- /// the action id the caller correlates against the fold stream.
+ /// the action id the caller correlates against the fold stream, and
+ /// whether the action went out or waits in the session's queue.
fn control_event(
&self,
id: AgentSessionId,
event: ControlEvent,
- ) -> impl Future<Output = Result<AgentActionId>> + Send;
+ ) -> impl Future<Output = Result<AcceptedControl>> + Send;
+
+ /// The actions waiting in this session's queue, oldest first.
+ fn queued_controls(
+ &self,
+ id: AgentSessionId,
+ ) -> impl Future<Output = Result<Vec<QueuedControl>>> + Send;
+
+ /// Replace a queued prompt's text. [`AgentSessionError::QueuedControlNotFound`]
+ /// once it has dispatched; [`AgentSessionError::QueuedControlNotEditable`]
+ /// for a queued action that carries no text.
+ ///
+ /// `actor` is the user responsible, judged by the same gates as sending:
+ /// whoever may not prompt a session may not rewrite what it is about to
+ /// be prompted with.
+ fn edit_queued_control(
+ &self,
+ id: AgentSessionId,
+ action_id: AgentActionId,
+ prompt: String,
+ actor: Option<MacroUserIdStr<'static>>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Remove a queued action before it dispatches.
+ /// [`AgentSessionError::QueuedControlNotFound`] once it has. `actor` as
+ /// on [`Self::edit_queued_control`].
+ fn remove_queued_control(
+ &self,
+ id: AgentSessionId,
+ action_id: AgentActionId,
+ actor: Option<MacroUserIdStr<'static>>,
+ ) -> impl Future<Output = Result<()>> + Send;
/// Resize this session's sandbox and remember `size` as the owner's default.
fn set_sandbox_size(
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index 6cec76b604..1872cad6d6 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -53,7 +53,8 @@ use super::model::{
};
use super::ports::{
AgentConnector, AgentSessionLogRepo, AgentSessionLogWriter, AgentSessionNameGenerator,
- AgentSessionRealtime, AgentSessionRepo, NoOpAgentSessionNameGenerator, SessionOwnership,
+ AgentSessionQueueChanged, AgentSessionRealtime, AgentSessionRepo,
+ NoOpAgentSessionNameGenerator, NoOpTurnObserver, SessionOwnership, SessionTurnObserver,
};
use super::session::actors::{SessionActor, SessionCommand, Stepped};
use super::session::{CloseReason, Input};
@@ -202,6 +203,17 @@ pub trait AgentSessionService: Send + Sync + 'static {
/// that have to be kept agreeing. See [`SessionLog`].
fn session_log(&self, id: AgentSessionId) -> impl Future<Output = Result<SessionLog>> + Send;
+ /// Push a session's changed queue - the whole queue, every time - to its
+ /// viewers.
+ ///
+ /// Here because this service is the harness's one door to the realtime
+ /// stream and its audience: the queue itself lives above, but who is
+ /// watching a session is answered here for log frames already.
+ fn publish_queue_changed(
+ &self,
+ event: AgentSessionQueueChanged,
+ ) -> impl Future<Output = Result<()>> + Send;
+
/// Persist the sandbox size this session is running at.
fn set_sandbox_size(
&self,
@@ -238,6 +250,9 @@ pub struct AgentSessionServiceImpl<R, Folds, Rt, Namer = NoOpAgentSessionNameGen
folds: Folds,
realtime: Rt,
name_generator: Namer,
+ /// Told when a session's turn ends or its actor stops - the harness's
+ /// prompt-queue gate. Erased so wiring it is not another type parameter.
+ turn_observer: Arc<dyn SessionTurnObserver>,
active: Arc<ActiveSessions>,
/// This service's identity in the session-management lease. Minted at
/// construction: a restarted process is a new replica, and its claims
@@ -261,6 +276,7 @@ impl<R, Folds, Rt> AgentSessionServiceImpl<R, Folds, Rt> {
folds,
realtime,
name_generator: NoOpAgentSessionNameGenerator,
+ turn_observer: Arc::new(NoOpTurnObserver),
active: Arc::new(DashMap::new()),
replica: ReplicaId::mint(),
tasks: TaskTracker::new(),
@@ -282,6 +298,7 @@ impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
folds: self.folds,
realtime: self.realtime,
name_generator,
+ turn_observer: self.turn_observer,
active: self.active,
replica: self.replica,
tasks: self.tasks,
@@ -290,6 +307,14 @@ impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
}
}
+ /// Replace the no-op turn observer with whoever gates prompts on turns -
+ /// in production, the harness's queue.
+ #[must_use]
+ pub fn with_turn_observer(mut self, turn_observer: Arc<dyn SessionTurnObserver>) -> Self {
+ self.turn_observer = turn_observer;
+ self
+ }
+
/// This service's identity in the session-management lease, for the
/// composition root to heartbeat while the process lives.
#[must_use]
@@ -397,6 +422,7 @@ impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
logs,
command_rx,
attachment.handshake,
+ Arc::clone(&self.turn_observer),
);
self.tasks.spawn(
run_session(
@@ -407,6 +433,7 @@ impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
self.cancellation.clone(),
self.repo.clone(),
claim,
+ Arc::clone(&self.turn_observer),
)
.with_current_subscriber(),
);
@@ -696,6 +723,10 @@ where
})
}
+ async fn publish_queue_changed(&self, event: AgentSessionQueueChanged) -> Result<()> {
+ Ok(self.realtime.publish_queue_changed(event).await?)
+ }
+
async fn set_sandbox_size(&self, id: AgentSessionId, size: SandboxSize) -> Result<()> {
self.repo.set_sandbox_size(id, size).await
}
@@ -1070,6 +1101,9 @@ where
/// Step the actor until its machine stops, then release the registry entry
/// and the session's management claim.
+// One argument per fact the loop owns; a struct here would only move the
+// same list one level down.
+#[allow(clippy::too_many_arguments)]
async fn run_session<Connector, Logs, Ownership>(
mut actor: SessionActor<Connector, Logs>,
active: std::sync::Weak<ActiveSessions>,
@@ -1078,6 +1112,7 @@ async fn run_session<Connector, Logs, Ownership>(
cancellation: CancellationToken,
ownership: Ownership,
claim: SessionClaim,
+ turn_observer: Arc<dyn SessionTurnObserver>,
) where
Connector: AgentConnector,
Logs: AgentSessionLogWriter + AgentSessionRepo,
@@ -1115,4 +1150,8 @@ async fn run_session<Connector, Logs, Ownership>(
current.commands.is_some() && Arc::ptr_eq(&current.marker, &marker)
});
}
+ // Last, after the registry entry is gone: whatever the observer does with
+ // the fact - clear a busy flag, dispatch nothing - it sees a session that
+ // really has no actor anymore.
+ turn_observer.session_stopped(id);
}
diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rs
index e2ee17977f..4fcb3dce3e 100644
--- a/crates/agent_session/src/domain/service/test.rs
+++ b/crates/agent_session/src/domain/service/test.rs
@@ -721,6 +721,7 @@ async fn cancellation_does_not_drop_an_effect_batch_after_machine_mutation() {
logs,
command_rx,
handshake,
+ Arc::new(crate::domain::ports::NoOpTurnObserver),
);
let active = Arc::new(ActiveSessions::new());
let cancellation = CancellationToken::new();
@@ -735,6 +736,7 @@ async fn cancellation_does_not_drop_an_effect_batch_after_machine_mutation() {
cancellation.clone(),
repo.clone(),
claim,
+ Arc::new(crate::domain::ports::NoOpTurnObserver),
));
open_test_session(&inbound_tx, &mut outbound_rx, session).await;
@@ -798,6 +800,7 @@ async fn live_inbound_logs_do_not_reuse_the_expired_handshake_deadline() {
logs,
command_rx,
handshake,
+ Arc::new(crate::domain::ports::NoOpTurnObserver),
);
let active = Arc::new(ActiveSessions::new());
let cancellation = CancellationToken::new();
@@ -812,6 +815,7 @@ async fn live_inbound_logs_do_not_reuse_the_expired_handshake_deadline() {
cancellation.clone(),
repo.clone(),
claim,
+ Arc::new(crate::domain::ports::NoOpTurnObserver),
)
.with_current_subscriber(),
);
diff --git a/crates/agent_session/src/domain/session/actors.rs b/crates/agent_session/src/domain/session/actors.rs
index 084de131c0..5dc28cf54a 100644
--- a/crates/agent_session/src/domain/session/actors.rs
+++ b/crates/agent_session/src/domain/session/actors.rs
@@ -29,7 +29,9 @@ use crate::domain::error::{AgentSessionError, Result};
use crate::domain::model::{AgentSessionId, AgentSessionLog, Message};
use agent_runtime_protocol::domain::ports::{TransportReceiver, TransportSender};
-use crate::domain::ports::{AgentConnector, AgentSessionLogWriter, AgentSessionRepo};
+use crate::domain::ports::{
+ AgentConnector, AgentSessionLogWriter, AgentSessionRepo, SessionTurnObserver,
+};
use super::{CloseReason, Effect, HandshakeStatus, Input, RuntimeStatus, SessionMachine};
@@ -81,6 +83,9 @@ pub(crate) struct SessionActor<Connector: AgentConnector, Logs> {
/// dead. Every effect run before then hangs off it.
handshake_span: Option<tracing::Span>,
handshake_deadline: Instant,
+ /// Told when the machine reports a turn over, so the harness can dispatch
+ /// its next queued prompt.
+ turn_observer: std::sync::Arc<dyn SessionTurnObserver>,
}
impl<Connector, Logs> SessionActor<Connector, Logs>
@@ -100,6 +105,7 @@ where
logs: Logs,
commands: mpsc::Receiver<SessionCommand>,
handshake: watch::Sender<HandshakeStatus>,
+ turn_observer: std::sync::Arc<dyn SessionTurnObserver>,
) -> Self {
// Marked unseen so the first wait reports the *current* state rather
// than only later changes: a session binding after the handshake
@@ -128,6 +134,7 @@ where
commands,
handshake_span: Some(handshake_span),
handshake_deadline: Instant::now() + HANDSHAKE_TIMEOUT,
+ turn_observer,
}
}
@@ -342,6 +349,14 @@ where
// actor holds one.
let _ = self.handshake.send(HandshakeStatus::Ready(restore));
}
+ Effect::TurnEnded { action_id } => {
+ tracing::info!(
+ id = %self.machine.id(),
+ %action_id,
+ "agent session turn ended"
+ );
+ self.turn_observer.turn_ended(self.machine.id());
+ }
Effect::Complete { token, result } => {
if let Err(error) = &result {
token.span.record("otel.status_code", "ERROR");
@@ -470,7 +485,8 @@ where
Effect::Send { .. }
| Effect::Log { .. }
| Effect::PersistAcpSession { .. }
- | Effect::Initialized { .. } => {}
+ | Effect::Initialized { .. }
+ | Effect::TurnEnded { .. } => {}
}
}
if let Some(stop) = stop {
diff --git a/crates/agent_session/src/domain/session/session.rs b/crates/agent_session/src/domain/session/session.rs
index ad6a29e374..bdb1437225 100644
--- a/crates/agent_session/src/domain/session/session.rs
+++ b/crates/agent_session/src/domain/session/session.rs
@@ -35,6 +35,13 @@ pub struct SessionMachine<Token> {
next_request: u64,
/// Held outside the phase so a partial flush strands nothing.
pending: VecDeque<PendingAction<Token>>,
+ /// The newest turn-occupying request the runtime has not answered yet.
+ /// The harness dispatches its queue one turn at a time, so there is at
+ /// most one in the ordinary course; a direct `send_action` caller racing
+ /// the previous turn's answer displaces the old entry (see
+ /// [`Self::flush`]). Its response - result or error alike - is what emits
+ /// [`Effect::TurnEnded`].
+ in_flight_turn: Option<(RequestId, AgentActionId)>,
resume_session_id: Option<SessionId>,
/// Directory the agent works in, snapshotted on the session row at
/// creation; `session/new`, `session/resume`, and `session/load` all
@@ -55,6 +62,7 @@ impl<Token> SessionMachine<Token> {
phase: SessionPhase::Booting,
next_request: INITIAL_REQUEST_NUM,
pending: VecDeque::new(),
+ in_flight_turn: None,
resume_session_id: None,
workspace,
mcp_servers,
@@ -73,6 +81,7 @@ impl<Token> SessionMachine<Token> {
phase: SessionPhase::Booting,
next_request: INITIAL_REQUEST_NUM,
pending: VecDeque::new(),
+ in_flight_turn: None,
resume_session_id: Some(session_id),
workspace,
mcp_servers,
@@ -140,12 +149,6 @@ impl<Token> SessionMachine<Token> {
) -> Vec<Effect<Token>> {
let mut effects = Vec::new();
- // A superseding action - a stop - means the queued actions must not
- // reach the agent at all, rather than being sent and then cancelled.
- if action.supersedes_queued() {
- self.drop_pending(&mut effects);
- }
-
let session_id = match &self.phase {
SessionPhase::Booting
| SessionPhase::Initializing { .. }
@@ -231,6 +234,19 @@ impl<Token> SessionMachine<Token> {
fn on_frame(&mut self, frame: RawJsonRpcMessage, effects: &mut Vec<Effect<Token>>) {
if matches!(self.phase, SessionPhase::Live { .. }) {
+ // The in-flight turn's answer ends the turn whichever shape it
+ // takes: a result carries the stop reason, an error is the agent
+ // refusing the prompt. Either way the agent can take another.
+ if let Some((request_id, _)) = &self.in_flight_turn
+ && frame.response_id() == Some(request_id)
+ {
+ let (_, action_id) = self
+ .in_flight_turn
+ .take()
+ .expect("checked just above; nothing between the check and the take");
+ effects.push(Effect::TurnEnded { action_id });
+ return;
+ }
self.respond_to_permission_request(&frame, effects);
return;
}
@@ -486,8 +502,24 @@ impl<Token> SessionMachine<Token> {
fn flush(&mut self, session_id: &SessionId, effects: &mut Vec<Effect<Token>>) {
while let Some(queued) = self.pending.pop_front() {
let request_id = queued.action_id.to_request_id();
- match queued.action.to_runtime(session_id, request_id) {
+ match queued.action.to_runtime(session_id, request_id.clone()) {
Ok(message) => {
+ if queued.action.occupies_turn() {
+ // The harness dispatches one turn at a time, but
+ // `send_action` is public and a direct caller can race
+ // the previous turn's answer. Track the newest: its
+ // answer is what ends the turn, and the displaced
+ // one's answer simply matches nothing.
+ if let Some((_, displaced)) =
+ self.in_flight_turn.replace((request_id, queued.action_id))
+ {
+ tracing::warn!(
+ id = %self.id,
+ %displaced,
+ "a turn-occupying action was sent while a turn was in flight"
+ );
+ }
+ }
effects.push(Effect::Send {
from: queued.from,
message,
@@ -505,25 +537,15 @@ impl<Token> SessionMachine<Token> {
}
}
- /// Drop every queued action without sending it, resolving each caller.
- ///
- /// `Ok` rather than an error: the action was accepted and then superseded
- /// by a later one, which is not a failure of the caller's request. It also
- /// matters upstream - the harness treats `Disconnected` as "reattach and
- /// resend", which would resurrect the very prompt a stop just dropped.
- fn drop_pending(&mut self, effects: &mut Vec<Effect<Token>>) {
- while let Some(queued) = self.pending.pop_front() {
- effects.push(Effect::Complete {
- token: queued.token,
- result: Ok(()),
- });
- }
- }
-
/// End the connection: fail everything queued, then stop. The `Stop` is
/// last so the shell resolves waiting callers before it tears down.
+ ///
+ /// A turn that was in flight is forgotten without [`Effect::TurnEnded`]:
+ /// the turn did not end, the session stopped, and the shell reports that
+ /// as its own event.
fn die(&mut self, reason: StopReason, effects: &mut Vec<Effect<Token>>) {
self.phase = SessionPhase::Dead;
+ self.in_flight_turn = None;
while let Some(queued) = self.pending.pop_front() {
effects.push(Effect::Complete {
token: queued.token,
diff --git a/crates/agent_session/src/domain/session/tests.rs b/crates/agent_session/src/domain/session/tests.rs
index a922a51e0d..4b2f28111d 100644
--- a/crates/agent_session/src/domain/session/tests.rs
+++ b/crates/agent_session/src/domain/session/tests.rs
@@ -39,6 +39,15 @@ fn command_with_id(text: &str, action_id: AgentActionId, token: u32) -> Input<u3
}
}
+fn set_model_with_id(model: &str, action_id: AgentActionId, token: u32) -> Input<u32> {
+ Input::Command {
+ from: None,
+ action: AgentAction::set_model(model),
+ action_id,
+ token,
+ }
+}
+
fn acp_ready() -> Input<u32> {
Input::Inbound(ToServerMessage::Event {
event: SystemEvent::AcpReady,
@@ -201,8 +210,11 @@ fn a_second_acp_ready_only_logs() {
#[test]
fn session_new_success_flushes_the_queue() {
let mut machine = machine();
+ // One prompt and one model change: at most one turn-occupying action is
+ // ever pending, because the harness dispatches its queue one turn at a
+ // time - the machine asserts that contract rather than managing it.
machine.handle(command("first", 1));
- machine.handle(command("second", 2));
+ machine.handle(set_model_with_id("opus", AgentActionId::mint(), 2));
begin_opening(&mut machine);
let effects = machine.handle(session_opened("acp-42"));
@@ -579,11 +591,13 @@ fn actions_go_out_under_the_ids_they_were_accepted_with() {
let live_id = AgentActionId::mint();
let mut machine = machine();
- machine.handle(command_with_id("queued", queued_id.clone(), 1));
+ machine.handle(command_with_id("queued", queued_id, 1));
let initialize = machine.handle(acp_ready());
let open = machine.handle(initialized());
let flushed = machine.handle(session_opened("acp-42"));
- let live = machine.handle(command_with_id("live", live_id.clone(), 2));
+ // A model change, because the queued prompt's turn is still in flight and
+ // only non-turn actions may go out beside it.
+ let live = machine.handle(set_model_with_id("opus", live_id, 2));
let mut ids = Vec::new();
for effects in [&initialize, &open, &flushed, &live] {
@@ -613,56 +627,121 @@ fn stop(token: u32) -> Input<u32> {
}
#[test]
-fn a_stop_while_booting_drops_the_queued_prompts_instead_of_sending_them() {
+fn a_stop_while_booting_leaves_the_queued_prompt_to_run() {
let mut machine = machine();
// Queued, because nothing can be sent before the handshake finishes.
assert!(machine.handle(command("start the work", 1)).is_empty());
assert_eq!(machine.pending_count(), 1);
+ // A stop cancels only the turn that is running - here, none. The queued
+ // prompt stays: it will open the next turn, which its caller can stop in
+ // turn if they meant that too.
let effects = machine.handle(stop(2));
+ assert!(effects.is_empty(), "nothing completes early: {effects:?}");
+ assert_eq!(machine.pending_count(), 2);
+
+ begin_opening(&mut machine);
+ let effects = machine.handle(session_opened("acp-1"));
+
+ assert_eq!(
+ sent_methods(&effects),
+ ["session/prompt", "session/cancel"],
+ "the prompt still runs, in the order the actions were accepted"
+ );
+}
+
+/// The response answering the in-flight prompt's request id, however the
+/// turn ended.
+fn turn_answered(request_id: RequestId) -> Input<u32> {
+ frame(RawJsonRpcMessage::response(
+ request_id,
+ Ok(serde_json::json!({ "stopReason": "end_turn" })),
+ ))
+}
+
+/// A live machine with `action_id`'s prompt in flight.
+fn machine_with_turn_in_flight(action_id: AgentActionId) -> SessionMachine<u32> {
+ let mut machine = machine();
+ machine.handle(command_with_id("work", action_id, 1));
+ begin_opening(&mut machine);
+ machine.handle(session_opened("acp-42"));
+ machine
+}
+
+#[test]
+fn the_prompts_response_ends_its_turn() {
+ let action_id = AgentActionId::mint();
+ let mut machine = machine_with_turn_in_flight(action_id);
+
+ let effects = machine.handle(turn_answered(action_id.to_request_id()));
- // The queued prompt resolves as accepted rather than failed: it was
- // superseded, and a `Disconnected` here would have the harness resume and
- // resend the very prompt this stop dropped.
assert!(
matches!(
- effects[0],
- Effect::Complete {
- token: 1,
- result: Ok(())
- }
+ effects[..],
+ [Effect::Log { .. }, Effect::TurnEnded { action_id: ended }] if ended == action_id
),
- "the queued prompt is completed, got {effects:?}"
+ "the answer is logged and the turn ends: {effects:?}"
);
- // Only the stop is left to send once the session opens.
- assert_eq!(machine.pending_count(), 1);
+}
- begin_opening(&mut machine);
- let effects = machine.handle(session_opened("acp-1"));
+#[test]
+fn a_refused_prompt_ends_its_turn_too() {
+ let action_id = AgentActionId::mint();
+ let mut machine = machine_with_turn_in_flight(action_id);
+
+ let effects = machine.handle(frame(RawJsonRpcMessage::response(
+ action_id.to_request_id(),
+ Err(agent_client_protocol::Error::internal_error()),
+ )));
- let methods: Vec<_> = effects
- .iter()
- .filter_map(|effect| match effect {
- Effect::Send {
- message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Notification(n))),
- ..
- } => Some(n.method.to_string()),
- Effect::Send {
- message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(r))),
- ..
- } => Some(r.method.to_string()),
- _ => None,
- })
- .collect();
assert!(
- !methods.iter().any(|method| method == "session/prompt"),
- "the dropped prompt must never reach the agent, sent {methods:?}"
+ matches!(
+ effects[..],
+ [Effect::Log { .. }, Effect::TurnEnded { action_id: ended }] if ended == action_id
+ ),
+ "a refusal ends the turn the same way: {effects:?}"
);
+}
+
+#[test]
+fn another_requests_response_does_not_end_the_turn() {
+ let action_id = AgentActionId::mint();
+ let mut machine = machine_with_turn_in_flight(action_id);
+
+ // A model change answered while the prompt's turn is still running.
+ let effects = machine.handle(frame(RawJsonRpcMessage::response(
+ AgentActionId::mint().to_request_id(),
+ Ok(serde_json::json!({})),
+ )));
+ assert!(
+ matches!(effects[..], [Effect::Log { .. }]),
+ "only logged: {effects:?}"
+ );
+
+ // The turn is still in flight: its own answer still ends it.
+ let effects = machine.handle(turn_answered(action_id.to_request_id()));
+ assert!(matches!(effects[..], [
+ Effect::Log { .. },
+ Effect::TurnEnded { action_id: ended }
+ ] if ended == action_id));
+}
+
+#[test]
+fn a_death_mid_turn_is_not_a_turn_end() {
+ let action_id = AgentActionId::mint();
+ let mut machine = machine_with_turn_in_flight(action_id);
+
+ let effects = machine.handle(Input::Closed(CloseReason::TransportClosed));
+
assert!(
- methods.iter().any(|method| method == "session/cancel"),
- "the stop itself is still delivered, sent {methods:?}"
+ !effects
+ .iter()
+ .any(|effect| matches!(effect, Effect::TurnEnded { .. })),
+ "the session stopped; the turn did not end: {effects:?}"
);
+ assert!(matches!(effects[..], [Effect::Stop { .. }]));
+ assert_eq!(machine.status(), RuntimeStatus::Dead);
}
#[test]
diff --git a/crates/agent_session/src/domain/session/types.rs b/crates/agent_session/src/domain/session/types.rs
index ef3a3302ef..02c0bfa203 100644
--- a/crates/agent_session/src/domain/session/types.rs
+++ b/crates/agent_session/src/domain/session/types.rs
@@ -204,6 +204,13 @@ pub enum Effect<Token> {
/// Whether the action reached the transport.
result: Result<()>,
},
+ /// The runtime answered the in-flight turn's `session/prompt` - however it
+ /// ended, including cancelled and refused. What the harness drains its
+ /// queue on: the agent can take another prompt now.
+ TurnEnded {
+ /// The action whose turn this was.
+ action_id: AgentActionId,
+ },
/// Tear the connection down. Always the final effect of its batch; the
/// machine is [`RuntimeStatus::Dead`] once it appears.
Stop {
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 379c7b3951..e843148a9a 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -2,8 +2,11 @@
//!
//! Every route authenticates its caller and then authorizes them with
//! [`AgentSessionAccessLevelExtractor`], checked before the handler body
-//! runs: viewing a session or its log needs `View`; renaming, controlling, or
-//! deleting one needs `Owner`. Permission comes from the session's own `entity_access`
+//! runs: viewing a session, its log, or its queue needs `View`; controlling
+//! it - sending, and editing or removing what is queued - needs `Edit`, which
+//! the mention's channel holds, so whoever can prompt the bot through the
+//! thread can prompt it here too; renaming, resizing, or deleting the session
+//! needs `Owner`. Permission comes from the session's own `entity_access`
//! rows - the owner with owner access, the mention's channel as editor - never
//! from any channel the session was once rendered in. Handlers only map
//! transport DTOs to domain types and call the [`AgentSessionService`]; they
@@ -28,7 +31,7 @@ use axum::{
};
use chrono::DateTime;
use chrono::Utc;
-use entity_access::domain::models::{OwnerAccessLevel, ViewAccessLevel};
+use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAccessLevel};
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::AgentSessionAccessLevelExtractor;
use macro_authorization::{
@@ -46,7 +49,7 @@ use crate::domain::model::{
StoredAgentSessionLog,
};
use crate::domain::ports::{
- AgentSessionNotificationRecipient, BotDirectory, BotFacts, ControlEvent,
+ AgentSessionNotificationRecipient, BotDirectory, BotFacts, ControlDisposition, ControlEvent,
OpenExternalAgentSession, OpenManagedSession, SessionOpener, SessionThread,
};
use crate::domain::service::AgentSessionService;
@@ -206,6 +209,15 @@ where
"/{session_id}/control",
post(control_agent_session_handler::<R, Access, Auth>),
)
+ .route(
+ "/{session_id}/queue",
+ get(get_agent_session_queue_handler::<R, Access, Auth>),
+ )
+ .route(
+ "/{session_id}/queue/{action_id}",
+ put(edit_queued_action_handler::<R, Access, Auth>)
+ .delete(remove_queued_action_handler::<R, Access, Auth>),
+ )
.route(
"/{session_id}/sandbox-size",
put(put_agent_session_sandbox_size_handler::<R, Access, Auth>),
@@ -265,6 +277,18 @@ impl IntoResponse for AgentSessionApiError {
Self::Domain(AgentSessionError::Forbidden) => {
(StatusCode::FORBIDDEN, "forbidden").into_response()
}
+ // Already dispatched, removed, or never queued: the caller's
+ // entry is not waiting anymore, and there is no un-sending it.
+ Self::Domain(error @ AgentSessionError::QueuedControlNotFound) => {
+ (StatusCode::NOT_FOUND, error.to_string()).into_response()
+ }
+ Self::Domain(
+ error @ (AgentSessionError::QueuedControlNotEditable
+ | AgentSessionError::EmptyQueuedPrompt),
+ ) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response(),
+ Self::Domain(error @ AgentSessionError::ControlQueueFull(_)) => {
+ (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response()
+ }
Self::Domain(error) => {
if let AgentSessionError::InvalidName(message) = error {
return (StatusCode::BAD_REQUEST, Json(message)).into_response();
@@ -335,6 +359,68 @@ pub struct ControlRequest {
pub action: AgentAction,
}
+/// What accepting a control operation did with it, on the wire.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum ControlStatusDto {
+ /// The action reached the agent's runtime.
+ Sent,
+ /// A turn was running; the action waits in the session's queue and
+ /// dispatches when that turn ends. Until then `GET .../queue` lists it,
+ /// and it can be edited or removed under its action id.
+ Queued,
+}
+
+impl From<ControlDisposition> for ControlStatusDto {
+ fn from(disposition: ControlDisposition) -> Self {
+ match disposition {
+ ControlDisposition::Sent => Self::Sent,
+ ControlDisposition::Queued => Self::Queued,
+ }
+ }
+}
+
+/// Response body for a control operation.
+///
+/// Clients deserialize this, so both derives are used.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ControlResponse {
+ /// Matches `requestId` on the folded message this action derives once it
+ /// dispatches, and names the queue entry until then.
+ pub action_id: AgentActionId,
+ /// Whether the action went out or waits in the queue.
+ pub status: ControlStatusDto,
+}
+
+// The queue entry's wire shape lives in the domain (`QueuedActionDto`,
+// re-exported here) because two transports serve it byte-identically: this
+// router's GET and the realtime queue snapshot.
+pub use crate::domain::model::QueuedActionDto;
+
+/// Response body for a session's queue: everything waiting, oldest first.
+///
+/// A wrapper rather than a bare array so that anything which is about the
+/// response rather than about an entry has somewhere to go later without
+/// breaking every client.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentSessionQueueResponse {
+ /// The waiting actions, in dispatch order.
+ pub entries: Vec<QueuedActionDto>,
+}
+
+/// Request body for editing a queued prompt.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct EditQueuedActionRequest {
+ /// The new raw prompt text, replacing the old wholesale. Never blank: a
+ /// prompt with nothing to say is a removal, and there is an endpoint for
+ /// that.
+ #[schema(min_length = 1)]
+ pub prompt: String,
+}
+
/// Response body describing an agent session.
///
/// Clients deserialize this, so both derives are used.
@@ -532,15 +618,20 @@ async fn ensure_harness_serves_session<R: AgentSessionNotificationRecipient>(
responses(
(
status = 200,
- body = AgentActionId,
- description = "Accepted; matches `requestId` on the folded message this action derives"
+ body = ControlResponse,
+ description = "Accepted. `sent` reached the runtime; `queued` waits for the \
+ running turn to end and can be edited or removed meanwhile."
),
(status = 401, body = String),
(status = 403, body = String),
+ (status = 422, body = String),
(status = 500, body = String),
)
)]
/// Perform a control operation on a live agent session.
+///
+/// Edit access suffices: whoever can prompt the bot through its thread can
+/// prompt it here.
#[tracing::instrument(
skip_all,
fields(
@@ -555,12 +646,12 @@ pub async fn control_agent_session_handler<
Access: EntityAccessService,
Auth: MacroAuthorizationService,
>(
- _access: AgentSessionAccessLevelExtractor<OwnerAccessLevel, Access, Auth>,
+ _access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,
State(state): State<AgentSessionControlState<R, Access, Auth>>,
caller: MacroAuthorizationExtractor<Auth, UserBotOrHarness>,
Path(session_id): Path<Uuid>,
Json(req): Json<ControlRequest>,
-) -> Result<Json<AgentActionId>, AgentSessionApiError> {
+) -> Result<Json<ControlResponse>, AgentSessionApiError> {
ensure_harness_serves_session(
&caller.authorization,
state.recipient.as_ref(),
@@ -573,7 +664,7 @@ pub async fn control_agent_session_handler<
.acting_user()
.map(|user| user.macro_user_id.clone());
- let action_id = state
+ let accepted = state
.recipient
.control_event(
AgentSessionId::new_from_uuid(session_id),
@@ -584,7 +675,153 @@ pub async fn control_agent_session_handler<
)
.await?;
- Ok(Json(action_id))
+ Ok(Json(ControlResponse {
+ action_id: accepted.action_id,
+ status: accepted.disposition.into(),
+ }))
+}
+
+#[utoipa::path(
+ get,
+ path = "/agent-sessions/{session_id}/queue",
+ tag = "agent-sessions",
+ operation_id = "get_agent_session_queue",
+ params(("session_id" = Uuid, Path, description = "ID of the agent session")),
+ responses(
+ (status = 200, body = AgentSessionQueueResponse),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// The actions waiting to dispatch in this session, oldest first.
+#[tracing::instrument(skip_all, fields(session_id = %session_id), err(Debug))]
+pub async fn get_agent_session_queue_handler<
+ R: AgentSessionNotificationRecipient,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ _access: AgentSessionAccessLevelExtractor<ViewAccessLevel, Access, Auth>,
+ State(state): State<AgentSessionControlState<R, Access, Auth>>,
+ caller: MacroAuthorizationExtractor<Auth, UserBotOrHarness>,
+ Path(session_id): Path<Uuid>,
+) -> Result<Json<AgentSessionQueueResponse>, AgentSessionApiError> {
+ let session_id = AgentSessionId::new_from_uuid(session_id);
+ ensure_harness_serves_session(&caller.authorization, state.recipient.as_ref(), session_id)
+ .await?;
+
+ let entries = state.recipient.queued_controls(session_id).await?;
+ Ok(Json(AgentSessionQueueResponse {
+ entries: entries.into_iter().map(Into::into).collect(),
+ }))
+}
+
+#[utoipa::path(
+ put,
+ path = "/agent-sessions/{session_id}/queue/{action_id}",
+ tag = "agent-sessions",
+ operation_id = "edit_queued_action",
+ params(
+ ("session_id" = Uuid, Path, description = "ID of the agent session"),
+ ("action_id" = Uuid, Path, description = "ID the action was accepted under"),
+ ),
+ request_body = EditQueuedActionRequest,
+ responses(
+ (status = 204),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 404, body = String, description = "Already dispatched or never queued"),
+ (status = 422, body = String, description = "The queued action carries no text"),
+ (status = 500, body = String),
+ )
+)]
+/// Replace a queued prompt's text before it dispatches.
+#[tracing::instrument(
+ skip_all,
+ fields(actor = %caller.acting_entity(), session_id = %session_id, %action_id),
+ err(Debug)
+)]
+pub async fn edit_queued_action_handler<
+ R: AgentSessionNotificationRecipient,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ _access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,
+ State(state): State<AgentSessionControlState<R, Access, Auth>>,
+ caller: MacroAuthorizationExtractor<Auth, UserBotOrHarness>,
+ Path((session_id, action_id)): Path<(Uuid, Uuid)>,
+ Json(request): Json<EditQueuedActionRequest>,
+) -> Result<StatusCode, AgentSessionApiError> {
+ let session_id = AgentSessionId::new_from_uuid(session_id);
+ ensure_harness_serves_session(&caller.authorization, state.recipient.as_ref(), session_id)
+ .await?;
+ if request.prompt.trim().is_empty() {
+ return Err(AgentSessionError::EmptyQueuedPrompt.into());
+ }
+
+ let actor = caller
+ .authorization
+ .acting_user()
+ .map(|user| user.macro_user_id.clone());
+ state
+ .recipient
+ .edit_queued_control(
+ session_id,
+ AgentActionId::from_uuid(action_id),
+ request.prompt,
+ actor,
+ )
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+#[utoipa::path(
+ delete,
+ path = "/agent-sessions/{session_id}/queue/{action_id}",
+ tag = "agent-sessions",
+ operation_id = "remove_queued_action",
+ params(
+ ("session_id" = Uuid, Path, description = "ID of the agent session"),
+ ("action_id" = Uuid, Path, description = "ID the action was accepted under"),
+ ),
+ responses(
+ (status = 204),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 404, body = String, description = "Already dispatched or never queued"),
+ (status = 500, body = String),
+ )
+)]
+/// Remove a queued action before it dispatches. There is no un-sending: an
+/// action that already went out answers 404.
+#[tracing::instrument(
+ skip_all,
+ fields(actor = %caller.acting_entity(), session_id = %session_id, %action_id),
+ err(Debug)
+)]
+pub async fn remove_queued_action_handler<
+ R: AgentSessionNotificationRecipient,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ _access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,
+ State(state): State<AgentSessionControlState<R, Access, Auth>>,
+ caller: MacroAuthorizationExtractor<Auth, UserBotOrHarness>,
+ Path((session_id, action_id)): Path<(Uuid, Uuid)>,
+) -> Result<StatusCode, AgentSessionApiError> {
+ let session_id = AgentSessionId::new_from_uuid(session_id);
+ ensure_harness_serves_session(&caller.authorization, state.recipient.as_ref(), session_id)
+ .await?;
+
+ let actor = caller
+ .authorization
+ .acting_user()
+ .map(|user| user.macro_user_id.clone());
+ state
+ .recipient
+ .remove_queued_control(session_id, AgentActionId::from_uuid(action_id), actor)
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
}
#[utoipa::path(
diff --git a/crates/agent_session/src/outbound/connection_gateway_realtime.rs b/crates/agent_session/src/outbound/connection_gateway_realtime.rs
index a550d21eae..c77dca727f 100644
--- a/crates/agent_session/src/outbound/connection_gateway_realtime.rs
+++ b/crates/agent_session/src/outbound/connection_gateway_realtime.rs
@@ -33,11 +33,12 @@
//! identified by that session plus the session-local `"{turn}:{author}"` id
//! the fold derives.
+use crate::domain::model::QueuedActionDto;
use crate::domain::model::{
AgentSessionId, AgentSessionLog, AgentSessionRenamed, LogAppended, Message,
StoredAgentSessionLog,
};
-use crate::domain::ports::AgentSessionRealtime;
+use crate::domain::ports::{AgentSessionQueueChanged, AgentSessionRealtime};
use connection_gateway_client::ConnectionGatewayClient;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
@@ -55,6 +56,14 @@ pub const AGENT_SESSION_LOG: &str = "agent_session_log";
/// The realtime message type carrying a persisted session-name change.
pub const AGENT_SESSION_RENAMED: &str = "agent_session_renamed";
+/// The realtime message type carrying a session's whole queue after a change.
+///
+/// Always the full queue, never a delta: any one event is a complete,
+/// self-sufficient truth, which is what lets a client treat the socket as the
+/// only writer once it has heard anything on it - a late `GET .../queue`
+/// response can never carry information the socket will not deliver.
+pub const AGENT_SESSION_QUEUE: &str = "agent_session_queue";
+
/// The body of an [`AGENT_SESSION_LOG`] message - the module docs are the
/// contract.
#[derive(Debug, Serialize)]
@@ -94,6 +103,31 @@ impl From<AgentSessionRenamed> for AgentSessionRenamedEvent {
}
}
+/// The body of an [`AGENT_SESSION_QUEUE`] message.
+///
+/// `entries` are [`QueuedActionDto`] - the exact rows `GET .../queue` serves -
+/// for the same reason the log event flattens [`Message`] verbatim: a client
+/// baselining from the REST endpoint and one following the socket are reading
+/// the same bytes, so they cannot disagree about what an entry means.
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentSessionQueueEvent {
+ /// The session whose queue this is.
+ pub agent_session_id: Uuid,
+ /// Everything waiting, oldest (next to dispatch) first. The whole queue,
+ /// every time - see [`AGENT_SESSION_QUEUE`].
+ pub entries: Vec<QueuedActionDto>,
+}
+
+impl From<AgentSessionQueueChanged> for AgentSessionQueueEvent {
+ fn from(event: AgentSessionQueueChanged) -> Self {
+ Self {
+ agent_session_id: event.agent_session_id.as_uuid(),
+ entries: event.entries.into_iter().map(Into::into).collect(),
+ }
+ }
+}
+
impl AgentSessionLogEvent {
/// The event for one appended frame.
#[must_use]
@@ -179,17 +213,20 @@ where
Ok(())
}
- async fn publish_renamed(&self, event: AgentSessionRenamed) -> Result<(), rootcause::Report> {
+ async fn publish_queue_changed(
+ &self,
+ event: AgentSessionQueueChanged,
+ ) -> Result<(), rootcause::Report> {
let recipients = self.participants.viewers(event.agent_session_id).await?;
if recipients.is_empty() {
return Ok(());
}
- let payload = serde_json::to_value(AgentSessionRenamedEvent::from(event))
+ let payload = serde_json::to_value(AgentSessionQueueEvent::from(event))
.map_err(|error| rootcause::report!(error))?;
self.client
.batch_send_message(
- AGENT_SESSION_RENAMED.to_string(),
+ AGENT_SESSION_QUEUE.to_string(),
payload,
recipients
.iter()
@@ -201,87 +238,27 @@ where
Ok(())
}
-}
-
-#[cfg(test)]
-mod test {
- use super::*;
- use agent_fold::testing::{TURN, parse_log_as, test_session};
- fn stored(entry: AgentSessionLog) -> StoredAgentSessionLog {
- StoredAgentSessionLog {
- created_at: chrono::DateTime::parse_from_rfc3339("2026-08-13T12:34:56.789Z")
- .expect("valid timestamp")
- .to_utc(),
- entry,
+ async fn publish_renamed(&self, event: AgentSessionRenamed) -> Result<(), rootcause::Report> {
+ let recipients = self.participants.viewers(event.agent_session_id).await?;
+ if recipients.is_empty() {
+ return Ok(());
}
- }
-
- /// The event is the REST entry shape plus its session id - the property the
- /// client relies on to fold a streamed frame and a fetched one with the
- /// same code. Asserted on the serialized keys rather than the types,
- /// because it is the bytes the two halves actually agree on.
- #[test]
- fn an_event_is_a_log_entry_plus_the_session_id() {
- let entry = parse_log_as(test_session(), TURN)
- .into_iter()
- .find(|entry| entry.user_id.is_some())
- .expect("the fixture attributes its prompt");
-
- let value = serde_json::to_value(AgentSessionLogEvent::new(LogAppended {
- agent_session_id: test_session(),
- entry: stored(entry),
- }))
- .expect("the event serializes");
-
- let object = value.as_object().expect("an event is a JSON object");
- assert_eq!(
- object.keys().map(String::as_str).collect::<Vec<_>>(),
- vec![
- "agentSessionId",
- "createdAt",
- "userId",
- "direction",
- "content"
- ],
- "the frame is flattened in beside the id, not nested under it"
- );
- assert_eq!(object["direction"], "to_runtime");
- assert_eq!(object["content"]["method"], "session/prompt");
- assert_eq!(object["createdAt"], "2026-08-13T12:34:56.789Z");
- }
-
- #[test]
- fn renamed_event_uses_the_frontend_wire_shape() {
- let event = AgentSessionRenamedEvent::from(AgentSessionRenamed {
- agent_session_id: test_session(),
- name: "Fix Flaky Tests".to_owned(),
- });
- assert_eq!(
- serde_json::to_value(event).expect("event serializes"),
- serde_json::json!({
- "agentSessionId": test_session().as_uuid(),
- "name": "Fix Flaky Tests",
- })
- );
- }
-
- /// An unattributed frame omits the key rather than sending null, matching
- /// the REST entry and keeping `userId` optional on the client.
- #[test]
- fn an_unattributed_frame_omits_the_user() {
- let entry = parse_log_as(test_session(), TURN)
- .into_iter()
- .find(|entry| entry.user_id.is_none())
- .expect("the fixture has unattributed frames");
-
- let value = serde_json::to_value(AgentSessionLogEvent::new(LogAppended {
- agent_session_id: test_session(),
- entry: stored(entry),
- }))
- .expect("the event serializes");
+ let payload = serde_json::to_value(AgentSessionRenamedEvent::from(event))
+ .map_err(|error| rootcause::report!(error))?;
+ self.client
+ .batch_send_message(
+ AGENT_SESSION_RENAMED.to_string(),
+ payload,
+ recipients
+ .iter()
+ .map(|user| GatewayEntityType::User.with_entity_str(user.as_ref()))
+ .collect(),
+ )
+ .await
+ .map_err(|error| rootcause::report!(error))?;
- assert!(value.get("userId").is_none(), "got {value}");
+ Ok(())
}
}
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 65239d61fa..7f3a439f8c 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -52,3 +52,22 @@ An agent session is `/app/agent/<uuid>`. The composer placeholder is
used in chat and channels; they serialize as `<m-document-mention>` tags in the prompt
the agent sees. Agent replies that emit those tags render as clickable chips in the
transcript (and in the originating channel thread).
+
+- Sending is never blocked by a running turn. A prompt sent mid-turn is queued
+ **server-side** and dispatches automatically when the current turn ends, one per turn.
+ The queue holds at most 50 entries; past that a send is refused with an error rather
+ than queued.
+- Queued prompts render as a list between the transcript and the input, newest at the
+ top — the prompt about to be sent sits at the bottom, immediately above the input.
+ Each row shows a `Queued` label (with `by {user}` when someone else queued it —
+ several users can stack prompts in one session's queue) and an always-visible remove
+ (`X`) button. A queued prompt's text is itself an editor: click in and type — changes
+ autosave (debounced, and on blur) with no save button. Editing and removal are
+ possible only until the entry dispatches; after that the row simply becomes the next
+ user message in the transcript.
+- Keyboard: Up at the very start of the composer input moves focus into the
+ bottom (next-to-send) queue row; further Up presses walk toward newer entries, Down
+ walks back and past the bottom row returns to the input.
+- The stop button cancels only the **current** turn. The queue keeps draining: the next
+ queued prompt starts a new turn. To fully quiesce a session, remove the queued
+ entries, then stop.
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index fd722ca9dc..58f6717c71 100644
--- a/packages/sdk/generated/agent-harness/index.ts
+++ b/packages/sdk/generated/agent-harness/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AgentAction, AgentActionId, AgentPromptAction, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionResponse, AgentSetModelAction, BotId, ClientOptions, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, ExternalSessionResponse, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionResponse, GetAgentSessionResponses, LogDirectionDto, LogFrameDto, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto } from './types.gen';
+export type { AgentAction, AgentActionId, AgentPromptAction, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, ClientOptions, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ExternalSessionResponse, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, LogDirectionDto, LogFrameDto, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.ts
index 891635a837..f8509e85b5 100644
--- a/packages/sdk/generated/agent-harness/sdk.gen.ts
+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses } from './types.gen';
+import type { ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -114,6 +114,9 @@ export class Sdk extends HeyApiClient {
/**
* Perform a control operation on a live agent session.
+ *
+ * Edit access suffices: whoever can prompt the bot through its thread can
+ * prompt it here.
*/
public controlAgentSession<ThrowOnError extends boolean = false>(options: Options<ControlAgentSessionData, ThrowOnError>): RequestResult<ControlAgentSessionResponses, ControlAgentSessionErrors, ThrowOnError> {
return (options.client ?? this.client).post<ControlAgentSessionResponses, ControlAgentSessionErrors, ThrowOnError>({
@@ -154,6 +157,35 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * The actions waiting to dispatch in this session, oldest first.
+ */
+ public getAgentSessionQueue<ThrowOnError extends boolean = false>(options: Options<GetAgentSessionQueueData, ThrowOnError>): RequestResult<GetAgentSessionQueueResponses, GetAgentSessionQueueErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<GetAgentSessionQueueResponses, GetAgentSessionQueueErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/queue', ...options });
+ }
+
+ /**
+ * Remove a queued action before it dispatches. There is no un-sending: an
+ * action that already went out answers 404.
+ */
+ public removeQueuedAction<ThrowOnError extends boolean = false>(options: Options<RemoveQueuedActionData, ThrowOnError>): RequestResult<RemoveQueuedActionResponses, RemoveQueuedActionErrors, ThrowOnError> {
+ return (options.client ?? this.client).delete<RemoveQueuedActionResponses, RemoveQueuedActionErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/queue/{action_id}', ...options });
+ }
+
+ /**
+ * Replace a queued prompt's text before it dispatches.
+ */
+ public editQueuedAction<ThrowOnError extends boolean = false>(options: Options<EditQueuedActionData, ThrowOnError>): RequestResult<EditQueuedActionResponses, EditQueuedActionErrors, ThrowOnError> {
+ return (options.client ?? this.client).put<EditQueuedActionResponses, EditQueuedActionErrors, ThrowOnError>({
+ url: '/agent-sessions/{session_id}/queue/{action_id}',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Resize this session's sandbox and remember the size as the owner's default.
*/
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 1984a14e10..737befe305 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -21,11 +21,13 @@ export type AgentAction = (AgentPromptAction & {
* Identifies one accepted [`AgentAction`] end to end: returned by the
* control endpoint, written as the JSON-RPC request id on the action's wire
* frame, and read back off that frame as `request_id` on the folded message
- * it derives. Correlation is string equality; the value is opaque.
+ * it derives.
*
- * Minted only by the server at accept time, as `agent_session:{uuid}` - the
- * prefix is what lets [`Self::from_request_id`] tell our ids from ones other
- * clients picked.
+ * Minted only by the server at accept time, as a v7 uuid so ids sort by mint
+ * time. On the wire and in JSON it is the bare uuid, and a uuid-shaped
+ * request id is the whole ownership test: the server is the only writer of
+ * runtime-bound frames. The machine's own handshake request ids
+ * (`agent_session:{session}:{n}`) are not uuids and stay `None`.
*/
export type AgentActionId = string;
@@ -95,6 +97,20 @@ export type AgentSessionLogResponse = {
entries: Array<AgentSessionLogEntryDto>;
};
+/**
+ * Response body for a session's queue: everything waiting, oldest first.
+ *
+ * A wrapper rather than a bare array so that anything which is about the
+ * response rather than about an entry has somewhere to go later without
+ * breaking every client.
+ */
+export type AgentSessionQueueResponse = {
+ /**
+ * The waiting actions, in dispatch order.
+ */
+ entries: Array<QueuedActionDto>;
+};
+
/**
* Response body describing an agent session.
*
@@ -191,6 +207,28 @@ export type BotId = string;
*/
export type ControlRequest = AgentAction;
+/**
+ * Response body for a control operation.
+ *
+ * Clients deserialize this, so both derives are used.
+ */
+export type ControlResponse = {
+ /**
+ * Matches `requestId` on the folded message this action derives once it
+ * dispatches, and names the queue entry until then.
+ */
+ actionId: AgentActionId;
+ /**
+ * Whether the action went out or waits in the queue.
+ */
+ status: ControlStatusDto;
+};
+
+/**
+ * What accepting a control operation did with it, on the wire.
+ */
+export type ControlStatusDto = 'sent' | 'queued';
+
/**
* Request body for `POST /agent-sessions`.
*
@@ -289,6 +327,18 @@ export type CreateSessionThread = {
threadId?: string | null;
};
+/**
+ * Request body for editing a queued prompt.
+ */
+export type EditQueuedActionRequest = {
+ /**
+ * The new raw prompt text, replacing the old wholesale. Never blank: a
+ * prompt with nothing to say is a removal, and there is an endpoint for
+ * that.
+ */
+ prompt: string;
+};
+
/**
* The provider-side identity of an externally-served session.
*/
@@ -335,6 +385,36 @@ export type LogFrameDto = {
direction: LogDirectionDto;
};
+/**
+ * One action waiting in a session's queue.
+ *
+ * Clients deserialize this, so both derives are used.
+ */
+export type QueuedActionDto = {
+ /**
+ * The id the action was accepted under.
+ */
+ actionId: AgentActionId;
+ /**
+ * The user who queued it, absent when a bot acted on nobody's behalf.
+ */
+ actorUserId?: string | null;
+ /**
+ * When it was accepted.
+ */
+ createdAt: string;
+ /**
+ * What kind of action waits - `prompt` or `compact`; only
+ * turn-occupying actions are ever queued.
+ */
+ kind: string;
+ /**
+ * The prompt's raw text, present for prompts only. What an edit
+ * replaces.
+ */
+ prompt?: string | null;
+};
+
/**
* Request body for renaming an agent session.
*/
@@ -525,6 +605,7 @@ export type ControlAgentSessionData = {
export type ControlAgentSessionErrors = {
401: string;
403: string;
+ 422: string;
500: string;
};
@@ -532,9 +613,9 @@ export type ControlAgentSessionError = ControlAgentSessionErrors[keyof ControlAg
export type ControlAgentSessionResponses = {
/**
- * Accepted; matches `requestId` on the folded message this action derives
+ * Accepted. `sent` reached the runtime; `queued` waits for the running turn to end and can be edited or removed meanwhile.
*/
- 200: AgentActionId;
+ 200: ControlResponse;
};
export type ControlAgentSessionResponse = ControlAgentSessionResponses[keyof ControlAgentSessionResponses];
@@ -592,6 +673,104 @@ export type RenameAgentSessionResponses = {
export type RenameAgentSessionResponse = RenameAgentSessionResponses[keyof RenameAgentSessionResponses];
+export type GetAgentSessionQueueData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/queue';
+};
+
+export type GetAgentSessionQueueErrors = {
+ 401: string;
+ 403: string;
+ 500: string;
+};
+
+export type GetAgentSessionQueueError = GetAgentSessionQueueErrors[keyof GetAgentSessionQueueErrors];
+
+export type GetAgentSessionQueueResponses = {
+ 200: AgentSessionQueueResponse;
+};
+
+export type GetAgentSessionQueueResponse = GetAgentSessionQueueResponses[keyof GetAgentSessionQueueResponses];
+
+export type RemoveQueuedActionData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ /**
+ * ID the action was accepted under
+ */
+ action_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/queue/{action_id}';
+};
+
+export type RemoveQueuedActionErrors = {
+ 401: string;
+ 403: string;
+ /**
+ * Already dispatched or never queued
+ */
+ 404: string;
+ 500: string;
+};
+
+export type RemoveQueuedActionError = RemoveQueuedActionErrors[keyof RemoveQueuedActionErrors];
+
+export type RemoveQueuedActionResponses = {
+ 204: void;
+};
+
+export type RemoveQueuedActionResponse = RemoveQueuedActionResponses[keyof RemoveQueuedActionResponses];
+
+export type EditQueuedActionData = {
+ body: EditQueuedActionRequest;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ /**
+ * ID the action was accepted under
+ */
+ action_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/queue/{action_id}';
+};
+
+export type EditQueuedActionErrors = {
+ 401: string;
+ 403: string;
+ /**
+ * Already dispatched or never queued
+ */
+ 404: string;
+ /**
+ * The queued action carries no text
+ */
+ 422: string;
+ 500: string;
+};
+
+export type EditQueuedActionError = EditQueuedActionErrors[keyof EditQueuedActionErrors];
+
+export type EditQueuedActionResponses = {
+ 204: void;
+};
+
+export type EditQueuedActionResponse = EditQueuedActionResponses[keyof EditQueuedActionResponses];
+
export type PutAgentSessionSandboxSizeData = {
body: SandboxSizeBody;
path: {
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index e261a2ebfc..39f203e4bc 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -293,6 +293,7 @@
"post": {
"tags": ["agent-sessions"],
"summary": "Perform a control operation on a live agent session.",
+ "description": "Edit access suffices: whoever can prompt the bot through its thread can\nprompt it here.",
"operationId": "control_agent_session",
"parameters": [
{
@@ -318,11 +319,11 @@
},
"responses": {
"200": {
- "description": "Accepted; matches `requestId` on the folded message this action derives",
+ "description": "Accepted. `sent` reached the runtime; `queued` waits for the running turn to end and can be edited or removed meanwhile.",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/AgentActionId"
+ "$ref": "#/components/schemas/ControlResponse"
}
}
}
@@ -347,6 +348,16 @@
}
}
},
+ "422": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -496,6 +507,233 @@
}
}
},
+ "/agent-sessions/{session_id}/queue": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "The actions waiting to dispatch in this session, oldest first.",
+ "operationId": "get_agent_session_queue",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentSessionQueueResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/agent-sessions/{session_id}/queue/{action_id}": {
+ "put": {
+ "tags": ["agent-sessions"],
+ "summary": "Replace a queued prompt's text before it dispatches.",
+ "operationId": "edit_queued_action",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "action_id",
+ "in": "path",
+ "description": "ID the action was accepted under",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/EditQueuedActionRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Already dispatched or never queued",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "The queued action carries no text",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["agent-sessions"],
+ "summary": "Remove a queued action before it dispatches. There is no un-sending: an\naction that already went out answers 404.",
+ "operationId": "remove_queued_action",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "action_id",
+ "in": "path",
+ "description": "ID the action was accepted under",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Already dispatched or never queued",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions/{session_id}/sandbox-size": {
"put": {
"tags": ["agent-sessions"],
@@ -637,7 +875,8 @@
},
"AgentActionId": {
"type": "string",
- "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives. Correlation is string equality; the value is opaque.\n\nMinted only by the server at accept time, as `agent_session:{uuid}` - the\nprefix is what lets [`Self::from_request_id`] tell our ids from ones other\nclients picked."
+ "format": "uuid",
+ "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nMinted only by the server at accept time, as a v7 uuid so ids sort by mint\ntime. On the wire and in JSON it is the bare uuid, and a uuid-shaped\nrequest id is the whole ownership test: the server is the only writer of\nruntime-bound frames. The machine's own handshake request ids\n(`agent_session:{session}:{n}`) are not uuids and stay `None`."
},
"AgentPromptAction": {
"type": "object",
@@ -692,6 +931,20 @@
}
}
},
+ "AgentSessionQueueResponse": {
+ "type": "object",
+ "description": "Response body for a session's queue: everything waiting, oldest first.\n\nA wrapper rather than a bare array so that anything which is about the\nresponse rather than about an entry has somewhere to go later without\nbreaking every client.",
+ "required": ["entries"],
+ "properties": {
+ "entries": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/QueuedActionDto"
+ },
+ "description": "The waiting actions, in dispatch order."
+ }
+ }
+ },
"AgentSessionResponse": {
"type": "object",
"description": "Response body describing an agent session.\n\nClients deserialize this, so both derives are used.",
@@ -820,6 +1073,26 @@
],
"description": "Request body for a control operation on a live session.\n\nA wrapper around the operation rather than the bare enum so that fields\nwhich are about the request rather than the operation have somewhere to go.\nThe acting user is deliberately not one of them: it comes from the caller's\ncredentials, so that a caller cannot attribute an operation to someone else.\n\nClients serialize this, so both derives are used."
},
+ "ControlResponse": {
+ "type": "object",
+ "description": "Response body for a control operation.\n\nClients deserialize this, so both derives are used.",
+ "required": ["actionId", "status"],
+ "properties": {
+ "actionId": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "Matches `requestId` on the folded message this action derives once it\ndispatches, and names the queue entry until then."
+ },
+ "status": {
+ "$ref": "#/components/schemas/ControlStatusDto",
+ "description": "Whether the action went out or waits in the queue."
+ }
+ }
+ },
+ "ControlStatusDto": {
+ "type": "string",
+ "description": "What accepting a control operation did with it, on the wire.",
+ "enum": ["sent", "queued"]
+ },
"CreateAgentSessionRequest": {
"type": "object",
"description": "Request body for `POST /agent-sessions`.\n\nCarries two shapes, told apart by `workspace`. Naming one asks for an\nexternal session: the runtime is the bot operator's, so the caller has to\nsay which bot and which directory, and must own that bot. Omitting it asks\nfor a managed session, whose sandbox this deployment provisions from its\nown configuration - which is why the fields describing someone else's\nruntime must be omitted along with it rather than quietly ignored. Mixing\nthe two is refused rather than guessed at, so that no request can reach the\nmanaged path carrying a bot the caller was never entitled to name.\n\nClients serialize this, so both derives are used.",
@@ -899,6 +1172,18 @@
}
}
},
+ "EditQueuedActionRequest": {
+ "type": "object",
+ "description": "Request body for editing a queued prompt.",
+ "required": ["prompt"],
+ "properties": {
+ "prompt": {
+ "type": "string",
+ "description": "The new raw prompt text, replacing the old wholesale. Never blank: a\nprompt with nothing to say is a removal, and there is an endpoint for\nthat.",
+ "minLength": 1
+ }
+ }
+ },
"ExternalSessionResponse": {
"type": "object",
"description": "The provider-side identity of an externally-served session.",
@@ -938,6 +1223,34 @@
}
}
},
+ "QueuedActionDto": {
+ "type": "object",
+ "description": "One action waiting in a session's queue.\n\nClients deserialize this, so both derives are used.",
+ "required": ["actionId", "kind", "createdAt"],
+ "properties": {
+ "actionId": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The id the action was accepted under."
+ },
+ "actorUserId": {
+ "type": ["string", "null"],
+ "description": "The user who queued it, absent when a bot acted on nobody's behalf."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When it was accepted."
+ },
+ "kind": {
+ "type": "string",
+ "description": "What kind of action waits - `prompt` or `compact`; only\nturn-occupying actions are ever queued."
+ },
+ "prompt": {
+ "type": ["string", "null"],
+ "description": "The prompt's raw text, present for prompts only. What an edit\nreplaces."
+ }
+ }
+ },
"RenameAgentSessionRequest": {
"type": "object",
"description": "Request body for renaming an agent session.",
diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.ts
index 9f7935e6b7..d202407a01 100644
--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts
+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts
@@ -1,13 +1,14 @@
import type {
AgentAction,
- AgentActionId,
AgentSessionLogResponse,
AgentSessionResponse,
+ ControlResponse,
SandboxSize,
} from '../../../generated/agent-harness/types.gen';
import { unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
import { MacroEntity } from '../entity';
+import { QueuedAction } from './queued-action';
/** A managed or externally hosted coding-agent session. */
export class AgentSession extends MacroEntity<AgentSessionResponse> {
@@ -108,8 +109,15 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
).size;
}
- /** Send a prompt or lifecycle operation to the live agent session. */
- async control(action: AgentAction): Promise<AgentActionId> {
+ /**
+ * Send a prompt or lifecycle operation to the live agent session.
+ *
+ * The returned `actionId` matches `requestId` on the folded message the
+ * action derives once it dispatches. A `queued` status means a turn was
+ * running: the action waits in the session's queue ({@link queue}) and
+ * dispatches when that turn ends.
+ */
+ async control(action: AgentAction): Promise<ControlResponse> {
return this.mutate((client) =>
client.agentHarness.controlAgentSession({
path: { session_id: this.id },
@@ -118,6 +126,26 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
);
}
+ /** Send a prompt to the session — sugar over {@link control}. */
+ prompt(text: string): Promise<ControlResponse> {
+ return this.control({ type: 'prompt', prompt: text });
+ }
+
+ /**
+ * The actions waiting to dispatch in this session, oldest first. Each can
+ * be edited or removed until it dispatches.
+ */
+ async queue(): Promise<QueuedAction[]> {
+ const { entries } = unwrap(
+ await this.client.agentHarness.getAgentSessionQueue({
+ path: { session_id: this.id },
+ }),
+ );
+ return entries.map((entry) =>
+ QueuedAction.from(this.client, this.id, entry),
+ );
+ }
+
/** Read the complete raw protocol log for this session. */
async log(): Promise<AgentSessionLogResponse> {
return unwrap(
diff --git a/packages/sdk/src/entities/agent-sessions/queued-action.ts b/packages/sdk/src/entities/agent-sessions/queued-action.ts
new file mode 100644
index 0000000000..a622f62b8d
--- /dev/null
+++ b/packages/sdk/src/entities/agent-sessions/queued-action.ts
@@ -0,0 +1,84 @@
+import type { QueuedActionDto } from '../../../generated/agent-harness/types.gen';
+import { unwrap } from '../../utils';
+import type { MacroClient } from '../../utils/client';
+
+/**
+ * One action waiting in an agent session's server-side queue: a prompt or a
+ * compact accepted while a turn was running, dispatching when that turn
+ * ends. Until then it can be edited (prompts only) or removed; once it has
+ * dispatched, both answer 404 — there is no un-sending.
+ *
+ * List-sourced only - there is no per-action GET, only the queue snapshot -
+ * so this wraps whatever DTO the caller already has, the same shape
+ * `CrmComment` wraps a list-sourced record, rather than `MacroEntity`'s
+ * lazy-fetch-by-id.
+ */
+export class QueuedAction {
+ private constructor(
+ private readonly client: MacroClient,
+ private readonly sessionId: string,
+ private dto: QueuedActionDto,
+ ) {}
+
+ /** Wrap a queue entry already in hand (e.g. from `AgentSession.queue()`). */
+ static from(
+ client: MacroClient,
+ sessionId: string,
+ dto: QueuedActionDto,
+ ): QueuedAction {
+ return new QueuedAction(client, sessionId, dto);
+ }
+
+ /**
+ * The id the action was accepted under. Once it dispatches, this equals
+ * `requestId` on the folded message the action derives.
+ */
+ get actionId(): string {
+ return this.dto.actionId;
+ }
+
+ /** `prompt` or `compact`; only turn-occupying actions are ever queued. */
+ get kind(): string {
+ return this.dto.kind;
+ }
+
+ /** The prompt's raw text, present for prompts only. What an edit replaces. */
+ get prompt(): string | undefined {
+ return this.dto.prompt ?? undefined;
+ }
+
+ /** The user who queued it, absent when a bot acted on nobody's behalf. */
+ get actorUserId(): string | undefined {
+ return this.dto.actorUserId ?? undefined;
+ }
+
+ /** When the action was accepted, as an RFC 3339 timestamp. */
+ get createdAt(): string {
+ return this.dto.createdAt;
+ }
+
+ /**
+ * Replace this queued prompt's text before it dispatches. Returns this
+ * handle for chaining; the edit endpoint answers 204, so `prompt` is
+ * applied locally rather than reread from a response body.
+ */
+ async edit(prompt: string): Promise<this> {
+ unwrap(
+ await this.client.agentHarness.editQueuedAction({
+ path: { session_id: this.sessionId, action_id: this.actionId },
+ body: { prompt },
+ }),
+ );
+ this.dto = { ...this.dto, prompt };
+ return this;
+ }
+
+ /** Remove this action from the queue before it dispatches. */
+ async remove(): Promise<void> {
+ unwrap(
+ await this.client.agentHarness.removeQueuedAction({
+ path: { session_id: this.sessionId, action_id: this.actionId },
+ }),
+ );
+ }
+}
diff --git a/packages/sdk/tests/agent-sessions.test.ts b/packages/sdk/tests/agent-sessions.test.ts
index 5e6e56fb98..f6a0782757 100644
--- a/packages/sdk/tests/agent-sessions.test.ts
+++ b/packages/sdk/tests/agent-sessions.test.ts
@@ -104,7 +104,10 @@ describe('AgentSession', () => {
return Response.json({ session }, { status: 201 });
}
if (request.url.endsWith('/control')) {
- return Response.json('agent_session:request', { status: 200 });
+ return Response.json(
+ { actionId: '0198a4cc-e138-7670-a308-a6b766602702', status: 'sent' },
+ { status: 200 },
+ );
}
if (request.url.endsWith('/log')) {
return Response.json(
@@ -123,9 +126,10 @@ describe('AgentSession', () => {
prompt: 'Fix it',
});
await expect(created.name()).resolves.toBe('Agent Session');
- await expect(created.control({ type: 'stop' })).resolves.toBe(
- 'agent_session:request',
- );
+ await expect(created.control({ type: 'stop' })).resolves.toEqual({
+ actionId: '0198a4cc-e138-7670-a308-a6b766602702',
+ status: 'sent',
+ });
await expect(created.log()).resolves.toMatchObject({ entries: [] });
await created.delete();
@@ -136,4 +140,93 @@ describe('AgentSession', () => {
'DELETE',
]);
});
+
+ test('prompt is sugar over control and reports queueing', async () => {
+ let request: Request | undefined;
+ globalThis.fetch = (async (input) => {
+ request = input instanceof Request ? input : new Request(input);
+ return Response.json(
+ {
+ actionId: '0198a4cc-e138-7670-a308-a6b766602703',
+ status: 'queued',
+ },
+ { status: 200 },
+ );
+ }) as typeof fetch;
+ const macro = new Macro({
+ token: 'user-token',
+ hosts: { 'agent-harness': 'https://agent.example.test' },
+ });
+
+ await expect(
+ macro.agentSessions.byId(sessionId).prompt('Fix the flaky test'),
+ ).resolves.toEqual({
+ actionId: '0198a4cc-e138-7670-a308-a6b766602703',
+ status: 'queued',
+ });
+
+ expect(request?.method).toBe('POST');
+ expect(request?.url).toBe(
+ `https://agent.example.test/agent-sessions/${sessionId}/control`,
+ );
+ await expect(request?.json()).resolves.toEqual({
+ type: 'prompt',
+ prompt: 'Fix the flaky test',
+ });
+ });
+
+ test('lists the queue and edits or removes an entry through its handle', async () => {
+ const actionId = '0198a4cc-e138-7670-a308-a6b766602704';
+ const requests: Request[] = [];
+ globalThis.fetch = (async (input) => {
+ const request = input instanceof Request ? input : new Request(input);
+ requests.push(request);
+ if (request.method === 'GET') {
+ return Response.json(
+ {
+ entries: [
+ {
+ actionId,
+ kind: 'prompt',
+ prompt: 'Also update the docs',
+ actorUserId: 'macro|[email protected]',
+ createdAt: '2026-08-24T12:01:00Z',
+ },
+ ],
+ },
+ { status: 200 },
+ );
+ }
+ return new Response(null, { status: 204 });
+ }) as typeof fetch;
+ const macro = new Macro({
+ token: 'user-token',
+ hosts: { 'agent-harness': 'https://agent.example.test' },
+ });
+
+ const [queued] = await macro.agentSessions.byId(sessionId).queue();
+ expect(queued?.actionId).toBe(actionId);
+ expect(queued?.kind).toBe('prompt');
+ expect(queued?.prompt).toBe('Also update the docs');
+ expect(queued?.actorUserId).toBe('macro|[email protected]');
+ expect(queued?.createdAt).toBe('2026-08-24T12:01:00Z');
+
+ await queued?.edit('Also update the README');
+ await queued?.remove();
+
+ expect(requests.map((request) => request.method)).toEqual([
+ 'GET',
+ 'PUT',
+ 'DELETE',
+ ]);
+ expect(requests[1]?.url).toBe(
+ `https://agent.example.test/agent-sessions/${sessionId}/queue/${actionId}`,
+ );
+ await expect(requests[1]?.json()).resolves.toEqual({
+ prompt: 'Also update the README',
+ });
+ expect(requests[2]?.url).toBe(
+ `https://agent.example.test/agent-sessions/${sessionId}/queue/${actionId}`,
+ );
+ });
});
diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rs
index 496fa94503..d57ee78d4c 100644
--- a/services/agent_harness_service/src/api/swagger.rs
+++ b/services/agent_harness_service/src/api/swagger.rs
@@ -3,9 +3,11 @@
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use agent_session::domain::model::{SandboxSize, SessionBot};
use agent_session::inbound::axum_router::{
- self, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionResponse, ControlRequest,
- CreateAgentSessionRequest, CreateAgentSessionResponse, CreateSessionThread, LogDirectionDto,
- LogFrameDto, RenameAgentSessionRequest, SandboxSizeBody, SessionStatusDto,
+ self, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionQueueResponse,
+ AgentSessionResponse, ControlRequest, ControlResponse, ControlStatusDto,
+ CreateAgentSessionRequest, CreateAgentSessionResponse, CreateSessionThread,
+ EditQueuedActionRequest, LogDirectionDto, LogFrameDto, QueuedActionDto,
+ RenameAgentSessionRequest, SandboxSizeBody, SessionStatusDto,
};
use utoipa::OpenApi;
@@ -18,6 +20,9 @@ use utoipa::OpenApi;
axum_router::rename_agent_session_handler,
axum_router::get_agent_session_log_handler,
axum_router::control_agent_session_handler,
+ axum_router::get_agent_session_queue_handler,
+ axum_router::edit_queued_action_handler,
+ axum_router::remove_queued_action_handler,
axum_router::delete_agent_session_handler,
axum_router::put_agent_session_sandbox_size_handler,
axum_router::get_agent_sandbox_size_handler,
@@ -28,6 +33,11 @@ use utoipa::OpenApi;
CreateAgentSessionResponse,
CreateSessionThread,
ControlRequest,
+ ControlResponse,
+ ControlStatusDto,
+ AgentSessionQueueResponse,
+ QueuedActionDto,
+ EditQueuedActionRequest,
AgentAction,
AgentActionId,
AgentSessionResponse,
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 4bf2dea003..597a00da70 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -258,6 +258,9 @@ async fn run() -> anyhow::Result<()> {
address = ?replica_address.as_ref().map(ReplicaAddress::as_str),
"harness replica identity"
);
+ // Bound to the harness once it exists (it is built *from* this service);
+ // both attach-capable service instances report turns to the same one.
+ let turn_observer = Arc::new(agent_session::domain::ports::LateBoundTurnObserver::new());
let sessions = AgentSessionServiceImpl::new(
session_repo.clone(),
FoldedMessageService::new(session_repo.clone()),
@@ -267,6 +270,7 @@ async fn run() -> anyhow::Result<()> {
),
)
.with_replica(replica)
+ .with_turn_observer(turn_observer.clone())
.with_name_generator(HaikuAgentSessionNameGenerator::new(ai_usage::pg_recorder(
pool.clone(),
)));
@@ -346,7 +350,8 @@ async fn run() -> anyhow::Result<()> {
FoldedMessageService::new(session_repo.clone()),
NoOpRealtime,
)
- .with_replica(replica);
+ .with_replica(replica)
+ .with_turn_observer(turn_observer.clone());
let sandbox_and_inmem = RoutedContainers::new(sandbox, inmem, inmem_sessions);
// Cursor sessions run on their owner's own Cursor account, so there is no
@@ -517,6 +522,9 @@ async fn run() -> anyhow::Result<()> {
.map_err(|error| anyhow::anyhow!("failed to build the command forwarder: {error}"))?,
defaults,
));
+ // Close the loop: turn ends observed by the session actors drain the
+ // harness's prompt queue.
+ turn_observer.bind(harness.clone());
// The complete session API is served from this process because it owns the
// live sessions. Spawned rather than awaited: the Kafka loop below owns the
@@ -739,6 +747,12 @@ async fn run() -> anyhow::Result<()> {
HarnessCommand::SetSandboxSize(_) => {
"agent_trigger.set_sandbox_size"
}
+ // Never trigger-borne: queue mutations arrive over
+ // HTTP, and the turn signals are the harness's own.
+ HarnessCommand::EditQueued { .. }
+ | HarnessCommand::RemoveQueued { .. }
+ | HarnessCommand::TurnEnded
+ | HarnessCommand::SessionStopped => "agent_trigger.unexpected",
};
tracing::Span::current().record("macro.event.type", event_type);
let execution_span = tracing::info_span!(
@@ -752,6 +766,7 @@ async fn run() -> anyhow::Result<()> {
// what carries this child context through the queue.
let execution = execution_span
.in_scope(|| harness.execute(session_id, command));
+ let execution = async move { execution.await.map(drop) };
PendingHarnessWork {
session_id,
span: execution_span,