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(agent): atomically settle completed topic operations (#18696)

Arvin Xuf2982f00f95f
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts
index 677732dcbc9..554fe149d1e 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts
@@ -6,7 +6,7 @@ import { ServerOperationStore } from './ServerOperationStore';
const topicMock = {
findById: vi.fn(),
- takeRunningOperation: vi.fn(),
+ settleRunningOperation: vi.fn(),
};
vi.mock('@/database/models/topic', () => ({
@@ -28,7 +28,7 @@ const markedWith = (operationId: string) => ({
describe('ServerOperationStore', () => {
beforeEach(() => {
vi.clearAllMocks();
- topicMock.takeRunningOperation.mockResolvedValue(undefined);
+ topicMock.settleRunningOperation.mockResolvedValue({ status: 'settled' });
});
describe('clearRunningMark', () => {
@@ -37,7 +37,28 @@ describe('ServerOperationStore', () => {
await createStore('op-main').clearRunningMark();
- expect(topicMock.takeRunningOperation).toHaveBeenCalledWith('topic-1', 'op-main');
+ expect(topicMock.settleRunningOperation).toHaveBeenCalledWith('topic-1', 'op-main', 'unread');
+ });
+
+ // The bug this adapter caused: `finish` calls clearRunningMark BEFORE it
+ // publishes `execution_complete`, and the client only learns the run ended
+ // from that event β€” so the client's own settle always arrived to a mark this
+ // method had already dropped and returned 'missing'. Dropping the mark
+ // without writing a status therefore stranded `topics.status` on 'running'
+ // permanently: the one field a later settle matches on was gone. Observed on
+ // a self-hosted deployment as topics stuck 'running' whose
+ // `metadata.runningOperation` was present-and-JSON-null, operation rows
+ // already terminal, and the topic's last write landing ~100ms BEFORE the
+ // operation was finalised β€” i.e. this very call.
+ it('writes the terminal status with the clear, not just the mark', async () => {
+ topicMock.findById.mockResolvedValue(markedWith('op-main'));
+
+ await createStore('op-main').clearRunningMark();
+
+ // 'unread' is the honest terminal state here: the run finished and nothing
+ // on the server proves the user watched it. The client corrects to
+ // 'active' when it knows better.
+ expect(topicMock.settleRunningOperation).toHaveBeenCalledWith('topic-1', 'op-main', 'unread');
});
it('leaves the mark alone when it belongs to another operation', async () => {
@@ -50,7 +71,7 @@ describe('ServerOperationStore', () => {
await createStore('op-child').clearRunningMark();
- expect(topicMock.takeRunningOperation).not.toHaveBeenCalled();
+ expect(topicMock.settleRunningOperation).not.toHaveBeenCalled();
});
it('is a no-op when the topic carries no mark', async () => {
@@ -58,21 +79,21 @@ describe('ServerOperationStore', () => {
await createStore('op-main').clearRunningMark();
- expect(topicMock.takeRunningOperation).not.toHaveBeenCalled();
+ expect(topicMock.settleRunningOperation).not.toHaveBeenCalled();
});
it('skips the lookup entirely without a topic', async () => {
await createTopiclessStore().clearRunningMark();
expect(topicMock.findById).not.toHaveBeenCalled();
- expect(topicMock.takeRunningOperation).not.toHaveBeenCalled();
+ expect(topicMock.settleRunningOperation).not.toHaveBeenCalled();
});
it('swallows lookup failures β€” clearing the mark is best-effort', async () => {
topicMock.findById.mockRejectedValue(new Error('db down'));
await expect(createStore('op-main').clearRunningMark()).resolves.toBeUndefined();
- expect(topicMock.takeRunningOperation).not.toHaveBeenCalled();
+ expect(topicMock.settleRunningOperation).not.toHaveBeenCalled();
});
it('takes a matching child marker without clearing its parent', async () => {
@@ -87,7 +108,11 @@ describe('ServerOperationStore', () => {
await createStore('op-child').clearRunningMark();
- expect(topicMock.takeRunningOperation).toHaveBeenCalledWith('topic-1', 'op-child');
+ expect(topicMock.settleRunningOperation).toHaveBeenCalledWith(
+ 'topic-1',
+ 'op-child',
+ 'unread',
+ );
});
});
});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts
index e76b9d3cbc5..30f9fa6cca6 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts
@@ -45,7 +45,25 @@ export class ServerOperationStore implements OperationStore {
// No mark (already cleared) or someone else's mark β€” nothing of ours to drop.
if (!markedOperationId || (markedOperationId !== this.operationId && !isChild)) return;
- await topicModel.takeRunningOperation(this.topicId, this.operationId!);
+ // Settle rather than merely take: this clears the mark AND writes the
+ // topic's terminal status in one transaction, under the same row lock.
+ //
+ // Taking it alone left `topics.status` on 'running' with the mark β€” the
+ // only thing a later `settleRunningOperation` can match on β€” already
+ // gone, so no server path could ever correct it. `finish` runs this
+ // BEFORE publishing `execution_complete`, and the client only learns the
+ // run ended from that event, so its own settle always arrived to a
+ // cleared mark and returned 'missing'. The topic then depended entirely
+ // on a fire-and-forget `markTopicUnread`, and when that did not land the
+ // sidebar spun forever. Observed as topics stuck 'running' whose
+ // `metadata.runningOperation` was present-and-JSON-null with their
+ // operation rows already terminal.
+ //
+ // 'unread' is what the server can honestly assert: the run finished and
+ // nothing here proves the user watched it. Only the client knows that, so
+ // it corrects to 'active' on its own β€” with a mark-independent write,
+ // since by then this call has legitimately consumed the mark.
+ await topicModel.settleRunningOperation(this.topicId, this.operationId!, 'unread');
} catch {
// best-effort β€” swallow
}
diff --git a/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts b/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts
index 424037d6f3a..6cdb4277809 100644
--- a/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts
@@ -16,7 +16,7 @@ vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
}));
const mockTopicFindById = vi.fn();
-const mockTopicTakeRunningOperation = vi.fn();
+const mockTopicSettleRunningOperation = vi.fn();
const mockTopicUpdateMetadata = vi.fn();
const mockTopicRemoveRunningOperationChild = vi.fn();
const mockMessageFindById = vi.fn();
@@ -40,7 +40,7 @@ vi.mock('@/database/models/topic', () => ({
TopicModel: vi.fn(() => ({
findById: mockTopicFindById,
removeRunningOperationChild: mockTopicRemoveRunningOperationChild,
- takeRunningOperation: mockTopicTakeRunningOperation,
+ settleRunningOperation: mockTopicSettleRunningOperation,
updateMetadata: mockTopicUpdateMetadata,
})),
}));
@@ -102,8 +102,9 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
},
},
});
- mockTopicTakeRunningOperation.mockResolvedValue({
+ mockTopicSettleRunningOperation.mockResolvedValue({
isRoot: true,
+ status: 'settled',
operation: {
assistantMessageId: FINAL_MSG_ID,
hooks: [{ id: 'task-on-complete', type: 'onComplete', webhook: { url: '/wh' } }],
@@ -147,7 +148,7 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
});
expect(onError).not.toHaveBeenCalled();
- expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, OP);
+ expect(mockTopicSettleRunningOperation).toHaveBeenCalledWith(TOPIC, OP, expect.any(String));
});
it('cancelled terminal signal finalizes the run as interrupted', async () => {
@@ -176,7 +177,7 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
});
expect(onError).not.toHaveBeenCalled();
expect(mockInstantiateVerifyPlan).not.toHaveBeenCalled();
- expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, OP);
+ expect(mockTopicSettleRunningOperation).toHaveBeenCalledWith(TOPIC, OP, expect.any(String));
});
it('uses the marker snapshot read before terminal lifecycle completion', async () => {
@@ -213,7 +214,7 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });
expect(mockPublishAgentRuntimeEnd).not.toHaveBeenCalled();
- expect(mockTopicTakeRunningOperation).not.toHaveBeenCalled();
+ expect(mockTopicSettleRunningOperation).not.toHaveBeenCalled();
await expect(
createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC }),
@@ -221,7 +222,7 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
expect(completeOperationSpy).toHaveBeenCalledTimes(2);
expect(mockPublishAgentRuntimeEnd).toHaveBeenCalledTimes(1);
- expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, OP);
+ expect(mockTopicSettleRunningOperation).toHaveBeenCalledWith(TOPIC, OP, expect.any(String));
completeOperationSpy.mockRestore();
});
@@ -235,8 +236,9 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
metadata: { runningOperation: { operationId: OP, assistantMessageId: FINAL_MSG_ID } },
})
.mockResolvedValueOnce({ agentId: 'agent-1', metadata: { runningOperation: null } });
- mockTopicTakeRunningOperation.mockResolvedValueOnce({
+ mockTopicSettleRunningOperation.mockResolvedValueOnce({
isRoot: true,
+ status: 'settled',
operation: { operationId: OP, assistantMessageId: FINAL_MSG_ID },
});
mockOpFindById.mockResolvedValue({
@@ -268,7 +270,7 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
expect(completeOperationSpy).toHaveBeenCalledTimes(1);
expect(mockPublishAgentRuntimeEnd).toHaveBeenCalledTimes(2);
- expect(mockTopicTakeRunningOperation).toHaveBeenCalledTimes(1);
+ expect(mockTopicSettleRunningOperation).toHaveBeenCalledTimes(1);
completeOperationSpy.mockRestore();
});
@@ -305,7 +307,7 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
await createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC });
- expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, OP);
+ expect(mockTopicSettleRunningOperation).toHaveBeenCalledWith(TOPIC, OP, expect.any(String));
expect(mockInstantiateVerifyPlan).not.toHaveBeenCalled();
});
@@ -346,8 +348,9 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
},
},
});
- mockTopicTakeRunningOperation.mockResolvedValue({
+ mockTopicSettleRunningOperation.mockResolvedValue({
isRoot: false,
+ status: 'settled',
operation: { operationId: childOperationId, orchestrationRole: 'member' },
});
@@ -362,7 +365,11 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
expect(mockPublishAgentRuntimeEnd).toHaveBeenCalledWith(
expect.objectContaining({ operationId: childOperationId, reason: 'success' }),
);
- expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, childOperationId);
+ expect(mockTopicSettleRunningOperation).toHaveBeenCalledWith(
+ TOPIC,
+ childOperationId,
+ expect.any(String),
+ );
expect(completeOperationSpy).toHaveBeenCalledWith(
expect.objectContaining({ operationId: childOperationId, orchestrationRole: 'member' }),
'done',
@@ -388,8 +395,9 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
},
},
});
- mockTopicTakeRunningOperation.mockResolvedValue({
+ mockTopicSettleRunningOperation.mockResolvedValue({
isRoot: false,
+ status: 'settled',
operation: { operationId: childOperationId, orchestrationRole: 'member' },
});
@@ -400,7 +408,11 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
'done',
expect.anything(),
);
- expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, childOperationId);
+ expect(mockTopicSettleRunningOperation).toHaveBeenCalledWith(
+ TOPIC,
+ childOperationId,
+ expect.any(String),
+ );
completeOperationSpy.mockRestore();
});
@@ -422,7 +434,7 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC }),
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
- expect(mockTopicTakeRunningOperation).not.toHaveBeenCalled();
+ expect(mockTopicSettleRunningOperation).not.toHaveBeenCalled();
});
it('ignores a repeated child terminal callback after its marker was removed', async () => {
@@ -448,12 +460,13 @@ describe('agentNotifyRouter.notify β€” remote hetero terminal signal', () => {
},
},
});
- mockTopicTakeRunningOperation
+ mockTopicSettleRunningOperation
.mockResolvedValueOnce({
isRoot: false,
+ status: 'settled',
operation: { operationId: childOperationId, orchestrationRole: 'member' },
})
- .mockResolvedValueOnce(undefined);
+ .mockResolvedValueOnce({ status: 'missing' });
await createCaller().notify({
content: '',
diff --git a/apps/server/src/routers/lambda/agentNotify.ts b/apps/server/src/routers/lambda/agentNotify.ts
index 10c2b8b9d68..8832ce5e78f 100644
--- a/apps/server/src/routers/lambda/agentNotify.ts
+++ b/apps/server/src/routers/lambda/agentNotify.ts
@@ -313,9 +313,18 @@ export const agentNotifyRouter = router({
// Claim the marker before publishing. A retry after a successful
// lifecycle can then publish the missing stream event without firing
// completion hooks a second time.
+ // Settle rather than take, for the same reason as
+ // `ServerOperationStore.clearRunningMark`: dropping the marker on its
+ // own leaves `topics.status` on 'running' with nothing left to match.
+ // `status === 'settled'` carries exactly the claim this used to read
+ // off `takeRunningOperation`'s return.
if (!terminalRetry) {
- const claimed = await ctx.topicModel.takeRunningOperation(topicId, remoteOperationId);
- if (!claimed) return;
+ const settled = await ctx.topicModel.settleRunningOperation(
+ topicId,
+ remoteOperationId,
+ completionReason === 'done' ? 'unread' : 'active',
+ );
+ if (settled.status !== 'settled') return;
}
const streamReason = completionReason === 'done' ? 'success' : completionReason;
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index c18f432e68e..798e527481f 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -846,10 +846,14 @@ export class AiAgentService {
log('finalizeHeteroDispatchError: publishAgentRuntimeEnd failed (non-fatal): %O', err);
}
- // 3. The operation never started β€” drop the running marker so reconnect /
+ // 3. The operation never started β€” settle the topic so reconnect /
// heteroIngest validation and the next turn don't see a stale operation.
+ // Settle, not take: dropping the marker alone would strand `status` on
+ // 'running' with nothing left for any later settle to match β€” see
+ // `ServerOperationStore.clearRunningMark`. 'active' rather than 'unread'
+ // because a dispatch that never started produced nothing to read.
try {
- await this.topicModel.takeRunningOperation(topicId, operationId);
+ await this.topicModel.settleRunningOperation(topicId, operationId, 'active');
} catch (err) {
log('finalizeHeteroDispatchError: clear runningOperation failed (non-fatal): %O', err);
}
diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.ts
index a3121cd89ea..aad527f7fe5 100644
--- a/packages/database/src/models/__tests__/topic.test.ts
+++ b/packages/database/src/models/__tests__/topic.test.ts
@@ -601,10 +601,51 @@ describe('TopicModel', () => {
threadId: 'thread-old',
});
const row = await topicModel.findById(topic.id);
+ expect(row?.metadata?.lastSettledOperationId).toBe('op-old');
expect(row?.metadata?.runningOperation).toBeNull();
expect(row?.status).toBe('unread');
});
+ it('corrects unread to active only for the operation that most recently settled', async () => {
+ const topic = await topicModel.create({
+ metadata: {
+ runningOperation: { assistantMessageId: 'msg-old', operationId: 'op-old' },
+ },
+ title: 'watched completion',
+ });
+ await topicModel.update(topic.id, { status: 'running' });
+
+ await topicModel.settleRunningOperation(topic.id, 'op-old');
+ const corrected = await topicModel.settleRunningOperation(topic.id, 'op-old', 'active');
+
+ expect(corrected.status).toBe('corrected');
+ expect((await topicModel.findById(topic.id))?.status).toBe('active');
+ });
+
+ it('does not let a watched correction from an old operation hide a newer run', async () => {
+ const topic = await topicModel.create({
+ metadata: {
+ runningOperation: { assistantMessageId: 'msg-old', operationId: 'op-old' },
+ },
+ title: 'new run wins',
+ });
+ await topicModel.update(topic.id, { status: 'running' });
+ await topicModel.settleRunningOperation(topic.id, 'op-old');
+ await topicModel.update(topic.id, {
+ metadata: {
+ runningOperation: { assistantMessageId: 'msg-new', operationId: 'op-new' },
+ },
+ status: 'running',
+ });
+
+ const corrected = await topicModel.settleRunningOperation(topic.id, 'op-old', 'active');
+
+ expect(corrected).toEqual({ activeOperationId: 'op-new', status: 'conflict' });
+ const row = await topicModel.findById(topic.id);
+ expect(row?.metadata?.runningOperation?.operationId).toBe('op-new');
+ expect(row?.status).toBe('running');
+ });
+
it('uses the requested terminal status only for the matching operation', async () => {
const topic = await topicModel.create({
metadata: {
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index ecc77e8a59a..2dca5bf492b 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -1350,6 +1350,23 @@ export class TopicModel {
const runningOperation = existing?.metadata?.runningOperation;
if (!runningOperation) {
const currentMessage = existing?.metadata?.heteroCurrentMsgId;
+ if (
+ existing?.metadata?.lastSettledOperationId === operationId &&
+ existing.status === 'unread' &&
+ status === 'active'
+ ) {
+ await tx
+ .update(topics)
+ .set({ status: 'active', updatedAt: new Date() })
+ .where(and(eq(topics.id, id), this.ownership()));
+
+ return {
+ assistantMessageId:
+ currentMessage?.operationId === operationId ? currentMessage.msgId : undefined,
+ status: 'corrected' as const,
+ };
+ }
+
return {
assistantMessageId:
currentMessage?.operationId === operationId ? currentMessage.msgId : undefined,
@@ -1366,6 +1383,7 @@ export class TopicModel {
const metadata = {
...existing.metadata,
+ ...(isRoot ? { lastSettledOperationId: operationId } : {}),
runningOperation: isRoot
? null
: {
diff --git a/packages/types/src/topic/topic.test.ts b/packages/types/src/topic/topic.test.ts
index a4659767dfe..5f67b1c7bf9 100644
--- a/packages/types/src/topic/topic.test.ts
+++ b/packages/types/src/topic/topic.test.ts
@@ -57,6 +57,12 @@ describe('chatTopicMetadataUpdateSchema', () => {
expect(chatTopicMetadataUpdateSchema.parse(metadata)).toEqual(metadata);
});
+ it('preserves the operation-scoped terminal correction marker', () => {
+ const metadata = { lastSettledOperationId: 'operation-1' };
+
+ expect(chatTopicMetadataUpdateSchema.parse(metadata)).toEqual(metadata);
+ });
+
it('rejects a delayed start with no user message β€” the persisted turn IS the prompt', () => {
const result = chatTopicMetadataUpdateSchema.safeParse({
scheduledRun: {
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 312f90ce24b..126f1866b79 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -118,8 +118,6 @@ export interface ChatTopicMetadata {
summarizedAt: string;
version: number;
};
- /** Restored-history tail used as the source message for eval attempt threads. */
- evalHistoryTailMessageId?: string;
bot?: ChatTopicBotContext;
boundDeviceId?: string;
cronJobId?: string;
@@ -145,6 +143,8 @@ export interface ChatTopicMetadata {
* written without it can never be attributed afterwards.
*/
editingGroupId?: string;
+ /** Restored-history tail used as the source message for eval attempt threads. */
+ evalHistoryTailMessageId?: string;
/**
* Scoped pointer to the currently active assistant message for a running
* heterogeneous agent operation. Includes `operationId` so cold-start
@@ -195,6 +195,12 @@ export interface ChatTopicMetadata {
heteroSourceEndAt?: string;
/** origin marker for imported topics, e.g. `claude-code-local` / `codex-local` */
importedFrom?: string;
+ /**
+ * Root operation that most recently consumed `runningOperation`.
+ * Used to scope a post-terminal `unread` β†’ `active` correction when the
+ * watching client receives the terminal event after the server cleared the marker.
+ */
+ lastSettledOperationId?: string;
/**
* Measured dominant model by token volume, written by the usage roll-up
* (`topicUsage.recompute`). This is an analytics projection of "what actually
@@ -506,6 +512,7 @@ export const chatTopicMetadataUpdateSchema = z.object({
})
.optional(),
provider: z.string().optional(),
+ lastSettledOperationId: z.string().optional(),
repos: z.array(z.string()).optional(),
runningOperation: z
.object({
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 54efb039472..dc591ad7990 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -1973,14 +1973,14 @@ describe('GatewayActionImpl', () => {
// Captures the onSessionComplete handed to connectToGateway so we can drive
// both close paths directly. Provides the methods that callback reaches.
- function createOnSessionCompleteHarness() {
+ function createOnSessionCompleteHarness({ activeTopicId = 'topic-1' } = {}) {
const captured: { onSessionComplete?: (p: any) => void } = {};
const completeOperation = vi.fn();
const updateTopicStatus = vi.fn();
const startOperation = vi.fn(() => ({ operationId: 'gw-op-reconnect' }));
const state: Record<string, any> = {
activeAgentId: 'agent-1',
- activeTopicId: 'topic-1',
+ activeTopicId,
gatewayConnections: {},
messagesMap: { 'agent-1_topic-1': [{ createdAt: 1, id: 'ast-1' }] },
topicDataMap: {},
@@ -2052,7 +2052,7 @@ describe('GatewayActionImpl', () => {
topicId: 'topic-1',
});
- vi.mocked(topicService.updateTopicMetadata)
+ vi.mocked(topicService.settleRunningOperation)
.mockClear()
.mockResolvedValue(undefined as never);
captured.onSessionComplete!({ authFailed: false, succeeded: true, terminalReceived: true });
@@ -2060,9 +2060,13 @@ describe('GatewayActionImpl', () => {
// The run lifecycle owns completion when a terminal event arrives, so the
// reconnect path must not double-complete its local op here.
expect(completeOperation).not.toHaveBeenCalled();
- expect(topicService.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {
- runningOperation: null,
- });
+ // Watching the topic, so the terminal status is 'active' β€” written by the
+ // same server call that clears the marker.
+ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(
+ 'topic-1',
+ 'server-op-1',
+ 'active',
+ );
});
// auth_failed (or a failed token refresh) is authoritative that the op is
@@ -2078,15 +2082,61 @@ describe('GatewayActionImpl', () => {
topicId: 'topic-1',
});
- vi.mocked(topicService.updateTopicMetadata)
+ vi.mocked(topicService.settleRunningOperation)
.mockClear()
.mockResolvedValue(undefined as never);
captured.onSessionComplete!({ authFailed: true, succeeded: false, terminalReceived: false });
expect(completeOperation).toHaveBeenCalledWith('gw-op-reconnect');
- expect(topicService.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {
- runningOperation: null,
+ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(
+ 'topic-1',
+ 'server-op-1',
+ 'active',
+ );
+ });
+
+ // The case that stranded 7 topics on a self-hosted deployment: a run that
+ // finishes cleanly while the user is on a DIFFERENT topic.
+ //
+ // This path used to clear `runningOperation` unconditionally via
+ // `updateTopicMetadata` and skip the status write entirely, delegating it to
+ // `markTopicUnread` β€” a separate call on a separate guard. When that one did
+ // not land, the topic kept `status: 'running'` forever AND had already lost
+ // the marker, so every later `settleRunningOperation` returned 'missing' and
+ // no server-side path could repair it. The stuck rows all carried
+ // `metadata.runningOperation` present-and-JSON-null, which is what that
+ // unconditional clear leaves behind.
+ //
+ // Reconnect is the path a page refresh takes β€” hence the symptom always
+ // being "still spinning after a reload".
+ it('settles to unread (not a bare marker clear) when a clean run ends off-topic', async () => {
+ const { action, captured } = createOnSessionCompleteHarness({
+ activeTopicId: 'some-other-topic',
+ });
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
});
+
+ vi.mocked(topicService.settleRunningOperation)
+ .mockClear()
+ .mockResolvedValue(undefined as never);
+ vi.mocked(topicService.updateTopicMetadata)
+ .mockClear()
+ .mockResolvedValue(undefined as never);
+ captured.onSessionComplete!({ authFailed: false, succeeded: true, terminalReceived: true });
+
+ // One atomic server call carries BOTH the marker clear and the terminal
+ // status, under the topic row lock and compared by operation id.
+ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(
+ 'topic-1',
+ 'server-op-1',
+ 'unread',
+ );
+ // ...and never the unguarded two-step that dropped the status.
+ expect(topicService.updateTopicMetadata).not.toHaveBeenCalled();
});
// Seeds a topic whose local metadata still carries a runningOperation, wires up
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 7589502721b..e4c58601a03 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -851,11 +851,16 @@ export class GatewayActionImpl {
// terminal-missing fallback so the op never sticks `running`.
if (!terminalReceived) this.#get().completeOperation(gatewayOpId);
if (result.topicId) {
- // A clean completion the user isn't watching is owned by
- // `markTopicUnread` (status: 'unread'). Every other case (viewing,
- // error, abort) settles the running state back to 'active'. The server
- // compares the operation id under the topic row lock so a late close
- // from another tab cannot clear or settle a newer run.
+ // The server already settled this topic: the runtime's `finish`
+ // executor settles to 'unread' before it publishes the terminal event
+ // this callback rides on, so by now the mark is legitimately gone and
+ // a settle from here would only ever return 'missing'.
+ //
+ // What the server could NOT know is whether the user is watching. The
+ // settle below performs that correction with the completed operation
+ // id: after the marker is gone, the model only accepts unread β†’ active
+ // when `lastSettledOperationId` still matches. It also remains the
+ // backstop when `clearRunningMark` failed and left the marker in place.
const viewing = this.#get().activeTopicId === result.topicId;
topicService
.settleRunningOperation(
@@ -1053,32 +1058,54 @@ export class GatewayActionImpl {
if (authFailed) this.#get().completeOperation(gatewayOpId);
// Same supersede guard as executeGatewayAgent's onSessionComplete: a
- // newer run may own this topic by now, and both writes below are
- // unconditional stomps that would retire it mid-flight.
+ // newer run may own this topic by now, and the settle below would
+ // retire it mid-flight.
const superseded = this.#isSupersededRunningOperation({
agentId: context.agentId,
operationId,
topicId,
});
- // See executeGatewayAgent's onSessionComplete: a clean background
- // completion is left to markTopicUnread (status: 'unread').
+ // Settle through the server exactly as executeGatewayAgent's
+ // onSessionComplete does: ONE call that clears the marker and writes the
+ // terminal status inside the topic row lock, comparing the operation id
+ // so a late close from another tab cannot settle a newer run.
+ //
+ // This was hand-rolled here as two independent fire-and-forget writes: an
+ // UNCONDITIONAL `updateTopicMetadata({ runningOperation: null })` plus an
+ // `updateTopicStatus('active')` that was SKIPPED whenever the run finished
+ // cleanly while the user was on another topic. That case delegated the
+ // status write to `markTopicUnread` β€” a separate call, on a separate
+ // guard β€” and when it did not land the topic stayed `running` forever:
+ // the marker was already gone, so every later `settleRunningOperation`
+ // returned `missing` and nothing on the server could repair it. Observed
+ // on a self-hosted deployment as 7 topics stuck `running` whose
+ // `metadata.runningOperation` was present-and-JSON-null (the signature of
+ // that unconditional clear) with their operation rows already terminal.
+ //
+ // Reconnect is the path a page refresh takes, which is why the symptom
+ // was always "still spinning after a reload" β€” refreshing is what moved
+ // the run off the primary path and onto this one.
const viewing = this.#get().activeTopicId === topicId;
- if (!superseded && (viewing || !succeeded)) {
- void this.#get().updateTopicStatus?.({
- agentId: context.agentId,
- status: 'active',
- topicId,
- });
- }
- // Clear the persisted marker useGatewayReconnect keys off so a dead op
- // doesn't get reconnected on every reload / task-drawer open.
if (!superseded) {
- topicService.updateTopicMetadata(topicId, { runningOperation: null }).catch(() => {});
+ topicService
+ .settleRunningOperation(
+ topicId,
+ operationId,
+ viewing || !succeeded ? 'active' : 'unread',
+ )
+ .catch(console.error);
}
- // Mirror the clear into the local store β€” the server clear above leaves the
- // Zustand topic map stale, which useGatewayReconnect keys off.
- this.clearLocalRunningOperation({ agentId: context.agentId, operationId, topicId });
+ // Mirror into the local store β€” the server settle does NOT touch the
+ // Zustand topic map that useGatewayReconnect (and the sidebar spinner)
+ // read. Status omitted for the unwatched-clean case, which
+ // `markTopicUnread` owns locally; same split as the primary path.
+ this.clearLocalRunningOperation({
+ agentId: context.agentId,
+ operationId,
+ status: viewing || !succeeded ? 'active' : undefined,
+ topicId,
+ });
},
operationId,
resumeOnConnect: true,
@@ -1125,8 +1152,8 @@ export class GatewayActionImpl {
/**
* Clear the client-store copy of `topic.metadata.runningOperation`.
*
- * The server-side clear (`topicService.updateTopicMetadata(topicId, { runningOperation: null })`)
- * alone leaves the Zustand store stale: `useGatewayReconnect` keys off the LOCAL
+ * The server-side clear (`topicService.settleRunningOperation`, which nulls the
+ * marker inside the topic row lock) alone leaves the Zustand store stale: `useGatewayReconnect` keys off the LOCAL
* copy, so after an error run (e.g. insufficient credits) the stale marker keeps
* firing `aiAgentService.refreshGatewayToken(topicId)`, which the server now answers
* with NOT_FOUND (404 β€” the server-side marker is already null). Raw SWR retries the