Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(goal): don't kill a live Claude Code run on goal-page follow-up (#22881)

Rdmclin2bac133c3a6d7
diff --git a/src/features/AgentGoals/GoalChat/GoalChatProvider.test.tsx b/src/features/AgentGoals/GoalChat/GoalChatProvider.test.tsx
new file mode 100644
index 00000000000..46a65f62c75
--- /dev/null
+++ b/src/features/AgentGoals/GoalChat/GoalChatProvider.test.tsx
@@ -0,0 +1,112 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GoalChatProvider } from './GoalChatProvider';
+
+const hooks = vi.hoisted(() => ({
+ useGatewayReconnect: vi.fn(),
+ useTopicRunEvents: vi.fn(),
+}));
+
+const marker = vi.hoisted(() => ({
+ assistantMessageId: 'msg_1',
+ heteroType: 'claude-code',
+ operationId: 'op_live',
+}));
+
+vi.mock('@/hooks/useGatewayReconnect', () => ({ useGatewayReconnect: hooks.useGatewayReconnect }));
+vi.mock('@/hooks/useTopicRunEvents', () => ({ useTopicRunEvents: hooks.useTopicRunEvents }));
+vi.mock('@/hooks/useOperationState', () => ({ useOperationState: () => ({}) }));
+
+vi.mock('@/features/Conversation', () => ({
+ ConversationProvider: ({ children }: { children: unknown }) => children,
+}));
+
+vi.mock('@/store/agent', () => {
+ const state = { activeAgentId: 'agt_goal', setActiveAgentId: vi.fn() };
+ const useAgentStore = (selector: (s: typeof state) => unknown) => selector(state);
+ useAgentStore.getState = () => state;
+ return { useAgentStore };
+});
+
+const chat = vi.hoisted(() => ({
+ state: {} as {
+ activeAgentId: string;
+ activeTopicId: string;
+ switchTopic: ReturnType<typeof vi.fn>;
+ topicDataMap: Record<string, { items: any[] }>;
+ },
+}));
+
+vi.mock('@/store/chat', () => {
+ const useChatStore = (selector: (s: typeof chat.state) => unknown) => selector(chat.state);
+ useChatStore.getState = () => chat.state;
+ useChatStore.setState = vi.fn();
+ return { useChatStore };
+});
+
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: {
+ getTopicById: (id: string) => (s: any) =>
+ Object.values(s.topicDataMap as Record<string, { items: any[] }>)
+ .flatMap((bucket) => bucket.items)
+ .find((topic) => topic.id === id),
+ },
+}));
+
+beforeEach(() => {
+ hooks.useGatewayReconnect.mockReset();
+ hooks.useTopicRunEvents.mockReset();
+ chat.state = {
+ activeAgentId: 'agt_goal',
+ activeTopicId: 'tpc_goal',
+ switchTopic: vi.fn(),
+ topicDataMap: {
+ agent_agt_goal: { items: [{ id: 'tpc_goal', metadata: { runningOperation: marker } }] },
+ agent_agt_other: {
+ items: [{ id: 'tpc_other', metadata: { runningOperation: { operationId: 'op_other' } } }],
+ },
+ },
+ };
+});
+
+describe('GoalChatProvider', () => {
+ // ROOT CAUSE (T-13930):
+ //
+ // The goal page's supervision conversation never followed a run already going
+ // on its topic. Opened after a reload or in a new window, it had no local
+ // operation for a Claude Code run still waiting on a background task, so the
+ // composer read idle; the next message started a second run, the live CLI's
+ // output was discarded as stale and the CLI stopped, killing that task.
+ //
+ // Before: no reconnect on this surface. After: it reconnects like the agent page.
+ it('follows the run still going on its topic', () => {
+ render(
+ <GoalChatProvider pinned agentId="agt_goal" goalId="goal_1" initialTopicId="tpc_goal">
+ <div />
+ </GoalChatProvider>,
+ );
+
+ expect(hooks.useGatewayReconnect).toHaveBeenCalledWith('tpc_goal', marker, 'agt_goal');
+ expect(hooks.useTopicRunEvents).toHaveBeenCalledWith('tpc_goal', 'agt_goal');
+ });
+
+ // Until the panel's switch lands, the store still names whatever was open
+ // before; its run must not be followed under the goal agent.
+ it('does not follow the previous conversation before the switch lands', () => {
+ chat.state.activeAgentId = 'agt_other';
+ chat.state.activeTopicId = 'tpc_other';
+
+ render(
+ <GoalChatProvider pinned agentId="agt_goal" goalId="goal_1" initialTopicId="tpc_goal">
+ <div />
+ </GoalChatProvider>,
+ );
+
+ for (const [topicId] of hooks.useGatewayReconnect.mock.calls) expect(topicId).toBeUndefined();
+ for (const [topicId] of hooks.useTopicRunEvents.mock.calls) expect(topicId).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentGoals/GoalChat/GoalChatProvider.tsx b/src/features/AgentGoals/GoalChat/GoalChatProvider.tsx
index 349868b27e4..21b750f36f3 100644
--- a/src/features/AgentGoals/GoalChat/GoalChatProvider.tsx
+++ b/src/features/AgentGoals/GoalChat/GoalChatProvider.tsx
@@ -4,9 +4,12 @@ import { memo, useEffect, useMemo, useState } from 'react';
import { PinnedTopicContext } from '@/features/ChatInput/InputEditor/ReferTopic/pinnedTopic';
import { ConversationProvider } from '@/features/Conversation';
+import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
import { useOperationState } from '@/hooks/useOperationState';
+import { useTopicRunEvents } from '@/hooks/useTopicRunEvents';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
interface GoalChatProviderProps {
/** The goal's responsible agent β€” the one the user asks about progress. */
@@ -32,6 +35,7 @@ export const GoalChatProvider = memo<GoalChatProviderProps>(
const [initialized, setInitialized] = useState(false);
const setActiveAgentId = useAgentStore((s) => s.setActiveAgentId);
const activeTopicId = useChatStore((s) => s.activeTopicId);
+ const activeChatAgentId = useChatStore((s) => s.activeAgentId);
useEffect(() => {
if (!agentId) return;
@@ -67,6 +71,27 @@ export const GoalChatProvider = memo<GoalChatProviderProps>(
const operationState = useOperationState(context);
+ // Follow a run still going on this topic, as the agent page does: a page
+ // that opens here after a reload or in a new window has no local operation
+ // for it, so without this the composer reads idle and the next message
+ // starts a second run that discards the live one (and kills its CLI).
+ // Only once the store points at this panel's conversation: until the
+ // switch above lands, `activeTopicId` is whatever was open before, and its
+ // run would be followed under this panel's agent.
+ const followedTopicId =
+ initialized &&
+ activeChatAgentId === agentId &&
+ (!initialTopicId || activeTopicId === initialTopicId)
+ ? activeTopicId
+ : undefined;
+ const runningOperation = useChatStore((s) =>
+ followedTopicId
+ ? topicSelectors.getTopicById(followedTopicId)(s)?.metadata?.runningOperation
+ : undefined,
+ );
+ useGatewayReconnect(followedTopicId, runningOperation, agentId);
+ useTopicRunEvents(followedTopicId, agentId);
+
if (!initialized) return null;
return (
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.serverSteerQueue.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.serverSteerQueue.test.ts
index 6ea3e01d45b..a7e8b2f2634 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.serverSteerQueue.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.serverSteerQueue.test.ts
@@ -6,8 +6,10 @@ import { aiAgentService } from '@/services/aiAgent';
import { getSessionStoreState } from '@/store/session';
import { useUserStore } from '@/store/user';
+import { topicSelectors } from '../../../../selectors';
import { useChatStore } from '../../../../store';
import { messageMapKey } from '../../../../utils/messageMapKey';
+import { resetReleasedMarkers } from '../transports/gateway/untrackedHeteroRun';
import { createMockAgentConfig, TEST_IDS } from './fixtures';
import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';
@@ -216,3 +218,94 @@ describe('sendMessage behind a running Gateway run', () => {
]);
});
});
+
+// ROOT CAUSE (T-13930):
+//
+// The gateway ends the local operation of a Claude Code run on a transport
+// signal alone (a terminal resume status after a quiet socket), while the
+// server keeps the topic marker because the CLI is still working β€” e.g. waiting
+// on a background download. The composer then looked idle, and the next message
+// started a second run: the topic moved to it, the live CLI's output was
+// discarded as stale, and the CLI stopped its agent and the background work.
+//
+// Before: no local operation β†’ a fresh send, next to the live run.
+// After: the send is queued on the server, which types it into the live session.
+describe('sendMessage while the topic names a hetero run this tab no longer follows', () => {
+ const marker = {
+ assistantMessageId: 'msg-assistant',
+ heteroType: 'claude-code',
+ operationId: 'op-hetero-live',
+ };
+
+ beforeEach(() => {
+ act(() => {
+ useChatStore.setState({
+ operations: {},
+ operationsByContext: {},
+ reconnectToGatewayOperation: vi.fn().mockResolvedValue(undefined),
+ });
+ });
+ vi.spyOn(topicSelectors, 'getTopicById').mockReturnValue(
+ () => ({ id: TEST_IDS.TOPIC_ID, metadata: { runningOperation: marker } }) as any,
+ );
+ });
+
+ afterEach(() => {
+ resetReleasedMarkers();
+ });
+
+ it('steers the live run through the server queue and re-attaches its stream', async () => {
+ const append = vi
+ .spyOn(aiAgentService, 'appendQueuedFollowUp')
+ .mockResolvedValue({ id: 'x', length: 1, queued: true });
+ const { result } = renderHook(() => useChatStore());
+
+ await act(async () => {
+ await result.current.sendMessage({ context, message: 'ζ€ŽδΉˆζ ·δΊ†' });
+ });
+
+ await vi.waitFor(() => expect(append).toHaveBeenCalled());
+ expect(append.mock.calls[0][0].request).toMatchObject({ prompt: 'ζ€ŽδΉˆζ ·δΊ†' });
+ expect(result.current.executeGatewayAgent).not.toHaveBeenCalled();
+ await vi.waitFor(() =>
+ expect(result.current.reconnectToGatewayOperation).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: 'op-hetero-live', topicId: TEST_IDS.TOPIC_ID }),
+ ),
+ );
+ });
+
+ // `full` / `unavailable` used to bounce: the fallback re-entered the send,
+ // which queued behind the same marker again every 100ms, never sending.
+ it.each(['idle', 'full', 'unavailable'])(
+ 'sends fresh once the server does not take the follow-up (%s)',
+ async (reason) => {
+ vi.useFakeTimers();
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ queued: false,
+ reason,
+ } as any);
+ const sendQueued = vi.fn().mockResolvedValue(undefined);
+ const { result } = renderHook(() => useChatStore());
+ const original = result.current.sendMessage;
+
+ await act(async () => {
+ await original({ context, message: 'hello' });
+ });
+ useChatStore.setState({ sendMessage: sendQueued });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(200);
+ });
+ vi.useRealTimers();
+
+ // The client sends it itself; a re-entry no longer queues behind the stale marker.
+ expect(sendQueued).toHaveBeenCalledWith(expect.objectContaining({ message: 'hello' }));
+ // No local reconnect op was started that could block that send.
+ expect(useChatStore.getState().reconnectToGatewayOperation).not.toHaveBeenCalled();
+ useChatStore.setState({ sendMessage: original });
+ await act(async () => {
+ await useChatStore.getState().sendMessage({ context, message: 'again' });
+ });
+ expect(useChatStore.getState().executeGatewayAgent).toHaveBeenCalled();
+ },
+ );
+});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.externalProducerSettle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.externalProducerSettle.test.ts
index 369e47ad719..7813dda0fad 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.externalProducerSettle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.externalProducerSettle.test.ts
@@ -8,9 +8,11 @@ import type { GatewayConnection } from '../transports/gateway/gateway';
import { GatewayActionImpl } from '../transports/gateway/gateway';
const reclaimServerQueuedMessages = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+const resumeClientHeldQueue = vi.hoisted(() => vi.fn());
vi.mock('../transports/gateway/serverSteerQueue', () => ({
restoreServerQueuedMessages: vi.fn(),
reclaimServerQueuedMessages,
+ resumeClientHeldQueue,
withdrawQueuedMessage: vi.fn(),
}));
@@ -305,6 +307,25 @@ describe('external producer session ending without its terminal', () => {
expect(topicService.settleRunningOperation).not.toHaveBeenCalled();
});
+ // This path completes the local op without the run lifecycle's queue drain:
+ // a follow-up handed back to this client (e.g. a refused unconfirmed append)
+ // would wait for the next send unless it is resumed here.
+ it('resumes what waits in this conversation behind the run', async () => {
+ resumeClientHeldQueue.mockClear();
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ id: 'topic-1',
+ metadata: { runningOperation: { operationId: 'server-op' } },
+ status: 'running',
+ } as any);
+
+ await endExternalRunWithoutTerminal();
+
+ expect(resumeClientHeldQueue).toHaveBeenCalledWith(
+ expect.any(Function),
+ expect.objectContaining({ agentId: 'agent-1', topicId: 'topic-1' }),
+ );
+ });
+
it('keeps the row running when the server row cannot be read', async () => {
vi.mocked(topicService.getTopicDetail).mockRejectedValue(new Error('offline'));
vi.spyOn(console, 'error').mockImplementation(() => {});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
index 4394d110c1c..add96592eaa 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
@@ -93,11 +93,12 @@ import {
handOffQueuedMessage,
reclaimServerQueuedMessages,
} from '@/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue';
+import { findUntrackedHeteroMarker } from '@/store/chat/slices/agentRun/actions/transports/gateway/untrackedHeteroRun';
import {
getNativeHeteroSessionBindingKey,
resolveHeteroResume,
} from '@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume';
-import { isQueueBlockingOperation, snapshotQueuedFiles } from '@/store/chat/slices/operation/types';
+import { snapshotQueuedFiles } from '@/store/chat/slices/operation/types';
import { PortalViewType } from '@/store/chat/slices/portal/initialState';
import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';
import { topicListFilterOf } from '@/store/chat/slices/topic/projection';
@@ -141,6 +142,7 @@ import { pageConversationNeedsGateway, preparePageConversation } from '../pageCo
import { mergePartialPersistedMessages, resolveSendResponseMessages } from '../persistedMessages';
import { resolveExistingTopicForRun } from '../resolveExistingTopic';
import { type ContextCompressionOptions, executeContextCompression } from './compression';
+import { findRunningBlockingOp } from './queueBlockingOp';
import { resolveRunCwd, resolveSendProjectRun, type SourceTopicDirectory } from './runCwd';
import { showSendErrorInContext } from './sendErrorNotice';
@@ -658,42 +660,10 @@ export class ConversationLifecycleActionImpl {
].filter((key) => key !== currentContextKey)
: []),
];
- const findRunningBlockingOp = (key: string) => {
- const contextOpIds = this.#get().operationsByContext[key] || [];
- const hasQueuedMessages = (this.#get().queuedMessages[key]?.length ?? 0) > 0;
- const ownVoiceUploadIndex = optimisticUserMessageId
- ? contextOpIds.findIndex((id) => {
- const operation = this.#get().operations[id];
- return (
- operation?.type === 'uploadVoiceMessage' &&
- operation.context.messageId === optimisticUserMessageId
- );
- })
- : -1;
-
- return contextOpIds
- .map((id, index) => ({ index, operation: this.#get().operations[id] }))
- .find(
- ({ index, operation }) =>
- operation &&
- // Shared predicate β€” an op the composer already treats as finished
- // (aborting, or done with its visible output) must NOT swallow this
- // send into the tray.
- isQueueBlockingOperation(operation, { hasQueuedMessages }) &&
- // The upload transaction calls this lifecycle after its own binary is ready. It must
- // not queue behind itself (or a later voice upload); earlier voice uploads still block.
- !(
- optimisticUserMessageId &&
- operation.type === 'uploadVoiceMessage' &&
- (operation.context.messageId === optimisticUserMessageId ||
- (ownVoiceUploadIndex >= 0 && index > ownVoiceUploadIndex))
- ),
- )?.operation;
- };
let queueTargetKey = currentContextKey;
let runningQueueBlockingOp: ReturnType<typeof findRunningBlockingOp>;
for (const key of queueCandidateKeys) {
- runningQueueBlockingOp = findRunningBlockingOp(key);
+ runningQueueBlockingOp = findRunningBlockingOp(this.#get, key, optimisticUserMessageId);
if (runningQueueBlockingOp) {
queueTargetKey = key;
break;
@@ -703,15 +673,16 @@ export class ConversationLifecycleActionImpl {
!runningQueueBlockingOp &&
!onlyAddUserMessage &&
operationSelectors.isQueueDrainPending(operationContext)(this.#get());
+ const canQueue = (key: string) =>
+ !onlyAddUserMessage &&
+ canQueueOnServer(this.#get, key, {
+ context: operationContext,
+ isGatewayRun: runtimeType === 'gateway' && !directMentionRoute && !willCreateNewTopic,
+ });
/** Queue this send behind what holds `key`; on the server when the run can join it there. */
const queueThisSend = (key: string) => {
const queuedId = nanoid();
- const queueOnServer =
- !onlyAddUserMessage &&
- canQueueOnServer(this.#get, key, {
- context: operationContext,
- isGatewayRun: runtimeType === 'gateway' && !directMentionRoute && !willCreateNewTopic,
- });
+ const queueOnServer = canQueue(key);
this.#get().enqueueMessage(
key,
{
@@ -744,7 +715,11 @@ export class ConversationLifecycleActionImpl {
);
notifyMessageAccepted();
};
- if (runningQueueBlockingOp || queueDrainPending) return void queueThisSend(queueTargetKey);
+ // A live hetero run this tab lost track of takes the send as a steer, never a parallel run.
+ const untrackedHetero =
+ canQueue(currentContextKey) && !!findUntrackedHeteroMarker(this.#get, operationContext);
+ if (runningQueueBlockingOp || queueDrainPending || untrackedHetero)
+ return void queueThisSend(queueTargetKey);
// Nothing runs: take server-queued follow-ups back; one still being delivered keeps its place.
await Promise.all(queueCandidateKeys.map((key) => reclaimServerQueuedMessages(this.#get, key)));
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/queueBlockingOp.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/queueBlockingOp.ts
new file mode 100644
index 00000000000..8126a47674b
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/queueBlockingOp.ts
@@ -0,0 +1,44 @@
+import { isQueueBlockingOperation } from '@/store/chat/slices/operation/types';
+import { type ChatStore } from '@/store/chat/store';
+
+/**
+ * The operation in `key` a fresh send must queue behind, if any.
+ *
+ * `optimisticUserMessageId` is the voice message whose upload transaction is
+ * sending: it must not queue behind its own upload (or a later voice upload);
+ * earlier voice uploads still block.
+ */
+export const findRunningBlockingOp = (
+ get: () => ChatStore,
+ key: string,
+ optimisticUserMessageId?: string,
+) => {
+ const contextOpIds = get().operationsByContext[key] || [];
+ const hasQueuedMessages = (get().queuedMessages[key]?.length ?? 0) > 0;
+ const ownVoiceUploadIndex = optimisticUserMessageId
+ ? contextOpIds.findIndex((id) => {
+ const operation = get().operations[id];
+ return (
+ operation?.type === 'uploadVoiceMessage' &&
+ operation.context.messageId === optimisticUserMessageId
+ );
+ })
+ : -1;
+
+ return contextOpIds
+ .map((id, index) => ({ index, operation: get().operations[id] }))
+ .find(
+ ({ index, operation }) =>
+ operation &&
+ // Shared predicate β€” an op the composer already treats as finished
+ // (aborting, or done with its visible output) must NOT swallow this
+ // send into the tray.
+ isQueueBlockingOperation(operation, { hasQueuedMessages }) &&
+ !(
+ optimisticUserMessageId &&
+ operation.type === 'uploadVoiceMessage' &&
+ (operation.context.messageId === optimisticUserMessageId ||
+ (ownVoiceUploadIndex >= 0 && index > ownVoiceUploadIndex))
+ ),
+ )?.operation;
+};
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index ae077502b0f..ccf66f47c84 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -1567,9 +1567,8 @@ export class GatewayActionImpl {
topicId: result.topicId,
}),
onSessionComplete: ({ authFailed, completion, succeeded, terminalReceived }) => {
- // The gateway event handler already completed the op via the shared run
- // lifecycle on `agent_runtime_end` / `error`. Only complete here as the
- // terminal-missing fallback so the op never sticks `running`.
+ // The shared run lifecycle completes the op on `agent_runtime_end` / `error`;
+ // this is the terminal-missing fallback so the op never sticks `running`.
if (!terminalReceived) this.#get().completeOperation(gatewayOpId);
// An external hetero producer does not run on this socket: the CLI
@@ -1952,8 +1951,7 @@ export class GatewayActionImpl {
// the preserved external producer case below) must close it here.
if (!terminalReceived) this.#get().completeOperation(gatewayOpId);
- // An external producer never streamed over this socket: no transport
- // signal proves it ended β€” see the same guard in `executeGatewayAgent`.
+ // External producer: no transport signal proves it ended (see `executeGatewayAgent`).
if (!terminalReceived && heteroType !== null) {
const { agentId } = context;
if (!agentShareId) this.#retireExternalRow({ agentId, operationId, topicId });
@@ -2519,18 +2517,20 @@ export class GatewayActionImpl {
.catch(console.error);
};
- /** See {@link retireLocalRowIfServerSettled}. */
+ /** See {@link retireLocalRowIfServerSettled}; what waited here behind the run goes next. */
#retireExternalRow = (params: {
agentId?: string;
groupId?: string;
operationId: string;
topicId: string;
- }) =>
+ }) => {
void retireLocalRowIfServerSettled({
clear: (status) => this.clearLocalRunningOperation({ ...params, status }),
isViewing: () => this.#get().activeTopicId === params.topicId,
readTopic: () => topicService.getTopicDetail(params.topicId),
});
+ if (!params.groupId) serverSteerQueue.resumeClientHeldQueue(this.#get, params);
+ };
/**
* @returns Whether a terminal status was written without a local marker β€” the
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.test.ts
index e71f569226e..85ed01f030f 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.test.ts
@@ -12,10 +12,12 @@ import {
handOffQueuedMessage,
reclaimServerQueuedMessages,
restoreServerQueuedMessages,
+ resumeClientHeldQueue,
SERVER_QUEUE_POLL_MS,
watchServerQueue,
withdrawQueuedMessage,
} from './serverSteerQueue';
+import { findUntrackedHeteroMarker, resetReleasedMarkers } from './untrackedHeteroRun';
const context = { agentId: 'agt-1', topicId: 'tpc-1' };
const key = messageMapKey(context);
@@ -48,6 +50,7 @@ beforeEach(() => {
});
afterEach(async () => {
+ resetReleasedMarkers();
// An emptied tray ends any watch a test left running.
useChatStore.setState(useChatStore.getInitialState());
await vi.runOnlyPendingTimersAsync();
@@ -554,6 +557,145 @@ describe('server queue watch after the run ended without taking them', () => {
});
});
+describe('server queue watch behind a hetero run this tab no longer follows', () => {
+ const marker = {
+ assistantMessageId: 'msg-1',
+ heteroType: 'claude-code',
+ operationId: 'op-hetero',
+ };
+
+ beforeEach(() => {
+ useChatStore.setState({ reconnectToGatewayOperation: vi.fn().mockResolvedValue(undefined) });
+ get().internal_dispatchTopic({
+ type: 'addTopic',
+ value: { id: 'tpc-1', metadata: { runningOperation: marker }, title: 't' } as any,
+ });
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ id: 'q1',
+ length: 1,
+ queued: true,
+ });
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps').mockResolvedValue([
+ pending('q1', { createdAt: 1, prompt: 'q1' }),
+ ]);
+ });
+
+ // The run failed or its CLI was killed: no stream tells this tab, and a failed
+ // run leaves its queue to the user.
+ it('takes them back once the server no longer names the run', async () => {
+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue({
+ id: 'tpc-1',
+ metadata: { runningOperation: null },
+ } as any);
+ const remove = vi
+ .spyOn(aiAgentService, 'removeQueuedFollowUp')
+ .mockResolvedValue({ removed: true, state: 'removed' });
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 45);
+
+ expect(remove).toHaveBeenCalledWith({ id: 'q1', threadId: null, topicId: 'tpc-1' });
+ expect(queue()[0].serverDelivery).toBeUndefined();
+ });
+
+ // The answer is about the run the follow-up was handed off behind; a run
+ // another client started meanwhile was never checked and stays held.
+ it('releases only the marker it was handed off behind', async () => {
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockImplementation(async () => {
+ const newer = { ...marker, operationId: 'op-newer' };
+ get().internal_dispatchTopic({
+ id: 'tpc-1',
+ type: 'updateTopic',
+ value: { metadata: { runningOperation: newer } } as any,
+ });
+ return { queued: false, reason: 'idle' } as any;
+ });
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+
+ expect(findUntrackedHeteroMarker(get, context)?.operationId).toBe('op-newer');
+ });
+
+ // An unknown append outcome turned the follow-up `serverUnconfirmed`; when
+ // the same-id retry is refused, the marker it was held behind is released
+ // too, or its local resend would queue behind the same run again.
+ it('releases the marker when an unconfirmed follow-up is refused later', async () => {
+ const append = vi
+ .spyOn(aiAgentService, 'appendQueuedFollowUp')
+ .mockRejectedValueOnce(new Error('network'))
+ .mockResolvedValue({ queued: false, reason: 'full' } as any);
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps').mockResolvedValue([]);
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+ expect(queue()[0]).toMatchObject({ serverDelivery: 'server', serverUnconfirmed: true });
+ expect(findUntrackedHeteroMarker(get, context)?.operationId).toBe('op-hetero');
+
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 2);
+
+ expect(append).toHaveBeenCalledTimes(2);
+ expect(findUntrackedHeteroMarker(get, context)).toBeUndefined();
+ });
+
+ it('keeps holding them while the server still names the run', async () => {
+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue({
+ id: 'tpc-1',
+ metadata: { runningOperation: marker },
+ } as any);
+ const remove = vi.spyOn(aiAgentService, 'removeQueuedFollowUp');
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 45);
+
+ expect(remove).not.toHaveBeenCalled();
+ expect(queue()[0].serverDelivery).toBe('server');
+ expect(get().reconnectToGatewayOperation).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: 'op-hetero', topicId: 'tpc-1' }),
+ );
+ });
+});
+
+describe('resumeClientHeldQueue', () => {
+ it('hands a queueable follow-up back to the server', async () => {
+ const append = vi
+ .spyOn(aiAgentService, 'appendQueuedFollowUp')
+ .mockResolvedValue({ id: 'q1', length: 1, queued: true });
+ get().enqueueMessage(key, queued('q1', { serverRequest: request }));
+
+ resumeClientHeldQueue(get, context);
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(append).toHaveBeenCalledWith(expect.objectContaining({ id: 'q1', request }));
+ expect(queue()[0].serverDelivery).toBe('server');
+ });
+
+ it('sends the rest once nothing runs here', async () => {
+ const sendMessage = vi.fn().mockResolvedValue(undefined);
+ useChatStore.setState({ sendMessage });
+ get().enqueueMessage(key, queued('q1'));
+
+ resumeClientHeldQueue(get, context);
+ await vi.advanceTimersByTimeAsync(200);
+
+ expect(sendMessage).toHaveBeenCalledWith(expect.objectContaining({ message: 'q1' }));
+ });
+
+ it('leaves them to a run still going here', async () => {
+ const sendMessage = vi.fn().mockResolvedValue(undefined);
+ useChatStore.setState({ sendMessage });
+ startRun();
+ get().enqueueMessage(key, queued('q1'));
+
+ resumeClientHeldQueue(get, context);
+ await vi.advanceTimersByTimeAsync(200);
+
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+});
+
describe('restoreServerQueuedMessages', () => {
// ROOT CAUSE:
//
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.ts
index a673cd6a4fb..5047b2358d5 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.ts
@@ -15,6 +15,12 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { isTrpcErrorCode } from '@/utils/trpcError';
import { scheduleQueuedFollowUp } from '../../lifecycle/queuedFollowUp';
+import {
+ findUntrackedHeteroMarker,
+ reattachUntrackedHeteroRun,
+ refreshUntrackedHeteroMarker,
+ releaseUntrackedMarker,
+} from './untrackedHeteroRun';
const log = debug('lobe-store:server-steer-queue');
@@ -171,6 +177,14 @@ export const handOffQueuedMessage = (
sendIfIdle(get, contextKey, context);
};
+ // The untracked hetero run this send is held behind, if any: a follow-up
+ // the server does not take must not be held behind it again.
+ const heldMarkerId = findUntrackedHeteroMarker(get, context)?.operationId;
+ const giveUp = (reason: string) => {
+ releaseUntrackedMarker(heldMarkerId, reason);
+ keepHere();
+ };
+
const queue = queueOf(get, contextKey);
const index = queue.findIndex((message) => message.id === id);
if (index < 0) return;
@@ -186,13 +200,19 @@ export const handOffQueuedMessage = (
console.error('[serverSteerQueue] building the queued request failed:', error);
}
}
- if (!request) return keepHere();
+ if (!request) return giveUp('request-unavailable');
- get().updateQueuedMessage(contextKey, id, { serverDelivery: 'appending' });
+ get().updateQueuedMessage(contextKey, id, {
+ heldBehindOperationId: heldMarkerId,
+ serverDelivery: 'appending',
+ });
let queued = false;
let unconfirmed = false;
+ let refusal: string | undefined;
try {
- queued = (await appendWithRetry(id, request, findQueued(get, contextKey, id))).queued;
+ const result = await appendWithRetry(id, request, findQueued(get, contextKey, id));
+ queued = result.queued;
+ if (!result.queued) refusal = result.reason;
} catch (error) {
console.error('[serverSteerQueue] queueing on the server failed:', error);
// Unless refused outright it may have been stored, and sending it from
@@ -207,7 +227,7 @@ export const handOffQueuedMessage = (
await aiAgentService.removeQueuedFollowUp({ ...surfaceOf(request), id }).catch(() => {});
return;
}
- if (!queued && !unconfirmed) return keepHere();
+ if (!queued && !unconfirmed) return giveUp(refusal ?? 'rejected');
log('[%s] %s queued on the server%s', contextKey, id, unconfirmed ? ' (unconfirmed)' : '');
get().updateQueuedMessage(contextKey, id, {
@@ -215,6 +235,7 @@ export const handOffQueuedMessage = (
serverUnconfirmed: unconfirmed || undefined,
});
watchServerQueue(get, contextKey, context);
+ reattachUntrackedHeteroRun(get, context);
};
const previous = handOffChains.get(contextKey) ?? Promise.resolve();
@@ -273,6 +294,8 @@ const onServerQueueDelivered = async (
while (hasLocalRun(get, context) && Date.now() < settleBy)
await new Promise((resolve) => setTimeout(resolve, SERVER_QUEUE_POLL_MS));
if (!hasLocalRun(get, context)) await syncQueuedSuccessorRun(get, context);
+ // Typed into a live hetero run this tab no longer follows: follow its reply.
+ if (!hasLocalRun(get, context)) reattachUntrackedHeteroRun(get, context);
// Queued here behind the delivered ones: the server can take them now.
const left = queueOf(get, contextKey).filter(
@@ -282,6 +305,29 @@ const onServerQueueDelivered = async (
for (const message of left) void handOffQueuedMessage(get, contextKey, context, message.id);
};
+/**
+ * Send what waits here behind a heterogeneous run whose stream ended without
+ * its terminal frame. That path completes the local operation without the
+ * run lifecycle's queue drain, and the watch stops once nothing is held on
+ * the server, so follow-ups handed back to this client would otherwise wait
+ * for the next send. Ones that were queueable go to the server again β€” still
+ * steered into a live run, or handed back when it is over β€” the rest are sent
+ * once nothing runs here.
+ */
+export const resumeClientHeldQueue = (
+ get: Get,
+ surface: { agentId?: string; topicId: string },
+): void => {
+ if (!surface.agentId) return;
+ const context: ConversationContext = { agentId: surface.agentId, topicId: surface.topicId };
+ const contextKey = messageMapKey(context);
+ const left = queueOf(get, contextKey).filter(
+ (message) => isClientHeldQueuedMessage(message) && message.serverRequest,
+ );
+ if (left.length === 0) return sendIfIdle(get, contextKey, context);
+ for (const message of left) void handOffQueuedMessage(get, contextKey, context, message.id);
+};
+
/**
* An append whose answer was lost and that the server does not list: append
* the same id again, which never stores it twice, and let the answer say where
@@ -311,7 +357,9 @@ const reconcileUnconfirmed = async (
} catch (error) {
if (!isDefiniteRejection(error)) return 'held';
}
- // Not on the server and refused now: only this client holds it.
+ // Not on the server and refused now: only this client holds it, and it must
+ // not be held behind the same untracked run again when it is sent.
+ releaseUntrackedMarker(message.heldBehindOperationId, 'unconfirmed-refused');
get().updateQueuedMessage(contextKey, message.id, {
serverDelivery: undefined,
serverUnconfirmed: undefined,
@@ -330,6 +378,7 @@ export const watchServerQueue = (get: Get, contextKey: string, context: Conversa
if (watchers.has(contextKey)) return;
watchers.add(contextKey);
let ticksWithoutRun = 0;
+ let markerOnlyTicks = 0;
let failures = 0;
const tick = async () => {
@@ -392,7 +441,13 @@ export const watchServerQueue = (get: Get, contextKey: string, context: Conversa
console.error('[serverSteerQueue] reading the server queue failed:', error);
}
- ticksWithoutRun = hasLocalRun(get, context) ? 0 : ticksWithoutRun + 1;
+ // A live hetero run this tab lost track of still takes them (see `findUntrackedHeteroMarker`);
+ // confirm it with the server now and then, since no stream tells this tab it ended.
+ const markerHolds = !hasLocalRun(get, context) && !!findUntrackedHeteroMarker(get, context);
+ if (markerHolds && ++markerOnlyTicks % ORPHANED_QUEUE_TICKS === 0)
+ await refreshUntrackedHeteroMarker(get, context.topicId!);
+ const runHolds = hasLocalRun(get, context) || !!findUntrackedHeteroMarker(get, context);
+ ticksWithoutRun = runHolds ? 0 : ticksWithoutRun + 1;
// Stopped elsewhere: that run starts nothing next, take them back now.
const stopped =
operationSelectors.getIdleQueueHost(context)(get())?.metadata.endedWithoutCompletion;
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/untrackedHeteroRun.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/untrackedHeteroRun.test.ts
new file mode 100644
index 00000000000..395fbdff0d4
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/untrackedHeteroRun.test.ts
@@ -0,0 +1,155 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { topicService } from '@/services/topic';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import {
+ findUntrackedHeteroMarker,
+ reattachUntrackedHeteroRun,
+ refreshUntrackedHeteroMarker,
+ releaseUntrackedMarker,
+ resetReleasedMarkers,
+} from './untrackedHeteroRun';
+
+const context = { agentId: 'agt-1', threadId: null, topicId: 'tpc-1' };
+
+const makeGet = (params: { heteroType?: string | null; operations?: Record<string, any> }) => {
+ const reconnectToGatewayOperation = vi.fn().mockResolvedValue(undefined);
+ vi.spyOn(topicSelectors, 'getTopicById').mockReturnValue(
+ () =>
+ ({
+ id: 'tpc-1',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'msg-1',
+ heteroType: params.heteroType,
+ operationId: `op-${params.heteroType}`,
+ },
+ },
+ }) as any,
+ );
+ const state = { operations: params.operations ?? {}, reconnectToGatewayOperation };
+ return { get: () => state as any, reconnectToGatewayOperation };
+};
+
+afterEach(() => {
+ resetReleasedMarkers();
+ vi.restoreAllMocks();
+});
+
+describe('findUntrackedHeteroMarker', () => {
+ it('finds a hetero marker no local operation follows, without side effects', () => {
+ const { get, reconnectToGatewayOperation } = makeGet({ heteroType: 'claude-code' });
+
+ expect(findUntrackedHeteroMarker(get, context)?.operationId).toBe('op-claude-code');
+ expect(reconnectToGatewayOperation).not.toHaveBeenCalled();
+ });
+
+ it('leaves a run this tab follows to the composer predicate', () => {
+ const { get } = makeGet({
+ heteroType: 'codex',
+ operations: {
+ local: {
+ metadata: { serverOperationId: 'op-codex', visibleLoadingDone: true },
+ status: 'running',
+ type: 'execServerAgentRuntime',
+ },
+ },
+ });
+
+ expect(findUntrackedHeteroMarker(get, context)).toBeUndefined();
+ });
+
+ it('ignores markers of ordinary server runs and thread conversations', () => {
+ expect(findUntrackedHeteroMarker(makeGet({ heteroType: null }).get, context)).toBeUndefined();
+ const { get } = makeGet({ heteroType: 'claude-code' });
+ expect(findUntrackedHeteroMarker(get, { ...context, threadId: 'thd-1' })).toBeUndefined();
+ });
+
+ it('stops finding a marker once it was released', () => {
+ const { get } = makeGet({ heteroType: 'amp' });
+
+ releaseUntrackedMarker('op-amp', 'idle');
+
+ expect(findUntrackedHeteroMarker(get, context)).toBeUndefined();
+ });
+
+ it('keeps finding a newer marker when an older one was released', () => {
+ const { get } = makeGet({ heteroType: 'codex' });
+
+ releaseUntrackedMarker('op-older', 'idle');
+
+ expect(findUntrackedHeteroMarker(get, context)?.operationId).toBe('op-codex');
+ });
+});
+
+describe('reattachUntrackedHeteroRun', () => {
+ it('reconnects this tab to the untracked run', () => {
+ const { get, reconnectToGatewayOperation } = makeGet({ heteroType: 'claude-code' });
+
+ reattachUntrackedHeteroRun(get, context);
+
+ expect(reconnectToGatewayOperation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agt-1',
+ assistantMessageId: 'msg-1',
+ heteroType: 'claude-code',
+ operationId: 'op-claude-code',
+ topicId: 'tpc-1',
+ }),
+ );
+ });
+
+ it('does nothing for an ordinary server run', () => {
+ const { get, reconnectToGatewayOperation } = makeGet({ heteroType: null });
+
+ reattachUntrackedHeteroRun(get, context);
+
+ expect(reconnectToGatewayOperation).not.toHaveBeenCalled();
+ });
+});
+
+describe('refreshUntrackedHeteroMarker', () => {
+ const topicWith = (operationId: string | null) =>
+ ({
+ id: 'tpc-1',
+ metadata: {
+ runningOperation: operationId ? { operationId, heteroType: 'claude-code' } : null,
+ },
+ }) as any;
+
+ it('takes the server marker when it changed', async () => {
+ let local = topicWith('op-old');
+ vi.spyOn(topicSelectors, 'getTopicById').mockReturnValue(() => local);
+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(topicWith(null));
+ const dispatch = vi.fn((action: any) => {
+ local = { ...local, ...action.value };
+ });
+
+ await refreshUntrackedHeteroMarker(
+ () => ({ internal_dispatchTopic: dispatch }) as any,
+ 'tpc-1',
+ );
+
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ value: { metadata: { runningOperation: null } } }),
+ );
+ });
+
+ it('keeps a newer local marker that landed while the read was in flight', async () => {
+ let local = topicWith('op-old');
+ vi.spyOn(topicSelectors, 'getTopicById').mockReturnValue(() => local);
+ vi.spyOn(topicService, 'getTopicDetail').mockImplementation(async () => {
+ local = topicWith('op-new');
+ return topicWith(null);
+ });
+ const dispatch = vi.fn();
+
+ await refreshUntrackedHeteroMarker(
+ () => ({ internal_dispatchTopic: dispatch }) as any,
+ 'tpc-1',
+ );
+
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/untrackedHeteroRun.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/untrackedHeteroRun.ts
new file mode 100644
index 00000000000..70ccc9221a6
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/untrackedHeteroRun.ts
@@ -0,0 +1,119 @@
+import type { ConversationContext } from '@lobechat/types';
+import debug from 'debug';
+
+import { topicService } from '@/services/topic';
+import { topicSelectors } from '@/store/chat/selectors';
+import type { ChatStore } from '@/store/chat/store';
+
+const log = debug('lobe-store:untracked-hetero-run');
+
+type Get = () => ChatStore;
+
+/**
+ * Markers the server did not take a follow-up behind β€” no live run of ours
+ * (`idle`), a full queue, a failed store, or a request that could not be built.
+ * The queue's fallback re-enters the send, so without this it would queue
+ * behind the same marker again, forever. The next send starts fresh instead.
+ */
+const releasedMarkers = new Set<string>();
+
+/** Test-only: forget the released markers. */
+export const resetReleasedMarkers = () => releasedMarkers.clear();
+
+/**
+ * Stop holding sends behind this marker. Takes the operation id the follow-up
+ * was handed off behind, not the topic's current marker: another client may
+ * have started a newer run meanwhile, and that one was never checked.
+ */
+export const releaseUntrackedMarker = (operationId: string | undefined, reason: string) => {
+ if (!operationId) return;
+ log('releasing untracked marker %s (%s)', operationId, reason);
+ releasedMarkers.add(operationId);
+};
+
+/**
+ * The topic marker of a heterogeneous run (Claude Code / Codex on a device)
+ * that no local operation follows, unless the server already found it over.
+ *
+ * The gateway ends the local operation of such a run on a transport signal
+ * alone (a terminal resume status, a raw `session_complete`, a failed
+ * re-auth), while the server keeps the marker because the CLI may still be
+ * producing. The composer then looks idle; a send that started a fresh run
+ * next to the live one would move the topic to it, so the live CLI's next
+ * batch is discarded as stale and the CLI stops its agent β€” killing whatever
+ * background work it was waiting on. A send behind such a marker is queued on
+ * the server instead: typed into the live session (steer), or handed back
+ * when the server finds the run over.
+ */
+export const findUntrackedHeteroMarker = (get: Get, context: ConversationContext) => {
+ if (!context.topicId || context.threadId) return;
+
+ const marker = topicSelectors.getTopicById(context.topicId)(get())?.metadata?.runningOperation;
+ if (!marker?.heteroType || releasedMarkers.has(marker.operationId)) return;
+
+ // A run this tab follows is judged by the composer's own predicate.
+ const tracked = Object.values(get().operations).some(
+ (operation) =>
+ operation.type === 'execServerAgentRuntime' &&
+ operation.status === 'running' &&
+ operation.metadata.serverOperationId === marker.operationId,
+ );
+ return tracked ? undefined : marker;
+};
+
+/**
+ * Follow the stream of the untracked hetero run a follow-up was just queued
+ * behind, so the steered turn renders live. Only once the server holds the
+ * follow-up: the local operation the reconnect starts would otherwise block
+ * the client's own send of a follow-up the server handed back.
+ */
+export const reattachUntrackedHeteroRun = (get: Get, context: ConversationContext) => {
+ const marker = findUntrackedHeteroMarker(get, context);
+ if (!marker || !context.topicId) return;
+
+ log('re-attaching to untracked hetero run %s on topic %s', marker.operationId, context.topicId);
+ get()
+ .reconnectToGatewayOperation({
+ agentId: context.agentId,
+ assistantMessageId: marker.assistantMessageId,
+ heteroType: marker.heteroType,
+ operationId: marker.operationId,
+ scope: marker.scope,
+ startedAt: marker.startedAt,
+ threadId: marker.threadId,
+ topicId: context.topicId,
+ })
+ .catch((error: unknown) => {
+ console.error('[untrackedHeteroRun] re-attaching to the live run failed:', error);
+ });
+};
+
+/**
+ * Re-read the topic when only an untracked hetero marker keeps follow-ups on
+ * the server: this tab has no stream left to learn the run ended (a failed or
+ * killed CLI never starts them), so the local marker must follow the server's,
+ * or the queue would be held β€” and polled β€” for as long as the page is open.
+ */
+export const refreshUntrackedHeteroMarker = async (get: Get, topicId: string) => {
+ const localMarkerId = (s: ChatStore) =>
+ topicSelectors.getTopicById(topicId)(s)?.metadata?.runningOperation?.operationId;
+ const before = localMarkerId(get());
+ const topic = await topicService.getTopicDetail(topicId).catch(() => undefined);
+ const current = topicSelectors.getTopicById(topicId)(get());
+ if (!topic || !current) return;
+
+ // A newer marker landed while the read was in flight: the response predates
+ // it and must not overwrite it.
+ const localId = current.metadata?.runningOperation?.operationId;
+ if (localId !== before) return;
+
+ const runningOperation = topic.metadata?.runningOperation ?? null;
+ if (runningOperation?.operationId === localId) return;
+
+ log('marker %s on topic %s is gone on the server', localId, topicId);
+ get().internal_dispatchTopic({
+ id: topicId,
+ type: 'updateTopic',
+ value: { metadata: { ...current.metadata, runningOperation } },
+ });
+};
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index d8f055acc8b..0cd6b1a59e6 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -1018,7 +1018,7 @@ export class OperationActionsImpl {
patch: Partial<
Pick<
QueuedMessage,
- 'serverDelivering' | 'serverDelivery' | 'serverRequest' | 'serverUnconfirmed'
+ 'heldBehindOperationId' | 'serverDelivering' | 'serverDelivery' | 'serverRequest' | 'serverUnconfirmed'
>
>,
): void => {
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index 432e8e0de90..e861cf05a94 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -335,6 +335,12 @@ export interface QueuedMessage {
/** Mirrors SendMessageParams.forceRuntime so a queued task-topic follow-up
* keeps its gateway pin when the queue drains. */
forceRuntime?: 'client' | 'gateway' | 'hetero';
+ /**
+ * The untracked heterogeneous run this follow-up was handed to the server
+ * behind. A later refusal releases exactly that run's marker, so the local
+ * fallback send does not queue behind it again.
+ */
+ heldBehindOperationId?: string;
id: string;
interruptMode: 'soft' | 'hard';
metadata?: MessageMetadata;