π€― 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): update Gateway tool approval cards instantly (#21566)
YuTengjinge1d7bc565501
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.tsindex ff5dbe9f2e5..713c8cdf66d 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest';import type * as ConstVersion from '@/const/version';-import { aiAgentService } from '@/services/aiAgent';+import { aiAgentService, type ExecAgentResult } from '@/services/aiAgent';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import type { GatewayConnection } from '../transports/gateway/gateway';@@ -162,8 +162,26 @@ afterEach(() => {const context = { agentId: 'agent-1', scope: 'main' as const, threadId: null, topicId: 'topic-1' };+const serverResult: ExecAgentResult = {+ agentId: 'agent-1',+ assistantMessageId: 'ast-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'ok',+ operationId: 'server-op',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ token: 'test-token',+ topicId: 'topic-1',+ userMessageId: 'usr-1',+};+/** Start a Gateway run and return its registered cancel hook. */-const startRun = async (interrupt: { deviceCancellationConfirmed?: boolean }) => {+const startRun = async (+ interrupt: { deviceCancellationConfirmed?: boolean },+ stoppedApproval?: ExecAgentResult,+) => {const onOperationCancel = vi.fn();const state: Record<string, any> = { gatewayConnections: {}, topicDataMap: {} };const set = vi.fn((updater: any) => {@@ -172,7 +190,10 @@ const startRun = async (interrupt: { deviceCancellationConfirmed?: boolean }) =>const get = vi.fn(() => ({...state,associateMessageWithOperation: vi.fn(),+ completeOperation: vi.fn(),connectToGateway: vi.fn(),+ getOperationAbortSignal: vi.fn(() => AbortSignal.abort()),+ internal_pinTopicStatus: vi.fn(),internal_dispatchTopic: vi.fn(),moveQueuedMessages: vi.fn(),moveVoiceMessages: vi.fn(),@@ -193,21 +214,18 @@ const startRun = async (interrupt: { deviceCancellationConfirmed?: boolean }) =>operationId: 'server-op',success: true,});- vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({- agentId: 'agent-1',- assistantMessageId: 'ast-1',- autoStarted: true,- createdAt: new Date().toISOString(),- message: 'ok',- operationId: 'server-op',- status: 'created',- success: true,- timestamp: new Date().toISOString(),- token: 'test-token',- topicId: 'topic-1',- userMessageId: 'usr-1',- });+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue(serverResult);+ if (stoppedApproval) {+ await action.executeGatewayAgent({+ context,+ message: '',+ parentMessageId: 'tool-1',+ parentOperationId: 'approve-op',+ precreatedResult: stoppedApproval,+ });+ return { get, handler: undefined as never };+ }await action.executeGatewayAgent({ context, message: 'Hello' });const [, handler] = onOperationCancel.mock.calls[0];return { get, handler: handler as () => Promise<void> };@@ -235,4 +253,24 @@ describe('stopping a Gateway run', () => {expect(reclaimServerQueuedMessages).not.toHaveBeenCalled();});++ // ROOT CAUSE:+ //+ // Approving a tool claims it on the server, which already starts the resumed+ // run. A Stop pressed while that claim was in flight made the run start+ // throw before it looked at the precreated run, so the run kept going.+ //+ // Before: an aborted start abandoned the precreated run.+ // After: it falls through to the late interrupt, which stops that run.+ it('interrupts the run an approval claim already started', async () => {+ await startRun({}, { ...serverResult, operationId: 'claimed-op' });++ expect(aiAgentService.execAgentTask).not.toHaveBeenCalled();+ await vi.waitFor(() =>+ expect(aiAgentService.interruptTask).toHaveBeenCalledWith({+ operationId: 'claimed-op',+ topicId: 'topic-1',+ }),+ );+ });});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.gatewayOptimistic.test.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.gatewayOptimistic.test.tsnew file mode 100644index 00000000000..64bc9c2ea9e--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.gatewayOptimistic.test.ts@@ -0,0 +1,419 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';++import { useChatStore } from '../../../../store';+import { messageMapKey } from '../../../../utils/messageMapKey';+import { mergeFetchedMessagesWithLocalState } from '../../../message/transcript/mergeFetched';+import { createMockMessage } from '../__tests__/fixtures';+import { resetTestEnvironment } from '../__tests__/helpers';++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ aiAgent: {+ resolveAgentInterventionBySource: { mutate: vi.fn() },+ },+ },+}));++vi.mock('@/utils/localStorage', () => {+ class AsyncLocalStorage<State> {+ getFromLocalStorageSync(): State {+ return {} as State;+ }++ async getFromLocalStorage(): Promise<State> {+ return {} as State;+ }++ async saveToLocalStorage(): Promise<void> {+ return undefined;+ }+ }++ return { AsyncLocalStorage };+});++const agentId = 'server-agent';+const topicId = 'server-topic';+const chatKey = messageMapKey({ agentId, topicId });++const createDeferred = () => {+ let reject!: (error: Error) => void;+ let resolve!: () => void;+ const promise = new Promise<any>((res, rej) => {+ resolve = () => res({});+ reject = rej;+ });+ return { promise, reject, resolve };+};++const seedPendingTools = (ids: string[]) => {+ const assistant = createMockMessage({ id: 'assistant-1', role: 'assistant' });+ const tools = ids.map((id) =>+ createMockMessage({+ id,+ parentId: assistant.id,+ plugin: { apiName: 'writeFile', arguments: '{}', identifier: 'fs', type: 'default' },+ pluginIntervention: { batchId: 'batch-1', operationId: 'operation-1', status: 'pending' },+ role: 'tool',+ tool_call_id: `call-${id}`,+ } as any),+ );+ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [assistant, ...tools] },+ messagesMap: { [chatKey]: [assistant, ...tools] },+ });+ });+};++const interventionOf = (id: string) =>+ useChatStore.getState().dbMessagesMap[chatKey].find((message) => message.id === id)+ ?.pluginIntervention;++beforeEach(() => {+ resetTestEnvironment();+ vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate)+ .mockReset()+ .mockResolvedValue({ contractVersion: 2, status: 'unavailable', success: false } as any);+ useChatStore.setState({ updateTopicStatus: vi.fn().mockResolvedValue(undefined) });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('Gateway approval cards update before the resume returns', () => {+ const setupGateway = () => {+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);+ const persist = vi+ .spyOn(result.current, 'optimisticUpdateMessagePlugin')+ .mockResolvedValue(undefined);+ const resume = createDeferred();+ vi.spyOn(result.current, 'executeGatewayAgent').mockReturnValue(resume.promise);+ return { persist, result, resume };+ };++ it('shows approval while the resume is in flight without persisting it', async () => {+ seedPendingTools(['tool-1']);+ const { persist, result, resume } = setupGateway();++ let approval!: Promise<void>;+ await act(async () => {+ approval = result.current.approveToolCalling('tool-1', '');+ await vi.waitFor(() => expect(result.current.executeGatewayAgent).toHaveBeenCalled());+ });++ expect(interventionOf('tool-1')).toMatchObject({ batchId: 'batch-1', status: 'approved' });+ expect(persist).not.toHaveBeenCalled();++ await act(async () => {+ resume.resolve();+ await approval;+ });+ });++ it('restores the pending card when the approval resume fails', async () => {+ seedPendingTools(['tool-1']);+ const { result, resume } = setupGateway();+ resume.reject(new Error('network error'));++ await act(async () => {+ await expect(result.current.approveToolCalling('tool-1', '')).rejects.toThrow(+ 'network error',+ );+ });++ expect(interventionOf('tool-1')).toMatchObject({ batchId: 'batch-1', status: 'pending' });+ });++ it('marks every card of an approve-all batch approved while the resume is in flight', async () => {+ seedPendingTools(['tool-1', 'tool-2']);+ const { result, resume } = setupGateway();++ let approval!: Promise<void>;+ await act(async () => {+ approval = result.current.approveAllToolCalls(['tool-1', 'tool-2']);+ await vi.waitFor(() => expect(result.current.executeGatewayAgent).toHaveBeenCalled());+ });++ expect(interventionOf('tool-1')?.status).toBe('approved');+ expect(interventionOf('tool-2')?.status).toBe('approved');++ await act(async () => {+ resume.resolve();+ await approval;+ });+ });++ it('shows the rejection while the resume is in flight and restores the card on failure', async () => {+ seedPendingTools(['tool-1']);+ const { result, resume } = setupGateway();++ let rejection!: Promise<void>;+ await act(async () => {+ rejection = result.current.rejectAndContinueToolCalling('tool-1', 'not now');+ await vi.waitFor(() => expect(result.current.executeGatewayAgent).toHaveBeenCalled());+ });++ expect(interventionOf('tool-1')).toMatchObject({+ rejectedReason: 'not now',+ status: 'rejected',+ });++ await act(async () => {+ resume.reject(new Error('network error'));+ await expect(rejection).rejects.toThrow('network error');+ });++ expect(interventionOf('tool-1')).toMatchObject({ batchId: 'batch-1', status: 'pending' });+ });++ it('drops an abandoned rejection reason when a retry rejects without one', async () => {+ seedPendingTools(['tool-1']);+ const { result, resume } = setupGateway();+ resume.reject(new Error('network error'));++ await act(async () => {+ await expect(+ result.current.rejectAndContinueToolCalling('tool-1', 'not now'),+ ).rejects.toThrow('network error');+ });++ const retry = createDeferred();+ vi.mocked(result.current.executeGatewayAgent).mockReturnValueOnce(retry.promise);+ let rejection!: Promise<void>;+ await act(async () => {+ rejection = result.current.rejectAndContinueToolCalling('tool-1');+ await vi.waitFor(() => expect(result.current.executeGatewayAgent).toHaveBeenCalledTimes(2));+ });++ // The reason renders on a rejected card only when truthy.+ expect(interventionOf('tool-1')?.status).toBe('rejected');+ expect(interventionOf('tool-1')?.rejectedReason).toBeFalsy();++ await act(async () => {+ retry.resolve();+ await rejection;+ });+ });++ it('lets the server state win when another device already resolved the card', async () => {+ seedPendingTools(['tool-1']);+ const { result } = setupGateway();+ vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).mockResolvedValueOnce({+ contractVersion: 2,+ state: 'already_resolved',+ status: 'resolved',+ success: true,+ } as any);+ const serverRow = {+ ...useChatStore.getState().dbMessagesMap[chatKey][1],+ pluginIntervention: { batchId: 'batch-1', operationId: 'operation-1', status: 'rejected' },+ } as any;+ let merged: any[] = [];+ vi.spyOn(result.current, 'refreshMessages').mockImplementation(async () => {+ // Run the real merge the refresh applies, against the local rows at refresh time.+ merged = mergeFetchedMessagesWithLocalState(+ [serverRow],+ useChatStore.getState().dbMessagesMap[chatKey],+ new Set(),+ new Set(),+ );+ });++ await act(async () => {+ await result.current.approveToolCalling('tool-1', '');+ });++ expect(merged.find((message) => message.id === 'tool-1')?.pluginIntervention?.status).toBe(+ 'rejected',+ );+ });++ it('does not undo a server state that landed before the resume failed', async () => {+ seedPendingTools(['tool-1']);+ const { result, resume } = setupGateway();++ let approval!: Promise<void>;+ await act(async () => {+ approval = result.current.approveToolCalling('tool-1', '');+ await vi.waitFor(() => expect(result.current.executeGatewayAgent).toHaveBeenCalled());+ });+ act(() => {+ useChatStore.getState().internal_dispatchMessage(+ {+ id: 'tool-1',+ type: 'updateMessage',+ value: { pluginIntervention: { ...interventionOf('tool-1'), status: 'aborted' } },+ },+ { context: { agentId, topicId } },+ );+ });++ await act(async () => {+ resume.reject(new Error('network error'));+ await expect(approval).rejects.toThrow('network error');+ });++ expect(interventionOf('tool-1')?.status).toBe('aborted');+ });++ it('keeps a server-confirmed approval when the resume fails afterwards', async () => {+ seedPendingTools(['tool-1']);+ const { result, resume } = setupGateway();++ let approval!: Promise<void>;+ await act(async () => {+ approval = result.current.approveToolCalling('tool-1', '');+ await vi.waitFor(() => expect(result.current.executeGatewayAgent).toHaveBeenCalled());+ });+ act(() => {+ useChatStore.getState().internal_dispatchMessage(+ {+ id: 'tool-1',+ type: 'updateMessage',+ value: {+ pluginIntervention: {+ ...interventionOf('tool-1'),+ resolutionRequestId: 'request-1',+ status: 'approved',+ },+ },+ },+ { context: { agentId, topicId } },+ );+ });++ await act(async () => {+ resume.reject(new Error('network error'));+ await expect(approval).rejects.toThrow('network error');+ });++ expect(interventionOf('tool-1')?.status).toBe('approved');+ });++ const stopApproval = () => {+ const op = Object.values(useChatStore.getState().operations).find(+ (operation) => operation.type === 'approveToolCalling',+ );+ act(() => {+ void useChatStore.getState().cancelOperation(op!.id, 'User stopped');+ });+ return op!.id;+ };++ it('sends no claim when Stop lands before the approval leaves', async () => {+ seedPendingTools(['tool-1']);+ const { result } = setupGateway();++ await act(async () => {+ const approval = result.current.approveToolCalling('tool-1', '');+ stopApproval();+ await approval;+ });++ expect(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).not.toHaveBeenCalled();+ expect(result.current.executeGatewayAgent).not.toHaveBeenCalled();+ expect(interventionOf('tool-1')?.status).toBe('pending');+ expect(useChatStore.getState().updateTopicStatus).not.toHaveBeenCalled();+ });++ it('hands Stop to the resumed run when it lands while the claim is in flight', async () => {+ seedPendingTools(['tool-1']);+ const { result, resume } = setupGateway();+ const refresh = vi.spyOn(result.current, 'refreshMessages').mockResolvedValue(undefined);+ let claim!: (value: unknown) => void;+ vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).mockReturnValueOnce(+ new Promise((resolve) => (claim = resolve)) as any,+ );++ let approval!: Promise<void>;+ let operationId!: string;+ await act(async () => {+ approval = result.current.approveToolCalling('tool-1', '');+ await vi.waitFor(() =>+ expect(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).toHaveBeenCalled(),+ );+ operationId = stopApproval();+ claim({+ execution: { operationId: 'resumed-op' },+ state: 'claimed',+ success: true,+ });+ await vi.waitFor(() => expect(result.current.executeGatewayAgent).toHaveBeenCalled());+ });++ expect(result.current.executeGatewayAgent).toHaveBeenCalledWith(+ expect.objectContaining({ parentOperationId: operationId }),+ );++ await act(async () => {+ resume.resolve();+ await approval;+ });++ expect(refresh).toHaveBeenCalled();+ // The claim landed, so the topic no longer waits on the user. The local row+ // already reads `active`, so only a forced write reaches the server.+ expect(useChatStore.getState().updateTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({ force: true, status: 'active' }),+ );+ });++ it('keeps the claim request on the still-pending server row', async () => {+ seedPendingTools(['tool-1']);+ const { result, resume } = setupGateway();+ resume.resolve();++ await act(async () => {+ await result.current.approveToolCalling('tool-1', '');+ });++ expect(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ batchId: 'batch-1', operationId: 'operation-1' }),+ );+ });+});++describe('Client runtime approval cards', () => {+ const setupClient = () => {+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(false);+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockRejectedValue(+ new Error('save failed'),+ );+ vi.spyOn(result.current, 'executeClientAgent').mockResolvedValue(undefined as any);+ return { result };+ };++ it('restores the pending card when persisting the approval fails', async () => {+ seedPendingTools(['tool-1']);+ const { result } = setupClient();++ await act(async () => {+ await expect(result.current.approveToolCalling('tool-1', '')).rejects.toThrow('save failed');+ });++ expect(interventionOf('tool-1')).toMatchObject({ status: 'pending' });+ expect(result.current.executeClientAgent).not.toHaveBeenCalled();+ });++ it('restores the pending card when persisting the rejection fails', async () => {+ seedPendingTools(['tool-1']);+ const { result } = setupClient();++ await act(async () => {+ await expect(+ result.current.rejectAndContinueToolCalling('tool-1', 'not now'),+ ).rejects.toThrow('save failed');+ });++ expect(interventionOf('tool-1')).toMatchObject({ rejectedReason: '', status: 'pending' });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.tsindex 4c0bd9f8654..11f2be5a49e 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -49,6 +49,7 @@ import { userProfileSelectors } from '@/store/user/selectors';import { buildRunLifecycle } from '../lifecycle/buildRunLifecycle';import { type RunScope } from '../lifecycle/types';+import { createInterventionProjection } from './interventionProjection';/*** Actions for controlling conversation operations like cancellation and error handling@@ -127,6 +128,7 @@ export class ConversationControlActionImpl {readonly #interventionResolutionRequestIds = new Map<string, string>();/** Stable per-intervention idempotency key reused by transport retries. */readonly #heteroResolutionRequestIds = new Map<string, string>();+ readonly #interventions = createInterventionProjection(() => this.#get());constructor(set: Setter, get: () => ChatStore, _api?: unknown) {void _api;@@ -204,6 +206,9 @@ export class ConversationControlActionImpl {: await aiAgentService.resolveAgentInterventionBySource(sourceParams);if (result.handled) {this.#interventionResolutionRequestIds.delete(resolutionKey);+ // The server owns the decision now: keep a claimed one, undo a lost one before the refresh.+ if (result.state === 'claimed') this.#interventions.settle(params.toolMessageIds);+ else this.#interventions.rollback(params.toolMessageIds);if (result.state === 'claimed' && params.context) {for (const id of params.toolMessageIds) {this.#get().internal_confirmQuestionSubmission(id, params.action, params.context);@@ -475,44 +480,6 @@ export class ConversationControlActionImpl {return true;};- /**- * Write an intervention state onto both projections the UI reads: the tool- * row's own `pluginIntervention` (what the pending-card list is built from)- * and the parent assistant's tool entry (inline row), so every subscribed- * surface agrees immediately.- *- * Local only. For `resolving` that is the whole point β it describes this- * client's in-flight publish, not durable truth, and a slow write could land- * after the producer's terminal ACK and resurrect a settled card. For a- * terminal settle it is the fast half: the durable write follows separately,- * and the card must not wait on it to leave the screen.- */- #dispatchInterventionState = (- toolMessageId: string,- patch: Partial<ToolIntervention>,- context: OptimisticUpdateContext,- ): void => {- const message = dbMessageSelectors.getDbMessageById(toolMessageId)(this.#get());- if (!message) return;-- const intervention = { ...message.pluginIntervention, ...patch };- this.#get().internal_dispatchMessage(- { id: toolMessageId, type: 'updateMessage', value: { pluginIntervention: intervention } },- context,- );- if (message.parentId && message.tool_call_id) {- this.#get().internal_dispatchMessage(- {- id: message.parentId,- tool_call_id: message.tool_call_id,- type: 'updateMessageTools',- value: { intervention },- },- context,- );- }- };-/*** A remote submit parks the card on `pending + resolving` until the blocked* producer echoes its ACK. That ACK can never arrive when the producer is@@ -556,7 +523,7 @@ export class ConversationControlActionImpl {// top-level `pluginIntervention` (what the card list is built from) once// the server echoes, so a failed or slow write would leave the card on// screen β the exact state this settle exists to end.- this.#dispatchInterventionState(toolMessageId, settled, context);+ this.#interventions.dispatch(toolMessageId, settled, context);void this.#get().optimisticUpdateMessagePlugin(toolMessageId,{ intervention: settled },@@ -565,7 +532,7 @@ export class ConversationControlActionImpl {}, HETERO_INTERVENTION_ACK_TIMEOUT_MS);};- #writeTopicStatus = (context: ConversationContext, status: ChatTopicStatus): void => {+ #writeTopicStatus = (context: ConversationContext, status: ChatTopicStatus, force?: boolean) => {// A share visitor's topic belongs to the creator; the owner-scoped topic// write would be rejected, and the share page has no topic status UI.if (!context.topicId || context.agentShareId) return;@@ -577,6 +544,7 @@ export class ConversationControlActionImpl {agentId: context.agentId,groupId: context.groupId,...(topicScope ? { scope: topicScope } : {}),+ force,status,topicId: context.topicId,});@@ -740,6 +708,88 @@ export class ConversationControlActionImpl {return !!op && op.status !== 'running';};+ /**+ * Claim a Gateway approval and start the run that resumes it, for both single+ * and batch approve. The card already shows the decision and no longer covers+ * the composer, so Stop is reachable while the claim is in flight:+ * - Before the claim leaves, nothing reached the server: undo locally.+ * - After it, `executeGatewayAgent` interrupts the started run (via+ * `parentOperationId`). The local decision is undone and the server's state+ * reloaded, since the refresh merge would otherwise keep the local approval.+ */+ #resumeGatewayApproval = async (approval: {+ action: AgentInterventionSourceAction;+ anchorMessageId: string;+ context: ConversationContext;+ logTag: string;+ /** Runs once the resumed run started; `handled` means the source store took the decision. */+ onClaimed?: (handled: boolean) => Promise<void>;+ operationId: string;+ /** Resume through the message-row claim when no source store handles the decision. */+ resumeLegacy: (params: Parameters<ChatStore['executeGatewayAgent']>[0]) => Promise<unknown>;+ rollbackLocalDecision: () => void;+ toolMessageIds: string[];+ }): Promise<void> => {+ const { anchorMessageId, context, logTag, operationId, toolMessageIds } = approval;+ const isStopped = () => this.#get().operations[operationId]?.status === 'cancelled';+ const settleStopped = () => {+ this.#interventions.rollback(toolMessageIds);+ return this.#get()+ .refreshMessages(context)+ .catch((error) => console.error(`${logTag} refresh after Stop failed:`, error));+ };+ if (isStopped()) return approval.rollbackLocalDecision();++ // Retired only once the resume starts, so a retry still sees Gateway mode.+ const pausedOpIds = this.#getRunningServerOps(context).map((op) => op.id);+ const params = {+ context,+ message: '',+ metadata: this.#getRequestMetadataFromMessageChain(anchorMessageId),+ parentMessageId: anchorMessageId,+ parentOperationId: operationId,+ };+ try {+ const sourceResolution = await this.tryResolveAgentInterventionBySource({+ action: approval.action,+ context,+ toolMessageIds,+ });+ if (this.#discardAlreadyResolvedSource(sourceResolution, operationId)) return;++ this.#emitRunResumed(context, {+ operationId,+ parentMessageId: anchorMessageId,+ runtimeType: 'gateway',+ });+ if (!sourceResolution.handled) await approval.resumeLegacy(params);+ else if (sourceResolution.execution) {+ await this.#get().executeGatewayAgent({+ ...params,+ precreatedResult: sourceResolution.execution,+ });+ }+ await approval.onClaimed?.(sourceResolution.handled);+ // The server took the decision. A stopped run never writes its own status,+ // so force past the local row: it already reads `active` (pinned when the+ // paused run ended) while the server's still reads `waitingForHuman`.+ this.#writeTopicStatus(context, 'active', isStopped());+ this.#completeOpsById(pausedOpIds);+ if (isStopped()) return await settleStopped();+ this.#get().completeOperation(operationId);+ } catch (error) {+ if (isStopped()) return await settleStopped();+ const err = error as Error;+ console.error(`${logTag} Gateway resume failed:`, err);+ approval.rollbackLocalDecision();+ this.#get().failOperation(operationId, {+ type: 'approveToolCalling',+ message: err.message || 'Unknown error',+ });+ throw error;+ }+ };+approveToolCalling = async (toolMessageId: string,_assistantGroupId: string,@@ -781,6 +831,11 @@ export class ConversationControlActionImpl {});const optimisticContext = { operationId };+ const rollbackLocalDecision = this.#interventions.applyLocalDecision(+ [toolMessageId],+ { status: 'approved' },+ optimisticContext,+ );const shouldUseGatewayResume = await this.#shouldUseGatewayResume(effectiveContext);if (!shouldUseGatewayResume) {@@ -793,24 +848,20 @@ export class ConversationControlActionImpl {});}- // Local runtime owns its message mutation. Gateway resumes claim the- // still-pending row atomically on the server, so they must not persist an- // optimistic approved state before calling the claim endpoint.+ // Local runtime persists the decision itself. A Gateway claim needs the row still+ // `pending` on the server, so it must not persist an optimistic approval first.if (!shouldUseGatewayResume) {- await this.#get().optimisticUpdateMessagePlugin(- toolMessageId,- { intervention: { status: 'approved' } },- optimisticContext,+ await this.#interventions.settleAfter([toolMessageId], () =>+ this.#get().optimisticUpdateMessagePlugin(+ toolMessageId,+ { intervention: { status: 'approved' } },+ optimisticContext,+ ),);}- // NOTE: intentionally do NOT bail on Stop here. `intervention: approved` is- // already persisted above; returning early would leave the tool marked- // approved but never executed β a stuck conversation. Stop pressed in this- // sub-second window is best-effort (the paused run can't be aborted yet);- // let the approval complete atomically and honor the next Stop normally.- const requestMetadata = this.#getRequestMetadataFromMessageChain(toolMessageId);-+ // NOTE: the client path does NOT bail on Stop: the approval is persisted above, so+ // returning would leave the tool approved but never run. Gateway honors Stop below.// 2.5. Server-mode: start a **new** Gateway op carrying the approval// decision via `resumeApproval`. The server reads the target tool// message, persists `intervention=approved`, dispatches the approved@@ -822,82 +873,45 @@ export class ConversationControlActionImpl {console.warn('[approveToolCalling][server] tool message missing tool_call_id; skipping resume',);+ rollbackLocalDecision();completeOperation(operationId);return;}- // Snapshot paused op IDs before the resume call; retire them only- // after executeGatewayAgent succeeds so a transient failure leaves- // the running marker intact and `#shouldUseGatewayResume` still flags- // Gateway mode on retry.- const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);// A share run belongs to the agent's owner, so a server-side `remember`// would write the OWNER's allow list (the share mirror rejects it). A// visitor's "don't ask again" approves once and lands in their own allow// list instead, which their share runs send as `userInterventionConfig`.const remembersOnServer = !!options?.rememberToolKey && !effectiveContext.agentShareId;- try {- const sourceResolution = await this.tryResolveAgentInterventionBySource({- action: {- ...(options?.editedArguments && {- edits: { [toolMessageId]: options.editedArguments },- }),- scope: remembersOnServer ? 'remember' : 'once',- type: 'approve_tool',- },- context: effectiveContext,- toolMessageIds: [toolMessageId],- });- if (this.#discardAlreadyResolvedSource(sourceResolution, operationId)) return;-- this.#emitRunResumed(effectiveContext, {- operationId,- parentMessageId: toolMessageId,- runtimeType: 'gateway',- });- if (sourceResolution.handled) {- if (sourceResolution.execution) {- await this.#get().executeGatewayAgent({- context: effectiveContext,- message: '',- metadata: requestMetadata,- parentMessageId: toolMessageId,- precreatedResult: sourceResolution.execution,- });+ await this.#resumeGatewayApproval({+ action: {+ ...(options?.editedArguments && {+ edits: { [toolMessageId]: options.editedArguments },+ }),+ scope: remembersOnServer ? 'remember' : 'once',+ type: 'approve_tool',+ },+ anchorMessageId: toolMessageId,+ context: effectiveContext,+ logTag: '[approveToolCalling][server]',+ onClaimed: async (handled) => {+ if (options?.rememberToolKey && !(handled && remembersOnServer)) {+ await useUserStore.getState().addToolToAllowList(options.rememberToolKey);}- } else {+ },+ operationId,+ resumeLegacy: async (params) => {// OSS compatibility: no generic durable store. Persist a staged edit// only now, after the generic capability probe, then use the existing// message-row claim path.- if (options?.editedArguments) {- await options.onLegacyEditFallback?.();- }+ if (options?.editedArguments) await options.onLegacyEditFallback?.();await this.#get().executeGatewayAgent({- context: effectiveContext,- message: '',- metadata: requestMetadata,- parentMessageId: toolMessageId,- resumeApproval: {- decision: 'approved',- parentMessageId: toolMessageId,- toolCallId,- },+ ...params,+ resumeApproval: { decision: 'approved', parentMessageId: toolMessageId, toolCallId },});- }- if (options?.rememberToolKey && !(sourceResolution.handled && remembersOnServer)) {- await useUserStore.getState().addToolToAllowList(options.rememberToolKey);- }- this.#writeTopicStatus(effectiveContext, 'active');- this.#completeOpsById(pausedOpIds);- completeOperation(operationId);- } catch (error) {- const err = error as Error;- console.error('[approveToolCalling][server] Gateway resume failed:', err);- this.#get().failOperation(operationId, {- type: 'approveToolCalling',- message: err.message || 'Unknown error',- });- throw error;- }+ },+ rollbackLocalDecision,+ toolMessageIds: [toolMessageId],+ });return;}@@ -1048,7 +1062,7 @@ export class ConversationControlActionImpl {// client still listens on, so no refetch would ever land the aborted rows// and the card would stay on screen until a reload.for (const id of addressable) {- this.#dispatchInterventionState(id, { status: 'aborted' }, { context: effectiveContext });+ this.#interventions.dispatch(id, { status: 'aborted' }, { context: effectiveContext });}this.#completeOpsById(pausedOpIds);} catch (error) {@@ -1076,7 +1090,7 @@ export class ConversationControlActionImpl {return;}- const { completeOperation, startOperation } = this.#get();+ const { startOperation } = this.#get();// Drop anything that can't be addressed: an optimistic row (`tmp_`) has no// server identity yet, and a tool message without `tool_call_id` can't be@@ -1099,59 +1113,29 @@ export class ConversationControlActionImpl {// The op-level anchor. The server re-derives the spine anchor from the// batch itself, so this only has to be one of the batch's own rows.const anchorMessageId = decisions.at(-1)!.parentMessageId;+ const approvedIds = decisions.map(({ parentMessageId }) => parentMessageId);const { operationId } = startOperation({type: 'approveToolCalling',context: { ...effectiveContext, messageId: anchorMessageId },});+ const rollbackLocalDecision = this.#interventions.applyLocalDecision(+ approvedIds,+ { status: 'approved' },+ { operationId },+ );- const requestMetadata = this.#getRequestMetadataFromMessageChain(anchorMessageId);- const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);-- try {- const sourceResolution = await this.tryResolveAgentInterventionBySource({- action: { scope: 'once', type: 'approve_tool' },- context: effectiveContext,- toolMessageIds: decisions.map(({ parentMessageId }) => parentMessageId),- });- if (this.#discardAlreadyResolvedSource(sourceResolution, operationId)) return;-- this.#emitRunResumed(effectiveContext, {- operationId,- parentMessageId: anchorMessageId,- runtimeType: 'gateway',- });- if (sourceResolution.handled) {- if (sourceResolution.execution) {- await this.#get().executeGatewayAgent({- context: effectiveContext,- message: '',- metadata: requestMetadata,- parentMessageId: anchorMessageId,- precreatedResult: sourceResolution.execution,- });- }- } else {- await this.#get().executeGatewayAgent({- context: effectiveContext,- message: '',- metadata: requestMetadata,- parentMessageId: anchorMessageId,- resumeApprovals: decisions,- });- }- this.#writeTopicStatus(effectiveContext, 'active');- this.#completeOpsById(pausedOpIds);- completeOperation(operationId);- } catch (error) {- const err = error as Error;- console.error('[approveAllToolCalls][server] Gateway resume failed:', err);- this.#get().failOperation(operationId, {- type: 'approveToolCalling',- message: err.message || 'Unknown error',- });- throw error;- }+ await this.#resumeGatewayApproval({+ action: { scope: 'once', type: 'approve_tool' },+ anchorMessageId,+ context: effectiveContext,+ logTag: '[approveAllToolCalls][server]',+ operationId,+ resumeLegacy: (params) =>+ this.#get().executeGatewayAgent({ ...params, resumeApprovals: decisions }),+ rollbackLocalDecision,+ toolMessageIds: approvedIds,+ });};submitToolInteraction = async (@@ -1833,7 +1817,7 @@ export class ConversationControlActionImpl {if (sourceResolution.handled) {const sourceOptimisticContext: OptimisticUpdateContext = { context: effectiveContext };- this.#dispatchInterventionState(+ this.#interventions.dispatch(toolMessageId,{ resolving: true, status: 'pending' },sourceOptimisticContext,@@ -1889,7 +1873,7 @@ export class ConversationControlActionImpl {// Publishing the user intent is not completion. Keep the interaction// pending but mark its in-flight phase so a remount/retry cannot present// an optimistic terminal state before the producer has consumed it.- this.#dispatchInterventionState(+ this.#interventions.dispatch(toolMessageId,{ resolving: true, status: 'pending' },optimisticContext,@@ -1999,7 +1983,7 @@ export class ConversationControlActionImpl {// `pluginIntervention` once the server echoes, and a failed publish must// never leave the card disabled waiting on an ACK that was never asked for.if (!isLocalDesktopHetero) {- this.#dispatchInterventionState(+ this.#interventions.dispatch(toolMessageId,{ resolving: false, status: 'pending' },optimisticContext,@@ -2129,6 +2113,11 @@ export class ConversationControlActionImpl {});const optimisticContext = { operationId };+ const rollbackLocalDecision = this.#interventions.applyLocalDecision(+ [messageId],+ { rejectedReason: reason, status: 'rejected' },+ optimisticContext,+ );const shouldUseGatewayResume = await this.#shouldUseGatewayResume(effectiveContext);if (!shouldUseGatewayResume) this.#writeTopicStatus(effectiveContext, 'active');@@ -2137,17 +2126,19 @@ export class ConversationControlActionImpl {? `User reject this tool calling with reason: ${reason}`: 'User reject this tool calling without reason';if (!shouldUseGatewayResume) {- await this.#get().optimisticUpdateMessagePlugin(- toolMessage.id,- { intervention: { rejectedReason: reason, status: 'rejected' } },- optimisticContext,- );- await this.#get().optimisticUpdateMessageContent(- messageId,- toolContent,- undefined,- optimisticContext,- );+ await this.#interventions.settleAfter([messageId], async () => {+ await this.#get().optimisticUpdateMessagePlugin(+ toolMessage.id,+ { intervention: { rejectedReason: reason, status: 'rejected' } },+ optimisticContext,+ );+ await this.#get().optimisticUpdateMessageContent(+ messageId,+ toolContent,+ undefined,+ optimisticContext,+ );+ });}const requestMetadata = this.#getRequestMetadataFromMessageChain(messageId);@@ -2162,6 +2153,7 @@ export class ConversationControlActionImpl {console.warn('[rejectToolCalling][server] tool message missing tool_call_id; skipping resume',);+ rollbackLocalDecision();completeOperation(operationId);return;}@@ -2209,6 +2201,7 @@ export class ConversationControlActionImpl {} catch (error) {const err = error as Error;console.error('[rejectToolCalling][server] Gateway resume failed:', err);+ rollbackLocalDecision();this.#get().failOperation(operationId, {type: 'rejectToolCalling',message: err.message || 'Unknown error',@@ -2244,6 +2237,11 @@ export class ConversationControlActionImpl {// the LLM loop with the rejection content surfaced as user feedback.// Skip the client-mode `rejectToolCalling` chain below β that would fire// a duplicate halting `reject` before this continue signal.+ const rollbackLocalDecision = this.#interventions.applyLocalDecision(+ [messageId],+ { rejectedReason: reason, status: 'rejected' },+ { context: effectiveContext },+ );if (await this.#shouldUseGatewayResume(effectiveContext)) {const requestMetadata = this.#getRequestMetadataFromMessageChain(messageId);const toolCallId = toolMessage.tool_call_id;@@ -2251,6 +2249,7 @@ export class ConversationControlActionImpl {console.warn('[rejectAndContinueToolCalling][server] tool message missing tool_call_id; skipping resume',);+ rollbackLocalDecision();return;}@@ -2311,6 +2310,7 @@ export class ConversationControlActionImpl {} catch (error) {const err = error as Error;console.error('[rejectAndContinueToolCalling][server] Gateway resume failed:', err);+ rollbackLocalDecision();this.#get().failOperation(operationId, {type: 'rejectToolCalling',message: err.message || 'Unknown error',diff --git a/src/store/chat/slices/agentRun/actions/entries/interventionProjection.ts b/src/store/chat/slices/agentRun/actions/entries/interventionProjection.tsnew file mode 100644index 00000000000..95d86e62498--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/entries/interventionProjection.ts@@ -0,0 +1,139 @@+import { type ToolIntervention } from '@lobechat/types';++import { type OptimisticUpdateContext } from '@/store/chat/slices/message/actions/optimisticUpdate';+import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';+import { type ChatStore } from '@/store/chat/store';++/**+ * Write an intervention state onto both projections the UI reads: the tool+ * row's own `pluginIntervention` (what the pending-card list is built from)+ * and the parent assistant's tool entry (inline row), so every subscribed+ * surface agrees immediately.+ *+ * Local only. For `resolving` that is the whole point β it describes this+ * client's in-flight publish, not durable truth, and a slow write could land+ * after the producer's terminal ACK and resurrect a settled card. For a+ * terminal settle it is the fast half: the durable write follows separately,+ * and the card must not wait on it to leave the screen.+ */+const dispatchInterventionState = (+ get: () => ChatStore,+ toolMessageId: string,+ patch: Partial<ToolIntervention>,+ context: OptimisticUpdateContext,+): void => {+ const message = dbMessageSelectors.getDbMessageById(toolMessageId)(get());+ if (!message) return;++ const intervention = { ...message.pluginIntervention, ...patch };+ get().internal_dispatchMessage(+ { id: toolMessageId, type: 'updateMessage', value: { pluginIntervention: intervention } },+ context,+ );+ if (message.parentId && message.tool_call_id) {+ get().internal_dispatchMessage(+ {+ id: message.parentId,+ tool_call_id: message.tool_call_id,+ type: 'updateMessageTools',+ value: { intervention },+ },+ context,+ );+ }+};++/**+ * Bind the intervention projection writers to one chat store.+ *+ * `applyLocalDecision` shows an approve/reject decision on the card the instant+ * the user clicks. A Gateway resume only echoes the decision after the server+ * claim and the new op's start request return, which kept the card spinning for+ * seconds. The decision goes to the local projections only: the server claims+ * the row atomically and requires it to still be `pending`, so it must never be+ * persisted here.+ *+ * Until the server answers, each card keeps a rollback:+ * - `settle` drops it once the server owns the decision (claimed, or, through+ * `settleAfter`, a local runtime persisted it).+ * - `rollback` restores the card when the resume fails, and before an+ * authoritative refresh, whose merge would otherwise keep the newer local+ * terminal state over the server's.+ */+export const createInterventionProjection = (get: () => ChatStore) => {+ const rollbacks = new Map<string, () => void>();+ /** The pre-decision state, kept from the first of nested decisions on one card. */+ const originals = new Map<string, ToolIntervention | undefined>();++ const rollback = (toolMessageIds: readonly string[]) => {+ for (const id of toolMessageIds) {+ rollbacks.get(id)?.();+ settle([id]);+ }+ };++ const settle = (toolMessageIds: readonly string[]) => {+ for (const id of toolMessageIds) {+ rollbacks.delete(id);+ originals.delete(id);+ }+ };++ const applyLocalDecision = (+ toolMessageIds: readonly string[],+ decision: Partial<ToolIntervention>,+ context: OptimisticUpdateContext,+ ): (() => void) => {+ for (const id of toolMessageIds) {+ // The client reject-and-continue path decides once itself, then again through+ // `rejectToolCalling`; the rollback must restore the card from before both.+ const original = originals.has(id)+ ? originals.get(id)+ : dbMessageSelectors.getDbMessageById(id)(get())?.pluginIntervention;+ originals.set(id, original);+ dispatchInterventionState(get, id, decision, context);+ const applied = dbMessageSelectors.getDbMessageById(id)(get())?.pluginIntervention;+ rollbacks.set(id, () => {+ // Any server write since (an `aborted`, or the same `approved` confirmed by the+ // server) replaces the immer-frozen object, so it is not ours to undo.+ const current = dbMessageSelectors.getDbMessageById(id)(get())?.pluginIntervention;+ if (current !== applied) return;+ // The message reducers `merge`, which skips `undefined`, so restoring an absent+ // `rejectedReason` as `undefined` would keep the abandoned one, and a retry+ // rejecting without a reason would show it. An empty reason renders as none.+ dispatchInterventionState(+ get,+ id,+ {+ ...original,+ rejectedReason: original?.rejectedReason ?? '',+ status: original?.status ?? 'pending',+ },+ context,+ );+ });+ }+ return () => rollback(toolMessageIds);+ };++ return {+ applyLocalDecision,+ dispatch: (+ toolMessageId: string,+ patch: Partial<ToolIntervention>,+ context: OptimisticUpdateContext,+ ) => dispatchInterventionState(get, toolMessageId, patch, context),+ rollback,+ settle,+ /** Settle once a local runtime persisted the decision; restore the card if it failed. */+ settleAfter: async (toolMessageIds: readonly string[], persist: () => Promise<unknown>) => {+ try {+ await persist();+ } catch (error) {+ rollback(toolMessageIds);+ throw error;+ }+ settle(toolMessageIds);+ },+ };+};diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 12d468e222f..f129946e885 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -1050,13 +1050,13 @@ export class GatewayActionImpl {: undefined;// Honour user-initiated cancel during phase-1 init: while we await the- // execAgentTask round-trip the caller's loading state (e.g. `sendMessage`)- // is still running, so the ChatInput stop button is active. Forward the- // abort into the round-trip wait (never into the fetch itself, see- // `awaitStartRequest`): the send rejects at once and the run the server- // still creates is interrupted when its result arrives. If the server has- // already persisted the turn, interrupt generation but still reconcile the- // message locally before returning.+ // execAgentTask round-trip the caller's loading state is still running, so+ // the ChatInput stop button is active. Forward the abort into the+ // round-trip wait (never into the fetch itself, see `awaitStartRequest`):+ // the send rejects at once and the run the server still creates is+ // interrupted when its result arrives, as is a run the intervention claim+ // already precreated. If the server has already persisted the turn,+ // interrupt generation but still reconcile the message locally.const abortSignal = parentOperationId? this.#get().getOperationAbortSignal(parentOperationId): undefined;@@ -1069,7 +1069,7 @@ export class GatewayActionImpl {);const userInterventionConfig = resolveUserInterventionConfig();- if (abortSignal?.aborted) {+ if (abortSignal?.aborted && !precreatedResult) {throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');}diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 4a1ab8d403c..a58966963ec 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -559,12 +559,13 @@ export const INPUT_LOADING_OPERATION_TYPES: OperationType[] = [// after the round-trips. See INTERIM_LOADING_OPERATION_TYPES for the bridge// semantics and why they stay out of AI_RUNTIME_OPERATION_TYPES.//- // Known limitation (accepted): this also makes Stop appear during the pre-- // generation window. The approve/submit/skip gateway branches don't forward- // `parentOperationId` to `executeGatewayAgent`, so hitting Stop in that- // narrow window doesn't actually abort the in-flight request (loading- // briefly flickers, generation proceeds). No stuck state; wiring the abort- // handoff through those branches is deferred. The `regenerate` branch DOES+ // This also makes Stop appear during the pre-generation window. The approve+ // gateway branches forward `parentOperationId` to `executeGatewayAgent`, so+ // Stop there interrupts the resumed run: approval cards resolve instantly+ // and no longer cover the composer, which keeps this window reachable.+ // Known limitation (accepted): the submit/skip gateway branches don't+ // forward it yet, so Stop in that narrow window doesn't abort (loading+ // briefly flickers, generation proceeds). The `regenerate` branch DOES// forward it β an unsettled regenerate wrapper is what the retry guard// reads, so it must never outlive phase-1 (a WS drop before session end// would otherwise brick retry for that turn permanently).diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 9befffc50ca..484c723bac8 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -962,26 +962,26 @@ export class ChatTopicActionImpl {};/**- * Persist the topic's status. Optimistically patches the in-memory map so- * the sidebar reflects the change immediately; persistence runs- * fire-and-forget so a transient network blip never tears down the agent- * run that owns the write.+ * Persist the topic's status. Optimistically patches the in-memory map so the+ * sidebar reflects it at once; persistence is fire-and-forget so a network+ * blip never tears down the agent run that owns the write.*- * Pass `agentId`/`groupId` when the call originates from an agent run- * rather than the active UI β without them, the lookup falls back to the- * currently active agent, and a status write arriving after the user has- * switched agents lands in the wrong bucket. The DB write is unconditional- * so even if no bucket is loaded for this topic, the next refetch picks- * up the persisted status.+ * Pass `agentId`/`groupId` when the call originates from an agent run rather+ * than the active UI β without them, the lookup falls back to the currently+ * active agent, and a write arriving after the user switched agents lands in+ * the wrong bucket. The DB write is unconditional so even if no bucket is+ * loaded for this topic, the next refetch picks up the persisted status.*/updateTopicStatus = async (params: {agentId?: string;+ /** Write even when the local row already reads `status`; the server's may differ. */+ force?: boolean;groupId?: string;scope?: TopicMapScope;status: ChatTopicStatus;topicId: string;}): Promise<void> => {- const { topicId, status, agentId, groupId, scope } = params;+ const { agentId, force, groupId, scope, status, topicId } = params;const state = this.#get();const scopedAgentId = scope ? agentId : (agentId ?? state.activeAgentId);const scopedGroupId = scope ? groupId : (groupId ?? state.activeGroupId);@@ -993,7 +993,7 @@ export class ChatTopicActionImpl {const topic = state.topicDataMap[key]?.items?.find((t) => t.id === topicId);// Already at the target status β both the in-memory and DB writes are no-ops.- if (topic?.status === status) return;+ if (!force && topic?.status === status) return;this.internal_pinTopicStatus(params);diff --git a/src/store/chat/slices/topic/action.updateTopicStatus.test.ts b/src/store/chat/slices/topic/action.updateTopicStatus.test.tsnew file mode 100644index 00000000000..f20e0978d2e--- /dev/null+++ b/src/store/chat/slices/topic/action.updateTopicStatus.test.ts@@ -0,0 +1,63 @@+import { act } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { topicService } from '@/services/topic';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';+import { type ChatTopic } from '@/types/topic';++import { useChatStore } from '../../store';++afterEach(() => {+ vi.restoreAllMocks();+});++/** Seed a loaded topic row whose local status is `active`. */+const seedActiveTopic = (topicId: string) => {+ const key = topicMapKey({ agentId: 'agent-1' });+ useChatStore.setState({+ topicDataMap: {+ [key]: { items: [{ id: topicId, status: 'active' } as ChatTopic] } as any,+ },+ });+};++describe('updateTopicStatus', () => {+ // ROOT CAUSE:+ //+ // A paused run that ends while its topic is open pins the local row `active`+ // without persisting it, so the server can still read `waitingForHuman`.+ // Stopping the run an approval resumed then wrote `active`, which the+ // same-status shortcut swallowed: the sidebar kept "waiting for you".+ //+ // Before: a write matching the local row never reached the server.+ // After: `force` persists it anyway.+ it('skips a write that matches the local row', async () => {+ // Unique ids: pending status writes outlive the store state between tests.+ seedActiveTopic('status-skip-topic');+ const updateSpy = vi.spyOn(topicService, 'updateTopic').mockResolvedValue(undefined as any);++ await act(() =>+ useChatStore+ .getState()+ .updateTopicStatus({ agentId: 'agent-1', status: 'active', topicId: 'status-skip-topic' }),+ );++ expect(updateSpy).not.toHaveBeenCalled();+ });++ it('persists a forced write even when the local row already matches', async () => {+ seedActiveTopic('status-force-topic');+ const updateSpy = vi.spyOn(topicService, 'updateTopic').mockResolvedValue(undefined as any);++ await act(() =>+ useChatStore.getState().updateTopicStatus({+ agentId: 'agent-1',+ force: true,+ status: 'active',+ topicId: 'status-force-topic',+ }),+ );++ expect(updateSpy).toHaveBeenCalledWith('status-force-topic', { status: 'active' });+ });+});