π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(chat): settle local topic status for follow-up gateway runs (#20049)
YuTengjing4bb65673cada
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 0fea5d1eb45..3eed2ee3d29 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -2411,6 +2411,227 @@ describe('GatewayActionImpl', () => {});});+ // LOBE-14423: a follow-up on an existing topic starts with no local+ // `runningOperation` marker (run start only rewrites a stale one), so the+ // terminal status write must not depend on the marker naming this run.+ describe('follow-up run on an existing topic without a local marker', () => {+ const setupFollowUpRun = (extraState: Record<string, any> = {}) => {+ const connectToGateway = vi.fn();+ const internalDispatchTopic = vi.fn();+ const internalPinTopicStatus = vi.fn();+ const refreshTopic = vi.fn(async () => {});+ const state: Record<string, any> = {+ activeAgentId: 'agent-1',+ activeTopicId: 'topic-1',+ gatewayConnections: {},+ topicDataMap: {+ 'agent_agent-1': {+ items: [+ {+ id: 'topic-1',+ metadata: { model: 'gpt-4', runningOperation: null },+ status: 'running',+ },+ ],+ },+ },+ ...extraState,+ };+ const set = vi.fn((updater: any) => {+ if (typeof updater === 'function') Object.assign(state, updater(state));+ else Object.assign(state, updater);+ });+ const get = vi.fn(() => ({+ ...state,+ associateMessageWithOperation: vi.fn(),+ completeOperation: vi.fn(),+ connectToGateway,+ internal_dispatchTopic: internalDispatchTopic,+ internal_pinTopicStatus: internalPinTopicStatus,+ moveQueuedMessages: vi.fn(),+ moveVoiceMessages: vi.fn(),+ onOperationCancel: vi.fn(),+ refreshTopic,+ startOperation: vi.fn(() => ({ operationId: 'gw-op-1' })),+ updateTopicStatus: vi.fn(),+ })) as any;++ (globalThis as any).window = {+ global_serverConfigStore: {+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),+ },+ };++ const action = new GatewayActionImpl(set as any, get, undefined);+ action.createClient = vi.fn(() => createMockClient());++ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'ast-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'ok',+ operationId: 'server-op-1',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ token: 'test-token',+ topicId: 'topic-1',+ userMessageId: 'usr-1',+ });+ vi.mocked(topicService.settleRunningOperation).mockResolvedValue(undefined as never);++ return {+ action,+ connectToGateway,+ internalDispatchTopic,+ internalPinTopicStatus,+ refreshTopic,+ };+ };++ it('resets the local status to active when the watched run completes', async () => {+ const { action, connectToGateway, internalDispatchTopic, internalPinTopicStatus } =+ setupFollowUpRun();++ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },+ message: 'Follow-up',+ });++ const { onSessionComplete } = connectToGateway.mock.calls[0][0];+ internalDispatchTopic.mockClear();+ internalPinTopicStatus.mockClear();++ onSessionComplete({ succeeded: true, terminalReceived: true });++ expect(internalPinTopicStatus).toHaveBeenCalledWith({+ agentId: 'agent-1',+ groupId: undefined,+ status: 'active',+ topicId: 'topic-1',+ });+ // Nothing to clear: there was no marker in the local row.+ expect(internalDispatchTopic).not.toHaveBeenCalled();+ });++ // A run started from another tab or device replaces the server marker+ // without appearing in this tab's operations; only the server can tell.+ it('restores running when the server reports another run owns the topic', async () => {+ const { action, connectToGateway, internalPinTopicStatus, refreshTopic } =+ setupFollowUpRun();+ vi.mocked(topicService.settleRunningOperation).mockResolvedValue({+ activeOperationId: 'server-op-other-tab',+ status: 'conflict',+ } as never);++ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },+ message: 'Follow-up',+ });++ const { onSessionComplete } = connectToGateway.mock.calls[0][0];+ internalPinTopicStatus.mockClear();++ onSessionComplete({ succeeded: true, terminalReceived: true });+ await vi.waitFor(() => expect(refreshTopic).toHaveBeenCalledWith('agent_agent-1'));++ expect(internalPinTopicStatus.mock.calls.map(([params]) => params.status)).toEqual([+ 'active',+ 'running',+ ]);+ });++ it('keeps the active status when the server settle does not conflict', async () => {+ const { action, connectToGateway, internalPinTopicStatus, refreshTopic } =+ setupFollowUpRun();+ vi.mocked(topicService.settleRunningOperation).mockResolvedValue({+ status: 'missing',+ } as never);++ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },+ message: 'Follow-up',+ });++ const { onSessionComplete } = connectToGateway.mock.calls[0][0];+ internalPinTopicStatus.mockClear();++ onSessionComplete({ succeeded: true, terminalReceived: true });+ await Promise.resolve();+ await Promise.resolve();++ expect(internalPinTopicStatus.mock.calls.map(([params]) => params.status)).toEqual([+ 'active',+ ]);+ expect(refreshTopic).not.toHaveBeenCalled();+ });++ it('leaves the status alone when a newer local turn already started on the topic', async () => {+ const { action, connectToGateway, internalPinTopicStatus } = setupFollowUpRun({+ operations: {+ 'newer-send': {+ context: { agentId: 'agent-1', topicId: 'topic-1' },+ id: 'newer-send',+ metadata: {},+ status: 'running',+ type: 'sendMessage',+ },+ },+ operationsByType: { sendMessage: ['newer-send'] },+ });++ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },+ message: 'Follow-up',+ });++ const { onSessionComplete } = connectToGateway.mock.calls[0][0];+ internalPinTopicStatus.mockClear();++ onSessionComplete({ succeeded: true, terminalReceived: true });++ expect(internalPinTopicStatus).not.toHaveBeenCalled();+ });++ it('ignores live operations that belong to the completing run itself', async () => {+ const { action, connectToGateway, internalPinTopicStatus } = setupFollowUpRun({+ operations: {+ 'own-runtime': {+ context: { agentId: 'agent-1', topicId: 'topic-1' },+ id: 'own-runtime',+ metadata: { serverOperationId: 'server-op-1' },+ status: 'running',+ type: 'execServerAgentRuntime',+ },+ 'own-member': {+ context: { agentId: 'agent-1', topicId: 'topic-1' },+ id: 'own-member',+ metadata: { serverOperationId: 'member-op-1' },+ parentOperationId: 'own-runtime',+ status: 'running',+ type: 'execServerAgentRuntime',+ },+ },+ operationsByType: { execServerAgentRuntime: ['own-runtime', 'own-member'] },+ });++ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },+ message: 'Follow-up',+ });++ const { onSessionComplete } = connectToGateway.mock.calls[0][0];+ internalPinTopicStatus.mockClear();++ onSessionComplete({ succeeded: true, terminalReceived: true });++ expect(internalPinTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active', topicId: 'topic-1' }),+ );+ });+ });+// The clean, unwatched-completion case is owned by `markTopicUnread`// elsewhere β the local mirror here must NOT also write 'active' for it,// or the two would race over the status field.diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 5d16846f921..7a48d26ae88 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -48,6 +48,7 @@ import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import { topicSelectors } from '@/store/chat/selectors';+import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';import type { ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { topicMapKey } from '@/store/chat/utils/topicMapKey';@@ -1451,27 +1452,31 @@ export class GatewayActionImpl {const viewing = this.#get().activeTopicId === result.topicId;// Share visitors cannot settle the creator-owned topic row (the topic// router is owner-scoped) β the local clear below still runs.- if (!agentShareId)- topicService- .settleRunningOperation(+ const settle = agentShareId+ ? undefined+ : topicService.settleRunningOperation(result.topicId,result.operationId,viewing || !effectiveSucceeded ? 'active' : 'unread',- )- .catch(console.error);+ );// Also clear the local store copy β the server settle above does NOT// touch the Zustand topic map that useGatewayReconnect (and the sidebar// spinner) read. Mirror the same 'active' decision passed to the server// call above; omit it for the unwatched-clean-completion case, which// `markTopicUnread` owns. Ownership-guarded on its own (see// clearLocalRunningOperation), so it is safe to call either way.- this.clearLocalRunningOperation({+ const settledWithoutMarker = this.clearLocalRunningOperation({agentId: resolvedMessageContext.agentId,groupId: resolvedMessageContext.groupId,operationId: result.operationId,status: viewing || !effectiveSucceeded ? 'active' : undefined,topicId: result.topicId,});+ this.#restoreRunningOnSettleConflict(settle, settledWithoutMarker, {+ agentId: resolvedMessageContext.agentId,+ groupId: resolvedMessageContext.groupId,+ topicId: result.topicId,+ });}onComplete?.();},@@ -1755,25 +1760,28 @@ 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.- if (!superseded && !agentShareId) {- topicService- .settleRunningOperation(- topicId,- operationId,- viewing || !effectiveSucceeded ? 'active' : 'unread',- )- .catch(console.error);- }+ const settle =+ superseded || 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// `markTopicUnread` owns locally; same split as the primary path.- this.clearLocalRunningOperation({+ const settledWithoutMarker = this.clearLocalRunningOperation({agentId: context.agentId,operationId,status: viewing || !effectiveSucceeded ? 'active' : undefined,topicId,});+ this.#restoreRunningOnSettleConflict(settle, settledWithoutMarker, {+ agentId: context.agentId,+ topicId,+ });},agentShareId,operationId,@@ -1893,6 +1901,79 @@ export class GatewayActionImpl {this.clearLocalRunningOperation({ ...params, status: 'active' });};+ /**+ * Whether this tab has a live turn on `topicId` that belongs to a run other+ * than `serverOperationId` β e.g. a follow-up (or queued message) already sent+ * after this run ended. Operations of this run itself (its runtime op and its+ * descendants such as broadcast members) are excluded.+ */+ #hasOtherLiveRunOnTopic = (topicId: string, serverOperationId: string): boolean => {+ const { operations, operationsByType } = this.#get();++ const belongsToRun = (op: (typeof operations)[string] | undefined): boolean => {+ let current = op;+ while (current) {+ if (current.metadata.serverOperationId === serverOperationId) return true;+ current = current.parentOperationId ? operations[current.parentOperationId] : undefined;+ }+ return false;+ };++ return INPUT_LOADING_OPERATION_TYPES.some((type) =>+ (operationsByType?.[type] ?? []).some((id) => {+ const op = operations?.[id];+ return (+ !!op &&+ op.status === 'running' &&+ !op.metadata.isAborting &&+ op.context.topicId === topicId &&+ !belongsToRun(op)+ );+ }),+ );+ };++ /**+ * Await the server settle and undo a markerless local status write that the+ * server proves wrong.+ *+ * Without a local marker, {@link clearLocalRunningOperation} can only rule out+ * newer runs started in THIS tab. A run started from another tab or device+ * replaces the server marker without appearing in this tab's operations, and+ * the server reports it as a `conflict`. The local `active` pin would then hide+ * that run's spinner, so re-pin `running` and refetch the row to pick up the+ * newer run's marker (the pin is released once the refetch matches it).+ */+ #restoreRunningOnSettleConflict = (+ settle: ReturnType<typeof topicService.settleRunningOperation> | undefined,+ settledWithoutMarker: boolean,+ target: { agentId?: string; groupId?: string; topicId: string },+ ): void => {+ if (!settle) return;++ settle+ .then((result) => {+ if (!settledWithoutMarker || result?.status !== 'conflict') return;++ const state = this.#get();+ state.internal_pinTopicStatus?.({ ...target, status: 'running' });+ // Revalidate the run's own bucket β the user may have switched agents+ // since β so that row receives the newer run's reconnect marker.+ return state.refreshTopic?.(+ topicMapKey({+ agentId: target.agentId ?? state.activeAgentId,+ groupId: target.groupId ?? state.activeGroupId,+ }),+ );+ })+ .catch(console.error);+ };++ /**+ * @returns Whether a terminal status was written without a local marker β the+ * only case whose ownership still needs the server's confirmation (see+ * `#restoreRunningOnSettleConflict`).+ */private clearLocalRunningOperation = (params: {agentId?: string;groupId?: string;@@ -1904,7 +1985,7 @@ export class GatewayActionImpl {*/status?: ChatTopicStatus;topicId: string;- }): void => {+ }): boolean => {const { topicId, operationId, agentId, groupId, status } = params;const state = this.#get();const key = topicMapKey({@@ -1912,28 +1993,39 @@ export class GatewayActionImpl {groupId: groupId ?? state.activeGroupId,});const existingTopic = state.topicDataMap[key]?.items?.find((t) => t.id === topicId);- // Same ownership guard the removed client-side `superseded` check used to- // provide: if a newer run already overwrote this topic's local marker with- // its own operationId, this stale session's completion must not clobber it- // (neither the metadata clear nor, now, the status write).- if (existingTopic?.metadata?.runningOperation?.operationId !== operationId) return;+ if (!existingTopic) return false;- state.internal_dispatchTopic({- agentId,- groupId,- id: topicId,- type: 'updateTopic',- value: { metadata: { ...existingTopic.metadata, runningOperation: null } },- });+ // Ownership guard: a stale session's completion must not clobber a newer+ // run's row (neither the metadata clear nor the status write).+ //+ // The local `runningOperation` marker alone cannot prove ownership: run start+ // only rewrites it when an older marker is present (see executeGatewayAgent),+ // so a follow-up on an existing topic runs with a `null` local marker while+ // its optimistic `running` status is still in place. Requiring the marker to+ // match skipped the status write for every such run and left the sidebar+ // spinner on until a later topic-list refetch (LOBE-14423).+ const markerOperationId = existingTopic.metadata?.runningOperation?.operationId;+ if (markerOperationId && markerOperationId !== operationId) return false;+ if (!markerOperationId && this.#hasOtherLiveRunOnTopic(topicId, operationId)) return false;++ if (markerOperationId) {+ state.internal_dispatchTopic({+ agentId,+ groupId,+ id: topicId,+ type: 'updateTopic',+ value: { metadata: { ...existingTopic.metadata, runningOperation: null } },+ });+ }// Routed through `internal_pinTopicStatus`, not a bare dispatch: it also// registers the pending-write pin so a topic-list refetch racing in// behind this (e.g. within the 15s window of the 'running' pin set at// run start) reconciles to this status instead of reapplying the stale// 'running' one and stranding the spinner again.- if (status) {- state.internal_pinTopicStatus?.({ agentId, groupId, status, topicId });- }+ if (!status) return false;+ state.internal_pinTopicStatus?.({ agentId, groupId, status, topicId });+ return !markerOperationId;};private internal_cleanupGatewayConnection = (operationId: string): void => {