Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat: retry a failed turn without posting the message again
raullopez-sandboxdb8a671327c5
diff --git a/console/apps/switch-console-desktop/src/main/core/chats/controller.ts b/console/apps/switch-console-desktop/src/main/core/chats/controller.tsindex 5dd716dac..a2f887528 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/controller.ts@@ -287,12 +287,14 @@ export const chatsController = createRPCController({requestId: string;agentId: string;command: ChatControlCommand;+ messageId: string | null;}): Promise<string> =>onServer(params.serverId, (server) =>sendChatControl(server, params.roomId, {requestId: params.requestId,agentId: params.agentId,command: params.command,+ messageId: params.messageId,})),answerApproval: (params: {diff --git a/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts b/console/apps/switch-console-desktop/src/main/core/chats/gateway.tsindex 5e39ac97e..ff2fd3eb4 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts@@ -289,12 +289,23 @@ export async function fetchRoomActivity(export async function sendChatControl(server: SwitchServer,roomId: string,- input: { requestId: string; agentId: string; command: ChatControlCommand }+ input: {+ requestId: string;+ agentId: string;+ command: ChatControlCommand;+ /** The message a `retry` runs again; null for every other control. */+ messageId: string | null;+ }): Promise<string> {return (await json(server, `${room(roomId)}/controls`, chatControlAcceptedSchema, {method: 'POST',- body: input,+ body: {+ requestId: input.requestId,+ agentId: input.agentId,+ command: input.command,+ ...(input.messageId !== null ? { messageId: input.messageId } : {}),+ },})).commandId;}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.tsindex c6fd17d27..5b0704d11 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts@@ -16,7 +16,7 @@ import {} from './session-commands';import { manageAgentSidecar } from './sidecar-management';import { stopSharedSession } from './stop-shared-session';-import { closeTranscript, openTranscript } from './transcripts';+import { closeTranscript, openTranscript, sessionRetrySupport } from './transcripts';export const sdkHostController = createRPCController({stop: (agentId: string, sessionId: string) => stopSharedSession(agentId, sessionId),startupStatus: (sessionId: string) => sessionStartupStatus(sessionId),@@ -46,4 +46,6 @@ export const sdkHostController = createRPCController({sessionCommandStatus(agentId, sessionId, commandId),reasoningList: (agentId: string, sessionId: string, turnIds: string[] | null) =>listReasoning(agentId, sessionId, turnIds),+ sessionRetrySupport: (agentId: string, sessionId: string) =>+ sessionRetrySupport(agentId, sessionId),});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/transcripts.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/transcripts.tsindex 95c606802..83c43427f 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/transcripts.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/transcripts.ts@@ -90,6 +90,27 @@ export async function currentSnapshot(agentId: string, sessionId: string): Promi}}+/**+ * Whether the session's running host can run a message's turn again+ * (`message.retry`): `no` from a host built before it, `unknown` when no host+ * of this Console answers for the session.+ */+export async function sessionRetrySupport(+ agentId: string,+ sessionId: string+): Promise<'yes' | 'no' | 'unknown'> {+ try {+ return (await currentSnapshot(agentId, sessionId)).session.capabilities.retry ? 'yes' : 'no';+ } catch (error) {+ log.info('Could not ask the session whether it can retry', {+ agentId,+ sessionId,+ error: String(error),+ });+ return 'unknown';+ }+}+type Place = 'local' | 'remote';/** The session as last recorded: from its host if it runs, else its journal. */diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-activity-block.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-activity-block.tsxindex b2a6452b7..c2b2b02b3 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-activity-block.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-activity-block.tsx@@ -1,6 +1,8 @@+import { useQuery } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';-import { type ComponentProps, type ReactNode, useState } from 'react';+import { type ComponentProps, type ReactNode, useEffect, useState } from 'react';import { AgentAvatar } from '@renderer/lib/components/agent-avatar';+import { Button } from '@renderer/lib/ui/button';import { cn } from '@renderer/utils/utils';import type { ChatActivityItem, ChatApproval } from '@shared/core/chats/activity';import { reasoningLabel } from '@shared/core/sessions/reasoning';@@ -214,6 +216,9 @@ export const ChatActivityBlock = observer(function ChatActivityBlock({title={endReason ?? undefined}tone="failed"/>+ {turn.status === 'error' && turn.messageId && (+ <RetryTurn activity={activity} turn={turn} />+ )}</div>)}{requests.length > 0 && <ChatRequests activity={activity} requests={requests} />}@@ -241,3 +246,79 @@ export const ChatRequests = observer(function ChatRequests({</WorkLogDetails>);});++/** How long a posted retry waits for its new turn before it is said to have gone unanswered. */+export const RETRY_UNANSWERED_MS = 20_000;++/** The text shown in place of Retry when the agent's session cannot run a turn again. */+export const RETRY_UNSUPPORTED_TEXT =+ "This agent's Switch Console is too old to retry; ask its owner to update.";++/**+ * Run again the turn a message started, which failed: the same message goes to+ * the agent again, and nothing is posted in its name. Offered only when the+ * session here says it can; for one this Console does not host it is offered,+ * and a retry no new turn follows says so.+ */+const RetryTurn = observer(function RetryTurn({+ activity,+ turn,+}: {+ activity: AgentActivity;+ turn: TurnActivity;+}) {+ const target = activity.target;+ const support = useQuery({+ queryKey: [+ 'chat-retry-support',+ target?.kind === 'session' ? target.hostAgentKey : null,+ target?.kind === 'session' ? target.sessionId : null,+ ],+ queryFn: () => activity.retrySupport(),+ // A lookup that failed leaves no session to ask: offered, and the fallback says if it went unheard.+ enabled: target !== null || activity.resolveError !== null,+ });+ const request = activity.retries.get(turn.turnId) ?? null;+ const [now, setNow] = useState(() => Date.now());+ const waitingSince = request?.state === 'requested' ? request.requestedAt : null;+ useEffect(() => {+ if (waitingSince === null) return;+ const left = waitingSince + RETRY_UNANSWERED_MS - Date.now();+ const timer = setTimeout(() => setNow(Date.now()), Math.max(left, 0));+ return () => clearTimeout(timer);+ }, [waitingSince]);++ if (support.data === 'no')+ return <p className="mt-1 text-xs text-foreground-muted">{RETRY_UNSUPPORTED_TEXT}</p>;+ const unanswered = waitingSince !== null && now - waitingSince >= RETRY_UNANSWERED_MS;+ return (+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <Button+ size="xs"+ variant="outline"+ disabled={+ !support.isSuccess ||+ request?.state === 'sending' ||+ (waitingSince !== null && !unanswered)+ }+ onClick={() => void activity.retry(turn)}+ >+ {request?.state === 'sending'+ ? 'Retrying…'+ : waitingSince !== null && !unanswered+ ? 'Retry asked'+ : 'Retry'}+ </Button>+ {(request?.state === 'failed' || request?.state === 'unknown') && request.error && (+ <span role="alert" className="text-xs text-destructive">+ {request.error}+ </span>+ )}+ {unanswered && (+ <span role="status" className="text-xs text-foreground-muted">+ The agent did not pick up the retry. Its machine may need a newer Switch Console.+ </span>+ )}+ </div>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/activities.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/activities.tsindex 80daaf8e6..d1f9cb661 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/activities.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/activities.ts@@ -29,6 +29,8 @@ export const agentActivities = new AgentActivities(roomActivity: (serverId, roomId) => rpc.chats.roomActivity(serverId, roomId),roomMessages: (serverId, roomId) => chatsStore.timelines.peek(serverId, roomId)?.messages ?? [],control: (input) => rpc.chats.control(input),+ retrySupport: (hostAgentKey, sessionId) =>+ rpc.sdkHost.sessionRetrySupport(hostAgentKey, sessionId),answerApproval: (input) => rpc.chats.answerApproval(input),},sessionStoragediff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-activity-store.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-activity-store.tsindex 20cb66b3e..e057f6d03 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-activity-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-activity-store.ts@@ -51,7 +51,11 @@ export type ActivityApi = {requestId: string;agentId: string;command: ChatControlCommand;+ /** The message a `retry` runs again; null for every other command. */+ messageId: string | null;}) => Promise<string>;+ /** Whether the session's host can retry a turn; `unknown` when no host of this Console answers for it. */+ retrySupport: (hostAgentKey: string, sessionId: string) => Promise<'yes' | 'no' | 'unknown'>;answerApproval: (input: {serverId: string;agentId: string;@@ -67,15 +71,33 @@ export type ActivityApi = {* it is only ever sent again under the same request id, which Switch answers* with the command it already posted.*/+/** The commands the chat's own controls post: Stop, Reset and Compact. */+export type SessionControl = Exclude<ChatControlCommand, 'retry'>;+export type ControlRequest = {requestId: string;- command: ChatControlCommand;+ command: SessionControl;state: 'sending' | 'requested' | 'failed' | 'unknown';/** The room message the command is; the agent's answer threads under it. */commandId: string | null;error: string | null;};+/**+ * A Retry of a failed turn sent from here: `requested` once Switch posted it,+ * not once the turn runs again. `unknown`: no answer came back, so it may have+ * been posted; it is only ever sent again under the same request id, which+ * Switch answers with the command it already posted.+ */+export type RetryRequest = {+ requestId: string;+ messageId: string;+ state: 'sending' | 'requested' | 'failed' | 'unknown';+ error: string | null;+ /** When Switch took it, so a retry no new turn followed can be told apart. */+ requestedAt: number | null;+};+const unsettled = (control: ControlRequest) =>control.state === 'sending' || control.state === 'unknown';@@ -89,6 +111,8 @@ export class AgentActivity {feedError: string | null = null;readonly items = observable.map<string, ChatActivityItem>({}, { deep: false });readonly approvals = observable.map<string, ChatApproval>({}, { deep: false });+ /** Retries sent from here, by the failed turn each runs again. */+ readonly retries = observable.map<string, RetryRequest>({}, { deep: false });controls: ControlRequest[] = [];reasoning = new Map<string, ReasoningTurn>();/** Tool item id → what the call was given and gave back; local and SSH hosts only. */@@ -217,7 +241,7 @@ export class AgentActivity {* whose outcome is unknown is sent again under its own request id instead,* so a Reset that landed before its answer was lost never runs twice.*/- async control(command: ChatControlCommand): Promise<void> {+ async control(command: SessionControl): Promise<void> {const unknown = this.controls.find((control) => control.state === 'unknown' && control.command === command);@@ -232,6 +256,55 @@ export class AgentActivity {return this.post(this.controls.at(-1)!);}+ /**+ * Ask the agent to run again the turn a message started, which failed. Pressed+ * again while it is being posted or once posted, nothing more is sent; one+ * whose answer was lost goes again under its own request id.+ */+ async retry(turn: TurnActivity): Promise<void> {+ const messageId = turn.messageId;+ if (!messageId) return;+ const held = this.retries.get(turn.turnId);+ if (held?.state === 'sending' || held?.state === 'requested') return;+ const requestId = held?.state === 'unknown' ? held.requestId : crypto.randomUUID();+ const update = (change: Partial<RetryRequest>) =>+ runInAction(() => {+ const current = this.retries.get(turn.turnId);+ if (current?.requestId === requestId)+ this.retries.set(turn.turnId, { ...current, ...change });+ });+ runInAction(() =>+ this.retries.set(turn.turnId, {+ requestId,+ messageId,+ state: 'sending',+ error: null,+ requestedAt: null,+ })+ );+ try {+ await this.api.control({+ serverId: this.serverId,+ roomId: this.roomId,+ requestId,+ agentId: this.agentId,+ command: 'retry',+ messageId,+ });+ update({ state: 'requested', requestedAt: Date.now() });+ } catch (error) {+ const failure = chatFailure(error);+ update({ state: failure.uncertain ? 'unknown' : 'failed', error: failure.message });+ }+ }++ /** Whether this agent's session can retry a turn, asked of the host running it here. */+ async retrySupport(): Promise<'yes' | 'no' | 'unknown'> {+ const target = this.target;+ if (target?.kind !== 'session') return 'unknown';+ return this.api.retrySupport(target.hostAgentKey, target.sessionId);+ }+/** Send a command whose outcome is unknown again, under the same request id. */async retryControl(requestId: string): Promise<void> {const control = this.controls.find((each) => each.requestId === requestId);@@ -256,6 +329,7 @@ export class AgentActivity {requestId: held.requestId,agentId: this.agentId,command,+ messageId: null,});runInAction(() => {held.state = 'requested';diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/retry-turn.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/retry-turn.test.tsxnew file mode 100644index 000000000..982a032bd--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/retry-turn.test.tsx@@ -0,0 +1,148 @@+/**+ * Retry on a failed turn: offered when the agent's session says it can, in its+ * place a plain reason when it cannot, held while it is being posted, the+ * server's refusal said, and a retry no new turn followed called out.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';+import {+ ChatActivityBlock,+ RETRY_UNANSWERED_MS,+ RETRY_UNSUPPORTED_TEXT,+} from '@renderer/features/chats/components/chat-activity-block';+import {+ type ActivityApi,+ AgentActivities,+} from '@renderer/features/chats/stores/chat-activity-store';+import type { ChatActivityItem } from '@shared/core/chats/activity';+import { RpcError } from '@shared/lib/ipc/rpc-error';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+ vi.useRealTimers();+});++const failedTurn: ChatActivityItem = {+ agentId: 'agent-a',+ sessionId: 's1',+ turnId: 't1',+ itemId: 'turn',+ kind: 'turn',+ revision: 1,+ status: 'error',+ title: '',+ text: '',+ commandId: null,+ roomId: 'room-1',+ threadId: null,+ messageId: 'm1',+ occurredAt: '2026-01-01T00:00:00Z',+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+};++async function render(+ support: 'yes' | 'no' | 'unknown',+ control: ActivityApi['control']+): Promise<HTMLDivElement> {+ const api: ActivityApi = {+ resolve: async () => ({+ kind: 'session',+ target: { kind: 'local' } as never,+ hostAgentKey: 'agent-local',+ sessionId: 's1',+ }),+ reasoning: async () => null,+ watchPlacements: () => () => {},+ roomActivity: async () => ({ items: [failedTurn], approvals: [] }),+ roomMessages: () => [],+ control,+ retrySupport: async () => support,+ answerApproval: async () => {+ throw new Error('unused');+ },+ };+ const activities = new AgentActivities(api, {+ getItem: () => null,+ setItem: () => {},+ });+ const activity = activities.acquire('server', 'tenant', 'room-1', 'agent-a');+ await vi.waitFor(() => expect(activity.turns().size).toBe(1));+ await vi.waitFor(() => expect(activity.target).not.toBeNull());+ const turn = activity.turns().get('m1')!;+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () =>+ root!.render(+ <QueryClientProvider client={new QueryClient()}>+ <ChatActivityBlock+ activity={activity}+ turn={turn}+ agent={{ name: 'helper', iconUrl: null }}+ head+ endReason="model not supported"+ serverId="server"+ />+ </QueryClientProvider>+ )+ );+ for (let i = 0; i < 5; i++) await act(async () => await Promise.resolve());+ return container;+}++const retryButton = (el: HTMLElement) =>+ [...el.querySelectorAll('button')].find((b) => /^Retr/.test(b.textContent ?? ''));++it('says why in place of Retry when the session cannot retry', async () => {+ const el = await render('no', vi.fn());+ expect(retryButton(el)).toBeUndefined();+ expect(el.textContent).toContain(RETRY_UNSUPPORTED_TEXT);+ expect(el.textContent).toContain('model not supported');+});++it('asks once, holds the button while it is posted, and says when no new turn followed', async () => {+ let answer: (commandId: string) => void = () => {};+ const control = vi.fn(() => new Promise<string>((resolve) => (answer = resolve)));+ const el = await render('yes', control);+ const button = retryButton(el)!;+ expect(button.disabled).toBe(false);++ await act(async () => button.click());+ expect(retryButton(el)!.textContent).toBe('Retrying…');+ expect(retryButton(el)!.disabled).toBe(true);+ await act(async () => retryButton(el)!.click());+ expect(control).toHaveBeenCalledTimes(1);+ expect(control).toHaveBeenCalledWith(+ expect.objectContaining({ command: 'retry', messageId: 'm1' })+ );++ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ await act(async () => answer('cmd-1'));+ expect(retryButton(el)!.textContent).toBe('Retry asked');+ await act(async () => vi.advanceTimersByTime(RETRY_UNANSWERED_MS + 10));+ expect(el.textContent).toContain('did not pick up the retry');+ expect(retryButton(el)!.disabled).toBe(false);+});++it('says the server’s refusal and offers Retry again', async () => {+ const el = await render('unknown', async () => {+ throw new RpcError({+ code: 'ChatApiError',+ message: 'helper took no turn for that message.',+ data: { status: 409, code: 'NOTHING_TO_RETRY' },+ } as never);+ });+ await act(async () => retryButton(el)!.click());+ for (let i = 0; i < 3; i++) await act(async () => await Promise.resolve());+ expect(el.querySelector('[role="alert"]')?.textContent).toContain('took no turn');+ expect(retryButton(el)!.disabled).toBe(false);+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.tsindex 92994d76c..a2135c71e 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.ts@@ -407,6 +407,7 @@ function fakeApi(snapshots: RoomActivity[], messages: ChatMessage[] = []) {return snapshots.shift() ?? { items: [], approvals: [] };},roomMessages: () => messages,+ retrySupport: async () => 'yes' as const,control: async (input) => {controls.push(input);return 'cmd-1';@@ -478,6 +479,64 @@ describe('AgentActivities', () => {activities.release(activity);});+ it('asks for a retry of a failed turn once, however often it is pressed', async () => {+ const { api, controls } = fakeApi([+ { items: [row('t1', 'turn', { status: 'error' })], approvals: [] },+ ]);+ let answer: (commandId: string) => void = () => {};+ api.control = (input) => {+ controls.push(input);+ return new Promise((resolve) => (answer = resolve));+ };+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', 'tenant', 'room-1', 'agent-a');+ await vi.waitFor(() => expect(activity.turns().size).toBe(1));+ const turn = activity.turns().get('m-t1')!;++ const first = activity.retry(turn);+ void activity.retry(turn);+ expect(activity.retries.get('t1')?.state).toBe('sending');+ answer('cmd-retry');+ await first;+ void activity.retry(turn);+ expect(controls).toEqual([+ expect.objectContaining({ command: 'retry', messageId: 'm-t1', agentId: 'agent-a' }),+ ]);+ expect(activity.retries.get('t1')).toMatchObject({ state: 'requested', error: null });+ activities.release(activity);+ });++ it('sends a retry whose answer was lost again under the same request id, and says why one failed', async () => {+ const { api, controls } = fakeApi([+ { items: [row('t1', 'turn', { status: 'error' })], approvals: [] },+ ]);+ const outcomes = [+ () => Promise.reject(rpcError('GatewayError', 'socket hang up', { kind: 'network' })),+ () =>+ Promise.reject(+ rpcError('ChatApiError', 'helper took no turn for that message.', {+ status: 409,+ code: 'NOTHING_TO_RETRY',+ })+ ),+ ];+ api.control = (input) => {+ controls.push(input);+ return outcomes.shift()!();+ };+ const activities = new AgentActivities(api, memoryStorage());+ const activity = activities.acquire('server', 'tenant', 'room-1', 'agent-a');+ await vi.waitFor(() => expect(activity.turns().size).toBe(1));+ const turn = activity.turns().get('m-t1')!;+ await activity.retry(turn);+ await activity.retry(turn);+ const [lost, again] = controls as { requestId: string }[];+ expect(again!.requestId).toBe(lost!.requestId);+ expect(activity.retries.get('t1')?.state).toBe('failed');+ expect(activity.retries.get('t1')?.error).toBeTruthy();+ activities.release(activity);+ });+it('merges live rows with the snapshot by revision, dropping stale ones', async () => {const snapshotTool = row('t1', 'tool', { revision: 5, title: 'from snapshot' });const { api } = fakeApi([{ items: [row('t1', 'turn'), snapshotTool], approvals: [] }]);@@ -562,6 +621,7 @@ describe('AgentActivities', () => {requestId: activity.controls[0].requestId,agentId: 'agent-a',command: 'interrupt',+ messageId: null,},]);expect(activity.controls[0]).toMatchObject({ state: 'requested', commandId: 'cmd-1' });diff --git a/console/apps/switch-console-desktop/src/shared/core/chats/activity.ts b/console/apps/switch-console-desktop/src/shared/core/chats/activity.tsindex 7153583d2..2bf50ee34 100644--- a/console/apps/switch-console-desktop/src/shared/core/chats/activity.ts+++ b/console/apps/switch-console-desktop/src/shared/core/chats/activity.ts@@ -124,6 +124,7 @@ export const SERVER_TOO_OLD_FOR_ACTIVITY ='This Switch server is too old for live chat activity — update the server.';/** What the chat's Stop, Reset and Compact post to the room for an agent. */-export type ChatControlCommand = 'interrupt' | 'reset' | 'compact';+/** Stop, Reset and Compact, and `retry`: run again the turn a message started, which failed. */+export type ChatControlCommand = 'interrupt' | 'reset' | 'compact' | 'retry';export const chatControlAcceptedSchema = z.object({ commandId: z.string() });diff --git a/console/packages/agent-providers/src/host/room-control-followup.ts b/console/packages/agent-providers/src/host/room-control-followup.tsindex 78909c452..5a6b87d0f 100644--- a/console/packages/agent-providers/src/host/room-control-followup.ts+++ b/console/packages/agent-providers/src/host/room-control-followup.ts@@ -34,3 +34,12 @@ export function roomControlRefusal(action: 'reset' | 'compact', reason: string |return `I can't ${action} my session while I'm working on a turn. Ask again once I've finished, or stop the turn first.`;return `I couldn't ${action} my session: ${reason?.replace(/^Error: /, '') || 'the session refused it.'}`;}++/** What the room is told when the session could not run a message's turn again. */+export function retryRefusal(reason: string | null): string {+ if (reason?.includes('SESSION_BUSY'))+ return "I can only try again once that turn has ended without an answer, and it hasn't.";+ if (reason?.includes('NOT_FOUND'))+ return "I couldn't try that again: my current session never worked on that message.";+ return `I couldn't try that again: ${reason?.replace(/^Error: /, '') || 'the session refused it.'}`;+}diff --git a/console/packages/agent-providers/src/host/session-host.test.ts b/console/packages/agent-providers/src/host/session-host.test.tsindex 0ab43b89a..08dd72add 100644--- a/console/packages/agent-providers/src/host/session-host.test.ts+++ b/console/packages/agent-providers/src/host/session-host.test.ts@@ -3,7 +3,7 @@ import { appendFile, mkdtemp, readFile, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import type { Command, Session } from '@switch-console/shared/session-v1';-import { afterEach, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { ProviderConversationUnavailableError, type ProviderAdapter } from '../adapter';import type { ProviderRuntimeEvent } from '../events';import { abandonWaits, announcing, changed, until } from '../testing/until';@@ -1654,3 +1654,67 @@ it("tells its owner when the provider asks to run a connector's tool, and only t);expect(order).toEqual(['bash', 'notice', 'search', 'add_comment']);});++describe('retrying a room message', () => {+ const roomMessage = (commandId: string): Command => ({+ ...message(commandId),+ origin: {+ actorId: 'user',+ surface: 'switch-web',+ roomId: 'room',+ threadId: null,+ messageId: 'm1',+ },+ });+ const retry = (commandId: string): Command => ({+ ...message(commandId),+ origin: {+ actorId: 'user',+ surface: 'switch-web',+ roomId: 'room',+ threadId: null,+ messageId: null,+ },+ body: { type: 'message.retry', messageId: 'm1' },+ });++ it('says it can retry', async () => {+ const { host } = await start('codex');+ expect(host.snapshot().session.capabilities.retry).toBe(true);+ });++ it('runs a failed turn again under the same message, once however often it is asked', async () => {+ const { host, emit, adapter } = await start('codex');+ await host.command(roomMessage('first'));+ await until(() => expect(host.snapshot().turns[0]?.status).toBe('running'));+ emit({+ type: 'turn.completed',+ turnId: 'first',+ outcome: 'error',+ message: 'model',+ usage: [],+ });+ await until(() => expect(host.snapshot().turns[0]?.status).toBe('error'));++ expect((await host.command(retry('again'))).status).toBe('applied');+ // A double press or a reconnect replaying it.+ expect((await host.command(retry('again'))).status).toBe('applied');+ await until(() => expect(adapter.sendTurn).toHaveBeenCalledTimes(2));+ const turns = host.snapshot().turns;+ expect(turns.map((turn) => turn.turnId)).toEqual(['first', 'again']);+ expect(adapter.sendTurn).toHaveBeenLastCalledWith(+ expect.objectContaining({ turnId: 'again', text: 'Hello' })+ );+ // The retry repeats nothing in the transcript the person wrote: its turn carries the same text.+ const userItems = host.snapshot().items.filter((item) => item.kind === 'user-message');+ expect(userItems.map((item) => item.origin?.messageId)).toEqual(['m1', 'm1']);+ });++ it('refuses to run again a turn still going, or a message it never worked on', async () => {+ const { host } = await start('codex');+ await expect(host.command(retry('nothing'))).rejects.toThrow('NOT_FOUND');+ await host.command(roomMessage('first'));+ await until(() => expect(host.snapshot().turns[0]?.status).toBe('running'));+ await expect(host.command(retry('busy'))).rejects.toThrow('SESSION_BUSY');+ });+});diff --git a/console/packages/agent-providers/src/host/session-host.ts b/console/packages/agent-providers/src/host/session-host.tsindex f7f9c3287..6331a8c3e 100644--- a/console/packages/agent-providers/src/host/session-host.ts+++ b/console/packages/agent-providers/src/host/session-host.ts@@ -138,6 +138,8 @@ export class HostedSession {private readonly events: Journal<ServerEvent>,private readonly inbox: Journal<RecordEntry>) {+ // Every host from this one on runs `message.retry`; one built before says nothing, meaning no.+ config.session.capabilities.retry = true;const snapshot: Snapshot = {contractVersion: 1,throughSequence: 0,@@ -693,10 +695,39 @@ export class HostedSession {return result;}+ /**+ * A retry as the room message it repeats: the message's turn run again, under+ * the retry's own id and tied to the same message, so nothing is posted twice+ * and the new turn shows where the failed one did. Only a turn that ended+ * without an answer is run again.+ */+ private retried(command: Command): Command {+ if (command.body.type !== 'message.retry') return command;+ const { messageId } = command.body;+ const original = [...this.commands.values()]+ .filter(+ (each) =>+ each.body.type === 'message.send' &&+ each.origin.messageId === messageId &&+ each.commandId !== command.commandId+ )+ .at(-1);+ if (!original || original.body.type !== 'message.send')+ throw new Error('NOT_FOUND: this session has no turn for that message to run again.');+ const turn = this.snapshot().turns.find((each) => each.turnId === original.commandId);+ if (turn?.status !== 'error' && turn?.status !== 'interrupted')+ throw new Error('SESSION_BUSY: only a turn that ended without an answer can run again.');+ return { ...command, origin: original.origin, body: original.body };+ }+private async accept(command: Command): Promise<Snapshot['commandStatuses'][number]> {if (this.shuttingDown) throw new Error('HOST_STOPPING');const { session } = this.snapshot();if (command.sessionId !== session.sessionId) throw new Error('NOT_FOUND: session mismatch.');+ // Asked again (a double press, a reconnect replaying it): the answer it already has.+ if (command.body.type === 'message.retry' && this.commands.has(command.commandId))+ return this.status(command.commandId);+ command = this.retried(command);const previous = this.commands.get(command.commandId);if (previous) {if (!isDeepStrictEqual(previous, command)) throw new Error('IDEMPOTENCY_CONFLICT');diff --git a/console/packages/agent-providers/src/host/shared-host.test.ts b/console/packages/agent-providers/src/host/shared-host.test.tsindex c27148228..e2c3dc92b 100644--- a/console/packages/agent-providers/src/host/shared-host.test.ts+++ b/console/packages/agent-providers/src/host/shared-host.test.ts@@ -1435,3 +1435,55 @@ it('reports the turn a fault ended, and the fault, before it stops', async () =>// The host stopped on its own, faulted, once the reports were out.expect(String(await host.stop())).toContain('HOST_FAULTED');});++it('runs a room message again on a retry asked for there, and says so when it cannot', async () => {+ const host = await start({ rooms: true });+ const asks = () =>+ host.parent.sent.filter(+ (message): message is typeof message & { id: number; ask: Record<string, unknown> } =>+ message.kind === 'ask' && message.ask?.type !== 'room-instructions'+ );+ const retry = (commandId: string): Command => ({+ ...relayed('current', commandId, { type: 'message.retry', messageId: 'message-1' }),+ origin: {+ actorId: '@person:test',+ surface: 'switch-web',+ roomId: 'room',+ threadId: 'thread',+ messageId: 'retry-command',+ },+ });+ try {+ await host.parent.ask({ type: 'room', handoff: roomMessage(1, 'work on it') });+ await until(() => expect(host.turns).toHaveLength(1));+ // Still running: refused, and the room is told once, however often it is relayed.+ expect(+ await host.parent.ask({ type: 'command', command: retry('early'), requesterName: null })+ ).toMatchObject({ ok: true, value: { status: 'rejected' } });+ await until(() => expect(asks()).toHaveLength(1));+ expect(asks()[0]!.ask).toMatchObject({+ type: 'room-reply',+ roomId: 'room',+ threadId: 'thread',+ });+ await host.parent.ask({ type: 'command', command: retry('early'), requesterName: null });++ host.emit({+ type: 'turn.completed',+ turnId: host.turns[0]!.turnId,+ outcome: 'error',+ message: 'model not supported',+ usage: [],+ });+ await until(() => expect(asks()).toHaveLength(2)); // the host's "the turn failed" post+ expect(+ await host.parent.ask({ type: 'command', command: retry('again'), requesterName: null })+ ).toMatchObject({ ok: true, value: { status: 'applied' } });+ await until(() => expect(host.turns).toHaveLength(2));+ expect(host.turns[1]!.text).toBe(host.turns[0]!.text);+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(asks()).toHaveLength(2);+ } finally {+ await host.stop();+ }+}, 20000);diff --git a/console/packages/agent-providers/src/host/shared-host.ts b/console/packages/agent-providers/src/host/shared-host.tsindex 343b680ea..c931e8cbc 100644--- a/console/packages/agent-providers/src/host/shared-host.ts+++ b/console/packages/agent-providers/src/host/shared-host.ts@@ -13,6 +13,7 @@ import { agentHasOwnUser } from './host-permissions';import { Redactions } from './redaction';import {followupCommandId,+ retryRefusal,roomControlFollowup,roomControlRefusal,} from './room-control-followup';@@ -755,6 +756,27 @@ export async function runSharedHost(`Could not tell room ${owed.roomId} that its ${owed.action} was refused: ${String(error)}`));+ // A retry asked for from a room that cannot run is answered there, where it was asked.+ if (+ command.body.type === 'message.retry' &&+ status?.status === 'rejected' &&+ !repeated &&+ parentChannel &&+ options.roomConnection &&+ command.origin.roomId+ )+ void parentChannel+ .ask({+ type: 'room-reply',+ roomId: command.origin.roomId,+ threadId: command.origin.threadId,+ body: retryRefusal(status.message),+ })+ .catch((error: unknown) =>+ console.warn(+ `Could not tell room ${command.origin.roomId} that its retry was refused: ${String(error)}`+ )+ );// A fresh conversation starts with the instructions this host was given,// and has been told no room's.if (command.body.type === 'session.reset' && status?.status === 'applied') {diff --git a/console/packages/shared/src/session-v1/contract.ts b/console/packages/shared/src/session-v1/contract.tsindex a73b1698f..58ea1f6f4 100644--- a/console/packages/shared/src/session-v1/contract.ts+++ b/console/packages/shared/src/session-v1/contract.ts@@ -24,6 +24,8 @@ export type Capability = {compact: boolean;modelChange: boolean;attachmentMimeTypes: string[];+ /** The host runs `message.retry`; absent from a host built before it, which means no. */+ retry?: boolean;};export type Attachment = {attachmentId: Id;@@ -145,6 +147,8 @@ export type CommandBody =| { type: 'session.stop' }| { type: 'session.reset' }| { type: 'session.compact' }+ /** Run again the turn a room message started, which ended without an answer; nothing is posted again. */+ | { type: 'message.retry'; messageId: Id }| { type: 'session.model.set'; modelId: string; options: Record<string, string> };/** The server sets origin from a verified identity. Do not trust origin from a client. */export type Command = {diff --git a/console/packages/shared/src/session-v1/validation.ts b/console/packages/shared/src/session-v1/validation.tsindex 31d09b81d..2131391f3 100644--- a/console/packages/shared/src/session-v1/validation.ts+++ b/console/packages/shared/src/session-v1/validation.ts@@ -25,6 +25,7 @@ const capabilities = z.object({compact: z.boolean(),modelChange: z.boolean(),attachmentMimeTypes: z.array(z.string()),+ retry: z.boolean().optional(),});export const attachmentSchema = z.strictObject({attachmentId: id,@@ -243,6 +244,7 @@ export const commandSchema: z.ZodType<Command> = z.strictObject({z.strictObject({ type: z.literal('session.stop') }),z.strictObject({ type: z.literal('session.reset') }),z.strictObject({ type: z.literal('session.compact') }),+ z.strictObject({ type: z.literal('message.retry'), messageId: id }),z.strictObject({type: z.literal('session.model.set'),modelId: id,diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.pyindex 12023e1ef..c8bb0f598 100644--- a/core/switch_core/bridges/agent/commands.py+++ b/core/switch_core/bridges/agent/commands.py@@ -259,6 +259,12 @@ _CONTROL_BODIES: dict[str, dict[str, str]] = {}+def retry_target(args: str) -> str | None:+ """The message a `!retry @agent <message id>` names: the token after the target."""+ tokens = args.split()+ return tokens[1] if len(tokens) > 1 and tokens[0].startswith("@") else None++def room_control_frame(*,agent_id: str,@@ -270,15 +276,25 @@ def room_control_frame(thread_id: str | None,surface: str,requester_name: str,+ target_message_id: str | None,) -> dict[str, object]:"""The `session_command` frame a room control is relayed as.Beside the contract command it names who asked, as the room knows them,so the session can answer that person once the control has applied.`session_id` is None for a controller-backed agent, whose controller- picks the session from the room.+ picks the session from the room. `target_message_id` is the message a+ `retry` runs again, and None for every other control."""- body = _CONTROL_BODIES.get(action)+ if action == "retry":+ if target_message_id is None:+ raise ValueError("a retry names the message to run again")+ body: dict[str, str] | None = {+ "type": "message.retry",+ "messageId": target_message_id,+ }+ else:+ body = _CONTROL_BODIES.get(action)if body is None:raise ValueError(f"{action} is not a room control")frame = _control_frame(@@ -480,6 +496,9 @@ async def _decide_control_command(return say(f"Could not send {command}: the room command has no stable message ID.")+ target = retry_target(event.args) if command == "retry" else None+ if command == "retry" and target is None:+ return say("Could not retry: the command names no message to run again.")frame = room_control_frame(agent_id=agent.id,session_id=placed,@@ -490,6 +509,7 @@ async def _decide_control_command(thread_id=event.thread_id,surface=await _room_surface(client, meta.room_id),requester_name=event.user_name,+ target_message_id=target,)async def relay() -> None:@@ -636,6 +656,31 @@ _INTERRUPT = ControlTexts()+_RETRY = ControlTexts(+ ack="Trying that message again.",+ unsupported="I can't try a message again — this isn't supported for me.",+ no_live_session=(+ "I have no active session in this room, so there's nothing to try again."+ ),+ no_session=(+ "I can't try a message again from here — my session wasn't started "+ "from Switch Console."+ ),+)+++async def _cmd_retry(+ client: AgentRecipient, room: RoomRef, event: CommandEvent, _is_direct: bool+) -> None:+ await _dispatch_control_command(client, room, event, "retry", _RETRY)+++async def _decide_retry(+ client: AgentRecipient, room: RoomRef, event: CommandEvent+) -> ControlDecision:+ return await _decide_control_command(client, room, event, "retry", _RETRY)++async def _cmd_reset(client: AgentRecipient, room: RoomRef, event: CommandEvent, _is_direct: bool) -> None:@@ -1881,6 +1926,19 @@ COMMANDS: list[Command] = [addressed=_addressed_by_required_first_mention,admin_check=_check_control_target,),+ Command(+ "retry",+ "Run again the turn a message started, which ended without an answer. "+ "Sent by Switch Console's Retry: `!retry @agent-name <message id>`.",+ _cmd_retry,+ decide=_decide_retry,+ args_spec=(+ CommandArg("target", "Agent name, alias, or role to retry", required=True),+ CommandArg("message", "The id of the message to run again", required=True),+ ),+ addressed=_addressed_by_required_first_mention,+ hidden=True,+ ),Command("interrupt-all-agents","Interrupt EVERY agent's current turn in this room. "diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.pyindex e996e2831..68cc3fd0b 100644--- a/core/switch_core/chats/service.py+++ b/core/switch_core/chats/service.py@@ -140,7 +140,7 @@ RemovalReason = Literal["access", "unlisted"]# Long enough for a welcome with tips; a greeting is not a document.GREETING_MAX_CHARS = 4000-RoomControl = Literal["interrupt", "reset", "compact"]+RoomControl = Literal["interrupt", "reset", "compact", "retry"]def _hash(payload: dict[str, object]) -> str:@@ -1685,16 +1685,32 @@ class ChatService:request_id: str,agent_id: str,command: RoomControl,+ message_id: str | None,) -> str:"""Post `!<command> @agent` as the user; the command's event id.+ `retry` names the room message whose turn to run again (`message_id`):+ one the agent took a turn for, sent by the caller or in a room the+ caller manages. It is posted as `!retry @agent <message id>`.+Written as the `com.switch.command` event a platform bridge writes fora typed `!interrupt`, so the agents' own command handling, addressinggate and in-room acknowledgement apply unchanged. The addressing checkhere only turns a refusal into an answer instead of a room message."""+ if (command == "retry") != (message_id is not None):+ raise ChatError(+ 422,+ "INVALID_CONTROL",+ "A retry names the message to run again, and only a retry does.",+ )payload_hash = _hash(- {"roomId": room_id, "agentId": agent_id, "command": command}+ {+ "roomId": room_id,+ "agentId": agent_id,+ "command": command,+ **({"messageId": message_id} if message_id is not None else {}),+ })async with tenant_session(self.session_factory, tenant_id) as session:room, client = await self.require_member(session, tenant_id, user, room_id)@@ -1714,6 +1730,11 @@ class ChatService:)if not decision.allowed:raise ChatError(403, "AGENT_NOT_ALLOWED", decision.refusal)+ if command == "retry":+ assert message_id is not None+ await self._require_retryable(+ session, tenant_id, user, room, client, agent, message_id+ )# `!interrupt` stops the agent's running turn wherever it runs; this check can race a turn change.if command == "interrupt":turn = await self._activity_store.newest_running_turn(session, agent.id)@@ -1754,7 +1775,8 @@ class ChatService:event_type=COMMAND_EVENT_TYPE,content={"command": command,- "args": f"@{agent.name}",+ "args": f"@{agent.name}"+ + (f" {message_id}" if message_id is not None else ""),"user_id": client.transport_user_id,"user_name": user.name,},@@ -1775,6 +1797,48 @@ class ChatService:routed.committed()return command_id+ async def _require_retryable(+ self,+ session: AsyncSession,+ tenant_id: str,+ user: User,+ room: Room,+ client: Client,+ agent: Agent,+ message_id: str,+ ) -> None:+ """Refuse a retry of anything but a message of this room the agent took a+ turn for, asked by whoever sent it or someone who manages the room."""+ message = (+ await session.execute(+ select(Message).where(+ Message.room_id == room.id,+ Message.transport_event_id == message_id,+ )+ )+ ).scalar_one_or_none()+ if message is None:+ raise ChatError(+ 404, "MESSAGE_NOT_FOUND", "That message is not in this chat."+ )+ if message.sender_client_id != client.id and not await self.can_manage(+ session, tenant_id, user, room+ ):+ raise ChatError(+ 403,+ "NOT_YOUR_MESSAGE",+ "Only whoever sent that message, or someone who manages the chat, can retry it.",+ )+ turn = await self._activity_store.turn_for_message(+ session, agent.id, room.id, message_id+ )+ if turn is None:+ raise ChatError(+ 409,+ "NOTHING_TO_RETRY",+ f"{agent.name} took no turn for that message, so there is nothing to retry.",+ )+async def warm(self, tenant_id: str, user: User, room_id: str, *, agent_id: str) -> None:diff --git a/core/switch_core/db/stores/session_activity_store.py b/core/switch_core/db/stores/session_activity_store.pyindex 534138631..7e1a9e570 100644--- a/core/switch_core/db/stores/session_activity_store.py+++ b/core/switch_core/db/stores/session_activity_store.py@@ -279,6 +279,23 @@ class AgentSessionActivityStore:)return list(result.scalars())+ async def turn_for_message(+ self, session: AsyncSession, agent_id: str, room_id: str, message_id: str+ ) -> AgentSessionActivityItem | None:+ """The agent's latest turn started by `message_id` in `room_id`, if it took one."""+ result = await session.execute(+ select(AgentSessionActivityItem)+ .where(+ AgentSessionActivityItem.agent_id == agent_id,+ AgentSessionActivityItem.room_id == room_id,+ AgentSessionActivityItem.message_id == message_id,+ AgentSessionActivityItem.item_id == TURN_ITEM_ID,+ )+ .order_by(AgentSessionActivityItem.created_at.desc())+ .limit(1)+ )+ return result.scalar_one_or_none()+async def newest_running_turn(self, session: AsyncSession, agent_id: str) -> AgentSessionActivityItem | None:diff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.pyindex 9877a226a..7b9d6b7c5 100644--- a/core/switch_core/gateway/chats.py+++ b/core/switch_core/gateway/chats.py@@ -141,6 +141,8 @@ class ControlRequest(CamelModel):request_id: stragent_id: strcommand: RoomControl+ # The message whose turn a `retry` runs again; absent for every other control.+ message_id: str | None = Noneclass ControlAccepted(CamelModel):@@ -460,6 +462,7 @@ async def send_control(request_id=req.request_id,agent_id=req.agent_id,command=req.command,+ message_id=req.message_id,)return ControlAccepted(command_id=command_id)diff --git a/core/switch_core/sessions/contract.py b/core/switch_core/sessions/contract.pyindex fd3fc9ea7..60199f8ee 100644--- a/core/switch_core/sessions/contract.py+++ b/core/switch_core/sessions/contract.py@@ -100,6 +100,8 @@ class Capability(_Model):compact: boolmodel_change: boolattachment_mime_types: list[str]+ # Absent from a host built before `message.retry`, which means it cannot.+ retry: bool = Falseclass Attachment(_Model):@@ -381,6 +383,13 @@ class SessionCompact(_Model):type: Literal["session.compact"]+class MessageRetry(_Model):+ """Run again the turn a room message started, which ended without an answer."""++ type: Literal["message.retry"]+ message_id: Id++class SessionModelSet(_Model):type: Literal["session.model.set"]model_id: Id@@ -394,6 +403,7 @@ CommandBody = Annotated[| SessionStop| SessionReset| SessionCompact+ | MessageRetry| SessionModelSet,Field(discriminator="type"),]diff --git a/core/tests/switch_core/bridges/agent/test_control_commands.py b/core/tests/switch_core/bridges/agent/test_control_commands.pyindex 3b4bce41e..bf202df0c 100644--- a/core/tests/switch_core/bridges/agent/test_control_commands.py+++ b/core/tests/switch_core/bridges/agent/test_control_commands.py@@ -10,6 +10,7 @@ import switch_core.bridges.agent.commands as commandsfrom switch_core.bridges.agent.commands import (_check_control_target,_cmd_reset,+ _cmd_retry,)from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.bridges.agent.protocol.controller_presence import Binding@@ -425,5 +426,76 @@ def test_an_interrupt_names_the_current_turn() -> None:thread_id=None,surface="slack",requester_name="louisa",+ target_message_id=None,)assert frame["body"] == {"type": "turn.interrupt", "turnId": "current"}+++def test_a_retry_runs_again_the_message_it_names() -> None:+ assert commands.retry_target("@helper $m1") == "$m1"+ assert commands.retry_target("@helper") is None+ assert commands.retry_target("$m1") is None+ frame = commands.room_control_frame(+ agent_id="a",+ session_id=None,+ room_id="r",+ action="retry",+ actor_id="@u:s",+ message_id="$retry-command",+ thread_id=None,+ surface="switch-web",+ requester_name="louisa",+ target_message_id="$m1",+ )+ assert frame["body"] == {"type": "message.retry", "messageId": "$m1"}+ with pytest.raises(ValueError):+ commands.room_control_frame(+ agent_id="a",+ session_id=None,+ room_id="r",+ action="retry",+ actor_id="@u:s",+ message_id="$retry-command",+ thread_id=None,+ surface="switch-web",+ requester_name="louisa",+ target_message_id=None,+ )+++async def test_a_controller_backed_agent_is_relayed_a_retry_of_the_message(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ reply = _Reply()+ monkeypatch.setattr(commands, "_reply", reply)++ async def _surface(*_a: Any) -> str:+ return "switch-web"++ monkeypatch.setattr(commands, "_room_surface", _surface)+ registry = AgentConnectionRegistry()+ registry.controllers.bind(+ Binding(+ agent_id="agent-1",+ controller_id="controller-1",+ tenant_id="tenant",+ controller_name="machine",+ running=True,+ )+ )+ conn = registry.controllers.open(+ controller_id="controller-1", tenant_id="tenant", resume_cursors={}+ )+ registry.controllers.attach_stream(conn)+ client = _client(reply, command_level="unsupported", enqueue=[])+ client._connections = registry++ event = _event("retry")+ event.args = "@agent $m1"+ await _cmd_retry(client, SimpleNamespace(room_id="!m:server"), event, False)++ [(agent_id, frame)] = conn.session_commands+ assert agent_id == "agent-1"+ assert frame["body"] == {"type": "message.retry", "messageId": "$m1"}+ assert reply.bodies[-1] == "Trying that message again."diff --git a/core/tests/switch_core/gateway/test_chats_controls.py b/core/tests/switch_core/gateway/test_chats_controls.pyindex e7e0781be..e95207778 100644--- a/core/tests/switch_core/gateway/test_chats_controls.py+++ b/core/tests/switch_core/gateway/test_chats_controls.py@@ -182,3 +182,95 @@ async def test_stop_follows_the_running_turn_not_one_queued_behind_it(running = await _control(chats, chats.alice, running_room, agent, "k2", "interrupt")assert running.status_code == 202, running.text+++async def _retry(+ chats: _Harness,+ user: User,+ room_id: str,+ agent: Agent,+ request_id: str,+ message_id: str | None,+) -> httpx.Response:+ return await chats.client.post(+ f"/chats/{room_id}/controls",+ json={+ "requestId": request_id,+ "agentId": agent.id,+ "command": "retry",+ **({"messageId": message_id} if message_id is not None else {}),+ },+ headers=chats.as_user(user),+ )+++async def _turn_for(+ chats: _Harness, agent: Agent, room_id: str, message_id: str+) -> None:+ await _step(chats, agent, room_id, "t1", "turn", 1)+ async with chats.factory() as session:+ await session.execute(+ update(AgentSessionActivityItem)+ .where(AgentSessionActivityItem.turn_id == "t1")+ .values(message_id=message_id, status="error")+ )+ await session.commit()+++async def test_a_retry_names_a_message_the_agent_took_a_turn_for(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ sent = await chats.send(chats.alice, room_id, "m1", "@helper plan a picnic")+ message_id = sent.json()["messages"][0]["messageId"]++ unnamed = await _retry(chats, chats.alice, room_id, agent, "k0", None)+ assert unnamed.status_code == 422+ assert _code(unnamed) == "INVALID_CONTROL"+ elsewhere = await _retry(chats, chats.alice, room_id, agent, "k1", "$nowhere")+ assert elsewhere.status_code == 404+ assert _code(elsewhere) == "MESSAGE_NOT_FOUND"+ untried = await _retry(chats, chats.alice, room_id, agent, "k2", message_id)+ assert untried.status_code == 409+ assert _code(untried) == "NOTHING_TO_RETRY"+ assert await _commands(chats, room_id) == []++ await _turn_for(chats, agent, room_id, message_id)+ accepted = await _retry(chats, chats.alice, room_id, agent, "k3", message_id)+ assert accepted.status_code == 202, accepted.text+ [row] = await _commands(chats, room_id)+ assert row.content["command"] == "retry"+ assert row.content["args"] == f"@helper {message_id}"+ # Nothing the person wrote is posted again.+ humans = [+ m+ for m in await chats.message_rows(room_id)+ if m.body == "@helper plan a picnic"+ ]+ assert len(humans) == 1+++async def test_a_retry_is_for_the_sender_or_a_manager_and_posts_once(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200+ sent = await chats.send(chats.alice, room_id, "m1", "@helper plan a picnic")+ message_id = sent.json()["messages"][0]["messageId"]+ await _turn_for(chats, agent, room_id, message_id)++ not_theirs = await _retry(chats, chats.bob, room_id, agent, "k1", message_id)+ assert not_theirs.status_code in (403,)+ assert _code(not_theirs) in ("NOT_YOUR_MESSAGE", "AGENT_NOT_ALLOWED")++ # A double press, or a reconnect replaying the request: one command.+ first = await _retry(chats, chats.alice, room_id, agent, "k2", message_id)+ again = await _retry(chats, chats.alice, room_id, agent, "k2", message_id)+ assert first.status_code == again.status_code == 202+ assert first.json() == again.json()+ assert len(await _commands(chats, room_id)) == 1+ other = await _retry(chats, chats.alice, room_id, agent, "k2", "$other")+ assert other.status_code == 409+ assert _code(other) == "REQUEST_REUSED"diff --git a/core/tests/switch_core/management/test_contract_fixtures.py b/core/tests/switch_core/management/test_contract_fixtures.pyindex 4095c524b..485b7f22b 100644--- a/core/tests/switch_core/management/test_contract_fixtures.py+++ b/core/tests/switch_core/management/test_contract_fixtures.py@@ -407,6 +407,7 @@ class TestStreamFrames:thread_id=None,surface="slack",requester_name="Ada",+ target_message_id=None,),)provoked += await take(stream, 1)diff --git a/core/tests/switch_core/management/test_stream.py b/core/tests/switch_core/management/test_stream.pyindex 39b3b3288..2e4e474cb 100644--- a/core/tests/switch_core/management/test_stream.py+++ b/core/tests/switch_core/management/test_stream.py@@ -399,6 +399,7 @@ class TestLiveChanges:thread_id=None,surface="slack",requester_name="Ada",+ target_message_id=None,)assert harness.protocol.connections.relay_session_command(agent_id, command)(frame,) = await take(stream, 1)