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(topic): settle a topic when its run ends without a `finish` (#20881)

LiJiane75c50a2ef63
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index a192875524b..fa0e90a7b71 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -1,6 +1,10 @@
import { isParkedStatus } from '@lobechat/agent-runtime';
import { readHeterogeneousErrorContext } from '@lobechat/heterogeneous-agents/errors';
-import { RequestTrigger } from '@lobechat/types';
+import {
+ type AgentOperationStatus,
+ isAgentOperationInFlight,
+ RequestTrigger,
+} from '@lobechat/types';
import { deserializeParts } from '@lobechat/utils';
import { isRecord } from '@lobechat/utils/object';
import debug from 'debug';
@@ -13,6 +17,7 @@ import {
type RecordOperationStartParams,
} from '@/database/models/agentOperation';
import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
import { recomputeTopicUsage } from '@/database/models/topicUsage';
import { VerifyRunModel } from '@/database/models/verifyRun';
import { WorkModel } from '@/database/models/work';
@@ -57,6 +62,21 @@ export const isSuccessLikeCompletionReason = (reason: string): boolean =>
reason === 'cost_limit' ||
reason === 'tool_call_repeat_limit';
+/**
+ * The topic status a finished run leaves behind, mirroring what the client
+ * writes for the same outcome (`executeGatewayAgent`'s `onSessionComplete`) and
+ * what `agentNotify` does for the remote path: only a clean finish is something
+ * the user may not have watched (`unread`); every other ending is an
+ * interruption they already saw (`active`).
+ *
+ * Agrees with the one existing server-side settle, too:
+ * `ServerOperationStore.clearRunningMark` hardcodes `unread`, and it only ever
+ * runs from the `finish` executor β€” the success path, where this helper returns
+ * `unread` as well.
+ */
+const topicStatusForTerminalRun = (status: string): 'active' | 'unread' =>
+ status === 'done' ? 'unread' : 'active';
+
/**
* Triggers whose completion recalls the user with a push notification. Beyond
* plain chat: `Scheduled` is a user-deferred chat turn ("send this in 3
@@ -424,6 +444,12 @@ export class CompletionLifecycle {
return (own ?? 0) + child;
};
+ let completionDurable = false;
+ let conflictingTerminalOwner = false;
+ // The status the durable row actually carries. Usually this callback's own,
+ // but NOT when a terminal owner got there first with a different one β€” see
+ // the fallback below.
+ let durableStatus: AgentOperationStatus = status;
try {
const accepted = await this.agentOperationModel.recordCompletion(operationId, {
completedAt,
@@ -456,16 +482,40 @@ export class CompletionLifecycle {
// the scalar columns β€” the reporting surface β€” carry the whole tree.
usage: state?.usage ?? null,
});
- if (!accepted) {
+ if (accepted) {
+ completionDurable = true;
+ } else {
const operation = await this.agentOperationModel.findById(operationId);
// Preserve the historical best-effort behavior when no durable start
// row exists, but never let a conflicting terminal owner be replaced.
- if (operation) return false;
+ conflictingTerminalOwner = !!operation;
+ // Someone else wrote a terminal row: the run is over even though this
+ // call is not the one that recorded it.
+ completionDurable = conflictingTerminalOwner;
+ // `recordCompletion` only refuses a row that is ALREADY terminal with a
+ // different status than this callback carries (its `where` matches every
+ // in-flight status, plus an equal one). So the row it refused is the
+ // authoritative outcome, and the topic must be settled for what landed β€”
+ // not for what this late callback is carrying. Two racing terminal
+ // callbacks (`done` vs `error`/`interrupted`) would otherwise write
+ // whichever one arrived second, `unread` and `active` included.
+ if (operation) durableStatus = operation.status;
}
} catch (error) {
log('[%s] Failed to persist operation completion (non-fatal): %O', operationId, error);
}
+ // The run is over durably β€” converge the topic's running mark, or it outlives
+ // the run (see `settleTopicRunningMark`). Deliberately not attempted when the
+ // completion above did not land: a DB error or a missing start row leaves the
+ // operation's own end unproven, and a mark cleared on an unproven ending
+ // reads as settled while `agent_operations` still says `running`.
+ if (completionDurable) {
+ await this.settleTopicRunningMark({ operationId, status: durableStatus, topicId });
+ }
+
+ if (conflictingTerminalOwner) return false;
+
// The topic rollup's tool / human-interaction stats derive from the
// operation rows written above (`recomputeTopicUsage` reads their usage/cost
// blobs), but its usual trigger is the assistant message's usage write,
@@ -485,6 +535,80 @@ export class CompletionLifecycle {
return true;
}
+ /**
+ * Drop the topic's `runningOperation` mark when a run reaches its terminal row.
+ *
+ * The ONLY server-side settle used to be `ServerOperationStore.clearRunningMark`,
+ * and it runs from a single place: the `finish` executor. Every ending that
+ * never emits a `finish` instruction therefore wrote a terminal
+ * `agent_operations` row and left the topic exactly as the run's start had left
+ * it β€” `status = 'running'` with `metadata.runningOperation` naming an operation
+ * that had already finished:
+ *
+ * - a Stop is persisted at the step boundary (`AgentRuntimeService.executeStep`
+ * sets the state to `interrupted` once the in-flight step returns), and the
+ * following delivery usually finds the operation already terminal;
+ * - `interruptOperation` settles a client-parked run itself, and
+ * `buildShareAbortResult` settles a revoked share visitor run;
+ * - a loop stopped by `max_steps` / `cost_limit` ends without the agent asking
+ * to finish.
+ *
+ * Nothing then revisited the row: the client's own settle is a single attempt
+ * that a transient server refusal discards, and the client watchdog only runs
+ * with that user's sidebar open. Observed 2026-10-13 on a self-hosted
+ * deployment as a topic shown "running" for 45 minutes whose operation row had
+ * been `interrupted` since 03:33:58Z with `topics.updated_at` frozen at the
+ * run's start β€” `settleRunningOperation` always bumps `updated_at`, so that
+ * timestamp is proof no settle ever reached the row. 16 rows of the same shape,
+ * the oldest two months old.
+ *
+ * Persisting the terminal row is the moment the run is over, so converging
+ * here covers every ending above (and any future one) instead of adding a call
+ * to each caller. Compare-and-clear, exactly as the executor's adapter does:
+ * only the operation the mark names β€” or one of its children β€” may drop it, so
+ * a newer run that claimed the topic meanwhile is left alone and answers
+ * `conflict`. Best-effort: a topic that cannot be reached must not fail the
+ * completion it already persisted.
+ */
+ private async settleTopicRunningMark(params: {
+ operationId: string;
+ status: AgentOperationStatus;
+ topicId?: string;
+ }): Promise<void> {
+ const { operationId, status, topicId } = params;
+
+ // No topic to settle (a sub-agent run, a bot thread, a verify pass).
+ if (!topicId) return;
+ // Only an ending may drop the mark. Not merely the parked three: the fallback
+ // above settles for the status read back from the row rather than one this
+ // callback authored, and `idle` / `running` are no more of an ending than a
+ // pause is. `isAgentOperationInFlight` is the shared authority for both.
+ if (isAgentOperationInFlight(status)) return;
+ // A lease-expired abandon settles the topic on its own path with its own
+ // status (`AbandonOperationService`); leave that one to it.
+ if (status === 'abandoned') return;
+
+ try {
+ const topicModel = new TopicModel(this.serverDB, this.userId, this.workspaceId, undefined, {
+ includeShareVisitor: this.includeShareVisitor,
+ });
+
+ const settled = await topicModel.settleRunningOperation(
+ topicId,
+ operationId,
+ topicStatusForTerminalRun(status),
+ );
+
+ // `missing` (another writer already cleared it) and `conflict` (a newer run
+ // owns the mark) are both correct no-ops, not failures.
+ if (settled.status !== 'settled') {
+ log('[%s] Topic running mark left alone: %s', operationId, settled.status);
+ }
+ } catch (error) {
+ log('[%s] Failed to settle the topic running mark (non-fatal): %O', operationId, error);
+ }
+ }
+
/** Best-effort child-usage rollup β€” a DB hiccup must not fail the completion write. */
private async sumChildUsage(operationId: string): Promise<ChildUsageRollup | undefined> {
try {
diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
index aab004c57fd..a19778e7a7e 100644
--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
@@ -28,6 +28,7 @@ const {
mockNotifyAgentInterventionRequired,
mockNotifyAgentRunCompleted,
mockListWorks,
+ mockSettleRunningOperation,
} = vi.hoisted(() => ({
mockBuildRuntimeInterventionNotification: vi.fn<
() => Promise<NotifyAgentInterventionRequiredParams | undefined>
@@ -35,6 +36,7 @@ const {
mockNotifyAgentInterventionRequired: vi.fn(async () => {}),
mockNotifyAgentRunCompleted: vi.fn(async () => {}),
mockListWorks: vi.fn(async (): Promise<{ id: string }[]> => []),
+ mockSettleRunningOperation: vi.fn(async () => ({ status: 'settled' as const })),
}));
vi.mock('@/database/models/work', () => ({
@@ -43,6 +45,16 @@ vi.mock('@/database/models/work', () => ({
}),
}));
+// `TopicModel.settleRunningOperation` is a class FIELD (bound per instance, not
+// on the prototype), so observing it means swapping the class. This is the only
+// TopicModel use in the lifecycle, and the tests below assert both that it runs
+// for a finished run and that it is deliberately skipped otherwise.
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn(function () {
+ return { settleRunningOperation: mockSettleRunningOperation };
+ }),
+}));
+
vi.mock('@/business/server/agent-run/agentInterventionReview', () => ({
notifyAgentInterventionRequired: mockNotifyAgentInterventionRequired,
}));
@@ -851,6 +863,224 @@ describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
});
});
+describe('CompletionLifecycle.dispatchHooks β€” the topic running mark', () => {
+ /**
+ * `recordCompletion` must land for the mark to be converged: the lifecycle
+ * treats an ending whose own row write failed as unproven, and a mark cleared
+ * on an unproven ending reads settled while `agent_operations` still says
+ * `running`.
+ */
+ const acceptingOperationModel = () => ({
+ findById: vi.fn(async () => null),
+ recordCompletion: vi.fn(async () => true),
+ sumChildUsage: vi.fn(async () => undefined),
+ });
+
+ const state = (overrides: Record<string, unknown> = {}) => ({
+ host: { hooks: [] },
+ messages: [{ content: 'final reply', role: 'assistant' }],
+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },
+ status: 'interrupted',
+ ...overrides,
+ });
+
+ beforeEach(() => {
+ mockSettleRunningOperation.mockReset().mockResolvedValue({ status: 'settled' });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('drops the mark when an interrupted run reaches its terminal row', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+
+ await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
+
+ // A Stop is a visible ending the user already saw: `active`, the same status
+ // the client writes for an interrupted run.
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'active');
+ });
+
+ it('drops the mark for a clean finish, as unread', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'done');
+
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'unread');
+ });
+
+ it('drops the mark for a run the step cap stopped, which never runs `finish`', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'max_steps');
+
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'unread');
+ });
+
+ it.each(['waiting_for_async_tool', 'waiting_for_client', 'waiting_for_human'])(
+ 'leaves the mark while the same operation is parked in %s',
+ async (reason) => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+
+ await lifecycle.dispatchHooks('op-1', state({ status: reason }), reason);
+
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ },
+ );
+
+ it('does nothing for a run with no topic', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+
+ await lifecycle.dispatchHooks('op-1', state({ origin: { agentId: 'agt_1' } }), 'interrupted');
+
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it('leaves a lease-expired abandon to the path that settles it', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ id: 'op-1', status: 'abandoned' })),
+ recordCompletion: vi.fn(
+ async (_id: string, params: { status: string }) => params.status === 'abandoned',
+ ),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'error' }), 'error', {
+ settledAsAbandoned: true,
+ skipErrorMessageWrite: true,
+ });
+
+ // `AbandonOperationService` owns the topic there, with its own status.
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it('leaves the mark when the terminal row could not be written', async () => {
+ const lifecycle = buildLifecycle();
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => null),
+ recordCompletion: vi.fn(async () => {
+ throw new Error('db is down');
+ }),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
+
+ // The operation's own end is unproven, so the topic must keep saying so.
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ consoleError.mockRestore();
+ });
+
+ it('leaves the mark when no durable row exists to prove the ending', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => null),
+ recordCompletion: vi.fn(async () => false),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
+
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it('still converges when another owner already wrote the terminal row', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ id: 'op-1', status: 'interrupted' })),
+ recordCompletion: vi.fn(async () => false),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state(), 'interrupted');
+
+ // The run is over β€” someone else just recorded it β€” and hooks still stay
+ // parked with that owner.
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'active');
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ /**
+ * Two terminal callbacks can race for the same operation: `recordCompletion`
+ * accepts the first and refuses the second β€” its `where` matches every
+ * in-flight status plus an equal one, so a refusal proves the row already
+ * landed and carries a DIFFERENT outcome. The topic must then be settled for
+ * what landed. Settling for the late callback instead would flip `unread`
+ * (a clean finish) to `active` (an interruption) or the other way round,
+ * depending purely on which of the two reached its settle first.
+ */
+ it('settles for a `done` row when a late `interrupted` callback loses the race', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ id: 'op-1', status: 'done' })),
+ recordCompletion: vi.fn(async () => false),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'interrupted' }), 'interrupted');
+
+ // The run finished cleanly, so the user may not have watched it.
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'unread');
+ });
+
+ it('settles for an `interrupted` row when a late `done` callback loses the race', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ id: 'op-1', status: 'interrupted' })),
+ recordCompletion: vi.fn(async () => false),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'done');
+
+ // The stopping point was a visible interruption, not a clean finish.
+ expect(mockSettleRunningOperation).toHaveBeenCalledWith('tpc_1', 'op-1', 'active');
+ });
+
+ it('leaves the mark when the refused row is not an ending either', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = {
+ // `idle` is outside `recordCompletion`'s in-flight set, so a row that
+ // never started can refuse a terminal write while still not being over.
+ findById: vi.fn(async () => ({ id: 'op-1', status: 'idle' })),
+ recordCompletion: vi.fn(async () => false),
+ sumChildUsage: vi.fn(async () => undefined),
+ };
+
+ await lifecycle.dispatchHooks('op-1', state({ status: 'done' }), 'done');
+
+ expect(mockSettleRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it('treats losing the race to a newer run as a no-op', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+ mockSettleRunningOperation.mockResolvedValue({ status: 'conflict' });
+
+ await expect(lifecycle.dispatchHooks('op-1', state(), 'interrupted')).resolves.toBeUndefined();
+
+ expect(mockSettleRunningOperation).toHaveBeenCalledTimes(1);
+ });
+
+ it('never fails the completion when the topic cannot be settled', async () => {
+ const lifecycle = buildLifecycle();
+ (lifecycle as any).agentOperationModel = acceptingOperationModel();
+ mockSettleRunningOperation.mockRejectedValue(new Error('topic row is locked'));
+
+ await expect(lifecycle.dispatchHooks('op-1', state(), 'interrupted')).resolves.toBeUndefined();
+ });
+});
+
describe('CompletionLifecycle.dispatchHooks β€” verify plan race', () => {
afterEach(() => {
vi.restoreAllMocks();
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 3ab24c74653..4c4c6c7f8bd 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -4315,7 +4315,9 @@ describe('GatewayActionImpl', () => {
const action = new GatewayActionImpl(set as any, get, undefined);
action.createClient = vi.fn(() => createMockClient());
- return { action, captured, completeOperation, updateTopicStatus };
+ // `state` is returned live so a test can mutate the topic map mid-stream β€”
+ // modelling another run claiming the topic after this reconnect attached.
+ return { action, captured, completeOperation, state, updateTopicStatus };
}
// The core black-hole guard: a reconnect that closes WITHOUT witnessing a
@@ -4415,6 +4417,64 @@ describe('GatewayActionImpl', () => {
expect(topicService.settleRunningOperation).not.toHaveBeenCalled();
});
+ // One settle this tab's own topic map must not be able to veto.
+ //
+ // The map is only a guess about whether another run claimed the topic, while
+ // the call it used to skip is authoritative in a way the guess cannot be: the
+ // server compares the operation id itself and answers `conflict` for a newer
+ // run, which `#restoreRunningOnSettleConflict` already consumes. Skipping on
+ // the guess dropped the settle whenever the map was stale or the newer run
+ // never landed its server-side mark β€” and nothing retried it, so the row kept
+ // `status='running'` with a `runningOperation` naming a finished operation.
+ // Observed 2026-10-13: a topic shown "running" for 45 minutes whose operation
+ // row had been `interrupted` since 03:33:58Z, `topics.updated_at` frozen at
+ // the run's start (settling always bumps it, so that is proof no settle ever
+ // reached the row), 16 rows of the same shape in the database.
+ //
+ // Reconnect is the path a page refresh takes, which is why the symptom read
+ // as "still spinning after a reload". `executeGatewayAgent`'s
+ // onSessionComplete β€” the path this one mirrors β€” has never had the guard.
+ it('settles the server row even when this tab already names a newer operation', async () => {
+ const { action, captured, state } = createOnSessionCompleteHarness();
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ heteroType: null,
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ // A newer run claims the topic while this reconnect is streaming. The
+ // pre-attach re-check already bails when the map names another operation
+ // BEFORE the connect, so this is the only window in which the removed guard
+ // could still fire.
+ state.topicDataMap['agent_agent-1'] = {
+ items: [
+ {
+ id: 'topic-1',
+ metadata: { runningOperation: { operationId: 'server-newer-op' } },
+ status: 'running',
+ },
+ ],
+ };
+
+ vi.mocked(topicService.settleRunningOperation).mockClear();
+ captured.onSessionComplete!({
+ authFailed: false,
+ completion: { source: 'resume_status', status: 'completed' },
+ succeeded: false,
+ terminalReceived: false,
+ });
+
+ // Issued, and left to the server to arbitrate: it writes only while its own
+ // mark still names this operation, so the newer run above keeps its mark.
+ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(
+ 'topic-1',
+ 'server-op-1',
+ 'active',
+ );
+ });
+
// A genuine terminal event (agent_runtime_end / error) still finalizes the
// run: clear runningOperation so the topic doesn't reconnect forever.
it('clears runningOperation when a real terminal event was received', async () => {
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 3a8be3c6389..d05edd79ab4 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -2143,15 +2143,6 @@ export class GatewayActionImpl {
succeeded,
});
- // Same supersede guard as executeGatewayAgent's onSessionComplete: a
- // 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,
- });
-
// 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
@@ -2176,14 +2167,25 @@ export class GatewayActionImpl {
// Share visitors cannot settle the creator-owned topic row (the topic
// router is owner-scoped) β€” the local clear below still runs. Same
// split as executeGatewayAgent's onSessionComplete.
- const settle =
- superseded || agentShareId
- ? undefined
- : topicService.settleRunningOperation(
- topicId,
- operationId,
- viewing || !effectiveSucceeded ? 'active' : 'unread',
- );
+ //
+ // Deliberately NOT also gated on a local supersede read. This tab's topic
+ // map is only a guess about whether another run claimed the topic, and
+ // the settle below is authoritative in a way the guess cannot be: it
+ // writes only while the SERVER's mark still names THIS operation, and
+ // answers `conflict` for a newer one, which `#restoreRunningOnSettleConflict`
+ // already consumes by re-pinning `running` and refetching the newer mark.
+ // Skipping the call on the guess dropped the settle entirely whenever the
+ // map was stale or the newer run never landed its server-side mark, and
+ // nothing retried it β€” the row then kept `status='running'` with a
+ // `runningOperation` naming a finished operation. `executeGatewayAgent`'s
+ // onSessionComplete (the path this one mirrors) has never had that guard.
+ const settle = agentShareId
+ ? undefined
+ : topicService.settleRunningOperation(
+ topicId,
+ operationId,
+ viewing || !effectiveSucceeded ? 'active' : 'unread',
+ );
// 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
@@ -2275,35 +2277,6 @@ export class GatewayActionImpl {
* user switched agent/group, when the active-bucket `getTopicById` would miss the topic
* and leave its marker stale.
*/
- /**
- * Whether a DIFFERENT run has since claimed this topic's `runningOperation`.
- *
- * Read from the local topic map, which every run's start writes optimistically
- * β€” so a session closing after a newer run began can tell "my run ended" from
- * "the topic is idle" and keep its hands off the newer run's markers.
- *
- * Deliberately false when the topic carries no marker at all (not loaded into
- * `topicDataMap`, or already cleared): there is nothing to protect, and the
- * caller's clear must still run so a dead marker never survives.
- */
- #isSupersededRunningOperation = (params: {
- agentId?: string;
- groupId?: string;
- operationId: string;
- topicId: string;
- }): boolean => {
- const { agentId, groupId, operationId, topicId } = params;
- const state = this.#get();
- const key = topicMapKey({
- agentId: agentId ?? state.activeAgentId,
- groupId: groupId ?? state.activeGroupId,
- });
- const owner = state.topicDataMap[key]?.items?.find((t) => t.id === topicId)?.metadata
- ?.runningOperation?.operationId;
-
- return !!owner && owner !== operationId;
- };
-
/**
* Whether a silently-ended gateway run is over, judged from the server's own
* reservation of the topic.