π€― 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): mirror topic status reset into local store on gateway run completion (#18682)
LiJiana6565dcbfff3
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 042cd5767bb..54efb039472 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -1175,6 +1175,7 @@ describe('GatewayActionImpl', () => {it('clears the local runningOperation marker when the gateway session completes with an error', async () => {const connectToGateway = vi.fn();const internalDispatchTopic = vi.fn();+ const internalPinTopicStatus = vi.fn();const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));const state: Record<string, any> = {activeAgentId: 'agent-1',@@ -1204,6 +1205,7 @@ describe('GatewayActionImpl', () => {completeOperation: vi.fn(),connectToGateway,internal_dispatchTopic: internalDispatchTopic,+ internal_pinTopicStatus: internalPinTopicStatus,moveQueuedMessages: vi.fn(),moveVoiceMessages: vi.fn(),onOperationCancel: vi.fn(),@@ -1243,6 +1245,7 @@ describe('GatewayActionImpl', () => {const { onSessionComplete } = connectToGateway.mock.calls[0][0];// Ignore any dispatches from the optimistic-update path during setup.internalDispatchTopic.mockClear();+ internalPinTopicStatus.mockClear();vi.mocked(topicService.updateTopicMetadata).mockResolvedValue(undefined as never);onSessionComplete({ succeeded: false, terminalReceived: true });@@ -1254,6 +1257,12 @@ describe('GatewayActionImpl', () => {type: 'updateTopic',value: { metadata: { model: 'gpt-4', runningOperation: null } },});+ expect(internalPinTopicStatus).toHaveBeenCalledWith({+ agentId: 'agent-1',+ groupId: undefined,+ status: 'active',+ topicId: 'topic-1',+ });});// Background completion: the run's owning agent bucket must be targeted even@@ -1262,6 +1271,7 @@ describe('GatewayActionImpl', () => {it('clears the owning bucket marker even after the user switched agents', async () => {const connectToGateway = vi.fn();const internalDispatchTopic = vi.fn();+ const internalPinTopicStatus = vi.fn();const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));const state: Record<string, any> = {activeAgentId: 'agent-1',@@ -1292,6 +1302,7 @@ describe('GatewayActionImpl', () => {completeOperation: vi.fn(),connectToGateway,internal_dispatchTopic: internalDispatchTopic,+ internal_pinTopicStatus: internalPinTopicStatus,moveQueuedMessages: vi.fn(),moveVoiceMessages: vi.fn(),onOperationCancel: vi.fn(),@@ -1330,6 +1341,7 @@ describe('GatewayActionImpl', () => {const { onSessionComplete } = connectToGateway.mock.calls[0][0];internalDispatchTopic.mockClear();+ internalPinTopicStatus.mockClear();vi.mocked(topicService.updateTopicMetadata).mockResolvedValue(undefined as never);// The user switched away before the run finished in the background.@@ -1345,6 +1357,12 @@ describe('GatewayActionImpl', () => {type: 'updateTopic',value: { metadata: { model: 'gpt-4', runningOperation: null } },});+ expect(internalPinTopicStatus).toHaveBeenCalledWith({+ agentId: 'agent-1',+ groupId: undefined,+ status: 'active',+ topicId: 'topic-1',+ });});// A late close may observe a stale local marker even after another tab has@@ -1438,6 +1456,213 @@ describe('GatewayActionImpl', () => {expect(updateTopicStatus).not.toHaveBeenCalled();});+ // Regression guard: a successful run the user is watching must reset the+ // topic's local `status` back to 'active', not just clear the metadata+ // marker. `settleRunningOperation` above writes this to the DB, but it+ // does not touch the Zustand topic map β without this local mirror, the+ // sidebar spinner (gated on `topic.status === 'running'` once the local+ // operation itself completes) is stuck permanently, even though the+ // conversation is genuinely finished.+ it('resets the local topic status to active when a watched run completes successfully', async () => {+ const connectToGateway = vi.fn();+ const internalDispatchTopic = vi.fn();+ const internalPinTopicStatus = vi.fn();+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));+ 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: { assistantMessageId: 'ast-1', operationId: 'server-op-1' },+ },+ status: 'running',+ },+ ],+ },+ },+ };+ 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(),+ startOperation,+ 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',+ });++ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },+ message: 'Hello',+ });++ const { onSessionComplete } = connectToGateway.mock.calls[0][0];+ internalDispatchTopic.mockClear();+ internalPinTopicStatus.mockClear();+ vi.mocked(topicService.settleRunningOperation).mockClear();+ vi.mocked(topicService.settleRunningOperation).mockResolvedValue(undefined as never);++ // Still viewing the topic when the run's terminal event lands.+ onSessionComplete({ succeeded: true, terminalReceived: true });++ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(+ 'topic-1',+ 'server-op-1',+ 'active',+ );+ expect(internalDispatchTopic).toHaveBeenCalledWith({+ agentId: 'agent-1',+ groupId: undefined,+ id: 'topic-1',+ type: 'updateTopic',+ value: { metadata: { model: 'gpt-4', runningOperation: null } },+ });+ // Routed through the pin-aware setter, not a bare dispatch β see+ // `internal_pinTopicStatus`'s doc comment for why that matters.+ expect(internalPinTopicStatus).toHaveBeenCalledWith({+ agentId: 'agent-1',+ groupId: undefined,+ 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.+ it('does not touch the local topic status for a clean completion the user is not watching', async () => {+ const connectToGateway = vi.fn();+ const internalDispatchTopic = vi.fn();+ const internalPinTopicStatus = vi.fn();+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));+ const state: Record<string, any> = {+ activeAgentId: 'agent-1',+ activeTopicId: null,+ gatewayConnections: {},+ topicDataMap: {+ 'agent_agent-1': {+ items: [+ {+ id: 'topic-1',+ metadata: {+ model: 'gpt-4',+ runningOperation: { assistantMessageId: 'ast-1', operationId: 'server-op-1' },+ },+ status: 'running',+ },+ ],+ },+ },+ };+ 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(),+ startOperation,+ 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',+ });++ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },+ message: 'Hello',+ });++ const { onSessionComplete } = connectToGateway.mock.calls[0][0];+ internalDispatchTopic.mockClear();+ internalPinTopicStatus.mockClear();+ vi.mocked(topicService.settleRunningOperation).mockClear();+ vi.mocked(topicService.settleRunningOperation).mockResolvedValue(undefined as never);++ // Not viewing, and the run succeeded cleanly in the background.+ onSessionComplete({ succeeded: true, terminalReceived: true });++ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(+ 'topic-1',+ 'server-op-1',+ 'unread',+ );+ expect(internalDispatchTopic).toHaveBeenCalledWith({+ agentId: 'agent-1',+ groupId: undefined,+ id: 'topic-1',+ type: 'updateTopic',+ value: { metadata: { model: 'gpt-4', runningOperation: null } },+ });+ expect(internalPinTopicStatus).not.toHaveBeenCalled();+ });+// When the desktop runs against ζ¬ζΊ (effective runtime mode 'local'), the// client must forward this machine's own gateway deviceId so the server can// preset activeDeviceId and inject lobe-local-system into the first LLMdiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 3ae56f773c9..7589502721b 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -7,6 +7,7 @@ import {import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';import type {ChatTopicMetadata,+ ChatTopicStatus,ConversationContext,ExecAgentResult,MessageMetadata,@@ -863,13 +864,17 @@ export class GatewayActionImpl {viewing || !succeeded ? 'active' : 'unread',).catch(console.error);- // Also clear the local store copy β the server clear above does NOT touch- // the Zustand topic map that useGatewayReconnect reads. Ownership-guarded- // on its own, so it is safe to call either way.+ // 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({agentId: resolvedMessageContext.agentId,groupId: resolvedMessageContext.groupId,operationId: result.operationId,+ status: viewing || !succeeded ? 'active' : undefined,topicId: result.topicId,});}@@ -1171,15 +1176,25 @@ export class GatewayActionImpl {agentId?: string;groupId?: string;operationId: string;+ /**+ * Mirror the topic's terminal status into the local Zustand copy alongside+ * the metadata clear. Omit for the "clean completion, not watching" case β+ * that one is owned by `markTopicUnread` elsewhere.+ */+ status?: ChatTopicStatus;topicId: string;}): void => {- const { topicId, operationId, agentId, groupId } = params;+ const { topicId, operationId, agentId, groupId, status } = params;const state = this.#get();const key = topicMapKey({agentId: agentId ?? state.activeAgentId,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;state.internal_dispatchTopic({@@ -1189,6 +1204,15 @@ export class GatewayActionImpl {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 });+ }};private internal_cleanupGatewayConnection = (operationId: string): void => {diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex d4e4958dba9..160ed88e5ff 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -564,18 +564,67 @@ export class ChatTopicActionImpl {// Already at the target status β both the in-memory and DB writes are no-ops.if (topic?.status === status) return;+ this.internal_pinTopicStatus(params);+// "Archive" in the UI writes status:'completed'. Stamp `completedAt` on that// transition so bulk/stale archive records when the topic was completed,// matching the single-item `markTopicCompleted`. Other status transitions// (agent runs β running/active/unread/β¦) leave `completedAt` untouched.+ const patch: Partial<ChatTopic> =+ status === 'completed' ? { completedAt: new Date(), status } : { status };++ await topicService.updateTopic(topicId, patch).catch((err) => {+ console.error('[updateTopicStatus] persist failed:', err);+ // The DB never got the write β stop pinning it over fetched rows.+ this.#pendingTopicStatusWrites.delete(topicId);+ });+ };++ /**+ * Local-only half of {@link updateTopicStatus}: registers the optimistic+ * pending-write pin and dispatches the in-memory patch, without persisting+ * to the server.+ *+ * For completion paths that already have their own ownership-guarded+ * server write (e.g. the gateway transport's `settleRunningOperation`,+ * compared under a row lock by operation id) and only need to mirror the+ * outcome locally β calling `updateTopicStatus` there would add a second,+ * unguarded `topicService.updateTopic` write that could stomp a newer run's+ * status. Skipping the pin entirely instead (a bare `internal_dispatchTopic`)+ * is also wrong: a topic-list refetch racing in behind this write has no+ * signal that a fresher status just landed, and `#reconcileFetchedTopics`+ * would happily reapply the older pending write (e.g. the 'running' pin set+ * when the run started) right back over it, stranding the sidebar spinner+ * again until that pin expires.+ */+ internal_pinTopicStatus = (params: {+ agentId?: string;+ groupId?: string;+ scope?: TopicMapScope;+ status: ChatTopicStatus;+ topicId: string;+ }): void => {+ const { topicId, status, agentId, groupId, scope } = params;+ const state = this.#get();+ const scopedAgentId = scope ? agentId : (agentId ?? state.activeAgentId);+ const scopedGroupId = scope ? groupId : (groupId ?? state.activeGroupId);+ const key = topicMapKey({+ agentId: scopedAgentId,+ groupId: scopedGroupId,+ scope,+ });+ const topic = state.topicDataMap[key]?.items?.find((t) => t.id === topicId);++ if (topic?.status === status) return;+const patch: Partial<ChatTopic> =status === 'completed' ? { completedAt: new Date(), status } : { status };this.#pendingTopicStatusWrites.set(topicId, { expiresAt: Date.now() + 15_000, status });// Scope on the payload routes the write to the owning bucket inside- // `internal_dispatchTopic`. A no-op if the bucket isn't loaded; the DB- // write below still ensures the status sticks across the next refetch.+ // `internal_dispatchTopic`. A no-op if the bucket isn't loaded; the pin+ // above still ensures the status sticks across the next refetch.state.internal_dispatchTopic({type: 'updateTopic',id: topicId,@@ -584,12 +633,6 @@ export class ChatTopicActionImpl {groupId,scope,});-- await topicService.updateTopic(topicId, patch).catch((err) => {- console.error('[updateTopicStatus] persist failed:', err);- // The DB never got the write β stop pinning it over fetched rows.- this.#pendingTopicStatusWrites.delete(topicId);- });};#getTopicUpdatedAt = (topic: RunningTopicForWatchdog): number | undefined => {