π€― 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: attach registered Works to the final assistant reply (#19345)
YuTengjingdac6eb0fdc2f
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex c8b442f0997..f696b15c4bc 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -14,6 +14,7 @@ import {import { MessageModel } from '@/database/models/message';import { recomputeTopicUsage } from '@/database/models/topicUsage';import { VerifyRunModel } from '@/database/models/verifyRun';+import { WorkModel } from '@/database/models/work';import { type LobeChatDatabase } from '@/database/type';import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';import { buildFinalSnapshotKey } from '@/server/modules/AgentTracing';@@ -783,7 +784,8 @@ export class CompletionLifecycle {const outcome = await registerWorksForOperation({// The round's final assistant message β the shell github scan stamps the// Work display anchor onto it for hetero runs (see registerWorksForOperation).- assistantMessageId: state?.metadata?.assistantMessageId ?? null,+ assistantMessageId:+ state?.metadata?.workAssistantMessageId ?? state?.metadata?.assistantMessageId ?? null,// Live terminal totals: on the pre-snapshot path the op row's cost/usage// columns are not persisted yet (recordCompletion runs later), so the// registration must not rely on reading them back from the DB.@@ -794,6 +796,35 @@ export class CompletionLifecycle {userId: state?.metadata?.userId || this.userId,workspaceId: this.workspaceId,});+ // Skill tools may have registered Works before the terminal file scan.+ // Query the registry instead of inferring output from display messages.+ const works = await new WorkModel(+ this.serverDB,+ state?.metadata?.userId || this.userId,+ this.workspaceId,+ ).listByRootOperation({ includeFileWorks: true, limit: 1, rootOperationId: operationId });+ if (works.length > 0) {+ const assistantMessageId =+ state?.metadata?.workAssistantMessageId ??+ state?.metadata?.assistantMessageId ??+ outcome.anchorMessageId;+ if (!assistantMessageId) {+ log('[%s] No assistant message available for registered Works', operationId);+ return;+ }+ const result = await this.messageModel.update(assistantMessageId, {+ metadata: {+ work: {+ rootOperationId: operationId,+ userMessageId: state?.metadata?.sourceMessageId,+ },+ },+ });+ if (!result.success) {+ log('[%s] Failed to stamp Work anchor on %s', operationId, assistantMessageId);+ return;+ }+ }// Stamp the idempotency marker ONLY when nothing failed. A partial failure// (some files exported/registered, others did not) must NOT be recorded as// a completed registration, or the dispatchHooks backstop would skip thediff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex 39321199b5e..428d1794959 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -1,7 +1,7 @@// @vitest-environment nodeimport { type Message, parse } from '@lobechat/conversation-flow';import { ChatErrorType, RequestTrigger } from '@lobechat/types';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { NotifyAgentInterventionRequiredParams } from '@/business/server/agent-run/agentInterventionReview';import * as agentSignalService from '@/server/services/agentSignal';@@ -23,12 +23,20 @@ const {mockBuildRuntimeInterventionNotification,mockNotifyAgentInterventionRequired,mockNotifyAgentRunCompleted,+ mockListWorks,} = vi.hoisted(() => ({mockBuildRuntimeInterventionNotification: vi.fn<() => Promise<NotifyAgentInterventionRequiredParams | undefined>>(async () => undefined),mockNotifyAgentInterventionRequired: vi.fn(async () => {}),mockNotifyAgentRunCompleted: vi.fn(async () => {}),+ mockListWorks: vi.fn(async (): Promise<{ id: string }[]> => []),+}));++vi.mock('@/database/models/work', () => ({+ WorkModel: vi.fn(function () {+ return { listByRootOperation: mockListWorks };+ }),}));vi.mock('@/business/server/agent-run/agentInterventionReview', () => ({@@ -1442,6 +1450,98 @@ describe('CompletionLifecycle.emitSignalEvents β assistant anchor', () => {describe('CompletionLifecycle.registerFileWorks', () => {const mockRegister = vi.mocked(registerWorksForOperation);+ beforeEach(() => {+ mockListWorks.mockReset();+ });++ it('anchors an already registered Work after a folded tool turn with no file scan candidates', async () => {+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });+ mockListWorks.mockResolvedValue([{ id: 'registered-document' }]);+ const lifecycle = buildLifecycle();+ const update = vi+ .spyOn(lifecycle['messageModel'], 'update')+ .mockResolvedValue({ success: true });+ const state = {+ messages: [{ id: 'display-group', role: 'assistantGroup', children: [] }],+ metadata: { workAssistantMessageId: 'final-assistant', sourceMessageId: 'source-user' },+ };++ await lifecycle.registerFileWorks('op-1', state);++ expect(mockListWorks).toHaveBeenCalledWith({+ includeFileWorks: true,+ limit: 1,+ rootOperationId: 'op-1',+ });+ expect(update).toHaveBeenCalledWith('final-assistant', {+ metadata: { work: { rootOperationId: 'op-1', userMessageId: 'source-user' } },+ });+ expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);+ });++ it('does not anchor a reply when only other operations have Works', async () => {+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });+ const lifecycle = buildLifecycle();+ const update = vi+ .spyOn(lifecycle['messageModel'], 'update')+ .mockResolvedValue({ success: true });++ await lifecycle.registerFileWorks('op-1', {+ metadata: { assistantMessageId: 'final-assistant' },+ });++ expect(update).not.toHaveBeenCalled();+ });++ it('withholds the completion marker when an anchor write fails and retries it', async () => {+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });+ mockListWorks.mockResolvedValue([{ id: 'registered-document' }]);+ const lifecycle = buildLifecycle();+ const update = vi+ .spyOn(lifecycle['messageModel'], 'update')+ .mockResolvedValueOnce({ success: false })+ .mockResolvedValueOnce({ success: true });+ const state = { metadata: { assistantMessageId: 'final-assistant' } };+ await lifecycle.registerFileWorks('op-1', state);+ expect(state.metadata).not.toHaveProperty('_fileWorksRegistered');+ await lifecycle.registerFileWorks('op-1', state);+ expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);+ expect(update).toHaveBeenCalledTimes(2);+ });++ it('keeps registration retryable until the explicit final assistant id is available', async () => {+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });+ mockListWorks.mockResolvedValue([{ id: 'registered-document' }]);+ const lifecycle = buildLifecycle();+ const update = vi+ .spyOn(lifecycle['messageModel'], 'update')+ .mockResolvedValue({ success: true });+ const state: { metadata: { assistantMessageId?: string } } = { metadata: {} };+ await lifecycle.registerFileWorks('op-1', state);+ expect(update).not.toHaveBeenCalled();+ expect(state.metadata).not.toHaveProperty('_fileWorksRegistered');+ state.metadata.assistantMessageId = 'final-assistant';+ await lifecycle.registerFileWorks('op-1', state);+ expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);+ });++ it('preserves completion idempotency when the shell scanner resolved a fallback anchor', async () => {+ mockRegister.mockResolvedValue({ anchorMessageId: 'shell-assistant', attempted: 1, failed: 0 });+ mockListWorks.mockResolvedValue([{ id: 'registered-shell-work' }]);+ const lifecycle = buildLifecycle();+ const update = vi+ .spyOn(lifecycle['messageModel'], 'update')+ .mockResolvedValue({ success: true });+ const state = { metadata: {} };+ await lifecycle.registerFileWorks('op-1', state);+ expect(update).toHaveBeenCalledWith('shell-assistant', {+ metadata: { work: { rootOperationId: 'op-1', userMessageId: undefined } },+ });+ expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);+ mockRegister.mockClear();+ await lifecycle.registerFileWorks('op-1', state);+ expect(mockRegister).not.toHaveBeenCalled();+ });it('registers once and stamps the state marker so later calls skip', async () => {mockRegister.mockClear();diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.workAnchors.integration.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.workAnchors.integration.test.tsnew file mode 100644index 00000000000..003a64361f7--- /dev/null+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.workAnchors.integration.test.ts@@ -0,0 +1,144 @@+// @vitest-environment node+import { type Message, parse } from '@lobechat/conversation-flow';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AgentDocumentModel } from '@/database/models/agentDocuments';+import { MessageModel } from '@/database/models/message';+import { WorkModel } from '@/database/models/work';+import { agents, messages, topics, users } from '@/database/schemas';++import { CompletionLifecycle } from '../CompletionLifecycle';++// No terminal files are discovered: the Work was already registered by a tool.+vi.mock('@/server/services/workRegistration', () => ({+ registerWorksForOperation: vi.fn(async () => ({ attempted: 0, failed: 0 })),+}));++const db = await getTestDB();+const userId = 'anchor-user';+const topicId = 'anchor-topic';+const agentId = 'anchor-agent';+const operationId = 'anchor-operation';+const workModel = new WorkModel(db, userId);+const messageModel = new MessageModel(db, userId);+const lifecycle = new CompletionLifecycle(db, userId);++beforeEach(async () => {+ await db.delete(users);+ await db.insert(users).values({ id: userId });+ await db.insert(agents).values({ id: agentId, userId });+ await db.insert(topics).values({ id: topicId, userId });+ await db.insert(messages).values([+ { id: 'source', role: 'user', content: 'Create a document', topicId, userId },+ {+ id: 'intermediate',+ role: 'assistant',+ content: '',+ parentId: 'source',+ topicId,+ userId,+ tools: [+ {+ apiName: 'createDocument',+ arguments: '{}',+ id: 'create-document',+ identifier: 'lobe-agent-documents',+ result_msg_id: 'tool',+ type: 'builtin',+ },+ ],+ },+ { id: 'tool', role: 'tool', content: 'Created', parentId: 'intermediate', topicId, userId },+ {+ id: 'final',+ role: 'assistant',+ content: 'Created the document',+ parentId: 'tool',+ metadata: { finishType: 'stop' },+ topicId,+ userId,+ },+ ]);+});++const registerDocument = async () => {+ const doc = await new AgentDocumentModel(db, userId).create(agentId, 'notes.md', 'Notes', {+ title: 'Notes',+ });+ return workModel.registerDocument({+ agentDocumentId: doc.id,+ agentId,+ documentId: doc.documentId,+ changeType: 'created',+ rootOperationId: operationId,+ toolName: 'createDocument',+ toolIdentifier: 'lobe-agent-documents',+ toolCallId: 'create-document',+ topicId,+ });+};++describe('completion Work anchors with persisted messages and registered outputs', () => {+ it('attaches registered document and external Works only to the explicit final reply', async () => {+ const document = await registerDocument();+ const external = await workModel.registerExternal({+ changeType: 'created',+ resourceId: 'issue-1',+ resourceType: 'linear_issue',+ rootOperationId: operationId,+ toolIdentifier: 'linear',+ toolName: 'save_issue',+ toolCallId: 'create-issue',+ title: 'Follow up',+ topicId,+ });+ const raw = await messageModel.query({ topicId });+ const folded = parse(raw as unknown as Message[]).flatList;+ expect(folded.some((message) => message.role === 'assistantGroup')).toBe(true);+ const state = {+ messages: folded,+ metadata: { workAssistantMessageId: 'final', sourceMessageId: 'source' },+ };+ await lifecycle.registerFileWorks(operationId, state);+ const result = await messageModel.query({ topicId });+ const final = result.find((message) => message.id === 'final');+ expect(final?.metadata).toMatchObject({+ finishType: 'stop',+ work: { rootOperationId: operationId, userMessageId: 'source' },+ });+ expect(final?.works?.map((work) => work.id).sort()).toEqual(+ [document!.id, external!.id].sort(),+ );+ expect(+ result.filter((message) => message.id !== 'final').every((message) => !message.works),+ ).toBe(true);+ expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);+ });++ it("does not attach another operation's existing Work to an empty reply", async () => {+ await registerDocument();+ await lifecycle.registerFileWorks('empty-operation', {+ metadata: { assistantMessageId: 'final' },+ });+ const final = (await messageModel.query({ topicId })).find((message) => message.id === 'final');+ expect(final?.metadata?.work).toBeUndefined();+ expect(final?.works).toBeUndefined();+ });++ it('retries an unsuccessful anchor update after the final message becomes available', async () => {+ await registerDocument();+ const state = { metadata: { assistantMessageId: 'late-final' } };+ await lifecycle.registerFileWorks(operationId, state);+ expect(state.metadata).not.toHaveProperty('_fileWorksRegistered');+ await db+ .insert(messages)+ .values({ id: 'late-final', role: 'assistant', content: 'Done', topicId, userId });+ await lifecycle.registerFileWorks(operationId, state);+ const final = (await messageModel.query({ topicId })).find(+ (message) => message.id === 'late-final',+ );+ expect(final?.works).toHaveLength(1);+ expect(state.metadata).toHaveProperty('_fileWorksRegistered', true);+ });+});diff --git a/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.test.tsindex a035a068df6..ae5e7aea4bf 100644--- a/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts@@ -987,7 +987,7 @@ describe('registerWorksForOperation Β· shell github works', () => {expect(mockUpdateMessage).toHaveBeenCalledWith('msg-assistant', {metadata: { work: { rootOperationId: 'op-1' } },});- expect(outcome).toEqual({ attempted: 1, failed: 0 });+ expect(outcome).toEqual({ anchorMessageId: 'msg-assistant', attempted: 1, failed: 0 });});it('counts a failed anchor stamp so the completion backstop retries', async () => {@@ -1097,7 +1097,7 @@ describe('registerWorksForOperation Β· shell github works', () => {expect(mockUpdateMessage).toHaveBeenCalledWith('msg-owner-assistant', {metadata: { work: { rootOperationId: 'op-1' } },});- expect(outcome).toEqual({ attempted: 1, failed: 0 });+ expect(outcome).toEqual({ anchorMessageId: 'msg-owner-assistant', attempted: 1, failed: 0 });});it('counts a missing anchor as failed so the completion marker is withheld', async () => {diff --git a/apps/server/src/services/workRegistration/registerWorksForOperation.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.tsindex 00386c99429..b1a1aa49ccd 100644--- a/apps/server/src/services/workRegistration/registerWorksForOperation.ts+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.ts@@ -71,6 +71,8 @@ export interface RegisterWorksForOperationParams {* also fold in the shell Work scan (see `registerShellWorks`).*/export interface WorksRegistrationOutcome {+ /** Assistant message successfully anchored by the shell scan, including its fallback. */+ anchorMessageId?: string;/** Entity files + shell-scanned external entities this completion tried to register. */attempted: number;/** How many of `attempted` did not end up registered this round. */@@ -421,6 +423,7 @@ export const registerWorksForOperation = async (// runs β without the stamp a registered Work never renders below the message.// `messageModel.update` deep-merges metadata, so re-stamping an anchor the// finalizer already wrote (same rootOperationId) is a no-op.+ let stampedAnchorMessageId: string | undefined;if (shellOutcome.registered > 0) {let anchorMessageId = params.assistantMessageId ?? null;if (!anchorMessageId && shellOutcome.anchorCandidateMessageId) {@@ -449,6 +452,8 @@ export const registerWorksForOperation = async (if (!stamp.success) {shellOutcome.failed += 1;log('[%s] Failed to stamp work anchor on %s', operationId, anchorMessageId);+ } else {+ stampedAnchorMessageId = anchorMessageId;}} else {// No resolvable anchor at all: the Work row exists but nothing would@@ -516,7 +521,11 @@ export const registerWorksForOperation = async ();if (entities.length === 0) {log('[%s] Skipping file Work registration: no sandbox-backed entity candidates', operationId);- return { attempted: shellOutcome.attempted, failed: shellOutcome.failed };+ return {+ ...(stampedAnchorMessageId ? { anchorMessageId: stampedAnchorMessageId } : {}),+ attempted: shellOutcome.attempted,+ failed: shellOutcome.failed,+ };}// The sandbox is derived from userId + topicId and outlives the operation, so@@ -660,6 +669,7 @@ export const registerWorksForOperation = async ((result) => result.status === 'rejected' || result.value === 'failed',).length;return {+ ...(stampedAnchorMessageId ? { anchorMessageId: stampedAnchorMessageId } : {}),attempted: entities.length + shellOutcome.attempted,failed: failed + shellOutcome.failed,};diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.tsindex df927824e19..0bf6f451c85 100644--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts@@ -62,6 +62,32 @@ const createOutput = (overrides: Partial<LLMAttemptOutput> = {}): LLMAttemptOutp});describe('callLlmFinalizer', () => {+ it('retains the final assistant id independently of the rehydrated message shape', async () => {+ const state = AgentRuntime.createInitialState({+ messages: [{ id: 'group-1', role: 'assistantGroup', children: [] }],+ metadata: { sourceMessageId: 'user-1' },+ operationId: 'operation-1',+ });+ const result = await finalizeCallLlmTurn({+ assistantMessageId: 'final-assistant',+ events: [],+ host: createHost(),+ model: 'gpt-4',+ output: createOutput(),+ provider: 'openai',+ shouldReplayAssistantReasoning: false,+ state,+ });++ expect(result.newState.metadata).toMatchObject({+ sourceMessageId: 'user-1',+ workAssistantMessageId: 'final-assistant',+ });+ // This key belongs to error recovery; a completed tool turn must not+ // redirect a subsequent LLM failure to the previous assistant message.+ expect(result.newState.metadata).not.toHaveProperty('assistantMessageId');+ });+it('blocks the limit-th consecutive identical tool call before it can execute', async () => {const messages = createMessageTransport();const stream = createStreamSink();diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.tsindex beb2dff9ba9..2a7eb2b9858 100644--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts@@ -226,6 +226,9 @@ const buildFinalState = ({visibleOutputEndPublishedStepIndex?: number;}): AgentState => {const newState = structuredClone(state);+ // Completion must retain the persisted assistant identity even when messages+ // are rehydrated into display groups before the next runtime step.+ newState.metadata = { ...newState.metadata, workAssistantMessageId: assistantMessageId };newState.toolCallRepeatGuard = toolCallRepeatGuard;newState.messages.push({content: output.content,diff --git a/packages/builtin-skills/src/acceptance/SKILL.md b/packages/builtin-skills/src/acceptance/SKILL.mdindex 30dda0779c5..4f614120154 100644--- a/packages/builtin-skills/src/acceptance/SKILL.md+++ b/packages/builtin-skills/src/acceptance/SKILL.md@@ -238,22 +238,26 @@ excuse below was made in a real round.| "One more config edit and the env will boot" / "I'll mock it" / "I'll drive the rest myself" | Timebox. Inventory running instances, probe for the real capability before mocking (a mock that records nothing is not in the path), re-delegate a dead subagent's remaining steps, revert experiments and ask. (M17) || "The fix is in and tests pass β verified" | Reproduce the failure's precondition first, then verify with it held. A run that cannot fail proves nothing; "reproduces sometimes" means an unnamed precondition. When the mocked seam is the suspect, drop the mock. (M31) |-## Pick the surface by what you changed+## Pick the surface by the user-visible outcome-Match the change to the cheapest surface that can prove it; escalate only if-needed.+Match the requirement to the cheapest surface that can prove the complete outcome,+not merely the layer containing the code change. A backend fix for missing cards,+stale lists, navigation, or another visible behavior still requires the consuming+UI, its actual data response, and inspected screenshots. Database assertions and+passing tests support that evidence; they do not replace it.| What your task changed | Surface | Guide || ----------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------ |-| Backend / CLI / library / data logic | **CLI** β stdout as `text`, zero UI flakiness | [surfaces/cli.md](surfaces/cli.md) |+| Backend / CLI / library / data logic with no UI outcome | **CLI** β stdout as `text`, zero UI flakiness | [surfaces/cli.md](surfaces/cli.md) || Web app frontend / styles / interactions | **Web** (agent-browser β running web app) | [surfaces/web.md](surfaces/web.md) || New/changed API **plus** the UI consuming it | **Web**, full-stack (agent-browser + network capture) | [surfaces/web.md](surfaces/web.md#web-full-stack) || Desktop-only behavior (native windows, IPC, packaged shell) | **Electron** (agent-browser `--cdp`) | [surfaces/electron.md](surfaces/electron.md) || Native macOS app / OS chrome agent-browser can't reach | **Native** (osascript + screencapture, local macOS) | [surfaces/native.md](surfaces/native.md) || Native iOS behavior, gestures, device-size layout | **iOS Simulator** (AXe/native CLI + `simctl`) | [surfaces/ios-simulator.md](surfaces/ios-simulator.md) |-- **Don't open a browser for a backend change**; command output as `text` is the- strongest, cheapest proof. Use **Electron** only when the criterion depends on+- **Use CLI alone only when the required outcome has no UI surface.** If a visible+ outcome cannot be exercised, report that acceptance as incomplete instead of+ narrowing it to data checks. Use **Electron** only when the criterion depends ondesktop-only code; iOS is driven by a Simulator HID/AX CLI, never host mouse βmark the case `blocked` if the CLI cannot express the gesture.- **Structured data uses native visualizations** (`cases[].datasets` +diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.tsindex 70c56e2a8e2..db94d1c2ecb 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts@@ -10,6 +10,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import * as toolEngineering from '@/helpers/toolEngineering';import { chatService } from '@/services/chat';import * as agentConfigResolver from '@/services/chat/mecha/agentConfigResolver';+import { messageService } from '@/services/message';+import { workService } from '@/services/work';import { useAgentStore } from '@/store/agent';import { useAiInfraStore } from '@/store/aiInfra';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';@@ -194,6 +196,7 @@ beforeEach(() => {resetTestEnvironment();setupMockSelectors();spyOnMessageService();+ vi.spyOn(workService, 'listByRootOperation').mockResolvedValue([]);desktopFlag.value = false;completionSoundMock.getNotificationSoundFile.mockReset().mockResolvedValue(undefined);completionSoundMock.play.mockReset().mockResolvedValue(undefined);@@ -218,61 +221,106 @@ afterEach(() => {});describe('StreamingExecutor actions', () => {- describe('executeClientAgent', () => {- it('should handle the core AI message processing', async () => {- act(() => {- useChatStore.setState({ executeClientAgent: realExecAgentRuntime });- });+ it('keeps the original source message when initializing and resuming a run', () => {+ const params = {+ agentId: TEST_IDS.SESSION_ID,+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ topicId: TEST_IDS.TOPIC_ID,+ };+ const { state } = useChatStore.getState().internal_createAgentState(params);+ expect(state.metadata?.sourceMessageId).toBe(TEST_IDS.USER_MESSAGE_ID);+ const resumed = useChatStore.getState().internal_createAgentState({+ ...params,+ initialState: state,+ parentMessageId: 'intermediate-assistant',+ });+ expect(resumed.state.metadata?.sourceMessageId).toBe(TEST_IDS.USER_MESSAGE_ID);+ });- const { result } = renderHook(() => useChatStore());- const userMessage = {- id: TEST_IDS.USER_MESSAGE_ID,- role: 'user',- content: TEST_CONTENT.USER_MESSAGE,- sessionId: TEST_IDS.SESSION_ID,- topicId: TEST_IDS.TOPIC_ID,- } as UIChatMessage;- const messages = [userMessage];- seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, messages);+ describe('executeClientAgent', () => {+ it.each([false, true])(+ 'completes the reply and anchors only registered Works (hasWork=%s)',+ async (hasWork) => {+ if (hasWork) {+ vi.mocked(workService.listByRootOperation).mockResolvedValue([+ { id: 'registered-work' } as Awaited<+ ReturnType<typeof workService.listByRootOperation>+ >[number],+ ]);+ }+ act(() => {+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });+ });- const streamSpy = spyOnClientLLMStream(async ({ onFinish }) => {- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);- });+ const { result } = renderHook(() => useChatStore());+ const userMessage = {+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ content: TEST_CONTENT.USER_MESSAGE,+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ } as UIChatMessage;+ const messages = [userMessage];+ seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, messages);- await act(async () => {- await result.current.executeClientAgent({- context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },- messages,- parentMessageId: userMessage.id,- parentMessageType: 'user',+ const streamSpy = spyOnClientLLMStream(async ({ onFinish }) => {+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);});- });- // Verify agent runtime executed successfully- expect(streamSpy).toHaveBeenCalled();- expect(result.current.refreshMessages).toHaveBeenCalledWith({- agentId: TEST_IDS.SESSION_ID,- topicId: TEST_IDS.TOPIC_ID,- });-- // Verify operation was completed- const operations = Object.values(result.current.operations);- const execOperation = operations.find((op) => op.type === 'execAgentRuntime');- expect(execOperation?.status).toBe('completed');- expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(- expect.objectContaining({- payload: expect.objectContaining({+ await act(async () => {+ await result.current.executeClientAgent({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ messages,parentMessageId: userMessage.id,parentMessageType: 'user',- triggerMessageId: userMessage.id,+ });+ });++ // Verify agent runtime executed successfully+ expect(streamSpy).toHaveBeenCalled();+ expect(result.current.refreshMessages).toHaveBeenCalledWith({+ agentId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ });++ // Verify operation was completed+ const operations = Object.values(result.current.operations);+ const execOperation = operations.find((op) => op.type === 'execAgentRuntime');+ expect(execOperation?.status).toBe('completed');+ expect(workService.listByRootOperation).toHaveBeenCalledWith({+ limit: 1,+ rootOperationId: execOperation?.id,+ });+ const anchorWrites = vi+ .mocked(messageService.updateMessageMetadata)+ .mock.calls.filter(([, metadata]) => metadata.work);+ expect(anchorWrites).toHaveLength(hasWork ? 1 : 0);+ if (hasWork) {+ expect(anchorWrites[0]).toEqual([+ expect.any(String),+ { work: { rootOperationId: execOperation?.id, userMessageId: userMessage.id } },+ { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ ]);+ expect(+ vi.mocked(messageService.updateMessageMetadata).mock.invocationCallOrder[0],+ ).toBeLessThan(vi.mocked(result.current.refreshMessages).mock.invocationCallOrder[0]);+ }+ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ parentMessageId: userMessage.id,+ parentMessageType: 'user',+ triggerMessageId: userMessage.id,+ }),+ sourceId: `${execOperation?.id}:client:start`,+ sourceType: 'client.runtime.start',}),- sourceId: `${execOperation?.id}:client:start`,- sourceType: 'client.runtime.start',- }),- );+ );- streamSpy.mockRestore();- });+ streamSpy.mockRestore();+ },+ );it('writes topics.status=running at run start so off-conversation surfaces see it', async () => {act(() => {diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 57ef60c77eb..9950292c893 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -41,6 +41,7 @@ import { type ResolvedAgentConfig } from '@/services/chat/mecha';import { composeEnabledTools, resolveAgentConfig } from '@/services/chat/mecha';import { localFileService } from '@/services/electron/localFileService';import { messageService } from '@/services/message';+import { workService } from '@/services/work';import { getAgentStoreState } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { aiModelSelectors } from '@/store/aiInfra/selectors';@@ -376,6 +377,7 @@ export class StreamingExecutorActionImpl {agentId,groupId,scope,+ sourceMessageId: baseState.metadata?.sourceMessageId ?? parentMessageId,subAgentId: paramSubAgentId,threadId,topicId,@@ -912,6 +914,32 @@ export class StreamingExecutorActionImpl {stepCount,);+ // Registered Works survive message folding; anchor them before refreshing+ // the message list so its summary query can attach them to the final reply.+ const finalAssistantId = state.metadata?.workAssistantMessageId;+ if (state.status === 'done' && typeof finalAssistantId === 'string') {+ try {+ const works = await workService.listByRootOperation({+ limit: 1,+ rootOperationId: operationId,+ });+ if (works.length > 0) {+ await messageService.updateMessageMetadata(+ finalAssistantId,+ {+ work: {+ rootOperationId: operationId,+ userMessageId: state.metadata?.sourceMessageId,+ },+ },+ context,+ );+ }+ } catch (error) {+ log('[executeClientAgent] Failed to persist Work anchor: %O', error);+ }+ }+// Runtime message transports persist through quiet batch mutations. Reconcile// once at the run boundary instead of replacing the full list after every write.await this.#get().refreshMessages(context);