The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(chat): identify sub-agent spawn events so a replay cannot cancel a question\n\nTwo P2 review findings on the delegation card, both about a signal the surface\ncould not act on.\n\n**A replayed spawn cleared a live question.** `continue_subagent` announces a\nresume by republishing `subagent_spawned` for the same task/agent, so "a row\nthat already exists got spawned again" was read as a resume — and that is\nexactly what Socket.IO redelivering the ORIGINAL spawn looks like. This socket\nreconnects and replays freely (13+ times in one measured session), so the\nfailure was likely, not theoretical: the pause cleared, the question vanished,\nand the user was left with a spinner for a child still blocked on them. That is\nthe class of bug this change set exists to remove.\n\nThe core already stamps the answer. `publish_seq_stamped` puts a per-request\nmonotonic `seq` on every event it emits, and `WebChannelEvent` documents\n`(request_id, seq)` as the pair the frontend is meant to dedupe replayed\nagainst live events with. It was simply not declared on the sub-agent wire\ntypes or read anywhere, so it is declared and read now, in two places:\n\n- `ChatRuntimeProvider` gates `onSubagentSpawned` and `onSubagentAwaitingUser`\n through the same `markChatEventSeen` cache `onToolCall`/`onToolResult`\n already use. The mirrored guard matters on its own: a replayed\n `subagent_awaiting_user` would otherwise re-park a child that had resumed.\n- `subagentSpawned` records the identity of the event that started the row and\n unparks only for an identity it has not already been started by. That cache\n is bounded (10 min, 500 entries) and a busy thread can evict a key, so the\n reducer keeps a durable check of its own rather than trusting it.\n\nUnidentifiable events (an older core with no `seq`, replayed inside one\nrequest) collapse to the same string and are treated as replays deliberately.\nIt is the safe direction to fail: a stale question is visible and still settles\non `subagent_done`, while a silently cleared one strands the user. The resume\nthat matters carries a different `request_id` regardless, because the user's\nanswer is what triggers it.\n\n**Inline delegations could not open the drawer.** `SubagentCall` is the only\nrenderer for a delegation on the assistant-ui surface and supplied no `onView`,\nso it could not set `openSubagentTaskId`. The legacy `ToolTimelineBlock` passes\none per row; the sole remaining launcher, `BackgroundProcessesPanel`, lists\nasync/typed spawns only — so every other delegation's persisted worker\nconversation was unreachable.\n\n`subagentDrawerHost` is the seam: a context, because the consumer is a tool\npart rendered from inside the transcript while the drawer's disclosure state\nbelongs to `Conversations`. It carries `canOpen` as well as `open` — the host\nresolves a `taskId` against the thread's live timeline and renders nothing when\nit is absent, so a delegation replayed from the settled core transcript would\notherwise get a button that opens an empty sheet. Asking the host also keeps\nthe tool part free of a store subscription: it renders on surfaces that have no\nRedux provider. No host, no affordance, which is what the read-only mounts (the\ndrawer itself, past-turn insights) want.\n\nThe two fixes share a commit because they share a test file: the drawer cases\nbuild on the spawn-identity helpers the replay cases introduce.\n
M3gA-Minda70ae2d8b24c
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsxindex 3b57446115..2e2c73177f 100644--- a/app/src/features/conversations/Conversations.tsx+++ b/app/src/features/conversations/Conversations.tsx@@ -1732,6 +1732,14 @@ const Conversations = ({[selectedThreadToolTimeline]);const runningBackgroundCount = backgroundProcesses.filter(p => p.status === 'running').length;+ // `TranscriptOverlays` resolves the open delegation out of this same live+ // timeline and renders nothing when the id is absent, so an inline card must+ // not offer "View full processing" for a delegation that would open an empty+ // sheet -- a delegation replayed from the settled core transcript, say.+ const canOpenSubagentDrawer = useCallback(+ (taskId: string) => selectedThreadToolTimeline.some(entry => entry.subagent?.taskId === taskId),+ [selectedThreadToolTimeline]+ );// Poll-free live signal: lights the badge when memories are syncing even if// no sub-agent is running and the panel is closed.const memorySyncActive = useMemorySyncActive();@@ -2648,6 +2656,12 @@ const Conversations = ({// same conversation partner, not a second one.onOpenHumanMode={() => navigate('/human')}onSwitchToMicCloud={() => setComposerOverride('mic-cloud')}+ // Lets a delegation card inside the transcript open the drawer below.+ // `setOpenSubagentTaskId` is a stable setter, and `canOpenSubagent` is+ // memoised on the timeline, so the context value only churns when the+ // set of resolvable delegations actually changes.+ onOpenSubagent={setOpenSubagentTaskId}+ canOpenSubagent={canOpenSubagentDrawer}onModelChange={(value, contextWindow) => {setComposerModelOverride(value);setComposerModelContextWindow(contextWindow ?? null);diff --git a/app/src/features/conversations/components/AssistantUiChat.tsx b/app/src/features/conversations/components/AssistantUiChat.tsxindex bd0a8a9d59..e91d8b3712 100644--- a/app/src/features/conversations/components/AssistantUiChat.tsx+++ b/app/src/features/conversations/components/AssistantUiChat.tsx@@ -15,6 +15,7 @@ import { useAppSelector } from '../../../store/hooks';import { DEFAULT_MASCOT_COLOR } from '../../../store/mascotSlice';import { MascotChipAvatar } from '../../human/Mascot/MascotChipAvatar';import { AssistantUiInferenceStatus } from './AssistantUiInferenceStatus';+import { SubagentDrawerHost } from './aui/subagentDrawerHost';import { ChatToolFallback, ChatToolGroup } from './ChatToolParts';import { contextUsageFromTokenUsage, ContextWindowPill } from './composer/ContextWindowPill';import {@@ -78,6 +79,8 @@ export function AssistantUiChat({onAttachmentOnlySend,onOpenHumanMode,onSwitchToMicCloud,+ onOpenSubagent,+ canOpenSubagent,}: {threadGoal: ThreadGoalController;model: string | null;@@ -104,6 +107,14 @@ export function AssistantUiChat({onOpenHumanMode?: () => void;/** Switches to the existing microphone-first chat composer. */onSwitchToMicCloud?: () => void;+ /**+ * Opens the host's `SubagentDrawer` on a delegation, by spawn `taskId`.+ * Handed down by context rather than by prop because the caller is a tool+ * part rendered from inside the transcript; see `subagentDrawerHost`.+ */+ onOpenSubagent?: (taskId: string) => void;+ /** Whether the host's drawer can resolve that delegation; see the same file. */+ canOpenSubagent?: (taskId: string) => boolean;}) {const { t } = useT();const fileInputRef = useRef<HTMLInputElement>(null);@@ -275,14 +286,16 @@ export function AssistantUiChat({return (<AssistantUiRuntimeProvider><ComposerTextBridge value={inputValue} onChange={onInputValueChange} />- <Thread- components={components}- model={model}- onModelChange={onModelChange}- loadError={loadError}- onEscape={onEscape}- slashCommands={slashCommands}- />+ <SubagentDrawerHost onOpenSubagent={onOpenSubagent} canOpenSubagent={canOpenSubagent}>+ <Thread+ components={components}+ model={model}+ onModelChange={onModelChange}+ loadError={loadError}+ onEscape={onEscape}+ slashCommands={slashCommands}+ />+ </SubagentDrawerHost></AssistantUiRuntimeProvider>);}diff --git a/app/src/features/conversations/components/AssistantUiSubagentCall.awaitingUser.test.tsx b/app/src/features/conversations/components/AssistantUiSubagentCall.awaitingUser.test.tsxindex e0f6f1655a..b483d4c528 100644--- a/app/src/features/conversations/components/AssistantUiSubagentCall.awaitingUser.test.tsx+++ b/app/src/features/conversations/components/AssistantUiSubagentCall.awaitingUser.test.tsx@@ -25,6 +25,7 @@ import chatRuntimeReducer, {} from '../../../store/chatRuntimeSlice';import threadReducer from '../../../store/threadSlice';import { AssistantUiSubagentCall } from './AssistantUiSubagentCall';+import { SubagentDrawerHost } from './aui/subagentDrawerHost';import { SubagentCall } from './ChatToolParts';vi.mock('../../../services/api/threadApi', () => ({@@ -70,8 +71,8 @@ function buildStore() {});}-/** Drive the row through the real reducers, exactly as the socket does. */-function parkTheDelegation(store: ReturnType<typeof buildStore>, question: string) {+/** One `subagent_spawned`, identified the way the provider identifies them. */+function spawn(store: ReturnType<typeof buildStore>, spawnEventId?: string) {store.dispatch(subagentSpawned({threadId: THREAD_ID,@@ -80,11 +81,25 @@ function parkTheDelegation(store: ReturnType<typeof buildStore>, question: strintaskId: 'sub-1',agentId: 'researcher',displayName: 'Researcher',+ spawnEventId,}));+}++/** Drive the row through the real reducers, exactly as the socket does. */+function parkTheDelegation(+ store: ReturnType<typeof buildStore>,+ question: string,+ spawnEventId = 'req-1:3'+) {+ spawn(store, spawnEventId);store.dispatch(subagentAwaitingUser({ threadId: THREAD_ID, rowId: ROW_ID, question }));}+function rowOf(store: ReturnType<typeof buildStore>) {+ return store.getState().chatRuntime.toolTimelineByThread[THREAD_ID]?.[0];+}+afterEach(() => __resetChatSurfaces());describe('sub-agent awaiting user', () => {@@ -109,16 +124,10 @@ describe('sub-agent awaiting user', () => {// `subagent_spawned` for the SAME task/agent, so the row id is identical.// The idempotency guard used to swallow it wholesale, leaving the card// asking a question the user had already answered for the rest of the run.- store.dispatch(- subagentSpawned({- threadId: THREAD_ID,- round: 1,- rowId: ROW_ID,- taskId: 'sub-1',- agentId: 'researcher',- displayName: 'Researcher',- })- );+ // The resume is a new emission, so it carries a new `(request_id, seq)`+ // -- in practice a whole new parent turn, since the user's answer is what+ // triggers it.+ spawn(store, 'req-2:0');const rows = store.getState().chatRuntime.toolTimelineByThread[THREAD_ID] ?? [];expect(rows).toHaveLength(1); // still idempotent: no duplicate row@@ -126,6 +135,52 @@ describe('sub-agent awaiting user', () => {expect(rows[0]?.subagent?.status).toBe('running');expect(rows[0]?.subagent?.awaitingQuestion).toBeUndefined();});++ it('keeps the pending question when the ORIGINAL spawn is redelivered', () => {+ // This socket reconnects and replays freely -- 13+ times in one measured+ // session. A redelivered `subagent_spawned` arriving after+ // `subagent_awaiting_user` is shape-identical to `continue_subagent`+ // resuming the child, so the unpark used to fire on it and the question+ // vanished while the child was still blocked on the user: a spinner with+ // nothing to answer, which is the exact bug this whole change exists to+ // remove. The redelivery repeats the identity the core stamped, so it is+ // recognisable as a replay.+ const store = buildStore();+ parkTheDelegation(store, 'Which of the two repos should I patch?', 'req-1:3');++ spawn(store, 'req-1:3'); // <- the same emission, delivered twice++ const rows = store.getState().chatRuntime.toolTimelineByThread[THREAD_ID] ?? [];+ expect(rows).toHaveLength(1);+ expect(rows[0]?.status).toBe('awaiting_user');+ expect(rows[0]?.subagent?.status).toBe('awaiting_user');+ expect(rows[0]?.subagent?.awaitingQuestion).toBe('Which of the two repos should I patch?');+ });++ it('keeps the pending question when the spawn cannot be identified at all', () => {+ // An older core stamps no `seq`, so a replay inside one request collapses+ // to the same string as the original. Failing towards "this is a replay"+ // is deliberate: a stale question is visible and still settles on+ // `subagent_done`, while a silently cleared one strands the user.+ const store = buildStore();+ parkTheDelegation(store, 'Which repo?', undefined);++ spawn(store, undefined);++ expect(rowOf(store)?.status).toBe('awaiting_user');+ expect(rowOf(store)?.subagent?.awaitingQuestion).toBe('Which repo?');+ });++ it('leaves a running row alone when its spawn is redelivered', () => {+ // The replay guard must not disturb the ordinary case it also covers.+ const store = buildStore();+ spawn(store, 'req-1:3');+ spawn(store, 'req-1:3');++ const rows = store.getState().chatRuntime.toolTimelineByThread[THREAD_ID] ?? [];+ expect(rows).toHaveLength(1);+ expect(rows[0]?.status).toBe('running');+ });});describe('the render half', () => {@@ -223,4 +278,91 @@ describe('sub-agent awaiting user', () => {expect(screen.getByTestId('subagent-answer-sent')).toBeInTheDocument();});});++ describe('opening the drawer', () => {+ /** Render the inline delegation card the way the /chat transcript does. */+ function renderInlineCall(+ store: ReturnType<typeof buildStore>,+ onOpenSubagent?: (taskId: string) => void,+ canOpenSubagent?: (taskId: string) => boolean+ ) {+ return render(+ <Provider store={store}>+ <AssistantUiRuntimeProvider>+ <SubagentDrawerHost onOpenSubagent={onOpenSubagent} canOpenSubagent={canOpenSubagent}>+ <SubagentCall+ type="tool-call"+ toolName="task"+ toolCallId={ROW_ID}+ args={{ subagent_type: 'researcher', progress: activity } as never}+ argsText="{}"+ result={undefined}+ status={{ type: 'running' }}+ addResult={() => {}}+ resume={() => {}}+ respondToApproval={() => {}}+ />+ </SubagentDrawerHost>+ </AssistantUiRuntimeProvider>+ </Provider>+ );+ }++ /**+ * The card is collapsed by default and the "View full processing" button+ * lives in its content, so every assertion here has to open it first --+ * otherwise the two negative cases pass for the wrong reason.+ */+ async function expandCard() {+ await act(async () => {+ await userEvent.click(screen.getByRole('button', { name: /Delegated to Researcher/i }));+ });+ }++ it('opens the sub-agent drawer on the delegation the card is showing', async () => {+ // This is the ONLY renderer for a delegation on the assistant-ui surface,+ // and it offered no way into `SubagentDrawer`: the legacy+ // `ToolTimelineBlock` passes `onView` per row, and the one remaining+ // launcher (`BackgroundProcessesPanel`) lists async/typed spawns only, so+ // every other delegation's persisted worker conversation was unreachable.+ const store = buildStore();+ spawn(store, 'req-1:3');+ const onOpenSubagent = vi.fn();++ renderInlineCall(store, onOpenSubagent, () => true);+ await expandCard();++ await act(async () => {+ await userEvent.click(screen.getByTestId('subagent-view-processing'));+ });+ expect(onOpenSubagent).toHaveBeenCalledWith('sub-1');+ });++ it('offers nothing when no host is mounted', async () => {+ // The read-only mounts of this card (the drawer itself, past-turn+ // insights) render outside the host and must not grow a dead button.+ const store = buildStore();+ spawn(store, 'req-1:3');++ renderInlineCall(store, undefined, () => true);+ await expandCard();++ expect(screen.getByTestId('subagent-activity')).toBeInTheDocument();+ expect(screen.queryByTestId('subagent-view-processing')).not.toBeInTheDocument();+ });++ it('offers nothing for a delegation the drawer cannot resolve', async () => {+ // `TranscriptOverlays` looks the row up by `taskId` in the thread's live+ // timeline and renders nothing when it is absent, so a part replayed from+ // the settled core transcript would get a button opening an empty sheet.+ const store = buildStore();+ spawn(store, 'req-1:3');++ renderInlineCall(store, vi.fn(), () => false);+ await expandCard();++ expect(screen.getByTestId('subagent-activity')).toBeInTheDocument();+ expect(screen.queryByTestId('subagent-view-processing')).not.toBeInTheDocument();+ });+ });});diff --git a/app/src/features/conversations/components/ChatToolParts.tsx b/app/src/features/conversations/components/ChatToolParts.tsxindex ef8779e81a..279d4bccb6 100644--- a/app/src/features/conversations/components/ChatToolParts.tsx+++ b/app/src/features/conversations/components/ChatToolParts.tsx@@ -18,6 +18,7 @@ import type { PendingApproval, SubagentActivity } from '../../../store/chatRuntiimport { useAppSelector } from '../../../store/hooks';import { AssistantUiSubagentCall, isActiveSubagentStatus } from './AssistantUiSubagentCall';import { isApprovalPending, OpenHumanToolCall } from './AssistantUiToolCall';+import { useSubagentDrawerHost } from './aui/subagentDrawerHost';function asSubagentActivity(value: unknown): SubagentActivity | undefined {if (!value || typeof value !== 'object') return undefined;@@ -72,12 +73,29 @@ export const SubagentCall: ToolCallMessagePartComponent = ({ args, result }) =>},[aui]);+ // "View full processing" opens the host's `SubagentDrawer`. This is the only+ // renderer for a delegation on the assistant-ui surface, and it was the only+ // one that offered no way in: the legacy `ToolTimelineBlock` passes `onView`+ // per row, and the sole remaining launcher -- `BackgroundProcessesPanel` --+ // lists async/typed spawns only, so every other delegation's persisted worker+ // conversation was unreachable.+ //+ // Offered only when the host says the drawer can resolve the row -- it looks+ // the delegation up by `taskId` in the thread's live timeline+ // (`TranscriptOverlays`) and renders nothing for a `taskId` that is not+ // there, so a part replayed from the settled core transcript would otherwise+ // get a button that opens an empty sheet. Asked of the host rather than of+ // Redux directly: this component renders on surfaces that have no store.+ const drawerHost = useSubagentDrawerHost();+ const taskId = resolved.taskId;+ const view = useCallback(() => drawerHost?.open(taskId), [drawerHost, taskId]);return (<AssistantUiSubagentCallactivity={resolved}running={running}description={description}onAnswer={answer}+ onView={drawerHost?.canOpen(taskId) ? view : undefined}/>);};diff --git a/app/src/features/conversations/components/aui/subagentDrawerHost.tsx b/app/src/features/conversations/components/aui/subagentDrawerHost.tsxnew file mode 100644index 0000000000..b770195a18--- /dev/null+++ b/app/src/features/conversations/components/aui/subagentDrawerHost.tsx@@ -0,0 +1,55 @@+import { createContext, type ReactNode, useContext, useMemo } from 'react';++export interface SubagentDrawerHostValue {+ /** Opens the host's `SubagentDrawer` on a delegation, by spawn `taskId`. */+ open: (taskId: string) => void;+ /**+ * Whether the drawer can actually show that delegation.+ *+ * The host resolves a `taskId` against the thread's live tool timeline and+ * renders nothing when it is absent, so a delegation replayed from the+ * settled core transcript would otherwise get a button that opens an empty+ * sheet. Asking the host keeps that knowledge where it already lives, and+ * keeps this seam's consumers - which are tool parts, rendered by+ * assistant-ui in contexts that do not all have a Redux store - free of a+ * store subscription of their own.+ */+ canOpen: (taskId: string) => boolean;+}++/**+ * The host that owns the sub-agent drawer's disclosure state.+ *+ * A context rather than a prop because the consumer is a *tool part*: the+ * delegation card is rendered by assistant-ui from inside the transcript, many+ * layers below anything the host passes props to, while the drawer belongs to+ * `Conversations`. `null` outside a provider, which is what every read-only+ * mount of the card (the drawer itself, past-turn insights) wants: no host, no+ * "View full processing" affordance.+ */+const SubagentDrawerHostContext = createContext<SubagentDrawerHostValue | null>(null);++export function SubagentDrawerHost({+ onOpenSubagent,+ canOpenSubagent,+ children,+}: {+ onOpenSubagent?: ((taskId: string) => void) | undefined;+ canOpenSubagent?: ((taskId: string) => boolean) | undefined;+ children: ReactNode;+}) {+ const value = useMemo<SubagentDrawerHostValue | null>(+ () =>+ onOpenSubagent ? { open: onOpenSubagent, canOpen: canOpenSubagent ?? (() => true) } : null,+ [onOpenSubagent, canOpenSubagent]+ );+ return (+ <SubagentDrawerHostContext.Provider value={value}>+ {children}+ </SubagentDrawerHostContext.Provider>+ );+}++export function useSubagentDrawerHost(): SubagentDrawerHostValue | null {+ return useContext(SubagentDrawerHostContext);+}diff --git a/app/src/providers/ChatRuntimeProvider.tsx b/app/src/providers/ChatRuntimeProvider.tsxindex 9bc2535233..7a21d1ca34 100644--- a/app/src/providers/ChatRuntimeProvider.tsx+++ b/app/src/providers/ChatRuntimeProvider.tsx@@ -639,6 +639,22 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {);},onSubagentSpawned: event => {+ // Event-seen guard, matching `onToolCall`/`onToolResult`. This socket+ // reconnects and redelivers freely (13+ times in one measured+ // session), and a replayed `subagent_spawned` that lands AFTER+ // `subagent_awaiting_user` looks exactly like `continue_subagent`+ // resuming the child — the reducer would clear the pause and the+ // question would vanish while the child was still blocked. `seq` is+ // the core's own answer to this: `(request_id, seq)` is stamped per+ // emission (`publish_seq_stamped`), so a redelivery repeats the pair+ // and a real resume never does. The reducer keeps its own durable+ // check for the case this bounded cache has already evicted.+ const eventKey = `subagent_spawned:${event.thread_id}:${event.request_id ?? 'none'}:${event.seq ?? `${event.round}:${event.skill_id}:${event.tool_name}`}`;+ if (+ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })+ ) {+ return;+ }const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];dispatch(setInferenceStatusForThread({@@ -664,10 +680,21 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {workerThreadId: event.subagent?.worker_thread_id,mode: event.subagent?.mode,dedicatedThread: event.subagent?.dedicated_thread,+ // Identity of THIS emission, carried into the reducer so it can+ // tell a resume from a replay without depending on the cache above.+ spawnEventId: `${event.request_id ?? 'none'}:${event.seq ?? 'noseq'}`,}));},onSubagentAwaitingUser: (event: ChatSubagentDoneEvent) => {+ // Same guard, mirrored: a replayed `subagent_awaiting_user` arriving+ // after the child has resumed would re-park a running row.+ const eventKey = `subagent_awaiting_user:${event.thread_id}:${event.request_id ?? 'none'}:${event.seq ?? `${event.round}:${event.skill_id}:${event.tool_name}`}`;+ if (+ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })+ ) {+ return;+ }dispatch(subagentAwaitingUser({threadId: event.thread_id,diff --git a/app/src/providers/__tests__/ChatRuntimeProvider.subagentReplay.test.tsx b/app/src/providers/__tests__/ChatRuntimeProvider.subagentReplay.test.tsxnew file mode 100644index 0000000000..14ef17a102--- /dev/null+++ b/app/src/providers/__tests__/ChatRuntimeProvider.subagentReplay.test.tsx@@ -0,0 +1,172 @@+/**+ * A redelivered `subagent_spawned` must not cancel a live sub-agent question.+ *+ * `continue_subagent` announces a resume by republishing `subagent_spawned` for+ * the same task/agent, so "a row that already exists got spawned again" is the+ * only resume signal the frontend receives — and it is exactly what Socket.IO+ * redelivering the ORIGINAL spawn looks like. This socket reconnects and+ * replays freely (13+ times in one measured session), so the failure is not+ * hypothetical: the pause is cleared, the question disappears, and the user is+ * left with a spinner for a child that is still blocked on them.+ *+ * Two independent guards, tested here at the seam they defend: the provider's+ * event-seen cache keyed on the core's `(request_id, seq)` stamp, and — for the+ * case that cache has evicted — the reducer's own identity check.+ */+import { render } from '@testing-library/react';+import { act } from 'react';+import { Provider } from 'react-redux';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import * as chatService from '../../services/chatService';+import { threadApi } from '../../services/api/threadApi';+import { store } from '../../store';+import { clearAllChatRuntime, resetSessionTokenUsage } from '../../store/chatRuntimeSlice';+import { setStatusForUser } from '../../store/socketSlice';+import { clearAllThreads } from '../../store/threadSlice';+import ChatRuntimeProvider from '../ChatRuntimeProvider';++vi.mock('../../services/chatService', async () => {+ const actual = await vi.importActual<typeof chatService>('../../services/chatService');+ return { ...actual, subscribeChatEvents: vi.fn() };+});++vi.mock('../../services/api/threadApi', () => ({+ threadApi: {+ createNewThread: vi.fn(),+ getThreads: vi.fn(),+ getThreadMessages: vi.fn(),+ appendMessage: vi.fn(),+ generateTitleIfNeeded: vi.fn(),+ updateMessage: vi.fn(),+ deleteThread: vi.fn(),+ purge: vi.fn(),+ getTaskBoard: vi.fn(),+ putTaskBoard: vi.fn(),+ },+}));++vi.mock('../../hooks/usageRefresh', () => ({ requestUsageRefresh: vi.fn() }));+vi.mock('../../hooks/useRefetchSnapshotOnTurnEnd', () => ({+ useRefetchSnapshotOnTurnEnd: () => ({ refetch: vi.fn() }),+}));++const THREAD = 't-replay';+const ROW = `${THREAD}:subagent:sub-1:researcher`;+const QUESTION = 'Which of the two repos should I patch?';++function renderProvider(): chatService.ChatEventListeners {+ let captured: chatService.ChatEventListeners = {};+ vi.mocked(chatService.subscribeChatEvents).mockImplementation(listeners => {+ captured = listeners;+ return () => {};+ });+ store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));+ render(+ <Provider store={store}>+ <ChatRuntimeProvider>+ <div />+ </ChatRuntimeProvider>+ </Provider>+ );+ return captured;+}++/** The socket frame the core emits, `seq` and all. */+function spawnEvent(seq: number, requestId = 'req-1') {+ return {+ thread_id: THREAD,+ request_id: requestId,+ round: 0,+ tool_name: 'researcher',+ skill_id: 'sub-1',+ message: "Sub-agent 'researcher' spawned",+ seq,+ subagent: { mode: 'typed' },+ };+}++function awaitingEvent(seq: number, requestId = 'req-1') {+ return {+ thread_id: THREAD,+ request_id: requestId,+ round: 0,+ tool_name: 'researcher',+ skill_id: 'sub-1',+ message: QUESTION,+ success: true,+ seq,+ };+}++function row() {+ return store.getState().chatRuntime.toolTimelineByThread[THREAD]?.find(e => e.id === ROW);+}++describe('ChatRuntimeProvider — replayed sub-agent spawn', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ store.dispatch(clearAllThreads());+ store.dispatch(clearAllChatRuntime());+ store.dispatch(resetSessionTokenUsage());+ store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));+ vi.mocked(threadApi.getThreads).mockResolvedValue({ threads: [], count: 0 });+ });++ it('keeps the question when the original spawn frame is redelivered', () => {+ const listeners = renderProvider();++ act(() => {+ listeners.onSubagentSpawned?.(spawnEvent(3));+ listeners.onSubagentAwaitingUser?.(awaitingEvent(7));+ });+ expect(row()?.status).toBe('awaiting_user');+ expect(row()?.subagent?.awaitingQuestion).toBe(QUESTION);++ act(() => {+ // Reconnect. The core does not re-emit; the transport re-delivers the+ // same frame, `seq` included.+ listeners.onSubagentSpawned?.(spawnEvent(3));+ });++ expect(row()?.status).toBe('awaiting_user');+ expect(row()?.subagent?.status).toBe('awaiting_user');+ expect(row()?.subagent?.awaitingQuestion).toBe(QUESTION);+ });++ it('still resumes on a real continue_subagent spawn', () => {+ const listeners = renderProvider();++ act(() => {+ listeners.onSubagentSpawned?.(spawnEvent(3));+ listeners.onSubagentAwaitingUser?.(awaitingEvent(7));+ });+ expect(row()?.status).toBe('awaiting_user');++ act(() => {+ // The user answered, so this is a new parent turn: new request, and the+ // bridge's per-request counter starts over.+ listeners.onSubagentSpawned?.(spawnEvent(0, 'req-2'));+ });++ expect(row()?.status).toBe('running');+ expect(row()?.subagent?.awaitingQuestion).toBeUndefined();+ });++ it('does not re-park a resumed child when the awaiting frame is redelivered', () => {+ const listeners = renderProvider();++ act(() => {+ listeners.onSubagentSpawned?.(spawnEvent(3));+ listeners.onSubagentAwaitingUser?.(awaitingEvent(7));+ listeners.onSubagentSpawned?.(spawnEvent(0, 'req-2'));+ });+ expect(row()?.status).toBe('running');++ act(() => {+ listeners.onSubagentAwaitingUser?.(awaitingEvent(7));+ });++ expect(row()?.status).toBe('running');+ });+});diff --git a/app/src/services/chatService.ts b/app/src/services/chatService.tsindex 2249ff670f..4c3a1052b7 100644--- a/app/src/services/chatService.ts+++ b/app/src/services/chatService.ts@@ -355,6 +355,13 @@ export interface ChatSubagentSpawnedEvent {skill_id: string;message: string;round: number;+ /**+ * Per-request monotonic ordering key stamped by the core's progress bridge+ * (`publish_seq_stamped`). `(request_id, seq)` is the event's identity: a+ * Socket.IO redelivery carries the same pair, a genuinely new emission never+ * does. Absent on cores that predate the stamping bridge.+ */+ seq?: number;}/** Emitted when a sub-agent completes or fails. */@@ -366,6 +373,8 @@ export interface ChatSubagentDoneEvent {message: string;success: boolean;round: number;+ /** Event identity with `request_id`; see {@link ChatSubagentSpawnedEvent.seq}. */+ seq?: number;/** Per-event subagent detail. Mirrors `SubagentProgressDetail` in core. */subagent?: SubagentProgressDetail;}diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.tsindex 263f07e551..d4b7852c47 100644--- a/app/src/store/chatRuntimeSlice.ts+++ b/app/src/store/chatRuntimeSlice.ts@@ -92,6 +92,20 @@ export interface SubagentActivity {* but not what on, and the user has nothing to answer.*/awaitingQuestion?: string;+ /**+ * Identity (`<request_id>:<seq>`) of the `subagent_spawned` event that last+ * started or resumed this delegation.+ *+ * `continue_subagent` announces a resume by republishing `subagent_spawned`+ * for the same task/agent, so "an existing row got spawned again" is the+ * only resume signal the frontend gets — and a Socket.IO redelivery of the+ * ORIGINAL spawn is indistinguishable from it by shape alone. Comparing+ * identities separates them: a redelivery repeats the pair the core stamped+ * (`publish_seq_stamped`), a genuine resume never does. Without this a+ * replay clears a live pause and the child's question disappears while it is+ * still blocked on the user.+ */+ spawnEventId?: string;/** Human-readable display name from the agent registry (e.g. "Researcher"). */displayName?: string;/**@@ -1478,6 +1492,8 @@ const chatRuntimeSlice = createSlice({workerThreadId?: string;mode?: string;dedicatedThread?: boolean;+ /** `<request_id>:<seq>` of the emitting event; see {@link SubagentActivity.spawnEventId}. */+ spawnEventId?: string;}>) => {const {@@ -1490,6 +1506,7 @@ const chatRuntimeSlice = createSlice({workerThreadId,mode,dedicatedThread,+ spawnEventId,} = action.payload;const entries = (state.toolTimelineByThread[threadId] ??= []);// Idempotent: a socket redelivery must not append a second row with the@@ -1503,11 +1520,30 @@ const chatRuntimeSlice = createSlice({// frontend gets that the pause is over. Swallowing it left the row// stuck on `awaiting_user` for the rest of the run: the card kept// asking a question the user had already answered.- if (existing.status === 'awaiting_user') {+ //+ // But "the row already exists and got spawned again" is ALSO what a+ // redelivered original spawn looks like, and this socket redelivers+ // often. So the unpark is gated on event identity: only a spawn the+ // row has not already been started by can be a resume. A replay+ // repeats the identity the core stamped and is ignored, which is the+ // safe direction to fail — a stale question is visible and recoverable+ // (`subagent_done` still settles the row), a silently cleared one+ // leaves the user staring at a spinner with nothing to answer.+ //+ // Unidentifiable events (an older core with no `seq`, replaying inside+ // one request) collapse to the same string and are therefore treated+ // as replays, deliberately: the cross-turn resume that matters carries+ // a different `request_id` regardless.+ const isResume =+ existing.status === 'awaiting_user' &&+ spawnEventId !== undefined &&+ spawnEventId !== existing.subagent?.spawnEventId;+ if (isResume) {existing.status = 'running';if (existing.subagent) {existing.subagent.status = 'running';existing.subagent.awaitingQuestion = undefined;+ existing.subagent.spawnEventId = spawnEventId;}}return;@@ -1535,6 +1571,7 @@ const chatRuntimeSlice = createSlice({agentId,displayName,workerThreadId,+ spawnEventId,mode,dedicatedThread,prompt: pending.prompt,