Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: add work version registry (#17079)

YuTengjing3a587d15e651
diff --git a/apps/server/src/modules/AgentRuntime/ToolResultWaiter.ts b/apps/server/src/modules/AgentRuntime/ToolResultWaiter.ts
index 0c595d1ee9b..45ee59fd1c6 100644
--- a/apps/server/src/modules/AgentRuntime/ToolResultWaiter.ts
+++ b/apps/server/src/modules/AgentRuntime/ToolResultWaiter.ts
@@ -1,3 +1,4 @@
+import type { WorkRegistrationIntent } from '@lobechat/types';
import debug from 'debug';
import type { Redis } from 'ioredis';
@@ -12,6 +13,12 @@ export interface ToolResultPayload {
state?: Record<string, any>;
success: boolean;
toolCallId: string;
+ /**
+ * In-memory relay of the client-side Work registration intent. Forwarded onto
+ * the execution result so the agent runtime registers the Work version once
+ * the cumulative cost is known; never persisted with the tool message.
+ */
+ workRegistration?: WorkRegistrationIntent;
}
const CANCEL_SENTINEL = '__tool_result_cancelled__';
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 025860aba0f..cc326c54c95 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -137,6 +137,29 @@ vi.mock('@/server/services/file', () => ({
})),
}));
+const {
+ mockDeleteDocumentWork,
+ mockDeleteTaskWork,
+ mockHandleSkillToolResult,
+ mockRegisterDocument,
+ mockRegisterTask,
+} = vi.hoisted(() => ({
+ mockDeleteDocumentWork: vi.fn(),
+ mockDeleteTaskWork: vi.fn(),
+ mockHandleSkillToolResult: vi.fn(),
+ mockRegisterDocument: vi.fn(),
+ mockRegisterTask: vi.fn(),
+}));
+vi.mock('@/database/models/work', () => ({
+ WorkModel: vi.fn().mockImplementation(() => ({
+ deleteDocumentWork: mockDeleteDocumentWork,
+ deleteTaskWork: mockDeleteTaskWork,
+ handleSkillToolResult: mockHandleSkillToolResult,
+ registerDocument: mockRegisterDocument,
+ registerTask: mockRegisterTask,
+ })),
+}));
+
describe('RuntimeExecutors', { timeout: 60_000 }, () => {
let mockMessageModel: any;
let mockStreamManager: any;
@@ -145,6 +168,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
beforeEach(() => {
vi.clearAllMocks();
+ mockDeleteTaskWork.mockReset();
+ mockDeleteTaskWork.mockResolvedValue(undefined);
+ mockHandleSkillToolResult.mockReset();
+ mockHandleSkillToolResult.mockResolvedValue(undefined);
+ mockDeleteDocumentWork.mockReset();
+ mockDeleteDocumentWork.mockResolvedValue(undefined);
+ mockRegisterDocument.mockReset();
+ mockRegisterDocument.mockResolvedValue({ id: 'doc-work-1' });
+ mockRegisterTask.mockReset();
+ mockRegisterTask.mockResolvedValue({ id: 'work-1' });
vi.mocked(initModelRuntimeFromDB).mockReset();
mockCreateCompressionGroup.mockReset();
mockCancelCompression.mockReset();
@@ -1149,6 +1182,91 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
);
});
+ it('marks the final assistant message as the work display anchor after current tool interaction', async () => {
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState({
+ messages: [
+ { content: 'Create a task', id: 'user-msg-1', role: 'user' },
+ {
+ content: '',
+ id: 'assistant-tool-msg-1',
+ role: 'assistant',
+ tool_calls: [{ function: { arguments: '{}', name: 'createTask' }, id: 'call_1' }],
+ },
+ { content: 'created', id: 'tool-msg-1', role: 'tool', tool_call_id: 'call_1' },
+ ] as any,
+ metadata: {
+ agentId: 'agent-123',
+ sourceMessageId: 'user-msg-1',
+ threadId: 'thread-123',
+ topicId: 'topic-123',
+ },
+ });
+
+ await executors.call_llm!(
+ {
+ payload: {
+ messages: [{ content: 'Create a task', role: 'user' }],
+ model: 'gpt-4',
+ provider: 'openai',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ },
+ state,
+ );
+
+ expect(mockMessageModel.update).toHaveBeenCalledWith(
+ 'msg-123',
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ work: { rootOperationId: 'op-123', userMessageId: 'user-msg-1' },
+ }),
+ }),
+ );
+ });
+
+ it('does not mark ordinary replies because of older tool calls from another turn', async () => {
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState({
+ messages: [
+ { content: 'Old request', id: 'old-user-msg', role: 'user' },
+ {
+ content: '',
+ id: 'old-assistant-tool-msg',
+ role: 'assistant',
+ tool_calls: [{ function: { arguments: '{}', name: 'createTask' }, id: 'old_call' }],
+ },
+ { content: 'old result', id: 'old-tool-msg', role: 'tool', tool_call_id: 'old_call' },
+ { content: 'What model are you?', id: 'user-msg-2', role: 'user' },
+ ] as any,
+ metadata: {
+ agentId: 'agent-123',
+ sourceMessageId: 'user-msg-2',
+ threadId: 'thread-123',
+ topicId: 'topic-123',
+ },
+ });
+
+ await executors.call_llm!(
+ {
+ payload: {
+ messages: [{ content: 'What model are you?', role: 'user' }],
+ model: 'gpt-4',
+ provider: 'openai',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ },
+ state,
+ );
+
+ const updatePayload = mockMessageModel.update.mock.calls.at(-1)?.[1];
+ // Before the current-turn slice, any historical tool call could make this
+ // unrelated assistant reply render work cards after refresh.
+ expect(updatePayload?.metadata?.work).toBeUndefined();
+ });
+
// Gemini 2.5+/3 thinking streams deliver assistant text/reasoning as
// content_part / reasoning_part events instead of plain text / reasoning.
// These must be captured or the turn finalizes to a blank `done`.
@@ -2878,6 +2996,58 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
);
});
+ it('registers a Work version once with its cumulative cost from the executor intent', async () => {
+ const executors = createRuntimeExecutors(ctx);
+ // The executor now hands back a registration intent instead of writing the
+ // Work itself; the runtime persists it after cost is accumulated, stamping
+ // cumulativeCost + provenance (source message = the just-created tool msg).
+ mockToolExecutionService.executeTool.mockResolvedValueOnce({
+ content: 'ok',
+ error: null,
+ executionTime: 100,
+ state: {},
+ success: true,
+ workRegistration: {
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: 'task_x', taskIdentifier: 'T-X' }],
+ type: 'task',
+ },
+ });
+ const state = createMockState({ cost: { ...createMockCost(), total: 0.02 } });
+
+ const instruction = {
+ payload: {
+ parentMessageId: 'assistant-msg-intent',
+ toolCalling: {
+ apiName: 'createTask',
+ arguments: '{"name":"A"}',
+ id: 'tool-call-intent',
+ identifier: 'lobe-task',
+ type: 'builtin' as const,
+ },
+ },
+ type: 'call_tool' as const,
+ };
+
+ await executors.call_tool!(instruction, state);
+
+ expect(mockRegisterTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cumulativeCost: 0.02,
+ cumulativeUsage: expect.objectContaining({
+ cost: expect.objectContaining({ total: 0.02 }),
+ }),
+ changeType: 'created',
+ messageId: 'msg-123',
+ taskId: 'task_x',
+ taskIdentifier: 'T-X',
+ toolCallId: 'tool-call-intent',
+ toolName: 'createTask',
+ }),
+ );
+ });
+
it('should return tool message ID as parentMessageId in nextContext for parentId chain', async () => {
// Setup: mock messageModel.create to return a specific tool message ID
const toolMessageId = 'tool-msg-789';
@@ -3534,6 +3704,85 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
);
});
+ it('registers each batch tool Work version once with its own cumulative cost + provenance', async () => {
+ // Each executor result carries a task registration intent; the batch
+ // persists it ONCE per tool, stamping that call's cumulative cost and the
+ // just-created tool message as the source — no cost-less insert + backfill.
+ mockToolExecutionService.executeTool.mockImplementation((payload: any) =>
+ Promise.resolve({
+ content: 'ok',
+ error: null,
+ executionTime: 100,
+ state: {},
+ success: true,
+ workRegistration:
+ payload.id === 'tool-call-1'
+ ? {
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ type: 'task',
+ }
+ : {
+ action: 'update',
+ changeType: 'updated',
+ targets: [{ taskId: 'task_2', taskIdentifier: 'T-2' }],
+ type: 'task',
+ },
+ }),
+ );
+
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+
+ const instruction = {
+ payload: {
+ parentMessageId: 'assistant-msg-123',
+ toolsCalling: [
+ {
+ apiName: 'createTask',
+ arguments: '{"name":"A"}',
+ id: 'tool-call-1',
+ identifier: 'lobe-task',
+ type: 'default' as const,
+ },
+ {
+ apiName: 'updateTask',
+ arguments: '{"name":"B"}',
+ id: 'tool-call-2',
+ identifier: 'lobe-task',
+ type: 'default' as const,
+ },
+ ],
+ },
+ type: 'call_tools_batch' as const,
+ };
+
+ await executors.call_tools_batch!(instruction, state);
+
+ expect(mockRegisterTask).toHaveBeenCalledTimes(2);
+ const registerCalls = mockRegisterTask.mock.calls.map(([params]) => params);
+ expect(registerCalls).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ cumulativeUsage: expect.objectContaining({ cost: expect.any(Object) }),
+ changeType: 'created',
+ messageId: expect.stringMatching(/^tool-msg-/),
+ taskId: 'task_1',
+ toolCallId: 'tool-call-1',
+ toolName: 'createTask',
+ }),
+ expect.objectContaining({
+ changeType: 'updated',
+ messageId: expect.stringMatching(/^tool-msg-/),
+ taskId: 'task_2',
+ toolCallId: 'tool-call-2',
+ toolName: 'updateTask',
+ }),
+ ]),
+ );
+ });
+
it('should apply retry policy per tool in batch mode', async () => {
const attemptsByTool: Record<string, number> = {};
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/ToolResultWaiter.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/ToolResultWaiter.test.ts
index f5430a97d1b..e0f8a721161 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/ToolResultWaiter.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/ToolResultWaiter.test.ts
@@ -113,6 +113,21 @@ describe('ToolResultWaiter', () => {
expect(result).toEqual(payload);
});
+ it('preserves the workRegistration intent through the JSON roundtrip', async () => {
+ const { blockingClient, lpush, producingClient } = createMockRedisPair();
+ const payload: ToolResultPayload = {
+ content: 'task created',
+ success: true,
+ toolCallId: 'call-work',
+ workRegistration: { action: 'create', targets: [{ taskId: 't-1' }], type: 'task' },
+ };
+ lpush('tool_result:call-work', JSON.stringify(payload));
+
+ const waiter = new ToolResultWaiter(blockingClient, producingClient);
+ const result = await waiter.waitForResult('call-work', 5000);
+ expect(result).toEqual(payload);
+ });
+
it('returns the parsed payload when LPUSHed after BLPOP starts waiting', async () => {
const { blockingClient, lpush, producingClient } = createMockRedisPair();
const waiter = new ToolResultWaiter(blockingClient, producingClient);
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts
index 0261fffec5b..a1496096c05 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts
@@ -73,6 +73,7 @@ describe('dispatchClientTool', () => {
const streamManager = makeStreamManager(undefined);
const result = await dispatchClientTool(makePayload(), {
+ assistantMessageId: 'msg-assistant',
operationId: 'op-1',
streamManager,
});
@@ -87,8 +88,18 @@ describe('dispatchClientTool', () => {
const streamManager = makeStreamManager(vi.fn());
const result = await dispatchClientTool(makePayload(), {
+ agentId: 'agent-1',
+ assistantMessageId: 'msg-assistant',
+ documentId: 'doc-1',
+ groupId: 'group-1',
operationId: 'op-1',
+ rootOperationId: 'op-root',
+ scope: 'thread',
+ sourceMessageId: 'msg-user',
streamManager,
+ taskId: 'task-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
});
expect(result.success).toBe(false);
@@ -109,8 +120,18 @@ describe('dispatchClientTool', () => {
]);
const result = await dispatchClientTool(makePayload(), {
+ agentId: 'agent-1',
+ assistantMessageId: 'msg-assistant',
+ documentId: 'doc-1',
+ groupId: 'group-1',
operationId: 'op-1',
+ rootOperationId: 'op-root',
+ scope: 'thread',
+ sourceMessageId: 'msg-user',
streamManager,
+ taskId: 'task-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
});
expect(sendToolExecute).toHaveBeenCalledTimes(1);
@@ -118,8 +139,18 @@ describe('dispatchClientTool', () => {
expect(sendCall[0]).toBe('op-1');
expect(sendCall[1]).toMatchObject({
apiName: 'readFile',
+ agentId: 'agent-1',
+ assistantMessageId: 'msg-assistant',
+ documentId: 'doc-1',
+ groupId: 'group-1',
identifier: 'local-system',
+ rootOperationId: 'op-root',
+ scope: 'thread',
+ sourceMessageId: 'msg-user',
+ taskId: 'task-1',
+ threadId: 'thread-1',
toolCallId: 'call-1',
+ topicId: 'topic-1',
});
expect(result.success).toBe(true);
@@ -151,6 +182,50 @@ describe('dispatchClientTool', () => {
expect(result.state).toEqual(state);
});
+ it('forwards workRegistration from the BLPOP payload onto the execution result', async () => {
+ const sendToolExecute = vi.fn().mockResolvedValue(undefined);
+ const streamManager = makeStreamManager(sendToolExecute);
+
+ const workRegistration = {
+ action: 'create',
+ targets: [{ taskId: 'task-9' }],
+ type: 'task',
+ };
+ mockBlpop.mockResolvedValue([
+ 'tool_result:call-1',
+ JSON.stringify({
+ content: 'created',
+ success: true,
+ toolCallId: 'call-1',
+ workRegistration,
+ }),
+ ]);
+
+ const result = await dispatchClientTool(makePayload(), {
+ operationId: 'op-1',
+ streamManager,
+ });
+
+ expect(result.workRegistration).toEqual(workRegistration);
+ });
+
+ it('leaves workRegistration undefined when the BLPOP payload omits it', async () => {
+ const sendToolExecute = vi.fn().mockResolvedValue(undefined);
+ const streamManager = makeStreamManager(sendToolExecute);
+
+ mockBlpop.mockResolvedValue([
+ 'tool_result:call-1',
+ JSON.stringify({ content: 'ok', success: true, toolCallId: 'call-1' }),
+ ]);
+
+ const result = await dispatchClientTool(makePayload(), {
+ operationId: 'op-1',
+ streamManager,
+ });
+
+ expect(result.workRegistration).toBeUndefined();
+ });
+
it('returns a timeout result and still disconnects when BLPOP times out', async () => {
const sendToolExecute = vi.fn().mockResolvedValue(undefined);
const streamManager = makeStreamManager(sendToolExecute);
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index df329d1b395..c92a4e76bde 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -1,4 +1,10 @@
-import type { ToolRunContext, ToolRunExecution, ToolTransport } from '@lobechat/agent-runtime';
+import type {
+ AgentState,
+ ToolRunContext,
+ ToolRunExecution,
+ ToolTransport,
+ ToolWorkRegistration,
+} from '@lobechat/agent-runtime';
import { executeToolWithRetry } from '@lobechat/agent-runtime';
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import {
@@ -26,6 +32,7 @@ import {
GEN_AI_FUNCTION_TOOL_TYPE,
isOperationInterrupted,
log,
+ registerWorkFromIntent,
TOOL_MAX_RETRIES,
TOOL_PRICING,
} from '../executorHelpers';
@@ -42,6 +49,24 @@ export class ServerToolTransport implements ToolTransport {
return TOOL_PRICING[toolName] || 0;
}
+ async registerWork(registration: ToolWorkRegistration, state: AgentState): Promise<void> {
+ await registerWorkFromIntent({
+ agentId: state.metadata?.agentId ?? null,
+ intent: registration.intent,
+ rootOperationId: this.ctx.operationId,
+ serverDB: this.ctx.serverDB,
+ sourceMessageId: registration.sourceMessageId,
+ sourceToolCallId: registration.sourceToolCallId,
+ sourceToolIdentifier: registration.sourceToolIdentifier,
+ sourceToolName: registration.sourceToolName,
+ state: registration.state,
+ threadId: state.metadata?.threadId,
+ topicId: state.metadata?.topicId,
+ userId: this.ctx.userId,
+ workspaceId: state.metadata?.workspaceId ?? this.ctx.workspaceId,
+ });
+ }
+
async handleError(
chatToolPayload: ChatToolPayload,
error: unknown,
@@ -130,9 +155,19 @@ export class ServerToolTransport implements ToolTransport {
manifest: context.effectiveManifestMap[chatToolPayload.identifier],
});
const dispatchResult = await dispatchClientTool(chatToolPayload, {
+ agentId: context.state.metadata?.agentId,
+ assistantMessageId: context.parentMessageId,
+ documentId: context.state.metadata?.documentId,
+ groupId: context.state.metadata?.groupId,
operationId,
+ rootOperationId: operationId,
+ scope: context.state.metadata?.scope,
+ sourceMessageId: context.state.metadata?.sourceMessageId,
streamManager,
+ taskId: context.state.metadata?.taskId,
+ threadId: context.state.metadata?.threadId,
timeoutMs,
+ topicId: context.state.metadata?.topicId ?? this.ctx.topicId,
});
execution = { attempts: 1, result: dispatchResult };
} else {
@@ -162,6 +197,7 @@ export class ServerToolTransport implements ToolTransport {
context.parentMessageId,
),
...(agentVisibility !== undefined && { agentVisibility }),
+ // Assistant message owning this tool call (≠ source user message).
assistantMessageId: context.parentMessageId,
deviceCapable: context.state.metadata?.executionPlan
? isDeviceCapablePlan(context.state.metadata.executionPlan)
@@ -177,6 +213,7 @@ export class ServerToolTransport implements ToolTransport {
messageId: context.state.metadata?.sourceMessageId,
operationId,
projectSkills: resolveRunProjectSkills(context.state.metadata),
+ rootOperationId: operationId,
scope: context.state.metadata?.scope,
serverDB,
skipResultTruncation: true,
@@ -190,6 +227,7 @@ export class ServerToolTransport implements ToolTransport {
threadId: context.state.metadata?.threadId,
toolCallId: chatToolPayload.id,
toolManifestMap: context.effectiveManifestMap,
+ toolMessageId: context.toolMessageId,
toolResultMaxLength: context.toolResultMaxLength,
topicId: this.ctx.topicId,
userId,
diff --git a/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts b/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts
index 65724e905f7..1a21137f90f 100644
--- a/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts
+++ b/apps/server/src/modules/AgentRuntime/dispatchClientTool.ts
@@ -12,8 +12,18 @@ import type { IStreamEventManager } from './types';
const log = debug('lobe-server:agent-runtime:dispatch-client-tool');
interface DispatchContext {
+ agentId?: string | null;
+ /** Assistant message that carries this tool call. */
+ assistantMessageId?: string;
+ documentId?: string | null;
+ groupId?: string | null;
operationId: string;
+ rootOperationId?: string;
+ scope?: string | null;
+ sourceMessageId?: string | null;
streamManager: IStreamEventManager;
+ taskId?: string | null;
+ threadId?: string | null;
/**
* Per-call execution budget in milliseconds, normally produced by
* `resolveToolTimeoutMs`. When omitted, falls back to the global default
@@ -22,6 +32,7 @@ interface DispatchContext {
* a suggester, this dispatcher is the arbiter.
*/
timeoutMs?: number;
+ topicId?: string | null;
}
const clampTimeout = (value: number): number =>
@@ -98,11 +109,21 @@ export async function dispatchClientTool(
);
await streamManager.sendToolExecute(operationId, {
+ agentId: ctx.agentId,
apiName: chatToolPayload.apiName,
arguments: chatToolPayload.arguments,
+ assistantMessageId: ctx.assistantMessageId,
+ documentId: ctx.documentId,
executionTimeoutMs: timeoutMs,
+ groupId: ctx.groupId,
identifier: chatToolPayload.identifier,
+ rootOperationId: ctx.rootOperationId ?? operationId,
+ scope: ctx.scope,
+ sourceMessageId: ctx.sourceMessageId,
+ taskId: ctx.taskId,
+ threadId: ctx.threadId,
toolCallId: chatToolPayload.id,
+ topicId: ctx.topicId,
});
const result = await waiter.waitForResult(chatToolPayload.id, timeoutMs);
@@ -138,5 +159,8 @@ function projectToExecutionResult(
executionTime,
state: payload.state,
success: payload.success,
+ // Forward the client-relayed Work registration intent so the agent runtime
+ // loop calls `registerWork` (the persist path strips it — never hits the DB).
+ workRegistration: payload.workRegistration,
};
}
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index cf183495d5c..1dfdb38468b 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -1,11 +1,17 @@
import { type AgentState } from '@lobechat/agent-runtime';
import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
+import { dispatchWorkRegistrationIntent } from '@lobechat/builtin-tools/workRegistration';
import { resolveSubAgentModel } from '@lobechat/const';
import { type OperationToolSet } from '@lobechat/context-engine';
import { type ToolType } from '@lobechat/observability-otel/modules/agent-runtime';
-import { type ChatToolPayload, type LobeAgentConfig } from '@lobechat/types';
+import {
+ type ChatToolPayload,
+ type LobeAgentConfig,
+ type WorkRegistrationIntent,
+} from '@lobechat/types';
import debug from 'debug';
+import { WorkModel } from '@/database/models/work';
import { type LobeChatDatabase } from '@/database/type';
import { FileService } from '@/server/services/file';
import {
@@ -14,6 +20,7 @@ import {
type ToolExecutionResultResponse,
} from '@/server/services/toolExecution';
import { archiveToolResultIfNeeded } from '@/server/services/toolExecution/archiveToolResult';
+import { buildWorkVersionCumulativeUsage } from '@/utils/workCumulativeUsage';
import { type RuntimeExecutorContext } from './context';
@@ -67,6 +74,87 @@ export const archiveRuntimeToolResult = async (
return archive.content === result.content ? result : { ...result, content: archive.content };
};
+/**
+ * Persist a Work version from the executor's registration intent, stamping the
+ * tool call's cumulative cost/usage onto the row at insert time. Replaces the
+ * old "register cost-less in the executor, back-fill cost later" two-step: the
+ * executor now only resolves the intent, and the runtime writes it once here,
+ * after `accumulateTool` has computed the cumulative cost.
+ *
+ * Thin server wrapper around the shared {@link dispatchWorkRegistrationIntent}:
+ * builds `WorkModel`-backed ports (all five, incl. `deleteDocumentWork`) and
+ * per-call provenance, then delegates all branch logic.
+ *
+ * Best-effort: any failure is swallowed so Work bookkeeping never breaks the
+ * tool result. Runs AFTER `tool_end` publishes (cost is known only then), so
+ * the Work row becomes durable slightly later than the tool_end event — the
+ * conversation view self-heals from the tool message metadata; the works
+ * sidebar refresh gap is tracked as a follow-up.
+ */
+export const registerWorkFromIntent = async ({
+ agentId,
+ intent,
+ rootOperationId,
+ serverDB,
+ sourceMessageId,
+ sourceToolCallId,
+ sourceToolIdentifier,
+ sourceToolName,
+ state,
+ threadId,
+ topicId,
+ userId,
+ workspaceId,
+}: {
+ agentId?: string | null;
+ intent: WorkRegistrationIntent;
+ rootOperationId?: string;
+ serverDB: LobeChatDatabase;
+ sourceMessageId?: string;
+ sourceToolCallId?: string;
+ /** Tool/plugin identifier supplied by the runtime event that produced this version. */
+ sourceToolIdentifier: string;
+ /** Runtime event's concrete tool name; skills may override it with their own toolName. */
+ sourceToolName: string;
+ state: Pick<AgentState, 'cost' | 'usage'>;
+ threadId?: string | null;
+ topicId?: string;
+ userId?: string;
+ workspaceId?: string;
+}) => {
+ if (!userId) return;
+
+ const cumulative = buildWorkVersionCumulativeUsage({ cost: state.cost, usage: state.usage });
+
+ try {
+ const workModel = new WorkModel(serverDB, userId, workspaceId);
+
+ await dispatchWorkRegistrationIntent(
+ intent,
+ {
+ deleteDocumentWork: (params) => workModel.deleteDocumentWork(params),
+ deleteTaskWork: (params) => workModel.deleteTaskWork(params),
+ handleSkillToolResult: (params) => workModel.handleSkillToolResult(params),
+ registerDocument: (params) => workModel.registerDocument(params),
+ registerTask: (params) => workModel.registerTask(params),
+ },
+ {
+ agentId,
+ ...cumulative,
+ messageId: sourceMessageId,
+ rootOperationId,
+ threadId,
+ toolCallId: sourceToolCallId,
+ toolIdentifier: sourceToolIdentifier,
+ toolName: sourceToolName,
+ topicId,
+ },
+ );
+ } catch (error) {
+ log('registerWorkFromIntent failed for toolCallId=%s: %O', sourceToolCallId, error);
+ }
+};
+
// Builds a postProcessUrl callback that resolves keys in file-backed fields
// (imageList, videoList, fileList) to externally accessible URLs. Must be
// passed to every messageModel.query() call whose output is later fed to the
diff --git a/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts b/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts
index b739edc80f7..23a5c5888d6 100644
--- a/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts
@@ -10,9 +10,11 @@ import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocum
import { agentDocumentRouter } from '../agentDocument';
const agentDocumentMocks = vi.hoisted(() => ({
+ deleteDocumentWork: vi.fn(),
emitAgentDocumentToolOutcomeSafely: vi.fn(),
findTopicById: vi.fn(),
getServerDB: vi.fn(),
+ registerDocument: vi.fn(),
}));
vi.mock('@/database/core/db-adaptor', () => ({
@@ -38,6 +40,13 @@ vi.mock('@/database/models/topicDocument', () => ({
TopicDocumentModel: vi.fn(),
}));
+vi.mock('@/database/models/work', () => ({
+ WorkModel: vi.fn().mockImplementation(() => ({
+ deleteDocumentWork: agentDocumentMocks.deleteDocumentWork,
+ registerDocument: agentDocumentMocks.registerDocument,
+ })),
+}));
+
vi.mock('@/server/services/agentDocuments', () => ({
AgentDocumentsService: vi.fn(),
}));
@@ -55,6 +64,9 @@ const createCaller = createCallerFactory(agentDocumentRouter);
interface MockAgentDocumentsService {
createDocument: ReturnType<typeof vi.fn>;
createForTopic: ReturnType<typeof vi.fn>;
+ getDocumentById: ReturnType<typeof vi.fn>;
+ removeDocumentById: ReturnType<typeof vi.fn>;
+ renameDocumentById: ReturnType<typeof vi.fn>;
}
describe('agentDocumentRouter tool outcomes', () => {
@@ -69,12 +81,17 @@ describe('agentDocumentRouter tool outcomes', () => {
beforeEach(() => {
vi.clearAllMocks();
+ agentDocumentMocks.deleteDocumentWork.mockResolvedValue(undefined);
agentDocumentMocks.getServerDB.mockResolvedValue({ kind: 'server-db' });
agentDocumentMocks.findTopicById.mockResolvedValue({ title: 'Topic fallback' });
+ agentDocumentMocks.registerDocument.mockResolvedValue({ id: 'work-1' });
serviceImpl = {
createDocument: vi.fn().mockResolvedValue(createdDocument),
createForTopic: vi.fn().mockResolvedValue(createdDocument),
+ getDocumentById: vi.fn().mockResolvedValue(createdDocument),
+ removeDocumentById: vi.fn().mockResolvedValue(true),
+ renameDocumentById: vi.fn().mockResolvedValue({ ...createdDocument, title: 'Renamed' }),
};
vi.mocked(AgentDocumentsService).mockImplementation(
() => serviceImpl as unknown as AgentDocumentsService,
@@ -93,7 +110,9 @@ describe('agentDocumentRouter tool outcomes', () => {
messageId: 'message-1',
operationId: 'operation-1',
taskId: 'task-1',
+ threadId: 'thread-1',
toolCallId: 'tool-call-1',
+ toolMessageId: 'tool-message-1',
topicId: 'topic-1',
},
trigger: 'tool',
@@ -116,6 +135,9 @@ describe('agentDocumentRouter tool outcomes', () => {
userId: 'user-1',
}),
);
+ // Document Work registration moved to the client (legacy) runtime's stash +
+ // `call_tool` write-once path, so the lambda no longer registers on create.
+ expect(agentDocumentMocks.registerDocument).not.toHaveBeenCalled();
});
it('does not emit outcome for normal createDocument', async () => {
@@ -128,6 +150,7 @@ describe('agentDocumentRouter tool outcomes', () => {
});
expect(emitAgentDocumentToolOutcomeSafely).not.toHaveBeenCalled();
+ expect(agentDocumentMocks.registerDocument).not.toHaveBeenCalled();
});
it('rejects tool trigger without toolContext', async () => {
@@ -155,7 +178,9 @@ describe('agentDocumentRouter tool outcomes', () => {
messageId: 'message-1',
operationId: 'operation-1',
taskId: null,
+ threadId: 'thread-1',
toolCallId: 'tool-call-1',
+ toolMessageId: 'tool-message-1',
},
trigger: 'tool',
});
@@ -176,5 +201,53 @@ describe('agentDocumentRouter tool outcomes', () => {
userId: 'user-1',
}),
);
+ // See the createDocument case: registration is client-side now.
+ expect(agentDocumentMocks.registerDocument).not.toHaveBeenCalled();
+ });
+
+ it('does not register document work on the lambda for attributed renameDocument', async () => {
+ const caller = createCaller(await createContextInner({ userId: 'user-1' }));
+
+ await caller.renameDocument({
+ agentId: 'agent-1',
+ id: 'agent-document-1',
+ newTitle: 'Renamed',
+ toolContext: {
+ messageId: 'message-1',
+ operationId: 'operation-1',
+ rootOperationId: 'root-operation-1',
+ threadId: 'thread-rename',
+ toolCallId: 'tool-call-rename',
+ toolMessageId: 'tool-message-rename',
+ },
+ trigger: 'tool',
+ });
+
+ // The client runtime stashes the rename intent and writes the Work version
+ // once cost is known; the lambda mutation no longer registers Work.
+ expect(agentDocumentMocks.registerDocument).not.toHaveBeenCalled();
+ });
+
+ it('deletes document work for attributed removeDocument', async () => {
+ const caller = createCaller(await createContextInner({ userId: 'user-1' }));
+
+ await caller.removeDocument({
+ agentId: 'agent-1',
+ id: 'agent-document-1',
+ toolContext: {
+ messageId: 'message-1',
+ operationId: 'operation-1',
+ toolCallId: 'tool-call-remove',
+ },
+ trigger: 'tool',
+ });
+
+ expect(agentDocumentMocks.deleteDocumentWork).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentDocumentId: 'agent-document-1',
+ agentId: 'agent-1',
+ documentId: 'document-1',
+ }),
+ );
});
});
diff --git a/apps/server/src/routers/lambda/__tests__/work.test.ts b/apps/server/src/routers/lambda/__tests__/work.test.ts
new file mode 100644
index 00000000000..172ba3b153e
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/work.test.ts
@@ -0,0 +1,91 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// serverDatabase middleware calls getServerDB(); stub it (the WorkModel mock
+// below ignores the db handle anyway).
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => ({})),
+}));
+
+// RBAC gate → instead of enforcing a real permission, throw a sentinel that
+// carries the required permission code. This makes each write procedure's
+// declared gate observable end-to-end: whichever code a procedure passes
+// through surfaces as `GATE:<code>`, so the test asserts procedure → permission
+// mapping rather than just the set of codes requested at module load.
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn((code: string) => () => {
+ throw new Error(`GATE:${code}`);
+ }),
+}));
+
+const mockDeleteTaskWork = vi.fn();
+const mockRegisterTask = vi.fn();
+const mockRegisterDocument = vi.fn();
+const mockHandleSkillToolResult = vi.fn();
+const mockListByConversation = vi.fn();
+
+vi.mock('@/database/models/work', () => ({
+ WorkModel: vi.fn(() => ({
+ deleteTaskWork: mockDeleteTaskWork,
+ handleSkillToolResult: mockHandleSkillToolResult,
+ listByConversation: mockListByConversation,
+ registerDocument: mockRegisterDocument,
+ registerTask: mockRegisterTask,
+ })),
+}));
+
+// Imported after the mocks above are registered.
+const { workRouter } = await import('../work');
+
+const createCaller = () =>
+ workRouter.createCaller({ serverDB: {}, userId: 'user-1', workspaceId: 'ws-1' } as any);
+
+describe('workRouter — per-procedure write permission gates', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('registerDocument gates on document:update (aligned with document mutations)', async () => {
+ await expect(
+ createCaller().registerDocument({
+ changeType: 'created',
+ documentId: 'doc-1',
+ toolIdentifier: 'lobe-agent-documents',
+ toolName: 'tool',
+ }),
+ ).rejects.toThrow('GATE:document:update');
+ // The gate short-circuits before the model mutation runs.
+ expect(mockRegisterDocument).not.toHaveBeenCalled();
+ });
+
+ it('registerTask gates on agent:update (aligned with task mutations)', async () => {
+ await expect(
+ createCaller().registerTask({
+ changeType: 'created',
+ toolIdentifier: 'lobe-task',
+ toolName: 'tool',
+ }),
+ ).rejects.toThrow('GATE:agent:update');
+ expect(mockRegisterTask).not.toHaveBeenCalled();
+ });
+
+ it('deleteTaskWork gates on agent:update (aligned with task mutations)', async () => {
+ await expect(createCaller().deleteTaskWork({ taskId: 'task-1' })).rejects.toThrow(
+ 'GATE:agent:update',
+ );
+ expect(mockDeleteTaskWork).not.toHaveBeenCalled();
+ });
+
+ it('handleSkillToolResult keeps the general agent:update workspace-write gate', async () => {
+ await expect(
+ createCaller().handleSkillToolResult({ provider: 'linear', toolName: 'createIssue' }),
+ ).rejects.toThrow('GATE:agent:update');
+ expect(mockHandleSkillToolResult).not.toHaveBeenCalled();
+ });
+
+ it('read-only list procedures stay ungated', async () => {
+ mockListByConversation.mockResolvedValue([]);
+ await expect(createCaller().listByConversation({})).resolves.toEqual([]);
+ expect(mockListByConversation).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentDocument.ts b/apps/server/src/routers/lambda/agentDocument.ts
index 97e2176e534..c67a0898457 100644
--- a/apps/server/src/routers/lambda/agentDocument.ts
+++ b/apps/server/src/routers/lambda/agentDocument.ts
@@ -17,6 +17,7 @@ import { TopicDocumentModel } from '@/database/models/topicDocument';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
+import { createDocumentWorkRegistrar } from '@/server/services/agentDocuments/documentWork';
import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocuments/toolOutcome';
import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';
import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
@@ -95,8 +96,11 @@ const mountedSkillNamespaceSchema = z.literal('agent');
const agentDocumentToolContextSchema = z.object({
messageId: z.string(),
operationId: z.string().optional(),
+ rootOperationId: z.string().optional(),
taskId: z.string().nullish(),
+ threadId: z.string().nullish(),
toolCallId: z.string(),
+ toolMessageId: z.string().optional(),
topicId: z.string().optional(),
});
const agentDocumentToolTriggerSchema = z
@@ -166,6 +170,12 @@ const agentDocumentProcedure = wsCompatProcedure.use(serverDatabase).use(async (
agentDocumentVfsService: new AgentDocumentVfsService(ctx.serverDB, ctx.userId, wsId),
skillManagementService: new SkillManagementDocumentService(ctx.serverDB, ctx.userId, wsId),
systemAgentService: new SystemAgentService(ctx.serverDB, ctx.userId, wsId),
+ documentWorkRegistrar: createDocumentWorkRegistrar({
+ db: ctx.serverDB,
+ logPrefix: '[agentDocumentRouter]',
+ userId: ctx.userId,
+ workspaceId: wsId,
+ }),
topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),
topicDocumentModel: new TopicDocumentModel(ctx.serverDB, ctx.userId, wsId),
},
@@ -1097,18 +1107,22 @@ export const agentDocumentRouter = router({
*/
modifyNodes: agentDocumentProcedureWrite
.input(
- z.object({
- agentId: z.string(),
- id: z.string(),
- operations: z.array(liteXMLOperationSchema).min(1),
- }),
+ z
+ .object({
+ agentId: z.string(),
+ id: z.string(),
+ operations: z.array(liteXMLOperationSchema).min(1),
+ })
+ .and(agentDocumentToolTriggerSchema),
)
.mutation(async ({ ctx, input }) => {
- return ctx.agentDocumentService.modifyDocumentNodesById(
+ const doc = await ctx.agentDocumentService.modifyDocumentNodesById(
input.id,
input.operations,
input.agentId,
);
+
+ return doc;
}),
/**
@@ -1116,18 +1130,22 @@ export const agentDocumentRouter = router({
*/
replaceDocumentContent: agentDocumentProcedureWrite
.input(
- z.object({
- agentId: z.string(),
- content: z.string(),
- id: z.string(),
- }),
+ z
+ .object({
+ agentId: z.string(),
+ content: z.string(),
+ id: z.string(),
+ })
+ .and(agentDocumentToolTriggerSchema),
)
.mutation(async ({ ctx, input }) => {
- return ctx.agentDocumentService.replaceDocumentContentById(
+ const doc = await ctx.agentDocumentService.replaceDocumentContentById(
input.id,
input.content,
input.agentId,
);
+
+ return doc;
}),
/**
@@ -1135,13 +1153,24 @@ export const agentDocumentRouter = router({
*/
removeDocument: agentDocumentProcedureWrite
.input(
- z.object({
- agentId: z.string(),
- id: z.string(),
- }),
+ z
+ .object({
+ agentId: z.string(),
+ id: z.string(),
+ })
+ .and(agentDocumentToolTriggerSchema),
)
.mutation(async ({ ctx, input }) => {
+ const doc = await ctx.agentDocumentService.getDocumentById(input.id, input.agentId);
const deleted = await ctx.agentDocumentService.removeDocumentById(input.id, input.agentId);
+ if (deleted && input.trigger === 'tool') {
+ await ctx.documentWorkRegistrar.deleteDocumentWork({
+ agentDocumentId: input.id,
+ agentId: input.agentId,
+ documentId: doc?.documentId,
+ });
+ }
+
return { deleted, id: input.id };
}),
@@ -1150,19 +1179,23 @@ export const agentDocumentRouter = router({
*/
copyDocument: agentDocumentProcedureWrite
.input(
- z.object({
- agentId: z.string(),
- id: z.string(),
- newTitle: z.string().optional(),
- }),
+ z
+ .object({
+ agentId: z.string(),
+ id: z.string(),
+ newTitle: z.string().optional(),
+ })
+ .and(agentDocumentToolTriggerSchema),
)
.mutation(async ({ ctx, input }) => {
try {
- return await ctx.agentDocumentService.copyDocumentById(
+ const doc = await ctx.agentDocumentService.copyDocumentById(
input.id,
input.newTitle,
input.agentId,
);
+
+ return doc;
} catch (error) {
handleAgentDocumentVfsError(error);
}
@@ -1173,19 +1206,23 @@ export const agentDocumentRouter = router({
*/
renameDocument: agentDocumentProcedureWrite
.input(
- z.object({
- agentId: z.string(),
- id: z.string(),
- newTitle: z.string(),
- }),
+ z
+ .object({
+ agentId: z.string(),
+ id: z.string(),
+ newTitle: z.string(),
+ })
+ .and(agentDocumentToolTriggerSchema),
)
.mutation(async ({ ctx, input }) => {
try {
- return await ctx.agentDocumentService.renameDocumentById(
+ const doc = await ctx.agentDocumentService.renameDocumentById(
input.id,
input.newTitle,
input.agentId,
);
+
+ return doc;
} catch (error) {
handleAgentDocumentVfsError(error);
}
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index 3cc3d17d1b3..af61431ebb9 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -83,6 +83,7 @@ import { userMemoryRouter } from './userMemory';
import { verifyRouter } from './verify';
import { videoRouter } from './video';
import { webBrowsingRouter } from './webBrowsing';
+import { workRouter } from './work';
import { workspaceUserSettingsRouter } from './workspaceUserSettings';
export const lambdaRouter = router({
@@ -153,6 +154,7 @@ export const lambdaRouter = router({
verify: verifyRouter,
video: videoRouter,
webBrowsing: webBrowsingRouter,
+ work: workRouter,
workspace: workspaceRouter,
workspaceAuditLog: workspaceAuditLogRouter,
workspaceCreds: workspaceCredsRouter,
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 404df4427bb..8609ef12497 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -290,6 +290,9 @@ export const messageRouter = router({
groupId: z.string().nullish(),
pageSize: z.number().optional(),
sessionId: z.string().nullish(),
+ // Mid-stream refetches skip the Work-summary assembly — see
+ // `QueryMessageParams.skipWorks`.
+ skipWorks: z.boolean().optional(),
threadId: z.string().nullish(),
topicId: z.string().nullish(),
topicShareId: z.string().optional(),
@@ -314,7 +317,10 @@ export const messageRouter = router({
const fileService = new FileService(ctx.serverDB, share.ownerId, shareWorkspaceId);
return messageModel.query(
- { ...queryParams, topicId: share.topicId },
+ // Force skipWorks: Work summaries join LIVE task/version state (not a
+ // share-time snapshot), so serving them here would leak post-share
+ // mutations to anonymous visitors. Share pages render no Work chips.
+ { ...queryParams, skipWorks: true, topicId: share.topicId },
{
postProcessUrl: (path, file) =>
fileService.getFileAccessUrl({ id: file.id, url: path }),
diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.ts
new file mode 100644
index 00000000000..1f3a6889c77
--- /dev/null
+++ b/apps/server/src/routers/lambda/work.ts
@@ -0,0 +1,174 @@
+import {
+ type RegisterDocumentWorkParams,
+ type RegisterSkillToolResultWorkParams,
+ type RegisterTaskWorkParams,
+ WORK_SKILL_PROVIDERS,
+ type WorkVersionCumulativeUsage,
+} from '@lobechat/types';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { WorkModel } from '@/database/models/work';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+
+const workProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const wsId = ctx.workspaceId ?? undefined;
+
+ return opts.next({
+ ctx: {
+ workModel: new WorkModel(ctx.serverDB, ctx.userId, wsId),
+ },
+ });
+});
+
+// Task-domain write gate. Task mutations elsewhere (see the task router's
+// `taskProcedureWrite`) gate on `agent:update`, so a Work registration that
+// records a task mutation must require the same permission — otherwise a role
+// that can't mutate tasks could still forge (or be denied) task provenance.
+const taskWorkProcedureWrite = workProcedure.use(withScopedPermission('agent:update'));
+
+// Document-domain write gate. Document mutations (see the document router)
+// gate on `document:update`; the document Work registration is the provenance
+// side of the same mutation and must align, so a role with `agent:update` but
+// without `document:update` can't forge document provenance, and a document-only
+// role's legitimate registration isn't rejected.
+const documentWorkProcedureWrite = workProcedure.use(withScopedPermission('document:update'));
+
+// Skill tool results (external skill providers, e.g. linear/github) touch no
+// first-class workspace resource with its own permission domain, so there is no
+// narrower gate to align with; keep the general `agent:update` workspace-write gate.
+const skillWorkProcedureWrite = workProcedure.use(withScopedPermission('agent:update'));
+
+const versionChangeTypeSchema = z.enum(['created', 'updated']);
+
+const cumulativeUsageSchema = z.object({
+ capturedAt: z.string(),
+ cost: z.unknown().optional(),
+ usage: z.unknown().optional(),
+}) satisfies z.ZodType<WorkVersionCumulativeUsage>;
+
+// Every register* schema must accept `cumulativeCost` / `cumulativeUsage`: the
+// client-first runtime stamps the tool call's cumulative cost onto the
+// registration (see registerClientWorkFromIntent), and `z.object` strips
+// undeclared keys — omitting them here silently stores cost-less versions.
+const registerTaskSchema = z.object({
+ agentId: z.string().nullable().optional(),
+ cumulativeCost: z.number().nullable().optional(),
+ cumulativeUsage: cumulativeUsageSchema.nullable().optional(),
+ changeType: versionChangeTypeSchema,
+ messageId: z.string().nullable().optional(),
+ rootOperationId: z.string().nullable().optional(),
+ taskId: z.string().optional(),
+ taskIdentifier: z.string().optional(),
+ threadId: z.string().nullable().optional(),
+ toolCallId: z.string().nullable().optional(),
+ toolIdentifier: z.string().min(1),
+ toolName: z.string().min(1),
+ topicId: z.string().nullable().optional(),
+}) satisfies z.ZodType<RegisterTaskWorkParams>;
+
+const registerSkillToolResultSchema = z.object({
+ agentId: z.string().nullable().optional(),
+ args: z.record(z.string(), z.unknown()).optional(),
+ cumulativeCost: z.number().nullable().optional(),
+ cumulativeUsage: cumulativeUsageSchema.nullable().optional(),
+ data: z.unknown().optional(),
+ messageId: z.string().nullable().optional(),
+ provider: z.string().min(1),
+ rootOperationId: z.string().nullable().optional(),
+ threadId: z.string().nullable().optional(),
+ toolCallId: z.string().nullable().optional(),
+ toolName: z.string().min(1),
+ topicId: z.string().nullable().optional(),
+}) satisfies z.ZodType<RegisterSkillToolResultWorkParams>;
+
+const registerDocumentSchema = z.object({
+ agentDocumentId: z.string().nullable().optional(),
+ agentId: z.string().nullable().optional(),
+ cumulativeCost: z.number().nullable().optional(),
+ cumulativeUsage: cumulativeUsageSchema.nullable().optional(),
+ description: z.string().nullable().optional(),
+ documentId: z.string().min(1),
+ changeType: versionChangeTypeSchema,
+ messageId: z.string().nullable().optional(),
+ rootOperationId: z.string().nullable().optional(),
+ threadId: z.string().nullable().optional(),
+ toolCallId: z.string().nullable().optional(),
+ toolIdentifier: z.string().min(1),
+ toolName: z.string().min(1),
+ topicId: z.string().nullable().optional(),
+}) satisfies z.ZodType<RegisterDocumentWorkParams>;
+
+export const workRouter = router({
+ listByConversation: workProcedure
+ .input(
+ z.object({
+ limit: z.number().min(1).max(100).default(50),
+ threadId: z.string().nullable().optional(),
+ topicId: z.string().nullable().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => ctx.workModel.listByConversation(input)),
+
+ listByWorkspace: workProcedure
+ .input(
+ z.object({
+ cursor: z.string().nullable().optional(),
+ limit: z.number().min(1).max(100).default(30),
+ provider: z.enum(WORK_SKILL_PROVIDERS).optional(),
+ type: z.enum(['task', 'document', 'external']).nullable().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => ctx.workModel.listByWorkspace(input)),
+
+ listByRootOperation: workProcedure
+ .input(
+ z.object({
+ limit: z.number().min(1).max(50).default(20),
+ rootOperationId: z.string().nullable().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) =>
+ ctx.workModel.listByRootOperation({
+ limit: input.limit,
+ rootOperationId: input.rootOperationId,
+ }),
+ ),
+
+ listByRootOperations: workProcedure
+ .input(
+ z.object({
+ limit: z.number().min(1).max(50).default(20),
+ rootOperationIds: z.array(z.string()).max(100).nullable().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) =>
+ ctx.workModel.listByRootOperations({
+ limit: input.limit,
+ rootOperationIds: input.rootOperationIds,
+ }),
+ ),
+
+ listVersions: workProcedure
+ .input(z.object({ workId: z.string().min(1) }))
+ .query(async ({ ctx, input }) => ctx.workModel.listVersions(input.workId)),
+
+ deleteTaskWork: taskWorkProcedureWrite
+ .input(z.object({ taskId: z.string().min(1) }))
+ .mutation(async ({ ctx, input }) => ctx.workModel.deleteTaskWork(input)),
+
+ registerTask: taskWorkProcedureWrite
+ .input(registerTaskSchema)
+ .mutation(async ({ ctx, input }) => ctx.workModel.registerTask(input)),
+
+ registerDocument: documentWorkProcedureWrite
+ .input(registerDocumentSchema)
+ .mutation(async ({ ctx, input }) => ctx.workModel.registerDocument(input)),
+
+ handleSkillToolResult: skillWorkProcedureWrite
+ .input(registerSkillToolResultSchema)
+ .mutation(async ({ ctx, input }) => ctx.workModel.handleSkillToolResult(input)),
+});
diff --git a/apps/server/src/services/agentDocuments/documentWork.ts b/apps/server/src/services/agentDocuments/documentWork.ts
new file mode 100644
index 00000000000..7c859961352
--- /dev/null
+++ b/apps/server/src/services/agentDocuments/documentWork.ts
@@ -0,0 +1,95 @@
+import { buildAgentDocumentUrl } from '@lobechat/builtin-tool-agent-documents';
+
+import { WorkModel } from '@/database/models/work';
+import { WorkspaceModel } from '@/database/models/workspace';
+import type { LobeChatDatabase } from '@/database/type';
+import { appEnv } from '@/envs/app';
+
+const getAgentDocumentAppUrl = (): string | undefined => {
+ try {
+ return appEnv.APP_URL;
+ } catch {
+ return process.env.APP_URL;
+ }
+};
+
+/**
+ * Shared best-effort agent-document Work helpers for the server tool runtime
+ * and the lambda `agentDocument` router: document URL building (used when the
+ * server runtime registers Work) and Work deletion (used by the lambda's
+ * removeDocument mutation). Registration itself now lives with each caller —
+ * the server runtime writes Work with cost inline, and the legacy client
+ * runtime stashes an intent that `call_tool` writes once — so this registrar no
+ * longer owns a `registerDocumentWork`. Failures are swallowed on purpose: Work
+ * bookkeeping must never fail the document operation itself.
+ *
+ * The workspace slug lookup for URL building is memoized per registrar
+ * instance, so create one registrar per runtime/request and reuse it.
+ */
+export const createDocumentWorkRegistrar = (deps: {
+ db: LobeChatDatabase;
+ /** Log prefix identifying the call site, e.g. '[agentDocumentsRuntime]'. */
+ logPrefix: string;
+ userId: string;
+ workspaceId?: string | null;
+}) => {
+ const workModel = new WorkModel(deps.db, deps.userId, deps.workspaceId ?? undefined);
+ let workspaceSlugPromise: Promise<string | undefined> | undefined;
+
+ const resolveWorkspaceSlugForUrl = async (): Promise<string | undefined> => {
+ if (!deps.workspaceId) return undefined;
+
+ workspaceSlugPromise ??= new WorkspaceModel(deps.db, deps.userId)
+ .findById(deps.workspaceId)
+ .then((workspace) => workspace?.slug)
+ .catch((error) => {
+ console.error(
+ `${deps.logPrefix} Failed to resolve workspace slug:`,
+ { userId: deps.userId, workspaceId: deps.workspaceId },
+ error,
+ );
+ return undefined;
+ });
+
+ return workspaceSlugPromise;
+ };
+
+ const buildRegisteredDocumentUrl = async (agentId: string, documentId?: string | null) => {
+ if (!documentId) return undefined;
+ const workspaceSlug = await resolveWorkspaceSlugForUrl();
+ if (deps.workspaceId && !workspaceSlug) return undefined;
+
+ return buildAgentDocumentUrl(getAgentDocumentAppUrl(), agentId, documentId, {
+ workspaceSlug,
+ });
+ };
+
+ const deleteDocumentWork = async (input: {
+ agentDocumentId?: string | null;
+ agentId: string;
+ documentId?: string | null;
+ }) => {
+ if (!input.documentId) return;
+
+ try {
+ await workModel.deleteDocumentWork({
+ agentDocumentId: input.agentDocumentId,
+ agentId: input.agentId,
+ documentId: input.documentId,
+ });
+ } catch (error) {
+ console.error(
+ `${deps.logPrefix} delete document work failed:`,
+ {
+ agentDocumentId: input.agentDocumentId,
+ documentId: input.documentId,
+ },
+ error,
+ );
+ }
+ };
+
+ return { buildRegisteredDocumentUrl, deleteDocumentWork };
+};
+
+export type DocumentWorkRegistrar = ReturnType<typeof createDocumentWorkRegistrar>;
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index ac9c4f279b1..a94b056988b 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -681,7 +681,19 @@ export class AgentRuntimeService {
* bootstrap before the topic row has been committed) so callers can skip
* the `uiMessages` field entirely instead of pushing an empty array.
*/
- async queryUiMessages(agentState: AgentState): Promise<UIChatMessage[] | undefined> {
+ async queryUiMessages(
+ agentState: AgentState,
+ options?: {
+ /**
+ * Skip the Work-summary assembly for mid-stream (step_start) snapshots —
+ * each step would otherwise re-run the per-type Work queries. Terminal
+ * (agent_runtime_end) snapshots keep works so the settled message list
+ * carries the round's Work chips. The client preserves previously
+ * rendered works when applying a skipped snapshot (`preserveWorks`).
+ */
+ skipWorks?: boolean;
+ },
+ ): Promise<UIChatMessage[] | undefined> {
const agentId: string | undefined = agentState?.metadata?.agentId;
const topicId: string | undefined = agentState?.metadata?.topicId;
// groupId scopes group conversations. Without it the query falls into the
@@ -691,7 +703,12 @@ export class AgentRuntimeService {
if (!agentId || !topicId) return undefined;
try {
- return await this.messageService.queryMessages({ agentId, groupId, topicId });
+ return await this.messageService.queryMessages({
+ agentId,
+ groupId,
+ skipWorks: options?.skipWorks,
+ topicId,
+ });
} catch (error) {
// Stream events must never fail the step. If the DB hiccups, fall back
// to letting the client refresh as before.
@@ -841,7 +858,7 @@ export class AgentRuntimeService {
throw new Error(`Agent state not found for operation ${operationId}`);
}
- const stepStartUiMessages = await this.queryUiMessages(agentState);
+ const stepStartUiMessages = await this.queryUiMessages(agentState, { skipWorks: true });
await this.streamManager.publishStreamEvent(operationId, {
data: {
...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }),
diff --git a/apps/server/src/services/gateway/MessageGatewayClient.ts b/apps/server/src/services/gateway/MessageGatewayClient.ts
index 92a64d95c40..102c42ceaa9 100644
--- a/apps/server/src/services/gateway/MessageGatewayClient.ts
+++ b/apps/server/src/services/gateway/MessageGatewayClient.ts
@@ -90,7 +90,7 @@ export class MessageGatewayClient {
async connect(
config: MessageGatewayConnectionConfig,
options?: { ensure?: boolean },
- ): Promise<{ status: string }> {
+ ): Promise<{ status: MessageGatewayConnectionStatus['state']['status'] }> {
log('Connecting %s:%s (platform=%s)', config.connectionId, config.userId, config.platform);
const res = await this.post('/api/connections', { config, ensure: options?.ensure });
diff --git a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts b/apps/server/src/services/gateway/__tests__/GatewayService.test.ts
index e663b45d9be..86cc2c03694 100644
--- a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts
+++ b/apps/server/src/services/gateway/__tests__/GatewayService.test.ts
@@ -77,6 +77,7 @@ vi.mock('../runtimeStatus', () => ({
BOT_RUNTIME_STATUSES: {
connected: 'connected',
disconnected: 'disconnected',
+ dormant: 'dormant',
failed: 'failed',
queued: 'queued',
starting: 'starting',
@@ -342,6 +343,39 @@ describe('GatewayService', () => {
);
});
+ it('persists a dormant ensure result as dormant, not starting', async () => {
+ // An `ensure` reconcile of a sparse-polling DO can legitimately return
+ // `dormant`; it must be mapped through the shared helper so it is not
+ // collapsed to `starting` (the DO sends no correcting callback).
+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
+ platform === 'discord'
+ ? [
+ {
+ applicationId: 'app-1',
+ credentials: { token: 'x' },
+ id: 'prov-1',
+ settings: {},
+ userId: 'u1',
+ },
+ ]
+ : [],
+ );
+ mockResolveConnectionMode.mockReturnValue('websocket');
+ mockGatewayClient.getStatus.mockResolvedValue({
+ state: { status: 'disconnected' },
+ });
+ mockGatewayClient.connect.mockResolvedValue({ status: 'dormant' });
+
+ await service.ensureRunning();
+
+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'dormant' }),
+ );
+ expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'starting' }),
+ );
+ });
+
it('disconnects paid-only WeChat providers when the owner is on a free plan', async () => {
mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>
platform === 'wechat'
diff --git a/apps/server/src/services/gateway/index.ts b/apps/server/src/services/gateway/index.ts
index ace7d967908..29e1f9953b1 100644
--- a/apps/server/src/services/gateway/index.ts
+++ b/apps/server/src/services/gateway/index.ts
@@ -250,14 +250,16 @@ export class GatewayService {
);
// Gateway returns "connecting" for async persistent connections
- // (e.g. Discord WebSocket), "connected" for sync webhook-mode.
+ // (e.g. Discord WebSocket), "connected" for sync webhook-mode. An
+ // `ensure` reconcile can also legitimately return "dormant" (the DO is
+ // sparse-polling and won't send a correcting callback), so map through
+ // the shared helper instead of collapsing every non-connected result
+ // to "starting" — otherwise a dormant connection is persisted as
+ // starting and never corrected.
await updateBotRuntimeStatus({
applicationId: provider.applicationId,
platform,
- status:
- result.status === 'connected'
- ? BOT_RUNTIME_STATUSES.connected
- : BOT_RUNTIME_STATUSES.starting,
+ status: mapGatewayStatusToRuntimeStatus(result.status),
});
connected++;
diff --git a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts b/apps/server/src/services/toolExecution/__tests__/builtin.test.ts
index 76ab615b4d3..6b95799bbc1 100644
--- a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/builtin.test.ts
@@ -4,18 +4,24 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { BuiltinToolsExecutor } from '../builtin';
import type { ToolExecutionContext } from '../types';
-const mockApiHandler = vi.fn();
+const mocks = vi.hoisted(() => ({
+ apiHandler: vi.fn(),
+ executeLobehubSkill: vi.fn(),
+}));
+const mockApiHandler = mocks.apiHandler;
vi.mock('../serverRuntimes', () => ({
hasServerRuntime: vi.fn().mockReturnValue(true),
- getServerRuntime: vi.fn(async () => ({ createDocument: mockApiHandler })),
+ getServerRuntime: vi.fn(async () => ({ createDocument: mocks.apiHandler })),
}));
vi.mock('@/server/services/composio', () => ({
ComposioService: vi.fn().mockImplementation(() => ({})),
}));
vi.mock('@/server/services/market', () => ({
- MarketService: vi.fn().mockImplementation(() => ({})),
+ MarketService: vi.fn().mockImplementation(() => ({
+ executeLobehubSkill: mocks.executeLobehubSkill,
+ })),
}));
// The runtime mock above only exposes `createDocument`, but the manifest is the
@@ -27,6 +33,17 @@ vi.mock('@lobechat/builtin-tools', () => ({
identifier: 'lobe-notebook',
manifest: { api: [{ name: 'createDocument' }, { name: 'listDocuments' }] },
},
+ {
+ identifier: 'lobe-task',
+ manifest: {
+ api: [
+ { name: 'createTask', work: { action: 'create', resourceType: 'task' } },
+ { name: 'createTasks', work: { action: 'create', resourceType: 'task' } },
+ { name: 'editTask', work: { action: 'update', resourceType: 'task' } },
+ { name: 'listTasks' },
+ ],
+ },
+ },
],
}));
@@ -48,6 +65,7 @@ describe('BuiltinToolsExecutor truncated arguments', () => {
beforeEach(() => {
mockApiHandler.mockReset();
+ mocks.executeLobehubSkill.mockReset();
});
it('short-circuits with TRUNCATED_ARGUMENTS when JSON is cut mid-object', async () => {
@@ -178,4 +196,233 @@ describe('BuiltinToolsExecutor truncated arguments', () => {
expect(result.error?.code).toBe('UNKNOWN_API');
expect(result.content).toContain('barApi');
});
+
+ it('emits a Linear skill Work intent after a successful server-side LobeHub Skill tool call', async () => {
+ mocks.executeLobehubSkill.mockResolvedValueOnce({
+ content: JSON.stringify({
+ id: 'LOBE-10966',
+ status: 'In Progress',
+ title: 'Linear Work issue',
+ url: 'https://linear.app/lobehub/issue/LOBE-10966/linear-work-issue',
+ }),
+ success: true,
+ });
+
+ const result = await executor.execute(
+ {
+ apiName: 'save_issue',
+ arguments: '{"id":"LOBE-10966","state":"In Progress"}',
+ id: 'tool-call-linear',
+ identifier: 'linear',
+ source: 'lobehubSkill',
+ type: 'default' as any,
+ },
+ { ...context, topicId: 'topic-1' },
+ );
+
+ expect(result.success).toBe(true);
+ expect(mocks.executeLobehubSkill).toHaveBeenCalledWith({
+ args: { id: 'LOBE-10966', state: 'In Progress' },
+ context: { topicId: 'topic-1' },
+ provider: 'linear',
+ toolName: 'save_issue',
+ });
+ // The executor no longer writes the Work — it hands the runtime an intent
+ // carrying the UNTRUNCATED payload; provenance + cost are stamped by the
+ // agent runtime at persist time.
+ expect(result.workRegistration).toEqual({
+ args: { id: 'LOBE-10966', state: 'In Progress' },
+ data: {
+ id: 'LOBE-10966',
+ status: 'In Progress',
+ title: 'Linear Work issue',
+ url: 'https://linear.app/lobehub/issue/LOBE-10966/linear-work-issue',
+ },
+ provider: 'linear',
+ toolName: 'save_issue',
+ type: 'skill',
+ });
+ });
+
+ it('emits a GitHub skill Work intent after a successful server-side LobeHub Skill tool call', async () => {
+ mocks.executeLobehubSkill.mockResolvedValueOnce({
+ content: JSON.stringify({
+ html_url: 'https://github.com/lobehub/lobehub/issues/123',
+ node_id: 'I_kwDOJj1234',
+ number: 123,
+ state: 'open',
+ title: 'GitHub Work issue',
+ }),
+ success: true,
+ });
+
+ const result = await executor.execute(
+ {
+ apiName: 'create_issue',
+ arguments: '{"owner":"lobehub","repo":"lobehub","title":"GitHub Work issue"}',
+ id: 'tool-call-github',
+ identifier: 'github',
+ source: 'lobehubSkill',
+ type: 'default' as any,
+ },
+ { ...context, topicId: 'topic-1' },
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.workRegistration).toEqual(
+ expect.objectContaining({
+ data: expect.objectContaining({ number: 123 }),
+ provider: 'github',
+ toolName: 'create_issue',
+ type: 'skill',
+ }),
+ );
+ });
+
+ it('emits no Work intent for non-adapted skill providers', async () => {
+ mocks.executeLobehubSkill.mockResolvedValueOnce({
+ content: JSON.stringify({ id: 'msg-1' }),
+ success: true,
+ });
+
+ const result = await executor.execute(
+ {
+ apiName: 'send_message',
+ arguments: '{}',
+ id: 'tool-call-ms',
+ identifier: 'microsoft',
+ source: 'lobehubSkill',
+ type: 'default' as any,
+ },
+ { ...context, topicId: 'topic-1' },
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.workRegistration).toBeUndefined();
+ });
+});
+
+describe('BuiltinToolsExecutor manifest-driven Work registration', () => {
+ const executor = new BuiltinToolsExecutor({} as any, 'user-1');
+
+ const taskContext: ToolExecutionContext = {
+ agentId: 'agent-1',
+ operationId: 'op-child',
+ rootOperationId: 'op-root',
+ serverDB: {} as NonNullable<ToolExecutionContext['serverDB']>,
+ threadId: 'thread-1',
+ toolCallId: 'tool-call-task',
+ toolManifestMap: {},
+ toolMessageId: 'msg-tool-task',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ };
+
+ const taskPayload = (apiName: string, argsStr = '{}'): ChatToolPayload => ({
+ apiName,
+ arguments: argsStr,
+ id: 'tool-call-task',
+ identifier: 'lobe-task',
+ type: 'default' as any,
+ });
+
+ it('emits a task Work intent after a successful createTask, reading identity from state', async () => {
+ const { getServerRuntime } = await import('../serverRuntimes');
+ vi.mocked(getServerRuntime).mockResolvedValueOnce({
+ createTask: vi.fn().mockResolvedValue({
+ content: 'ok',
+ state: { identifier: 'T-1', success: true, taskId: 'task_1' },
+ success: true,
+ }),
+ } as any);
+
+ const result = await executor.execute(
+ taskPayload('createTask', '{"name":"A","instruction":"do"}'),
+ taskContext,
+ );
+
+ expect(result.success).toBe(true);
+ // Provenance (agent / operation / message / tool-call ids) is added by the
+ // agent runtime at persist time, so the intent carries only the resolved
+ // action + targets.
+ expect(result.workRegistration).toEqual({
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ type: 'task',
+ });
+ });
+
+ it('emits an intent for only the succeeded items of a partial-failure batch', async () => {
+ const { getServerRuntime } = await import('../serverRuntimes');
+ vi.mocked(getServerRuntime).mockResolvedValueOnce({
+ createTasks: vi.fn().mockResolvedValue({
+ content: 'ok',
+ state: {
+ failed: 1,
+ results: [
+ { identifier: 'T-A', name: 'A', success: true },
+ { error: 'boom', name: 'B', success: false },
+ ],
+ succeeded: 1,
+ },
+ success: false,
+ }),
+ } as any);
+
+ const result = await executor.execute(taskPayload('createTasks', '{"tasks":[]}'), taskContext);
+
+ expect(result.workRegistration).toEqual({
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskIdentifier: 'T-A' }],
+ type: 'task',
+ });
+ });
+
+ it('emits no intent for an API without a work config', async () => {
+ const { getServerRuntime } = await import('../serverRuntimes');
+ vi.mocked(getServerRuntime).mockResolvedValueOnce({
+ listTasks: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
+ } as any);
+
+ const result = await executor.execute(taskPayload('listTasks'), taskContext);
+
+ expect(result.workRegistration).toBeUndefined();
+ });
+
+ it('emits no intent when the update failed (no extractable target)', async () => {
+ const { getServerRuntime } = await import('../serverRuntimes');
+ vi.mocked(getServerRuntime).mockResolvedValueOnce({
+ editTask: vi.fn().mockResolvedValue({ content: 'Task not found', success: false }),
+ } as any);
+
+ const result = await executor.execute(
+ taskPayload('editTask', '{"identifier":"T-404"}'),
+ taskContext,
+ );
+
+ expect(result.workRegistration).toBeUndefined();
+ });
+
+ it('emits an update intent for a successful editTask', async () => {
+ const { getServerRuntime } = await import('../serverRuntimes');
+ vi.mocked(getServerRuntime).mockResolvedValueOnce({
+ editTask: vi.fn().mockResolvedValue({ content: 'edited', success: true }),
+ } as any);
+
+ const result = await executor.execute(
+ taskPayload('editTask', '{"identifier":"T-1","name":"Edited"}'),
+ taskContext,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.workRegistration).toEqual({
+ action: 'update',
+ changeType: 'updated',
+ targets: [{ taskIdentifier: 'T-1' }],
+ type: 'task',
+ });
+ });
});
diff --git a/apps/server/src/services/toolExecution/builtin.ts b/apps/server/src/services/toolExecution/builtin.ts
index 8c9f9a64503..552f90a22ab 100644
--- a/apps/server/src/services/toolExecution/builtin.ts
+++ b/apps/server/src/services/toolExecution/builtin.ts
@@ -1,6 +1,10 @@
import { builtinTools } from '@lobechat/builtin-tools';
import { type LobeChatDatabase } from '@lobechat/database';
-import { type ChatToolPayload } from '@lobechat/types';
+import {
+ type ChatToolPayload,
+ isWorkSkillProvider,
+ type WorkRegistrationIntent,
+} from '@lobechat/types';
import { detectTruncatedJSON, safeParseJSON } from '@lobechat/utils';
import debug from 'debug';
@@ -9,6 +13,7 @@ import { MarketService } from '@/server/services/market';
import { getServerRuntime, hasServerRuntime } from './serverRuntimes';
import { type IToolExecutor, type ToolExecutionContext, type ToolExecutionResult } from './types';
+import { resolveBuiltinToolWorkIntent } from './workRegistration';
const log = debug('lobe-server:builtin-tools-executor');
@@ -102,7 +107,7 @@ export class BuiltinToolsExecutor implements IToolExecutor {
// Route LobeHub Skills to MarketService
if (source === 'lobehubSkill') {
- return this.marketService.executeLobehubSkill({
+ const result = await this.marketService.executeLobehubSkill({
args,
context: {
topicId: context.topicId,
@@ -110,6 +115,26 @@ export class BuiltinToolsExecutor implements IToolExecutor {
provider: identifier,
toolName: apiName,
});
+
+ if (result.success && isWorkSkillProvider(identifier)) {
+ // Defer Work registration to the agent runtime so the version is written
+ // ONCE with its cumulative cost (known only after execution). Carry the
+ // UNTRUNCATED payload here: the runtime only sees the truncated
+ // `content`, but skill identity (issue/PR url, number, …) lives
+ // exclusively in the raw result.
+ return {
+ ...result,
+ workRegistration: {
+ args,
+ data: safeParseJSON(result.content) ?? result.content,
+ provider: identifier,
+ toolName: apiName,
+ type: 'skill',
+ },
+ };
+ }
+
+ return result;
}
// Route Composio tools to ComposioService. Build it request-scoped: agentId
@@ -167,7 +192,41 @@ export class BuiltinToolsExecutor implements IToolExecutor {
}
try {
- return await runtime[apiName](args, context);
+ // Install a sink for runtimes whose Work registration is a side-effect
+ // decoupled from the returned result (the agentDocuments runtime emits its
+ // intent here instead of writing the version directly).
+ let collectedWorkIntent: WorkRegistrationIntent | undefined;
+ context.onWorkRegistration = (intent) => {
+ collectedWorkIntent = intent;
+ };
+
+ const result = await runtime[apiName](args, context);
+
+ // Manifest-driven Work registration: resolve the intent from the API's
+ // declarative `work` config + result/args and hand it to the agent
+ // runtime, which persists the Work version ONCE with its cumulative cost.
+ // Falls back to the intent a runtime emitted via `onWorkRegistration`
+ // (documents). No-op unless the API declares a `work` config or emits one.
+ //
+ // Best-effort: Work-intent resolution is post-hoc bookkeeping over an
+ // already-successful tool call, so a bug in the resolver must not turn a
+ // succeeded mutation into a reported tool failure. Isolate it from the
+ // execution try/catch below and swallow-and-log instead.
+ let workRegistration: WorkRegistrationIntent | undefined;
+ try {
+ workRegistration =
+ resolveBuiltinToolWorkIntent(identifier, apiName, { args, result }) ??
+ collectedWorkIntent;
+ } catch (workError) {
+ log(
+ 'Work registration intent resolution failed for %s:%s: %O',
+ identifier,
+ apiName,
+ workError,
+ );
+ }
+
+ return workRegistration ? { ...result, workRegistration } : result;
} catch (e) {
const error = e as Error;
console.error('Error executing builtin tool %s:%s: %O', identifier, apiName, error);
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts
index 90d6c67cf14..f4b806e7c80 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts
@@ -226,6 +226,83 @@ describe('agentDocumentsRuntime auto-pin to task', () => {
});
});
+describe('agentDocumentsRuntime Work registration state', () => {
+ // Work registration is now manifest-driven: the runtime no longer emits intents
+ // via `context.onWorkRegistration`. Instead every mutating API stamps a uniform
+ // identity block (`agentDocumentId` / `agentId` / `documentId`) into its result
+ // `state`, which the generic dispatch-layer resolver reads. These tests assert
+ // the runtime surfaces that block (create + delete-via-pre-read) and does NOT
+ // call the legacy sink.
+ const newDoc = {
+ documentId: 'documents-row-id',
+ filename: 'daily-brief',
+ id: 'agent-doc-assoc-id',
+ title: 'Daily Brief',
+ };
+
+ let serviceImpl: Record<string, ReturnType<typeof vi.fn>>;
+
+ beforeEach(() => {
+ agentDocumentToolOutcomeMocks.emitAgentDocumentToolOutcomeSafely.mockClear();
+ serviceImpl = {
+ createDocument: vi.fn().mockResolvedValue(newDoc),
+ getDocumentSnapshotById: vi.fn().mockResolvedValue(newDoc),
+ removeDocumentById: vi.fn().mockResolvedValue(true),
+ };
+ vi.mocked(AgentDocumentsService).mockImplementation(() => serviceImpl as any);
+ vi.mocked(TaskModel).mockImplementation(() => ({ pinDocument: vi.fn() }) as any);
+ vi.mocked(WorkspaceModel).mockImplementation(
+ () => ({ findById: vi.fn().mockResolvedValue({ slug: 'lobe-team' }) }) as any,
+ );
+ });
+
+ const buildContext = (onWorkRegistration?: ReturnType<typeof vi.fn>) => ({
+ onWorkRegistration,
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ });
+
+ it('surfaces the document identity block in create state without emitting an intent', async () => {
+ const onWorkRegistration = vi.fn();
+ const runtime = agentDocumentsRuntime.factory(buildContext(onWorkRegistration));
+
+ const result = await runtime.createDocument(
+ { content: 'body', title: 'Daily Brief' },
+ { agentId: 'agent-1' },
+ );
+
+ expect(result.state).toMatchObject({
+ agentDocumentId: 'agent-doc-assoc-id',
+ agentId: 'agent-1',
+ documentId: 'documents-row-id',
+ });
+ expect(onWorkRegistration).not.toHaveBeenCalled();
+ });
+
+ it('surfaces the document identity block in remove state via the pre-read', async () => {
+ const runtime = agentDocumentsRuntime.factory(buildContext());
+
+ const result = await runtime.removeDocument(
+ { id: 'agent-doc-assoc-id' },
+ { agentId: 'agent-1' },
+ );
+
+ expect(serviceImpl.getDocumentSnapshotById).toHaveBeenCalledWith(
+ 'agent-doc-assoc-id',
+ 'agent-1',
+ );
+ expect(result.success).toBe(true);
+ expect(result.state).toMatchObject({
+ agentDocumentId: 'agent-doc-assoc-id',
+ agentId: 'agent-1',
+ deleted: true,
+ documentId: 'documents-row-id',
+ });
+ });
+});
+
describe('AgentDocumentsExecutionRuntime.createDocument', () => {
const makeStub = () => ({
copyDocument: vi.fn(),
@@ -259,6 +336,7 @@ describe('AgentDocumentsExecutionRuntime.createDocument', () => {
expect(result.success).toBe(true);
expect(result.state).toEqual({
agentDocumentId: 'agent-doc-assoc-id',
+ agentId: 'agent-1',
documentId: 'documents-row-id',
});
});
@@ -318,6 +396,7 @@ describe('AgentDocumentsExecutionRuntime.createDocument', () => {
expect(result.success).toBe(true);
expect(result.state).toEqual({
agentDocumentId: 'agent-doc-assoc-id',
+ agentId: 'agent-1',
documentId: 'documents-row-id',
});
expect(stub.createTopicDocument).toHaveBeenCalledWith({
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
index 0273b78d6a4..73f44daaa76 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
@@ -192,6 +192,36 @@ describe('createTaskRuntime', () => {
expect(result.content).toContain('[T-1](https://app.lobehub.com/acme/task/T-1)');
});
+ it('surfaces the created task identity in state (the dispatch-layer registration source)', async () => {
+ const deps = makeDeps();
+
+ const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
+ agentId: 'agt-xyz',
+ assistantMessageId: 'msg-assistant',
+ operationId: 'op-1',
+ taskCaller: deps.taskCaller,
+ taskModel: deps.taskModel as any,
+ taskService: deps.taskService as any,
+ threadId: 'thread-1',
+ toolCallId: 'tool-call-1',
+ toolMessageId: 'msg-tool',
+ topicId: 'topic-1',
+ });
+
+ const result = await runtime.createTask({
+ instruction: 'Do something',
+ name: 'Test',
+ });
+
+ // Work registration now happens at the tool-execution dispatch layer, which
+ // reads the created task's identity from `result.state`.
+ expect(result.success).toBe(true);
+ expect(result).toMatchObject({
+ state: { identifier: 'T-1', success: true, taskId: 'task-1' },
+ });
+ });
+
it('leaves createdByAgentId undefined when no agentId in context', async () => {
const deps = makeDeps();
@@ -445,6 +475,46 @@ describe('createTaskRuntime', () => {
expect(deps.taskModel.update).not.toHaveBeenCalled();
expect(result.content).toContain('parent cleared');
});
+
+ it('applies an edit and succeeds (identity flows to dispatch-layer registration via args)', async () => {
+ const deps = makeDeps();
+
+ const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
+ agentId: 'agt-manager',
+ taskCaller: deps.taskCaller,
+ taskModel: deps.taskModel as any,
+ taskService: deps.taskService as any,
+ toolCallId: 'tool-call-edit',
+ });
+
+ const result = await runtime.editTask({
+ identifier: 'T-1',
+ name: 'Edited',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('name → "Edited"');
+ expect(deps.taskCaller.update).toHaveBeenCalledWith({ id: 'task-1', name: 'Edited' });
+ });
+
+ it('returns failure when no fields are provided', async () => {
+ const deps = makeDeps();
+
+ const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
+ agentId: 'agt-manager',
+ taskCaller: deps.taskCaller,
+ taskModel: deps.taskModel as any,
+ taskService: deps.taskService as any,
+ });
+
+ const result = await runtime.editTask({ identifier: 'T-1' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('No fields provided; nothing to update.');
+ expect(deps.taskCaller.update).not.toHaveBeenCalled();
+ });
});
describe('listTasks', () => {
@@ -493,7 +563,7 @@ describe('createTaskRuntime', () => {
};
};
- it('creates each task and aggregates a header line + per-item summary', async () => {
+ it('creates each task and aggregates a header line + per-item summary + state', async () => {
const deps = makeDeps();
const runtime = createTaskRuntime({
agentModel: deps.agentModel as any,
@@ -517,6 +587,18 @@ describe('createTaskRuntime', () => {
// clickable when the message is delivered to IM / mobile.
expect(result.content).toContain('[T-A](https://app.lobehub.com/task/T-A)');
expect(result.content).toContain('[T-B](https://app.lobehub.com/task/T-B)');
+ expect(result.content).toContain('T-A');
+ expect(result.content).toContain('T-B');
+ // State parity with the client executor: the dispatch-layer registration
+ // reads per-item identity + success from `state.results`.
+ expect(result.state).toEqual({
+ failed: 0,
+ results: [
+ { error: undefined, identifier: 'T-A', name: 'A', success: true },
+ { error: undefined, identifier: 'T-B', name: 'B', success: true },
+ ],
+ succeeded: 2,
+ });
});
it('continues past per-item failures and reports them in the summary', async () => {
@@ -568,6 +650,88 @@ describe('createTaskRuntime', () => {
});
});
+ describe('setTaskSchedule / setTaskVerify / updateTaskStatus', () => {
+ it('applies schedule changes and succeeds', async () => {
+ const taskCaller = {
+ update: vi.fn().mockResolvedValue({}),
+ updateConfig: vi.fn().mockResolvedValue({}),
+ };
+ const taskModel = {
+ resolve: vi.fn().mockResolvedValue({ id: 'task-1', identifier: 'T-1' }),
+ };
+ const runtime = createTaskRuntime({
+ agentModel: { existsById: vi.fn() } as any,
+ taskCaller: taskCaller as any,
+ taskModel: taskModel as any,
+ taskService: {} as any,
+ toolCallId: 'tool-call-schedule',
+ });
+
+ const result = await runtime.setTaskSchedule({
+ automationMode: 'schedule',
+ identifier: 'T-1',
+ schedulePattern: '0 9 * * *',
+ });
+
+ expect(result.success).toBe(true);
+ expect(taskCaller.update).toHaveBeenCalledWith(
+ expect.objectContaining({ automationMode: 'schedule', id: 'task-1' }),
+ );
+ });
+
+ it('applies verify config changes and succeeds', async () => {
+ const taskCaller = {
+ updateVerifyConfig: vi.fn().mockResolvedValue({}),
+ };
+ const taskModel = {
+ resolve: vi.fn().mockResolvedValue({ id: 'task-1', identifier: 'T-1' }),
+ };
+ const runtime = createTaskRuntime({
+ agentModel: { existsById: vi.fn() } as any,
+ taskCaller: taskCaller as any,
+ taskModel: taskModel as any,
+ taskService: {} as any,
+ toolCallId: 'tool-call-verify',
+ });
+
+ const result = await runtime.setTaskVerify({
+ enabled: true,
+ identifier: 'T-1',
+ requirement: 'The output must include a working demo.',
+ });
+
+ expect(result.success).toBe(true);
+ expect(taskCaller.updateVerifyConfig).toHaveBeenCalledWith({
+ id: 'task-1',
+ verify: {
+ enabled: true,
+ requirement: 'The output must include a working demo.',
+ },
+ });
+ });
+
+ it('handles status-only updates', async () => {
+ const taskCaller = {
+ updateStatus: vi.fn().mockResolvedValue({ data: { identifier: 'T-1' } }),
+ };
+ const runtime = createTaskRuntime({
+ agentModel: { existsById: vi.fn() } as any,
+ taskCaller: taskCaller as any,
+ taskModel: {} as any,
+ taskService: {} as any,
+ });
+
+ const result = await runtime.updateTaskStatus({ identifier: 'T-1', status: 'completed' });
+
+ expect(result.success).toBe(true);
+ expect(taskCaller.updateStatus).toHaveBeenCalledWith({
+ error: undefined,
+ id: 'T-1',
+ status: 'completed',
+ });
+ });
+ });
+
describe('runTask / runTasks', () => {
it('forwards identifier + prompt + continueTopicId to taskCaller.run', async () => {
const taskCaller = {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts
index 05e550986c7..68592ade9fa 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts
@@ -1,28 +1,16 @@
import type { DocumentLoadRule } from '@lobechat/agent-templates';
-import {
- AgentDocumentsIdentifier,
- buildAgentDocumentUrl,
-} from '@lobechat/builtin-tool-agent-documents';
+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';
import { AgentDocumentsExecutionRuntime } from '@lobechat/builtin-tool-agent-documents/executionRuntime';
import { eq } from 'drizzle-orm';
import { TaskModel } from '@/database/models/task';
-import { WorkspaceModel } from '@/database/models/workspace';
import { tasks } from '@/database/schemas';
-import { appEnv } from '@/envs/app';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
+import { createDocumentWorkRegistrar } from '@/server/services/agentDocuments/documentWork';
import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocuments/toolOutcome';
import { type ServerRuntimeRegistration } from './types';
-const getAgentDocumentAppUrl = (): string | undefined => {
- try {
- return appEnv.APP_URL;
- } catch {
- return process.env.APP_URL;
- }
-};
-
export const agentDocumentsRuntime: ServerRuntimeRegistration = {
factory: (context) => {
if (!context.userId || !context.serverDB) {
@@ -38,7 +26,12 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
context.agentVisibility,
);
const { taskId } = context;
- let workspaceSlugPromise: Promise<string | undefined> | undefined;
+ const workRegistrar = createDocumentWorkRegistrar({
+ db,
+ logPrefix: '[agentDocumentsRuntime]',
+ userId,
+ workspaceId: context.workspaceId,
+ });
const emitDocumentOutcome = async (input: {
agentId?: string;
agentDocumentId?: string;
@@ -128,24 +121,17 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
return doc;
};
- const resolveWorkspaceSlugForUrl = async (): Promise<string | undefined> => {
- if (!context.workspaceId) return undefined;
-
- workspaceSlugPromise ??= new WorkspaceModel(db, userId)
- .findById(context.workspaceId)
- .then((workspace) => workspace?.slug)
- .catch((error) => {
- console.error('[agentDocumentsRuntime] Failed to resolve workspace slug:', error);
- return undefined;
- });
-
- return workspaceSlugPromise;
- };
+ // Work registration is now manifest-driven: each mutating API declares a
+ // `work` config in the agent-documents manifest and stamps a uniform identity
+ // block into its result `state`. The tool-execution dispatch layer resolves
+ // the Work intent from that config + state (see `resolveBuiltinToolWorkIntent`
+ // / `stashBuiltinToolWorkIntent`), so this runtime no longer emits intents
+ // imperatively via `context.onWorkRegistration`.
return new AgentDocumentsExecutionRuntime(
{
- copyDocument: async ({ agentId, id, newTitle }) =>
- pinToTask(
+ copyDocument: async ({ agentId, id, newTitle }) => {
+ const doc = await pinToTask(
await withDocumentOutcome(
{
agentId,
@@ -157,9 +143,11 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
},
() => service.copyDocumentById(id, newTitle, agentId),
),
- ),
- createDocument: async ({ agentId, content, hintIsSkill, title }) =>
- pinToTask(
+ );
+ return doc;
+ },
+ createDocument: async ({ agentId, content, hintIsSkill, title }) => {
+ const doc = await pinToTask(
await withDocumentOutcome(
{
agentId,
@@ -172,9 +160,11 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
},
() => service.createDocument(agentId, title, content, { hintIsSkill }),
),
- ),
- createTopicDocument: async ({ agentId, content, hintIsSkill, title, topicId }) =>
- pinToTask(
+ );
+ return doc;
+ },
+ createTopicDocument: async ({ agentId, content, hintIsSkill, title, topicId }) => {
+ const doc = await pinToTask(
await withDocumentOutcome(
{
agentId,
@@ -187,7 +177,9 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
},
() => service.createForTopic(agentId, title, content, topicId, { hintIsSkill }),
),
- ),
+ );
+ return doc;
+ },
listDocuments: async ({ agentId, parentId, sourceType }) => {
// Agents discover archived tool results via this path (see
// `excludeArchivedToolResults`), so keep the `.tool-results` archive visible.
@@ -216,8 +208,8 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
title: d.title,
}));
},
- modifyNodes: ({ agentId, id, operations }) =>
- withDocumentOutcome(
+ modifyNodes: async ({ agentId, id, operations }) => {
+ const doc = await withDocumentOutcome(
{
agentId,
apiName: 'modifyNodes',
@@ -227,7 +219,9 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
toolAction: 'edit',
},
() => service.modifyDocumentNodesById(id, operations, agentId),
- ),
+ );
+ return doc;
+ },
readDocument: ({ agentId, id }) => service.getDocumentSnapshotById(id, agentId),
removeDocument: ({ agentId, id }) =>
withDocumentOutcome(
@@ -241,8 +235,8 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
},
() => service.removeDocumentById(id, agentId),
),
- renameDocument: ({ agentId, id, newTitle }) =>
- withDocumentOutcome(
+ renameDocument: async ({ agentId, id, newTitle }) => {
+ const doc = await withDocumentOutcome(
{
agentId,
apiName: 'renameDocument',
@@ -252,9 +246,11 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
toolAction: 'rename',
},
() => service.renameDocumentById(id, newTitle, agentId),
- ),
- replaceDocumentContent: ({ agentId, content, id }) =>
- withDocumentOutcome(
+ );
+ return doc;
+ },
+ replaceDocumentContent: async ({ agentId, content, id }) => {
+ const doc = await withDocumentOutcome(
{
agentId,
apiName: 'replaceDocumentContent',
@@ -264,7 +260,9 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
toolAction: 'replace',
},
() => service.replaceDocumentContentById(id, content, agentId),
- ),
+ );
+ return doc;
+ },
updateLoadRule: ({ agentId, id, rule }) =>
withDocumentOutcome(
{
@@ -284,14 +282,8 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
),
},
{
- getDocumentUrl: async ({ agentId, documentId }) => {
- const workspaceSlug = await resolveWorkspaceSlugForUrl();
- if (context.workspaceId && !workspaceSlug) return undefined;
-
- return buildAgentDocumentUrl(getAgentDocumentAppUrl(), agentId, documentId, {
- workspaceSlug,
- });
- },
+ getDocumentUrl: ({ agentId, documentId }) =>
+ workRegistrar.buildRegisteredDocumentUrl(agentId, documentId),
},
);
},
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
index 8118928c876..769b7dbe2be 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
@@ -58,17 +58,31 @@ export interface TaskRuntimeDeps {
// resolved workspaceId); when absent (unit tests) links fall back to the bare
// app origin.
resolveLinkBaseUrl?: () => Promise<string>;
+ // Root runtime operation used to aggregate Works produced during one run.
+ rootOperationId?: string;
scope?: string | null;
taskCaller: ReturnType<typeof taskRouter.createCaller>;
taskId?: string;
taskModel: TaskModel;
taskService: TaskService;
+ threadId?: string | null;
toolCallId?: string;
- topicId?: string;
+ // Source tool result message id, when the runtime already has one.
+ toolMessageId?: string;
+ topicId?: string | null;
}
export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
- const { agentId, assistantMessageId, operationId, scope, taskId, toolCallId, topicId } = deps;
+ const {
+ agentId,
+ assistantMessageId,
+ operationId,
+ rootOperationId,
+ scope,
+ taskId,
+ toolCallId,
+ topicId,
+ } = deps;
// Models are read through `deps` (not destructured) so callers can swap them
// in lazily — e.g. after async workspace resolution in the runtime factory.
const agentModel = () => deps.agentModel;
@@ -107,7 +121,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
const createTaskImpl = async (
args: CreateTaskArgs,
- ): Promise<{ content: string; identifier?: string; success: boolean }> => {
+ ): Promise<{ content: string; identifier?: string; success: boolean; taskId?: string }> => {
let parentLabel: string | undefined;
// Pre-resolve parent identifier so we can surface a tool-friendly error
@@ -128,9 +142,16 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
// bridge the handoff result back to the creator conversation.
// Only persist the pocket when we actually have a creator agent + topic;
// tasks created outside an agent turn (e.g. via API) have no origin.
+ const originOperationId = rootOperationId ?? operationId;
const origin =
agentId && topicId
- ? { agentId, messageId: assistantMessageId, operationId, toolCallId, topicId }
+ ? {
+ agentId,
+ messageId: assistantMessageId,
+ operationId: originOperationId,
+ toolCallId,
+ topicId,
+ }
: undefined;
const task = await taskService().createTask({
@@ -159,6 +180,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
}),
identifier: task.identifier,
success: true,
+ taskId: task.id,
};
};
@@ -191,12 +213,16 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
},
createTask: async (args: CreateTaskArgs) => {
- const { identifier, ...rest } = await createTaskImpl(args);
+ const result = await createTaskImpl(args);
+ const { identifier, taskId: createdTaskId, ...rest } = result;
// Surface the created task identifier as plugin state (mirrors the client
// executor's `{ identifier, success }`) so the inline render can link to
- // the task detail. Without this the tool message persists no state and the
- // card has nothing to open.
- return identifier ? { ...rest, state: { identifier, success: rest.success } } : rest;
+ // the task detail, AND so the dispatch-layer Work registration can read the
+ // created task identity from `result.state`. Without this the tool message
+ // persists no state and the card has nothing to open.
+ return identifier
+ ? { ...rest, state: { identifier, success: rest.success, taskId: createdTaskId } }
+ : rest;
},
createTasks: async (args: { tasks: CreateTaskArgs[] }) => {
@@ -222,12 +248,17 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
}
}
- const failed = results.filter((r) => !r.success).length;
+ const succeeded = results.filter((r) => r.success).length;
+ const failed = results.length - succeeded;
return {
// Absolute, workspace-scoped links so the summary stays clickable when
// pushed to IM / mobile.
content: formatTasksCreated(results, await taskLinkBaseUrl()),
+ // State parity with the client executor (`{ failed, results, succeeded }`)
+ // so the dispatch-layer Work registration can read per-item identity +
+ // success from `result.state.results` for partial-failure batches.
+ state: { failed, results, succeeded },
success: failed === 0,
};
},
@@ -240,6 +271,10 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
return {
content: formatTaskDeleted(task.identifier, task.name),
+ // Surface the deleted task's internal id so the dispatch-layer Work
+ // deletion (`work: { action: 'delete' }`) can locate the Work by
+ // `works.resourceId = taskId` after the task row is gone.
+ state: { identifier: task.identifier, success: true, taskId: task.id },
success: true,
};
},
@@ -358,6 +393,10 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
);
}
+ if (ops.length === 0 && depResults.length === 0) {
+ return { content: 'No fields provided; nothing to update.', success: false };
+ }
+
const [, depErrors] = await Promise.all([Promise.all(ops), Promise.all(depResults)]);
const firstDepError = depErrors.find((e) => e);
if (firstDepError) return { content: firstDepError, success: false };
@@ -698,8 +737,16 @@ export const taskRuntime: ServerRuntimeRegistration = {
const db = context.serverDB;
const userId = context.userId;
- const { agentId, assistantMessageId, operationId, taskId, toolCallId, topicId, scope } =
- context;
+ const {
+ agentId,
+ assistantMessageId,
+ operationId,
+ taskId,
+ threadId,
+ toolCallId,
+ topicId,
+ scope,
+ } = context;
// Workspace slug for deep-links: resolved once (memoized) from the workspace
// owning the created task (`workspaceId` is set by `ensureModels` below),
@@ -725,10 +772,13 @@ export const taskRuntime: ServerRuntimeRegistration = {
agentId,
assistantMessageId,
operationId,
+ rootOperationId: context.rootOperationId ?? operationId,
resolveLinkBaseUrl,
scope,
taskId,
+ threadId,
toolCallId,
+ toolMessageId: context.toolMessageId,
topicId,
// Initial personal-mode models cover the no-task-context case. Replaced
// before the first call when `taskId` is set.
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index 26432d80984..022c40c9ed3 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -5,6 +5,7 @@ import {
type ClientSecretPayload,
type ExecSubAgentParams,
type StepActivatedSkill,
+ type WorkRegistrationIntent,
} from '@lobechat/types';
export interface ToolExecutionMemoryEmbeddingRuntime {
@@ -210,6 +211,16 @@ export interface ToolExecutionContext {
memoryToolPermission?: 'read-only' | 'read-write';
/** Source user message ID used by Agent Signal procedure suppression. */
messageId?: string;
+ /**
+ * Sink for a Work-registration intent produced as a side-effect inside a tool
+ * runtime (e.g. the agentDocuments runtime, whose registration is decoupled
+ * from the returned tool result). The builtin executor installs this collector
+ * before dispatching the runtime call and hoists whatever intent the runtime
+ * emits onto {@link ToolExecutionResult.workRegistration}, so it reaches
+ * `callTool` / `callToolsBatch` and the Work version is inserted ONCE with cost
+ * — the same one-shot path task/skill tools use directly on the result.
+ */
+ onWorkRegistration?: (intent: WorkRegistrationIntent) => void;
/** Agent runtime operation ID for structured tool outcome identity. */
operationId?: string;
/**
@@ -218,6 +229,8 @@ export interface ToolExecutionContext {
* device gateway. Derived from the operation's skill set.
*/
projectSkills?: { location: string; name: string; source?: 'device' | 'project' }[];
+ /** Root AI runtime operation ID used to aggregate artifacts produced by one run. */
+ rootOperationId?: string;
/** Conversation scope captured when the operation was created */
scope?: string | null;
/** Server database for LobeHub Skills execution */
@@ -238,6 +251,8 @@ export interface ToolExecutionContext {
/** Stable LLM tool call ID for structured tool outcome identity. */
toolCallId?: string;
toolManifestMap: Record<string, LobeToolManifest>;
+ /** Source tool result message ID, when it already exists. */
+ toolMessageId?: string;
/**
* Maximum length for tool execution result content (in characters)
* @default 6000
@@ -278,6 +293,16 @@ export interface ToolExecutionResult {
error?: any;
state?: Record<string, any>;
success: boolean;
+ /**
+ * Transient Work-registration intent produced by the executor and consumed by
+ * the agent runtime (`callTool` / `callToolsBatch`) once the tool call's
+ * cumulative cost is known, so the Work version is inserted ONCE with its
+ * cost. In-memory only: it rides through the in-process executor→runtime
+ * boundary and is deliberately NOT persisted with the tool message (which
+ * stores only `content` / `state` / `error`) nor length-truncated (unlike
+ * `content`), so skill identity in the untruncated payload survives.
+ */
+ workRegistration?: WorkRegistrationIntent;
}
export interface ToolExecutionResultResponse extends ToolExecutionResult {
diff --git a/apps/server/src/services/toolExecution/workRegistration.ts b/apps/server/src/services/toolExecution/workRegistration.ts
new file mode 100644
index 00000000000..80318d512dc
--- /dev/null
+++ b/apps/server/src/services/toolExecution/workRegistration.ts
@@ -0,0 +1,27 @@
+import { builtinTools } from '@lobechat/builtin-tools';
+import { resolveWorkRegistration } from '@lobechat/builtin-tools/workRegistration';
+import { type WorkRegistrationIntent } from '@lobechat/types';
+
+import { type ToolExecutionResult } from './types';
+
+/**
+ * Manifest-driven Work registration intent for the server tool-execution path.
+ *
+ * The executor no longer writes the Work itself: it only RESOLVES what should
+ * be registered (from the API's declarative `work` config + the tool
+ * result/args) and hands the intent back on the result. The agent runtime
+ * (`callTool` / `callToolsBatch`) persists it ONCE the tool call's cumulative
+ * cost is known, so the Work version lands with its `cumulativeCost` instead of
+ * being created cost-less and back-filled.
+ *
+ * Returns `undefined` for APIs that declare no `work` config or resolve to no
+ * targets. Pure + side-effect-free — provenance and cost are supplied by the
+ * runtime at persist time.
+ */
+export const resolveBuiltinToolWorkIntent = (
+ identifier: string,
+ apiName: string,
+ payload: { args: Record<string, any>; result: ToolExecutionResult },
+): WorkRegistrationIntent | undefined => {
+ return resolveWorkRegistration(builtinTools, identifier, apiName, payload);
+};
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 6106e406e09..b925ea8e8b5 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1601,5 +1601,17 @@
"workingPanel.skills.title": "Skills",
"workingPanel.space": "Space",
"workingPanel.title": "Working Panel",
+ "workingPanel.works.changeType.created": "Created",
+ "workingPanel.works.changeType.updated": "Updated",
+ "workingPanel.works.empty": "No works in this conversation yet",
+ "workingPanel.works.emptyVersions": "No versions yet",
+ "workingPanel.works.error": "Failed to load works",
+ "workingPanel.works.taskDeleted": "Task deleted",
+ "workingPanel.works.title": "Works",
+ "workingPanel.works.totalCost": "Total cost: {{cost}}",
+ "workingPanel.works.versionCost": "Version cost: {{cost}}",
+ "workingPanel.works.versionError": "Failed to load versions",
+ "workingPanel.works.viewMode.history": "Version history",
+ "workingPanel.works.viewMode.summary": "Summary cards",
"you": "You"
}
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index ce22eaa628f..312c3663968 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -254,5 +254,13 @@
"uploadDock.uploadStatus.pending": "Waiting to upload",
"uploadDock.uploadStatus.processing": "Uploading",
"uploadDock.uploadStatus.success": "Upload completed",
- "uploadDock.uploadStatus.uploading": "Uploading"
+ "uploadDock.uploadStatus.uploading": "Uploading",
+ "work.empty.desc": "Works your agents produce — tasks, documents, Linear and GitHub items — will collect here.",
+ "work.empty.title": "No works yet",
+ "work.group": "Works",
+ "work.loadError": "Something went wrong while loading works.",
+ "work.loadErrorTitle": "Couldn’t load works",
+ "work.loadMoreError": "Failed to load more works.",
+ "work.retry": "Retry",
+ "work.topicGroup.other": "Other"
}
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index bb216ff27f9..5377a56c5aa 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1601,5 +1601,18 @@
"workingPanel.skills.title": "技能",
"workingPanel.space": "空间",
"workingPanel.title": "工作面板",
- "you": "你"
+ "workingPanel.works.changeType.created": "已创建",
+ "workingPanel.works.changeType.updated": "已编辑",
+ "workingPanel.works.empty": "当前会话暂无产物",
+ "workingPanel.works.emptyVersions": "暂无版本",
+ "workingPanel.works.error": "产物加载失败",
+ "workingPanel.works.taskDeleted": "任务已删除",
+ "workingPanel.works.title": "产物",
+ "workingPanel.works.totalCost": "总成本:{{cost}}",
+ "workingPanel.works.versionCost": "本版本成本:{{cost}}",
+ "workingPanel.works.versionError": "版本加载失败",
+ "workingPanel.works.viewMode.history": "版本历史",
+ "workingPanel.works.viewMode.summary": "摘要卡片",
+ "you": "你",
+ "zenMode": "专注模式"
}
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index 10d664bfdec..5dc04a06dac 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -254,5 +254,13 @@
"uploadDock.uploadStatus.pending": "等待上传",
"uploadDock.uploadStatus.processing": "正在上传",
"uploadDock.uploadStatus.success": "上传完成",
- "uploadDock.uploadStatus.uploading": "正在上传"
+ "uploadDock.uploadStatus.uploading": "正在上传",
+ "work.empty.desc": "Agent 产出的交付物(任务、文档、Linear 与 GitHub 条目)都会汇聚在这里。",
+ "work.empty.title": "还没有产物",
+ "work.group": "产物",
+ "work.loadError": "加载产物时出错了。",
+ "work.loadErrorTitle": "无法加载产物",
+ "work.loadMoreError": "加载更多产物失败。",
+ "work.retry": "重试",
+ "work.topicGroup.other": "其他"
}
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index 649fdb67be9..a6613838be9 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -193,16 +193,38 @@ export interface AgentInterventionResponseData {
* Server → Client: request the client to execute a tool locally and return the result.
*/
export interface ToolExecuteData {
+ /** Agent currently running the tool. */
+ agentId?: string | null;
/** Tool function name (e.g. "readFile"). */
apiName: string;
/** JSON-encoded argument string as returned by the LLM. */
arguments: string;
+ /** Assistant message that carries this tool call. */
+ assistantMessageId?: string;
+ /** Current page document ID for page-scoped conversations. */
+ documentId?: string | null;
/** Per-invocation deadline. Server caps against its own function budget. */
executionTimeoutMs: number;
+ /** Group chat ID, when the run belongs to a group conversation. */
+ groupId?: string | null;
/** Tool plugin identifier (e.g. "local-system"). */
identifier: string;
+ /** Root server-side runtime operation ID for this assistant run. */
+ rootOperationId?: string;
+ /** Conversation scope captured by the server runtime. */
+ scope?: string | null;
+ /** Source user message ID for tools that need the current turn. */
+ sourceMessageId?: string | null;
+ /** Current task identifier or database id when task-scoped. */
+ taskId?: string | null;
+ /** Current thread ID when thread-scoped. */
+ threadId?: string | null;
/** Unique tool call id; used as the correlation key for the returned result. */
toolCallId: string;
+ /** Tool result message id, when the server created it before dispatch. */
+ toolMessageId?: string;
+ /** Current topic ID. */
+ topicId?: string | null;
}
// ─── WebSocket Protocol Messages ───
@@ -245,6 +267,14 @@ export interface ToolResultMessage {
success: boolean;
toolCallId: string;
type: 'tool_result';
+ /**
+ * In-memory relay of the client-side Work registration intent (a
+ * `WorkRegistrationIntent`, kept opaque here to preserve this package's
+ * zero-`@lobechat` dependency surface — mirrors how `state` is typed). The
+ * server registers the Work version from it and NEVER persists it with the
+ * tool message.
+ */
+ workRegistration?: any;
}
export type ClientMessage =
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
index f49cf7af8c1..cbd0da332d7 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
@@ -199,6 +199,65 @@ describe('callLlmFinalizer', () => {
});
});
+ it('stamps the work display anchor only on the turn-final message after tool interaction', async () => {
+ const messages = createMessageTransport();
+ const state = AgentRuntime.createInitialState({
+ messages: [
+ { content: 'Create a task', id: 'user-1', role: 'user' },
+ {
+ content: '',
+ id: 'assistant-0',
+ role: 'assistant',
+ tool_calls: [
+ { function: { arguments: '{}', name: 'createTask' }, id: 'call-1', type: 'function' },
+ ],
+ },
+ { content: 'created', id: 'tool-1', role: 'tool' },
+ ],
+ metadata: { sourceMessageId: 'user-1' },
+ operationId: 'operation-1',
+ });
+
+ await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-1',
+ events: [],
+ host: createHost(messages),
+ model: 'gpt-4',
+ output: createOutput(),
+ provider: 'openai',
+ shouldReplayAssistantReasoning: false,
+ state,
+ });
+
+ expect(messages.update).toHaveBeenCalledWith(
+ 'assistant-1',
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ work: { rootOperationId: 'operation-1', userMessageId: 'user-1' },
+ }),
+ }),
+ );
+
+ // A plain answer with no prior tool interaction must NOT get an anchor.
+ const plainMessages = createMessageTransport();
+ await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-2',
+ events: [],
+ host: createHost(plainMessages),
+ model: 'gpt-4',
+ output: createOutput(),
+ provider: 'openai',
+ shouldReplayAssistantReasoning: false,
+ state: AgentRuntime.createInitialState({
+ messages: [{ content: 'Hi', id: 'user-2', role: 'user' }],
+ metadata: { sourceMessageId: 'user-2' },
+ operationId: 'operation-1',
+ }),
+ });
+ const [, plainUpdate] = vi.mocked(plainMessages.update).mock.calls[0];
+ expect(plainUpdate.metadata ?? {}).not.toHaveProperty('work');
+ });
+
it('serializes multimodal parts and keeps the null grounding sentinel', async () => {
const messages = createMessageTransport();
const state = AgentRuntime.createInitialState({ operationId: 'operation-1' });
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
index c51f19ab1d1..55f977eb00d 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
@@ -123,11 +123,52 @@ const sanitizeStateToolCalls = (toolCalls: MessageToolCall[]) => {
return sanitizedToolCalls.length > 0 ? sanitizedToolCalls : undefined;
};
+/**
+ * Work display anchor: Work cards render on the FINAL assistant message of a
+ * turn (stable across the two-round tool flow), so stamp `metadata.work` only
+ * when this LLM step ends the turn — i.e. it emits no new tool calls AND at
+ * least one tool ran earlier in this operation (messages after
+ * sourceMessageId, the triggering user message). Without the prior-tool check
+ * every plain answer would get a work anchor; without the slice the scan
+ * would see other turns' tool messages.
+ */
+const buildWorkAnchor = ({
+ operationId,
+ output,
+ state,
+}: {
+ operationId: string;
+ output: LLMAttemptOutput;
+ state: AgentState;
+}): MessageMetadata['work'] => {
+ if (output.toolsCalling.length > 0 || output.toolCalls.length > 0) return undefined;
+
+ const sourceMessageId = state.metadata?.sourceMessageId;
+ const sourceMessageIndex =
+ typeof sourceMessageId === 'string'
+ ? state.messages.findIndex((message) => message.id === sourceMessageId)
+ : -1;
+ const currentOperationMessages =
+ sourceMessageIndex >= 0 ? state.messages.slice(sourceMessageIndex + 1) : [];
+ const hasPriorToolInteraction = currentOperationMessages.some(
+ (message) =>
+ message.role === 'tool' ||
+ (Array.isArray(message.tool_calls) && message.tool_calls.length > 0),
+ );
+ if (!hasPriorToolInteraction) return undefined;
+
+ return {
+ rootOperationId: operationId,
+ ...(typeof sourceMessageId === 'string' && { userMessageId: sourceMessageId }),
+ };
+};
+
const persistFinalMessage = async ({
assistantMessageId,
host,
output,
-}: Pick<FinalizeCallLlmTurnInput, 'assistantMessageId' | 'host' | 'output'>) => {
+ state,
+}: Pick<FinalizeCallLlmTurnInput, 'assistantMessageId' | 'host' | 'output' | 'state'>) => {
const finalContent = output.hasContentImages
? serializePartsForStorage(output.contentParts)
: output.content;
@@ -139,12 +180,17 @@ const persistFinalMessage = async ({
finishType: output.finishReason,
hasContentImages: output.hasContentImages,
});
+ const workAnchor = buildWorkAnchor({
+ operationId: host.operation.operationId,
+ output,
+ state,
+ });
try {
await host.transports.messages.update(assistantMessageId, {
content: finalContent,
imageList: output.imageList.length > 0 ? output.imageList : undefined,
- metadata,
+ metadata: workAnchor ? { ...metadata, work: workAnchor } : metadata,
observationId: output.observationId,
reasoning: finalReasoning,
search: output.grounding,
@@ -267,7 +313,7 @@ export const finalizeCallLlmTurn = async ({
}
}
- const finalReasoning = await persistFinalMessage({ assistantMessageId, host, output });
+ const finalReasoning = await persistFinalMessage({ assistantMessageId, host, output, state });
const newState = buildFinalState({
assistantMessageId,
finalReasoning,
diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.ts
index 16a5465f784..29d8080fbea 100644
--- a/packages/agent-runtime/src/executors/tool.test.ts
+++ b/packages/agent-runtime/src/executors/tool.test.ts
@@ -442,4 +442,138 @@ describe('tool executors', () => {
stepIndex: 2,
});
});
+
+ describe('work registration redaction', () => {
+ // A skill intent carries the UNTRUNCATED tool payload (`data`/`args`) solely
+ // for server-side Work registration. It must NOT ride the published stream
+ // event nor the returned `events` array (which get serialized into the
+ // capped Redis step blob) — clients only read `workRegistration` as a
+ // presence flag.
+ const createSkillIntent = () => ({
+ args: { number: 42, repo: 'lobehub/lobehub' },
+ data: { body: 'x'.repeat(500), issues: Array.from({ length: 30 }, (_, i) => ({ id: i })) },
+ provider: 'github',
+ toolName: 'github.searchIssues',
+ type: 'skill' as const,
+ });
+
+ const findEvent = (calls: unknown[][], type: string) =>
+ calls.map((call) => call[0] as any).find((event) => event?.type === type);
+
+ it('redacts a skill intent on the stream event and returned events, but registers the full intent (single path)', async () => {
+ const skillIntent = createSkillIntent();
+ const registerWork = vi.fn().mockResolvedValue(undefined);
+ host.transports.tools!.registerWork = registerWork;
+ runTool.mockResolvedValueOnce({
+ attempts: 1,
+ result: {
+ content: 'issue found',
+ executionTime: 100,
+ state: {},
+ success: true,
+ workRegistration: skillIntent,
+ },
+ });
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },
+ type: 'call_tool',
+ };
+
+ const result = await callTool(host)(instruction, createState());
+
+ // 1) Published `tool_end` stream event: presence flag preserved, payload stripped.
+ const toolEnd = findEvent(publishEvent.mock.calls, 'tool_end');
+ expect(toolEnd.data.result.workRegistration).toEqual({
+ args: undefined,
+ data: null,
+ provider: 'github',
+ toolName: 'github.searchIssues',
+ type: 'skill',
+ });
+
+ // 2) Returned step `events` array (serialized into the Redis step blob).
+ const toolResultEvent = result.events.find(
+ (event: any) => event.type === 'tool_result',
+ ) as any;
+ expect(toolResultEvent.result.workRegistration.data).toBeNull();
+ expect(toolResultEvent.result.workRegistration.args).toBeUndefined();
+
+ // 3) `registerWork` still receives the FULL intent (data + args intact).
+ expect(registerWork).toHaveBeenCalledTimes(1);
+ const registeredIntent = registerWork.mock.calls[0][0].intent;
+ expect(registeredIntent.data).toEqual(skillIntent.data);
+ expect(registeredIntent.args).toEqual(skillIntent.args);
+ });
+
+ it('passes a non-skill (task) intent through unredacted (single path)', async () => {
+ const taskIntent = {
+ action: 'create',
+ targets: [{ taskId: 'task-9' }],
+ type: 'task' as const,
+ };
+ host.transports.tools!.registerWork = vi.fn().mockResolvedValue(undefined);
+ runTool.mockResolvedValueOnce({
+ attempts: 1,
+ result: {
+ content: 'task created',
+ executionTime: 100,
+ state: {},
+ success: true,
+ workRegistration: taskIntent,
+ },
+ });
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },
+ type: 'call_tool',
+ };
+
+ const result = await callTool(host)(instruction, createState());
+
+ const toolEnd = findEvent(publishEvent.mock.calls, 'tool_end');
+ expect(toolEnd.data.result.workRegistration).toEqual(taskIntent);
+ const toolResultEvent = result.events.find(
+ (event: any) => event.type === 'tool_result',
+ ) as any;
+ expect(toolResultEvent.result.workRegistration).toEqual(taskIntent);
+ });
+
+ it('redacts a skill intent on the returned events but registers the full intent (batch path)', async () => {
+ const skillIntent = createSkillIntent();
+ const registerWork = vi.fn().mockResolvedValue(undefined);
+ host.transports.tools!.registerWork = registerWork;
+ runTool.mockResolvedValue({
+ attempts: 1,
+ result: {
+ content: 'issue found',
+ executionTime: 100,
+ state: {},
+ success: true,
+ workRegistration: skillIntent,
+ },
+ });
+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {
+ payload: {
+ parentMessageId: 'assistant-msg-1',
+ toolsCalling: [createToolCall('server-call')],
+ },
+ type: 'call_tools_batch',
+ };
+
+ const result = await callToolsBatch(host)(instruction, createState());
+
+ const toolResultEvent = result.events.find(
+ (event: any) => event.type === 'tool_result',
+ ) as any;
+ expect(toolResultEvent.result.workRegistration.data).toBeNull();
+ expect(toolResultEvent.result.workRegistration.args).toBeUndefined();
+
+ const toolEnd = findEvent(publishEvent.mock.calls, 'tool_end');
+ expect(toolEnd.data.result.workRegistration.data).toBeNull();
+
+ expect(registerWork).toHaveBeenCalledTimes(1);
+ const registeredIntent = registerWork.mock.calls[0][0].intent;
+ expect(registeredIntent.data).toEqual(skillIntent.data);
+ expect(registeredIntent.args).toEqual(skillIntent.args);
+ });
+ });
});
diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.ts
index a1158696c4e..38c122d7df4 100644
--- a/packages/agent-runtime/src/executors/tool.ts
+++ b/packages/agent-runtime/src/executors/tool.ts
@@ -1,7 +1,12 @@
-import type { ChatToolPayload } from '@lobechat/types';
+import type { ChatToolPayload, WorkRegistrationIntent } from '@lobechat/types';
import { UsageCounter } from '../core';
-import type { AgentRuntimeHost, ToolRunContext, ToolRunResult } from '../transport';
+import type {
+ AgentRuntimeHost,
+ ToolRunContext,
+ ToolRunResult,
+ ToolWorkRegistration,
+} from '../transport';
import type {
AgentEvent,
AgentInstruction,
@@ -21,6 +26,8 @@ interface ToolResultEntry {
data: ToolRunResult;
executionTime: number;
isSuccess: boolean;
+ /** Tool message this result was persisted to — provenance for Work versions. */
+ sourceMessageId?: string;
toolCall: ChatToolPayload;
toolCallId: string;
usageParams?: {
@@ -29,10 +36,27 @@ interface ToolResultEntry {
toolCost: number;
toolName: string;
};
+ /** Carried so the post-batch accumulate loop can persist the Work version. */
+ workRegistration?: WorkRegistrationIntent;
}
const nowIso = () => new Date().toISOString();
+/**
+ * Skill work-registration intents carry the UNTRUNCATED tool payload
+ * (`data`/`args`) solely for server-side Work registration, which reads it
+ * off the in-process `executionResult` before anything leaves the executor.
+ * Strip it from every copy that DOES leave: realtime `tool_end` stream events
+ * (clients only read `workRegistration` as a presence flag, see
+ * gatewayEventHandler) and the recorded step `tool_result` events
+ * (AgentStateManager serializes those into Redis, where the raw payload would
+ * bloat the capped event blob).
+ */
+const redactResultForEvents = (result: ToolRunResult): ToolRunResult =>
+ result.workRegistration?.type === 'skill'
+ ? { ...result, workRegistration: { ...result.workRegistration, args: undefined, data: null } }
+ : result;
+
const markPersistFatal = <T>(error: T): T => {
if (error && typeof error === 'object') persistFatalErrors.add(error);
return error;
@@ -117,6 +141,7 @@ const createRunContext = ({
state,
stepContext,
tool,
+ toolMessageId,
}: {
host: AgentRuntimeHost;
mode: ToolRunContext['mode'];
@@ -125,6 +150,7 @@ const createRunContext = ({
state: AgentState;
stepContext?: AgentRuntimeContext['stepContext'];
tool: ChatToolPayload;
+ toolMessageId?: string;
}): ToolRunContext => {
const toolName = toolNameOf(tool);
const toolSource = resolveToolSource(state, tool);
@@ -148,6 +174,7 @@ const createRunContext = ({
stepIndex: host.operation.stepIndex,
stepContext,
threadId: host.operation.threadId ?? state.metadata?.threadId,
+ toolMessageId,
toolName,
toolResultMaxLength: agentConfig?.chatConfig?.toolResultMaxLength,
toolSource,
@@ -353,6 +380,7 @@ export const callTool =
state,
stepContext: runtimeContext?.stepContext,
tool,
+ toolMessageId: payload.skipCreateToolMessage ? payload.parentMessageId : undefined,
});
await host.transports.stream.publishEvent({
@@ -401,7 +429,7 @@ export const callTool =
maxAttempts: (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,
payload,
phase: TOOL_EXECUTION_PHASE,
- result: executionResult,
+ result: redactResultForEvents(executionResult),
},
stepIndex: host.operation.stepIndex,
type: 'tool_end',
@@ -446,7 +474,11 @@ export const callTool =
}
newState.lastModified = nowIso();
- events.push({ id: tool.id, result: executionResult, type: 'tool_result' });
+ events.push({
+ id: tool.id,
+ result: redactResultForEvents(executionResult),
+ type: 'tool_result',
+ });
const toolCost = tools.getCost?.(runContext.toolName) ?? 0;
const { usage, cost } = UsageCounter.accumulateTool({
@@ -461,6 +493,24 @@ export const callTool =
newState.usage = usage;
if (cost) newState.cost = cost;
+ // Persist the Work version ONCE, now that `accumulateTool` has resolved
+ // the cumulative cost. The tool execution only produced the registration
+ // intent (task / skill / document identity); provenance + cost are
+ // stamped here at insert time — no cost-less insert + later backfill.
+ if (executionResult.workRegistration) {
+ await tools.registerWork?.(
+ {
+ intent: executionResult.workRegistration,
+ sourceMessageId: toolMessageId,
+ sourceToolCallId: tool.id,
+ sourceToolIdentifier: tool.identifier,
+ sourceToolName: tool.apiName,
+ state: { cost: newState.cost, usage: newState.usage },
+ },
+ newState,
+ );
+ }
+
persistActivatedTools({
effectiveManifestMap: runContext.effectiveManifestMap,
newState,
@@ -597,7 +647,7 @@ export const callToolsBatch =
maxAttempts: (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,
payload: { parentMessageId, toolCalling: tool },
phase: TOOL_EXECUTION_PHASE,
- result: executionResult,
+ result: redactResultForEvents(executionResult),
},
stepIndex: host.operation.stepIndex,
type: 'tool_end',
@@ -621,15 +671,24 @@ export const callToolsBatch =
}
toolMessageIds.push(toolMessageId);
+ // `sourceMessageId` + `workRegistration` are carried so the
+ // post-batch accumulate loop can persist the Work version ONCE with
+ // this call's cumulative cost (known only then).
const resultEntry: ToolResultEntry = {
data: executionResult,
executionTime,
isSuccess,
+ sourceMessageId: toolMessageId,
toolCall: tool,
toolCallId: tool.id,
+ workRegistration: executionResult.workRegistration,
};
- events.push({ id: tool.id, result: executionResult, type: 'tool_result' });
+ events.push({
+ id: tool.id,
+ result: redactResultForEvents(executionResult),
+ type: 'tool_result',
+ });
const toolCost = tools.getCost?.(runContext.toolName) ?? 0;
resultEntry.usageParams = {
@@ -651,6 +710,9 @@ export const callToolsBatch =
);
const newState = structuredClone(state);
+ // Work-registration intents produced by the tool executions, paired with
+ // the cumulative cost as of their tool call so the version is inserted ONCE.
+ const workRegistrations: ToolWorkRegistration[] = [];
for (const result of toolResults) {
if (!result.usageParams) continue;
@@ -661,6 +723,25 @@ export const callToolsBatch =
});
newState.usage = usage;
if (cost) newState.cost = cost;
+
+ if (result.workRegistration) {
+ // Snapshot the running totals as of this tool call so the version is
+ // inserted with the right cumulative cost; the writes fire together
+ // below (each targets its own sourceToolCallId row).
+ workRegistrations.push({
+ intent: result.workRegistration,
+ sourceMessageId: result.sourceMessageId,
+ sourceToolCallId: result.toolCallId,
+ sourceToolIdentifier: result.toolCall.identifier,
+ sourceToolName: result.toolCall.apiName,
+ state: { cost: newState.cost, usage: newState.usage },
+ });
+ }
+ }
+ if (workRegistrations.length > 0 && tools.registerWork) {
+ await Promise.all(
+ workRegistrations.map((registration) => tools.registerWork!(registration, newState)),
+ );
}
persistActivatedTools({
diff --git a/packages/agent-runtime/src/transport/tool.ts b/packages/agent-runtime/src/transport/tool.ts
index 94bc2737bd6..2ee7f441b0d 100644
--- a/packages/agent-runtime/src/transport/tool.ts
+++ b/packages/agent-runtime/src/transport/tool.ts
@@ -1,4 +1,4 @@
-import type { ChatToolPayload, RuntimeStepContext } from '@lobechat/types';
+import type { ChatToolPayload, RuntimeStepContext, WorkRegistrationIntent } from '@lobechat/types';
import type { AgentState } from '../types';
import type { RuntimeRetryKind } from '../utils';
@@ -14,6 +14,34 @@ export interface ToolRunResult {
/** Tool result requests the current runtime flow to stop. */
stop?: boolean;
success: boolean;
+ /**
+ * Work-registration intent produced by the tool execution (task / skill /
+ * document identity). The executor forwards it to
+ * {@link ToolTransport.registerWork} once cumulative cost is known.
+ */
+ workRegistration?: WorkRegistrationIntent;
+}
+
+/**
+ * A Work version ready to persist: the executor pairs the tool's registration
+ * intent with provenance and the cumulative usage/cost snapshot as of that
+ * tool call, so the version is inserted ONCE — no cost-less insert + backfill.
+ */
+export interface ToolWorkRegistration {
+ intent: WorkRegistrationIntent;
+ /** Tool message the Work version is anchored to. */
+ sourceMessageId?: string;
+ sourceToolCallId: string;
+ /**
+ * Tool/plugin identifier that produced this registration (the tool payload's
+ * `identifier`, e.g. 'lobe-task' / 'lobe-agent-documents'). Stamped onto the
+ * Work as the creator tool. Skills stamp their own provider DB-side instead.
+ */
+ sourceToolIdentifier: string;
+ /** Fallback `source` for task Works (the API name); skills use their own toolName. */
+ sourceToolName: string;
+ /** Cumulative usage/cost as of this tool call. */
+ state: Pick<AgentState, 'cost' | 'usage'>;
}
export interface ToolRunExecution {
@@ -53,6 +81,12 @@ export interface ToolRunContext {
stepContext?: RuntimeStepContext;
stepIndex: number;
threadId?: string;
+ /**
+ * Pre-existing tool message the result will be written into (resume /
+ * `skipCreateToolMessage` flow) — unset when a new tool message is created
+ * after execution.
+ */
+ toolMessageId?: string;
toolName: string;
toolResultMaxLength?: number;
toolSource?: string;
@@ -75,6 +109,12 @@ export interface ToolTransport {
context: ToolRunContext,
) => Promise<void> | void;
maxRetries?: number;
+ /**
+ * Persists a Work version for a tool run that produced a
+ * {@link ToolRunResult.workRegistration} intent. Called by the executor
+ * AFTER usage accumulation so the registration carries the cumulative cost.
+ */
+ registerWork?: (registration: ToolWorkRegistration, state: AgentState) => Promise<void>;
run: (call: ChatToolPayload, context: ToolRunContext) => Promise<ToolRunExecution>;
shouldRetry?: (kind: RuntimeRetryKind, attempt: number, maxRetries: number) => boolean;
}
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
index e116e3f08d4..1e679442bf5 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
@@ -44,10 +44,44 @@ describe('AgentDocumentsExecutionRuntime', () => {
});
expect(result.state).toMatchObject({
agentDocumentId: 'agent-doc-1',
+ agentId: 'agent-1',
+ documentId: 'backing-doc-1',
+ });
+ });
+
+ it('surfaces the identity block and pre-reads documentId when removing a document', async () => {
+ const readDocument = vi.fn().mockResolvedValue({
+ documentId: 'backing-doc-1',
+ id: 'agent-doc-1',
+ title: 'Doomed',
+ });
+ const removeDocument = vi.fn().mockResolvedValue(true);
+ const runtime = createRuntime({ readDocument, removeDocument });
+
+ const result = await runtime.removeDocument({ id: 'agent-doc-1' }, { agentId: 'agent-1' });
+
+ expect(readDocument).toHaveBeenCalledWith({ agentId: 'agent-1', id: 'agent-doc-1' });
+ expect(result.success).toBe(true);
+ expect(result.state).toMatchObject({
+ agentDocumentId: 'agent-doc-1',
+ agentId: 'agent-1',
+ deleted: true,
documentId: 'backing-doc-1',
});
});
+ it('returns a not-found result when removeDocument pre-read misses', async () => {
+ const readDocument = vi.fn().mockResolvedValue(undefined);
+ const removeDocument = vi.fn();
+ const runtime = createRuntime({ readDocument, removeDocument });
+
+ const result = await runtime.removeDocument({ id: 'missing' }, { agentId: 'agent-1' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Document not found: missing');
+ expect(removeDocument).not.toHaveBeenCalled();
+ });
+
it('awaits an async document URL builder', async () => {
const createDocument = vi.fn().mockResolvedValue({
documentId: 'docs_backing-doc-1',
@@ -104,7 +138,9 @@ describe('AgentDocumentsExecutionRuntime', () => {
agentId: 'agent-1',
messageId: 'user-msg-1',
operationId: 'op-client-1',
+ threadId: 'thread-1',
toolCallId: 'call-create-doc-1',
+ toolMessageId: 'tool-msg-1',
topicId: 'topic-1',
},
);
@@ -116,7 +152,56 @@ describe('AgentDocumentsExecutionRuntime', () => {
toolContext: {
messageId: 'user-msg-1',
operationId: 'op-client-1',
+ threadId: 'thread-1',
toolCallId: 'call-create-doc-1',
+ toolMessageId: 'tool-msg-1',
+ topicId: 'topic-1',
+ },
+ trigger: 'tool',
+ });
+ });
+
+ it('forwards tool trigger metadata when mutating documents with same-turn tool context', async () => {
+ const readDocument = vi.fn().mockResolvedValue({
+ documentId: 'backing-doc-1',
+ id: 'agent-doc-1',
+ title: 'Research Notes',
+ });
+ const renameDocument = vi.fn().mockResolvedValue({
+ documentId: 'backing-doc-1',
+ id: 'agent-doc-1',
+ title: 'Renamed Notes',
+ });
+ const runtime = createRuntime({ readDocument, renameDocument });
+
+ await runtime.renameDocument(
+ {
+ id: 'agent-doc-1',
+ newTitle: 'Renamed Notes',
+ },
+ {
+ agentId: 'agent-1',
+ messageId: 'user-msg-1',
+ operationId: 'op-client-1',
+ rootOperationId: 'op-root-1',
+ threadId: 'thread-1',
+ toolCallId: 'call-rename-doc-1',
+ toolMessageId: 'tool-msg-rename-1',
+ topicId: 'topic-1',
+ },
+ );
+
+ expect(renameDocument).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ id: 'agent-doc-1',
+ newTitle: 'Renamed Notes',
+ toolContext: {
+ messageId: 'user-msg-1',
+ operationId: 'op-client-1',
+ rootOperationId: 'op-root-1',
+ threadId: 'thread-1',
+ toolCallId: 'call-rename-doc-1',
+ toolMessageId: 'tool-msg-rename-1',
topicId: 'topic-1',
},
trigger: 'tool',
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
index bc3570b521d..8e582af3050 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
@@ -45,25 +45,31 @@ interface AgentDocumentOperationContext {
currentDocumentId?: string | null;
messageId?: string | null;
operationId?: string | null;
+ rootOperationId?: string | null;
scope?: string | null;
taskId?: string | null;
+ threadId?: string | null;
toolCallId?: string | null;
+ toolMessageId?: string | null;
topicId?: string | null;
}
/**
- * Attribution data captured from a builtin tool call that creates an agent document.
+ * Attribution data captured from a builtin tool call that mutates an agent document.
*/
interface AgentDocumentToolContext {
messageId: string;
operationId?: string;
+ rootOperationId?: string;
taskId?: string | null;
+ threadId?: string | null;
toolCallId: string;
+ toolMessageId?: string;
topicId?: string;
}
/**
- * Tool-call attribution input for document create operations.
+ * Tool-call attribution input for document mutation operations.
*/
interface AgentDocumentToolTriggerInput {
/**
@@ -97,7 +103,7 @@ export interface AgentDocumentsRuntimeService {
copyDocument: (
params: CopyDocumentArgs & {
agentId: string;
- },
+ } & AgentDocumentToolTriggerInput,
) => Promise<AgentDocumentRecord | undefined>;
createDocument: (
params: CreateDocumentArgs & {
@@ -124,7 +130,7 @@ export interface AgentDocumentsRuntimeService {
modifyNodes: (
params: ModifyDocumentNodesArgs & {
agentId: string;
- },
+ } & AgentDocumentToolTriggerInput,
) => Promise<AgentDocumentRecord | undefined>;
readDocument: (
params: ReadDocumentArgs & {
@@ -134,17 +140,17 @@ export interface AgentDocumentsRuntimeService {
removeDocument: (
params: RemoveDocumentArgs & {
agentId: string;
- },
+ } & AgentDocumentToolTriggerInput,
) => Promise<boolean>;
renameDocument: (
params: RenameDocumentArgs & {
agentId: string;
- },
+ } & AgentDocumentToolTriggerInput,
) => Promise<AgentDocumentRecord | undefined>;
replaceDocumentContent: (
params: ReplaceDocumentContentArgs & {
agentId: string;
- },
+ } & AgentDocumentToolTriggerInput,
) => Promise<AgentDocumentRecord | undefined>;
updateLoadRule: (
params: UpdateLoadRuleArgs & {
@@ -227,7 +233,10 @@ export class AgentDocumentsExecutionRuntime {
};
if (context.operationId) toolContext.operationId = context.operationId;
+ if (context.rootOperationId) toolContext.rootOperationId = context.rootOperationId;
if (context.taskId) toolContext.taskId = context.taskId;
+ if (context.threadId) toolContext.threadId = context.threadId;
+ if (context.toolMessageId) toolContext.toolMessageId = context.toolMessageId;
if (context.topicId) toolContext.topicId = context.topicId;
return {
@@ -402,7 +411,7 @@ export class AgentDocumentsExecutionRuntime {
return {
content: formatCreateDocumentResult({ id: created.id, title, url }),
- state: { agentDocumentId: created.id, documentId: created.documentId },
+ state: { agentDocumentId: created.id, agentId, documentId: created.documentId },
success: true,
};
}
@@ -450,7 +459,11 @@ export class AgentDocumentsExecutionRuntime {
return this.buildCurrentPageDocumentWriteBlockedResult('replaceDocumentContent');
}
- const doc = await this.service.replaceDocumentContent({ ...args, agentId });
+ const doc = await this.service.replaceDocumentContent({
+ ...args,
+ ...this.buildToolTriggerInput(context),
+ agentId,
+ });
if (!doc) return { content: `Failed to update document ${args.id}.`, success: false };
const url = await this.buildDocumentUrl(agentId, doc.documentId ?? existing.documentId);
@@ -461,7 +474,13 @@ export class AgentDocumentsExecutionRuntime {
title: doc.title ?? existing.title,
url,
}),
- state: { id: args.id, updated: true },
+ state: {
+ agentDocumentId: args.id,
+ agentId,
+ documentId: doc.documentId ?? existing.documentId,
+ id: args.id,
+ updated: true,
+ },
success: true,
};
}
@@ -490,7 +509,12 @@ export class AgentDocumentsExecutionRuntime {
return { content: 'No operations provided.', success: false };
}
- const updated = await this.service.modifyNodes({ agentId, id: args.id, operations });
+ const updated = await this.service.modifyNodes({
+ agentId,
+ ...this.buildToolTriggerInput(context),
+ id: args.id,
+ operations,
+ });
if (!updated) return { content: `Failed to modify document ${args.id}.`, success: false };
const results = operations.map((operation) => ({
@@ -508,6 +532,9 @@ export class AgentDocumentsExecutionRuntime {
url,
}),
state: {
+ agentDocumentId: args.id,
+ agentId,
+ documentId: updated.documentId ?? existing.documentId,
id: args.id,
results,
successCount: results.length,
@@ -529,12 +556,29 @@ export class AgentDocumentsExecutionRuntime {
};
}
- const deleted = await this.service.removeDocument({ ...args, agentId });
+ // Pre-read the backing `documents` row id so the deleted document's Work can
+ // be located from `state` after the row is gone. Mirrors the replace / rename
+ // / modify pre-read and keeps the total query count flat (the server service
+ // impl previously ran this lookup imperatively for the delete registration).
+ const existing = await this.service.readDocument({ agentId, id: args.id });
+ if (!existing) return { content: `Document not found: ${args.id}`, success: false };
+
+ const deleted = await this.service.removeDocument({
+ ...args,
+ ...this.buildToolTriggerInput(context),
+ agentId,
+ });
if (!deleted) return { content: `Document not found: ${args.id}`, success: false };
return {
content: formatRemoveDocumentResult({ id: args.id }),
- state: { deleted: true, id: args.id },
+ state: {
+ agentDocumentId: args.id,
+ agentId,
+ deleted: true,
+ documentId: existing.documentId,
+ id: args.id,
+ },
success: true,
};
}
@@ -558,14 +602,25 @@ export class AgentDocumentsExecutionRuntime {
return this.buildCurrentPageDocumentWriteBlockedResult('renameDocument');
}
- const doc = await this.service.renameDocument({ ...args, agentId });
+ const doc = await this.service.renameDocument({
+ ...args,
+ ...this.buildToolTriggerInput(context),
+ agentId,
+ });
if (!doc) return { content: `Failed to rename document ${args.id}.`, success: false };
const url = await this.buildDocumentUrl(agentId, doc.documentId ?? existing.documentId);
return {
content: formatRenameDocumentResult({ id: args.id, title: args.newTitle, url }),
- state: { id: args.id, newTitle: args.newTitle, renamed: true },
+ state: {
+ agentDocumentId: args.id,
+ agentId,
+ documentId: doc.documentId ?? existing.documentId,
+ id: args.id,
+ newTitle: args.newTitle,
+ renamed: true,
+ },
success: true,
};
}
@@ -582,7 +637,11 @@ export class AgentDocumentsExecutionRuntime {
};
}
- const copied = await this.service.copyDocument({ ...args, agentId });
+ const copied = await this.service.copyDocument({
+ ...args,
+ ...this.buildToolTriggerInput(context),
+ agentId,
+ });
if (!copied) return { content: `Document not found: ${args.id}`, success: false };
const url = await this.buildDocumentUrl(agentId, copied.documentId);
@@ -594,7 +653,13 @@ export class AgentDocumentsExecutionRuntime {
title: copied.title,
url,
}),
- state: { copiedFromId: args.id, newDocumentId: copied.id },
+ state: {
+ agentDocumentId: copied.id,
+ agentId,
+ copiedFromId: args.id,
+ documentId: copied.documentId,
+ newDocumentId: copied.id,
+ },
success: true,
};
}
diff --git a/packages/builtin-tool-agent-documents/src/executor/index.ts b/packages/builtin-tool-agent-documents/src/executor/index.ts
index 11ecf5aa3ee..f693c1c6fa0 100644
--- a/packages/builtin-tool-agent-documents/src/executor/index.ts
+++ b/packages/builtin-tool-agent-documents/src/executor/index.ts
@@ -70,11 +70,14 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsAp
return this.runtime.createDocument(params, {
agentId: ctx.agentId,
currentDocumentId: ctx.documentId,
- messageId: ctx.sourceMessageId,
+ messageId: ctx.sourceMessageId ?? ctx.messageId,
operationId: ctx.operationId,
+ rootOperationId: ctx.rootOperationId,
scope: ctx.scope,
taskId: ctx.taskId,
+ threadId: ctx.threadId,
toolCallId: ctx.toolCallId,
+ toolMessageId: ctx.toolMessageId,
topicId: ctx.topicId,
});
};
@@ -97,7 +100,15 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsAp
return this.runtime.replaceDocumentContent(params, {
agentId: ctx.agentId,
currentDocumentId: ctx.documentId,
+ messageId: ctx.sourceMessageId ?? ctx.messageId,
+ operationId: ctx.operationId,
+ rootOperationId: ctx.rootOperationId,
scope: ctx.scope,
+ taskId: ctx.taskId,
+ threadId: ctx.threadId,
+ toolCallId: ctx.toolCallId,
+ toolMessageId: ctx.toolMessageId,
+ topicId: ctx.topicId,
});
};
@@ -108,7 +119,15 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsAp
return this.runtime.modifyNodes(params, {
agentId: ctx.agentId,
currentDocumentId: ctx.documentId,
+ messageId: ctx.sourceMessageId ?? ctx.messageId,
+ operationId: ctx.operationId,
+ rootOperationId: ctx.rootOperationId,
scope: ctx.scope,
+ taskId: ctx.taskId,
+ threadId: ctx.threadId,
+ toolCallId: ctx.toolCallId,
+ toolMessageId: ctx.toolMessageId,
+ topicId: ctx.topicId,
});
};
@@ -119,7 +138,15 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsAp
return this.runtime.removeDocument(params, {
agentId: ctx.agentId,
currentDocumentId: ctx.documentId,
+ messageId: ctx.sourceMessageId ?? ctx.messageId,
+ operationId: ctx.operationId,
+ rootOperationId: ctx.rootOperationId,
scope: ctx.scope,
+ taskId: ctx.taskId,
+ threadId: ctx.threadId,
+ toolCallId: ctx.toolCallId,
+ toolMessageId: ctx.toolMessageId,
+ topicId: ctx.topicId,
});
};
@@ -130,7 +157,15 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsAp
return this.runtime.renameDocument(params, {
agentId: ctx.agentId,
currentDocumentId: ctx.documentId,
+ messageId: ctx.sourceMessageId ?? ctx.messageId,
+ operationId: ctx.operationId,
+ rootOperationId: ctx.rootOperationId,
scope: ctx.scope,
+ taskId: ctx.taskId,
+ threadId: ctx.threadId,
+ toolCallId: ctx.toolCallId,
+ toolMessageId: ctx.toolMessageId,
+ topicId: ctx.topicId,
});
};
@@ -141,7 +176,15 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsAp
return this.runtime.copyDocument(params, {
agentId: ctx.agentId,
currentDocumentId: ctx.documentId,
+ messageId: ctx.sourceMessageId ?? ctx.messageId,
+ operationId: ctx.operationId,
+ rootOperationId: ctx.rootOperationId,
scope: ctx.scope,
+ taskId: ctx.taskId,
+ threadId: ctx.threadId,
+ toolCallId: ctx.toolCallId,
+ toolMessageId: ctx.toolMessageId,
+ topicId: ctx.topicId,
});
};
diff --git a/packages/builtin-tool-agent-documents/src/manifest.ts b/packages/builtin-tool-agent-documents/src/manifest.ts
index fe51083d51e..a40e7a2efc7 100644
--- a/packages/builtin-tool-agent-documents/src/manifest.ts
+++ b/packages/builtin-tool-agent-documents/src/manifest.ts
@@ -36,6 +36,10 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
required: ['title', 'content'],
type: 'object',
},
+ work: {
+ action: 'create',
+ resourceType: 'document',
+ },
},
{
description:
@@ -77,6 +81,10 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
required: ['id', 'content'],
type: 'object',
},
+ work: {
+ action: 'update',
+ resourceType: 'document',
+ },
},
{
description:
@@ -140,6 +148,10 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
required: ['id', 'operations'],
type: 'object',
},
+ work: {
+ action: 'update',
+ resourceType: 'document',
+ },
},
{
description: 'Remove an existing agent document by ID (similar intent to rm/delete).',
@@ -154,6 +166,10 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
required: ['id'],
type: 'object',
},
+ work: {
+ action: 'delete',
+ resourceType: 'document',
+ },
},
{
description:
@@ -173,6 +189,10 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
required: ['id', 'newTitle'],
type: 'object',
},
+ work: {
+ action: 'update',
+ resourceType: 'document',
+ },
},
{
description: 'Copy an existing document to a new document (similar intent to cp/copy).',
@@ -191,6 +211,10 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
required: ['id'],
type: 'object',
},
+ work: {
+ action: 'create',
+ resourceType: 'document',
+ },
},
{
description:
diff --git a/packages/builtin-tool-agent-documents/src/types.ts b/packages/builtin-tool-agent-documents/src/types.ts
index d8297846a29..5f87a416ac7 100644
--- a/packages/builtin-tool-agent-documents/src/types.ts
+++ b/packages/builtin-tool-agent-documents/src/types.ts
@@ -21,6 +21,8 @@ export interface CreateDocumentArgs {
export interface CreateDocumentState {
agentDocumentId?: string;
+ /** Owning agent id — used to attribute the created document's Work. */
+ agentId?: string;
documentId?: string;
}
@@ -42,6 +44,13 @@ export interface ReplaceDocumentContentArgs {
}
export interface ReplaceDocumentContentState {
+ /** The `agentDocuments` association row id. */
+ agentDocumentId?: string;
+ /** Owning agent id — used to attribute the document's Work. */
+ agentId?: string;
+ /** The backing `documents` table row id — the Work resource identity. */
+ documentId?: string;
+ /** @deprecated Prefer {@link agentDocumentId}; same-meaning alias kept for historical states. */
id: string;
updated: boolean;
}
@@ -69,9 +78,7 @@ export interface ModifyDocumentRemoveOperation {
}
export type ModifyDocumentOperation =
- | ModifyDocumentInsertOperation
- | ModifyDocumentRemoveOperation
- | ModifyDocumentUpdateOperation;
+ ModifyDocumentInsertOperation | ModifyDocumentRemoveOperation | ModifyDocumentUpdateOperation;
export interface ModifyDocumentNodesArgs {
id: string;
@@ -79,6 +86,13 @@ export interface ModifyDocumentNodesArgs {
}
export interface ModifyDocumentNodesState {
+ /** The `agentDocuments` association row id. */
+ agentDocumentId?: string;
+ /** Owning agent id — used to attribute the document's Work. */
+ agentId?: string;
+ /** The backing `documents` table row id — the Work resource identity. */
+ documentId?: string;
+ /** @deprecated Prefer {@link agentDocumentId}; same-meaning alias kept for historical states. */
id: string;
results: Array<{
action: 'insert' | 'remove' | 'modify';
@@ -93,7 +107,14 @@ export interface RemoveDocumentArgs {
}
export interface RemoveDocumentState {
+ /** The `agentDocuments` association row id. */
+ agentDocumentId?: string;
+ /** Owning agent id — used to attribute the document's Work. */
+ agentId?: string;
deleted: boolean;
+ /** The backing `documents` table row id — the Work resource identity. */
+ documentId?: string;
+ /** @deprecated Prefer {@link agentDocumentId}; same-meaning alias kept for historical states. */
id: string;
}
@@ -103,6 +124,13 @@ export interface RenameDocumentArgs {
}
export interface RenameDocumentState {
+ /** The `agentDocuments` association row id. */
+ agentDocumentId?: string;
+ /** Owning agent id — used to attribute the document's Work. */
+ agentId?: string;
+ /** The backing `documents` table row id — the Work resource identity. */
+ documentId?: string;
+ /** @deprecated Prefer {@link agentDocumentId}; same-meaning alias kept for historical states. */
id: string;
newTitle: string;
renamed: boolean;
@@ -114,7 +142,15 @@ export interface CopyDocumentArgs {
}
export interface CopyDocumentState {
+ /** The new copy's `agentDocuments` association row id. */
+ agentDocumentId?: string;
+ /** Owning agent id — used to attribute the copied document's Work. */
+ agentId?: string;
+ /** Source document's `agentDocuments` row id (NOT the new copy). */
copiedFromId: string;
+ /** The new copy's backing `documents` table row id — the Work resource identity. */
+ documentId?: string;
+ /** @deprecated Prefer {@link agentDocumentId}; same-meaning alias kept for historical states. */
newDocumentId?: string;
}
diff --git a/packages/builtin-tool-task/src/client/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.ts
index 296e534da86..f4c37cdae22 100644
--- a/packages/builtin-tool-task/src/client/executor/index.ts
+++ b/packages/builtin-tool-task/src/client/executor/index.ts
@@ -174,7 +174,13 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
}
};
- createTask = async (
+ /**
+ * Shared single-task create used by both `createTask` and the `createTasks`
+ * batch loop. Returns the raw {@link BuiltinToolResult}; Work registration is
+ * driven by the manifest `work` config at the tool-execution dispatch layer
+ * (`invokeExecutor`), not here.
+ */
+ #createTask = async (
params: {
instruction: string;
assigneeAgentId?: string;
@@ -228,6 +234,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
priority: task.priority,
status: task.status as TaskStatus,
success: true,
+ taskId: task.id,
},
success: true,
};
@@ -245,6 +252,18 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
}
};
+ createTask = async (
+ params: {
+ instruction: string;
+ assigneeAgentId?: string;
+ name: string;
+ parentIdentifier?: string;
+ priority?: number;
+ sortOrder?: number;
+ },
+ ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => this.#createTask(params, ctx);
+
createTasks = async (
params: { tasks: CreateTaskParams[] },
ctx?: BuiltinToolContext,
@@ -263,16 +282,13 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
const results: CreateTasksItemResult[] = [];
for (const item of items) {
- const result = await this.createTask(item, ctx);
+ const result = await this.#createTask(item, ctx);
const success = result.success === true;
- const identifier =
- success && result.state && typeof result.state.identifier === 'string'
- ? (result.state.identifier as string)
- : undefined;
const error = success
? undefined
: result.error?.message ||
(typeof result.content === 'string' ? result.content : 'Unknown error');
+ const identifier = (result.state as { identifier?: string } | undefined)?.identifier;
results.push({ error, identifier, name: item.name, success });
}
@@ -303,7 +319,11 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
return {
content: formatTaskDeleted(label, deleted?.name),
- state: { identifier: label, success: true },
+ // Surface the deleted task's internal id so the manifest-driven dispatch
+ // layer (`work: { action: 'delete' }`) can delete its Work + refresh the
+ // conversation caches — the task row is gone, so the Work can only be
+ // located by `works.resourceId = taskId`.
+ state: { identifier: label, success: true, taskId: deleted?.id },
success: true,
};
} catch (error) {
@@ -824,6 +844,9 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
const id = await getTaskStoreState().updateTaskStatus(identifier, params.status, {
error: params.error,
});
+ // Work chips read live task status via the message-list summary join;
+ // settle-time refresh (WorksSection / gateway tool_end) picks it up —
+ // avoid a full `message:list` revalidate on every status tool call.
return {
content:
diff --git a/packages/builtin-tool-task/src/client/executor/onAfterCall.test.ts b/packages/builtin-tool-task/src/client/executor/onAfterCall.test.ts
index c839baa370c..046ab09e40d 100644
--- a/packages/builtin-tool-task/src/client/executor/onAfterCall.test.ts
+++ b/packages/builtin-tool-task/src/client/executor/onAfterCall.test.ts
@@ -5,7 +5,13 @@ import { TaskApiName } from '../../types';
const mocks = vi.hoisted(() => ({
getChatStoreState: vi.fn(),
getTaskStoreState: vi.fn(),
+ internalRefreshTaskDetail: vi.fn(),
openTaskDetail: vi.fn(),
+ refreshConversation: vi.fn(),
+ refreshTaskList: vi.fn(),
+ refreshVersions: vi.fn(),
+ registerTask: vi.fn(),
+ updateVerifyConfig: vi.fn(),
}));
vi.mock('@/store/chat', () => ({
@@ -21,7 +27,17 @@ vi.mock('@/store/task/slices/detail/reducer', () => ({
}));
vi.mock('@/services/task', () => ({
- taskService: {},
+ taskService: {
+ updateVerifyConfig: mocks.updateVerifyConfig,
+ },
+}));
+
+vi.mock('@/services/work', () => ({
+ workService: {
+ refreshConversation: mocks.refreshConversation,
+ refreshVersions: mocks.refreshVersions,
+ registerTask: mocks.registerTask,
+ },
}));
// Imported after mocks so the executor module resolves the stubbed stores.
@@ -29,12 +45,18 @@ const { taskExecutor } = await import('./index');
describe('TaskExecutor.onAfterCall — portal auto-open', () => {
beforeEach(() => {
- mocks.openTaskDetail.mockClear();
+ vi.clearAllMocks();
+ mocks.internalRefreshTaskDetail.mockResolvedValue(undefined);
+ mocks.refreshConversation.mockResolvedValue(undefined);
+ mocks.refreshTaskList.mockResolvedValue(undefined);
+ mocks.refreshVersions.mockResolvedValue(undefined);
+ mocks.registerTask.mockResolvedValue({ id: 'work-1' });
+ mocks.updateVerifyConfig.mockResolvedValue(undefined);
mocks.getChatStoreState.mockReturnValue({ openTaskDetail: mocks.openTaskDetail });
mocks.getTaskStoreState.mockReturnValue({
activeTaskId: undefined,
- internal_refreshTaskDetail: vi.fn().mockResolvedValue(undefined),
- refreshTaskList: vi.fn().mockResolvedValue(undefined),
+ internal_refreshTaskDetail: mocks.internalRefreshTaskDetail,
+ refreshTaskList: mocks.refreshTaskList,
taskDetailMap: {},
});
});
@@ -68,4 +90,32 @@ describe('TaskExecutor.onAfterCall — portal auto-open', () => {
expect(mocks.openTaskDetail).not.toHaveBeenCalled();
});
+
+ // Note: Work registration is no longer done inside the executor. It now runs
+ // at the tool-execution dispatch layer (`invokeExecutor`), driven by the
+ // manifest `work` config — covered by the dispatch-layer + shared-extractor
+ // tests instead.
+ it('applies verify config and refreshes the task detail', async () => {
+ const result = await taskExecutor.setTaskVerify(
+ {
+ enabled: true,
+ identifier: 'TASK-1',
+ requirement: 'Ship tested output',
+ },
+ { agentId: 'agent-1' } as any,
+ );
+
+ expect(result.success).toBe(true);
+ expect(mocks.updateVerifyConfig).toHaveBeenCalledWith({
+ id: 'TASK-1',
+ verify: {
+ enabled: true,
+ requirement: 'Ship tested output',
+ },
+ });
+ expect(mocks.internalRefreshTaskDetail).toHaveBeenCalledWith('TASK-1');
+ // The executor itself no longer registers Work or touches the work caches.
+ expect(mocks.registerTask).not.toHaveBeenCalled();
+ expect(mocks.refreshVersions).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.ts
index 8a77e40c42f..5093a3855ee 100644
--- a/packages/builtin-tool-task/src/manifest.ts
+++ b/packages/builtin-tool-task/src/manifest.ts
@@ -47,6 +47,10 @@ export const TaskManifest: BuiltinToolManifest = {
required: ['name', 'instruction'],
type: 'object',
},
+ work: {
+ action: 'create',
+ resourceType: 'task',
+ },
},
{
description:
@@ -97,6 +101,10 @@ export const TaskManifest: BuiltinToolManifest = {
required: ['tasks'],
type: 'object',
},
+ work: {
+ action: 'create',
+ resourceType: 'task',
+ },
},
{
description:
@@ -256,6 +264,10 @@ export const TaskManifest: BuiltinToolManifest = {
required: ['identifier'],
type: 'object',
},
+ work: {
+ action: 'update',
+ resourceType: 'task',
+ },
},
{
description:
@@ -339,6 +351,10 @@ export const TaskManifest: BuiltinToolManifest = {
required: ['identifier'],
type: 'object',
},
+ work: {
+ action: 'update',
+ resourceType: 'task',
+ },
},
{
description:
@@ -385,6 +401,10 @@ export const TaskManifest: BuiltinToolManifest = {
required: ['identifier'],
type: 'object',
},
+ work: {
+ action: 'update',
+ resourceType: 'task',
+ },
},
{
description:
@@ -426,6 +446,10 @@ export const TaskManifest: BuiltinToolManifest = {
required: ['identifier'],
type: 'object',
},
+ work: {
+ action: 'delete',
+ resourceType: 'task',
+ },
},
],
identifier: TaskIdentifier,
@@ -435,5 +459,6 @@ export const TaskManifest: BuiltinToolManifest = {
title: 'Task Tools',
},
systemRole: systemPrompt,
+
type: 'builtin',
};
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index 30ccf0dde1a..53c1ae6c52a 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -14,7 +14,8 @@
"./portals": "./src/portals.ts",
"./streamings": "./src/streamings.ts",
"./identifiers": "./src/identifiers.ts",
- "./dynamicInterventionAudits": "./src/dynamicInterventionAudits.ts"
+ "./dynamicInterventionAudits": "./src/dynamicInterventionAudits.ts",
+ "./workRegistration": "./src/workRegistration.ts"
},
"main": "./src/index.ts",
"dependencies": {
diff --git a/packages/builtin-tools/src/workRegistration.test.ts b/packages/builtin-tools/src/workRegistration.test.ts
new file mode 100644
index 00000000000..726033d223c
--- /dev/null
+++ b/packages/builtin-tools/src/workRegistration.test.ts
@@ -0,0 +1,557 @@
+import type { LobeBuiltinTool, WorkRegistrationIntent } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ dispatchWorkRegistrationIntent,
+ extractDocumentWorkTarget,
+ extractTaskWorkTargets,
+ getApiWorkConfig,
+ resolveWorkRegistration,
+ workChangeTypeFromAction,
+ type WorkRegistrationPorts,
+ type WorkRegistrationProvenance,
+} from './workRegistration';
+
+const registry = [
+ {
+ identifier: 'lobe-task',
+ manifest: {
+ api: [
+ { name: 'createTask', work: { action: 'create', resourceType: 'task' } },
+ { name: 'createTasks', work: { action: 'create', resourceType: 'task' } },
+ { name: 'editTask', work: { action: 'update', resourceType: 'task' } },
+ { name: 'deleteTask', work: { action: 'delete', resourceType: 'task' } },
+ { name: 'listTasks' },
+ ],
+ },
+ },
+ {
+ identifier: 'lobe-agent-documents',
+ manifest: {
+ api: [
+ { name: 'createDocument', work: { action: 'create', resourceType: 'document' } },
+ { name: 'replaceDocumentContent', work: { action: 'update', resourceType: 'document' } },
+ { name: 'removeDocument', work: { action: 'delete', resourceType: 'document' } },
+ { name: 'readDocument' },
+ ],
+ },
+ },
+] as unknown as LobeBuiltinTool[];
+
+describe('getApiWorkConfig', () => {
+ it('returns the work config for an API that declares one', () => {
+ expect(getApiWorkConfig(registry, 'lobe-task', 'createTask')).toEqual({
+ action: 'create',
+ resourceType: 'task',
+ });
+ });
+
+ it('returns undefined for an API without a work config', () => {
+ expect(getApiWorkConfig(registry, 'lobe-task', 'listTasks')).toBeUndefined();
+ });
+
+ it('returns undefined for an unknown tool or API', () => {
+ expect(getApiWorkConfig(registry, 'lobe-unknown', 'createTask')).toBeUndefined();
+ expect(getApiWorkConfig(registry, 'lobe-task', 'unknownApi')).toBeUndefined();
+ });
+});
+
+describe('workChangeTypeFromAction', () => {
+ it('maps create → created and update → updated', () => {
+ expect(workChangeTypeFromAction('create')).toBe('created');
+ expect(workChangeTypeFromAction('update')).toBe('updated');
+ // `delete` is excluded from the input type — it writes no version changeType and
+ // must never be silently mapped to 'updated' (see resolveWorkRegistration).
+ });
+});
+
+describe('extractTaskWorkTargets', () => {
+ it('extracts a single created task from state (taskId + identifier)', () => {
+ expect(
+ extractTaskWorkTargets({
+ args: { name: 'A', instruction: 'do' },
+ result: { state: { identifier: 'T-1', taskId: 'task_1', success: true }, success: true },
+ }),
+ ).toEqual([{ taskId: 'task_1', taskIdentifier: 'T-1' }]);
+ });
+
+ it('falls back to args.identifier for updates that return no state (server runtime)', () => {
+ expect(
+ extractTaskWorkTargets({
+ args: { identifier: 'T-9' },
+ result: { success: true },
+ }),
+ ).toEqual([{ taskId: undefined, taskIdentifier: 'T-9' }]);
+ });
+
+ it('prefers state.identifier over args.identifier for updates', () => {
+ expect(
+ extractTaskWorkTargets({
+ args: { identifier: 'T-args' },
+ result: { state: { identifier: 'T-state', success: true }, success: true },
+ }),
+ ).toEqual([{ taskId: undefined, taskIdentifier: 'T-state' }]);
+ });
+
+ it('returns no targets when a single call failed', () => {
+ expect(
+ extractTaskWorkTargets({
+ args: { identifier: 'T-1' },
+ result: { success: false },
+ }),
+ ).toEqual([]);
+ });
+
+ it('extracts only the succeeded items from a batch, ignoring top-level success', () => {
+ expect(
+ extractTaskWorkTargets({
+ args: { tasks: [] },
+ result: {
+ state: {
+ failed: 1,
+ results: [
+ { identifier: 'T-A', name: 'A', success: true },
+ { error: 'boom', name: 'B', success: false },
+ { identifier: 'T-C', name: 'C', success: true },
+ ],
+ succeeded: 2,
+ },
+ // partial-failure batch reports overall failure but still registers winners
+ success: false,
+ },
+ }),
+ ).toEqual([
+ { taskId: undefined, taskIdentifier: 'T-A' },
+ { taskId: undefined, taskIdentifier: 'T-C' },
+ ]);
+ });
+
+ it('returns no targets for an empty batch', () => {
+ expect(
+ extractTaskWorkTargets({
+ args: { tasks: [] },
+ result: { state: { failed: 0, results: [], succeeded: 0 }, success: false },
+ }),
+ ).toEqual([]);
+ });
+});
+
+describe('resolveWorkRegistration', () => {
+ it('resolves create/update into a changeType-bearing plan', () => {
+ expect(
+ resolveWorkRegistration(registry, 'lobe-task', 'createTask', {
+ args: {},
+ result: { state: { identifier: 'T-1', taskId: 'task_1', success: true }, success: true },
+ }),
+ ).toEqual({
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ type: 'task',
+ });
+
+ expect(
+ resolveWorkRegistration(registry, 'lobe-task', 'editTask', {
+ args: { identifier: 'T-9' },
+ result: { success: true },
+ }),
+ ).toEqual({
+ action: 'update',
+ changeType: 'updated',
+ targets: [{ taskId: undefined, taskIdentifier: 'T-9' }],
+ type: 'task',
+ });
+ });
+
+ it('resolves delete into a changeType-less plan keyed off state.taskId', () => {
+ expect(
+ resolveWorkRegistration(registry, 'lobe-task', 'deleteTask', {
+ args: { identifier: 'T-1' },
+ result: { state: { identifier: 'T-1', taskId: 'task_1', success: true }, success: true },
+ }),
+ ).toEqual({
+ action: 'delete',
+ targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ type: 'task',
+ });
+ });
+
+ it('returns undefined when a delete call yields no extractable target', () => {
+ expect(
+ resolveWorkRegistration(registry, 'lobe-task', 'deleteTask', {
+ args: { identifier: 'T-1' },
+ result: { success: false },
+ }),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined for an API without a work config', () => {
+ expect(
+ resolveWorkRegistration(registry, 'lobe-task', 'listTasks', {
+ args: {},
+ result: { success: true },
+ }),
+ ).toBeUndefined();
+ });
+
+ it('resolves a document create/update directly into the final register intent', () => {
+ expect(
+ resolveWorkRegistration(registry, 'lobe-agent-documents', 'createDocument', {
+ args: {},
+ result: {
+ state: { agentDocumentId: 'assoc_1', agentId: 'agent-1', documentId: 'doc_1' },
+ success: true,
+ },
+ }),
+ ).toEqual({
+ action: 'register',
+ document: {
+ agentDocumentId: 'assoc_1',
+ agentId: 'agent-1',
+ changeType: 'created',
+ documentId: 'doc_1',
+ toolName: 'createDocument',
+ },
+ type: 'document',
+ });
+
+ expect(
+ resolveWorkRegistration(registry, 'lobe-agent-documents', 'replaceDocumentContent', {
+ args: { id: 'assoc_1' },
+ result: {
+ state: { agentDocumentId: 'assoc_1', agentId: 'agent-1', documentId: 'doc_1' },
+ success: true,
+ },
+ }),
+ ).toEqual({
+ action: 'register',
+ document: {
+ agentDocumentId: 'assoc_1',
+ agentId: 'agent-1',
+ changeType: 'updated',
+ documentId: 'doc_1',
+ toolName: 'replaceDocumentContent',
+ },
+ type: 'document',
+ });
+ });
+
+ it('resolves a document delete into a changeType-less plan keyed off state.documentId', () => {
+ expect(
+ resolveWorkRegistration(registry, 'lobe-agent-documents', 'removeDocument', {
+ args: { id: 'assoc_1' },
+ result: {
+ state: { agentDocumentId: 'assoc_1', agentId: 'agent-1', documentId: 'doc_1' },
+ success: true,
+ },
+ }),
+ ).toEqual({
+ action: 'delete',
+ document: { agentDocumentId: 'assoc_1', agentId: 'agent-1', documentId: 'doc_1' },
+ type: 'document',
+ });
+ });
+
+ it('returns undefined for a document API without a work config (readDocument)', () => {
+ expect(
+ resolveWorkRegistration(registry, 'lobe-agent-documents', 'readDocument', {
+ args: { id: 'assoc_1' },
+ result: {
+ state: { agentDocumentId: 'assoc_1', agentId: 'agent-1', documentId: 'doc_1' },
+ success: true,
+ },
+ }),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined for a failed document call', () => {
+ expect(
+ resolveWorkRegistration(registry, 'lobe-agent-documents', 'createDocument', {
+ args: {},
+ result: {
+ state: { agentDocumentId: 'assoc_1', agentId: 'agent-1', documentId: 'doc_1' },
+ success: false,
+ },
+ }),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined for a document call missing documentId in state', () => {
+ expect(
+ resolveWorkRegistration(registry, 'lobe-agent-documents', 'createDocument', {
+ args: {},
+ result: { state: { agentDocumentId: 'assoc_1', agentId: 'agent-1' }, success: true },
+ }),
+ ).toBeUndefined();
+ });
+});
+
+describe('extractDocumentWorkTarget', () => {
+ it('extracts the identity block from a successful mutation state', () => {
+ expect(
+ extractDocumentWorkTarget({
+ result: {
+ state: { agentDocumentId: 'assoc_1', agentId: 'agent-1', documentId: 'doc_1' },
+ success: true,
+ },
+ }),
+ ).toEqual({ agentDocumentId: 'assoc_1', agentId: 'agent-1', documentId: 'doc_1' });
+ });
+
+ it('returns undefined when the call failed', () => {
+ expect(
+ extractDocumentWorkTarget({
+ result: {
+ state: { agentDocumentId: 'assoc_1', agentId: 'agent-1', documentId: 'doc_1' },
+ success: false,
+ },
+ }),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined when documentId or agentId is missing', () => {
+ expect(
+ extractDocumentWorkTarget({
+ result: { state: { agentDocumentId: 'assoc_1', agentId: 'agent-1' }, success: true },
+ }),
+ ).toBeUndefined();
+ expect(
+ extractDocumentWorkTarget({
+ result: { state: { agentDocumentId: 'assoc_1', documentId: 'doc_1' }, success: true },
+ }),
+ ).toBeUndefined();
+ });
+});
+
+describe('dispatchWorkRegistrationIntent', () => {
+ const provenance: WorkRegistrationProvenance = {
+ agentId: 'agent-1',
+ cumulativeCost: 0.011,
+ cumulativeUsage: { capturedAt: '2026-06-30T08:00:00.000Z', cost: { total: 0.011 } },
+ rootOperationId: 'op-root',
+ messageId: 'msg-1',
+ toolCallId: 'tool-call-1',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ };
+
+ const buildPorts = (overrides?: Partial<WorkRegistrationPorts>): WorkRegistrationPorts => ({
+ deleteDocumentWork: vi.fn().mockResolvedValue(undefined),
+ deleteTaskWork: vi.fn().mockResolvedValue(undefined),
+ handleSkillToolResult: vi.fn().mockResolvedValue(undefined),
+ registerDocument: vi.fn().mockResolvedValue(undefined),
+ registerTask: vi.fn().mockResolvedValue(undefined),
+ ...overrides,
+ });
+
+ describe('task', () => {
+ it('registers every target of a create intent with provenance + cumulative usage', async () => {
+ const ports = buildPorts();
+ const intent: WorkRegistrationIntent = {
+ action: 'create',
+ changeType: 'created',
+ targets: [
+ { taskId: 'task_1', taskIdentifier: 'T-1' },
+ { taskId: 'task_2', taskIdentifier: 'T-2' },
+ ],
+ type: 'task',
+ };
+
+ await dispatchWorkRegistrationIntent(intent, ports, provenance);
+
+ expect(ports.registerTask).toHaveBeenCalledTimes(2);
+ expect(ports.registerTask).toHaveBeenNthCalledWith(1, {
+ agentId: 'agent-1',
+ changeType: 'created',
+ cumulativeCost: 0.011,
+ cumulativeUsage: provenance.cumulativeUsage,
+ rootOperationId: 'op-root',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ messageId: 'msg-1',
+ toolCallId: 'tool-call-1',
+ taskId: 'task_1',
+ taskIdentifier: 'T-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+ expect(ports.registerTask).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ taskId: 'task_2', taskIdentifier: 'T-2' }),
+ );
+ });
+
+ it('deletes each target that has a taskId and skips targetless ids', async () => {
+ const ports = buildPorts();
+ const intent: WorkRegistrationIntent = {
+ action: 'delete',
+ targets: [{ taskId: 'task_1' }, { taskIdentifier: 'T-2' }, { taskId: 'task_3' }],
+ type: 'task',
+ };
+
+ await dispatchWorkRegistrationIntent(intent, ports, provenance);
+
+ expect(ports.deleteTaskWork).toHaveBeenCalledTimes(2);
+ expect(ports.deleteTaskWork).toHaveBeenCalledWith({ taskId: 'task_1' });
+ expect(ports.deleteTaskWork).toHaveBeenCalledWith({ taskId: 'task_3' });
+ expect(ports.registerTask).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op for a create/update intent missing its changeType', async () => {
+ const ports = buildPorts();
+ const intent = {
+ action: 'create',
+ targets: [{ taskId: 'task_1' }],
+ type: 'task',
+ } as unknown as WorkRegistrationIntent;
+
+ await dispatchWorkRegistrationIntent(intent, ports, provenance);
+
+ expect(ports.registerTask).not.toHaveBeenCalled();
+ expect(ports.deleteTaskWork).not.toHaveBeenCalled();
+ });
+
+ it('keeps registering siblings when one target rejects (allSettled tolerance)', async () => {
+ const registerTask = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('trpc died'))
+ .mockResolvedValueOnce(undefined);
+ const ports = buildPorts({ registerTask });
+ const intent: WorkRegistrationIntent = {
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: 'task_1' }, { taskId: 'task_2' }],
+ type: 'task',
+ };
+
+ await expect(
+ dispatchWorkRegistrationIntent(intent, ports, provenance),
+ ).resolves.toBeUndefined();
+ expect(registerTask).toHaveBeenCalledTimes(2);
+ });
+
+ it('logs a rejected registration with sanitized context while still resolving', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ try {
+ const registerTask = vi.fn().mockRejectedValue(new Error('trpc died'));
+ const ports = buildPorts({ registerTask });
+ const intent: WorkRegistrationIntent = {
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ type: 'task',
+ };
+
+ await expect(
+ dispatchWorkRegistrationIntent(intent, ports, provenance),
+ ).resolves.toBeUndefined();
+
+ expect(consoleError).toHaveBeenCalledTimes(1);
+ expect(consoleError).toHaveBeenCalledWith(
+ '[workRegistration] failed to persist task Work',
+ expect.objectContaining({
+ action: 'create',
+ error: expect.any(Error),
+ rootOperationId: 'op-root',
+ toolCallId: 'tool-call-1',
+ taskId: 'task_1',
+ taskIdentifier: 'T-1',
+ }),
+ );
+ } finally {
+ consoleError.mockRestore();
+ }
+ });
+ });
+
+ describe('document', () => {
+ it('registers a document with provenance + cumulative usage', async () => {
+ const ports = buildPorts();
+ const intent: WorkRegistrationIntent = {
+ action: 'register',
+ document: {
+ agentId: 'agent-1',
+ changeType: 'created',
+ documentId: 'doc_1',
+ toolName: 'createDocument',
+ },
+ type: 'document',
+ };
+
+ await dispatchWorkRegistrationIntent(intent, ports, provenance);
+
+ expect(ports.registerDocument).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ changeType: 'created',
+ cumulativeCost: 0.011,
+ documentId: 'doc_1',
+ rootOperationId: 'op-root',
+ toolName: 'createDocument',
+ toolCallId: 'tool-call-1',
+ }),
+ );
+ });
+
+ it('routes a document delete to the deleteDocumentWork port when present', async () => {
+ const ports = buildPorts();
+ const intent: WorkRegistrationIntent = {
+ action: 'delete',
+ document: { agentId: 'agent-1', documentId: 'doc_1' },
+ type: 'document',
+ };
+
+ await dispatchWorkRegistrationIntent(intent, ports, provenance);
+
+ expect(ports.deleteDocumentWork).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ documentId: 'doc_1',
+ });
+ expect(ports.registerDocument).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op for a document delete when the port is absent (client)', async () => {
+ const ports = buildPorts({ deleteDocumentWork: undefined });
+ const intent: WorkRegistrationIntent = {
+ action: 'delete',
+ document: { documentId: 'doc_1' },
+ type: 'document',
+ };
+
+ await expect(
+ dispatchWorkRegistrationIntent(intent, ports, provenance),
+ ).resolves.toBeUndefined();
+ expect(ports.registerDocument).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('skill', () => {
+ it('forwards the skill payload to handleSkillToolResult with cumulative usage', async () => {
+ const ports = buildPorts();
+ const intent: WorkRegistrationIntent = {
+ args: { title: 'x' },
+ data: { url: 'https://linear.app/x' },
+ provider: 'linear',
+ toolName: 'createIssue',
+ type: 'skill',
+ };
+
+ await dispatchWorkRegistrationIntent(intent, ports, provenance);
+
+ expect(ports.handleSkillToolResult).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ args: { title: 'x' },
+ cumulativeCost: 0.011,
+ data: { url: 'https://linear.app/x' },
+ provider: 'linear',
+ rootOperationId: 'op-root',
+ toolCallId: 'tool-call-1',
+ toolName: 'createIssue',
+ }),
+ );
+ });
+ });
+});
diff --git a/packages/builtin-tools/src/workRegistration.ts b/packages/builtin-tools/src/workRegistration.ts
new file mode 100644
index 00000000000..f15931c8e50
--- /dev/null
+++ b/packages/builtin-tools/src/workRegistration.ts
@@ -0,0 +1,517 @@
+import type {
+ BuiltinToolResult,
+ DeleteDocumentWorkParams,
+ DeleteTaskWorkParams,
+ LobeBuiltinTool,
+ PluginApiWorkAction,
+ PluginApiWorkConfig,
+ PluginApiWorkResourceType,
+ RegisterDocumentWorkParams,
+ RegisterSkillToolResultWorkParams,
+ RegisterTaskWorkParams,
+ WorkRegistrationIntent,
+ WorkTaskTarget,
+ WorkVersionChangeType,
+ WorkVersionCumulativeUsage,
+} from '@lobechat/types';
+
+/**
+ * Shared, dependency-light helpers for manifest-driven Work registration.
+ *
+ * The tool-execution dispatch layers (server `BuiltinToolsExecutor` and client
+ * `invokeExecutor`) both consume these so the "what to register" logic lives in
+ * exactly ONE place with ONE test suite. Each layer keeps its own "how to
+ * register" wiring (server → `WorkModel`, client → `workService` + SWR
+ * refreshes) because those are inherently side-of-the-wire specific.
+ *
+ * Kept free of the heavy `builtinTools` registry import (type-only deps) so it
+ * can be pulled into either bundle cheaply — callers pass their own registry
+ * reference into {@link getApiWorkConfig}.
+ */
+
+/**
+ * A resolved document Work target extracted from a tool result's `state`.
+ * Documents have no batch operation, so there is exactly one target per call.
+ */
+export interface DocumentWorkTarget {
+ agentDocumentId?: string;
+ agentId: string;
+ documentId: string;
+}
+
+type WorkRegistrationIntentType = WorkRegistrationIntent['type'];
+type WorkRegistrationIntentFor<Type extends WorkRegistrationIntentType> = Extract<
+ WorkRegistrationIntent,
+ { type: Type }
+>;
+
+interface WorkRegistrationResolveContext {
+ apiName: string;
+ config: PluginApiWorkConfig;
+ payload: { args: unknown; result: Pick<BuiltinToolResult, 'state' | 'success'> };
+}
+
+interface WorkRegistrationAdapter<Type extends WorkRegistrationIntentType> {
+ dispatch: (
+ intent: WorkRegistrationIntentFor<Type>,
+ ports: WorkRegistrationPorts,
+ provenance: WorkRegistrationProvenance,
+ ) => Promise<void>;
+ resolve?: (
+ context: WorkRegistrationResolveContext,
+ ) => WorkRegistrationIntentFor<Type> | undefined;
+}
+
+type WorkRegistrationAdapterRegistry = {
+ [Type in WorkRegistrationIntentType]: WorkRegistrationAdapter<Type>;
+} & {
+ [Type in PluginApiWorkResourceType]: WorkRegistrationAdapter<Type> & {
+ resolve: NonNullable<WorkRegistrationAdapter<Type>['resolve']>;
+ };
+};
+
+/**
+ * Look up the declarative `work` config for a tool API from a builtin-tool
+ * registry. Reads the static manifest (the `work` config is context-free, so
+ * `resolveManifest` overrides never apply to it). Returns `undefined` when the
+ * tool/API declares no Work.
+ */
+export const getApiWorkConfig = (
+ tools: LobeBuiltinTool[],
+ identifier: string,
+ apiName: string,
+): PluginApiWorkConfig | undefined =>
+ tools
+ .find((tool) => tool.identifier === identifier)
+ ?.manifest.api.find((api) => api.name === apiName)?.work;
+
+/**
+ * Map a version-producing Work action onto the persisted version changeType. Only
+ * `create` / `update` reach this — `delete` writes no version, so it is
+ * deliberately excluded from the input type rather than silently mapped.
+ */
+export const workChangeTypeFromAction = (
+ action: Exclude<PluginApiWorkAction, 'delete'>,
+): WorkVersionChangeType => (action === 'create' ? 'created' : 'updated');
+
+const asString = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.length > 0 ? value : undefined;
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null;
+
+/** Read a non-empty string field off an optional untrusted record. */
+const optionalStringFromRecord = (
+ record: Record<string, unknown> | undefined,
+ key: string,
+): string | undefined => (record ? asString(record[key]) : undefined);
+
+/** One task-identity candidate before success-filtering and identity mapping. */
+interface TaskWorkTargetCandidate {
+ identifier?: unknown;
+ success?: unknown;
+ taskId?: unknown;
+}
+
+/**
+ * Extract the task identities to register from a `resourceType: 'task'` API
+ * result. Works uniformly for server and client because both surface identity
+ * the same way:
+ *
+ * - Batch (`createTasks`): `result.state.results[]`, each `{ identifier,
+ * success }`. Only the succeeded items are registered — a partially failed
+ * batch still registers its winners (top-level `success` is `false`, so this
+ * is gated per item, not on the whole result).
+ * - Single create (`createTask`): `result.state.taskId` / `result.state.identifier`.
+ * - Single update (`editTask` / `setTaskSchedule` / `setTaskVerify`): the
+ * `identifier` is a required manifest param, so it falls back to
+ * `args.identifier` when the server runtime returns no state.
+ *
+ * Single-target extraction is gated on `result.success` so a failed update
+ * (whose `args.identifier` is still present) never registers a phantom version.
+ */
+export const extractTaskWorkTargets = ({
+ args,
+ result,
+}: {
+ args: unknown;
+ result: Pick<BuiltinToolResult, 'state' | 'success'>;
+}): WorkTaskTarget[] => {
+ const stateRecord = isRecord(result.state) ? result.state : undefined;
+ const argsRecord = isRecord(args) ? args : undefined;
+
+ // Normalize both shapes into one candidate list, then run a single
+ // success-filter → identity-map → drop-empty pipeline:
+ // - Batch (`createTasks`): each `state.results[]` item, gated per item so a
+ // partially failed batch still registers its winners (top-level `success`
+ // is ignored here).
+ // - Single (`createTask` / `editTask` / …): one synthetic item gated on the
+ // call's own `success`; the update identifier falls back to
+ // `args.identifier` when the server runtime returns no state.
+ const candidates: unknown[] = Array.isArray(stateRecord?.results)
+ ? stateRecord.results
+ : result.success
+ ? [
+ {
+ identifier:
+ optionalStringFromRecord(stateRecord, 'identifier') ??
+ optionalStringFromRecord(argsRecord, 'identifier'),
+ success: true,
+ taskId: stateRecord?.taskId,
+ } satisfies TaskWorkTargetCandidate,
+ ]
+ : [];
+
+ return candidates
+ .filter(isRecord)
+ .filter((item) => (item as TaskWorkTargetCandidate).success === true)
+ .map((item) => ({
+ taskId: asString((item as TaskWorkTargetCandidate).taskId),
+ taskIdentifier: asString((item as TaskWorkTargetCandidate).identifier),
+ }))
+ .filter((target) => Boolean(target.taskId || target.taskIdentifier));
+};
+
+/**
+ * Extract the single document identity to register from a `resourceType:
+ * 'document'` API result. The document runtime stamps a uniform identity block
+ * (`agentDocumentId` / `agentId` / `documentId`) into `state` for every mutating
+ * API, so extraction is a flat read off `result.state`.
+ *
+ * Returns `undefined` unless the call SUCCEEDED and both `documentId` (the Work
+ * resource identity — the backing `documents` row) and `agentId` (the agent
+ * producing the version and validating the binding) are present.
+ * `agentDocumentId` is optional metadata and does not gate registration.
+ */
+export const extractDocumentWorkTarget = ({
+ result,
+}: {
+ result: Pick<BuiltinToolResult, 'state' | 'success'>;
+}): DocumentWorkTarget | undefined => {
+ if (!result.success) return undefined;
+
+ const stateRecord = isRecord(result.state) ? result.state : undefined;
+ const agentDocumentId = optionalStringFromRecord(stateRecord, 'agentDocumentId');
+ const agentId = optionalStringFromRecord(stateRecord, 'agentId');
+ const documentId = optionalStringFromRecord(stateRecord, 'documentId');
+
+ if (!documentId || !agentId) return undefined;
+
+ return { agentDocumentId, agentId, documentId };
+};
+
+const resolveTaskWorkIntent = ({
+ config,
+ payload,
+}: WorkRegistrationResolveContext): WorkRegistrationIntentFor<'task'> | undefined => {
+ const targets = extractTaskWorkTargets(payload);
+ if (targets.length === 0) return undefined;
+
+ // `delete` locates the Work by `state.taskId` (the task row is already gone),
+ // so it reuses the same target extraction but writes no version changeType.
+ if (config.action === 'delete') return { action: 'delete', targets, type: 'task' };
+
+ return {
+ action: config.action,
+ changeType: workChangeTypeFromAction(config.action),
+ targets,
+ type: 'task',
+ };
+};
+
+const resolveDocumentWorkIntent = ({
+ apiName,
+ config,
+ payload,
+}: WorkRegistrationResolveContext): WorkRegistrationIntentFor<'document'> | undefined => {
+ const document = extractDocumentWorkTarget(payload);
+ if (!document) return undefined;
+
+ // `delete` locates the Work by `state.documentId` (the row is already gone),
+ // so it reuses the same identity but writes no version changeType.
+ if (config.action === 'delete') return { action: 'delete', document, type: 'document' };
+
+ return {
+ action: 'register',
+ document: {
+ ...document,
+ changeType: workChangeTypeFromAction(config.action),
+ // The concrete API name is the document Work's producing tool.
+ toolName: apiName,
+ },
+ type: 'document',
+ };
+};
+
+/**
+ * Resolve the manifest-driven Work registration intent for a tool API call, or
+ * `undefined` when nothing should be registered (no `work` config, an
+ * unsupported `resourceType`, or no extractable targets).
+ *
+ * The type adapter emits the FINAL serializable intent directly. There is no
+ * intermediate resolved-plan union or second type switch before the intent is
+ * handed to the runtime.
+ */
+export const resolveWorkRegistration = (
+ tools: LobeBuiltinTool[],
+ identifier: string,
+ apiName: string,
+ payload: { args: unknown; result: Pick<BuiltinToolResult, 'state' | 'success'> },
+): WorkRegistrationIntent | undefined => {
+ const config = getApiWorkConfig(tools, identifier, apiName);
+ if (!config) return undefined;
+
+ const adapter = WORK_REGISTRATION_ADAPTERS[config.resourceType];
+ return adapter.resolve({ apiName, config, payload });
+};
+
+/**
+ * Side-of-the-wire persistence operations the dispatcher drives; the server
+ * backs them with `WorkModel` methods, the client with `workService` methods.
+ */
+export interface WorkRegistrationPorts {
+ /**
+ * Optional: the client deliberately does NOT handle document deletes (they
+ * stay a lambda-side effect of the `removeDocument` mutation — a deletion
+ * carries no cost, so it needs no cost-stamping defer). Leaving the port
+ * undefined makes the document-delete intent a no-op.
+ */
+ deleteDocumentWork?: (params: DeleteDocumentWorkParams) => Promise<unknown>;
+ deleteTaskWork: (params: DeleteTaskWorkParams) => Promise<unknown>;
+ handleSkillToolResult: (params: RegisterSkillToolResultWorkParams) => Promise<unknown>;
+ registerDocument: (params: RegisterDocumentWorkParams) => Promise<unknown>;
+ registerTask: (params: RegisterTaskWorkParams) => Promise<unknown>;
+}
+
+/**
+ * Runtime-supplied provenance stamped onto every persisted Work version. The
+ * cumulative cost/usage are stamped by the caller (not resolved here) because
+ * they are known only AFTER the tool call's `accumulateTool` step has computed
+ * the cumulative cost — see the wrapper JSDoc for why persistence is deferred
+ * until then.
+ */
+export interface WorkRegistrationProvenance {
+ agentId?: string | null;
+ cumulativeCost?: number | null;
+ cumulativeUsage?: WorkVersionCumulativeUsage | null;
+ messageId?: string;
+ rootOperationId?: string;
+ threadId?: string | null;
+ toolCallId?: string;
+ /**
+ * Tool/plugin identifier that produced this registration (the tool payload's
+ * `identifier`). Skills stamp their own provider DB-side, so this is unused
+ * for the skill branch.
+ */
+ toolIdentifier: string;
+ /** Fallback concrete tool name for task Works; skills/documents carry their own. */
+ toolName: string;
+ topicId?: string;
+}
+
+/**
+ * Log each rejected task-persistence result from a `Promise.allSettled` fan-out
+ * without breaking sibling-tolerance. The index correlates a settled result back
+ * to the target it was dispatched for (the two arrays are built in lockstep), so
+ * a failure carries enough sanitized context (action, task id/identifier,
+ * provenance ids, error) to be diagnosable — instead of silently vanishing.
+ */
+const logRejectedTaskWork = (
+ action: 'delete' | 'create' | 'update',
+ targets: WorkTaskTarget[],
+ results: PromiseSettledResult<unknown>[],
+ provenance: Pick<WorkRegistrationProvenance, 'rootOperationId' | 'toolCallId'>,
+): void => {
+ results.forEach((result, index) => {
+ if (result.status !== 'rejected') return;
+ const target = targets[index];
+
+ console.error('[workRegistration] failed to persist task Work', {
+ action,
+ error: result.reason,
+ rootOperationId: provenance.rootOperationId,
+ toolCallId: provenance.toolCallId,
+ taskId: target?.taskId,
+ taskIdentifier: target?.taskIdentifier,
+ });
+ });
+};
+
+const dispatchTaskWorkIntent = async (
+ intent: WorkRegistrationIntentFor<'task'>,
+ ports: WorkRegistrationPorts,
+ provenance: WorkRegistrationProvenance,
+): Promise<void> => {
+ const {
+ agentId,
+ cumulativeCost,
+ cumulativeUsage,
+ rootOperationId,
+ messageId,
+ threadId,
+ toolCallId,
+ toolIdentifier,
+ toolName,
+ topicId,
+ } = provenance;
+ const { action, changeType, targets } = intent;
+
+ if (action === 'delete') {
+ const deleteTargets = targets.filter((target) => target.taskId);
+ const results = await Promise.allSettled(
+ deleteTargets.map((target) => ports.deleteTaskWork({ taskId: target.taskId! })),
+ );
+ logRejectedTaskWork('delete', deleteTargets, results, { rootOperationId, toolCallId });
+ return;
+ }
+
+ if (!changeType) return;
+
+ const results = await Promise.allSettled(
+ targets.map((target) =>
+ ports.registerTask({
+ agentId,
+ changeType,
+ cumulativeCost,
+ cumulativeUsage,
+ rootOperationId,
+ messageId,
+ taskId: target.taskId,
+ taskIdentifier: target.taskIdentifier,
+ threadId,
+ toolCallId,
+ toolIdentifier,
+ toolName,
+ topicId,
+ }),
+ ),
+ );
+ logRejectedTaskWork(action, targets, results, { rootOperationId, toolCallId });
+};
+
+const dispatchDocumentWorkIntent = async (
+ intent: WorkRegistrationIntentFor<'document'>,
+ ports: WorkRegistrationPorts,
+ provenance: WorkRegistrationProvenance,
+): Promise<void> => {
+ if (intent.action === 'delete') {
+ // No-op when the port is absent (client): document deletes stay a
+ // lambda-side effect of the removeDocument mutation.
+ await ports.deleteDocumentWork?.(intent.document);
+ return;
+ }
+
+ const {
+ agentId: provenanceAgentId,
+ cumulativeCost,
+ cumulativeUsage,
+ rootOperationId,
+ messageId,
+ threadId,
+ toolCallId,
+ toolIdentifier,
+ topicId,
+ } = provenance;
+
+ await ports.registerDocument({
+ ...intent.document,
+ agentId: provenanceAgentId ?? intent.document.agentId,
+ cumulativeCost,
+ cumulativeUsage,
+ rootOperationId,
+ messageId,
+ threadId,
+ toolCallId,
+ toolIdentifier,
+ topicId,
+ });
+};
+
+const dispatchSkillWorkIntent = async (
+ intent: WorkRegistrationIntentFor<'skill'>,
+ ports: WorkRegistrationPorts,
+ provenance: WorkRegistrationProvenance,
+): Promise<void> => {
+ const {
+ agentId,
+ cumulativeCost,
+ cumulativeUsage,
+ rootOperationId,
+ messageId,
+ threadId,
+ toolCallId,
+ topicId,
+ } = provenance;
+
+ // Skill providers (Linear / GitHub) normalize the untruncated payload into a Work.
+ await ports.handleSkillToolResult({
+ agentId,
+ args: intent.args,
+ cumulativeCost,
+ cumulativeUsage,
+ data: intent.data,
+ provider: intent.provider,
+ rootOperationId,
+ messageId,
+ threadId,
+ toolCallId,
+ toolName: intent.toolName,
+ topicId,
+ });
+};
+
+/**
+ * Single extension point for Work registration types. Each adapter owns both
+ * sides of the serializable intent boundary: builtin result resolution (when
+ * applicable) and post-cost persistence. Adding a new intent type therefore
+ * fails this exhaustive registry until its behavior is registered here.
+ */
+export const WORK_REGISTRATION_ADAPTERS = {
+ document: {
+ dispatch: dispatchDocumentWorkIntent,
+ resolve: resolveDocumentWorkIntent,
+ },
+ skill: {
+ dispatch: dispatchSkillWorkIntent,
+ },
+ task: {
+ dispatch: dispatchTaskWorkIntent,
+ resolve: resolveTaskWorkIntent,
+ },
+} satisfies WorkRegistrationAdapterRegistry;
+
+/**
+ * Dispatch a Work registration intent through the same adapter registry that
+ * produced builtin intents. Consumed by BOTH persistence layers — the server runtime
+ * (`registerWorkFromIntent`, backed by `WorkModel`) and the legacy client
+ * runtime (`registerClientWorkFromIntent`, backed by `workService`). Each layer
+ * only supplies its own {@link WorkRegistrationPorts} and per-call
+ * {@link WorkRegistrationProvenance}; type-specific behavior lives in its adapter.
+ *
+ * Cost stamping happens in the wrappers, not here: the cumulative cost of a tool
+ * call is known only after `accumulateTool` runs, so each wrapper computes
+ * `cumulativeCost` / `cumulativeUsage` and passes them in via provenance. This
+ * dispatcher stays dependency-light (type-only `@lobechat/types` imports) so it
+ * can be pulled into either bundle cheaply.
+ *
+ * Multi-target fan-out uses `Promise.allSettled` so one target's failure never
+ * kills its siblings. This function does NOT swallow errors at the top level —
+ * the two wrappers keep their own try/catch + debug logging.
+ */
+export const dispatchWorkRegistrationIntent = async (
+ intent: WorkRegistrationIntent,
+ ports: WorkRegistrationPorts,
+ provenance: WorkRegistrationProvenance,
+): Promise<void> => {
+ // TypeScript cannot retain the correlation between a union discriminant and
+ // the matching mapped-registry value after indexed access. The registry key
+ // comes directly from the same intent, so this type erasure is localized and
+ // runtime-safe while every adapter remains strictly typed at declaration.
+ const dispatch = WORK_REGISTRATION_ADAPTERS[intent.type].dispatch as (
+ intent: WorkRegistrationIntent,
+ ports: WorkRegistrationPorts,
+ provenance: WorkRegistrationProvenance,
+ ) => Promise<void>;
+
+ await dispatch(intent, ports, provenance);
+};
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index f2d13b12dd2..6b74bd7ae9e 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -5,8 +5,10 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import { agents, briefs, documents, tasks, topics, users, workspaces } from '../../schemas';
import { taskTopics } from '../../schemas/task';
+import { works } from '../../schemas/work';
import type { LobeChatDatabase } from '../../type';
import { TaskModel } from '../task';
+import { WorkModel } from '../work';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -240,6 +242,27 @@ describe('TaskModel', () => {
const deleted = await model2.delete(task.id);
expect(deleted).toBe(false);
});
+
+ // Non-tool deletion (UI / CLI) must leave the Work artifact orphaned so the
+ // UI can render it as "resource deleted" from its snapshot. Tool-driven
+ // deletion removes the Work separately at the dispatch layer (LOBE-11606).
+ it('should NOT delete the task Work artifact', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Keep my Work' });
+ await workModel.registerTask({
+ changeType: 'created',
+ toolCallId: 'tool-call-task-keep',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ taskId: task.id,
+ });
+
+ await model.delete(task.id);
+
+ const workRows = await serverDB.select().from(works).where(eq(works.resourceId, task.id));
+ expect(workRows).toHaveLength(1);
+ });
});
describe('list', () => {
@@ -316,7 +339,7 @@ describe('TaskModel', () => {
const model = new TaskModel(serverDB, userId);
// Create tasks with different statuses
- const t1 = await model.create({ instruction: 'Backlog task' });
+ const _t1 = await model.create({ instruction: 'Backlog task' });
const t2 = await model.create({ instruction: 'Running task' });
await model.updateStatus(t2.id, 'running', { startedAt: new Date() });
const t3 = await model.create({ instruction: 'Paused task' });
diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.ts
index c49516ed909..781c84028b2 100644
--- a/packages/database/src/models/document.ts
+++ b/packages/database/src/models/document.ts
@@ -1,7 +1,7 @@
import { and, count, desc, eq, inArray, isNull, ne, notInArray, sum } from 'drizzle-orm';
import type { DocumentItem, NewDocument } from '../schemas';
-import { DOCUMENT_FOLDER_TYPE, documents, files } from '../schemas';
+import { DOCUMENT_FOLDER_TYPE, documents, files, works } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
@@ -318,7 +318,7 @@ export class DocumentModel {
const ids = subtree.map((d) => d.id);
- await (trx as LobeChatDatabase)
+ const updatedDocuments = await (trx as LobeChatDatabase)
.update(documents)
.set({ updatedAt: new Date(), visibility })
.where(
@@ -327,7 +327,28 @@ export class DocumentModel {
eq(documents.userId, this.userId),
eq(documents.visibility, fromVisibility),
),
- );
+ )
+ .returning({ id: documents.id });
+
+ const updatedDocumentIds = updatedDocuments.map(({ id }) => id);
+ if (updatedDocumentIds.length > 0) {
+ // Mirror visibility onto existing Work projections in the same
+ // transaction. Scope without works.visibility so a promotion can
+ // update rows that are currently private.
+ await (trx as LobeChatDatabase)
+ .update(works)
+ .set({ visibility })
+ .where(
+ and(
+ eq(works.resourceType, 'document'),
+ inArray(works.resourceId, updatedDocumentIds),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { userId: works.userId, workspaceId: works.workspaceId },
+ ),
+ ),
+ );
+ }
// No child-table cascade needed here — Pages (`sourceType: 'api'`) hold
// content inline in `documents.content` / `documents.pages`, and the
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index f51b574c89a..da72b181d94 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -21,6 +21,7 @@ import type {
UIChatMessage,
UpdateMessageParams,
UpdateMessageRAGParams,
+ WorkSummaryItem,
} from '@lobechat/types';
import { MessageGroupType, ThreadType } from '@lobechat/types';
import type { TimingSink } from '@lobechat/utils';
@@ -77,6 +78,18 @@ import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../
import { idGenerator } from '../utils/idGenerator';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { recomputeTopicUsage } from './topicUsage';
+import { WorkModel } from './work';
+
+/**
+ * Read the operation-final Work root id stamped on a message's metadata by the
+ * Work registry (`metadata.work.rootOperationId`). Mirrors the client-side
+ * `getOperationFinalRootId` without importing from the app layer.
+ */
+const getMessageWorkRootId = (metadata: unknown): string | undefined => {
+ const rootOperationId = (metadata as { work?: { rootOperationId?: unknown } } | null)?.work
+ ?.rootOperationId;
+ return typeof rootOperationId === 'string' && rootOperationId ? rootOperationId : undefined;
+};
/**
* Options for querying messages with relations
@@ -97,6 +110,10 @@ export interface QueryMessagesOptions {
path: string | null,
file: { fileType: string; id?: string | null },
) => Promise<string>;
+ /**
+ * Skip the Work-summary assembly (see `QueryMessageParams.skipWorks`).
+ */
+ skipWorks?: boolean;
timing?: ModelTimingContext;
/**
* Topic ID for MessageGroup aggregation queries
@@ -354,6 +371,7 @@ export class MessageModel {
current = 0,
pageSize = 1000,
sessionId,
+ skipWorks,
topicId,
groupId,
threadId,
@@ -403,6 +421,7 @@ export class MessageModel {
current,
pageSize,
postProcessUrl: options.postProcessUrl,
+ skipWorks,
timing,
// Thread queries optionally add agent/session scope if provided
where: agentCondition ? and(agentCondition, threadCondition) : threadCondition,
@@ -428,6 +447,7 @@ export class MessageModel {
current,
pageSize,
postProcessUrl: options.postProcessUrl,
+ skipWorks,
timing,
topicId: topicId ?? undefined,
where: whereCondition,
@@ -451,6 +471,7 @@ export class MessageModel {
current,
pageSize,
postProcessUrl: options.postProcessUrl,
+ skipWorks,
timing,
topicId: topicId ?? undefined,
where: whereCondition,
@@ -557,7 +578,15 @@ export class MessageModel {
* @returns Messages with all related data, including MessageGroup nodes
*/
queryWithWhere = async (options: QueryMessagesOptions = {}): Promise<UIChatMessage[]> => {
- const { where, current = 0, pageSize = 1000, postProcessUrl, topicId, timing } = options;
+ const {
+ where,
+ current = 0,
+ pageSize = 1000,
+ postProcessUrl,
+ skipWorks,
+ topicId,
+ timing,
+ } = options;
const totalStartedAt = Date.now();
const offset = current * pageSize;
@@ -667,12 +696,16 @@ export class MessageModel {
chunksList,
messageQueriesList,
threadData,
+ worksByMessageId,
] = await Promise.all([
messageGroupNodesPromise,
this.queryMessageFileRelations(messageIds, postProcessUrl, timing),
this.queryMessageChunkRelations(messageIds, timing),
this.queryMessageQueryRelations(messageIds, timing),
this.queryMessageThreadRelations(taskMessageIds, timing),
+ skipWorks
+ ? ({} as Record<string, WorkSummaryItem[]>)
+ : this.queryMessageWorkSummaries(result, timing),
]);
if (messageIds.length === 0 && messageGroupNodes.length === 0) {
@@ -780,6 +813,9 @@ export class MessageModel {
.filter((relation) => relation.messageId === item.id)
.map<ChatVideoItem>(({ id, url, name }) => ({ alt: name!, id, url })),
+ // Work summaries for this message's root operation, resolved
+ // server-side (attached only to the round's anchor message).
+ works: worksByMessageId[item.id as string],
audioList: audioList
.filter((relation) => relation.messageId === item.id)
@@ -1013,6 +1049,48 @@ export class MessageModel {
return chunksList;
};
+ /**
+ * Resolve Work summaries for a page of messages and key them by anchor
+ * message id — the LAST message (rows are createdAt-asc, so last occurrence)
+ * carrying each `metadata.work.rootOperationId`. Works ride the message-list
+ * payload so the in-message Works chips and the sidebar summary read from one
+ * source instead of a dedicated work-summary fetch. Attaching only to the
+ * round's last message (not every row sharing the operation) keeps the
+ * payload flat — the client re-keys by `rootOperationId`, so which row
+ * physically carries it doesn't matter.
+ */
+ private queryMessageWorkSummaries = async (
+ rows: { id: unknown; metadata: unknown }[],
+ timing?: ModelTimingContext,
+ ): Promise<Record<string, WorkSummaryItem[]>> => {
+ const anchorByRootId = new Map<string, string>();
+ for (const row of rows) {
+ const rootOperationId = getMessageWorkRootId(row.metadata);
+ if (rootOperationId) anchorByRootId.set(rootOperationId, row.id as string);
+ }
+ if (anchorByRootId.size === 0) return {};
+
+ const summaryMap = await runTimedStage(
+ timing,
+ 'db.message.queryWithWhere.workSummaries',
+ () =>
+ new WorkModel(this.db, this.userId, this.workspaceId).listSummariesByRootOperations({
+ rootOperationIds: Array.from(anchorByRootId.keys()),
+ }),
+ { rootOperationCount: anchorByRootId.size },
+ );
+
+ const worksByMessageId: Record<string, WorkSummaryItem[]> = {};
+ for (const [rootOperationId, messageId] of anchorByRootId) {
+ const works = summaryMap[rootOperationId];
+ if (works && works.length > 0) worksByMessageId[messageId] = works;
+ }
+ logTiming(timing, 'db.message.queryWithWhere.workSummaries:rows', {
+ messageCount: Object.keys(worksByMessageId).length,
+ });
+ return worksByMessageId;
+ };
+
private queryMessageQueryRelations = async (
messageIds: string[],
timing?: ModelTimingContext,
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index 61e7b233994..04f63080821 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -28,6 +28,7 @@ import { merge } from '@/utils/merge';
import { documents } from '../schemas/file';
import type { NewTaskComment, TaskCommentItem } from '../schemas/task';
import { taskComments, taskDependencies, taskDocuments, tasks, taskTopics } from '../schemas/task';
+import { works } from '../schemas/work';
import type { LobeChatDatabase } from '../type';
import { buildWorkspaceWhere } from '../utils/workspace';
@@ -246,13 +247,20 @@ export class TaskModel {
return updated[0] || null;
}
+ /**
+ * Delete a task. This does NOT touch the task's Work artifact: the Work
+ * lifecycle is driven by the deleteTask tool call at the tool-execution
+ * dispatch layer (which calls `WorkModel.deleteTaskWork`), so non-tool deletes
+ * (UI / CLI / deleteAll) deliberately leave the Work as an orphan for the UI
+ * to render as "resource deleted" from its version snapshot. See LOBE-11606.
+ */
async delete(id: string): Promise<boolean> {
- const result = await this.db
+ const deleted = await this.db
.delete(tasks)
.where(and(eq(tasks.id, id), this.ownership()))
- .returning();
+ .returning({ id: tasks.id });
- return result.length > 0;
+ return deleted.length > 0;
}
/**
@@ -320,6 +328,23 @@ export class TaskModel {
.set({ visibility })
.where(and(inArray(taskDocuments.taskId, taskIds), this.docsOwnership()));
+ // Work is a denormalized resource projection. Keep its indexed visibility
+ // mirror in the same transaction as the task subtree so gallery/list
+ // queries cannot observe a stale public row after demotion.
+ await tx
+ .update(works)
+ .set({ visibility })
+ .where(
+ and(
+ eq(works.resourceType, 'task'),
+ inArray(works.resourceId, taskIds),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { userId: works.userId, workspaceId: works.workspaceId },
+ ),
+ ),
+ );
+
// Demotion-only cascade for the event-shaped child rows (see docstring):
// their visibility mirrors the task, so pulling the task back to private
// must also pull public-era topics/comments out of workspace scope.
@@ -395,6 +420,7 @@ export class TaskModel {
return result.rows.length > 0;
}
+ /** See {@link delete}: bulk task deletion likewise leaves Work artifacts intact. */
async deleteAll(options?: { restrictToCreator?: boolean }): Promise<number> {
// `restrictToCreator` narrows the workspace-wide sweep to rows the caller
// created (non-owner members); owners/personal mode keep the full scope.
diff --git a/packages/database/src/models/work/__tests__/_fixtures.ts b/packages/database/src/models/work/__tests__/_fixtures.ts
new file mode 100644
index 00000000000..0a8accedcb6
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/_fixtures.ts
@@ -0,0 +1,89 @@
+import type {
+ DocumentWorkSummaryItem,
+ ExternalWorkSummaryItem,
+ TaskWorkListItem,
+ TaskWorkSummaryItem,
+ WorkListItem,
+ WorkSummaryItem,
+} from '@lobechat/types';
+import { expect } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agents, threads, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+
+/**
+ * Shared harness for the per-type WorkModel test files (task / document /
+ * linear / github / queries). Each file gets its own isolated PGlite instance
+ * (getTestDB is a per-module singleton), so seeding the same fixed ids across
+ * files never collides.
+ */
+export const serverDB: LobeChatDatabase = await getTestDB();
+
+export const userId = 'work-test-user-id';
+export const userId2 = 'work-test-user-id-2';
+export const topicId = 'work-test-topic-id';
+export const threadId = 'work-test-thread-id';
+export const agentId = 'work-test-agent-id';
+export const agentId2 = 'work-test-agent-id-2';
+
+export const seedWorkTestData = async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);
+ await serverDB.insert(agents).values([
+ { id: agentId, title: 'Work test agent', userId },
+ { id: agentId2, title: 'Work test agent 2', userId: userId2 },
+ ]);
+ await serverDB.insert(topics).values({ id: topicId, userId });
+ await serverDB.insert(threads).values({
+ id: threadId,
+ title: 'Work test thread',
+ topicId,
+ type: 'standalone',
+ userId,
+ });
+};
+
+export const cleanupWorkTestData = async () => {
+ await serverDB.delete(users);
+};
+
+export const expectTaskListItem = (item?: WorkListItem): TaskWorkListItem => {
+ expect(item).toBeDefined();
+
+ if (!item || item.type !== 'task') {
+ throw new Error('Expected task work list item');
+ }
+
+ return item;
+};
+
+export const expectTaskSummaryItem = (item?: WorkSummaryItem): TaskWorkSummaryItem => {
+ expect(item).toBeDefined();
+
+ if (!item || item.type !== 'task') {
+ throw new Error('Expected task work summary');
+ }
+
+ return item;
+};
+
+export const expectDocumentSummaryItem = (item?: WorkSummaryItem): DocumentWorkSummaryItem => {
+ expect(item).toBeDefined();
+
+ if (!item || item.type !== 'document') {
+ throw new Error('Expected document work summary');
+ }
+
+ return item;
+};
+
+export const expectExternalSummaryItem = (item?: WorkSummaryItem): ExternalWorkSummaryItem => {
+ expect(item).toBeDefined();
+
+ if (!item || item.type !== 'external') {
+ throw new Error('Expected external work summary');
+ }
+
+ return item;
+};
diff --git a/packages/database/src/models/work/__tests__/document.test.ts b/packages/database/src/models/work/__tests__/document.test.ts
new file mode 100644
index 00000000000..d6d8771654f
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/document.test.ts
@@ -0,0 +1,379 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { documents, works, workspaces, workVersions } from '../../../schemas';
+import { AgentDocumentModel } from '../../agentDocuments';
+import { DocumentModel } from '../../document';
+import { WorkModel } from '..';
+import {
+ agentId,
+ cleanupWorkTestData,
+ expectDocumentSummaryItem,
+ seedWorkTestData,
+ serverDB,
+ topicId,
+ userId,
+ userId2,
+} from './_fixtures';
+
+beforeEach(seedWorkTestData);
+afterEach(cleanupWorkTestData);
+
+describe('WorkModel · document', () => {
+ it('registers a document work using the backing document id', async () => {
+ const agentDocumentModel = new AgentDocumentModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const doc = await agentDocumentModel.create(agentId, 'research.md', 'Research body', {
+ metadata: { description: 'Research notes' },
+ title: 'Research Notes',
+ });
+
+ const work = await workModel.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ changeType: 'created',
+ rootOperationId: 'op-doc-create',
+ toolName: 'createDocument',
+ toolCallId: 'tool-call-doc-create',
+ toolIdentifier: 'lobe-agent-documents',
+ topicId,
+ });
+
+ expect(work).toBeDefined();
+ // Work keeps stable resource identity plus the current card projection.
+ expect(work).toMatchObject({
+ description: 'Research notes',
+ resourceId: doc.documentId,
+ resourceType: 'document',
+ toolIdentifier: 'lobe-agent-documents',
+ title: 'Research Notes',
+ type: 'document',
+ visibility: 'public',
+ });
+
+ const versions = await workModel.listVersions(work!.id);
+ expect(versions).toHaveLength(1);
+ expect(versions[0]).toMatchObject({
+ content: null,
+ description: 'Research notes',
+ identifier: 'research.md',
+ metadata: { agentDocumentId: doc.id },
+ rootOperationId: 'op-doc-create',
+ toolCallId: 'tool-call-doc-create',
+ title: 'Research Notes',
+ });
+
+ const byOperation = await workModel.listByRootOperation({ rootOperationId: 'op-doc-create' });
+ expect(byOperation[0]).toMatchObject({
+ description: 'Research notes',
+ id: work?.id,
+ identifier: 'research.md',
+ title: 'Research Notes',
+ type: 'document',
+ });
+
+ const summaries = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-doc-create'],
+ });
+ expect(summaries['op-doc-create']?.[0]).toMatchObject({
+ description: 'Research notes',
+ event: expect.objectContaining({
+ metadata: { agentDocumentId: doc.id },
+ }),
+ id: work?.id,
+ identifier: 'research.md',
+ type: 'document',
+ });
+ });
+
+ it('uses the document content prefix when document description is empty', async () => {
+ const agentDocumentModel = new AgentDocumentModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const content = [
+ 'This document explains how Work cards should display a useful document excerpt.',
+ 'It keeps the product panel populated even when document metadata has no description.',
+ 'The extra sentence makes the value long enough to verify truncation.',
+ ].join('\n\n');
+ const normalizedContent = content.replaceAll(/\s+/g, ' ').trim();
+ const expectedDescription = `${normalizedContent.slice(0, 120)}...`;
+ const doc = await agentDocumentModel.create(agentId, 'empty-description.md', content, {
+ title: 'No Description',
+ });
+
+ const work = await workModel.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ changeType: 'created',
+ rootOperationId: 'op-doc-empty-description',
+ toolName: 'createDocument',
+ toolIdentifier: 'lobe-agent-documents',
+ toolCallId: 'tool-call-doc-empty-description',
+ topicId,
+ });
+
+ expect(work?.description).toBe(expectedDescription);
+
+ const byOperation = await workModel.listByRootOperation({
+ rootOperationId: 'op-doc-empty-description',
+ });
+ expect(byOperation[0]).toMatchObject({ description: expectedDescription });
+
+ const summaries = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-doc-empty-description'],
+ });
+ const documentSummary = expectDocumentSummaryItem(summaries['op-doc-empty-description']?.[0]);
+ expect(documentSummary.description).toBe(expectedDescription);
+
+ const byConversation = await workModel.listByConversation({ topicId });
+ expect(byConversation[0]).toMatchObject({ description: expectedDescription });
+ });
+
+ it('truncates an oversized explicit description before writing the works row', async () => {
+ const agentDocumentModel = new AgentDocumentModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ // Simulate a multi-KB description that must never be copied verbatim into the
+ // card-preview `description` column.
+ const longDescription = 'A'.repeat(5000);
+ const expectedDescription = `${'A'.repeat(120)}...`;
+ const doc = await agentDocumentModel.create(agentId, 'long-description.md', 'Body', {
+ metadata: { description: 'Persisted description' },
+ title: 'Long Description',
+ });
+
+ const work = await workModel.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ description: longDescription,
+ documentId: doc.documentId,
+ changeType: 'created',
+ rootOperationId: 'op-doc-long-description',
+ toolName: 'createDocument',
+ toolIdentifier: 'lobe-agent-documents',
+ toolCallId: 'tool-call-doc-long-description',
+ topicId,
+ });
+
+ const versions = await workModel.listVersions(work!.id);
+ expect(versions).toHaveLength(1);
+ expect(work?.description).toBe(expectedDescription);
+ });
+
+ it('keeps one document work row and appends versions for document edits', async () => {
+ const agentDocumentModel = new AgentDocumentModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const doc = await agentDocumentModel.create(agentId, 'draft.md', 'Draft body', {
+ title: 'Draft',
+ });
+
+ const first = await workModel.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ changeType: 'created',
+ rootOperationId: 'op-doc-create',
+ toolName: 'createDocument',
+ toolIdentifier: 'lobe-agent-documents',
+ toolCallId: 'tool-call-doc-create',
+ topicId,
+ });
+
+ await agentDocumentModel.rename(doc.id, 'Renamed Draft');
+
+ const second = await workModel.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ changeType: 'updated',
+ rootOperationId: 'op-doc-rename',
+ toolName: 'renameDocument',
+ toolIdentifier: 'lobe-agent-documents',
+ toolCallId: 'tool-call-doc-rename',
+ topicId,
+ });
+
+ const replay = await workModel.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ changeType: 'updated',
+ rootOperationId: 'op-doc-rename',
+ toolName: 'renameDocument',
+ toolIdentifier: 'lobe-agent-documents',
+ toolCallId: 'tool-call-doc-rename',
+ topicId,
+ });
+
+ expect(second?.id).toBe(first?.id);
+ expect(replay?.id).toBe(first?.id);
+ expect(replay?.updatedAt).toEqual(second?.updatedAt);
+
+ const workRows = await serverDB
+ .select()
+ .from(works)
+ .where(eq(works.resourceId, doc.documentId));
+ expect(workRows).toHaveLength(1);
+
+ const versions = await workModel.listVersions(first!.id);
+ expect(versions.map((item) => item.version)).toEqual([2, 1]);
+ expect(versions[0].title).toBe('Renamed Draft');
+ expect(versions[1].title).toBe('Draft');
+ // The current title cache follows the selected version.
+ expect(second?.title).toBe('Renamed Draft');
+ });
+
+ it('deletes document work and cascades versions when agent document is removed', async () => {
+ const agentDocumentModel = new AgentDocumentModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const doc = await agentDocumentModel.create(agentId, 'delete.md', 'Delete body', {
+ title: 'Delete me',
+ });
+
+ const work = await workModel.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ changeType: 'created',
+ toolName: 'createDocument',
+ toolIdentifier: 'lobe-agent-documents',
+ toolCallId: 'tool-call-doc-delete',
+ });
+
+ await agentDocumentModel.delete(doc.id);
+ await workModel.deleteDocumentWork({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ });
+
+ const workRows = await serverDB.select().from(works).where(eq(works.id, work!.id));
+ const versionRows = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, work!.id));
+
+ expect(workRows).toHaveLength(0);
+ expect(versionRows).toHaveLength(0);
+ });
+
+ it('does not let another user register someone else document work', async () => {
+ const agentDocumentModel = new AgentDocumentModel(serverDB, userId);
+ const otherWorkModel = new WorkModel(serverDB, userId2);
+ const doc = await agentDocumentModel.create(agentId, 'private.md', 'Private body');
+
+ const work = await otherWorkModel.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ changeType: 'created',
+ toolName: 'createDocument',
+ toolIdentifier: 'lobe-agent-documents',
+ toolCallId: 'tool-call-other-doc-user',
+ topicId,
+ });
+
+ expect(work).toBeNull();
+ const workRows = await serverDB.select().from(works);
+ expect(workRows).toHaveLength(0);
+ });
+});
+
+describe('WorkModel · workspace document visibility', () => {
+ const workspaceId = 'work-test-doc-workspace-id';
+
+ const seedWorkspace = async () => {
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Work Test Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ };
+
+ const registerWorkspaceDocument = async (visibility: 'private' | 'public') => {
+ const ownerDocuments = new AgentDocumentModel(serverDB, userId, workspaceId);
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+
+ const doc = await ownerDocuments.create(agentId, 'shared.md', 'Shared body', {
+ metadata: { description: 'Shared description' },
+ title: 'Shared doc',
+ });
+ // `documents.visibility` is NOT NULL default 'public'; flip it directly to
+ // exercise the private branch of the guard.
+ if (visibility === 'private') {
+ await serverDB
+ .update(documents)
+ .set({ visibility: 'private' })
+ .where(eq(documents.id, doc.documentId));
+ }
+
+ const work = await ownerWorks.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ changeType: 'created',
+ rootOperationId: 'op-doc-visibility',
+ toolName: 'createDocument',
+ toolIdentifier: 'lobe-agent-documents',
+ toolCallId: 'tool-call-doc-visibility',
+ topicId,
+ });
+
+ return { doc, work };
+ };
+
+ it('hides another member private-document Work but keeps it for the registrant', async () => {
+ await seedWorkspace();
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+ const memberWorks = new WorkModel(serverDB, userId2, workspaceId);
+
+ const { work } = await registerWorkspaceDocument('private');
+
+ // The registrant keeps full access on every list path.
+ expect(await ownerWorks.listByConversation({ topicId })).toHaveLength(1);
+
+ // Another workspace member cannot see the private document's Work.
+ expect(await memberWorks.listByConversation({ topicId })).toHaveLength(0);
+ expect((await memberWorks.listByWorkspace({})).items).toHaveLength(0);
+ expect(await memberWorks.listVersions(work!.id)).toHaveLength(0);
+ });
+
+ it('keeps a public-document Work visible to other members', async () => {
+ await seedWorkspace();
+ const ownerDocuments = new DocumentModel(serverDB, userId, workspaceId);
+ const memberWorks = new WorkModel(serverDB, userId2, workspaceId);
+
+ const { doc } = await registerWorkspaceDocument('public');
+
+ const memberView = await memberWorks.listByConversation({ topicId });
+ expect(memberView).toHaveLength(1);
+ expect(memberView[0]).toMatchObject({ title: 'Shared doc', type: 'document' });
+
+ await ownerDocuments.setVisibility(doc.documentId, 'private');
+
+ const [mirrored] = await serverDB
+ .select({ visibility: works.visibility })
+ .from(works)
+ .where(eq(works.resourceId, doc.documentId));
+ expect(mirrored.visibility).toBe('private');
+ expect(await memberWorks.listByConversation({ topicId })).toHaveLength(0);
+ });
+
+ it('keeps an orphaned document Work (backing row deleted) visible to the registrant only', async () => {
+ await seedWorkspace();
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+ const memberWorks = new WorkModel(serverDB, userId2, workspaceId);
+
+ const { doc } = await registerWorkspaceDocument('public');
+
+ // Hard-delete the backing document outside the tool path: the Work survives
+ // as an orphan. With no backing row the EXISTS guard fails, so only the
+ // registrant keeps the orphan card.
+ await serverDB.delete(documents).where(eq(documents.id, doc.documentId));
+
+ expect(await ownerWorks.listByConversation({ topicId })).toHaveLength(1);
+ expect(await memberWorks.listByConversation({ topicId })).toHaveLength(0);
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/github.test.ts b/packages/database/src/models/work/__tests__/github.test.ts
new file mode 100644
index 00000000000..83c2cd0fe2b
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/github.test.ts
@@ -0,0 +1,362 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { works } from '../../../schemas';
+import { WorkModel } from '..';
+import {
+ cleanupWorkTestData,
+ expectExternalSummaryItem,
+ seedWorkTestData,
+ serverDB,
+ topicId,
+ userId,
+} from './_fixtures';
+
+beforeEach(seedWorkTestData);
+afterEach(cleanupWorkTestData);
+
+describe('WorkModel · github', () => {
+ it('registers GitHub issue creates and appends versions for edits', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+
+ const first = await workModel.handleSkillToolResult({
+ provider: 'github',
+ args: { owner: 'lobehub', repo: 'lobehub', title: 'GitHub Work issue' },
+ data: {
+ assignees: [{ login: 'arvinxx' }],
+ body: 'Track GitHub issue as Work',
+ html_url: 'https://github.com/lobehub/lobehub/issues/123',
+ id: 3_001,
+ labels: [{ name: 'enhancement' }],
+ node_id: 'I_kwDOJj1234',
+ number: 123,
+ state: 'open',
+ title: 'GitHub Work issue',
+ updated_at: '2026-07-02T08:00:00Z',
+ user: { login: 'yutengjing' },
+ },
+ rootOperationId: 'op-github-issue-create',
+ toolCallId: 'tool-call-github-issue-create',
+ toolName: 'create_issue',
+ topicId,
+ });
+ // Work keeps the current card projection and latest producer identity.
+ expect(first).toMatchObject({
+ description: 'Track GitHub issue as Work',
+ toolIdentifier: 'github',
+ title: 'GitHub Work issue',
+ });
+
+ const second = await workModel.handleSkillToolResult({
+ provider: 'github',
+ args: { issue_number: 123, owner: 'lobehub', repo: 'lobehub', state: 'closed' },
+ data: {
+ html_url: 'https://github.com/lobehub/lobehub/issues/123',
+ node_id: 'I_kwDOJj1234',
+ number: 123,
+ state: 'closed',
+ state_reason: 'completed',
+ updated_at: '2026-07-02T09:30:00Z',
+ },
+ rootOperationId: 'op-github-issue-edit',
+ toolCallId: 'tool-call-github-issue-edit',
+ toolName: 'update_issue',
+ topicId,
+ });
+ const replay = await workModel.handleSkillToolResult({
+ provider: 'github',
+ args: { issue_number: 123, owner: 'lobehub', repo: 'lobehub', state: 'closed' },
+ data: {
+ node_id: 'I_kwDOJj1234',
+ number: 123,
+ state: 'closed',
+ },
+ rootOperationId: 'op-github-issue-edit',
+ toolCallId: 'tool-call-github-issue-edit',
+ toolName: 'update_issue',
+ topicId,
+ });
+
+ expect(second?.id).toBe(first?.id);
+ expect(replay?.id).toBe(first?.id);
+ // `owner/repo#number` is the canonical identity across API and gh surfaces.
+ expect(second).toMatchObject({
+ description: 'Track GitHub issue as Work',
+ resourceId: 'lobehub/lobehub#123',
+ resourceType: 'github_issue',
+ title: 'GitHub Work issue',
+ type: 'external',
+ });
+
+ const versions = await workModel.listVersions(first!.id);
+ expect(versions.map((item) => item.version)).toEqual([2, 1]);
+ expect(versions[0]).toMatchObject({
+ changeType: 'updated',
+ content: 'Track GitHub issue as Work',
+ description: 'Track GitHub issue as Work',
+ identifier: 'lobehub/lobehub#123',
+ status: 'closed',
+ title: 'GitHub Work issue',
+ url: 'https://github.com/lobehub/lobehub/issues/123',
+ });
+ expect(versions[1]).toMatchObject({ status: 'open', title: 'GitHub Work issue' });
+
+ const byOperation = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-github-issue-create', 'op-github-issue-edit'],
+ });
+ expect(byOperation['op-github-issue-create']).toEqual([]);
+ const issueSummary = expectExternalSummaryItem(byOperation['op-github-issue-edit']?.[0]);
+ expect(issueSummary).toMatchObject({
+ identifier: 'lobehub/lobehub#123',
+ status: 'closed',
+ });
+
+ const byConversation = await workModel.listByConversation({ topicId });
+ expect(byConversation).toHaveLength(1);
+ expect(byConversation[0]).toMatchObject({
+ identifier: 'lobehub/lobehub#123',
+ resourceType: 'github_issue',
+ type: 'external',
+ });
+
+ // Read-only queries and failed results never register Works.
+ await workModel.handleSkillToolResult({
+ provider: 'github',
+ data: { node_id: 'I_kwDOJjRead', number: 200, title: 'Read only' },
+ toolCallId: 'tool-call-github-read',
+ toolName: 'get_issue',
+ topicId,
+ });
+ await workModel.handleSkillToolResult({
+ provider: 'github',
+ data: { error: 'Validation failed', isError: true },
+ toolCallId: 'tool-call-github-error',
+ toolName: 'create_issue',
+ topicId,
+ });
+
+ const workRows = await serverDB
+ .select()
+ .from(works)
+ .where(eq(works.resourceType, 'github_issue'));
+ expect(workRows).toHaveLength(1);
+ });
+
+ it('registers GitHub pull requests and dedupes updates by owner/repo#number', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+
+ const pullRequest = await workModel.handleSkillToolResult({
+ provider: 'github',
+ args: { base: 'canary', head: 'feat/work-registry', owner: 'lobehub', repo: 'lobehub' },
+ data: JSON.stringify({
+ base: { ref: 'canary', repo: { full_name: 'lobehub/lobehub' } },
+ body: 'Adds the Work registry',
+ draft: false,
+ head: { ref: 'feat/work-registry' },
+ html_url: 'https://github.com/lobehub/lobehub/pull/456',
+ id: 9_001,
+ merged: false,
+ node_id: 'PR_kwDOJj5678',
+ number: 456,
+ state: 'open',
+ title: 'feat: add work registry',
+ user: { login: 'yutengjing' },
+ }),
+ rootOperationId: 'op-github-pr-create',
+ toolCallId: 'tool-call-github-pr-create',
+ toolName: 'create_pull_request',
+ topicId,
+ });
+
+ expect(pullRequest).toMatchObject({
+ resourceId: 'lobehub/lobehub#456',
+ resourceType: 'github_pull_request',
+ type: 'external',
+ });
+
+ // Merge-style responses carry no node_id; the target still resolves to
+ // the same `owner/repo#number` identity and lands on the existing Work.
+ const merged = await workModel.handleSkillToolResult({
+ provider: 'github',
+ args: { owner: 'lobehub', pull_number: 456, repo: 'lobehub' },
+ data: {
+ merged: true,
+ message: 'Pull Request successfully merged',
+ sha: 'abc123def456',
+ },
+ rootOperationId: 'op-github-pr-merge',
+ toolCallId: 'tool-call-github-pr-merge',
+ toolName: 'update_pull_request',
+ topicId,
+ });
+
+ expect(merged?.id).toBe(pullRequest?.id);
+
+ const versions = await workModel.listVersions(pullRequest!.id);
+ expect(versions.map((item) => item.version)).toEqual([2, 1]);
+ // The status-only merge response inherits the complete create snapshot.
+ expect(versions[0]).toMatchObject({
+ content: 'Adds the Work registry',
+ description: 'Adds the Work registry',
+ identifier: 'lobehub/lobehub#456',
+ status: 'merged',
+ title: 'feat: add work registry',
+ url: 'https://github.com/lobehub/lobehub/pull/456',
+ });
+
+ // An update addressing an entity not registered before still creates its
+ // own Work row keyed by identity (consistent with the Linear adaptation).
+ const unknownTarget = await workModel.handleSkillToolResult({
+ provider: 'github',
+ args: { owner: 'lobehub', pull_number: 999, repo: 'lobehub' },
+ data: { merged: true, sha: 'fff000' },
+ toolCallId: 'tool-call-github-pr-unknown',
+ toolName: 'update_pull_request',
+ topicId,
+ });
+ expect(unknownTarget?.resourceId).toBe('lobehub/lobehub#999');
+ expect(unknownTarget?.id).not.toBe(pullRequest?.id);
+
+ // A result with no resolvable `owner/repo#number` identity is skipped.
+ const unresolvable = await workModel.handleSkillToolResult({
+ provider: 'github',
+ args: {},
+ data: { merged: true },
+ toolCallId: 'tool-call-github-pr-unresolvable',
+ toolName: 'update_pull_request',
+ topicId,
+ });
+ expect(unresolvable).toBeNull();
+
+ const workRows = await serverDB
+ .select()
+ .from(works)
+ .where(eq(works.resourceType, 'github_pull_request'));
+ expect(workRows).toHaveLength(2);
+ });
+
+ it('registers GitHub works from sandbox gh CLI runCommand results', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+
+ // The dominant github skill surface: `gh` executed in the cloud sandbox,
+ // where the result is only {command, exitCode, output}.
+ const created = await workModel.handleSkillToolResult({
+ provider: 'github',
+ args: {
+ command:
+ 'issue create -R lobehub-biz/lobehub-cloud --title "CLI Issue" --body "created from sandbox"',
+ description: 'Create a test issue',
+ },
+ data: {
+ command:
+ 'gh issue create -R lobehub-biz/lobehub-cloud --title "CLI Issue" --body "created from sandbox"',
+ exitCode: 0,
+ output: 'https://github.com/lobehub-biz/lobehub-cloud/issues/952\n',
+ },
+ rootOperationId: 'op-github-cli-create',
+ toolCallId: 'tool-call-github-cli-create',
+ toolName: 'runCommand',
+ topicId,
+ });
+
+ expect(created).toMatchObject({
+ description: 'created from sandbox',
+ resourceId: 'lobehub-biz/lobehub-cloud#952',
+ resourceType: 'github_issue',
+ title: 'CLI Issue',
+ type: 'external',
+ });
+
+ // Chained commands: the trailing stdout URL identifies the edited entity.
+ const edited = await workModel.handleSkillToolResult({
+ provider: 'github',
+ data: {
+ command:
+ 'git status && gh issue edit 952 -R lobehub-biz/lobehub-cloud --body "updated body"',
+ exitCode: 0,
+ output: 'On branch main\nhttps://github.com/lobehub-biz/lobehub-cloud/issues/952\n',
+ },
+ rootOperationId: 'op-github-cli-edit',
+ toolCallId: 'tool-call-github-cli-edit',
+ toolName: 'runCommand',
+ topicId,
+ });
+ expect(edited?.id).toBe(created?.id);
+
+ const versions = await workModel.listVersions(created!.id);
+ expect(versions.map((item) => item.version)).toEqual([2, 1]);
+ // Patch merge keeps the create-time title/status while applying the new body.
+ expect(versions[0]).toMatchObject({
+ changeType: 'updated',
+ content: 'updated body',
+ description: 'updated body',
+ identifier: 'lobehub-biz/lobehub-cloud#952',
+ status: 'open',
+ title: 'CLI Issue',
+ url: 'https://github.com/lobehub-biz/lobehub-cloud/issues/952',
+ });
+
+ const pullRequest = await workModel.handleSkillToolResult({
+ provider: 'github',
+ data: {
+ command:
+ 'gh pr create -R lobehub-biz/lobehub-cloud --title "CLI PR" --body "pr body" --base main --head feat/cli --draft',
+ exitCode: 0,
+ output: 'https://github.com/lobehub-biz/lobehub-cloud/pull/953\n',
+ },
+ toolCallId: 'tool-call-github-cli-pr',
+ toolName: 'runCommand',
+ topicId,
+ });
+ expect(pullRequest).toMatchObject({
+ description: 'pr body',
+ resourceId: 'lobehub-biz/lobehub-cloud#953',
+ resourceType: 'github_pull_request',
+ title: 'CLI PR',
+ });
+ const [pullRequestVersion] = await workModel.listVersions(pullRequest!.id);
+ expect(pullRequestVersion).toMatchObject({
+ content: 'pr body',
+ status: 'draft',
+ title: 'CLI PR',
+ });
+
+ // Failed commands, read-only subcommands, and non-gh commands are skipped.
+ const failed = await workModel.handleSkillToolResult({
+ provider: 'github',
+ data: {
+ command: 'gh issue create -R lobehub-biz/lobehub-cloud --title X',
+ exitCode: 1,
+ output: 'GraphQL: Resource not accessible',
+ },
+ toolCallId: 'tool-call-github-cli-failed',
+ toolName: 'runCommand',
+ topicId,
+ });
+ const readOnly = await workModel.handleSkillToolResult({
+ provider: 'github',
+ data: {
+ command: 'gh issue view 952 -R lobehub-biz/lobehub-cloud',
+ exitCode: 0,
+ output: 'CLI Issue #952\nhttps://github.com/lobehub-biz/lobehub-cloud/issues/952',
+ },
+ toolCallId: 'tool-call-github-cli-view',
+ toolName: 'runCommand',
+ topicId,
+ });
+ const nonGh = await workModel.handleSkillToolResult({
+ provider: 'github',
+ data: { command: 'git push origin main', exitCode: 0, output: 'Everything up-to-date' },
+ toolCallId: 'tool-call-github-cli-git',
+ toolName: 'runCommand',
+ topicId,
+ });
+ expect(failed).toBeNull();
+ expect(readOnly).toBeNull();
+ expect(nonGh).toBeNull();
+
+ const workRows = await serverDB.select().from(works).where(eq(works.type, 'external'));
+ expect(workRows).toHaveLength(2);
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/githubToolResult.test.ts b/packages/database/src/models/work/__tests__/githubToolResult.test.ts
new file mode 100644
index 00000000000..b1b74347607
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/githubToolResult.test.ts
@@ -0,0 +1,180 @@
+import { describe, expect, it } from 'vitest';
+
+import { normalizeGithubToolResult } from '../githubToolResult';
+
+/**
+ * Pins the quoting edge cases of the hand-rolled shell tokenizer behind the
+ * `runCommand` normalization path (see the tokenizer comment in
+ * githubToolResult.ts for why it is hand-rolled).
+ */
+const runCommand = (command: string, output = '') =>
+ normalizeGithubToolResult({
+ data: { command, exitCode: 0, output },
+ toolName: 'runCommand',
+ });
+
+describe('normalizeGithubToolResult (gh runCommand parsing)', () => {
+ it('keeps spaces and double quotes inside single-quoted values', () => {
+ const operation = runCommand(
+ `gh issue create --repo lobehub/lobehub --title 'Fix: "quoted" bug report'`,
+ 'https://github.com/lobehub/lobehub/issues/123',
+ );
+
+ expect(operation?.params).toMatchObject({
+ identifier: 'lobehub/lobehub#123',
+ resourceId: 'lobehub/lobehub#123',
+ changeType: 'created',
+ title: 'Fix: "quoted" bug report',
+ url: 'https://github.com/lobehub/lobehub/issues/123',
+ });
+ });
+
+ it('unescapes \\" inside double quotes and keeps $ literal', () => {
+ const operation = runCommand(
+ `gh issue create --repo lobehub/lobehub --title "hello" --body "He said \\"hi\\" for $5"`,
+ 'https://github.com/lobehub/lobehub/issues/7',
+ );
+
+ expect(operation?.params.description).toBe('He said "hi" for $5');
+ // The full `--body` value is also emitted as `content`, and both fields are
+ // named in `patchFields`.
+ expect(operation?.params.content).toBe('He said "hi" for $5');
+ expect(operation?.params.patchFields).toEqual(
+ expect.arrayContaining(['content', 'description']),
+ );
+ });
+
+ it('emits the full --body as content while capping the description preview', () => {
+ const body = 'C'.repeat(300);
+ const operation = runCommand(
+ `gh issue create --repo lobehub/lobehub --title 'Long body' --body '${body}'`,
+ 'https://github.com/lobehub/lobehub/issues/8',
+ );
+
+ // `content` keeps the full untruncated body; `description` is the ≤120 preview.
+ expect(operation?.params.content).toBe(body);
+ expect(operation?.params.description).toBe(`${'C'.repeat(120)}...`);
+ expect(operation?.params.patchFields).toContain('content');
+ });
+
+ it('honors backslash escapes outside quotes', () => {
+ const operation = runCommand(`gh issue edit 42 --repo lobehub/lobehub --title Fix\\ the\\ bug`);
+
+ expect(operation?.params).toMatchObject({
+ identifier: 'lobehub/lobehub#42',
+ changeType: 'updated',
+ title: 'Fix the bug',
+ });
+ });
+
+ it('treats backslash-newline as a line continuation', () => {
+ const operation = runCommand(
+ `gh issue create \\\n --repo lobehub/lobehub \\\n --title 'Multiline invocation'`,
+ 'https://github.com/lobehub/lobehub/issues/9',
+ );
+
+ expect(operation?.params.title).toBe('Multiline invocation');
+ });
+
+ it('supports --flag=value with quoted values', () => {
+ const operation = runCommand(
+ `gh issue edit 15 --repo lobehub/lobehub --title='Inline equals title'`,
+ );
+
+ expect(operation?.params.title).toBe('Inline equals title');
+ });
+
+ it('does not misread a value-flag argument as the edit target', () => {
+ const operation = runCommand(
+ `gh issue edit 952 --repo lobehub/lobehub --milestone 'v2 launch'`,
+ );
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#952');
+ // Milestone is consumed as the flag value, not snapshotted as a title.
+ expect(operation?.params.title).toBeUndefined();
+ });
+
+ it('skips registration on an unterminated single quote', () => {
+ expect(runCommand(`gh issue create --repo lobehub/lobehub --title 'broken`)).toBeNull();
+ });
+
+ it('skips registration on an unterminated double quote', () => {
+ expect(runCommand(`gh issue create --repo lobehub/lobehub --title "broken`)).toBeNull();
+ });
+
+ it('uses the last gh create/edit segment of a chained command', () => {
+ const operation = runCommand(
+ `git push origin HEAD && gh pr create --base main --title 'New PR'`,
+ 'https://github.com/lobehub/lobehub/pull/88',
+ );
+
+ expect(operation?.params).toMatchObject({
+ identifier: 'lobehub/lobehub#88',
+ resourceType: 'github_pull_request',
+ changeType: 'created',
+ title: 'New PR',
+ });
+ });
+
+ it('splits segments on semicolons and parses the last gh segment', () => {
+ const operation = runCommand(
+ `gh issue edit 1 --add-label bug; gh pr edit 7 --repo lobehub/lobehub --title 'Second'`,
+ );
+
+ expect(operation?.params).toMatchObject({
+ identifier: 'lobehub/lobehub#7',
+ changeType: 'updated',
+ title: 'Second',
+ });
+ });
+});
+
+/**
+ * The persisted url reaches shell.openExternal on desktop, and gh stdout is
+ * member-controlled free text, so only http(s) URLs may be stored.
+ */
+describe('normalizeGithubToolResult (url scheme allowlist)', () => {
+ const editWithStdoutUrl = (url: string) =>
+ // `gh issue edit 5` supplies repo+number identity; the stdout URL is the
+ // attacker-controlled value under test.
+ runCommand(`gh issue edit 5 --repo lobehub/lobehub`, url);
+
+ it.each([
+ ['javascript:alert(1)', 'javascript'],
+ ['data:text/html,x', 'data'],
+ ['file:///etc/passwd', 'file'],
+ ])('drops the persisted url for a %s scheme', (url) => {
+ // A non-github scheme never matches the entity-URL regex, so the ref falls
+ // back to the command's edit target (number 5) and carries no url.
+ const operation = editWithStdoutUrl(url);
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#5');
+ expect(operation?.params.url).toBeUndefined();
+ });
+
+ it('keeps a plain https github url', () => {
+ const operation = runCommand(
+ `gh issue create --repo lobehub/lobehub --title 'ok'`,
+ 'https://github.com/lobehub/lobehub/issues/321',
+ );
+
+ expect(operation?.params.url).toBe('https://github.com/lobehub/lobehub/issues/321');
+ });
+
+ it('keeps a structured-result html_url only when it is http(s)', () => {
+ const good = normalizeGithubToolResult({
+ data: { html_url: 'https://github.com/lobehub/lobehub/issues/9', number: 9 },
+ args: { owner: 'lobehub', repo: 'lobehub' },
+ toolName: 'create_issue',
+ });
+ expect(good?.params.url).toBe('https://github.com/lobehub/lobehub/issues/9');
+
+ const bad = normalizeGithubToolResult({
+ data: { html_url: 'javascript:alert(1)', number: 9 },
+ args: { owner: 'lobehub', repo: 'lobehub' },
+ toolName: 'create_issue',
+ });
+ expect(bad?.params.identifier).toBe('lobehub/lobehub#9');
+ expect(bad?.params.url).toBeUndefined();
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/linear.test.ts b/packages/database/src/models/work/__tests__/linear.test.ts
new file mode 100644
index 00000000000..760aa14f17b
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/linear.test.ts
@@ -0,0 +1,418 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { topics, works, workVersions } from '../../../schemas';
+import { WorkModel } from '..';
+import { normalizeLinearToolResult } from '../linearToolResult';
+import {
+ cleanupWorkTestData,
+ expectExternalSummaryItem,
+ seedWorkTestData,
+ serverDB,
+ topicId,
+ userId,
+ userId2,
+} from './_fixtures';
+
+beforeEach(seedWorkTestData);
+afterEach(cleanupWorkTestData);
+
+/** Re-query the immutable snapshot selected by works.currentVersionId. */
+const currentVersionRow = async (workId: string) => {
+ const [row] = await serverDB
+ .select({ version: workVersions })
+ .from(works)
+ .innerJoin(workVersions, eq(works.currentVersionId, workVersions.id))
+ .where(eq(works.id, workId));
+ return row.version;
+};
+
+describe('WorkModel · linear', () => {
+ it('keeps merged display columns when a version-create retry follows a concurrent write', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+ const baseParams = {
+ resourceId: 'issue-race',
+ resourceType: 'linear_issue' as const,
+ toolIdentifier: 'linear',
+ toolName: 'save_issue',
+ topicId,
+ };
+
+ const first = await workModel.registerExternal({
+ ...baseParams,
+ description: 'Original description',
+ patchFields: ['title', 'status', 'description'],
+ changeType: 'created',
+ rootOperationId: 'op-race-create',
+ toolCallId: 'tool-call-race-create',
+ status: 'Backlog',
+ title: 'Original title',
+ });
+ expect(first).toBeDefined();
+
+ // Simulate losing the version-number race: the first insert attempt fails
+ // with a unique violation while a concurrent registration commits a
+ // version that renames the issue.
+ const originalTransaction = serverDB.transaction.bind(serverDB);
+ let raced = false;
+ // Drizzle's transaction signature gained an optional config param upstream;
+ // the spy only exercises the callback path, so widen via cast.
+ const transactionSpy = vi.spyOn(serverDB, 'transaction').mockImplementation((async (
+ callback: never,
+ ) => {
+ if (raced) return originalTransaction(callback);
+ raced = true;
+
+ await workModel.registerExternal({
+ ...baseParams,
+ patchFields: ['title'],
+ changeType: 'updated',
+ rootOperationId: 'op-race-winner',
+ toolCallId: 'tool-call-race-winner',
+ title: 'Winner title',
+ });
+
+ throw new Error(
+ 'duplicate key value violates unique constraint "work_versions_work_id_version_unique"',
+ );
+ }) as never);
+
+ try {
+ await workModel.registerExternal({
+ ...baseParams,
+ patchFields: ['status'],
+ changeType: 'updated',
+ rootOperationId: 'op-race-loser',
+ toolCallId: 'tool-call-race-loser',
+ status: 'In Progress',
+ });
+ } finally {
+ transactionSpy.mockRestore();
+ }
+
+ const versions = await workModel.listVersions(first!.id);
+ expect(versions.map((item) => item.version)).toEqual([3, 2, 1]);
+
+ // Without re-reading inside the retry, the status-only patch would copy a
+ // stale snapshot and revert the winner's title. The latest immutable version
+ // must combine both concurrent changes with the original description.
+ const current = await currentVersionRow(first!.id);
+ expect(current).toMatchObject({
+ description: 'Original description',
+ status: 'In Progress',
+ title: 'Winner title',
+ });
+ });
+
+ it('registers Linear issue creates and appends versions for edits', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+
+ const first = await workModel.handleSkillToolResult({
+ provider: 'linear',
+ args: { team: 'Engineering', title: 'Linear Work issue' },
+ data: {
+ description: 'Track Linear issue as Work',
+ id: 'issue-uuid-10966',
+ identifier: 'LOBE-10966',
+ labels: ['claude code'],
+ priority: { name: 'High', value: 2 },
+ state: { name: 'Backlog' },
+ statusType: 'backlog',
+ team: 'Engineering',
+ teamId: 'team-1',
+ title: 'Linear Work issue',
+ url: 'https://linear.app/lobehub/issue/LOBE-10966/linear-work-issue',
+ },
+ rootOperationId: 'op-linear-issue-create',
+ toolCallId: 'tool-call-linear-issue-create',
+ toolName: 'save_issue',
+ topicId,
+ });
+
+ const second = await workModel.handleSkillToolResult({
+ provider: 'linear',
+ args: { id: 'issue-uuid-10966', state: 'In Progress' },
+ data: {
+ id: 'issue-uuid-10966',
+ state: 'In Progress',
+ statusType: 'started',
+ updatedAt: '2026-07-01T13:23:10.614Z',
+ },
+ rootOperationId: 'op-linear-issue-edit',
+ toolCallId: 'tool-call-linear-issue-edit',
+ toolName: 'save_issue',
+ topicId,
+ });
+ const replay = await workModel.handleSkillToolResult({
+ provider: 'linear',
+ args: { id: 'issue-uuid-10966', state: 'In Progress' },
+ data: {
+ id: 'issue-uuid-10966',
+ state: 'In Progress',
+ },
+ rootOperationId: 'op-linear-issue-edit',
+ toolCallId: 'tool-call-linear-issue-edit',
+ toolName: 'save_issue',
+ topicId,
+ });
+
+ expect(second?.id).toBe(first?.id);
+ expect(replay?.id).toBe(first?.id);
+ // The Work row keeps stable resource identity plus the current card projection.
+ expect(second).toMatchObject({
+ description: 'Track Linear issue as Work',
+ resourceId: 'issue-uuid-10966',
+ resourceType: 'linear_issue',
+ toolIdentifier: 'linear',
+ title: 'Linear Work issue',
+ type: 'external',
+ });
+
+ const versions = await workModel.listVersions(first!.id);
+ expect(versions.map((item) => item.version)).toEqual([2, 1]);
+ expect(versions[0]).toMatchObject({
+ changeType: 'updated',
+ content: 'Track Linear issue as Work',
+ description: 'Track Linear issue as Work',
+ identifier: 'LOBE-10966',
+ status: 'In Progress',
+ title: 'Linear Work issue',
+ url: 'https://linear.app/lobehub/issue/LOBE-10966/linear-work-issue',
+ });
+ expect(versions[1]).toMatchObject({
+ status: 'Backlog',
+ title: 'Linear Work issue',
+ });
+
+ const byOperation = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-linear-issue-create', 'op-linear-issue-edit'],
+ });
+ expect(byOperation['op-linear-issue-create']).toEqual([]);
+ const issueSummary = expectExternalSummaryItem(byOperation['op-linear-issue-edit']?.[0]);
+ expect(issueSummary).toMatchObject({
+ identifier: 'LOBE-10966',
+ status: 'In Progress',
+ title: 'Linear Work issue',
+ });
+
+ const byConversation = await workModel.listByConversation({ topicId });
+ expect(byConversation).toHaveLength(1);
+ expect(byConversation[0]).toMatchObject({
+ identifier: 'LOBE-10966',
+ resourceType: 'linear_issue',
+ type: 'external',
+ });
+
+ await workModel.handleSkillToolResult({
+ provider: 'linear',
+ data: { id: 'issue-uuid-read', title: 'Read only' },
+ toolCallId: 'tool-call-linear-read',
+ toolName: 'get_issue',
+ topicId,
+ });
+ await workModel.handleSkillToolResult({
+ provider: 'linear',
+ data: { error: 'Invalid issue', isError: true },
+ toolCallId: 'tool-call-linear-error',
+ toolName: 'save_issue',
+ topicId,
+ });
+
+ const workRows = await serverDB
+ .select()
+ .from(works)
+ .where(eq(works.resourceType, 'linear_issue'));
+ expect(workRows).toHaveLength(1);
+ });
+
+ it('registers Linear documents and keeps merged display columns across partial updates', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+
+ const document = await workModel.handleSkillToolResult({
+ provider: 'linear',
+ args: { title: 'Linear document', team: 'Engineering' },
+ data: JSON.stringify({
+ document: {
+ content: 'Document body',
+ id: 'doc-1',
+ slug: 'linear-document',
+ title: 'Linear document',
+ url: 'https://linear.app/lobehub/document/linear-document',
+ },
+ }),
+ rootOperationId: 'op-linear-document-create',
+ toolCallId: 'tool-call-linear-document-create',
+ toolName: 'create_document',
+ topicId,
+ });
+ const editedDocument = await workModel.handleSkillToolResult({
+ provider: 'linear',
+ args: { content: 'Updated body', id: 'doc-1' },
+ data: {
+ content: 'Updated body',
+ id: 'doc-1',
+ slugId: '8298fa69b2e3',
+ title: 'Linear document updated',
+ url: 'https://linear.app/lobehub/document/linear-document-8298fa69b2e3',
+ },
+ rootOperationId: 'op-linear-document-edit',
+ toolCallId: 'tool-call-linear-document-edit',
+ toolName: 'save_document',
+ topicId,
+ });
+ const partialDocumentUpdate = await workModel.handleSkillToolResult({
+ provider: 'linear',
+ args: { content: 'Partial body', id: 'doc-1' },
+ data: {
+ content: 'Partial body',
+ id: 'doc-1',
+ },
+ rootOperationId: 'op-linear-document-partial-edit',
+ toolCallId: 'tool-call-linear-document-partial-edit',
+ toolName: 'save_document',
+ topicId,
+ });
+
+ // Comments are intentionally NOT adapted as Work entities — a comment
+ // mutation must neither create its own work nor touch the parent issue.
+ const comment = await workModel.handleSkillToolResult({
+ provider: 'linear',
+ args: { body: 'Looks good', issueId: 'LOBE-10966' },
+ data: {
+ body: 'Looks good',
+ id: 'comment-1',
+ url: 'https://linear.app/lobehub/issue/LOBE-10966#comment-1',
+ },
+ rootOperationId: 'op-linear-comment-create',
+ toolCallId: 'tool-call-linear-comment-create',
+ toolName: 'save_comment',
+ topicId,
+ });
+ expect(comment).toBeNull();
+
+ expect(document).toMatchObject({
+ resourceId: 'doc-1',
+ resourceType: 'linear_document',
+ type: 'external',
+ });
+ expect(editedDocument?.id).toBe(document!.id);
+ expect(partialDocumentUpdate?.id).toBe(document!.id);
+
+ const documentVersions = await workModel.listVersions(document!.id);
+ expect(documentVersions.map((item) => item.version)).toEqual([3, 2, 1]);
+ // The content-only update inherits every field it did not carry from v2.
+ expect(documentVersions[0]).toMatchObject({
+ content: 'Partial body',
+ description: 'Partial body',
+ identifier: 'linear-document-8298fa69b2e3',
+ title: 'Linear document updated',
+ url: 'https://linear.app/lobehub/document/linear-document-8298fa69b2e3',
+ });
+
+ await workModel.handleSkillToolResult({
+ provider: 'linear',
+ args: { id: 'comment-1' },
+ data: { id: 'comment-1' },
+ toolCallId: 'tool-call-linear-comment-delete',
+ toolName: 'delete_comment',
+ topicId,
+ });
+
+ const commentWork = await serverDB
+ .select()
+ .from(works)
+ .where(eq(works.resourceId, 'comment-1'));
+ const documentWork = await serverDB.select().from(works).where(eq(works.resourceId, 'doc-1'));
+ expect(commentWork).toHaveLength(0);
+ expect(documentWork).toHaveLength(1);
+ });
+
+ it('keeps Linear works isolated by user for the same external resource', async () => {
+ const otherTopicId = 'work-test-other-linear-topic-id';
+ await serverDB.insert(topics).values({ id: otherTopicId, userId: userId2 });
+
+ const workModel = new WorkModel(serverDB, userId);
+ const otherWorkModel = new WorkModel(serverDB, userId2);
+
+ const ownerWork = await workModel.handleSkillToolResult({
+ provider: 'linear',
+ args: { team: 'Engineering', title: 'Owner issue title' },
+ data: {
+ id: 'shared-issue-uuid',
+ identifier: 'LOBE-10966',
+ title: 'Owner issue title',
+ url: 'https://linear.app/lobehub/issue/LOBE-10966/shared-issue',
+ },
+ toolCallId: 'tool-call-linear-owner-issue',
+ toolName: 'save_issue',
+ topicId,
+ });
+ const otherWork = await otherWorkModel.handleSkillToolResult({
+ provider: 'linear',
+ args: { id: 'shared-issue-uuid', title: 'Other user issue title' },
+ data: {
+ id: 'shared-issue-uuid',
+ identifier: 'LOBE-10966',
+ title: 'Other user issue title',
+ url: 'https://linear.app/lobehub/issue/LOBE-10966/shared-issue',
+ },
+ toolCallId: 'tool-call-linear-other-issue',
+ toolName: 'save_issue',
+ topicId: otherTopicId,
+ });
+
+ expect(ownerWork?.id).not.toBe(otherWork?.id);
+
+ const ownerItems = await workModel.listByConversation({ topicId });
+ const otherItems = await otherWorkModel.listByConversation({ topicId: otherTopicId });
+ expect(ownerItems).toHaveLength(1);
+ expect(ownerItems[0]).toMatchObject({
+ id: ownerWork!.id,
+ resourceId: 'shared-issue-uuid',
+ title: 'Owner issue title',
+ type: 'external',
+ });
+ expect(otherItems).toHaveLength(1);
+ expect(otherItems[0]).toMatchObject({
+ id: otherWork!.id,
+ title: 'Other user issue title',
+ type: 'external',
+ });
+ });
+});
+
+/**
+ * The persisted url reaches shell.openExternal on desktop, and Linear tool
+ * payloads are member-controlled, so only http(s) URLs may be stored.
+ */
+describe('normalizeLinearToolResult (url scheme allowlist)', () => {
+ const registerIssueWithUrl = (url: string) =>
+ normalizeLinearToolResult({
+ data: { id: 'issue-uuid', identifier: 'LOBE-1', title: 'T', url },
+ toolName: 'save_issue',
+ });
+
+ it.each([['javascript:alert(1)'], ['data:text/html,x'], ['file:///etc/passwd']])(
+ 'drops the persisted url for %s',
+ (url) => {
+ const operation = registerIssueWithUrl(url);
+
+ // Identity is still resolved from the payload; only the unsafe url is dropped.
+ expect(operation?.params.identifier).toBe('LOBE-1');
+ expect(operation?.params.url).toBeUndefined();
+ },
+ );
+
+ it('keeps a whitespace-padded https url after trimming', () => {
+ const operation = registerIssueWithUrl(' https://linear.app/lobehub/issue/LOBE-1 ');
+
+ expect(operation?.params.url).toBe('https://linear.app/lobehub/issue/LOBE-1');
+ });
+
+ it('keeps a plain https url', () => {
+ const operation = registerIssueWithUrl('https://linear.app/lobehub/issue/LOBE-1');
+
+ expect(operation?.params.url).toBe('https://linear.app/lobehub/issue/LOBE-1');
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/messageAttachment.test.ts b/packages/database/src/models/work/__tests__/messageAttachment.test.ts
new file mode 100644
index 00000000000..520cd0f6760
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/messageAttachment.test.ts
@@ -0,0 +1,81 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { messages } from '../../../schemas';
+import { MessageModel } from '../../message';
+import { TaskModel } from '../../task';
+import { WorkModel } from '..';
+import { cleanupWorkTestData, seedWorkTestData, serverDB, topicId, userId } from './_fixtures';
+
+beforeEach(seedWorkTestData);
+afterEach(cleanupWorkTestData);
+
+/**
+ * Works ride the message-list payload: `MessageModel.query` resolves each
+ * round's Work summaries and attaches them to the round's anchor message (keyed
+ * by `metadata.work.rootOperationId`), so the in-message chips and the sidebar
+ * summary read from one source instead of a dedicated work-summary fetch.
+ */
+describe('MessageModel · work summary attachment', () => {
+ it("attaches a round's Work summaries to its anchor message", async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const messageModel = new MessageModel(serverDB, userId);
+
+ const task = await taskModel.create({ instruction: 'Plan', name: 'Plan task' });
+
+ await serverDB.insert(messages).values([
+ {
+ content: '',
+ id: 'msg-assistant',
+ // The anchor stamp the server keys the attachment by.
+ metadata: { work: { rootOperationId: 'op-root' } },
+ role: 'assistant',
+ topicId,
+ userId,
+ },
+ {
+ content: '',
+ id: 'msg-tool',
+ parentId: 'msg-assistant',
+ role: 'tool',
+ topicId,
+ userId,
+ },
+ ]);
+
+ const work = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-root',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ messageId: 'msg-tool',
+ toolCallId: 'tool-call-create',
+ taskId: task.id,
+ topicId,
+ });
+
+ const result = await messageModel.query({ topicId });
+
+ const anchor = result.find((m) => m.id === 'msg-assistant');
+ expect(anchor?.works).toHaveLength(1);
+ expect(anchor?.works?.[0].id).toBe(work!.id);
+ // Only the anchor carries the works — the tool row that shares the round does not.
+ expect(result.find((m) => m.id === 'msg-tool')?.works).toBeUndefined();
+ });
+
+ it('omits works for messages that carry no work rootOperationId', async () => {
+ const messageModel = new MessageModel(serverDB, userId);
+
+ await serverDB.insert(messages).values({
+ content: 'hi',
+ id: 'msg-plain',
+ role: 'user',
+ topicId,
+ userId,
+ });
+
+ const result = await messageModel.query({ topicId });
+ expect(result.find((m) => m.id === 'msg-plain')?.works).toBeUndefined();
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/queries.test.ts b/packages/database/src/models/work/__tests__/queries.test.ts
new file mode 100644
index 00000000000..f003252b842
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/queries.test.ts
@@ -0,0 +1,373 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { topics, works } from '../../../schemas';
+import { AgentDocumentModel } from '../../agentDocuments';
+import { TaskModel } from '../../task';
+import { WorkModel } from '..';
+import {
+ agentId,
+ cleanupWorkTestData,
+ seedWorkTestData,
+ serverDB,
+ topicId,
+ userId,
+} from './_fixtures';
+
+beforeEach(seedWorkTestData);
+afterEach(cleanupWorkTestData);
+
+describe('WorkModel · queries', () => {
+ it('groups version events by root operation', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const firstTask = await taskModel.create({
+ instruction: 'First tool work',
+ name: 'First work',
+ });
+ const secondTask = await taskModel.create({
+ instruction: 'Second tool work',
+ name: 'Second work',
+ });
+
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-first',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-1',
+ taskId: firstTask.id,
+ topicId,
+ });
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-second',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-2',
+ taskId: secondTask.id,
+ topicId,
+ });
+
+ const byOperations = await workModel.listByRootOperations({
+ rootOperationIds: ['op-missing', 'op-second', 'op-first', 'op-first'],
+ });
+
+ expect(byOperations['op-first']?.map((item) => item.resourceId)).toEqual([firstTask.id]);
+ expect(byOperations['op-second']?.map((item) => item.resourceId)).toEqual([secondTask.id]);
+ expect(byOperations['op-missing']).toEqual([]);
+ });
+
+ it('batches listByRootOperations into one query per work type', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const firstTask = await taskModel.create({ instruction: 'Batch 1', name: 'Batch one' });
+ const secondTask = await taskModel.create({ instruction: 'Batch 2', name: 'Batch two' });
+
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-batch-1',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-batch-1',
+ taskId: firstTask.id,
+ topicId,
+ });
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-batch-2',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-batch-2',
+ taskId: secondTask.id,
+ topicId,
+ });
+
+ const selectSpy = vi.spyOn(serverDB, 'select');
+ try {
+ const byOperations = await workModel.listByRootOperations({
+ rootOperationIds: ['op-batch-1', 'op-batch-2', 'op-batch-missing'],
+ });
+
+ // One query per work type across all ids, not per (id x type). Three
+ // registered types now: document / external / task.
+ expect(selectSpy).toHaveBeenCalledTimes(3);
+ expect(byOperations['op-batch-1']?.map((item) => item.resourceId)).toEqual([firstTask.id]);
+ expect(byOperations['op-batch-2']?.map((item) => item.resourceId)).toEqual([secondTask.id]);
+ expect(byOperations['op-batch-missing']).toEqual([]);
+ } finally {
+ selectSpy.mockRestore();
+ }
+ });
+
+ it('surfaces a shared work only on the latest operation touching it', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Shared work', name: 'Shared work' });
+
+ // Turn A creates the task, turn B updates the same task: only the last
+ // touching round's anchor card surfaces the Work — earlier rounds drop the
+ // chip instead of repeating the same artifact every turn.
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-shared-create',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-shared-1',
+ taskId: task.id,
+ topicId,
+ });
+ await workModel.registerTask({
+ changeType: 'updated',
+ rootOperationId: 'op-shared-update',
+ toolName: 'updateTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-shared-2',
+ taskId: task.id,
+ topicId,
+ });
+
+ const summaries = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-shared-create', 'op-shared-update'],
+ });
+
+ expect(summaries['op-shared-create']).toEqual([]);
+ expect(summaries['op-shared-update']).toHaveLength(1);
+ expect(summaries['op-shared-update'][0].event).toMatchObject({
+ changeType: 'updated',
+ rootOperationId: 'op-shared-update',
+ });
+ });
+
+ it('keeps the summary card in this conversation when a later edit happens in a foreign operation', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Cross-topic work', name: 'Cross-topic' });
+
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-home-round',
+ taskId: task.id,
+ toolCallId: 'tool-call-home-1',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ topicId,
+ });
+ // Same task edited later by an operation from ANOTHER conversation. That
+ // operation is not in this conversation's anchor set, so it must not steal
+ // the card: anchoring is latest-wins WITHIN the requested ids only.
+ await workModel.registerTask({
+ changeType: 'updated',
+ rootOperationId: 'op-foreign-round',
+ taskId: task.id,
+ toolCallId: 'tool-call-foreign-1',
+ toolIdentifier: 'lobe-task',
+ toolName: 'editTask',
+ topicId,
+ });
+
+ const summaries = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-home-round'],
+ });
+
+ expect(summaries['op-home-round']).toHaveLength(1);
+ // The card still shows the Work's CURRENT snapshot (the foreign edit).
+ expect(summaries['op-home-round'][0].event).toMatchObject({
+ changeType: 'updated',
+ rootOperationId: 'op-foreign-round',
+ version: 2,
+ });
+ });
+
+ it('clamps the summary over-fetch limit while still returning results for large id batches', async () => {
+ const agentDocumentModel = new AgentDocumentModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const doc = await agentDocumentModel.create(agentId, 'clamp.md', 'Clamp body', {
+ title: 'Clamp',
+ });
+
+ await workModel.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ changeType: 'created',
+ rootOperationId: 'op-doc-clamp',
+ toolName: 'createDocument',
+ toolIdentifier: 'lobe-agent-documents',
+ toolCallId: 'tool-call-doc-clamp',
+ topicId,
+ });
+
+ // 601 ids * limit 20 far exceeds MAX_SUMMARY_ROW_LIMIT, so the
+ // query LIMIT is clamped — the real operation's summary must still surface.
+ const syntheticIds = Array.from({ length: 600 }, (_, index) => `op-doc-clamp-pad-${index}`);
+ const summaries = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-doc-clamp', ...syntheticIds],
+ });
+
+ expect(Object.keys(summaries)).toHaveLength(601);
+ expect(summaries['op-doc-clamp']).toHaveLength(1);
+ expect(summaries['op-doc-clamp'][0]).toMatchObject({
+ identifier: 'clamp.md',
+ resourceId: doc.documentId,
+ });
+ expect(summaries[syntheticIds[0]]).toEqual([]);
+ });
+
+ it('filters the workspace list to one skill provider by its resource types', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+
+ await workModel.registerExternal({
+ changeType: 'created',
+ identifier: 'ENG-1',
+ patchFields: ['identifier', 'title'],
+ resourceId: 'linear-issue-1',
+ resourceType: 'linear_issue',
+ toolCallId: 'tool-call-linear-issue-1',
+ toolIdentifier: 'linear',
+ toolName: 'save_issue',
+ title: 'Linear issue',
+ topicId,
+ });
+ await workModel.registerExternal({
+ changeType: 'created',
+ identifier: 'lobehub/lobehub#1',
+ patchFields: ['identifier', 'title'],
+ resourceId: 'lobehub/lobehub#1',
+ resourceType: 'github_issue',
+ toolCallId: 'tool-call-github-issue-1',
+ toolIdentifier: 'github',
+ toolName: 'create_issue',
+ title: 'GitHub issue',
+ topicId,
+ });
+
+ // provider: 'linear' narrows the unified `external` type to linear_* rows,
+ // excluding the github row.
+ const linearOnly = await workModel.listByWorkspace({ provider: 'linear' });
+ expect(linearOnly.items).toHaveLength(1);
+ expect(linearOnly.items[0]).toMatchObject({
+ resourceId: 'linear-issue-1',
+ resourceType: 'linear_issue',
+ type: 'external',
+ });
+
+ // The unified `external` type still spans both providers.
+ const allExternal = await workModel.listByWorkspace({ type: 'external' });
+ expect(allExternal.items.map((item) => item.resourceType).sort()).toEqual([
+ 'github_issue',
+ 'linear_issue',
+ ]);
+ });
+
+ it('joins the origin topic title onto workspace list rows for grouping', async () => {
+ const titledTopicId = 'work-origin-titled-topic';
+ await serverDB.insert(topics).values({ id: titledTopicId, title: 'Origin topic', userId });
+ const workModel = new WorkModel(serverDB, userId);
+
+ await workModel.registerExternal({
+ changeType: 'created',
+ identifier: 'lobehub/lobehub#7',
+ patchFields: ['identifier', 'title'],
+ resourceId: 'lobehub/lobehub#7',
+ resourceType: 'github_issue',
+ toolCallId: 'tool-call-origin-titled',
+ toolIdentifier: 'github',
+ toolName: 'create_issue',
+ title: 'Titled origin',
+ topicId: titledTopicId,
+ });
+ // No topicId: origin is never stamped, so the gallery's "other" bucket case.
+ await workModel.registerExternal({
+ changeType: 'created',
+ identifier: 'lobehub/lobehub#8',
+ patchFields: ['identifier', 'title'],
+ resourceId: 'lobehub/lobehub#8',
+ resourceType: 'github_issue',
+ toolCallId: 'tool-call-origin-none',
+ toolIdentifier: 'github',
+ toolName: 'create_issue',
+ title: 'No origin',
+ });
+
+ const workspace = await workModel.listByWorkspace({});
+ const byResource = new Map(workspace.items.map((item) => [item.resourceId, item]));
+
+ expect(byResource.get('lobehub/lobehub#7')).toMatchObject({
+ originTopicId: titledTopicId,
+ originTopicTitle: 'Origin topic',
+ });
+ expect(byResource.get('lobehub/lobehub#8')).toMatchObject({
+ originTopicId: null,
+ originTopicTitle: null,
+ });
+ });
+
+ it('omits full content from every card-facing query payload', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+ const content = 'Full external body that must stay off card payloads';
+
+ const work = await workModel.registerExternal({
+ changeType: 'created',
+ content,
+ description: 'Bounded preview',
+ identifier: 'lobehub/lobehub#42',
+ patchFields: ['content', 'description', 'identifier', 'title'],
+ resourceId: 'lobehub/lobehub#42',
+ resourceType: 'github_issue',
+ rootOperationId: 'op-card-projection',
+ toolCallId: 'tool-call-card-projection',
+ toolIdentifier: 'github',
+ toolName: 'create_issue',
+ title: 'Card projection',
+ topicId,
+ });
+
+ // The immutable version retains layer-3 content for a future detail read.
+ const [version] = await workModel.listVersions(work!.id);
+ expect(version.content).toBe(content);
+
+ const events = await workModel.listByRootOperation({
+ rootOperationId: 'op-card-projection',
+ });
+ const summaries = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-card-projection'],
+ });
+ const conversation = await workModel.listByConversation({ topicId });
+ const workspace = await workModel.listByWorkspace({});
+ const cardItems = [
+ ...events,
+ ...summaries['op-card-projection'],
+ ...conversation,
+ ...workspace.items,
+ ];
+
+ expect(cardItems).toHaveLength(4);
+ for (const item of cardItems) {
+ expect(item).not.toHaveProperty('content');
+ expect(item.description).toBe('Bounded preview');
+ }
+ });
+
+ it('accepts a works row with a null resourceId', async () => {
+ // `works.resourceId` is nullable now: rows with no stable backing resource
+ // bypass the partial unique indexes (Postgres treats NULLs as distinct).
+ const [row] = await serverDB
+ .insert(works)
+ .values({
+ resourceType: 'document',
+ toolIdentifier: 'manual-test',
+ toolName: 'manual-test',
+ type: 'document',
+ userId,
+ visibility: 'private',
+ })
+ .returning();
+
+ expect(row.resourceId).toBeNull();
+
+ const [stored] = await serverDB.select().from(works).where(eq(works.id, row.id));
+ expect(stored.resourceId).toBeNull();
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/task.test.ts b/packages/database/src/models/work/__tests__/task.test.ts
new file mode 100644
index 00000000000..b46842c50c5
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/task.test.ts
@@ -0,0 +1,991 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { messages, topics, works, workspaces, workVersions } from '../../../schemas';
+import { TaskModel } from '../../task';
+import { WorkModel } from '..';
+import {
+ agentId,
+ cleanupWorkTestData,
+ expectTaskListItem,
+ expectTaskSummaryItem,
+ seedWorkTestData,
+ serverDB,
+ threadId,
+ topicId,
+ userId,
+ userId2,
+} from './_fixtures';
+
+beforeEach(seedWorkTestData);
+afterEach(cleanupWorkTestData);
+
+describe('WorkModel · task', () => {
+ it('registers a task work with v1 carrying the attribution fields', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({
+ instruction: 'Write the MVP plan',
+ name: 'Work MVP plan',
+ priority: 2,
+ });
+ await serverDB.insert(messages).values([
+ {
+ content: '',
+ id: 'msg-assistant',
+ role: 'assistant',
+ topicId,
+ userId,
+ },
+ {
+ content: '',
+ id: 'msg-tool',
+ parentId: 'msg-assistant',
+ role: 'tool',
+ topicId,
+ userId,
+ },
+ ]);
+
+ const work = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-root',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ messageId: 'msg-tool',
+ toolCallId: 'tool-call-create',
+ taskId: task.id,
+ threadId,
+ topicId,
+ });
+
+ expect(work).toBeDefined();
+ expect(work?.resourceId).toBe(task.id);
+ expect(work?.currentVersionId).toBeTruthy();
+
+ const versions = await workModel.listVersions(work!.id);
+ expect(versions).toHaveLength(1);
+ expect(versions[0]).toMatchObject({
+ changeType: 'created',
+ content: 'Write the MVP plan',
+ description: 'Write the MVP plan',
+ identifier: task.identifier,
+ rootOperationId: 'op-root',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ messageId: 'msg-tool',
+ toolCallId: 'tool-call-create',
+ status: 'backlog',
+ threadId,
+ title: 'Work MVP plan',
+ topicId,
+ version: 1,
+ });
+ // Work materializes every current card field from the same version.
+ expect(work).toMatchObject({
+ description: 'Write the MVP plan',
+ identifier: task.identifier,
+ originThreadId: threadId,
+ originTopicId: topicId,
+ status: 'backlog',
+ title: 'Work MVP plan',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ visibility: 'public',
+ });
+
+ const worksInConversation = await workModel.listByConversation({ threadId, topicId });
+ expect(worksInConversation).toHaveLength(1);
+ expect(worksInConversation[0]).toMatchObject({
+ id: work?.id,
+ task: { name: 'Work MVP plan', priority: 2, status: 'backlog' },
+ taskDeleted: false,
+ });
+
+ const byOperation = await workModel.listByRootOperation({ rootOperationId: 'op-root' });
+ expect(byOperation).toHaveLength(1);
+ expect(byOperation[0].id).toBe(work?.id);
+
+ const byOperations = await workModel.listByRootOperations({
+ rootOperationIds: ['op-missing', 'op-root'],
+ });
+ expect(byOperations['op-root']).toHaveLength(1);
+ expect(byOperations['op-root']?.[0]).toMatchObject({
+ id: work?.id,
+ version: expect.objectContaining({
+ rootOperationId: 'op-root',
+ messageId: 'msg-tool',
+ }),
+ });
+ expect(byOperations['op-missing']).toEqual([]);
+ });
+
+ it('stamps origin provenance once at identity creation and never updates it', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Origin task', name: 'Origin task' });
+
+ const otherTopicId = 'work-test-topic-id-origin';
+ await serverDB.insert(topics).values({ id: otherTopicId, userId });
+
+ const created = await workModel.registerTask({
+ agentId,
+ changeType: 'created',
+ rootOperationId: 'op-origin-create',
+ taskId: task.id,
+ threadId,
+ toolCallId: 'tool-call-origin-1',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ topicId,
+ });
+ expect(created).toMatchObject({
+ originAgentId: agentId,
+ originThreadId: threadId,
+ originTopicId: topicId,
+ });
+
+ // A later registration from another conversation (and no agent) appends a
+ // version but must NOT touch the immutable origin columns.
+ const updated = await workModel.registerTask({
+ changeType: 'updated',
+ rootOperationId: 'op-origin-update',
+ taskId: task.id,
+ toolCallId: 'tool-call-origin-2',
+ toolIdentifier: 'lobe-task',
+ toolName: 'editTask',
+ topicId: otherTopicId,
+ });
+ expect(updated).toMatchObject({
+ originAgentId: agentId,
+ originThreadId: threadId,
+ originTopicId: topicId,
+ });
+ // The version itself carries the new conversation's provenance.
+ const versions = await workModel.listVersions(created!.id);
+ expect(versions[0]).toMatchObject({ topicId: otherTopicId, version: 2 });
+ });
+
+ it('keeps conversation provenance on versions and latest card state on Work', async () => {
+ const otherTopicId = 'work-test-second-topic-id';
+ await serverDB.insert(topics).values({ id: otherTopicId, userId });
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Creator topic', name: 'Creator topic' });
+
+ // Conversation provenance belongs to each immutable mutation version.
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-provenance-first',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-provenance-first',
+ taskId: task.id,
+ threadId,
+ topicId,
+ });
+
+ await taskModel.update(task.id, { name: 'Latest title' });
+ const edited = await workModel.registerTask({
+ changeType: 'updated',
+ rootOperationId: 'op-provenance-second',
+ toolName: 'editTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-provenance-second',
+ taskIdentifier: task.identifier,
+ topicId: otherTopicId,
+ });
+
+ const [row] = await serverDB.select().from(works).where(eq(works.id, edited!.id));
+ expect(row).toMatchObject({
+ // Origin stays pinned to the first registration's conversation even
+ // though the current card state comes from the second one.
+ originThreadId: threadId,
+ originTopicId: topicId,
+ title: 'Latest title',
+ toolName: 'editTask',
+ toolIdentifier: 'lobe-task',
+ });
+
+ const versions = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, edited!.id));
+ const byToolCall = new Map(versions.map((version) => [version.toolCallId, version]));
+ expect(byToolCall.get('tool-call-provenance-first')).toMatchObject({ threadId, topicId });
+ expect(byToolCall.get('tool-call-provenance-second')).toMatchObject({
+ threadId: null,
+ topicId: otherTopicId,
+ });
+ });
+
+ it('stores a complete task display snapshot and caches title/description on Work', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ // A long instruction proves `content` keeps the full text while `description`
+ // is the ≤120 preview.
+ const instruction = 'B'.repeat(300);
+ const expectedDescription = `${'B'.repeat(120)}...`;
+ const task = await taskModel.create({ instruction, name: 'Fill display task' });
+
+ const work = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-fill-display',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-fill-display',
+ taskId: task.id,
+ topicId,
+ });
+
+ const [workRow] = await serverDB.select().from(works).where(eq(works.id, work!.id));
+ expect(workRow).toMatchObject({
+ description: expectedDescription,
+ identifier: task.identifier,
+ status: 'backlog',
+ title: 'Fill display task',
+ });
+
+ const [version] = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, work!.id));
+ expect(version).toMatchObject({
+ content: instruction,
+ description: expectedDescription,
+ identifier: task.identifier,
+ status: 'backlog',
+ title: 'Fill display task',
+ });
+ });
+
+ it('caps workVersions.content at WORK_CONTENT_MAX_LENGTH on write', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ // An instruction past the 65 536-char cap must not land verbatim in the
+ // immutable version snapshot.
+ const instruction = 'C'.repeat(70_000);
+ const task = await taskModel.create({ instruction, name: 'Capped content task' });
+
+ const work = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-capped-content',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-capped-content',
+ taskId: task.id,
+ topicId,
+ });
+
+ const [version] = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, work!.id));
+ expect(version.content).toBe(`${'C'.repeat(65_536)}...`);
+ });
+
+ it('rolls back a newly inserted Work when version creation fails', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Atomic write', name: 'Atomic task' });
+
+ await expect(
+ workModel.registerTask({
+ agentId: 'missing-agent-id',
+ changeType: 'created',
+ rootOperationId: 'op-atomic-failure',
+ taskId: task.id,
+ toolCallId: 'tool-call-atomic-failure',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ }),
+ ).rejects.toThrow();
+
+ const workRows = await serverDB.select().from(works).where(eq(works.resourceId, task.id));
+ expect(workRows).toHaveLength(0);
+ });
+
+ it('updates Work tool fields to the latest version while preserving version provenance', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Creator', name: 'Creator task' });
+
+ const created = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-creator-create',
+ toolName: 'createTask',
+ toolCallId: 'tool-call-creator-create',
+ toolIdentifier: 'lobe-task',
+ taskId: task.id,
+ topicId,
+ });
+ expect(created).toMatchObject({ toolIdentifier: 'lobe-task', toolName: 'createTask' });
+
+ await taskModel.update(task.id, { name: 'Creator task edited' });
+
+ const edited = await workModel.registerTask({
+ changeType: 'updated',
+ rootOperationId: 'op-creator-edit',
+ toolName: 'editTask',
+ toolCallId: 'tool-call-creator-edit',
+ toolIdentifier: 'some-other-tool',
+ taskId: task.id,
+ topicId,
+ });
+ expect(edited).toMatchObject({ toolIdentifier: 'some-other-tool', toolName: 'editTask' });
+
+ const [row] = await serverDB.select().from(works).where(eq(works.id, created!.id));
+ expect(row).toMatchObject({ toolIdentifier: 'some-other-tool', toolName: 'editTask' });
+
+ // `work_versions.toolIdentifier` is per-version: each version keeps the
+ // value passed at that registration.
+ const versions = await workModel.listVersions(created!.id);
+ const byToolCall = new Map(versions.map((v) => [v.toolCallId, v.toolIdentifier]));
+ expect(byToolCall.get('tool-call-creator-create')).toBe('lobe-task');
+ expect(byToolCall.get('tool-call-creator-edit')).toBe('some-other-tool');
+ });
+
+ it('writes cumulativeCost only on the version that carried it at insert time', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const firstTask = await taskModel.create({
+ instruction: 'First tool work',
+ name: 'First work',
+ });
+ const secondTask = await taskModel.create({
+ instruction: 'Second tool work',
+ name: 'Second work',
+ });
+
+ // The agent runtime stamps each register call with its own tool-call cost,
+ // so only the version registered with cost carries it — a sibling version
+ // registered cost-less stays null (no shared backfill spills over).
+ const firstWork = await workModel.registerTask({
+ cumulativeCost: 0.03,
+ cumulativeUsage: {
+ capturedAt: '2026-06-30T08:00:00.000Z',
+ cost: { total: 0.03 },
+ usage: { llm: { tokens: { input: 1200, output: 300, total: 1500 } } },
+ },
+ changeType: 'created',
+ rootOperationId: 'op-cumulative',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-first',
+ taskId: firstTask.id,
+ topicId,
+ });
+ const secondWork = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-cumulative',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-second',
+ taskId: secondTask.id,
+ topicId,
+ });
+
+ const [firstVersion] = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, firstWork!.id));
+ const [secondVersion] = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, secondWork!.id));
+
+ expect(firstVersion.cumulativeCost).toBe(0.03);
+ expect(firstVersion.cumulativeUsage).toMatchObject({
+ capturedAt: '2026-06-30T08:00:00.000Z',
+ cost: { total: 0.03 },
+ });
+ expect(secondVersion.cumulativeCost).toBeNull();
+ expect(secondVersion.cumulativeUsage).toBeNull();
+
+ const byOperation = await workModel.listByRootOperation({ rootOperationId: 'op-cumulative' });
+ const firstOperationWork = byOperation.find((item) => item.id === firstWork!.id);
+ expect(firstOperationWork?.version.cumulativeCost).toBe(0.03);
+ });
+
+ it('writes cumulativeCost/cumulativeUsage at insert time when registered with cost', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Insert cost', name: 'Insert cost' });
+
+ // The agent runtime now stamps the cumulative cost onto the register call,
+ // so the version row lands with its cost instead of being back-filled.
+ const work = await workModel.registerTask({
+ cumulativeCost: 0.042,
+ cumulativeUsage: {
+ capturedAt: '2026-07-08T08:00:00.000Z',
+ cost: { total: 0.042 },
+ usage: { llm: { tokens: { input: 900, output: 100, total: 1000 } } },
+ },
+ changeType: 'created',
+ rootOperationId: 'op-insert-cost',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-insert-cost',
+ taskId: task.id,
+ topicId,
+ });
+
+ const [version] = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, work!.id));
+
+ expect(version.cumulativeCost).toBe(0.042);
+ expect(version.cumulativeUsage).toMatchObject({ cost: { total: 0.042 } });
+ });
+
+ it('keeps one work row and appends versions for task edits', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Original', name: 'Original title' });
+ await serverDB.insert(messages).values({
+ content: '',
+ id: 'msg-tool-edit',
+ role: 'tool',
+ topicId,
+ userId,
+ });
+
+ const first = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-create',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-create',
+ taskId: task.id,
+ topicId,
+ });
+
+ await taskModel.update(task.id, {
+ instruction: 'Updated instruction',
+ name: 'Updated title',
+ });
+
+ const second = await workModel.registerTask({
+ changeType: 'updated',
+ rootOperationId: 'op-edit',
+ toolName: 'editTask',
+ toolIdentifier: 'lobe-task',
+ messageId: 'msg-tool-edit',
+ toolCallId: 'tool-call-edit',
+ taskIdentifier: task.identifier,
+ topicId,
+ });
+
+ expect(second?.id).toBe(first?.id);
+
+ const workRows = await serverDB.select().from(works).where(eq(works.resourceId, task.id));
+ expect(workRows).toHaveLength(1);
+
+ const versions = await workModel.listVersions(first!.id);
+ expect(versions.map((item) => item.version)).toEqual([2, 1]);
+ expect(versions[0].changeType).toBe('updated');
+ expect(versions[0].id).toBeTruthy();
+ // Every version preserves the display state captured at that mutation.
+ expect(versions[0]).toMatchObject({
+ content: 'Updated instruction',
+ identifier: task.identifier,
+ title: 'Updated title',
+ });
+ expect(versions[1]).toMatchObject({
+ content: 'Original',
+ identifier: task.identifier,
+ title: 'Original title',
+ });
+ expect(second).toMatchObject({ description: 'Updated instruction', title: 'Updated title' });
+
+ const [updatedVersion] = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.toolCallId, 'tool-call-edit'));
+ expect(updatedVersion.messageId).toBe('msg-tool-edit');
+ });
+
+ it('summarizes a task work on its latest operation with total version cost', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({
+ description: 'Original description',
+ instruction: 'Original',
+ name: 'Original title',
+ });
+
+ const first = await workModel.registerTask({
+ cumulativeCost: 0.000_295,
+ changeType: 'created',
+ rootOperationId: 'op-summary-create',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-summary-create',
+ taskId: task.id,
+ topicId,
+ });
+
+ await taskModel.update(task.id, {
+ description: 'Updated description',
+ instruction: 'Updated instruction',
+ name: 'Updated title',
+ });
+
+ await workModel.registerTask({
+ cumulativeCost: 0.000_692,
+ changeType: 'updated',
+ rootOperationId: 'op-summary-edit',
+ toolName: 'editTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-summary-edit',
+ taskIdentifier: task.identifier,
+ topicId,
+ });
+ await taskModel.update(task.id, { description: 'Live task description after snapshot' });
+
+ const byOperation = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-summary-create', 'op-summary-edit'],
+ });
+ expect(byOperation['op-summary-create']).toEqual([]);
+ expect(byOperation['op-summary-edit']).toHaveLength(1);
+ const summary = expectTaskSummaryItem(byOperation['op-summary-edit']?.[0]);
+ expect(summary).toMatchObject({
+ event: expect.objectContaining({ changeType: 'updated', rootOperationId: 'op-summary-edit' }),
+ id: first?.id,
+ task: expect.objectContaining({ name: 'Updated title' }),
+ version: expect.objectContaining({ version: 2 }),
+ });
+ // Cost is written once at insert time and summed across the two operations.
+ expect(summary.totalCost).toBeCloseTo(0.000_987, 6);
+ // Instruction is the card preview text; like name/status it coalesces the
+ // live task row onto the version snapshot.
+ expect(summary.task.instruction).toBe('Updated instruction');
+ });
+
+ it('surfaces the instruction as the card preview on every list path', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({
+ instruction: 'Print the current date with Python',
+ name: 'Greeting test',
+ });
+
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-instruction-preview',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-instruction-preview',
+ taskId: task.id,
+ threadId,
+ topicId,
+ });
+
+ // Conversation list path (live tasks join).
+ const byConversation = await workModel.listByConversation({ threadId, topicId });
+ expect(byConversation).toHaveLength(1);
+ expect(byConversation[0]).toMatchObject({
+ task: expect.objectContaining({ instruction: 'Print the current date with Python' }),
+ });
+
+ // Summary path (snapshot projection).
+ const byOperation = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-instruction-preview'],
+ });
+ const summary = expectTaskSummaryItem(byOperation['op-instruction-preview']?.[0]);
+ expect(summary.task.instruction).toBe('Print the current date with Python');
+ });
+
+ it('does not double-count cumulative cost snapshots within the same operation', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Cost', name: 'Cost task' });
+
+ // cumulativeCost is the operation's running total written once at insert
+ // time: the edit's 0.016 already contains the create's 0.01 (same
+ // operation), so the work's total is 0.016 + 0.005, not the 0.031 sum of
+ // all three snapshots.
+ await workModel.registerTask({
+ cumulativeCost: 0.01,
+ changeType: 'created',
+ rootOperationId: 'op-cost-same',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-cost-create',
+ taskId: task.id,
+ topicId,
+ });
+ await workModel.registerTask({
+ cumulativeCost: 0.016,
+ changeType: 'updated',
+ rootOperationId: 'op-cost-same',
+ toolName: 'editTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-cost-edit',
+ taskId: task.id,
+ topicId,
+ });
+ await workModel.registerTask({
+ cumulativeCost: 0.005,
+ changeType: 'updated',
+ rootOperationId: 'op-cost-other',
+ toolName: 'editTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-cost-other',
+ taskId: task.id,
+ topicId,
+ });
+
+ const summaries = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-cost-other', 'op-cost-same'],
+ });
+ const summary = expectTaskSummaryItem(summaries['op-cost-other']?.[0]);
+ expect(summary.totalCost).toBeCloseTo(0.021, 6);
+ });
+
+ it('does not let another user register someone else task', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const otherWorkModel = new WorkModel(serverDB, userId2);
+ const task = await taskModel.create({ instruction: 'Private task' });
+
+ const work = await otherWorkModel.registerTask({
+ changeType: 'created',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-other-user',
+ taskIdentifier: task.identifier,
+ topicId,
+ });
+
+ expect(work).toBeNull();
+ const workRows = await serverDB.select().from(works);
+ expect(workRows).toHaveLength(0);
+ });
+
+ it('does not expose another user task work summaries', async () => {
+ const otherTopicId = 'work-test-other-topic-id';
+ await serverDB.insert(topics).values({ id: otherTopicId, userId: userId2 });
+ const otherTaskModel = new TaskModel(serverDB, userId2);
+ const otherWorkModel = new WorkModel(serverDB, userId2);
+ const workModel = new WorkModel(serverDB, userId);
+ const otherTask = await otherTaskModel.create({
+ instruction: 'Other user summary',
+ name: 'Private summary',
+ });
+
+ await otherWorkModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-other-summary',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-other-summary',
+ taskId: otherTask.id,
+ topicId: otherTopicId,
+ });
+
+ expect(
+ await workModel.listSummariesByRootOperations({ rootOperationIds: ['op-other-summary'] }),
+ ).toEqual({ 'op-other-summary': [] });
+ });
+
+ it('deletes task work and cascades versions when removed via the tool dispatch path', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Delete task work', name: 'Delete me' });
+
+ const work = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-delete-task',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-delete-task',
+ taskId: task.id,
+ threadId,
+ topicId,
+ });
+
+ // Tool-driven deletion: the task row is removed first, then the dispatch
+ // layer drops the Work by its internal id (LOBE-11606).
+ await taskModel.delete(task.id);
+ await workModel.deleteTaskWork({ taskId: task.id });
+
+ const workRows = await serverDB.select().from(works).where(eq(works.id, work!.id));
+ const versionRows = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, work!.id));
+
+ expect(workRows).toHaveLength(0);
+ expect(versionRows).toHaveLength(0);
+ expect(await workModel.listByRootOperation({ rootOperationId: 'op-delete-task' })).toEqual([]);
+ expect(await workModel.listByConversation({ threadId, topicId })).toEqual([]);
+ });
+
+ it('leaves the task work orphaned when the task is deleted without the tool', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Non-tool delete', name: 'Keep my Work' });
+
+ const work = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-orphan-task',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-orphan-task',
+ taskId: task.id,
+ threadId,
+ topicId,
+ });
+
+ // UI / CLI delete (no tool dispatch): the Work row + versions survive as
+ // orphans so the UI can render "resource deleted" from the snapshot.
+ await taskModel.delete(task.id);
+
+ const workRows = await serverDB.select().from(works).where(eq(works.id, work!.id));
+ const versionRows = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, work!.id));
+
+ expect(workRows).toHaveLength(1);
+ expect(versionRows.length).toBeGreaterThan(0);
+ // The task-joined lists now surface the orphan via LEFT JOIN, rendered from
+ // its version snapshot and flagged `taskDeleted` so the UI shows "task
+ // deleted" instead of dropping the card entirely.
+ const orphaned = await workModel.listByConversation({ threadId, topicId });
+ expect(orphaned).toHaveLength(1);
+ expect(orphaned[0]).toMatchObject({
+ id: work!.id,
+ task: expect.objectContaining({ name: 'Keep my Work' }),
+ taskDeleted: true,
+ });
+ });
+
+ it('scopes deleteTaskWork to the current owner without touching another owner', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const otherTaskModel = new TaskModel(serverDB, userId2);
+ const workModel = new WorkModel(serverDB, userId);
+ const otherWorkModel = new WorkModel(serverDB, userId2);
+ const task = await taskModel.create({ instruction: 'Owner task' });
+ const otherTask = await otherTaskModel.create({ instruction: 'Other owner task' });
+
+ const work = await workModel.registerTask({
+ changeType: 'created',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-owner-clear',
+ taskId: task.id,
+ });
+ const otherWork = await otherWorkModel.registerTask({
+ changeType: 'created',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-other-clear',
+ taskId: otherTask.id,
+ });
+
+ // Wrong owner cannot delete another owner's Work; the right owner can.
+ await otherWorkModel.deleteTaskWork({ taskId: task.id });
+ const stillPresent = await serverDB.select().from(works).where(eq(works.id, work!.id));
+ expect(stillPresent).toHaveLength(1);
+
+ await workModel.deleteTaskWork({ taskId: task.id });
+
+ const deletedWorkRows = await serverDB.select().from(works).where(eq(works.id, work!.id));
+ const remainingOtherWorkRows = await serverDB
+ .select()
+ .from(works)
+ .where(eq(works.id, otherWork!.id));
+
+ expect(deletedWorkRows).toHaveLength(0);
+ expect(remainingOtherWorkRows).toHaveLength(1);
+ });
+
+ it('preserves work and versions when the topic is deleted', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Topic scoped task' });
+
+ const work = await workModel.registerTask({
+ changeType: 'created',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-topic-delete',
+ taskId: task.id,
+ topicId,
+ });
+
+ await serverDB.delete(topics).where(eq(topics.id, topicId));
+
+ const workRows = await serverDB.select().from(works).where(eq(works.id, work!.id));
+ const versionRows = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, work!.id));
+
+ expect(workRows).toHaveLength(1);
+ expect(versionRows).toHaveLength(1);
+ // topic FK on work_versions is ON DELETE SET NULL — the event row survives.
+ expect(versionRows[0].topicId).toBeNull();
+ });
+});
+
+describe('WorkModel · workspace task visibility', () => {
+ const workspaceId = 'work-test-workspace-id';
+
+ const seedWorkspace = async () => {
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Work Test Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ };
+
+ it('hides another member private-task Work from every list path', async () => {
+ await seedWorkspace();
+ const ownerTasks = new TaskModel(serverDB, userId, workspaceId);
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+ const memberWorks = new WorkModel(serverDB, userId2, workspaceId);
+
+ const task = await ownerTasks.create({
+ instruction: 'Secret instruction',
+ name: 'Secret task',
+ visibility: 'private',
+ });
+ const work = await ownerWorks.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-private-visibility',
+ toolCallId: 'tool-call-private-visibility',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ taskId: task.id,
+ topicId,
+ });
+
+ // The registrant keeps full access.
+ expect(await ownerWorks.listByConversation({ topicId })).toHaveLength(1);
+
+ // The other member sees nothing on any list path.
+ expect(await memberWorks.listByConversation({ topicId })).toHaveLength(0);
+ expect((await memberWorks.listByWorkspace({})).items).toHaveLength(0);
+ expect(
+ await memberWorks.listSummariesByRootOperations({
+ rootOperationIds: ['op-private-visibility'],
+ }),
+ ).toEqual({ 'op-private-visibility': [] });
+ expect(await memberWorks.listVersions(work!.id)).toHaveLength(0);
+ });
+
+ it('keeps public-task Works member-visible until the task flips private', async () => {
+ await seedWorkspace();
+ const ownerTasks = new TaskModel(serverDB, userId, workspaceId);
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+ const memberWorks = new WorkModel(serverDB, userId2, workspaceId);
+
+ const task = await ownerTasks.create({
+ instruction: 'Shared instruction',
+ name: 'Shared task',
+ visibility: 'public',
+ });
+ await ownerWorks.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-public-visibility',
+ toolCallId: 'tool-call-public-visibility',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ taskId: task.id,
+ topicId,
+ });
+
+ const memberView = await memberWorks.listByConversation({ topicId });
+ expect(memberView).toHaveLength(1);
+ expect(expectTaskListItem(memberView[0]).task.name).toBe('Shared task');
+
+ // The task transition mirrors visibility onto Work in the same transaction.
+ await ownerTasks.updateVisibility(task.id, 'private');
+
+ const [mirrored] = await serverDB
+ .select({ visibility: works.visibility })
+ .from(works)
+ .where(eq(works.resourceId, task.id));
+ expect(mirrored.visibility).toBe('private');
+
+ expect(await memberWorks.listByConversation({ topicId })).toHaveLength(0);
+ expect(await ownerWorks.listByConversation({ topicId })).toHaveLength(1);
+ });
+
+ it('does not let a member register a Work against another member private task', async () => {
+ await seedWorkspace();
+ const ownerTasks = new TaskModel(serverDB, userId, workspaceId);
+ const memberWorks = new WorkModel(serverDB, userId2, workspaceId);
+
+ const privateTask = await ownerTasks.create({
+ instruction: 'Private register target',
+ visibility: 'private',
+ });
+ const publicTask = await ownerTasks.create({
+ instruction: 'Public register target',
+ visibility: 'public',
+ });
+
+ expect(
+ await memberWorks.registerTask({
+ changeType: 'updated',
+ toolCallId: 'tool-call-member-private',
+ toolName: 'updateTask',
+ toolIdentifier: 'lobe-task',
+ taskId: privateTask.id,
+ topicId,
+ }),
+ ).toBeNull();
+
+ const memberRegisteredPublicWork = await memberWorks.registerTask({
+ changeType: 'updated',
+ toolCallId: 'tool-call-member-public',
+ toolName: 'updateTask',
+ toolIdentifier: 'lobe-task',
+ taskId: publicTask.id,
+ topicId,
+ });
+ expect(memberRegisteredPublicWork).toMatchObject({
+ userId,
+ visibility: 'public',
+ });
+ });
+
+ it('hides an orphaned private-task Work from other members but keeps it for the registrant', async () => {
+ await seedWorkspace();
+ const ownerTasks = new TaskModel(serverDB, userId, workspaceId);
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+ const memberWorks = new WorkModel(serverDB, userId2, workspaceId);
+
+ const task = await ownerTasks.create({
+ instruction: 'Orphan candidate',
+ name: 'Orphan task',
+ visibility: 'private',
+ });
+ await ownerWorks.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-orphan-visibility',
+ toolCallId: 'tool-call-orphan-visibility',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ taskId: task.id,
+ topicId,
+ });
+
+ // Hard-delete outside the tool path: the Work survives as an orphan. The
+ // deleted row no longer carries visibility, so only the registrant keeps
+ // the orphan card — its snapshot title must not leak to other members.
+ await ownerTasks.delete(task.id);
+
+ const ownerView = await ownerWorks.listByConversation({ topicId });
+ expect(ownerView).toHaveLength(1);
+ expect(expectTaskListItem(ownerView[0]).taskDeleted).toBe(true);
+
+ expect(await memberWorks.listByConversation({ topicId })).toHaveLength(0);
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/workspace.test.ts b/packages/database/src/models/work/__tests__/workspace.test.ts
new file mode 100644
index 00000000000..9a71eb34e27
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/workspace.test.ts
@@ -0,0 +1,224 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { topics, workspaces } from '../../../schemas';
+import { AgentDocumentModel } from '../../agentDocuments';
+import { TaskModel } from '../../task';
+import { WorkModel } from '..';
+import {
+ agentId,
+ cleanupWorkTestData,
+ expectDocumentSummaryItem,
+ expectTaskSummaryItem,
+ seedWorkTestData,
+ serverDB,
+ topicId,
+ userId,
+ userId2,
+} from './_fixtures';
+
+beforeEach(seedWorkTestData);
+afterEach(cleanupWorkTestData);
+
+/**
+ * Register N task works sequentially so their `works.updatedAt` timestamps
+ * differ, giving the keyset cursor a deterministic order to page over. Returns
+ * the created works newest-first (registration order reversed) to mirror the
+ * `desc(updatedAt)` list ordering.
+ */
+const seedTaskWorks = async (workModel: WorkModel, taskModel: TaskModel, count: number) => {
+ const works = [];
+ for (let index = 0; index < count; index += 1) {
+ const task = await taskModel.create({
+ instruction: `Task ${index}`,
+ name: `Task ${index}`,
+ });
+ const work = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: `op-workspace-${index}`,
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: `tool-call-workspace-${index}`,
+ taskId: task.id,
+ topicId,
+ });
+ works.push(work!);
+ }
+ return works.reverse();
+};
+
+describe('WorkModel · listByWorkspace', () => {
+ it('lists works across topics and types, newest first', async () => {
+ const otherTopicId = 'work-test-other-topic-id';
+ await serverDB.insert(topics).values({ id: otherTopicId, userId });
+
+ const taskModel = new TaskModel(serverDB, userId);
+ const agentDocumentModel = new AgentDocumentModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+
+ const firstTask = await taskModel.create({ instruction: 'First', name: 'First task' });
+ const firstWork = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-cross-1',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-cross-1',
+ taskId: firstTask.id,
+ topicId,
+ });
+
+ const doc = await agentDocumentModel.create(agentId, 'cross.md', 'Cross body', {
+ title: 'Cross doc',
+ });
+ const docWork = await workModel.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ changeType: 'created',
+ rootOperationId: 'op-cross-doc',
+ toolName: 'createDocument',
+ toolIdentifier: 'lobe-agent-documents',
+ toolCallId: 'tool-call-cross-doc',
+ // Deliberately on a different topic to prove the query is cross-topic.
+ topicId: otherTopicId,
+ });
+
+ const { items, nextCursor } = await workModel.listByWorkspace({});
+
+ expect(nextCursor).toBeNull();
+ expect(items.map((item) => item.id)).toEqual([docWork!.id, firstWork!.id]);
+ expect(expectDocumentSummaryItem(items[0]).title).toBe('Cross doc');
+ expect(expectTaskSummaryItem(items[1]).task.name).toBe('First task');
+ });
+
+ it('narrows to a single type when `type` is given', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const agentDocumentModel = new AgentDocumentModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+
+ const task = await taskModel.create({ instruction: 'Typed', name: 'Typed task' });
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-typed-task',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-typed-task',
+ taskId: task.id,
+ topicId,
+ });
+
+ const doc = await agentDocumentModel.create(agentId, 'typed.md', 'Typed body', {
+ title: 'Typed doc',
+ });
+ const docWork = await workModel.registerDocument({
+ agentDocumentId: doc.id,
+ agentId,
+ documentId: doc.documentId,
+ changeType: 'created',
+ rootOperationId: 'op-typed-doc',
+ toolName: 'createDocument',
+ toolIdentifier: 'lobe-agent-documents',
+ toolCallId: 'tool-call-typed-doc',
+ topicId,
+ });
+
+ const { items } = await workModel.listByWorkspace({ type: 'document' });
+ expect(items).toHaveLength(1);
+ expect(items[0].id).toBe(docWork!.id);
+ expect(items[0].type).toBe('document');
+ });
+
+ it('pages over the keyset cursor without gaps or overlaps', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const expected = await seedTaskWorks(workModel, taskModel, 5);
+
+ const firstPage = await workModel.listByWorkspace({ limit: 2 });
+ expect(firstPage.items.map((item) => item.id)).toEqual(expected.slice(0, 2).map((w) => w.id));
+ expect(firstPage.nextCursor).toBeTruthy();
+
+ const secondPage = await workModel.listByWorkspace({ cursor: firstPage.nextCursor, limit: 2 });
+ expect(secondPage.items.map((item) => item.id)).toEqual(expected.slice(2, 4).map((w) => w.id));
+ expect(secondPage.nextCursor).toBeTruthy();
+
+ const thirdPage = await workModel.listByWorkspace({ cursor: secondPage.nextCursor, limit: 2 });
+ expect(thirdPage.items.map((item) => item.id)).toEqual(expected.slice(4).map((w) => w.id));
+ // Last page is short (1 of 2), so there is no further cursor.
+ expect(thirdPage.nextCursor).toBeNull();
+ });
+
+ it('does not expose another owner works', async () => {
+ const otherTopicId = 'work-test-other-owner-topic';
+ await serverDB.insert(topics).values({ id: otherTopicId, userId: userId2 });
+
+ const otherTaskModel = new TaskModel(serverDB, userId2);
+ const otherWorkModel = new WorkModel(serverDB, userId2);
+ const workModel = new WorkModel(serverDB, userId);
+
+ const otherTask = await otherTaskModel.create({ instruction: 'Private', name: 'Private task' });
+ await otherWorkModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-private',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-private',
+ taskId: otherTask.id,
+ topicId: otherTopicId,
+ });
+
+ const { items } = await workModel.listByWorkspace({});
+ expect(items).toEqual([]);
+ });
+
+ it('keeps workspace external Works private to their registrant', async () => {
+ const workspaceId = 'work-test-external-workspace';
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'External Work Test Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+ const memberWorks = new WorkModel(serverDB, userId2, workspaceId);
+ const work = await ownerWorks.registerExternal({
+ changeType: 'created',
+ identifier: 'lobehub/lobehub#42',
+ resourceId: 'lobehub/lobehub#42',
+ resourceType: 'github_issue',
+ toolCallId: 'tool-call-private-external',
+ toolIdentifier: 'github',
+ toolName: 'create_issue',
+ });
+
+ expect(work).toMatchObject({ userId, visibility: 'private' });
+ expect((await ownerWorks.listByWorkspace({})).items).toHaveLength(1);
+ expect((await memberWorks.listByWorkspace({})).items).toHaveLength(0);
+ });
+
+ it('flags an orphaned task work whose task was deleted without the tool', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Orphan', name: 'Orphan task' });
+
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-orphan-workspace',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ toolCallId: 'tool-call-orphan-workspace',
+ taskId: task.id,
+ topicId,
+ });
+
+ // UI/CLI delete (no tool dispatch) leaves the Work orphaned; the LEFT JOIN
+ // miss must render as `taskDeleted` from the version snapshot, not drop it.
+ await taskModel.delete(task.id);
+
+ const { items } = await workModel.listByWorkspace({});
+ expect(items).toHaveLength(1);
+ const summary = expectTaskSummaryItem(items[0]);
+ expect(summary.task.name).toBe('Orphan task');
+ expect(summary.taskDeleted).toBe(true);
+ });
+});
diff --git a/packages/database/src/models/work/context.ts b/packages/database/src/models/work/context.ts
new file mode 100644
index 00000000000..61fab97a9fc
--- /dev/null
+++ b/packages/database/src/models/work/context.ts
@@ -0,0 +1,91 @@
+import type { SQL } from 'drizzle-orm';
+import { and, eq, ne, or, sql } from 'drizzle-orm';
+
+import { agentDocuments } from '../../schemas/agentDocuments';
+import { documents } from '../../schemas/file';
+import { tasks } from '../../schemas/task';
+import { works } from '../../schemas/work';
+import type { LobeChatDatabase } from '../../type';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+
+/**
+ * Ambient dependencies every Work query/mutation needs. Passed as the first
+ * argument to the per-type free functions instead of `this`, so the per-type
+ * modules never import the `WorkModel` facade (keeping the dependency graph
+ * acyclic).
+ */
+export interface WorkContext {
+ db: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Row-level guard for task Works: visible iff the viewer registered the Work
+ * themselves OR can see the live task under the public-or-owner rule.
+ * `buildWorkspaceWhere` filters the mirrored `works.visibility`; this live
+ * resource check is defense in depth for stale/moved resources and direct DB
+ * mutations that bypass the visibility cascade. The registrant branch keeps
+ * orphaned Works (task row hard-deleted outside the tool path) rendering from
+ * their snapshot for their creator, while an orphan of a formerly-private task
+ * never leaks its snapshot to other members — the trade-off is that other
+ * members also lose orphan cards of public tasks, which is marginal. Write
+ * paths sharing `workOwnership` are safe under the guard: a Work write is
+ * always driven by a task mutation the actor performed, which the task tool
+ * layer already gates with the same public-or-owner rule (see `TaskModel`'s
+ * ownership predicate).
+ */
+const taskVisibilityGuard = (ctx: WorkContext): SQL =>
+ or(
+ ne(works.resourceType, 'task'),
+ eq(works.userId, ctx.userId),
+ // Raw EXISTS instead of a `ctx.db.select()` subquery builder so the guard
+ // stays a pure predicate. NULL visibility predates the column and is
+ // treated as public, mirroring `buildWorkspaceWhere`.
+ sql`exists (select 1 from ${tasks} where ${tasks.id} = ${works.resourceId} and (${tasks.visibility} is null or ${tasks.visibility} = 'public' or ${tasks.createdByUserId} = ${ctx.userId}))`,
+ ) as SQL;
+
+/**
+ * Row-level guard for document Works, mirroring {@link taskVisibilityGuard}:
+ * `works.visibility` is the indexed primary filter; this live resource check
+ * additionally prevents a stale or moved backing document from exposing its
+ * Work snapshot. Visible iff the viewer registered the Work themselves OR can
+ * see the backing document under the public-or-owner rule.
+ *
+ * Unlike tasks, `documents.visibility` is NOT NULL default 'public', so there is
+ * no null branch to treat as public. Orphaned document Works (backing row
+ * hard-deleted outside the tool path) fall back to registrant-only — the same
+ * trade-off the task guard makes: an orphan of a formerly-private document never
+ * leaks to other members, at the cost of other members also losing orphan cards
+ * of public documents.
+ */
+const documentVisibilityGuard = (ctx: WorkContext): SQL =>
+ or(
+ ne(works.resourceType, 'document'),
+ eq(works.userId, ctx.userId),
+ sql`exists (select 1 from ${documents} where ${documents.id} = ${works.resourceId} and (${documents.visibility} = 'public' or ${documents.userId} = ${ctx.userId}))`,
+ ) as SQL;
+
+export const workOwnership = (ctx: WorkContext) =>
+ and(
+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, works),
+ taskVisibilityGuard(ctx),
+ documentVisibilityGuard(ctx),
+ ) as SQL;
+
+/**
+ * Public-or-owner predicate for the live `tasks` join/lookup — mirrors
+ * `TaskModel`'s visibility-aware ownership so Work registration and the
+ * summary join can never see a task the task tool layer itself would hide.
+ */
+export const taskOwnership = (ctx: WorkContext) =>
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ { userId: tasks.createdByUserId, visibility: tasks.visibility, workspaceId: tasks.workspaceId },
+ );
+
+export const documentOwnership = (ctx: WorkContext) =>
+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, documents);
+
+export const agentDocumentOwnership = (ctx: WorkContext) =>
+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, agentDocuments);
diff --git a/packages/database/src/models/work/cost.ts b/packages/database/src/models/work/cost.ts
new file mode 100644
index 00000000000..986edb53a17
--- /dev/null
+++ b/packages/database/src/models/work/cost.ts
@@ -0,0 +1,46 @@
+import { inArray } from 'drizzle-orm';
+
+import { workVersions } from '../../schemas/work';
+import type { WorkContext } from './context';
+
+/**
+ * `cumulativeCost` is a running snapshot of the whole operation's spend at
+ * the time each version was written (see schemas/work.ts), not a per-version
+ * delta — so versions produced by the same root operation must not be added
+ * together (v2 already contains v1's spend). Take MAX per operation, then
+ * sum across operations. Versions without a rootOperationId are treated as
+ * independent operations.
+ */
+export const getTotalCostByWorkIds = async (ctx: WorkContext, workIds: string[]) => {
+ const ids = Array.from(new Set(workIds));
+ const result = new Map<string, number | null>();
+ if (ids.length === 0) return result;
+
+ const rows = await ctx.db
+ .select({
+ cumulativeCost: workVersions.cumulativeCost,
+ rootOperationId: workVersions.rootOperationId,
+ versionId: workVersions.id,
+ workId: workVersions.workId,
+ })
+ .from(workVersions)
+ .where(inArray(workVersions.workId, ids));
+
+ const maxCostByOperation = new Map<string, Map<string, number>>();
+ for (const row of rows) {
+ if (row.cumulativeCost === null) continue;
+
+ const operationKey = row.rootOperationId ?? row.versionId;
+ const operations = maxCostByOperation.get(row.workId) ?? new Map<string, number>();
+ operations.set(operationKey, Math.max(operations.get(operationKey) ?? 0, row.cumulativeCost));
+ maxCostByOperation.set(row.workId, operations);
+ }
+
+ for (const [workId, operations] of maxCostByOperation) {
+ let totalCost = 0;
+ for (const cost of operations.values()) totalCost += cost;
+ result.set(workId, totalCost);
+ }
+
+ return result;
+};
diff --git a/packages/database/src/models/work/displayWork.ts b/packages/database/src/models/work/displayWork.ts
new file mode 100644
index 00000000000..e3d3be42a05
--- /dev/null
+++ b/packages/database/src/models/work/displayWork.ts
@@ -0,0 +1,107 @@
+import type {
+ RegisterExternalWorkParams,
+ WorkListBaseItem,
+ WorkListItem,
+ WorkSummaryItem,
+ WorkVersionEventItem,
+} from '@lobechat/types';
+import { and, desc, eq } from 'drizzle-orm';
+
+import { works, workVersions } from '../../schemas/work';
+import { type WorkContext, workOwnership } from './context';
+import {
+ currentWorkListFields,
+ type DisplayWorkType,
+ listDisplayVersionEventRows,
+ type WorkDisplayColumns,
+ type WorkTypeAdapter,
+} from './internal';
+import { registerWorkVersion } from './writes';
+
+/**
+ * External register pipeline: atomically find-or-create the Work, merge partial
+ * results with its current snapshot under the Work-row lock, append a complete
+ * immutable version, and update the Work's current projection.
+ */
+export const registerExternalWork = async (
+ ctx: WorkContext,
+ params: RegisterExternalWorkParams,
+) => {
+ const display: WorkDisplayColumns = {
+ content: params.content,
+ description: params.description,
+ identifier: params.identifier,
+ status: params.status,
+ title: params.title,
+ url: params.url,
+ };
+
+ return registerWorkVersion(
+ ctx,
+ {
+ resourceId: params.resourceId,
+ resourceType: params.resourceType,
+ type: 'external',
+ userId: ctx.userId,
+ visibility: 'private',
+ },
+ params,
+ () => ({ display, patchFields: params.patchFields }),
+ );
+};
+
+/**
+ * Build the `WorkTypeAdapter` for a display-backed work type (document /
+ * external). Current card fields come from the Work projection; the joined
+ * version contributes event metadata only. Full `content` stays excluded from
+ * list/summary payloads.
+ */
+export const createDisplayWorkAdapter = (config: { type: DisplayWorkType }): WorkTypeAdapter => {
+ const toListItem = (work: WorkListBaseItem): WorkListItem => work as WorkListItem;
+
+ return {
+ listConversationRows: async (ctx, params) => {
+ const rows = await ctx.db
+ .select({
+ eventCreatedAt: workVersions.createdAt,
+ work: currentWorkListFields,
+ })
+ .from(workVersions)
+ .innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))
+ .where(
+ and(
+ eq(workVersions.topicId, params.topicId),
+ params.threadFilter,
+ eq(works.type, config.type),
+ ),
+ )
+ .orderBy(desc(workVersions.createdAt), desc(works.updatedAt))
+ .limit(params.rowLimit);
+
+ return rows.map((row) => ({
+ eventCreatedAt: row.eventCreatedAt,
+ item: toListItem(row.work),
+ }));
+ },
+
+ listVersionEvents: async (ctx, filters, limit) => {
+ const rows = await listDisplayVersionEventRows(ctx, config.type, filters, limit);
+
+ return rows.map(
+ (row) =>
+ ({
+ ...toListItem(row.work),
+ version: row.version,
+ }) as WorkVersionEventItem,
+ );
+ },
+
+ mapCurrentRow: (row, totalCost) =>
+ ({
+ ...toListItem(row.work),
+ event: row.event,
+ totalCost,
+ version: row.version,
+ }) as WorkSummaryItem,
+ };
+};
diff --git a/packages/database/src/models/work/document.ts b/packages/database/src/models/work/document.ts
new file mode 100644
index 00000000000..d5e46760261
--- /dev/null
+++ b/packages/database/src/models/work/document.ts
@@ -0,0 +1,100 @@
+import type { RegisterDocumentWorkParams } from '@lobechat/types';
+import type { SQL } from 'drizzle-orm';
+import { and, eq, isNull } from 'drizzle-orm';
+
+import { agentDocuments } from '../../schemas/agentDocuments';
+import { type DocumentItem, documents } from '../../schemas/file';
+import { agentDocumentOwnership, documentOwnership, type WorkContext } from './context';
+import { createDisplayWorkAdapter } from './displayWork';
+import { truncateSummaryText, type WorkDisplayColumns } from './internal';
+import { registerWorkVersion } from './writes';
+
+export const documentDisplayColumns = (
+ doc: DocumentItem,
+ params: Pick<RegisterDocumentWorkParams, 'description'>,
+): WorkDisplayColumns => {
+ // Run EVERY description source through the same card-sized truncation helper at
+ // write time. Explicit `params.description` and the persisted
+ // `documents.description` can each be multi-MB; without truncation that full
+ // body would be copied into the card-preview `description` column. Chaining
+ // with `||` preserves the original precedence (explicit → persisted → content)
+ // because `truncateSummaryText` returns `null` for empty/whitespace input.
+ const description =
+ truncateSummaryText(params.description) ||
+ truncateSummaryText(doc.description) ||
+ truncateSummaryText(doc.content);
+
+ return {
+ // Layer 3 for documents is opening the document itself; the full text lives
+ // in `documents`, so `content` stays NULL here.
+ content: null,
+ description,
+ identifier: doc.filename,
+ // No synthesized fallback for a null title: the card falls through to the
+ // identifier at the call site so data gaps stay visible.
+ title: doc.title,
+ };
+};
+
+const resolveDocument = async (
+ ctx: WorkContext,
+ params: Pick<RegisterDocumentWorkParams, 'agentDocumentId' | 'agentId' | 'documentId'>,
+): Promise<DocumentItem | null> => {
+ const [doc] = await ctx.db
+ .select()
+ .from(documents)
+ .where(and(documentOwnership(ctx), eq(documents.id, params.documentId)))
+ .limit(1);
+
+ if (!doc) return null;
+ if (!params.agentDocumentId) return doc;
+
+ const filters: SQL[] = [
+ agentDocumentOwnership(ctx),
+ eq(agentDocuments.id, params.agentDocumentId),
+ eq(agentDocuments.documentId, doc.id),
+ isNull(agentDocuments.deletedAt),
+ ...(params.agentId ? [eq(agentDocuments.agentId, params.agentId)] : []),
+ ];
+
+ const [agentDocument] = await ctx.db
+ .select({ id: agentDocuments.id })
+ .from(agentDocuments)
+ .where(and(...filters))
+ .limit(1);
+
+ return agentDocument ? doc : null;
+};
+
+/**
+ * Document keeps a custom register (unlike the linear/github factory path):
+ * it must resolve + ownership-check the backing `documents` row (and the
+ * optional `agentDocuments` binding) before any Work is written, and it stamps
+ * the binding into version metadata.
+ */
+export const registerDocumentWork = async (
+ ctx: WorkContext,
+ params: RegisterDocumentWorkParams,
+) => {
+ const doc = await resolveDocument(ctx, params);
+ if (!doc) return null;
+
+ return registerWorkVersion(
+ ctx,
+ {
+ resourceId: doc.id,
+ resourceType: 'document',
+ type: 'document',
+ userId: doc.userId,
+ visibility: doc.visibility,
+ },
+ params,
+ () => ({
+ display: documentDisplayColumns(doc, params),
+ metadata: params.agentDocumentId ? { agentDocumentId: params.agentDocumentId } : null,
+ }),
+ );
+};
+
+/** Document display fields are card-sized before the immutable version snapshot is written. */
+export const documentWorkAdapter = createDisplayWorkAdapter({ type: 'document' });
diff --git a/packages/database/src/models/work/external.ts b/packages/database/src/models/work/external.ts
new file mode 100644
index 00000000000..87424201fba
--- /dev/null
+++ b/packages/database/src/models/work/external.ts
@@ -0,0 +1,5 @@
+import { createDisplayWorkAdapter, registerExternalWork } from './displayWork';
+
+export { registerExternalWork };
+
+export const externalWorkAdapter = createDisplayWorkAdapter({ type: 'external' });
diff --git a/packages/database/src/models/work/githubToolResult.ts b/packages/database/src/models/work/githubToolResult.ts
new file mode 100644
index 00000000000..071f25b81ca
--- /dev/null
+++ b/packages/database/src/models/work/githubToolResult.ts
@@ -0,0 +1,612 @@
+import type {
+ GithubWorkResourceType,
+ RegisterExternalWorkParams,
+ SkillToolResultWorkInput,
+ WorkDisplayField,
+} from '@lobechat/types';
+
+import { WORK_DESCRIPTION_PREVIEW_LENGTH } from './internal';
+import {
+ type ExternalToolWorkOperation,
+ fromRecord,
+ hasOwn,
+ isApplicationError,
+ parseMaybeJSON,
+ sanitizeExternalUrl,
+ stringValue,
+ toRecord,
+} from './toolResultParsing';
+
+/** GitHub entity vocabulary internal to this normalizer. */
+type GithubWorkEntityType = 'issue' | 'pull_request';
+
+/**
+ * Only successful create/edit results become Works (LOBE-10967): read-only
+ * queries (get/list/search), comments, and branch/repo operations are
+ * intentionally excluded, mirroring the Linear adaptation.
+ *
+ * The github skill has two tool surfaces:
+ * - structured REST-shaped tools (`create_issue`, `update_pull_request`, ...)
+ * - a generic `runCommand` that executes `gh` CLI in the cloud sandbox — the
+ * dominant surface in production, whose results are only a command string
+ * plus stdout.
+ *
+ * Both normalize to the same identity: `owner/repo#number`. The CLI surface
+ * never returns a GitHub node_id, so node_id cannot be the dedup key — the
+ * same issue touched via both surfaces must land on one Work row.
+ */
+const GITHUB_WORK_TOOLS: Record<
+ string,
+ { entityType: GithubWorkEntityType; changeType: 'created' | 'updated' }
+> = {
+ create_issue: { entityType: 'issue', changeType: 'created' },
+ create_pull_request: { entityType: 'pull_request', changeType: 'created' },
+ update_issue: { entityType: 'issue', changeType: 'updated' },
+ update_pull_request: { entityType: 'pull_request', changeType: 'updated' },
+};
+
+const GITHUB_CLI_TOOLS = new Set(['runCommand', 'run_command']);
+
+/**
+ * Builds a `patch` helper bound to a `patchFields` set: it records that a field
+ * is present in the partial snapshot and returns the value only when present
+ * (so absent fields stay `undefined` and don't overwrite the current snapshot).
+ * Shared by the structured-tool and gh-CLI param builders.
+ */
+const makePatch =
+ (patchFields: Set<WorkDisplayField>) =>
+ <T>(field: WorkDisplayField, present: boolean, value: T): T | undefined => {
+ if (present) patchFields.add(field);
+ return present ? value : undefined;
+ };
+
+/** The card-preview `description` column stores capped text; the full body goes to `content`. */
+const previewText = (value: unknown): string | null => {
+ const text = stringValue(value);
+ if (!text) return null;
+
+ return text.length > WORK_DESCRIPTION_PREVIEW_LENGTH
+ ? `${text.slice(0, WORK_DESCRIPTION_PREVIEW_LENGTH)}...`
+ : text;
+};
+
+const numberValue = (value: unknown): number | null => {
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
+
+ if (typeof value === 'string' && /^\d+$/.test(value.trim())) return Number(value.trim());
+
+ return null;
+};
+
+const numberFromRecord = (record: Record<string, unknown>, keys: string[]) => {
+ for (const key of keys) {
+ const value = numberValue(record[key]);
+ if (value !== null) return value;
+ }
+
+ return null;
+};
+
+/** Join MCP-style content parts (`{ content: [{ text }] }`) back into one string. */
+const textFromContentParts = (value: unknown): string | null => {
+ if (!Array.isArray(value)) return null;
+
+ const joined = value
+ .map((item) => {
+ if (typeof item === 'string') return item;
+ const record = toRecord(item);
+ return record ? (stringValue(record.text) ?? stringValue(record.content)) : null;
+ })
+ .filter(Boolean)
+ .join('\n\n');
+
+ return joined || null;
+};
+
+const RESOURCE_WRAPPER_KEYS = ['issue', 'pull_request', 'pullRequest', 'data', 'result'];
+
+const unwrapData = (data: unknown): Record<string, unknown> | null => {
+ let parsed = parseMaybeJSON(data);
+
+ if (Array.isArray(parsed)) {
+ parsed = parseMaybeJSON(textFromContentParts(parsed)) ?? toRecord(parsed[0]);
+ }
+
+ let record = toRecord(parsed);
+ if (!record) return null;
+
+ if (Array.isArray(record.content)) {
+ const inner = parseMaybeJSON(textFromContentParts(record.content));
+ record = toRecord(inner) ?? record;
+ }
+
+ for (const key of RESOURCE_WRAPPER_KEYS) {
+ const nested = toRecord(record[key]);
+ if (nested) return nested;
+ }
+
+ return record;
+};
+
+const ownerRepoFromUrl = (url: string | null): string | null => {
+ if (!url) return null;
+
+ try {
+ const segments = new URL(url).pathname.split('/').filter(Boolean);
+ // https://api.github.com/repos/{owner}/{repo}/... vs https://github.com/{owner}/{repo}/...
+ const start = segments[0] === 'repos' ? 1 : 0;
+ const owner = segments[start];
+ const repo = segments[start + 1];
+ return owner && repo ? `${owner}/${repo}` : null;
+ } catch {
+ return null;
+ }
+};
+
+const isOwnerRepo = (value: string | null): value is string =>
+ !!value && /^[^/\s]+\/[^/\s#]+$/.test(value);
+
+const resolveRepo = (
+ record: Record<string, unknown>,
+ args: Record<string, unknown>,
+): string | null => {
+ const direct =
+ fromRecord(record, ['repository_full_name', 'full_name', 'repositoryFullName']) ??
+ fromRecord(toRecord(record.repository) ?? {}, ['full_name', 'fullName']) ??
+ fromRecord(toRecord(toRecord(record.base)?.repo) ?? {}, ['full_name', 'fullName']);
+ if (isOwnerRepo(direct)) return direct;
+
+ const fromUrls =
+ ownerRepoFromUrl(fromRecord(record, ['repository_url', 'repositoryUrl'])) ??
+ ownerRepoFromUrl(fromRecord(record, ['html_url', 'htmlUrl']));
+ if (fromUrls) return fromUrls;
+
+ const fromArgs = fromRecord(args, ['repository_full_name', 'full_name', 'repository', 'repo']);
+ if (isOwnerRepo(fromArgs)) return fromArgs;
+
+ const owner = fromRecord(args, ['owner']);
+ const repo = fromRecord(args, ['repo', 'name']);
+ return owner && repo ? `${owner}/${repo}` : null;
+};
+
+const resolveNumber = (
+ record: Record<string, unknown>,
+ args: Record<string, unknown>,
+): number | null =>
+ numberFromRecord(record, ['number']) ??
+ numberFromRecord(args, ['issue_number', 'pull_number', 'issueNumber', 'pullNumber', 'number']);
+
+const resolveUrl = (record: Record<string, unknown>): string | null => {
+ const htmlUrl = fromRecord(record, ['html_url', 'htmlUrl']);
+ if (htmlUrl) return htmlUrl;
+
+ const url = fromRecord(record, ['url']);
+ return url && /^https?:\/\/github\.com\//i.test(url) ? url : null;
+};
+
+/**
+ * Collapse GitHub's state/merged/draft triplet into one display status:
+ * merged and draft win over the raw `state` ('open' | 'closed').
+ */
+const resolveStatus = (record: Record<string, unknown>): string | null => {
+ if (record.merged === true) return 'merged';
+ if (record.draft === true) return 'draft';
+ return fromRecord(record, ['state']);
+};
+
+const hasStatusSignal = (record: Record<string, unknown>) =>
+ hasOwn(record, 'state') ||
+ typeof record.merged === 'boolean' ||
+ typeof record.draft === 'boolean';
+
+const githubResourceType = (entityType: GithubWorkEntityType): GithubWorkResourceType =>
+ entityType === 'issue' ? 'github_issue' : 'github_pull_request';
+
+const buildParams = (
+ params: SkillToolResultWorkInput,
+ tool: { entityType: GithubWorkEntityType; changeType: 'created' | 'updated' },
+ record: Record<string, unknown>,
+): Omit<RegisterExternalWorkParams, 'resourceId' | 'toolIdentifier'> => {
+ const args = params.args ?? {};
+ const repo = resolveRepo(record, args);
+ const number = resolveNumber(record, args);
+ // Allowlist http(s) only: a tool-result `html_url` is member-controlled and
+ // the persisted url reaches shell.openExternal on desktop.
+ const url = sanitizeExternalUrl(resolveUrl(record));
+
+ const patchFields = new Set<WorkDisplayField>();
+ const patch = makePatch(patchFields);
+
+ // `owner/repo#number` is encoded into `identifier`; repo/number are no longer
+ // persisted as their own display fields.
+ if (repo && number !== null) patchFields.add('identifier');
+ if (url) patchFields.add('url');
+
+ return {
+ agentId: params.agentId ?? null,
+ changeType: tool.changeType,
+ // The FULL issue/PR body (layer 3); the card preview is the capped `description`.
+ content: patch('content', hasOwn(record, 'body'), stringValue(record.body)),
+ cumulativeCost: params.cumulativeCost ?? null,
+ cumulativeUsage: params.cumulativeUsage ?? null,
+ description: patch('description', hasOwn(record, 'body'), previewText(record.body)),
+ identifier: repo && number !== null ? `${repo}#${number}` : null,
+ resourceType: githubResourceType(tool.entityType),
+ messageId: params.messageId ?? null,
+ rootOperationId: params.rootOperationId ?? null,
+ status: patch('status', hasStatusSignal(record), resolveStatus(record)),
+ threadId: params.threadId ?? null,
+ title: patch('title', hasOwn(record, 'title'), stringValue(record.title)),
+ toolCallId: params.toolCallId ?? null,
+ toolName: params.toolName,
+ topicId: params.topicId ?? null,
+ url,
+ // Evaluated last: every patch() call above must run before the set is
+ // materialized (object literal properties evaluate in order).
+ patchFields: Array.from(patchFields),
+ };
+};
+
+// ---------------------------------------------------------------------------
+// gh CLI (`runCommand`) parsing
+// ---------------------------------------------------------------------------
+
+const CONTROL_OPERATORS = new Set(['&&', '||', ';', '|', '&']);
+
+/**
+ * Minimal POSIX-ish tokenizer: whitespace splitting with single/double quote
+ * and backslash handling. Returns null on unterminated quotes — better to
+ * skip registration than to mis-attribute flag values.
+ *
+ * Deliberately hand-rolled instead of adding a `shell-quote`-style dependency:
+ * a real shell parser would also expand what we must keep literal (`$VAR`,
+ * globs) and adds a dependency to the database package for a best-effort
+ * bookkeeping path whose worst failure mode is skipping a Work registration.
+ * Known trade-off: quoting is stripped before operator splitting, so a quoted
+ * literal like `--title '&&'` is treated as a control operator and at worst
+ * truncates the parsed segment. Edge cases are pinned in
+ * `__tests__/githubToolResult.test.ts`.
+ */
+const tokenizeShellCommand = (input: string): string[] | null => {
+ const tokens: string[] = [];
+ let current = '';
+ let hasCurrent = false;
+ let i = 0;
+
+ const push = () => {
+ if (hasCurrent) {
+ tokens.push(current);
+ current = '';
+ hasCurrent = false;
+ }
+ };
+
+ while (i < input.length) {
+ const ch = input[i];
+
+ if (ch === "'") {
+ const end = input.indexOf("'", i + 1);
+ if (end === -1) return null;
+ current += input.slice(i + 1, end);
+ hasCurrent = true;
+ i = end + 1;
+ } else if (ch === '"') {
+ i++;
+ let closed = false;
+ while (i < input.length) {
+ const c = input[i];
+ if (c === '\\' && '"\\$`'.includes(input[i + 1] ?? '')) {
+ current += input[i + 1];
+ i += 2;
+ } else if (c === '"') {
+ closed = true;
+ i++;
+ break;
+ } else {
+ current += c;
+ i++;
+ }
+ }
+ if (!closed) return null;
+ hasCurrent = true;
+ } else if (ch === '\\') {
+ // Backslash-newline is a line continuation; otherwise escape the next char.
+ if (input[i + 1] === '\n') {
+ i += 2;
+ } else {
+ current += input[i + 1] ?? '';
+ hasCurrent = true;
+ i += 2;
+ }
+ } else if (/\s/.test(ch)) {
+ push();
+ i++;
+ } else {
+ current += ch;
+ hasCurrent = true;
+ i++;
+ }
+ }
+
+ push();
+ return tokens;
+};
+
+/** Split a token stream on whitespace-separated shell control operators. */
+const splitCommandSegments = (tokens: string[]): string[][] => {
+ const segments: string[][] = [];
+ let current: string[] = [];
+
+ for (const token of tokens) {
+ if (CONTROL_OPERATORS.has(token)) {
+ if (current.length > 0) segments.push(current);
+ current = [];
+ } else {
+ current.push(token);
+ }
+ }
+
+ if (current.length > 0) segments.push(current);
+ return segments;
+};
+
+/**
+ * gh flags that consume a value. Needed even for flags we don't extract, so
+ * their values are not misread as positional targets (`gh issue edit 952`).
+ */
+const GH_VALUE_FLAGS = new Set([
+ '--add-assignee',
+ '--add-label',
+ '--add-project',
+ '--add-reviewer',
+ '--assignee',
+ '--base',
+ '--body',
+ '--body-file',
+ '--head',
+ '--label',
+ '--milestone',
+ '--project',
+ '--recover',
+ '--remove-assignee',
+ '--remove-label',
+ '--remove-project',
+ '--remove-reviewer',
+ '--repo',
+ '--reviewer',
+ '--template',
+ '--title',
+ '-a',
+ '-B',
+ '-b',
+ '-F',
+ '-H',
+ '-l',
+ '-m',
+ '-p',
+ '-R',
+ '-r',
+ '-T',
+ '-t',
+]);
+
+interface GithubEntityRef {
+ entityType: GithubWorkEntityType;
+ number: number;
+ repo: string;
+ url: string;
+}
+
+const GITHUB_ENTITY_URL_RE = /https?:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/(issues|pull)\/(\d+)/gi;
+
+const parseGithubEntityUrls = (text: string | null): GithubEntityRef[] => {
+ if (!text) return [];
+
+ return Array.from(text.matchAll(GITHUB_ENTITY_URL_RE), (match) => ({
+ entityType: (match[3] === 'issues' ? 'issue' : 'pull_request') as GithubWorkEntityType,
+ number: Number(match[4]),
+ repo: `${match[1]}/${match[2]}`,
+ url: match[0],
+ }));
+};
+
+interface ParsedGhCommand {
+ action: 'create' | 'edit';
+ body: string | null;
+ draft: boolean;
+ entityType: GithubWorkEntityType;
+ repo: string | null;
+ targetNumber: number | null;
+ targetRef: GithubEntityRef | null;
+ title: string | null;
+}
+
+const parseGhSegment = (segment: string[]): ParsedGhCommand | null => {
+ if (segment[0] !== 'gh') return null;
+
+ const noun = segment[1];
+ const action = segment[2];
+ if (noun !== 'issue' && noun !== 'pr') return null;
+ if (action !== 'create' && action !== 'edit') return null;
+
+ let body: string | null = null;
+ let draft = false;
+ let repoFlag: string | null = null;
+ let title: string | null = null;
+ const positionals: string[] = [];
+
+ for (let i = 3; i < segment.length; i++) {
+ let token = segment[i];
+ let value: string | null = null;
+
+ if (token.startsWith('--') && token.includes('=')) {
+ const eq = token.indexOf('=');
+ value = token.slice(eq + 1);
+ token = token.slice(0, eq);
+ }
+
+ if (!token.startsWith('-')) {
+ positionals.push(token);
+ continue;
+ }
+
+ if (value === null && GH_VALUE_FLAGS.has(token)) {
+ value = segment[i + 1] ?? null;
+ i++;
+ }
+
+ switch (token) {
+ case '-t':
+ case '--title': {
+ title = value;
+ break;
+ }
+ case '-b':
+ case '--body': {
+ body = value;
+ break;
+ }
+ case '-R':
+ case '--repo': {
+ repoFlag = value;
+ break;
+ }
+ case '-d':
+ case '--draft': {
+ draft = true;
+ break;
+ }
+ default: {
+ // Other value flags had their value consumed above; other boolean
+ // flags (--web, --fill, ...) carry nothing we snapshot.
+ break;
+ }
+ }
+ }
+
+ const repo = isOwnerRepo(repoFlag) ? repoFlag : ownerRepoFromUrl(repoFlag);
+
+ // Edit target: `gh issue edit 952` or `gh pr edit <url>`.
+ let targetNumber: number | null = null;
+ let targetRef: GithubEntityRef | null = null;
+ for (const positional of positionals) {
+ const ref = parseGithubEntityUrls(positional)[0];
+ if (ref) targetRef = ref;
+ else if (/^\d+$/.test(positional)) targetNumber = Number(positional);
+ }
+
+ return {
+ action,
+ body,
+ draft,
+ entityType: noun === 'issue' ? 'issue' : 'pull_request',
+ repo,
+ targetNumber,
+ targetRef,
+ title,
+ };
+};
+
+const normalizeGithubCliResult = (
+ params: SkillToolResultWorkInput,
+): ExternalToolWorkOperation | null => {
+ const record = unwrapData(params.data);
+ if (!record) return null;
+
+ const exitCode = numberFromRecord(record, ['exitCode', 'exit_code']);
+ if (exitCode !== null && exitCode !== 0) return null;
+
+ const args = params.args ?? {};
+ const command = fromRecord(record, ['command']) ?? fromRecord(args, ['command']);
+ if (!command) return null;
+
+ const tokens = tokenizeShellCommand(command);
+ if (!tokens) return null;
+
+ // A chained command (`git push && gh pr create ...`) reports one combined
+ // stdout; the trailing URL belongs to the last gh create/edit segment.
+ const parsed = splitCommandSegments(tokens)
+ .map(parseGhSegment)
+ .findLast((segment): segment is ParsedGhCommand => !!segment);
+ if (!parsed) return null;
+
+ // stdout is the source of truth for identity: `gh issue/pr create|edit`
+ // prints the entity URL as its result line. Fall back to the edit target
+ // in the command when stdout carries no URL.
+ const output = fromRecord(record, ['output', 'stdout']);
+ const ref =
+ parseGithubEntityUrls(output).at(-1) ??
+ parsed.targetRef ??
+ (parsed.targetNumber !== null && parsed.repo
+ ? {
+ entityType: parsed.entityType,
+ number: parsed.targetNumber,
+ repo: parsed.repo,
+ url: null,
+ }
+ : null);
+ if (!ref) return null;
+
+ const identifier = `${ref.repo}#${ref.number}`;
+
+ // Allowlist http(s) only: the url is parsed from member-controlled `gh`
+ // stdout and reaches shell.openExternal on desktop.
+ const safeUrl = sanitizeExternalUrl(ref.url);
+
+ const patchFields = new Set<WorkDisplayField>(['identifier']);
+ const patch = makePatch(patchFields);
+
+ return {
+ params: {
+ agentId: params.agentId ?? null,
+ changeType: parsed.action === 'create' ? 'created' : 'updated',
+ // The FULL `--body` value (layer 3); the card preview is the capped `description`.
+ content: patch('content', parsed.body !== null, parsed.body),
+ cumulativeCost: params.cumulativeCost ?? null,
+ cumulativeUsage: params.cumulativeUsage ?? null,
+ description: patch('description', parsed.body !== null, previewText(parsed.body)),
+ identifier,
+ resourceId: identifier,
+ resourceType: githubResourceType(ref.entityType),
+ messageId: params.messageId ?? null,
+ rootOperationId: params.rootOperationId ?? null,
+ // gh only exposes --draft on create; an edit carries no status signal.
+ status: patch('status', parsed.action === 'create', parsed.draft ? 'draft' : 'open'),
+ threadId: params.threadId ?? null,
+ title: patch('title', parsed.title !== null, stringValue(parsed.title)),
+ toolCallId: params.toolCallId ?? null,
+ toolName: params.toolName,
+ topicId: params.topicId ?? null,
+ url: patch('url', !!safeUrl, safeUrl),
+ // Evaluated last: every patch() call above must run before the set is
+ // materialized (object literal properties evaluate in order).
+ patchFields: Array.from(patchFields),
+ },
+ type: 'register',
+ };
+};
+
+export const normalizeGithubToolResult = (
+ params: SkillToolResultWorkInput,
+): ExternalToolWorkOperation | null => {
+ // Payload apiNames sometimes carry the provider prefix (e.g. `github_create_issue`).
+ const toolName = params.toolName.replace(/^github_/, '');
+
+ if (isApplicationError(params.data)) return null;
+
+ if (GITHUB_CLI_TOOLS.has(toolName)) return normalizeGithubCliResult(params);
+
+ const tool = GITHUB_WORK_TOOLS[toolName];
+ if (!tool) return null;
+
+ const record = unwrapData(params.data);
+ if (!record) return null;
+
+ const base = buildParams(params, tool, record);
+ // `owner/repo#number` is the canonical github Work identity — the CLI
+ // surface never returns node_id, so REST-shaped results must dedupe against
+ // CLI-created rows through the same key. Unidentifiable results are skipped.
+ if (!base.identifier) return null;
+
+ return { params: { ...base, resourceId: base.identifier }, type: 'register' };
+};
diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.ts
new file mode 100644
index 00000000000..e71bc8846e8
--- /dev/null
+++ b/packages/database/src/models/work/index.ts
@@ -0,0 +1,102 @@
+import {
+ type DeleteDocumentWorkParams,
+ type DeleteTaskWorkParams,
+ isWorkSkillProvider,
+ type RegisterDocumentWorkParams,
+ type RegisterExternalWorkParams,
+ type RegisterSkillToolResultWorkParams,
+ type RegisterTaskWorkParams,
+ type SkillToolResultWorkInput,
+ type WorkItem,
+ type WorkSkillProvider,
+} from '@lobechat/types';
+
+import type { LobeChatDatabase } from '../../type';
+import type { WorkContext } from './context';
+import { registerDocumentWork } from './document';
+import { registerExternalWork } from './external';
+import { normalizeGithubToolResult } from './githubToolResult';
+import { normalizeLinearToolResult } from './linearToolResult';
+import * as queries from './queries';
+import { registerTaskWork } from './task';
+import type { ExternalToolWorkOperation } from './toolResultParsing';
+import * as writes from './writes';
+
+/**
+ * Skill provider → tool-result normalizer. Keyed by `WorkSkillProvider`, so the
+ * `satisfies` turns a provider added to `WORK_SKILL_PROVIDERS` without a
+ * normalizer here into a compile error. Adding a provider = extend
+ * `WORK_SKILL_PROVIDERS` + `WORK_PROVIDER_RESOURCE_TYPES` + one entry here.
+ */
+const SKILL_TOOL_RESULT_NORMALIZERS = {
+ github: normalizeGithubToolResult,
+ linear: normalizeLinearToolResult,
+} satisfies Record<
+ WorkSkillProvider,
+ (input: SkillToolResultWorkInput) => ExternalToolWorkOperation | null
+>;
+
+/**
+ * Facade over the per-type Work modules. Holds the `WorkContext` (db + owner
+ * scope) and delegates each public method to a free function in the matching
+ * module, keeping the polymorphic Work registry logic split by provider type
+ * without changing the public API surface.
+ */
+export class WorkModel {
+ private readonly ctx: WorkContext;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.ctx = { db, userId, workspaceId };
+ }
+
+ registerTask = (params: RegisterTaskWorkParams): Promise<WorkItem | null> =>
+ registerTaskWork(this.ctx, params);
+
+ registerDocument = (params: RegisterDocumentWorkParams): Promise<WorkItem | null> =>
+ registerDocumentWork(this.ctx, params);
+
+ registerExternal = (params: RegisterExternalWorkParams): Promise<WorkItem | null> =>
+ registerExternalWork(this.ctx, params);
+
+ handleSkillToolResult = async (
+ params: RegisterSkillToolResultWorkParams,
+ ): Promise<WorkItem | null> => {
+ const { provider, ...rest } = params;
+ if (!isWorkSkillProvider(provider)) return null;
+
+ const operation = SKILL_TOOL_RESULT_NORMALIZERS[provider](rest);
+ if (!operation) return null;
+
+ // The skill provider is the producing tool identifier (github / linear);
+ // the DB layer stamps it here rather than plumbing it through transports.
+ return this.registerExternal({ ...operation.params, toolIdentifier: provider });
+ };
+
+ deleteDocumentWork = (params: DeleteDocumentWorkParams): Promise<void> =>
+ writes.deleteDocumentWork(this.ctx, params);
+
+ deleteTaskWork = (params: DeleteTaskWorkParams): Promise<void> =>
+ writes.deleteTaskWork(this.ctx, params);
+
+ listByRootOperation = (params: { limit?: number; rootOperationId?: string | null }) =>
+ queries.listByRootOperation(this.ctx, params);
+
+ listByRootOperations = (params: { limit?: number; rootOperationIds?: string[] | null }) =>
+ queries.listByRootOperations(this.ctx, params);
+
+ listSummariesByRootOperations = (params: {
+ limit?: number;
+ rootOperationIds?: string[] | null;
+ }) => queries.listSummariesByRootOperations(this.ctx, params);
+
+ listByConversation = (params: {
+ limit?: number;
+ threadId?: string | null;
+ topicId?: string | null;
+ }) => queries.listByConversation(this.ctx, params);
+
+ listByWorkspace = (params: queries.ListByWorkspaceParams) =>
+ queries.listByWorkspace(this.ctx, params);
+
+ listVersions = (workId: string) => queries.listVersions(this.ctx, workId);
+}
diff --git a/packages/database/src/models/work/internal.ts b/packages/database/src/models/work/internal.ts
new file mode 100644
index 00000000000..baaea741ee6
--- /dev/null
+++ b/packages/database/src/models/work/internal.ts
@@ -0,0 +1,294 @@
+import type {
+ RegisterTaskWorkParams,
+ TaskWorkListItem,
+ TaskWorkSummaryItem,
+ WorkDisplayField,
+ WorkListBaseItem,
+ WorkListItem,
+ WorkSummaryItem,
+ WorkVersionEventItem,
+ WorkVersionPreview,
+} from '@lobechat/types';
+import type { SQL } from 'drizzle-orm';
+import { and, desc, eq, sql } from 'drizzle-orm';
+import { alias } from 'drizzle-orm/pg-core';
+
+import { tasks } from '../../schemas/task';
+import { works, workVersions } from '../../schemas/work';
+import { taskOwnership, type WorkContext, workOwnership } from './context';
+
+/**
+ * Alias used when a current-Work query joins the immutable Version selected by
+ * `works.currentVersionId` to expose version metadata without another lookup.
+ */
+export const currentVersions = alias(workVersions, 'current_work_versions');
+
+/**
+ * Write-time cap for the card-preview `description` column (message list,
+ * sidebar summary, workspace gallery). The full body lives in the immutable
+ * version snapshot (external Works, capped at {@link WORK_CONTENT_MAX_LENGTH})
+ * or on the owning table (documents); list/summary projections deliberately
+ * omit `content` and carry only the `description` preview. Single source of
+ * truth, also consumed by the provider normalizers.
+ */
+export const WORK_DESCRIPTION_PREVIEW_LENGTH = 120;
+
+/**
+ * Write-time cap for the full-text `content` column (layer 3 of the display
+ * trio). Anchored to GitHub's 65 536-char issue-body limit; without a cap an
+ * agent-generated multi-MB body would land in a version row. Card-facing
+ * queries exclude this column and fetch only the bounded preview.
+ */
+export const WORK_CONTENT_MAX_LENGTH = 65_536;
+
+/** Cap the full-text `content` column; no whitespace collapsing (it IS the full text). */
+export const truncateContentText = (value: string | null | undefined): string | null => {
+ if (!value) return null;
+
+ return value.length > WORK_CONTENT_MAX_LENGTH
+ ? `${value.slice(0, WORK_CONTENT_MAX_LENGTH)}...`
+ : value;
+};
+
+/** Collapse whitespace and cap length for card-facing Work text fields. */
+export const truncateSummaryText = (value: string | null | undefined): string | null => {
+ const normalized = value?.replaceAll(/\s+/g, ' ').trim();
+ if (!normalized) return null;
+
+ return normalized.length > WORK_DESCRIPTION_PREVIEW_LENGTH
+ ? `${normalized.slice(0, WORK_DESCRIPTION_PREVIEW_LENGTH)}...`
+ : normalized;
+};
+
+/** Provenance fields shared by all four Register*WorkParams shapes. */
+export type WorkVersionEventParams = Pick<
+ RegisterTaskWorkParams,
+ | 'agentId'
+ | 'cumulativeCost'
+ | 'cumulativeUsage'
+ | 'changeType'
+ | 'messageId'
+ | 'rootOperationId'
+ | 'threadId'
+ | 'toolCallId'
+ | 'toolIdentifier'
+ | 'toolName'
+ | 'topicId'
+>;
+
+/** The display fields captured by an immutable Work version snapshot. */
+export interface WorkDisplayColumns {
+ content?: string | null;
+ description?: string | null;
+ identifier?: string | null;
+ status?: string | null;
+ title?: string | null;
+ url?: string | null;
+}
+
+/** Provider-specific inputs for one work-version insert attempt. */
+export interface CreateVersionInput {
+ /**
+ * Display fields used to build the next immutable snapshot under the Work row
+ * lock. When `patchFields` is set, unnamed fields inherit from the current
+ * version; otherwise omitted fields become null (task/document carry complete
+ * data).
+ */
+ display: WorkDisplayColumns;
+ metadata?: (typeof workVersions.$inferInsert)['metadata'];
+ patchFields?: WorkDisplayField[];
+}
+
+/** Event-version columns embedded in list/summary rows (`WorkVersionPreview`). */
+export const versionEventSelection = {
+ createdAt: workVersions.createdAt,
+ cumulativeCost: workVersions.cumulativeCost,
+ id: workVersions.id,
+ metadata: workVersions.metadata,
+ changeType: workVersions.changeType,
+ messageId: workVersions.messageId,
+ rootOperationId: workVersions.rootOperationId,
+ toolCallId: workVersions.toolCallId,
+ toolName: workVersions.toolName,
+ version: workVersions.version,
+};
+
+/** Current-version event fields selected through the `currentVersions` alias. */
+export const currentVersionEventSelection = {
+ changeType: currentVersions.changeType,
+ createdAt: currentVersions.createdAt,
+ cumulativeCost: currentVersions.cumulativeCost,
+ id: currentVersions.id,
+ messageId: currentVersions.messageId,
+ metadata: currentVersions.metadata,
+ rootOperationId: currentVersions.rootOperationId,
+ toolCallId: currentVersions.toolCallId,
+ toolName: currentVersions.toolName,
+ version: currentVersions.version,
+};
+
+/** Stable Work columns shared by current-card and historical-event projections. */
+const workIdentityFields = {
+ createdAt: works.createdAt,
+ currentVersionId: works.currentVersionId,
+ id: works.id,
+ originAgentId: works.originAgentId,
+ originThreadId: works.originThreadId,
+ originTopicId: works.originTopicId,
+ resourceId: works.resourceId,
+ resourceType: works.resourceType,
+ toolIdentifier: works.toolIdentifier,
+ toolName: works.toolName,
+ type: works.type,
+ updatedAt: works.updatedAt,
+ url: works.url,
+ userId: works.userId,
+ visibility: works.visibility,
+ workspaceId: works.workspaceId,
+};
+
+/** Current-version card fields; full `content` remains intentionally excluded. */
+export const currentWorkListFields = {
+ ...workIdentityFields,
+ description: works.description,
+ identifier: works.identifier,
+ status: works.status,
+ title: works.title,
+};
+
+/** Historical event card fields sourced entirely from that event's version snapshot. */
+export const eventWorkListFields = {
+ ...workIdentityFields,
+ description: workVersions.description,
+ identifier: workVersions.identifier,
+ status: workVersions.status,
+ title: workVersions.title,
+ toolIdentifier: workVersions.toolIdentifier,
+ toolName: workVersions.toolName,
+ url: workVersions.url,
+};
+
+export interface TaskWorkSummaryQueryRow {
+ event: WorkVersionPreview;
+ /** Live-coalesced task columns; `deleted` flags a missing live row. */
+ task: TaskWorkListItem['task'] & { deleted: TaskWorkListItem['taskDeleted'] };
+ version: TaskWorkSummaryItem['version'];
+ work: WorkListBaseItem;
+}
+
+/**
+ * Work types whose list rows are fully described by the `works` display columns
+ * (unlike `task`, which additionally joins the live tasks table).
+ */
+export type DisplayWorkType = 'document' | 'external';
+
+/** Version-event row for display-backed types (each mutation event, no live join). */
+export interface DisplayVersionEventRow {
+ version: WorkVersionPreview;
+ work: WorkListBaseItem;
+}
+
+/**
+ * Current-card task projection. Live task columns take priority; a LEFT JOIN
+ * miss falls back to the Work's current-version cache/snapshot.
+ */
+export const currentTaskSummaryFields = {
+ task: {
+ deleted: sql<boolean>`${tasks.id} is null`,
+ identifier: sql<string | null>`coalesce(${tasks.identifier}, ${works.identifier})`,
+ instruction: sql<string | null>`coalesce(${tasks.instruction}, ${works.description})`,
+ name: sql<string | null>`coalesce(${tasks.name}, ${works.title})`,
+ priority: sql<number | null>`${tasks.priority}`,
+ status: sql<string | null>`coalesce(${tasks.status}, ${works.status})`,
+ },
+};
+
+/** Historical task-event projection with fallback to that event's immutable snapshot. */
+export const eventTaskSummaryFields = {
+ task: {
+ deleted: sql<boolean>`${tasks.id} is null`,
+ identifier: sql<string | null>`coalesce(${tasks.identifier}, ${workVersions.identifier})`,
+ instruction: sql<string | null>`coalesce(${tasks.instruction}, ${workVersions.description})`,
+ name: sql<string | null>`coalesce(${tasks.name}, ${workVersions.title})`,
+ priority: sql<number | null>`${tasks.priority}`,
+ status: sql<string | null>`coalesce(${tasks.status}, ${workVersions.status})`,
+ },
+};
+
+/**
+ * LEFT JOIN condition pairing a Work row to its live `tasks` row (task type
+ * only, owner-scoped). Callers use a LEFT JOIN (not INNER) so orphaned task
+ * Works — the task deleted without the tool path — still surface; deletion is
+ * then derived from the missing `tasks` row (see `taskSummaryColumns`).
+ */
+export const taskSummaryJoin = (ctx: WorkContext) =>
+ and(eq(works.resourceType, 'task'), eq(works.resourceId, tasks.id), taskOwnership(ctx));
+
+/**
+ * Shared version-event query for display-backed work types; `task` keeps its
+ * own variant because it additionally joins the tasks table.
+ */
+export const listDisplayVersionEventRows = (
+ ctx: WorkContext,
+ type: DisplayWorkType,
+ filters: SQL[],
+ limit: number,
+): Promise<DisplayVersionEventRow[]> =>
+ ctx.db
+ .select({
+ version: versionEventSelection,
+ work: eventWorkListFields,
+ })
+ .from(workVersions)
+ .innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))
+ .where(and(...filters, eq(works.type, type)))
+ .orderBy(desc(workVersions.createdAt))
+ .limit(limit);
+
+/**
+ * One current-version row surfaced by the conversation-scoped list query,
+ * paired with the mutation-event timestamp used for cross-type ordering.
+ */
+export interface WorkConversationRow {
+ eventCreatedAt: Date;
+ item: WorkListItem;
+}
+
+export interface WorkConversationRowParams {
+ rowLimit: number;
+ threadFilter: SQL;
+ topicId: string;
+}
+
+/**
+ * Workspace-wide list row shape shared by every type (one query, no per-type
+ * fan-out): the `works` display columns plus the coalesced task columns (nulled
+ * for non-task rows by the LEFT JOIN).
+ */
+export interface WorkspaceSummaryQueryRow {
+ event: WorkVersionPreview;
+ task: TaskWorkSummaryQueryRow['task'];
+ version: TaskWorkSummaryItem['version'];
+ work: WorkListBaseItem;
+}
+
+/**
+ * Per-type event-query and display-mapping strategy. Current summaries use one
+ * shared Work-first query; adding a Work type requires only its historical and
+ * conversation projections plus a mapping entry in `WORK_TYPE_ADAPTERS`.
+ */
+export interface WorkTypeAdapter {
+ /** Current-version rows for the conversation sidebar list. */
+ listConversationRows: (
+ ctx: WorkContext,
+ params: WorkConversationRowParams,
+ ) => Promise<WorkConversationRow[]>;
+ /** Version-event rows carrying each mutation event. */
+ listVersionEvents: (
+ ctx: WorkContext,
+ filters: SQL[],
+ limit: number,
+ ) => Promise<WorkVersionEventItem[]>;
+ /** Map one shared current-Work row onto this type's summary item. */
+ mapCurrentRow: (row: WorkspaceSummaryQueryRow, totalCost: number | null) => WorkSummaryItem;
+}
diff --git a/packages/database/src/models/work/linearToolResult.ts b/packages/database/src/models/work/linearToolResult.ts
new file mode 100644
index 00000000000..5fbaa2d6459
--- /dev/null
+++ b/packages/database/src/models/work/linearToolResult.ts
@@ -0,0 +1,267 @@
+import type {
+ LinearWorkResourceType,
+ RegisterExternalWorkParams,
+ SkillToolResultWorkInput,
+ WorkDisplayField,
+} from '@lobechat/types';
+
+import { WORK_DESCRIPTION_PREVIEW_LENGTH } from './internal';
+import {
+ type ExternalToolWorkOperation,
+ fromRecord,
+ hasOwn,
+ isApplicationError,
+ parseMaybeJSON,
+ sanitizeExternalUrl,
+ stringValue,
+ toRecord,
+} from './toolResultParsing';
+
+/** Linear entity vocabulary internal to this normalizer. */
+type LinearWorkEntityType = 'document' | 'issue';
+
+const LINEAR_CREATE_TOOLS = new Set(['create_document', 'save_document', 'save_issue']);
+const LINEAR_ISSUE_IDENTIFIER_PATTERN = /^[A-Z][A-Z0-9]+-\d+$/u;
+
+/** The card-preview `description` column stores capped text; the full body goes to `content`. */
+const previewText = (value: unknown): string | null => {
+ const text = stringValue(value);
+ if (!text) return null;
+
+ return text.length > WORK_DESCRIPTION_PREVIEW_LENGTH
+ ? `${text.slice(0, WORK_DESCRIPTION_PREVIEW_LENGTH)}...`
+ : text;
+};
+
+const firstDefined = <T>(...values: Array<T | null | undefined>): T | null | undefined =>
+ values.find((value) => value !== undefined);
+
+const optionalStringFromRecord = (
+ record: Record<string, unknown>,
+ keys: string[],
+): string | null | undefined => {
+ for (const key of keys) {
+ if (!hasOwn(record, key)) continue;
+
+ const raw = record[key];
+ if (raw === null) return null;
+
+ const value = stringValue(raw);
+ if (value) return value;
+ if (typeof raw === 'string') return null;
+ }
+
+ return undefined;
+};
+
+const optionalTextFromRecord = (
+ record: Record<string, unknown>,
+ keys: string[],
+): string | null | undefined => {
+ for (const key of keys) {
+ if (!hasOwn(record, key)) continue;
+
+ const raw = record[key];
+ if (raw === null) return null;
+
+ const value = previewText(raw);
+ if (value) return value;
+ if (typeof raw === 'string') return null;
+ }
+
+ return undefined;
+};
+
+const optionalStringFromNestedRecord = (
+ record: Record<string, unknown>,
+ key: string,
+ keys: string[],
+): string | null | undefined => {
+ if (!hasOwn(record, key)) return undefined;
+ if (record[key] === null) return null;
+
+ const nested = toRecord(record[key]);
+ if (!nested) return undefined;
+
+ return optionalStringFromRecord(nested, keys) ?? null;
+};
+
+const nestedRecord = (record: Record<string, unknown>, keys: string[]) => {
+ for (const key of keys) {
+ const nested = toRecord(record[key]);
+ if (nested) return nested;
+ }
+
+ return record;
+};
+
+const unwrapData = (data: unknown, keys: string[]) => {
+ const parsed = parseMaybeJSON(data);
+ if (Array.isArray(parsed)) return toRecord(parsed[0]) ?? null;
+
+ const record = toRecord(parsed);
+ if (!record) return null;
+
+ return nestedRecord(record, keys);
+};
+
+const isIssueIdentifier = (value: string | null) =>
+ value ? LINEAR_ISSUE_IDENTIFIER_PATTERN.test(value) : false;
+
+const urlSegmentAfter = (url: string | null, segmentName: string) => {
+ if (!url) return null;
+
+ try {
+ const segments = new URL(url).pathname.split('/').filter(Boolean);
+ const index = segments.indexOf(segmentName);
+ return index >= 0 ? decodeURIComponent(segments[index + 1] ?? '') || null : null;
+ } catch {
+ return null;
+ }
+};
+
+const resolveResourceIdentifier = (params: {
+ entityType: LinearWorkEntityType;
+ id: string;
+ record: Record<string, unknown>;
+ url: string | null;
+}) => {
+ switch (params.entityType) {
+ case 'document': {
+ return (
+ fromRecord(params.record, ['slug']) ??
+ urlSegmentAfter(params.url, 'document') ??
+ fromRecord(params.record, ['slugId'])
+ );
+ }
+
+ case 'issue': {
+ return (
+ fromRecord(params.record, ['identifier', 'key']) ??
+ (isIssueIdentifier(params.id) ? params.id : null) ??
+ urlSegmentAfter(params.url, 'issue')
+ );
+ }
+ }
+};
+
+const linearResourceType = (entityType: LinearWorkEntityType): LinearWorkResourceType => {
+ switch (entityType) {
+ case 'document': {
+ return 'linear_document';
+ }
+ case 'issue': {
+ return 'linear_issue';
+ }
+ }
+};
+
+const contextParams = (
+ params: SkillToolResultWorkInput,
+): Pick<
+ RegisterExternalWorkParams,
+ | 'agentId'
+ | 'cumulativeCost'
+ | 'cumulativeUsage'
+ | 'messageId'
+ | 'rootOperationId'
+ | 'threadId'
+ | 'toolCallId'
+ | 'toolName'
+ | 'topicId'
+> => ({
+ agentId: params.agentId ?? null,
+ cumulativeCost: params.cumulativeCost ?? null,
+ cumulativeUsage: params.cumulativeUsage ?? null,
+ messageId: params.messageId ?? null,
+ rootOperationId: params.rootOperationId ?? null,
+ threadId: params.threadId ?? null,
+ toolCallId: params.toolCallId ?? null,
+ toolName: params.toolName,
+ topicId: params.topicId ?? null,
+});
+
+const createRegisterOperation = (
+ params: SkillToolResultWorkInput,
+ entityType: LinearWorkEntityType,
+ record: Record<string, unknown>,
+): ExternalToolWorkOperation | null => {
+ const id = fromRecord(record, ['id', 'uuid', 'identifier', 'slug', 'slugId']);
+ if (!id) return null;
+
+ const url = fromRecord(record, ['url', 'appUrl']);
+ const identifier = resolveResourceIdentifier({ entityType, id, record, url });
+ const patchFields = new Set<WorkDisplayField>();
+ const patch = <T>(field: WorkDisplayField, value: T | null | undefined) => {
+ if (value !== undefined) patchFields.add(field);
+ return value;
+ };
+
+ if (identifier) patchFields.add('identifier');
+
+ return {
+ params: {
+ ...contextParams(params),
+ changeType:
+ LINEAR_CREATE_TOOLS.has(params.toolName) && !params.args?.id ? 'created' : 'updated',
+ // The FULL body (layer 3); the card preview is the capped `description` below.
+ content: patch(
+ 'content',
+ firstDefined(
+ optionalStringFromRecord(record, ['description']),
+ optionalStringFromRecord(record, ['content']),
+ ),
+ ),
+ // Documents carry their preview in `content`; issues in `description`.
+ description: patch(
+ 'description',
+ firstDefined(
+ optionalTextFromRecord(record, ['description']),
+ optionalTextFromRecord(record, ['content']),
+ ),
+ ),
+ identifier,
+ resourceId: id,
+ resourceType: linearResourceType(entityType),
+ status: patch(
+ 'status',
+ firstDefined(
+ optionalStringFromRecord(record, ['status', 'state', 'statusName', 'stateName']),
+ optionalStringFromNestedRecord(record, 'state', ['name', 'type']),
+ ),
+ ),
+ title: patch('title', optionalStringFromRecord(record, ['title', 'name', 'subject'])),
+ // Allowlist http(s) only: the persisted url reaches shell.openExternal on
+ // desktop, and a member could plant a `javascript:`/`file:` scheme here.
+ url: patch('url', sanitizeExternalUrl(optionalStringFromRecord(record, ['url', 'appUrl']))),
+ // Evaluated last: every patch() call above must run before the set is
+ // materialized (object literal properties evaluate in order).
+ patchFields: Array.from(patchFields),
+ },
+ type: 'register',
+ };
+};
+
+export const normalizeLinearToolResult = (
+ params: SkillToolResultWorkInput,
+): ExternalToolWorkOperation | null => {
+ if (isApplicationError(params.data)) return null;
+
+ switch (params.toolName) {
+ case 'save_issue': {
+ const issue = unwrapData(params.data, ['issue', 'data', 'result']);
+ return issue ? createRegisterOperation(params, 'issue', issue) : null;
+ }
+
+ case 'create_document':
+ case 'save_document':
+ case 'update_document': {
+ const document = unwrapData(params.data, ['document', 'data', 'result']);
+ return document ? createRegisterOperation(params, 'document', document) : null;
+ }
+
+ default: {
+ return null;
+ }
+ }
+};
diff --git a/packages/database/src/models/work/queries.ts b/packages/database/src/models/work/queries.ts
new file mode 100644
index 00000000000..26f64caed35
--- /dev/null
+++ b/packages/database/src/models/work/queries.ts
@@ -0,0 +1,350 @@
+import {
+ WORK_PROVIDER_RESOURCE_TYPES,
+ type WorkListBaseItem,
+ type WorkListItem,
+ type WorkSkillProvider,
+ type WorkSummaryItem,
+ type WorkSummaryMap,
+ type WorkType,
+ type WorkVersionEventItem,
+ type WorkVersionEventMap,
+ type WorkVersionItem,
+} from '@lobechat/types';
+import type { SQL } from 'drizzle-orm';
+import { and, desc, eq, inArray, isNull, lt, or } from 'drizzle-orm';
+
+import { tasks } from '../../schemas/task';
+import { topics } from '../../schemas/topic';
+import { works, workVersions } from '../../schemas/work';
+import { type WorkContext, workOwnership } from './context';
+import { getTotalCostByWorkIds } from './cost';
+import {
+ currentTaskSummaryFields,
+ currentVersionEventSelection,
+ currentVersions,
+ currentWorkListFields,
+ taskSummaryJoin,
+} from './internal';
+import { WORK_TYPE_ADAPTERS, workTypeAdapters } from './registry';
+
+/**
+ * Conversation queries still fan out once per registered Work type, then
+ * merge and dedupe the event rows in memory.
+ */
+const WORK_TYPE_COUNT = workTypeAdapters.length;
+/**
+ * Hard ceiling for batched root-operation queries. `rootOperationIds` length
+ * is caller-controlled (the tRPC schema caps only `limit`), so without a clamp
+ * a long conversation could inflate the ORDER-BY query and in-memory
+ * repartitioning far beyond the final capped result.
+ */
+const MAX_SUMMARY_ROW_LIMIT = 1000;
+
+export const listByRootOperation = async (
+ ctx: WorkContext,
+ params: {
+ limit?: number;
+ rootOperationId?: string | null;
+ },
+): Promise<WorkVersionEventItem[]> => {
+ if (!params.rootOperationId) return [];
+
+ const map = await listByRootOperations(ctx, {
+ limit: params.limit,
+ rootOperationIds: [params.rootOperationId],
+ });
+
+ return map[params.rootOperationId] ?? [];
+};
+
+export const listByRootOperations = async (
+ ctx: WorkContext,
+ params: {
+ limit?: number;
+ rootOperationIds?: string[] | null;
+ },
+): Promise<WorkVersionEventMap> => {
+ const rootOperationIds = Array.from(
+ new Set((params.rootOperationIds ?? []).filter((id): id is string => !!id)),
+ ).sort();
+ if (rootOperationIds.length === 0) return {};
+
+ const limit = params.limit ?? 20;
+ const result: WorkVersionEventMap = Object.fromEntries(
+ rootOperationIds.map((rootOperationId) => [rootOperationId, []]),
+ );
+ // One batched query per work type across all ids (instead of one per type
+ // per id); rows are re-partitioned per rootOperationId below. Each per-type
+ // query over-fetches up to `limit` rows per id, clamped like the sibling
+ // listSummariesByRootOperations.
+ const filters = [inArray(workVersions.rootOperationId, rootOperationIds)];
+ const rowLimit = Math.min(rootOperationIds.length * limit, MAX_SUMMARY_ROW_LIMIT);
+ const itemsByType = await Promise.all(
+ workTypeAdapters.map((adapter) => adapter.listVersionEvents(ctx, filters, rowLimit)),
+ );
+
+ const items = itemsByType
+ .flat()
+ .sort((a, b) => b.version.createdAt.getTime() - a.version.createdAt.getTime());
+
+ for (const item of items) {
+ const rootOperationId = item.version.rootOperationId;
+ if (!rootOperationId || !(rootOperationId in result)) continue;
+ if (result[rootOperationId].length >= limit) continue;
+ result[rootOperationId].push(item);
+ }
+
+ return result;
+};
+
+export const listSummariesByRootOperations = async (
+ ctx: WorkContext,
+ params: {
+ limit?: number;
+ rootOperationIds?: string[] | null;
+ },
+): Promise<WorkSummaryMap> => {
+ const rootOperationIds = Array.from(
+ new Set((params.rootOperationIds ?? []).filter((id): id is string => !!id)),
+ ).sort();
+ const result: WorkSummaryMap = Object.fromEntries(
+ rootOperationIds.map((rootOperationId) => [rootOperationId, []]),
+ );
+ if (rootOperationIds.length === 0) return result;
+
+ const limit = params.limit ?? 20;
+ const rowLimit = Math.min(rootOperationIds.length * limit, MAX_SUMMARY_ROW_LIMIT);
+
+ // Anchor each Work to the LATEST version event among the requested operations
+ // (latest-wins within the caller's anchor set — typically one conversation's
+ // operations). An edit made in another conversation's operation is outside
+ // this set, so it never steals the card from this conversation's summaries.
+ const eventRows = await ctx.db
+ .select({
+ createdAt: workVersions.createdAt,
+ rootOperationId: workVersions.rootOperationId,
+ workId: workVersions.workId,
+ })
+ .from(workVersions)
+ .innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))
+ .where(inArray(workVersions.rootOperationId, rootOperationIds))
+ .orderBy(desc(workVersions.createdAt))
+ .limit(rowLimit);
+
+ const anchorByWorkId = new Map<string, string>();
+ for (const row of eventRows) {
+ if (!row.rootOperationId) continue;
+ if (!anchorByWorkId.has(row.workId)) anchorByWorkId.set(row.workId, row.rootOperationId);
+ }
+ if (anchorByWorkId.size === 0) return result;
+
+ const rows = await ctx.db
+ .select({
+ event: currentVersionEventSelection,
+ ...currentTaskSummaryFields,
+ version: {
+ createdAt: currentVersions.createdAt,
+ id: currentVersions.id,
+ version: currentVersions.version,
+ },
+ work: currentWorkListFields,
+ })
+ .from(works)
+ .innerJoin(currentVersions, eq(works.currentVersionId, currentVersions.id))
+ .leftJoin(tasks, taskSummaryJoin(ctx))
+ .where(and(workOwnership(ctx), inArray(works.id, Array.from(anchorByWorkId.keys()))))
+ .orderBy(desc(works.updatedAt), desc(works.id));
+
+ const costByWorkId = await getTotalCostByWorkIds(
+ ctx,
+ rows.map((row) => row.work.id),
+ );
+
+ const summaries = rows.map((row) =>
+ WORK_TYPE_ADAPTERS[row.work.type].mapCurrentRow(row, costByWorkId.get(row.work.id) ?? null),
+ );
+
+ for (const summary of summaries) {
+ const rootOperationId = anchorByWorkId.get(summary.id);
+ if (!rootOperationId || !(rootOperationId in result)) continue;
+ if (result[rootOperationId].length >= limit) continue;
+ result[rootOperationId].push(summary);
+ }
+
+ return result;
+};
+
+export const listByConversation = async (
+ ctx: WorkContext,
+ params: {
+ limit?: number;
+ threadId?: string | null;
+ topicId?: string | null;
+ },
+): Promise<WorkListItem[]> => {
+ if (!params.topicId) return [];
+
+ const limit = params.limit ?? 50;
+ const threadFilter = params.threadId
+ ? eq(workVersions.threadId, params.threadId)
+ : isNull(workVersions.threadId);
+
+ const rowsByType = await Promise.all(
+ workTypeAdapters.map((adapter) =>
+ adapter.listConversationRows(ctx, {
+ rowLimit: limit * WORK_TYPE_COUNT,
+ threadFilter,
+ topicId: params.topicId!,
+ }),
+ ),
+ );
+
+ const rows = rowsByType
+ .flat()
+ .sort((a, b) => b.eventCreatedAt.getTime() - a.eventCreatedAt.getTime());
+
+ const seen = new Set<string>();
+ const items: WorkListItem[] = [];
+ for (const row of rows) {
+ if (seen.has(row.item.id)) continue;
+ seen.add(row.item.id);
+ items.push(row.item);
+ if (items.length >= limit) break;
+ }
+
+ return items;
+};
+
+export const listVersions = async (
+ ctx: WorkContext,
+ workId: string,
+): Promise<WorkVersionItem[]> => {
+ const rows = await ctx.db
+ .select({ version: workVersions })
+ .from(workVersions)
+ .innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))
+ .where(eq(workVersions.workId, workId))
+ .orderBy(desc(workVersions.version));
+
+ return rows.map((row) => row.version);
+};
+
+/** Default page size for the workspace-wide Work list. */
+const WORKSPACE_WORK_LIMIT = 30;
+
+export interface ListByWorkspaceParams {
+ cursor?: string | null;
+ limit?: number;
+ /** Narrow the `external` type to a single skill provider's resource types. */
+ provider?: WorkSkillProvider | null;
+ type?: WorkType | null;
+}
+
+// Not exported: only used as this module's own return-type annotation. The
+// service layer (`src/services/work.ts`) names its own `WorkSummaryPage` for
+// client consumption, mirroring how `VerifyReportSummaryPage` is named once,
+// at the service boundary, rather than duplicated from the db layer.
+interface WorkSummaryPage {
+ items: WorkSummaryItem[];
+ nextCursor: string | null;
+}
+
+/**
+ * Keyset cursor over the `(updatedAt, id)` order key. `updatedAt` alone is not
+ * unique (batch task creation stamps many rows in the same instant), so the id
+ * tie-breaker prevents rows from being skipped or duplicated across pages. The
+ * cursor stays opaque to callers: `<updatedAt ISO>|<work id>` (a work id never
+ * contains `|`, and neither does an ISO timestamp).
+ */
+const encodeWorkCursor = (work: Pick<WorkListBaseItem, 'id' | 'updatedAt'>): string =>
+ `${work.updatedAt.toISOString()}|${work.id}`;
+
+const decodeWorkCursor = (cursor: string): { id: string; updatedAt: Date } | null => {
+ const separator = cursor.indexOf('|');
+ if (separator === -1) return null;
+
+ const updatedAt = new Date(cursor.slice(0, separator));
+ const id = cursor.slice(separator + 1);
+ if (!id || Number.isNaN(updatedAt.getTime())) return null;
+
+ return { id, updatedAt };
+};
+
+/**
+ * Workspace-wide (cross-topic) Work list for the resource page's 产物 group.
+ * Unlike the conversation/root-operation queries, this pages off `works` as the
+ * primary table (not `work_versions` events), so `event`/`version` both reflect
+ * the Work's current version. `type` optionally narrows to one registry entry;
+ * omitting it powers the combined 全部 view. One query serves every type — the
+ * per-type differences live in each adapter's `mapCurrentRow`.
+ */
+export const listByWorkspace = async (
+ ctx: WorkContext,
+ params: ListByWorkspaceParams,
+): Promise<WorkSummaryPage> => {
+ const limit = params.limit ?? WORKSPACE_WORK_LIMIT;
+
+ const filters: SQL[] = [workOwnership(ctx)];
+ if (params.type) filters.push(eq(works.type, params.type));
+ // User-visible gallery tabs stay per-provider (Linear / GitHub) but filter by
+ // provider — its resource types — over the unified `external` Work type.
+ if (params.provider) {
+ filters.push(eq(works.type, 'external'));
+ // inArray needs a mutable array, so spread the readonly tuple.
+ filters.push(inArray(works.resourceType, [...WORK_PROVIDER_RESOURCE_TYPES[params.provider]]));
+ }
+
+ if (params.cursor) {
+ const decoded = decodeWorkCursor(params.cursor);
+ // desc(updatedAt), desc(id): the next page holds rows strictly "after" the
+ // cursor in that order — older updatedAt, or same updatedAt with a lower id.
+ if (decoded)
+ filters.push(
+ or(
+ lt(works.updatedAt, decoded.updatedAt),
+ and(eq(works.updatedAt, decoded.updatedAt), lt(works.id, decoded.id)),
+ )!,
+ );
+ }
+
+ const rows = await ctx.db
+ .select({
+ // Global view has no mutation event to anchor on, so the current version
+ // doubles as the surfacing event (mirrors the summary row shape).
+ event: currentVersionEventSelection,
+ ...currentTaskSummaryFields,
+ // Joined for the gallery's group-by-conversation headers; null once the
+ // origin topic is deleted (originTopicId is set-null on topic deletion).
+ originTopicTitle: topics.title,
+ version: {
+ createdAt: currentVersions.createdAt,
+ id: currentVersions.id,
+ version: currentVersions.version,
+ },
+ work: currentWorkListFields,
+ })
+ .from(works)
+ .innerJoin(currentVersions, eq(works.currentVersionId, currentVersions.id))
+ .leftJoin(tasks, taskSummaryJoin(ctx))
+ .leftJoin(topics, eq(works.originTopicId, topics.id))
+ .where(and(...filters))
+ .orderBy(desc(works.updatedAt), desc(works.id))
+ .limit(limit + 1);
+
+ const hasMore = rows.length > limit;
+ const pageRows = hasMore ? rows.slice(0, limit) : rows;
+
+ const costByWorkId = await getTotalCostByWorkIds(
+ ctx,
+ pageRows.map((row) => row.work.id),
+ );
+
+ // Attached after the per-type mapping so adapters stay unaware of the
+ // gallery-only topic join.
+ const items = pageRows.map((row) => ({
+ ...WORK_TYPE_ADAPTERS[row.work.type].mapCurrentRow(row, costByWorkId.get(row.work.id) ?? null),
+ originTopicTitle: row.originTopicTitle,
+ }));
+
+ return { items, nextCursor: hasMore ? encodeWorkCursor(pageRows.at(-1)!.work) : null };
+};
diff --git a/packages/database/src/models/work/registry.ts b/packages/database/src/models/work/registry.ts
new file mode 100644
index 00000000000..5e65692c041
--- /dev/null
+++ b/packages/database/src/models/work/registry.ts
@@ -0,0 +1,23 @@
+import type { WorkType } from '@lobechat/types';
+
+import { documentWorkAdapter } from './document';
+import { externalWorkAdapter } from './external';
+import type { WorkTypeAdapter } from './internal';
+import { taskWorkAdapter } from './task';
+
+/**
+ * The single registry for Work-type query and display strategies. Adding a
+ * Work type = adding one entry here (the `Record<WorkType, …>` constraint
+ * turns a missing entry into a compile error, not a silently missing result
+ * set) plus its type unions in `@lobechat/types`.
+ */
+export const WORK_TYPE_ADAPTERS = {
+ document: documentWorkAdapter,
+ external: externalWorkAdapter,
+ task: taskWorkAdapter,
+} satisfies Record<WorkType, WorkTypeAdapter>;
+
+export const WORK_TYPES = Object.keys(WORK_TYPE_ADAPTERS) as WorkType[];
+
+/** Type-erased adapter list for uniform iteration in the aggregate queries. */
+export const workTypeAdapters = Object.values(WORK_TYPE_ADAPTERS) as WorkTypeAdapter[];
diff --git a/packages/database/src/models/work/task.ts b/packages/database/src/models/work/task.ts
new file mode 100644
index 00000000000..9da5a9f4a6e
--- /dev/null
+++ b/packages/database/src/models/work/task.ts
@@ -0,0 +1,175 @@
+import type {
+ RegisterTaskWorkParams,
+ TaskItem,
+ TaskWorkListItem,
+ TaskWorkSummaryItem,
+} from '@lobechat/types';
+import type { SQL } from 'drizzle-orm';
+import { and, desc, eq, or } from 'drizzle-orm';
+
+import { tasks } from '../../schemas/task';
+import { works, workVersions } from '../../schemas/work';
+import { taskOwnership, type WorkContext, workOwnership } from './context';
+import {
+ currentTaskSummaryFields,
+ currentWorkListFields,
+ eventTaskSummaryFields,
+ eventWorkListFields,
+ taskSummaryJoin,
+ type TaskWorkSummaryQueryRow,
+ truncateSummaryText,
+ versionEventSelection,
+ type WorkDisplayColumns,
+ type WorkTypeAdapter,
+} from './internal';
+import { registerWorkVersion } from './writes';
+
+const normalizeTaskLookup = (value?: string) => {
+ const trimmed = value?.trim();
+ if (!trimmed) return undefined;
+ return trimmed.startsWith('task_') ? trimmed : trimmed.toUpperCase();
+};
+
+/**
+ * Task display fields captured by each immutable version. Live data stays on
+ * the `tasks` row (joined by every query); snapshots provide the deletion
+ * fallback when the backing task is later deleted.
+ */
+export const taskDisplayColumns = (task: TaskItem): WorkDisplayColumns => ({
+ content: task.instruction,
+ description: truncateSummaryText(task.instruction),
+ identifier: task.identifier,
+ status: task.status,
+ title: task.name,
+});
+
+const resolveTask = async (
+ ctx: WorkContext,
+ params: RegisterTaskWorkParams,
+): Promise<TaskItem | null> => {
+ const filters: SQL[] = [];
+ const taskId = normalizeTaskLookup(params.taskId);
+ const taskIdentifier = normalizeTaskLookup(params.taskIdentifier);
+
+ if (taskId) {
+ filters.push(taskId.startsWith('task_') ? eq(tasks.id, taskId) : eq(tasks.identifier, taskId));
+ }
+
+ if (taskIdentifier) {
+ filters.push(
+ taskIdentifier.startsWith('task_')
+ ? eq(tasks.id, taskIdentifier)
+ : eq(tasks.identifier, taskIdentifier),
+ );
+ }
+
+ if (filters.length === 0) return null;
+
+ const [task] = await ctx.db
+ .select()
+ .from(tasks)
+ .where(and(taskOwnership(ctx), filters.length === 1 ? filters[0] : or(...filters)))
+ .limit(1);
+
+ return task ?? null;
+};
+
+export const registerTaskWork = async (ctx: WorkContext, params: RegisterTaskWorkParams) => {
+ const task = await resolveTask(ctx, params);
+ if (!task) return null;
+
+ return registerWorkVersion(
+ ctx,
+ {
+ resourceId: task.id,
+ resourceType: 'task',
+ type: 'task',
+ userId: task.createdByUserId,
+ visibility: task.visibility,
+ },
+ params,
+ () => ({ display: taskDisplayColumns(task) }),
+ );
+};
+
+/** Card-facing task fields from a live-coalesced task projection. */
+const toTaskCardFields = (
+ task: TaskWorkSummaryQueryRow['task'],
+): Pick<TaskWorkListItem, 'task' | 'taskDeleted'> => ({
+ task: {
+ identifier: task.identifier,
+ instruction: truncateSummaryText(task.instruction),
+ name: task.name,
+ priority: task.priority,
+ status: task.status,
+ },
+ taskDeleted: task.deleted,
+});
+
+/**
+ * Task keeps bespoke adapter queries (unlike the snapshot factory types):
+ * every projection LEFT JOINs the live `tasks` row so cards render live
+ * name/status, falling back to the version snapshot only when the task row
+ * was deleted outside the tool path.
+ */
+export const taskWorkAdapter: WorkTypeAdapter = {
+ listConversationRows: async (ctx, params) => {
+ const rows = await ctx.db
+ .select({
+ eventCreatedAt: workVersions.createdAt,
+ ...currentTaskSummaryFields,
+ work: currentWorkListFields,
+ })
+ .from(workVersions)
+ .innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))
+ .leftJoin(tasks, taskSummaryJoin(ctx))
+ .where(
+ and(eq(workVersions.topicId, params.topicId), params.threadFilter, eq(works.type, 'task')),
+ )
+ .orderBy(desc(workVersions.createdAt), desc(works.updatedAt))
+ .limit(params.rowLimit);
+
+ return rows.map((row) => ({
+ eventCreatedAt: row.eventCreatedAt,
+ item: {
+ ...row.work,
+ ...toTaskCardFields(row.task),
+ resourceType: 'task' as const,
+ type: 'task' as const,
+ } satisfies TaskWorkListItem,
+ }));
+ },
+
+ listVersionEvents: async (ctx, filters, limit) => {
+ const rows = await ctx.db
+ .select({
+ ...eventTaskSummaryFields,
+ version: versionEventSelection,
+ work: eventWorkListFields,
+ })
+ .from(workVersions)
+ .innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))
+ .leftJoin(tasks, taskSummaryJoin(ctx))
+ .where(and(...filters, eq(works.type, 'task')))
+ .orderBy(desc(workVersions.createdAt))
+ .limit(limit);
+
+ return rows.map((row) => ({
+ ...row.work,
+ ...toTaskCardFields(row.task),
+ resourceType: 'task' as const,
+ type: 'task' as const,
+ version: row.version,
+ }));
+ },
+
+ mapCurrentRow: (row, totalCost): TaskWorkSummaryItem => ({
+ ...row.work,
+ ...toTaskCardFields(row.task),
+ event: row.event,
+ resourceType: 'task' as const,
+ totalCost,
+ type: 'task' as const,
+ version: row.version,
+ }),
+};
diff --git a/packages/database/src/models/work/toolResultParsing.ts b/packages/database/src/models/work/toolResultParsing.ts
new file mode 100644
index 00000000000..ec6a4e0fb20
--- /dev/null
+++ b/packages/database/src/models/work/toolResultParsing.ts
@@ -0,0 +1,86 @@
+import type { RegisterExternalWorkParams } from '@lobechat/types';
+import { toRecord } from '@lobechat/utils';
+
+/**
+ * Parsing primitives shared by the provider tool-result normalizers
+ * (githubToolResult.ts / linearToolResult.ts). Keep provider-specific
+ * variants (e.g. github's digit-string-aware numberValue) in their own files.
+ */
+
+export { toRecord };
+
+/**
+ * The single register operation every provider normalizer emits. Providers only
+ * differ in how they parse their tool result into `RegisterExternalWorkParams`;
+ * the resulting operation shape is unified.
+ */
+export interface ExternalToolWorkOperation {
+ params: Omit<RegisterExternalWorkParams, 'toolIdentifier'>;
+ type: 'register';
+}
+
+export const parseMaybeJSON = (value: unknown): unknown => {
+ if (typeof value !== 'string') return value;
+
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+};
+
+export const stringValue = (value: unknown): string | null => {
+ if (typeof value !== 'string') return null;
+
+ const trimmed = value.trim();
+ return trimmed || null;
+};
+
+export const hasOwn = (record: Record<string, unknown>, key: string) =>
+ Object.prototype.hasOwnProperty.call(record, key);
+
+export const fromRecord = (record: Record<string, unknown>, keys: string[]) => {
+ for (const key of keys) {
+ const value = stringValue(record[key]);
+ if (value) return value;
+ }
+
+ return null;
+};
+
+export const isApplicationError = (data: unknown) => {
+ const record = toRecord(parseMaybeJSON(data));
+ return record?.isError === true;
+};
+
+/**
+ * Allowlist an external Work URL to the `http`/`https` schemes before it is
+ * persisted into a Work snapshot.
+ *
+ * Work URLs are member-controlled free text: Linear results carry a `url` /
+ * `appUrl` field and GitHub URLs are parsed out of `gh` CLI stdout, so a
+ * workspace member can plant an arbitrary scheme (`javascript:`, `data:`,
+ * `file:`, custom protocols). Another member later clicking that Work card in
+ * the desktop (Electron) app hits `window.open` → `shell.openExternal`, which
+ * would turn the stored string into script execution or local-file access.
+ * Rejecting non-http(s) URLs here is the authoritative write-time boundary;
+ * render-time guards add defense in depth.
+ *
+ * @returns the trimmed URL when it parses via `new URL()` and uses the
+ * `http:`/`https:` protocol, otherwise `undefined` (so the caller skips it).
+ */
+export const sanitizeExternalUrl = (value: unknown): string | undefined => {
+ if (typeof value !== 'string') return undefined;
+
+ const trimmed = value.trim();
+ if (!trimmed) return undefined;
+
+ try {
+ const { protocol } = new URL(trimmed);
+ if (protocol === 'http:' || protocol === 'https:') return trimmed;
+ } catch {
+ return undefined;
+ }
+
+ return undefined;
+};
diff --git a/packages/database/src/models/work/writes.ts b/packages/database/src/models/work/writes.ts
new file mode 100644
index 00000000000..091eb288719
--- /dev/null
+++ b/packages/database/src/models/work/writes.ts
@@ -0,0 +1,316 @@
+import type {
+ DeleteDocumentWorkParams,
+ DeleteTaskWorkParams,
+ WorkDisplayField,
+ WorkItem,
+ WorkResourceType,
+ WorkType,
+ WorkVisibility,
+} from '@lobechat/types';
+import { and, eq, sql } from 'drizzle-orm';
+
+import { documents } from '../../schemas/file';
+import { works, workVersions } from '../../schemas/work';
+import type { LobeChatDatabase } from '../../type';
+import { documentOwnership, type WorkContext, workOwnership } from './context';
+import {
+ type CreateVersionInput,
+ truncateContentText,
+ type WorkDisplayColumns,
+ type WorkVersionEventParams,
+} from './internal';
+
+const MAX_VERSION_CREATE_RETRIES = 5;
+
+/** Every display column, written when a registration carries complete data. */
+const ALL_DISPLAY_FIELDS: WorkDisplayField[] = [
+ 'content',
+ 'description',
+ 'identifier',
+ 'status',
+ 'title',
+ 'url',
+];
+
+type WorkVersionSnapshot = Record<WorkDisplayField, string | null>;
+
+const EMPTY_VERSION_SNAPSHOT: WorkVersionSnapshot = {
+ content: null,
+ description: null,
+ identifier: null,
+ status: null,
+ title: null,
+ url: null,
+};
+
+const versionSnapshotSelection = {
+ content: workVersions.content,
+ description: workVersions.description,
+ identifier: workVersions.identifier,
+ status: workVersions.status,
+ title: workVersions.title,
+ url: workVersions.url,
+};
+
+const isUniqueViolation = (error: unknown) => {
+ const message = error instanceof Error ? error.message : String(error);
+ const code =
+ typeof error === 'object' && error && 'code' in error
+ ? String((error as { code?: unknown }).code)
+ : '';
+ const cause = error instanceof Error ? error.cause : undefined;
+ const causeCode =
+ typeof cause === 'object' && cause && 'code' in cause
+ ? String((cause as { code?: unknown }).code)
+ : '';
+
+ return (
+ code === '23505' ||
+ causeCode === '23505' ||
+ message.includes('23505') ||
+ message.includes('duplicate') ||
+ message.includes('unique')
+ );
+};
+
+const findVersionByToolCall = async (
+ ctx: WorkContext,
+ workId: string,
+ toolCallId?: string | null,
+) => {
+ if (!toolCallId) return null;
+
+ const [version] = await ctx.db
+ .select()
+ .from(workVersions)
+ .where(and(eq(workVersions.workId, workId), eq(workVersions.toolCallId, toolCallId)))
+ .limit(1);
+
+ return version ?? null;
+};
+
+interface RegisterWorkIdentity {
+ resourceId: string;
+ resourceType: WorkResourceType;
+ type: WorkType;
+ userId: string;
+ visibility: WorkVisibility;
+}
+
+/**
+ * Build the next complete immutable display snapshot. A partial registration
+ * starts from the locked Work's current version and replaces only named fields;
+ * a complete registration starts empty, so omitted fields become null.
+ */
+const buildVersionSnapshot = (
+ input: CreateVersionInput,
+ currentSnapshot?: WorkDisplayColumns,
+): WorkVersionSnapshot => {
+ const snapshot: WorkVersionSnapshot = input.patchFields
+ ? { ...EMPTY_VERSION_SNAPSHOT, ...currentSnapshot }
+ : { ...EMPTY_VERSION_SNAPSHOT };
+
+ const fields = input.patchFields ?? ALL_DISPLAY_FIELDS;
+ for (const field of fields) {
+ const value = input.display[field] ?? null;
+ // `content` is the only unbounded free-text field; cap it at the single
+ // choke point shared by every version-registration path.
+ snapshot[field] = field === 'content' ? truncateContentText(value) : value;
+ }
+
+ return snapshot;
+};
+
+/**
+ * Shared registration pipeline: find-or-create the Work identity, dedupe by
+ * toolCallId, allocate the next version number, insert the complete immutable
+ * snapshot, and update the Work's current projection in ONE transaction. Retry
+ * on unique-violation races (either the `(workId, version)` or the
+ * `(workId, toolCallId)` unique index).
+ *
+ * `buildInput` runs inside the transaction, after a `FOR UPDATE` lock on the
+ * works row (same pattern as `TopicModel.updateMetadata`): a concurrent
+ * registration holds that lock until its commit, so a partial update always
+ * merges against the actual latest snapshot. Without the lock, it could copy a
+ * stale snapshot into a cleanly allocated next version without triggering a
+ * uniqueness retry. Callers must do their reads through the tx-scoped context
+ * `buildInput` receives.
+ */
+export const registerWorkVersion = async (
+ ctx: WorkContext,
+ identity: RegisterWorkIdentity,
+ params: WorkVersionEventParams,
+ buildInput: (txCtx: WorkContext) => CreateVersionInput | Promise<CreateVersionInput>,
+): Promise<WorkItem> => {
+ for (let attempt = 0; attempt < MAX_VERSION_CREATE_RETRIES; attempt += 1) {
+ try {
+ return await ctx.db.transaction(async (tx) => {
+ const txCtx: WorkContext = { ...ctx, db: tx as LobeChatDatabase };
+
+ // Bare ON CONFLICT handles either owner-scope partial unique index. A
+ // conflict performs no UPDATE, so an idempotent replay cannot bump
+ // updatedAt before its toolCallId is checked under the Work row lock.
+ const [inserted] = await tx
+ .insert(works)
+ .values({
+ ...identity,
+ // Origin provenance is stamped ONLY here: it records where the Work
+ // identity was first registered and stays immutable through every
+ // later version (the current-projection UPDATE below never touches it).
+ originAgentId: params.agentId ?? null,
+ originThreadId: params.threadId ?? null,
+ originTopicId: params.topicId ?? null,
+ toolIdentifier: params.toolIdentifier,
+ toolName: params.toolName,
+ workspaceId: ctx.workspaceId ?? null,
+ })
+ .onConflictDoNothing()
+ .returning();
+
+ const [resolved] = inserted
+ ? [inserted]
+ : await tx
+ .select()
+ .from(works)
+ .where(
+ and(
+ workOwnership(txCtx),
+ eq(works.resourceType, identity.resourceType),
+ eq(works.resourceId, identity.resourceId),
+ ),
+ )
+ .limit(1);
+ if (!resolved) throw new Error(`Failed to resolve ${identity.type} Work identity`);
+
+ const [locked] = await tx
+ .select()
+ .from(works)
+ .where(and(eq(works.id, resolved.id), workOwnership(txCtx)))
+ .for('update');
+ if (!locked) throw new Error(`Work ${resolved.id} no longer exists`);
+
+ const dedupedUnderLock = await findVersionByToolCall(txCtx, locked.id, params.toolCallId);
+ if (dedupedUnderLock) return locked;
+
+ const input = await buildInput(txCtx);
+ const [currentSnapshot] = locked.currentVersionId
+ ? await tx
+ .select(versionSnapshotSelection)
+ .from(workVersions)
+ .where(
+ and(
+ eq(workVersions.id, locked.currentVersionId),
+ eq(workVersions.workId, locked.id),
+ ),
+ )
+ .limit(1)
+ : [];
+ const snapshot = buildVersionSnapshot(input, currentSnapshot);
+
+ const now = new Date();
+ const [next] = await tx
+ .select({
+ version: sql<number>`COALESCE(MAX(${workVersions.version}), 0) + 1`,
+ })
+ .from(workVersions)
+ .where(eq(workVersions.workId, locked.id));
+
+ const [version] = await tx
+ .insert(workVersions)
+ .values({
+ agentId: params.agentId ?? null,
+ content: snapshot.content,
+ // Written once at insert time: the agent runtime resolves the tool
+ // call's cumulative cost only AFTER execution (in `accumulateTool`),
+ // then registers the Work — so cost lands with the row instead of a
+ // follow-up UPDATE. Null for non-agent paths (e.g. manual document
+ // edits) that carry no cost.
+ cumulativeCost: params.cumulativeCost ?? null,
+ cumulativeUsage: params.cumulativeUsage ?? null,
+ description: snapshot.description,
+ identifier: snapshot.identifier,
+ messageId: params.messageId ?? null,
+ metadata: input.metadata ?? null,
+ changeType: params.changeType,
+ rootOperationId: params.rootOperationId ?? null,
+ status: snapshot.status,
+ threadId: params.threadId ?? null,
+ title: snapshot.title,
+ topicId: params.topicId ?? null,
+ toolCallId: params.toolCallId ?? null,
+ toolIdentifier: params.toolIdentifier,
+ toolName: params.toolName,
+ url: snapshot.url,
+ version: Number(next.version),
+ workId: locked.id,
+ createdAt: now,
+ })
+ .returning();
+
+ const [updatedWork] = await tx
+ .update(works)
+ .set({
+ currentVersionId: version.id,
+ description: snapshot.description,
+ identifier: snapshot.identifier,
+ status: snapshot.status,
+ title: snapshot.title,
+ toolIdentifier: params.toolIdentifier,
+ toolName: params.toolName,
+ updatedAt: now,
+ url: snapshot.url,
+ userId: identity.userId,
+ visibility: identity.visibility,
+ })
+ .where(and(eq(works.id, locked.id), workOwnership(txCtx)))
+ .returning();
+ if (!updatedWork) throw new Error(`Work ${locked.id} no longer exists`);
+
+ return updatedWork;
+ });
+ } catch (error) {
+ if (!isUniqueViolation(error) || attempt === MAX_VERSION_CREATE_RETRIES - 1) throw error;
+ }
+ }
+
+ throw new Error(`Failed to register ${identity.type} Work version after max retries`);
+};
+
+export const deleteDocumentWork = async (
+ ctx: WorkContext,
+ params: DeleteDocumentWorkParams,
+): Promise<void> => {
+ const [doc] = await ctx.db
+ .select({ id: documents.id })
+ .from(documents)
+ .where(and(documentOwnership(ctx), eq(documents.id, params.documentId)))
+ .limit(1);
+ if (!doc) return;
+
+ await ctx.db
+ .delete(works)
+ .where(
+ and(workOwnership(ctx), eq(works.resourceType, 'document'), eq(works.resourceId, doc.id)),
+ );
+};
+
+/**
+ * Delete the task Work (and its versions via the `work_versions.workId`
+ * cascade) for a task the agent removed through the deleteTask tool.
+ *
+ * Unlike {@link deleteDocumentWork} this does NOT re-resolve the resource
+ * first: the task row is already gone by the time the tool-execution dispatch
+ * layer calls this, so we can only locate the Work by its polymorphic
+ * `resourceId` (= the task's internal id, captured into `result.state.taskId`
+ * before deletion). Ownership still scopes the delete to the caller.
+ */
+export const deleteTaskWork = async (
+ ctx: WorkContext,
+ params: DeleteTaskWorkParams,
+): Promise<void> => {
+ await ctx.db
+ .delete(works)
+ .where(
+ and(workOwnership(ctx), eq(works.resourceType, 'task'), eq(works.resourceId, params.taskId)),
+ );
+};
diff --git a/packages/database/src/schemas/work.ts b/packages/database/src/schemas/work.ts
index 8b292dac999..bb36add4f78 100644
--- a/packages/database/src/schemas/work.ts
+++ b/packages/database/src/schemas/work.ts
@@ -4,6 +4,7 @@ import type {
WorkVersionChangeType,
WorkVersionCumulativeUsage,
WorkVersionMetadata,
+ WorkVisibility,
} from '@lobechat/types';
import { isNotNull, isNull } from 'drizzle-orm';
import { index, integer, jsonb, pgTable, text, uniqueIndex, uuid } from 'drizzle-orm/pg-core';
@@ -85,18 +86,18 @@ export const works = pgTable(
}),
originAgentId: text('origin_agent_id').references(() => agents.id, { onDelete: 'set null' }),
+ /** Backing-resource owner for task/document Works; registrant for external Works. */
userId: text('user_id')
.references(() => users.id, { onDelete: 'cascade' })
.notNull(),
/** Null for personal Works; determines which resource unique index applies below. */
workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),
/**
- * Visibility within the owning workspace. Registration must explicitly
- * inherit this from the backing resource; external Works default to private
- * at the write boundary until a workspace-shared authorization is known.
+ * Visibility within the owning workspace. Registration mirrors task/document
+ * visibility; external Works stay private until a shared authorization source exists.
* Ignored in personal mode where the row is implicitly private to its owner.
*/
- visibility: text('visibility', { enum: ['private', 'public'] }).notNull(),
+ visibility: text('visibility').$type<WorkVisibility>().notNull(),
createdAt: createdAt(),
updatedAt: updatedAt(),
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index a94bde5aed1..3157627d0eb 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1579,6 +1579,18 @@ export default {
'workingPanel.resources.updatedAt': 'Updated {{time}}',
'workingPanel.resources.viewMode.list': 'List view',
'workingPanel.resources.viewMode.tree': 'Tree view',
+ 'workingPanel.works.totalCost': 'Total cost: {{cost}}',
+ 'workingPanel.works.versionCost': 'Version cost: {{cost}}',
+ 'workingPanel.works.empty': 'No works in this conversation yet',
+ 'workingPanel.works.emptyVersions': 'No versions yet',
+ 'workingPanel.works.error': 'Failed to load works',
+ 'workingPanel.works.changeType.created': 'Created',
+ 'workingPanel.works.changeType.updated': 'Updated',
+ 'workingPanel.works.taskDeleted': 'Task deleted',
+ 'workingPanel.works.title': 'Works',
+ 'workingPanel.works.versionError': 'Failed to load versions',
+ 'workingPanel.works.viewMode.history': 'Version history',
+ 'workingPanel.works.viewMode.summary': 'Summary cards',
'workingPanel.localFile.binary': 'Binary file — preview unavailable',
'workingPanel.localFile.close': 'Close',
'workingPanel.localFile.closeLeft': 'Close to the Left',
diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.ts
index cb5f9b462a1..3617b3f279f 100644
--- a/packages/locales/src/default/file.ts
+++ b/packages/locales/src/default/file.ts
@@ -271,6 +271,15 @@ export default {
'tab.websites': 'Websites',
'title': 'Resources',
'toggleLeftPanel': 'Show/Hide Left Panel',
+ 'work.empty.desc':
+ 'Works your agents produce — tasks, documents, Linear and GitHub items — will collect here.',
+ 'work.empty.title': 'No works yet',
+ 'work.group': 'Works',
+ 'work.loadError': 'Something went wrong while loading works.',
+ 'work.loadErrorTitle': 'Couldn’t load works',
+ 'work.loadMoreError': 'Failed to load more works.',
+ 'work.retry': 'Retry',
+ 'work.topicGroup.other': 'Other',
'uploadDock.body.collapse': 'Collapse',
'uploadDock.header.cancelAll': 'Cancel all',
'uploadDock.body.item.cancel': 'Cancel',
diff --git a/packages/trpc/package.json b/packages/trpc/package.json
index 28c30bc6b80..7b57547a996 100644
--- a/packages/trpc/package.json
+++ b/packages/trpc/package.json
@@ -30,6 +30,6 @@
"vite-tsconfig-paths": "^6.1.1"
},
"peerDependencies": {
- "next": "^16.3.0-preview.5"
+ "next": "^16.3.0-preview.6"
}
}
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index 4914684435f..d5ff08e9469 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -180,6 +180,11 @@ export const MessageTaskCallbackSchema = z.object({
topicId: z.string().optional(),
});
+export const MessageWorkMetadataSchema = z.object({
+ rootOperationId: z.string().min(1),
+ userMessageId: z.string().optional(),
+});
+
export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSchema).extend({
collapsed: z.boolean().optional(),
contextSelections: z.array(ContextSelectionSchema).optional(),
@@ -211,6 +216,7 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSche
// role='verify' card: which Agent Run (agent_operations.id) it renders.
verifyOperationId: z.string().optional(),
verifyRound: z.number().optional(),
+ work: MessageWorkMetadataSchema.optional(),
// @deprecated token usage moved to the top-level `usage` column. Still listed
// so zod doesn't strip `metadata.usage` from legacy writes during migration.
usage: ModelUsageSchema.optional(),
@@ -450,6 +456,17 @@ export interface MessageMetadata {
verifyOperationId?: string;
/** Display round number for the verify card (1-based; repair rounds are separate). */
verifyRound?: number;
+ /**
+ * Final assistant message marker for Work artifacts produced during one root
+ * operation. Work ownership stays on `work_versions.root_operation_id`; this
+ * metadata only tells refreshed chat history where to render the cards.
+ */
+ work?: MessageWorkMetadata;
+}
+
+export interface MessageWorkMetadata {
+ rootOperationId: string;
+ userMessageId?: string;
}
/**
diff --git a/packages/types/src/message/db/params.ts b/packages/types/src/message/db/params.ts
index df32e322f70..d04b86b31d3 100644
--- a/packages/types/src/message/db/params.ts
+++ b/packages/types/src/message/db/params.ts
@@ -28,6 +28,13 @@ export interface QueryMessageParams {
groupId?: string | null;
pageSize?: number;
sessionId?: string | null;
+ /**
+ * Skip the Work-summary assembly (`message.works`). Mid-stream refetches
+ * (tool_end / step_complete / step_start snapshots) set this so each tool
+ * round doesn't re-run the per-type Work queries — works settle on the
+ * initial page load and the terminal agent_runtime_end refetch instead.
+ */
+ skipWorks?: boolean;
threadId?: string | null;
topicId?: string | null;
}
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index 6e21f16d2a7..457aa6e1af1 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -1,5 +1,6 @@
import type { GroundingSearch } from '../../search';
import type { ThreadStatus } from '../../topic/thread';
+import type { WorkSummaryItem } from '../../work';
import type {
ChatImageItem,
ChatMessageError,
@@ -345,4 +346,12 @@ export interface UIChatMessage {
*/
usage?: ModelUsage;
videoList?: ChatVideoItem[];
+ /**
+ * Work summaries produced by this message's root operation, resolved
+ * server-side and attached by `metadata.work.rootOperationId`. Rides the
+ * message-list payload so the in-message Works chips and the sidebar's
+ * summary view read from one source instead of a separate work-summary
+ * fetch. Empty/omitted when the message produced no Work.
+ */
+ works?: WorkSummaryItem[];
}
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index c7cb3a08b57..548988e74da 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -132,6 +132,42 @@ export const ExtendedHumanInterventionConfigSchema = z.union([
z.object({ dynamic: DynamicInterventionConfigSchema }),
]);
+/**
+ * Lifecycle action a tool API performs on its Work resource. Drives the Work
+ * version `role` (`create`/`update` → `created`/`updated`) and, for `delete`,
+ * routes to the resource's delete path instead of a version upsert.
+ */
+export type PluginApiWorkAction = 'create' | 'delete' | 'update';
+
+/**
+ * The Work resource kind an API produces. Selects the framework-side identity
+ * extractor and the `WorkModel` register method used by the dispatch layer.
+ */
+export type PluginApiWorkResourceType = 'document' | 'task';
+
+/**
+ * Declarative Work-registration config on a builtin tool API.
+ *
+ * Presence of this field is the single source of truth for "this API produces a
+ * Work". The tool-execution dispatch layers (server `BuiltinToolsExecutor` /
+ * client `invokeExecutor`) read it after a successful call, extract the resource
+ * identity from the result/args, and register the Work version — so tools need
+ * zero imperative registration code.
+ *
+ * Like `humanIntervention`, this is framework-only config: the model tools
+ * schema conversion only reads `name`/`description`/`parameters`, so `work`
+ * never leaks into the LLM-facing tool spec.
+ */
+export interface PluginApiWorkConfig {
+ action: PluginApiWorkAction;
+ resourceType: PluginApiWorkResourceType;
+}
+
+export const PluginApiWorkConfigSchema = z.object({
+ action: z.enum(['create', 'update', 'delete']),
+ resourceType: z.enum(['document', 'task']),
+});
+
export interface LobeChatPluginApi {
/**
* Default execution timeout in milliseconds for this API.
@@ -173,6 +209,12 @@ export interface LobeChatPluginApi {
*/
renderDisplayControl?: RenderDisplayControl;
url?: string;
+ /**
+ * Declarative Work-registration config. When present, the tool-execution
+ * dispatch layer registers a Work version after this API succeeds — the tool
+ * itself needs no imperative registration code. See {@link PluginApiWorkConfig}.
+ */
+ work?: PluginApiWorkConfig;
}
export const LobeChatPluginApiSchema = z.object({
@@ -183,6 +225,7 @@ export const LobeChatPluginApiSchema = z.object({
parameters: z.record(z.string(), z.any()),
renderDisplayControl: RenderDisplayControlSchema.optional(),
url: z.string().optional(),
+ work: PluginApiWorkConfigSchema.optional(),
});
export interface BuiltinToolManifest {
@@ -526,6 +569,9 @@ export interface BuiltinToolContext {
*/
agentId?: string;
+ /** Assistant message that owns this tool call. */
+ anchorMessageId?: string;
+
/**
* The current page document ID when the conversation is scoped to an open editor
* Uses the underlying `documents.id`, not tool-specific association IDs
@@ -551,7 +597,9 @@ export interface BuiltinToolContext {
isSubAgent?: boolean;
/**
- * The tool message ID
+ * Tool execution context key. It is the tool message ID for locally persisted
+ * tool messages, but gateway execution can temporarily use the toolCallId
+ * before the server-side tool result message exists.
*/
messageId: string;
@@ -579,6 +627,11 @@ export interface BuiltinToolContext {
*/
registerAfterCompletion?: (callback: AfterCompletionCallback) => void;
+ /**
+ * Root AI runtime operation ID for aggregating artifacts produced by one run.
+ */
+ rootOperationId?: string;
+
/**
* Conversation scope captured when the operation was created
*/
@@ -614,11 +667,24 @@ export interface BuiltinToolContext {
*/
taskId?: string | null;
+ /**
+ * The current thread ID when operating inside a thread-scoped conversation.
+ */
+ threadId?: string | null;
+
/**
* The tool call ID from the assistant message.
*/
toolCallId?: string;
+ /**
+ * Explicit source tool message ID for provenance. Prefer this over `messageId`
+ * when persisting cross-domain records because gateway tool execution may use
+ * `messageId` as a client-side context key before the server creates the tool
+ * message row.
+ */
+ toolMessageId?: string;
+
/**
* The current topic ID (only available when operating within a topic)
* Used by tools that need to create messages or operations within a topic
diff --git a/packages/types/src/work.ts b/packages/types/src/work.ts
index 7cf7e6ed142..c307f96b5ed 100644
--- a/packages/types/src/work.ts
+++ b/packages/types/src/work.ts
@@ -1,11 +1,28 @@
+import type { TaskStatus } from './task';
+
export type WorkType = 'document' | 'external' | 'task';
export type LinearWorkResourceType = 'linear_document' | 'linear_issue';
export type GithubWorkResourceType = 'github_issue' | 'github_pull_request';
+/** Every resource type backed by the unified `external` Work type. */
export type ExternalWorkResourceType = GithubWorkResourceType | LinearWorkResourceType;
export type WorkResourceType = 'document' | ExternalWorkResourceType | 'task';
-
+export type WorkVisibility = 'private' | 'public';
+/**
+ * How a version changed the Work. Not derivable from `version === 1`: updating
+ * an external resource that was never registered before yields a v1 row with
+ * changeType='updated'.
+ */
export type WorkVersionChangeType = 'created' | 'updated';
+/**
+ * The display fields captured by every immutable Work version. A partial tool
+ * result (e.g. Linear `{ id, state }`) names only the fields it carries in
+ * `patchFields`; registration merges them with the current version before
+ * inserting the next complete snapshot.
+ */
+export type WorkDisplayField =
+ 'content' | 'description' | 'identifier' | 'status' | 'title' | 'url';
+
export interface WorkVersionMetadata {
agentDocumentId?: string;
}
@@ -15,3 +32,363 @@ export interface WorkVersionCumulativeUsage {
cost?: unknown;
usage?: unknown;
}
+
+export interface WorkItem {
+ createdAt: Date;
+ currentVersionId: string | null;
+ /** Denormalized current-version preview used by Work list queries. */
+ description: string | null;
+ id: string;
+ /** Denormalized current-version human reference. */
+ identifier: string | null;
+ /** Agent that first registered this Work; stamped once at creation, immutable. */
+ originAgentId: string | null;
+ /** Thread where this Work was first registered; stamped once at creation, immutable. */
+ originThreadId: string | null;
+ /** Topic where this Work was first registered; stamped once at creation, immutable. */
+ originTopicId: string | null;
+ resourceId: string | null;
+ resourceType: WorkResourceType;
+ /** Denormalized current-version resource status. */
+ status: string | null;
+ /** Denormalized current-version title used by Work list queries. */
+ title: string | null;
+ /** Tool/plugin identifier that produced the current version. */
+ toolIdentifier: string;
+ /** Concrete tool that produced the current version. */
+ toolName: string;
+ type: WorkType;
+ updatedAt: Date;
+ /** Denormalized current-version canonical open target. */
+ url: string | null;
+ userId: string;
+ /** Workspace visibility mirrored from the backing resource; external Works are private. */
+ visibility: WorkVisibility;
+ workspaceId: string | null;
+}
+
+/** Card/list payload shared by conversation history, message chips, and the workspace gallery. */
+export type WorkListBaseItem = WorkItem & {
+ /**
+ * Title of the origin topic, joined for grouping the workspace gallery by
+ * conversation. Populated only by the workspace list query; `null` when the
+ * origin topic was deleted (originTopicId is set-null) or never stamped.
+ */
+ originTopicTitle?: string | null;
+};
+
+export interface WorkVersionItem {
+ /** Agent that produced this version. */
+ agentId: string | null;
+ changeType: WorkVersionChangeType;
+ /** Full text captured by this version. Null for document Works. */
+ content: string | null;
+ createdAt: Date;
+ cumulativeCost: number | null;
+ cumulativeUsage: WorkVersionCumulativeUsage | null;
+ /** Short preview text captured by this version. */
+ description: string | null;
+ id: string;
+ /** Short human reference captured by this version. */
+ identifier: string | null;
+ /** Persisted tool-result message that triggered this version. */
+ messageId: string | null;
+ metadata: WorkVersionMetadata | null;
+ rootOperationId: string | null;
+ /** Resource status captured by this version. */
+ status: string | null;
+ threadId: string | null;
+ /** Display title captured by this version. */
+ title: string | null;
+ /** Runtime tool-call id used to deduplicate repeated registration. */
+ toolCallId: string | null;
+ /** Tool/plugin identifier that produced THIS version (per-mutation). */
+ toolIdentifier: string;
+ /** Concrete tool that produced this version, e.g. 'createTask'. */
+ toolName: string;
+ topicId: string | null;
+ /** Canonical http(s) open target captured by this version. */
+ url: string | null;
+ version: number;
+ workId: string;
+}
+
+/** Version fields embedded in Work list rows (the mutation event that surfaced the Work). */
+export type WorkVersionPreview = Pick<
+ WorkVersionItem,
+ | 'createdAt'
+ | 'cumulativeCost'
+ | 'id'
+ | 'metadata'
+ | 'changeType'
+ | 'rootOperationId'
+ | 'messageId'
+ | 'toolCallId'
+ | 'toolName'
+ | 'version'
+>;
+
+export interface TaskWorkListItem extends WorkListBaseItem {
+ resourceType: 'task';
+ task: {
+ /** Short reference (`TASK-1`), live-coalesced like the other fields; card display + open target. */
+ identifier: string | null;
+ /**
+ * Card preview text: the task's instruction (NOT NULL on live rows),
+ * truncated server-side — never the full text.
+ */
+ instruction: string | null;
+ name: string | null;
+ priority: number | null;
+ status: TaskStatus | string | null;
+ };
+ /**
+ * The live task row backing this Work no longer exists (deleted outside the
+ * tool-dispatch path, which deliberately orphans the Work). When true, the
+ * `task` fields fall back to the version snapshot and the UI renders the card
+ * as "task deleted". Derived from a `tasks` LEFT JOIN missing its row, not a
+ * persisted flag.
+ */
+ taskDeleted: boolean;
+ type: 'task';
+}
+
+export interface DocumentWorkListItem extends WorkListBaseItem {
+ resourceType: 'document';
+ type: 'document';
+}
+
+export interface ExternalWorkListItem extends WorkListBaseItem {
+ resourceType: ExternalWorkResourceType;
+ type: 'external';
+}
+
+export type WorkListItem = DocumentWorkListItem | ExternalWorkListItem | TaskWorkListItem;
+
+export interface TaskWorkVersionEventItem extends TaskWorkListItem {
+ version: WorkVersionPreview;
+}
+
+export interface DocumentWorkVersionEventItem extends DocumentWorkListItem {
+ version: WorkVersionPreview;
+}
+
+export interface ExternalWorkVersionEventItem extends ExternalWorkListItem {
+ version: WorkVersionPreview;
+}
+
+export type WorkVersionEventItem =
+ DocumentWorkVersionEventItem | ExternalWorkVersionEventItem | TaskWorkVersionEventItem;
+export type WorkVersionEventMap = Record<string, WorkVersionEventItem[]>;
+
+export interface TaskWorkSummaryItem extends TaskWorkListItem {
+ event: WorkVersionPreview;
+ totalCost: number | null;
+ version: Pick<WorkVersionItem, 'createdAt' | 'id' | 'version'> | null;
+}
+
+export interface DocumentWorkSummaryItem extends DocumentWorkListItem {
+ event: WorkVersionPreview;
+ totalCost: number | null;
+ version: Pick<WorkVersionItem, 'createdAt' | 'id' | 'version'> | null;
+}
+
+export interface ExternalWorkSummaryItem extends ExternalWorkListItem {
+ event: WorkVersionPreview;
+ totalCost: number | null;
+ version: Pick<WorkVersionItem, 'createdAt' | 'id' | 'version'> | null;
+}
+
+export type WorkSummaryItem =
+ DocumentWorkSummaryItem | ExternalWorkSummaryItem | TaskWorkSummaryItem;
+export type WorkSummaryMap = Record<string, WorkSummaryItem[]>;
+
+export interface RegisterDocumentWorkParams {
+ agentDocumentId?: string | null;
+ /** Agent that produced this version; also validates the agent-document binding when present. */
+ agentId?: string | null;
+ changeType: WorkVersionChangeType;
+ cumulativeCost?: number | null;
+ cumulativeUsage?: WorkVersionCumulativeUsage | null;
+ description?: string | null;
+ documentId: string;
+ messageId?: string | null;
+ rootOperationId?: string | null;
+ threadId?: string | null;
+ toolCallId?: string | null;
+ /** Tool/plugin identifier that produced this version. */
+ toolIdentifier: string;
+ toolName: string;
+ topicId?: string | null;
+}
+
+export interface DeleteDocumentWorkParams {
+ agentDocumentId?: string | null;
+ agentId?: string | null;
+ documentId: string;
+}
+
+export interface DeleteTaskWorkParams {
+ /** Internal task id (`works.resourceId` for `resourceType: 'task'`). */
+ taskId: string;
+}
+
+export interface RegisterExternalWorkParams {
+ agentId?: string | null;
+ changeType: WorkVersionChangeType;
+ /** Full body captured in the next version when named in `patchFields`. */
+ content?: string | null;
+ cumulativeCost?: number | null;
+ cumulativeUsage?: WorkVersionCumulativeUsage | null;
+ description?: string | null;
+ identifier?: string | null;
+ messageId?: string | null;
+ patchFields?: WorkDisplayField[];
+ /**
+ * Canonical resource identity (`owner/repo#number`, a linear id, …). Required:
+ * every normalizer resolves it before registering, so there is no partial
+ * `Omit<…, 'resourceId'>` intermediate shape.
+ */
+ resourceId: string;
+ resourceType: ExternalWorkResourceType;
+ rootOperationId?: string | null;
+ status?: string | null;
+ threadId?: string | null;
+ title?: string | null;
+ toolCallId?: string | null;
+ /** Tool/plugin identifier that produced this version. */
+ toolIdentifier: string;
+ toolName: string;
+ topicId?: string | null;
+ url?: string | null;
+}
+
+/**
+ * LobeHub Skill providers whose tool results are adapted into the Work
+ * registry. Single source of truth: it gates `handleSkillToolResult` (client
+ * executors + server BuiltinToolsExecutor), keys the DB normalizer registry
+ * (`SKILL_TOOL_RESULT_NORMALIZERS`), keys `WORK_PROVIDER_RESOURCE_TYPES`, and
+ * drives the WorkGallery provider list filters.
+ *
+ * Adding a provider = extend this list + `WORK_PROVIDER_RESOURCE_TYPES` below +
+ * add one normalizer in the DB registry.
+ */
+export const WORK_SKILL_PROVIDERS = ['github', 'linear'] as const;
+export type WorkSkillProvider = (typeof WORK_SKILL_PROVIDERS)[number];
+
+export const isWorkSkillProvider = (provider?: string | null): provider is WorkSkillProvider =>
+ !!provider && (WORK_SKILL_PROVIDERS as readonly string[]).includes(provider);
+
+/**
+ * The `external` resource types each skill provider owns. Single source of
+ * truth for the provider ⇄ resourceType relationship: the workspace list filter
+ * narrows by provider through this map, and `workProviderOfResourceType` derives
+ * the reverse lookup from it (never a second hand-written map).
+ */
+export const WORK_PROVIDER_RESOURCE_TYPES: Record<
+ WorkSkillProvider,
+ readonly ExternalWorkResourceType[]
+> = {
+ github: ['github_issue', 'github_pull_request'],
+ linear: ['linear_document', 'linear_issue'],
+};
+
+/** Reverse lookup of `WORK_PROVIDER_RESOURCE_TYPES`, built once at module scope. */
+const RESOURCE_TYPE_TO_PROVIDER = new Map<string, WorkSkillProvider>(
+ (
+ Object.entries(WORK_PROVIDER_RESOURCE_TYPES) as [WorkSkillProvider, readonly string[]][]
+ ).flatMap(([provider, resourceTypes]) =>
+ resourceTypes.map((resourceType) => [resourceType, provider]),
+ ),
+);
+
+/** Which skill provider owns an `external` resource type, or `undefined`. */
+export const workProviderOfResourceType = (resourceType: string): WorkSkillProvider | undefined =>
+ RESOURCE_TYPE_TO_PROVIDER.get(resourceType);
+
+export interface RegisterSkillToolResultWorkParams {
+ agentId?: string | null;
+ args?: Record<string, unknown>;
+ cumulativeCost?: number | null;
+ cumulativeUsage?: WorkVersionCumulativeUsage | null;
+ data?: unknown;
+ messageId?: string | null;
+ provider: string;
+ rootOperationId?: string | null;
+ threadId?: string | null;
+ toolCallId?: string | null;
+ toolName: string;
+ topicId?: string | null;
+}
+
+/** Provider-agnostic normalizer input: a skill tool result minus its provider tag. */
+export type SkillToolResultWorkInput = Omit<RegisterSkillToolResultWorkParams, 'provider'>;
+
+export interface RegisterTaskWorkParams {
+ agentId?: string | null;
+ changeType: WorkVersionChangeType;
+ cumulativeCost?: number | null;
+ cumulativeUsage?: WorkVersionCumulativeUsage | null;
+ messageId?: string | null;
+ rootOperationId?: string | null;
+ taskId?: string;
+ taskIdentifier?: string;
+ threadId?: string | null;
+ toolCallId?: string | null;
+ /** Tool/plugin identifier that produced this version. */
+ toolIdentifier: string;
+ toolName: string;
+ topicId?: string | null;
+}
+
+/** One resolved task Work target extracted from a tool result / args. */
+export interface WorkTaskTarget {
+ taskId?: string;
+ taskIdentifier?: string;
+}
+
+/**
+ * Registration intent emitted by the tool-execution layer (`BuiltinToolsExecutor`,
+ * document runtime) and consumed by the agent runtime (`callTool` /
+ * `callToolsBatch`) once the tool call's cumulative cost is known, so the Work
+ * version is inserted ONCE carrying its `cumulativeCost` instead of created
+ * cost-less and back-filled by a second UPDATE.
+ *
+ * Carries only the type-specific resource identity; the runtime supplies
+ * provenance (operation / message / tool-call ids, thread / topic, agent)
+ * and the cumulative usage snapshot at persist time. The `skill` variant also
+ * carries the tool's UNTRUNCATED result payload (`data`), because the runtime
+ * only ever sees the truncated `content` — the identity fields (issue/PR url,
+ * number, …) live exclusively in the raw payload.
+ */
+export type WorkRegistrationIntent =
+ | {
+ action: 'create' | 'update' | 'delete';
+ changeType?: WorkVersionChangeType;
+ targets: WorkTaskTarget[];
+ type: 'task';
+ }
+ | {
+ args?: Record<string, unknown>;
+ data: unknown;
+ provider: string;
+ toolName: string;
+ type: 'skill';
+ }
+ | {
+ action: 'register';
+ document: {
+ agentDocumentId?: string | null;
+ agentId?: string | null;
+ description?: string | null;
+ documentId: string;
+ changeType: WorkVersionChangeType;
+ toolName: string;
+ };
+ type: 'document';
+ }
+ | {
+ action: 'delete';
+ document: { agentDocumentId?: string | null; agentId?: string | null; documentId: string };
+ type: 'document';
+ };
diff --git a/src/features/Conversation/ChatItem/ChatItem.tsx b/src/features/Conversation/ChatItem/ChatItem.tsx
index 812719e35a6..68a0770ba73 100644
--- a/src/features/Conversation/ChatItem/ChatItem.tsx
+++ b/src/features/Conversation/ChatItem/ChatItem.tsx
@@ -19,6 +19,7 @@ const ChatItem = memo<ChatItemProps>(
onAvatarClick,
avatarProps,
customAvatarRender,
+ afterActions,
actions,
className,
loading,
@@ -122,6 +123,15 @@ const ChatItem = memo<ChatItemProps>(
<FollowUpChips conversationKey={conversationKey} messageId={id} />
)}
{actions && <Actions actions={actions} placement={placement} />}
+ {afterActions && (
+ <Flexbox
+ style={{
+ width: isUser ? undefined : '100%',
+ }}
+ >
+ {afterActions}
+ </Flexbox>
+ )}
</Flexbox>
);
},
diff --git a/src/features/Conversation/ChatItem/type.ts b/src/features/Conversation/ChatItem/type.ts
index 7d3cbdafe9f..b8c6455e2e1 100644
--- a/src/features/Conversation/ChatItem/type.ts
+++ b/src/features/Conversation/ChatItem/type.ts
@@ -6,6 +6,7 @@ export interface ChatItemProps extends Omit<FlexboxProps, 'children' | 'onChange
aboveMessage?: ReactNode;
actions?: ReactNode;
actionsWrapWidth?: number;
+ afterActions?: ReactNode;
avatar: MetaData;
avatarProps?: AvatarProps;
belowMessage?: ReactNode;
diff --git a/src/features/Conversation/Messages/Assistant/index.tsx b/src/features/Conversation/Messages/Assistant/index.tsx
index dea13ee3afa..54dd6f55578 100644
--- a/src/features/Conversation/Messages/Assistant/index.tsx
+++ b/src/features/Conversation/Messages/Assistant/index.tsx
@@ -19,6 +19,7 @@ import {
useSetMessageItemActionElementPortialContext,
useSetMessageItemActionTypeContext,
} from '../Contexts/message-action-context';
+import MessageWorks from '../MessageWorks';
import InterruptedHint from './components/InterruptedHint';
import MessageContent from './components/MessageContent';
import { AssistantMessageExtra } from './Extra';
@@ -97,11 +98,11 @@ const AssistantMessage = memo<AssistantMessageProps>(
avatar={avatar}
belowMessage={hasEmptyErrorMessage ? footerRender : undefined}
customErrorRender={(error) => <ErrorMessageExtra data={item} error={error} />}
+ error={errorContent && error ? errorContent : undefined}
editing={editing}
// ChatItem renders this as the primary block when the message is empty,
// or inside messageExtra (below the content) when the turn streamed
// content before erroring — so don't gate it on empty content.
- error={errorContent && error ? errorContent : undefined}
id={id}
loading={generating || isCreating}
message={message}
@@ -119,6 +120,11 @@ const AssistantMessage = memo<AssistantMessageProps>(
{!disableEditing && actionBarHolder}
</>
}
+ afterActions={
+ metadata?.work?.rootOperationId ? (
+ <MessageWorks rootOperationId={metadata.work.rootOperationId} />
+ ) : undefined
+ }
messageExtra={
<>
{interrupted && <InterruptedHint />}
diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsx
index b6ae7c45d26..2cefbc3e42f 100644
--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx
@@ -32,6 +32,7 @@ import {
messageStateSelectors,
useConversationStore,
} from '../../store';
+import { getOperationFinalRootId } from '../../store/slices/data/workSummaries';
import InterruptedHint from '../Assistant/components/InterruptedHint';
import Usage from '../components/Extras/Usage';
import MessageBranch from '../components/MessageBranch';
@@ -39,6 +40,7 @@ import {
useSetMessageItemActionElementPortialContext,
useSetMessageItemActionTypeContext,
} from '../Contexts/message-action-context';
+import MessageWorks from '../MessageWorks';
import SignalCallbacks from '../SignalCallbacks';
import FileListViewer from '../User/components/FileListViewer';
import Group from './components/Group';
@@ -54,6 +56,22 @@ const actionBarHolder = (
style={{ height: '28px' }}
/>
);
+
+const findLatestWorkRootOperationId = (
+ metadata?: { work?: { rootOperationId?: unknown } } | null,
+ children?: AssistantContentBlock[],
+ taskCompletions?: AssistantContentBlock[],
+) => {
+ const blocks = [...(children ?? []), ...(taskCompletions ?? [])];
+
+ for (let index = blocks.length - 1; index >= 0; index -= 1) {
+ const rootOperationId = getOperationFinalRootId(blocks[index]?.metadata);
+ if (rootOperationId) return rootOperationId;
+ }
+
+ return getOperationFinalRootId(metadata);
+};
+
interface GroupMessageProps {
defaultWorkflowExpandLevel?: WorkflowExpandLevelDefault;
disableEditing?: boolean;
@@ -101,6 +119,10 @@ const GroupMessage = memo<GroupMessageProps>(
if (!children || children.length === 0) return [];
return children.flatMap((child: AssistantContentBlock) => child.fileList || []);
}, [children]);
+ const workRootOperationId = useMemo(
+ () => findLatestWorkRootOperationId(metadata, children, taskCompletions),
+ [children, metadata, taskCompletions],
+ );
const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
const [toggleSystemRole] = useGlobalStore((s) => [s.toggleSystemRole]);
@@ -200,6 +222,9 @@ const GroupMessage = memo<GroupMessageProps>(
</>
)
}
+ afterActions={
+ workRootOperationId ? <MessageWorks rootOperationId={workRootOperationId} /> : undefined
+ }
customAvatarRender={
isSupervisor
? () => (
diff --git a/src/features/Conversation/Messages/MessageWorks/index.tsx b/src/features/Conversation/Messages/MessageWorks/index.tsx
new file mode 100644
index 00000000000..8abf5f1996e
--- /dev/null
+++ b/src/features/Conversation/Messages/MessageWorks/index.tsx
@@ -0,0 +1,46 @@
+'use client';
+
+import type { WorkSummaryItem } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { memo } from 'react';
+
+import WorkSummaryCard from '@/features/Work/WorkSummaryCard';
+
+import { dataSelectors, useConversationStore } from '../../store';
+
+const styles = createStaticStyles(({ css }) => ({
+ container: css`
+ width: 100%;
+ `,
+}));
+
+interface MessageWorksProps {
+ rootOperationId?: string | null;
+}
+
+const MessageWorks = memo<MessageWorksProps>(({ rootOperationId }) => {
+ // Works ride the message payload (attached server-side to each round's anchor
+ // message), so the chip reads its summaries straight from the store index —
+ // no dedicated work-summary fetch. The index is memoized per dbMessages
+ // snapshot, so it's built once regardless of how many chips mount.
+ const data: WorkSummaryItem[] = useConversationStore(
+ dataSelectors.workSummariesByRootOperationId(rootOperationId),
+ isEqual,
+ );
+
+ if (data.length === 0) return null;
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ {data.map((item) => (
+ <WorkSummaryCard item={item} key={item.id} />
+ ))}
+ </Flexbox>
+ );
+}, isEqual);
+
+MessageWorks.displayName = 'MessageWorks';
+
+export default MessageWorks;
diff --git a/src/features/Conversation/store/slices/data/selectors.ts b/src/features/Conversation/store/slices/data/selectors.ts
index ed95ce8bd62..45789191208 100644
--- a/src/features/Conversation/store/slices/data/selectors.ts
+++ b/src/features/Conversation/store/slices/data/selectors.ts
@@ -9,6 +9,7 @@ import { topicSelectors } from '@/store/chat/selectors';
import { type State } from '../../initialState';
import { getPendingInterventions } from './pendingInterventions';
+import { getWorkSummariesByRootOperationId } from './workSummaries';
const displayMessages = (s: State) => s.displayMessages;
const displayMessageIds = (s: State) => s.displayMessages.map((m) => m.id);
@@ -126,6 +127,12 @@ const currentTopicSummary = () => {
const pendingInterventions = (s: State) => getPendingInterventions(s.displayMessages);
+// Works ride the message payload (attached server-side to each round's anchor
+// message), so the in-message chips read from the raw `dbMessages` (keyed by the
+// display-resolved rootOperationId) instead of a dedicated work-summary fetch.
+const workSummariesByRootOperationId = (rootOperationId?: string | null) => (s: State) =>
+ getWorkSummariesByRootOperationId(s.dbMessages, rootOperationId);
+
const isSecondLastMessageFromUser = (s: State) => s.displayMessages.at(-2)?.role === 'user';
const toAssistantContentBlock = (message: UIChatMessage): AssistantContentBlock => ({
@@ -239,4 +246,5 @@ export const dataSelectors = {
messagesInit,
pendingInterventions,
skipFetch,
+ workSummariesByRootOperationId,
};
diff --git a/src/features/Conversation/store/slices/data/workSummaries.test.ts b/src/features/Conversation/store/slices/data/workSummaries.test.ts
new file mode 100644
index 00000000000..542093f7006
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/workSummaries.test.ts
@@ -0,0 +1,113 @@
+import type { UIChatMessage, WorkSummaryItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { getAllWorkSummaries, getWorkSummariesByRootOperationId } from './workSummaries';
+
+const summary = (
+ id: string,
+ rootOperationId: string,
+ createdAt: string,
+ extra?: Partial<WorkSummaryItem>,
+): WorkSummaryItem =>
+ ({
+ event: { createdAt: new Date(createdAt), rootOperationId } as any,
+ id,
+ ...extra,
+ }) as WorkSummaryItem;
+
+const message = (overrides: Partial<UIChatMessage>): UIChatMessage =>
+ ({ id: 'msg', role: 'assistant', ...overrides }) as UIChatMessage;
+
+describe('getWorkSummariesByRootOperationId', () => {
+ it('resolves works by the anchor message metadata stamp', () => {
+ const works = [summary('work-1', 'op-a', '2026-07-01T00:00:00.000Z')];
+ const messages = [
+ message({ id: 'm1', metadata: { work: { rootOperationId: 'op-a' } } as any, works }),
+ ];
+
+ expect(getWorkSummariesByRootOperationId(messages, 'op-a')).toEqual(works);
+ });
+
+ it('falls back to the work event rootOperationId when metadata is unstamped', () => {
+ const works = [summary('work-1', 'op-b', '2026-07-01T00:00:00.000Z')];
+ // No `metadata.work.rootOperationId` — the index must still key by the event.
+ const messages = [message({ id: 'm1', works })];
+
+ expect(getWorkSummariesByRootOperationId(messages, 'op-b')).toEqual(works);
+ });
+
+ it('returns an empty array for an unknown or nullish rootOperationId', () => {
+ const messages = [
+ message({
+ id: 'm1',
+ metadata: { work: { rootOperationId: 'op-a' } } as any,
+ works: [summary('work-1', 'op-a', '2026-07-01T00:00:00.000Z')],
+ }),
+ ];
+
+ expect(getWorkSummariesByRootOperationId(messages, 'op-missing')).toEqual([]);
+ expect(getWorkSummariesByRootOperationId(messages, null)).toEqual([]);
+ expect(getWorkSummariesByRootOperationId(messages, undefined)).toEqual([]);
+ });
+
+ it('memoizes the index per messages array identity', () => {
+ const messages = [
+ message({
+ id: 'm1',
+ metadata: { work: { rootOperationId: 'op-a' } } as any,
+ works: [summary('work-1', 'op-a', '2026-07-01T00:00:00.000Z')],
+ }),
+ ];
+
+ // Same reference in, same resolved array out (built once, cached).
+ expect(getWorkSummariesByRootOperationId(messages, 'op-a')).toBe(
+ getWorkSummariesByRootOperationId(messages, 'op-a'),
+ );
+ });
+});
+
+describe('getAllWorkSummaries', () => {
+ it('flattens every message, deduping to the latest event per work id', () => {
+ const older = summary('work-1', 'op-a', '2026-07-01T00:00:00.000Z');
+ const newer = summary('work-1', 'op-a', '2026-07-03T00:00:00.000Z');
+ const other = summary('work-2', 'op-b', '2026-07-02T00:00:00.000Z');
+ const messages = [
+ message({ id: 'm1', works: [older] }),
+ message({ id: 'm2', works: [newer, other] }),
+ ];
+
+ const result = getAllWorkSummaries(messages);
+
+ // work-1 collapses to its newest event; sorted newest-first.
+ expect(result.map((w) => w.id)).toEqual(['work-1', 'work-2']);
+ expect(result[0]).toBe(newer);
+ expect(result[1]).toBe(other);
+ });
+
+ it('returns an empty array when no message carries works', () => {
+ expect(getAllWorkSummaries([message({ id: 'm1' })])).toEqual([]);
+ });
+
+ it('memoizes per (messages identity, threadId) so an unchanged snapshot is not rebuilt', () => {
+ const messages = [
+ message({ id: 'm1', works: [summary('work-1', 'op-a', '2026-07-01T00:00:00.000Z')] }),
+ ];
+
+ // Same reference + same thread scope in -> same resolved array out (built once).
+ expect(getAllWorkSummaries(messages)).toBe(getAllWorkSummaries(messages));
+ // A different thread scope over the same array is a distinct cache entry.
+ expect(getAllWorkSummaries(messages, 't1')).not.toBe(getAllWorkSummaries(messages));
+ });
+
+ it('scopes to the requested thread (main thread excludes threaded messages)', () => {
+ const mainWork = summary('work-main', 'op-a', '2026-07-01T00:00:00.000Z');
+ const threadWork = summary('work-thread', 'op-b', '2026-07-02T00:00:00.000Z');
+ const messages = [
+ message({ id: 'm1', works: [mainWork] }),
+ message({ id: 'm2', threadId: 't1', works: [threadWork] } as Partial<UIChatMessage>),
+ ];
+
+ expect(getAllWorkSummaries(messages).map((w) => w.id)).toEqual(['work-main']);
+ expect(getAllWorkSummaries(messages, 't1').map((w) => w.id)).toEqual(['work-thread']);
+ });
+});
diff --git a/src/features/Conversation/store/slices/data/workSummaries.ts b/src/features/Conversation/store/slices/data/workSummaries.ts
new file mode 100644
index 00000000000..86b4f3af086
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/workSummaries.ts
@@ -0,0 +1,112 @@
+import type { UIChatMessage, WorkSummaryItem } from '@lobechat/types';
+
+/**
+ * Reads the operation-final work root id stamped on message/block metadata by
+ * the server work registry (`metadata.work.rootOperationId`). Consumed by the
+ * in-message Works chip resolution (`AssistantGroup`) and the work-summary index
+ * below.
+ */
+export const getOperationFinalRootId = (
+ metadata?: { work?: { rootOperationId?: unknown } } | null,
+) =>
+ typeof metadata?.work?.rootOperationId === 'string' ? metadata.work.rootOperationId : undefined;
+
+const toTime = (value: unknown): number => {
+ if (!value) return 0;
+ const time = value instanceof Date ? value.getTime() : new Date(value as string).getTime();
+ return Number.isNaN(time) ? 0 : time;
+};
+
+/**
+ * Build a `rootOperationId -> works` index from the raw db messages. The server
+ * attaches each round's Work summaries to its anchor message (keyed by
+ * `metadata.work.rootOperationId`), so a single flat pass over the raw rows
+ * reconstructs the lookup the in-message chips need — no dedicated fetch.
+ */
+const buildWorkSummaryIndex = (messages: UIChatMessage[]): Map<string, WorkSummaryItem[]> => {
+ const index = new Map<string, WorkSummaryItem[]>();
+ for (const message of messages) {
+ const works = message.works;
+ if (!works || works.length === 0) continue;
+ // Prefer the anchor message's own stamp; fall back to the work event's
+ // rootOperationId so the lookup key always matches what the chip resolves.
+ const rootOperationId =
+ getOperationFinalRootId(message.metadata) ?? works[0].event.rootOperationId;
+ if (rootOperationId) index.set(rootOperationId, works);
+ }
+ return index;
+};
+
+// Memoize per dbMessages array identity so the pass runs once per snapshot,
+// regardless of how many MessageWorks instances read from it.
+const indexCache = new WeakMap<UIChatMessage[], Map<string, WorkSummaryItem[]>>();
+
+const getWorkSummaryIndex = (messages: UIChatMessage[]): Map<string, WorkSummaryItem[]> => {
+ let index = indexCache.get(messages);
+ if (!index) {
+ index = buildWorkSummaryIndex(messages);
+ indexCache.set(messages, index);
+ }
+ return index;
+};
+
+/** Works for one round's chip, resolved by the display-resolved rootOperationId. */
+export const getWorkSummariesByRootOperationId = (
+ messages: UIChatMessage[],
+ rootOperationId?: string | null,
+): WorkSummaryItem[] =>
+ rootOperationId ? (getWorkSummaryIndex(messages).get(rootOperationId) ?? []) : [];
+
+/**
+ * Flatten a thread's Work summaries into the conversation-wide list the Works
+ * sidebar (summary mode) renders: one row per Work, deduped to its latest event
+ * and sorted newest-first. Mirrors the server `latestSummaryItemsByWork` shaping
+ * the removed `listSummariesByConversation` used to return.
+ */
+const buildAllWorkSummaries = (
+ messages: UIChatMessage[],
+ threadId?: string | null,
+): WorkSummaryItem[] => {
+ const latestByWork = new Map<string, WorkSummaryItem>();
+ for (const message of messages) {
+ // Scope to the active thread here rather than at the call site: filtering
+ // upstream would hand this function a fresh array on every call and defeat
+ // the identity-keyed memo below.
+ if (threadId ? message.threadId !== threadId : !!message.threadId) continue;
+ for (const work of message.works ?? []) {
+ const existing = latestByWork.get(work.id);
+ if (!existing || toTime(work.event.createdAt) > toTime(existing.event.createdAt)) {
+ latestByWork.set(work.id, work);
+ }
+ }
+ }
+ return Array.from(latestByWork.values()).sort(
+ (a, b) => toTime(b.event.createdAt) - toTime(a.event.createdAt),
+ );
+};
+
+// Memoize per (dbMessages array identity, threadId). Keying on the RAW messages
+// reference — stable across unrelated chat-store `set()`s — means a full rebuild
+// runs once per actual message snapshot, not on every streamed token / store
+// tick. A pre-filtered array would produce a new identity each call and never
+// hit this cache.
+const MAIN_THREAD_CACHE_KEY = '__main__';
+const allWorkSummariesCache = new WeakMap<UIChatMessage[], Map<string, WorkSummaryItem[]>>();
+
+export const getAllWorkSummaries = (
+ messages: UIChatMessage[],
+ threadId?: string | null,
+): WorkSummaryItem[] => {
+ const cacheKey = threadId ?? MAIN_THREAD_CACHE_KEY;
+ let byThread = allWorkSummariesCache.get(messages);
+ if (!byThread) {
+ byThread = new Map();
+ allWorkSummariesCache.set(messages, byThread);
+ }
+ let list = byThread.get(cacheKey);
+ if (!list) {
+ list = buildAllWorkSummaries(messages, threadId);
+ byThread.set(cacheKey, list);
+ }
+ return list;
+};
diff --git a/src/features/Work/WorkSummaryCard.tsx b/src/features/Work/WorkSummaryCard.tsx
new file mode 100644
index 00000000000..7558117eb28
--- /dev/null
+++ b/src/features/Work/WorkSummaryCard.tsx
@@ -0,0 +1,164 @@
+'use client';
+
+import type { WorkSummaryItem } from '@lobechat/types';
+import { Flexbox, Tag, Text } from '@lobehub/ui';
+import { createStaticStyles, cx } from 'antd-style';
+import { Trash2Icon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+import { formatWorkVersionCost } from '@/utils/workVersionCost';
+
+import { getWorkTypeDescriptor, isSafeExternalUrl } from './descriptors';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ card: css`
+ overflow: hidden;
+
+ width: 100%;
+ padding-block: 12px;
+ padding-inline: 12px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+
+ background: ${cssVar.colorBgElevated};
+ `,
+ clickable: css`
+ cursor: pointer;
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+ cost: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ icon: css`
+ flex-shrink: 0;
+
+ width: 36px;
+ height: 36px;
+ border-radius: 8px;
+
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+ description: css`
+ min-width: 0;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ title: css`
+ min-width: 0;
+ font-size: 14px;
+ font-weight: 500;
+ `,
+}));
+
+interface WorkSummaryCardProps {
+ className?: string;
+ item: WorkSummaryItem;
+ /**
+ * Override the click target. The default opens the chat portal (task detail /
+ * document), which only renders inside the conversation UI; surfaces without
+ * that portal (e.g. the resource page's 产物 gallery) pass their own
+ * navigation here. Only ever receives a clickable item — the card still gates
+ * clickability on external-url presence and task-deleted state.
+ */
+ onOpen?: (item: WorkSummaryItem) => void;
+}
+
+const WorkSummaryCard = memo<WorkSummaryCardProps>(({ className, item, onOpen }) => {
+ const { t } = useTranslation('chat');
+ const openDocument = useChatStore((s) => s.openDocument);
+ const openTaskDetail = useChatStore((s) => s.openTaskDetail);
+ const cost = formatWorkVersionCost(item.totalCost);
+
+ const descriptor = getWorkTypeDescriptor(item);
+ const Icon = descriptor.getIcon(item);
+ const title =
+ descriptor.getTitle(item)?.trim() ||
+ descriptor.getIdentifier(item) ||
+ item.resourceId ||
+ item.id;
+ const description = descriptor.getDescription(item);
+ const openTarget = descriptor.getOpenTarget(item);
+ // The backing task was deleted outside the tool path: the Work lingers as an
+ // orphan rendered from its snapshot, and opening the gone task detail 404s, so
+ // strip the click affordance and surface a "task deleted" badge.
+ const taskDeleted = item.resourceType === 'task' && item.taskDeleted;
+ const clickable = !!openTarget && !taskDeleted;
+
+ const handleOpen = () => {
+ if (onOpen) {
+ onOpen(item);
+ return;
+ }
+ if (!openTarget) return;
+
+ switch (openTarget.kind) {
+ case 'document': {
+ openDocument(openTarget.documentId, openTarget.agentDocumentId);
+ return;
+ }
+ case 'external': {
+ // Defense in depth: only ever hand http(s) to shell.openExternal.
+ if (isSafeExternalUrl(openTarget.url))
+ window.open(openTarget.url, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ case 'task': {
+ openTaskDetail(openTarget.identifier);
+ }
+ }
+ };
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={cx(styles.card, clickable && styles.clickable, className)}
+ gap={12}
+ onClick={clickable ? handleOpen : undefined}
+ >
+ <Flexbox align={'center'} className={styles.icon} justify={'center'}>
+ <Icon size={18} />
+ </Flexbox>
+ <Flexbox flex={1} gap={6} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Text ellipsis className={styles.title}>
+ {title}
+ </Text>
+ {taskDeleted && (
+ <Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>
+ {t('workingPanel.works.taskDeleted')}
+ </Tag>
+ )}
+ </Flexbox>
+ {cost && (
+ <Text
+ code
+ className={styles.cost}
+ fontSize={12}
+ title={t('workingPanel.works.totalCost', { cost })}
+ >
+ {cost}
+ </Text>
+ )}
+ </Flexbox>
+ {description && (
+ <Text ellipsis className={styles.description} fontSize={13}>
+ {description}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+WorkSummaryCard.displayName = 'WorkSummaryCard';
+
+export default WorkSummaryCard;
diff --git a/src/features/Work/descriptors.tsx b/src/features/Work/descriptors.tsx
new file mode 100644
index 00000000000..508e4f4d9e7
--- /dev/null
+++ b/src/features/Work/descriptors.tsx
@@ -0,0 +1,151 @@
+import {
+ type WorkListItem,
+ workProviderOfResourceType,
+ type WorkSkillProvider,
+ type WorkSummaryItem,
+ type WorkType,
+} from '@lobechat/types';
+import { Github } from '@lobehub/icons';
+import { ClipboardListIcon, FileTextIcon, LinkIcon } from 'lucide-react';
+import type { ComponentType } from 'react';
+
+import LinearIcon from './icons/LinearIcon';
+
+type WorkIcon = ComponentType<{ className?: string; size?: number }>;
+
+/**
+ * Brand icon per skill provider for the unified `external` Work type. An
+ * unmapped provider (a future provider whose resource type isn't in
+ * `WORK_PROVIDER_RESOURCE_TYPES` yet) falls back to a generic link glyph.
+ */
+const PROVIDER_ICONS: Record<WorkSkillProvider, WorkIcon> = {
+ github: Github,
+ linear: LinearIcon,
+};
+
+/**
+ * Where opening a Work should lead. Components map this to their own action
+ * (chat portal, preview modal, router navigate, `window.open`) — the descriptor
+ * only names the destination, it never reaches into a store or the DOM itself.
+ */
+export type WorkOpenTarget =
+ | { agentDocumentId?: string; documentId: string; kind: 'document' }
+ | { identifier: string; kind: 'task' }
+ | { kind: 'external'; url: string };
+
+/**
+ * Client-side allowlist for external Work URLs (defense in depth over the
+ * authoritative write-time `sanitizeExternalUrl` in the database package —
+ * frontend code must not import that package). Work URLs are member-controlled
+ * (Linear payloads, parsed `gh` stdout), so an old snapshot could still hold a
+ * `javascript:`/`data:`/`file:`/custom scheme. On desktop (Electron) opening a
+ * Work card runs `window.open` → `shell.openExternal`, so only ever hand off
+ * http(s) URLs.
+ */
+export const isSafeExternalUrl = (url?: string | null): url is string => {
+ if (!url) return false;
+
+ try {
+ const { protocol } = new URL(url);
+ return protocol === 'http:' || protocol === 'https:';
+ } catch {
+ return false;
+ }
+};
+
+/** Narrow a Work list/summary union member to the variants of a single type. */
+type WorkItemOfType<T extends WorkType> =
+ Extract<WorkListItem, { type: T }> | Extract<WorkSummaryItem, { type: T }>;
+
+interface WorkTypeDescriptor<Item extends WorkListItem | WorkSummaryItem> {
+ /**
+ * Summary preview text. Summary payloads slim long free-text server-side
+ * (linear content / github body / task instruction capped), so prefer the
+ * description, then a short body/status — never a full document.
+ */
+ getDescription: (item: Item) => string | null;
+ /**
+ * The icon for one item. Constant for document/task; the `external` type
+ * resolves a per-provider brand icon from the item's resourceType.
+ */
+ getIcon: (item: Item) => WorkIcon;
+ /**
+ * Short human reference (`TASK-1`, filename, `ENG-123`, `owner/repo#42`) used
+ * as the card-title fallback when the resource has no title. Cards fall back
+ * further to `resourceId` when this is also null.
+ */
+ getIdentifier: (item: Item) => string | null;
+ /** Where a click should lead, or `null` when the Work is not clickable. */
+ getOpenTarget: (item: Item) => WorkOpenTarget | null;
+ /**
+ * Display title straight from the `works` row (task name is live from the
+ * tasks join). No synthesized fallback here: a nameless resource deliberately
+ * falls through to its bare identifier at the call site so data gaps stay visible.
+ */
+ getTitle: (item: Item) => string | null;
+}
+
+export const WORK_TYPE_DESCRIPTORS: {
+ [T in WorkType]: WorkTypeDescriptor<WorkItemOfType<T>>;
+} = {
+ document: {
+ getDescription: (item) => item.description?.trim() ?? null,
+ getIcon: () => FileTextIcon,
+ getIdentifier: (item) => item.identifier,
+ getOpenTarget: (item) =>
+ // For `document` works the resource identity IS the document id; a Work
+ // with no backing resource (nullable resourceId) has nothing to open.
+ item.resourceId
+ ? {
+ // WorkListItem carries no `event`; only summary rows can supply the
+ // agentDocumentId that scopes the chat portal's document view.
+ agentDocumentId: 'event' in item ? item.event?.metadata?.agentDocumentId : undefined,
+ documentId: item.resourceId,
+ kind: 'document',
+ }
+ : null,
+ getTitle: (item) => item.title,
+ },
+ external: {
+ getDescription: (item) => (item.description || item.status)?.trim() ?? null,
+ // Resolve the brand icon from the item's provider; unknown providers fall
+ // back to a generic link glyph (forward-compat).
+ getIcon: (item) => {
+ const provider = workProviderOfResourceType(item.resourceType);
+ return provider ? PROVIDER_ICONS[provider] : LinkIcon;
+ },
+ getIdentifier: (item) => item.identifier,
+ // External works registered from CLI/tool results may carry no URL (or a
+ // member-planted non-http(s) scheme) — those cards have nothing safe to
+ // open, so drop the click affordance entirely.
+ getOpenTarget: (item) =>
+ isSafeExternalUrl(item.url) ? { kind: 'external', url: item.url } : null,
+ getTitle: (item) => item.title,
+ },
+ task: {
+ getDescription: (item) => item.task.instruction?.trim() ?? null,
+ getIcon: () => ClipboardListIcon,
+ getIdentifier: (item) => item.task.identifier,
+ // Resolve the task detail by its human identifier (`TASK-1`, live-coalesced
+ // with the persisted works column) when present, else its id — the same
+ // identifier the chat portal and standalone route both accept. The
+ // task-deleted orphan case is gated by the call site (it also renders a
+ // badge), not stripped here. A task Work always has a resourceId, but it is
+ // nullable on the base type, so drop the affordance when both are missing.
+ getOpenTarget: (item) => {
+ const identifier = item.task.identifier ?? item.resourceId;
+ return identifier ? { identifier, kind: 'task' } : null;
+ },
+ getTitle: (item) => item.task.name,
+ },
+};
+
+/**
+ * Narrowing accessor so a call site holding a `WorkListItem` / `WorkSummaryItem`
+ * union keeps type safety: the returned descriptor's methods accept exactly the
+ * item type passed in.
+ */
+export const getWorkTypeDescriptor = <Item extends WorkListItem | WorkSummaryItem>(
+ item: Item,
+): WorkTypeDescriptor<Item> =>
+ WORK_TYPE_DESCRIPTORS[item.type] as unknown as WorkTypeDescriptor<Item>;
diff --git a/src/features/Work/icons/LinearIcon.tsx b/src/features/Work/icons/LinearIcon.tsx
new file mode 100644
index 00000000000..3ae4692ed06
--- /dev/null
+++ b/src/features/Work/icons/LinearIcon.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import type { IconType } from '@lobehub/icons';
+import { memo } from 'react';
+
+/**
+ * Linear brand logomark, same path as the Linear tool inspector
+ * (packages/shared-tool-ui/src/Inspector/Linear/Inspector.tsx) so Linear
+ * work cards stay visually consistent with Linear tool-call rows.
+ */
+const Icon: IconType = memo(({ size = '1em', style, ...rest }) => {
+ return (
+ <svg
+ fill="currentColor"
+ fillRule="evenodd"
+ height={size}
+ style={{ flex: 'none', lineHeight: 1, ...style }}
+ viewBox="0 0 100 100"
+ width={size}
+ xmlns="http://www.w3.org/2000/svg"
+ {...rest}
+ >
+ <path d="M1.22541 61.5228c-.2225-.9485.90748-1.5459 1.59638-.857l36.5217 36.5208c.6889.6892.0915 1.8191-.857 1.5962C20.0696 93.4248 6.4263 79.7822 1.22541 61.5228ZM.00189 46.8083c-.034026.4081.115306.8067.405562 1.0969l51.683 51.683c.2903.2903.6888.4396 1.0969.4056 2.0035-.16708 3.9669-.49328 5.8741-.96868.7361-.18352.9961-1.0903.4607-1.6256L2.5907 40.4732c-.5353-.5354-1.4421-.2754-1.6256.4607-.475415 1.9072-.801574 3.8706-.968613 5.8744ZM4.21462 29.7355c-.16002.3549-.08227.7719.19288 1.047L69.2174 95.5901c.275.2752.6921.353 1.047.193 1.4913-.6716 2.9332-1.43 4.3197-2.275.5025-.3061.5856-1.0023.1674-1.4205L8.31112 25.279c-.41817-.4181-1.11435-.3349-1.42044.1675-.84572 1.3873-1.60473 2.8284-2.27606 4.319ZM12.6963 18.6088c-.3683-.3684-.3923-.9577-.0469-1.3489C21.7846 6.9544 35.1342 0 50 0c27.6142 0 50 22.3858 50 50 0 14.8669-6.9544 28.2155-17.2598 37.3499-.3912.3461-.9805.3214-1.349-.0469L12.6963 18.6088Z" />
+ </svg>
+ );
+});
+
+export default Icon;
diff --git a/src/features/WorkGallery/WorkPreviewCard.tsx b/src/features/WorkGallery/WorkPreviewCard.tsx
new file mode 100644
index 00000000000..9643e678c64
--- /dev/null
+++ b/src/features/WorkGallery/WorkPreviewCard.tsx
@@ -0,0 +1,136 @@
+'use client';
+
+import type { WorkSummaryItem } from '@lobechat/types';
+import { Flexbox, Tag, Text } from '@lobehub/ui';
+import { createStaticStyles, cx } from 'antd-style';
+import { Trash2Icon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { getWorkTypeDescriptor } from '@/features/Work/descriptors';
+import { formatWorkVersionCost } from '@/utils/workVersionCost';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ card: css`
+ overflow: hidden;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 12px;
+ background: ${cssVar.colorBgElevated};
+ `,
+ clickable: css`
+ cursor: pointer;
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+ cost: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ header: css`
+ padding-block: 10px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ icon: css`
+ flex-shrink: 0;
+
+ width: 26px;
+ height: 26px;
+ border-radius: 6px;
+
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+ preview: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 6;
+
+ min-height: 108px;
+ padding-block: 12px;
+ padding-inline: 12px;
+
+ font-size: 12px;
+ line-height: 1.6;
+ color: ${cssVar.colorTextTertiary};
+ word-break: break-word;
+ `,
+ title: css`
+ min-width: 0;
+ font-size: 14px;
+ font-weight: 500;
+ `,
+}));
+
+interface WorkPreviewCardProps {
+ item: WorkSummaryItem;
+ /** The gallery owns navigation (no chat portal on the resource page). */
+ onOpen: (item: WorkSummaryItem) => void;
+}
+
+/**
+ * Gallery cell for the resource page's 产物 view: a vertical card with a
+ * header row (type icon + title + cost) and a content-preview body, mirroring
+ * the library page's file cards. The preview is the Work's write-time
+ * description slice — the in-chat `WorkSummaryCard` stays the compact
+ * one-line variant.
+ */
+const WorkPreviewCard = memo<WorkPreviewCardProps>(({ item, onOpen }) => {
+ const { t } = useTranslation('chat');
+ const cost = formatWorkVersionCost(item.totalCost);
+
+ const descriptor = getWorkTypeDescriptor(item);
+ const Icon = descriptor.getIcon(item);
+ const title =
+ descriptor.getTitle(item)?.trim() ||
+ descriptor.getIdentifier(item) ||
+ item.resourceId ||
+ item.id;
+ const description = descriptor.getDescription(item);
+ // Same clickability gating as WorkSummaryCard: no open target or an orphaned
+ // (deleted-task) Work renders inert.
+ const taskDeleted = item.resourceType === 'task' && item.taskDeleted;
+ const clickable = !!descriptor.getOpenTarget(item) && !taskDeleted;
+
+ return (
+ <Flexbox
+ className={cx(styles.card, clickable && styles.clickable)}
+ onClick={clickable ? () => onOpen(item) : undefined}
+ >
+ <Flexbox horizontal align={'center'} className={styles.header} gap={8}>
+ <Flexbox align={'center'} className={styles.icon} justify={'center'}>
+ <Icon size={15} />
+ </Flexbox>
+ <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>
+ <Text ellipsis className={styles.title}>
+ {title}
+ </Text>
+ {taskDeleted && (
+ <Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>
+ {t('workingPanel.works.taskDeleted')}
+ </Tag>
+ )}
+ </Flexbox>
+ {cost && (
+ <Text
+ code
+ className={styles.cost}
+ fontSize={12}
+ title={t('workingPanel.works.totalCost', { cost })}
+ >
+ {cost}
+ </Text>
+ )}
+ </Flexbox>
+ <div className={styles.preview}>{description}</div>
+ </Flexbox>
+ );
+});
+
+WorkPreviewCard.displayName = 'WorkPreviewCard';
+
+export default WorkPreviewCard;
diff --git a/src/features/WorkGallery/const.tsx b/src/features/WorkGallery/const.tsx
new file mode 100644
index 00000000000..77259577304
--- /dev/null
+++ b/src/features/WorkGallery/const.tsx
@@ -0,0 +1,36 @@
+import type { WorkSkillProvider, WorkType } from '@lobechat/types';
+
+/**
+ * `?works=` values: the per-type keys (task / document) plus the per-PROVIDER
+ * keys (linear / github) and a combined `all` view. The sidebar currently
+ * exposes only the single `all` entry — the narrower keys stay parseable so
+ * deep links keep working and per-category tabs can return without a URL
+ * migration.
+ */
+export type WorkGalleryKey = 'all' | 'document' | 'github' | 'linear' | 'task';
+
+/**
+ * How a gallery key narrows the workspace Work list: `type` selects a Work type
+ * (task / document); `provider` narrows the `external` type to one skill
+ * provider (linear / github); `all` carries neither (combined view).
+ */
+export interface WorkGalleryFilter {
+ provider?: WorkSkillProvider;
+ type?: WorkType;
+}
+
+const FILTER_BY_KEY = new Map<WorkGalleryKey, WorkGalleryFilter>([
+ ['all', {}],
+ ['task', { type: 'task' }],
+ ['document', { type: 'document' }],
+ ['linear', { provider: 'linear' }],
+ ['github', { provider: 'github' }],
+]);
+
+/** Parse the raw `?works=` param into a valid key, or null when absent/invalid. */
+export const parseWorkGalleryKey = (value: string | null): WorkGalleryKey | null =>
+ value && FILTER_BY_KEY.has(value as WorkGalleryKey) ? (value as WorkGalleryKey) : null;
+
+/** The type/provider filter a key maps to (`all` → `{}`, no filter). */
+export const workFilterFromKey = (key: WorkGalleryKey): WorkGalleryFilter =>
+ FILTER_BY_KEY.get(key) ?? {};
diff --git a/src/features/WorkGallery/hooks.ts b/src/features/WorkGallery/hooks.ts
new file mode 100644
index 00000000000..4db44fe9baa
--- /dev/null
+++ b/src/features/WorkGallery/hooks.ts
@@ -0,0 +1,81 @@
+import { useCallback, useEffect } from 'react';
+import useSWRInfinite from 'swr/infinite';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { workKeys } from '@/libs/swr/keys';
+import type { WorkSummaryPage } from '@/services/work';
+import { workService } from '@/services/work';
+
+import { workFilterFromKey, type WorkGalleryKey } from './const';
+
+const WORK_GALLERY_PAGE_SIZE = 30;
+
+/**
+ * Cursor-paginated, infinite-scrolling Work summaries scoped to the active
+ * workspace (or personal space). `galleryKey` selects the filter (a Work type,
+ * a skill provider, or the combined `all` view). Changing it collapses back to
+ * the first page. Mirrors `useVerifyReportSummariesInfinite`.
+ */
+export const useWorkspaceWorksInfinite = (galleryKey: WorkGalleryKey) => {
+ const workspaceId = useActiveWorkspaceId();
+ const filter = workFilterFromKey(galleryKey);
+
+ const getKey = useCallback(
+ (_index: number, previous: WorkSummaryPage | null) => {
+ // Stop paging once the previous page reported no further cursor.
+ if (previous && previous.nextCursor === null) return null;
+ return workKeys.workspace(workspaceId, galleryKey, previous?.nextCursor ?? undefined);
+ },
+ [galleryKey, workspaceId],
+ );
+
+ const { data, error, isLoading, isValidating, mutate, setSize, size } = useSWRInfinite(
+ getKey,
+ ([, , , cursor]: readonly [string, string | null, string, string | null]) =>
+ workService.listByWorkspace({
+ cursor: cursor || undefined,
+ limit: WORK_GALLERY_PAGE_SIZE,
+ provider: filter.provider,
+ type: filter.type ?? null,
+ }),
+ { revalidateFirstPage: false },
+ );
+
+ // A new filter starts a fresh key series; collapse size back to 1 so we
+ // don't cascade-fetch as many pages as the previous filter had loaded.
+ useEffect(() => {
+ setSize(1);
+ }, [galleryKey, setSize]);
+
+ const loadMore = useCallback(() => {
+ void setSize((s) => s + 1);
+ }, [setSize]);
+ const reload = useCallback(() => {
+ void mutate();
+ }, [mutate]);
+
+ // SWR leaves a failed/pending page's slot `undefined`, so guard the holes.
+ const items = data?.flatMap((page) => page?.items ?? []) ?? [];
+ const lastLoadedPage = data?.findLast(Boolean);
+ const reachedEnd = lastLoadedPage ? lastLoadedPage.nextCursor === null : false;
+
+ // A subsequent page is genuinely in flight only when it hasn't errored — an
+ // errored page also leaves its slot undefined, but must not read as loading.
+ const isLoadingMore =
+ !error && (isLoading || (size > 0 && !!data && typeof data[size - 1] === 'undefined'));
+
+ // Pause the sentinel while an error is showing so it can't hot-loop the failed
+ // page; the gallery offers a manual retry (`reload`) instead.
+ const hasMore = !reachedEnd && !error;
+
+ return {
+ error,
+ hasMore,
+ isLoadingInitial: isLoading,
+ isLoadingMore,
+ isValidating,
+ items,
+ loadMore,
+ reload,
+ };
+};
diff --git a/src/features/WorkGallery/index.tsx b/src/features/WorkGallery/index.tsx
new file mode 100644
index 00000000000..3530fbda5a0
--- /dev/null
+++ b/src/features/WorkGallery/index.tsx
@@ -0,0 +1,364 @@
+'use client';
+
+import type { WorkSummaryItem } from '@lobechat/types';
+import { Center, Empty, Flexbox, Skeleton, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { PackageOpenIcon, TriangleAlertIcon } from 'lucide-react';
+import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatTaskItemDate } from '@/features/AgentTasks/features/formatTaskItemDate';
+import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
+import DocumentPreviewModal from '@/features/DocumentModal/Preview';
+import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useDocumentStore } from '@/store/document';
+
+import type { WorkGalleryKey } from './const';
+import { useWorkspaceWorksInfinite } from './hooks';
+import WorkPreviewCard from './WorkPreviewCard';
+
+const styles = createStaticStyles(({ css }) => ({
+ container: css`
+ height: 100%;
+ `,
+ header: css`
+ flex: none;
+ padding-block: 16px 8px;
+ padding-inline: 24px;
+ `,
+ scroll: css`
+ overflow: hidden auto;
+ flex: 1;
+
+ min-height: 0;
+ padding-block: 8px 24px;
+ padding-inline: 24px;
+ `,
+ // Single-column stack (not a grid): cards keep the library page's fixed
+ // proportions and read top-to-bottom within each topic group.
+ cardList: css`
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+
+ width: 100%;
+ max-width: 420px;
+ `,
+ groupDate: css`
+ flex: none;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ groupHeader: css`
+ display: flex;
+ gap: 16px;
+ align-items: baseline;
+ justify-content: space-between;
+
+ margin-block-end: 12px;
+ `,
+ groupTitle: css`
+ overflow: hidden;
+
+ font-size: 16px;
+ font-weight: 600;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ // Loading placeholder shell that mirrors `WorkPreviewCard` so the skeleton
+ // lays out as vertical preview cards in the same grid.
+ skeletonCard: css`
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+
+ padding: 12px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 12px;
+
+ background: ${cssVar.colorBgElevated};
+ `,
+ emptyState: css`
+ height: 100%;
+ min-height: 320px;
+ `,
+ loadMoreError: css`
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ align-items: center;
+ justify-content: center;
+
+ padding-block: 16px;
+
+ font-size: 13px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ retry: css`
+ cursor: pointer;
+
+ padding-block: 4px;
+ padding-inline: 12px;
+ border: 1px solid ${cssVar.colorBorder};
+ border-radius: 6px;
+
+ font-size: 13px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorBgContainer};
+
+ &:hover {
+ border-color: ${cssVar.colorTextTertiary};
+ color: ${cssVar.colorText};
+ }
+ `,
+}));
+
+/** Card-shaped loading placeholders laid out in the same grid as real cards. */
+const SkeletonCards = memo<{ count: number }>(({ count }) => (
+ <div className={styles.cardList}>
+ {Array.from({ length: count }).map((_, index) => (
+ <div className={styles.skeletonCard} key={index}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Skeleton.Button
+ active
+ size={'small'}
+ style={{ borderRadius: 6, height: 26, maxWidth: 26, minWidth: 26 }}
+ />
+ <Skeleton.Button
+ active
+ block
+ size={'small'}
+ style={{ borderRadius: 4, height: 14, maxWidth: '60%' }}
+ />
+ </Flexbox>
+ <Flexbox gap={8}>
+ <Skeleton.Button active block size={'small'} style={{ borderRadius: 4, height: 12 }} />
+ <Skeleton.Button
+ active
+ block
+ size={'small'}
+ style={{ borderRadius: 4, height: 12, maxWidth: '80%', opacity: 0.7 }}
+ />
+ <Skeleton.Button
+ active
+ block
+ size={'small'}
+ style={{ borderRadius: 4, height: 12, maxWidth: '55%', opacity: 0.4 }}
+ />
+ </Flexbox>
+ </div>
+ ))}
+ </div>
+));
+
+SkeletonCards.displayName = 'SkeletonCards';
+
+/**
+ * Initial-load placeholder mirroring the final layout: topic-group sections,
+ * each with a title/date header row above its card grid — not a bare card pile.
+ */
+const SkeletonGroups = memo(() => (
+ <Flexbox gap={32}>
+ {[3, 2].map((count, index) => (
+ <div key={index}>
+ <div className={styles.groupHeader}>
+ <Skeleton.Button
+ active
+ size={'small'}
+ style={{ borderRadius: 4, height: 16, minWidth: 160, width: 160 }}
+ />
+ <Skeleton.Button
+ active
+ size={'small'}
+ style={{ borderRadius: 4, height: 12, minWidth: 48, opacity: 0.5, width: 48 }}
+ />
+ </div>
+ <SkeletonCards count={count} />
+ </div>
+ ))}
+ </Flexbox>
+));
+
+SkeletonGroups.displayName = 'SkeletonGroups';
+
+interface WorkGalleryProps {
+ galleryKey: WorkGalleryKey;
+}
+
+/**
+ * The resource page's 产物 content area: a cross-topic, cursor-paginated flow
+ * of Work previews grouped by origin topic. Renders `WorkPreviewCard` with an
+ * `onOpen` that navigates without the chat portal (task → standalone detail
+ * route, document → global preview modal, external skill works (linear /
+ * github) → external link).
+ */
+const WorkGallery = memo<WorkGalleryProps>(({ galleryKey }) => {
+ const { t, i18n } = useTranslation('file');
+ const navigate = useWorkspaceAwareNavigate();
+ const openDocumentPreview = useDocumentStore((s) => s.openDocumentPreview);
+
+ const { items, error, hasMore, isLoadingInitial, isLoadingMore, loadMore, reload } =
+ useWorkspaceWorksInfinite(galleryKey);
+
+ // Group the flat (updatedAt desc) page stream by origin topic. First
+ // appearance decides group order, so groups sort by their newest work; later
+ // pages can still append older works into an already-rendered group.
+ const groups = useMemo(() => {
+ const byKey = new Map<
+ string,
+ { items: WorkSummaryItem[]; newestAt: Date; title: string | null }
+ >();
+ for (const item of items) {
+ // Deleted-topic and non-conversation works share one trailing bucket per
+ // render order; their titles are gone, so finer keys would only produce
+ // several identical "other" sections.
+ const key = item.originTopicId ?? '__no_topic__';
+ const group = byKey.get(key);
+ if (group) group.items.push(item);
+ else
+ byKey.set(key, {
+ items: [item],
+ newestAt: item.updatedAt,
+ title: item.originTopicTitle ?? null,
+ });
+ }
+ return [...byKey.entries()].map(([key, group]) => ({ key, ...group }));
+ }, [items]);
+
+ const handleOpen = useCallback(
+ (item: WorkSummaryItem) => {
+ const openTarget = getWorkTypeDescriptor(item).getOpenTarget(item);
+ if (!openTarget) return;
+
+ switch (openTarget.kind) {
+ case 'document': {
+ openDocumentPreview(openTarget.documentId);
+ return;
+ }
+ // external skill works (linear / github): external link (URL-less cards
+ // yield no target above).
+ case 'external': {
+ // Defense in depth: only ever hand http(s) to shell.openExternal.
+ if (isSafeExternalUrl(openTarget.url))
+ window.open(openTarget.url, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ // task: no external URL — the standalone detail route resolves the same
+ // identifier-or-id the chat portal uses.
+ case 'task': {
+ navigate(taskDetailPath(openTarget.identifier));
+ }
+ }
+ },
+ [navigate, openDocumentPreview],
+ );
+
+ // Infinite scroll: load the next page when a sentinel near the list's end
+ // scrolls into view (rootMargin pre-fetches before the user hits the bottom).
+ const sentinelRef = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ const el = sentinelRef.current;
+ if (!el || !hasMore) return;
+ const io = new IntersectionObserver(
+ (entries) => {
+ if (entries[0]?.isIntersecting && hasMore && !isLoadingMore) loadMore();
+ },
+ { rootMargin: '240px' },
+ );
+ io.observe(el);
+ return () => io.disconnect();
+ }, [hasMore, isLoadingMore, loadMore]);
+
+ const renderBody = () => {
+ // A failed first fetch must read as an error with a retry — not masquerade
+ // as an empty "no works" page.
+ if (error && items.length === 0)
+ return (
+ <Center className={styles.emptyState} gap={12}>
+ <Empty
+ description={t('work.loadError')}
+ icon={TriangleAlertIcon}
+ title={t('work.loadErrorTitle')}
+ />
+ <button className={styles.retry} type={'button'} onClick={() => reload()}>
+ {t('work.retry')}
+ </button>
+ </Center>
+ );
+
+ if (isLoadingInitial && items.length === 0) return <SkeletonGroups />;
+
+ if (items.length === 0)
+ return (
+ <Center className={styles.emptyState}>
+ <Empty
+ description={t('work.empty.desc')}
+ icon={PackageOpenIcon}
+ title={t('work.empty.title')}
+ />
+ </Center>
+ );
+
+ return (
+ <>
+ <Flexbox gap={32}>
+ {groups.map((group) => (
+ <div key={group.key}>
+ <div className={styles.groupHeader}>
+ <span className={styles.groupTitle}>
+ {group.title ?? t('work.topicGroup.other')}
+ </span>
+ <span className={styles.groupDate}>
+ {formatTaskItemDate(group.newestAt, {
+ formatOtherYear: t('time.formatOtherYear', { ns: 'common' }),
+ formatThisYear: t('time.formatThisYear', { ns: 'common' }),
+ locale: i18n.language,
+ })}
+ </span>
+ </div>
+ <div className={styles.cardList}>
+ {group.items.map((item) => (
+ <WorkPreviewCard item={item} key={item.id} onOpen={handleOpen} />
+ ))}
+ </div>
+ </div>
+ ))}
+ </Flexbox>
+ {/* Sentinel drives infinite scroll; keep it mounted so the observer can
+ re-fire after each page appends. */}
+ <div aria-hidden ref={sentinelRef} style={{ height: 1 }} />
+ {isLoadingMore ? (
+ <Flexbox style={{ marginBlockStart: 12 }}>
+ <SkeletonCards count={2} />
+ </Flexbox>
+ ) : error ? (
+ <div className={styles.loadMoreError}>
+ <span>{t('work.loadMoreError')}</span>
+ <button className={styles.retry} type={'button'} onClick={() => reload()}>
+ {t('work.retry')}
+ </button>
+ </div>
+ ) : null}
+ </>
+ );
+ };
+
+ return (
+ <Flexbox className={styles.container}>
+ <div className={styles.header}>
+ <Text strong style={{ fontSize: 16 }}>
+ {t('work.group')}
+ </Text>
+ </div>
+ <Flexbox className={styles.scroll}>{renderBody()}</Flexbox>
+ <DocumentPreviewModal />
+ </Flexbox>
+ );
+});
+
+WorkGallery.displayName = 'WorkGallery';
+
+export default WorkGallery;
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 01c25492b88..e8c108c302a 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -18,6 +18,8 @@
* `@/services/document/swrKeys` (already a factory, widely imported) and
* re-exported here so the whole set is reachable from one place.
*/
+import { type ConversationContext } from '@lobechat/types';
+
import {
agentDocumentSWRKeys,
documentSWRKeys,
@@ -96,6 +98,22 @@ export const messageKeys = {
]),
};
+/**
+ * SWR `mutate` matcher for `message:list` keys. The key shape is
+ * `[message:list, ConversationContext, version]`, so this guards `key[0]` and
+ * hands the resolved context to an optional predicate (omit it to match every
+ * message list, any scope / thread / page-size / version variant). Shared by
+ * every message-list invalidation site so the key-shape knowledge lives once.
+ */
+export const isMessageListKey = (
+ key: unknown,
+ predicate?: (context: ConversationContext) => boolean,
+): boolean => {
+ if (!Array.isArray(key) || key[0] !== messageKeys.list.root) return false;
+ const context = key[1] as ConversationContext | undefined;
+ return !!context && (predicate ? predicate(context) : true);
+};
+
// ---- topic --------------------------------------------------------------
export const topicKeys = {
agentView: def('topic:agentView', (containerKey: string, opts: Record<string, unknown>) => [
@@ -208,6 +226,30 @@ export const taskKeys = {
),
};
+// ---- work ---------------------------------------------------------------
+export const workKeys = {
+ conversation: def('work:conversation', (topicId: string, threadId?: string | null) => [
+ 'work:conversation',
+ topicId,
+ threadId ?? null,
+ ]),
+ versions: def('work:versions', (workId: string) => ['work:versions', workId]),
+ // Cross-topic Work gallery on the resource page: keyed by owner scope + the
+ // gallery filter key (type OR provider tab, e.g. `all` / `task` / `linear`) +
+ // keyset cursor (one entry per infinite-scroll page). The filter key (not the
+ // Work type) is the discriminator so the per-provider linear/github tabs,
+ // which share the `external` Work type, get distinct cache entries.
+ workspace: def(
+ 'work:workspace',
+ (workspaceId: string | null | undefined, filterKey: string, cursor?: string | null) => [
+ 'work:workspace',
+ workspaceId ?? null,
+ filterKey,
+ cursor ?? null,
+ ],
+ ),
+};
+
// ---- brief --------------------------------------------------------------
export const briefKeys = {
list: def('brief:list', (isLogin: boolean) => ['brief:list', isLogin]),
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorksSection/VersionList.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorksSection/VersionList.tsx
new file mode 100644
index 00000000000..66113bb81db
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorksSection/VersionList.tsx
@@ -0,0 +1,128 @@
+import type { WorkVersionItem } from '@lobechat/types';
+import { Center, Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import { formatTaskItemDate } from '@/features/AgentTasks/features/formatTaskItemDate';
+import { useClientDataSWR } from '@/libs/swr';
+import { workKeys } from '@/libs/swr/keys';
+import { workService } from '@/services/work';
+import { computeWorkVersionCostDeltas, formatWorkVersionCost } from '@/utils/workVersionCost';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ context: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ error: css`
+ padding-block: 8px;
+ padding-inline: 36px 8px;
+ color: ${cssVar.colorError};
+ `,
+ versionCost: css`
+ color: ${cssVar.colorTextTertiary};
+ `,
+ versionList: css`
+ margin-inline-start: 34px;
+ padding-block: 6px 10px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ versionRow: css`
+ padding-block: 6px;
+ font-size: 12px;
+ `,
+ versionTitle: css`
+ color: ${cssVar.colorTextSecondary};
+ `,
+}));
+
+const VersionList = memo<{ workId: string }>(({ workId }) => {
+ const { i18n, t } = useTranslation(['chat', 'common']);
+ const {
+ data = [],
+ error,
+ isLoading,
+ } = useClientDataSWR<WorkVersionItem[]>(
+ workKeys.versions(workId),
+ () => workService.listVersions(workId),
+ {
+ fallbackData: [],
+ revalidateOnFocus: false,
+ },
+ );
+
+ if (isLoading) {
+ return (
+ <Center height={56}>
+ <NeuralNetworkLoading size={18} />
+ </Center>
+ );
+ }
+
+ if (error) {
+ return <Text className={styles.error}>{t('workingPanel.works.versionError')}</Text>;
+ }
+
+ if (data.length === 0) {
+ return (
+ <Flexbox className={styles.versionList}>
+ <Text type={'secondary'}>{t('workingPanel.works.emptyVersions')}</Text>
+ </Flexbox>
+ );
+ }
+
+ // cumulativeCost is a per-operation running snapshot; diff it so each row
+ // shows the version's own spend and the rows visibly sum to the card total.
+ const costDeltas = computeWorkVersionCostDeltas(data);
+
+ return (
+ <Flexbox className={styles.versionList}>
+ {data.map((version) => {
+ const cost = formatWorkVersionCost(costDeltas.get(version.id));
+ const time = formatTaskItemDate(version.createdAt, {
+ formatOtherYear: t('time.formatOtherYear', { ns: 'common' }),
+ formatThisYear: t('time.formatThisYear', { ns: 'common' }),
+ locale: i18n.language,
+ });
+
+ return (
+ <Flexbox className={styles.versionRow} gap={4} key={version.id}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Text code fontSize={12}>
+ v{version.version}
+ </Text>
+ <Text ellipsis className={styles.versionTitle}>
+ {t(`workingPanel.works.changeType.${version.changeType}` as never)}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={8} style={{ flexShrink: 0 }}>
+ {cost && (
+ <Text
+ code
+ className={styles.versionCost}
+ fontSize={12}
+ title={t('workingPanel.works.versionCost', { cost })}
+ >
+ {cost}
+ </Text>
+ )}
+ {time && (
+ <Text className={styles.context} type={'secondary'}>
+ {time}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ );
+});
+
+VersionList.displayName = 'VersionList';
+
+export default VersionList;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
new file mode 100644
index 00000000000..bc4d8c78365
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
@@ -0,0 +1,144 @@
+import type { TaskStatus, WorkListItem } from '@lobechat/types';
+import { Flexbox, Tag, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { ChevronDownIcon, ChevronRightIcon, Trash2Icon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import TaskPriorityTag from '@/features/AgentTasks/features/TaskPriorityTag';
+import TaskStatusTag from '@/features/AgentTasks/features/TaskStatusTag';
+import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';
+import { useChatStore } from '@/store/chat';
+
+import VersionList from './VersionList';
+
+const TASK_STATUS_SET = new Set<TaskStatus>([
+ 'backlog',
+ 'canceled',
+ 'completed',
+ 'failed',
+ 'paused',
+ 'running',
+ 'scheduled',
+]);
+
+const toTaskStatus = (status?: string | null): TaskStatus =>
+ status && TASK_STATUS_SET.has(status as TaskStatus) ? (status as TaskStatus) : 'backlog';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ context: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ header: css`
+ cursor: pointer;
+ user-select: none;
+ padding-block: 10px;
+ padding-inline: 8px;
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+ title: css`
+ min-width: 0;
+ font-size: 14px;
+ font-weight: 500;
+ `,
+ toggle: css`
+ flex-shrink: 0;
+ `,
+ workCard: css`
+ overflow: hidden;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+ background: ${cssVar.colorFillQuaternary};
+ `,
+}));
+
+const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {
+ const { t } = useTranslation('chat');
+ const [expanded, setExpanded] = useState(false);
+ const [openDocument, openTaskDetail] = useChatStore((s) => [s.openDocument, s.openTaskDetail]);
+ const ToggleIcon = expanded ? ChevronDownIcon : ChevronRightIcon;
+ // The underlying task was deleted outside the tool path — the Work survives as
+ // an orphan rendered from its snapshot, and opening the (gone) task detail 404s.
+ const taskDeleted = work.type === 'task' && work.taskDeleted;
+
+ const descriptor = getWorkTypeDescriptor(work);
+ const label = descriptor.getIdentifier(work) ?? work.resourceId;
+ const TypeIcon = descriptor.getIcon(work);
+ const title = descriptor.getTitle(work)?.trim();
+ const openTarget = descriptor.getOpenTarget(work);
+
+ // Mirrors WorkSummaryCard: external skill rows (linear/github) without a URL
+ // get no title click affordance (openTarget is null) — the click falls to the
+ // expand toggle. The history card opens documents without an agentDocumentId.
+ const handleTitleClick = (() => {
+ if (!openTarget) return undefined;
+ switch (openTarget.kind) {
+ case 'document': {
+ return () => openDocument(openTarget.documentId);
+ }
+ case 'external': {
+ // Defense in depth: only ever hand http(s) to shell.openExternal.
+ return isSafeExternalUrl(openTarget.url)
+ ? () => window.open(openTarget.url, '_blank', 'noopener,noreferrer')
+ : undefined;
+ }
+ case 'task': {
+ return taskDeleted ? undefined : () => openTaskDetail(openTarget.identifier);
+ }
+ }
+ })();
+
+ return (
+ <Flexbox className={styles.workCard}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.header}
+ gap={8}
+ onClick={() => setExpanded((value) => !value)}
+ >
+ <ToggleIcon className={styles.toggle} size={16} />
+ {work.type === 'task' ? (
+ <>
+ <TaskPriorityTag disableDropdown priority={work.task.priority} size={14} />
+ <TaskStatusTag disableDropdown size={14} status={toTaskStatus(work.task.status)} />
+ </>
+ ) : (
+ <TypeIcon className={styles.context} size={16} />
+ )}
+ <Text className={styles.context} style={{ flexShrink: 0 }}>
+ {label}
+ </Text>
+ {taskDeleted && (
+ <Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>
+ {t('workingPanel.works.taskDeleted')}
+ </Tag>
+ )}
+ {title && (
+ <Text
+ ellipsis
+ className={styles.title}
+ onClick={
+ handleTitleClick &&
+ ((event) => {
+ event.stopPropagation();
+ handleTitleClick();
+ })
+ }
+ >
+ {title}
+ </Text>
+ )}
+ </Flexbox>
+ {expanded && <VersionList workId={work.id} />}
+ </Flexbox>
+ );
+});
+
+WorkVersionHistoryCard.displayName = 'WorkVersionHistoryCard';
+
+export default WorkVersionHistoryCard;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorksSection/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorksSection/index.tsx
new file mode 100644
index 00000000000..89903954e3e
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorksSection/index.tsx
@@ -0,0 +1,200 @@
+import type { WorkListItem } from '@lobechat/types';
+import { ActionIcon, Center, Empty, Flexbox } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { ClipboardListIcon, HistoryIcon, ListIcon } from 'lucide-react';
+import { memo, useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import { getAllWorkSummaries } from '@/features/Conversation/store/slices/data/workSummaries';
+import WorkSummaryCard from '@/features/Work/WorkSummaryCard';
+import { useLocalStorageState } from '@/hooks/useLocalStorageState';
+import { useClientDataSWR } from '@/libs/swr';
+import { workKeys } from '@/libs/swr/keys';
+import { workService } from '@/services/work';
+import { useChatStore } from '@/store/chat';
+import { dbMessageSelectors, operationSelectors } from '@/store/chat/selectors';
+
+import WorkVersionHistoryCard from './WorkVersionHistoryCard';
+
+type WorksViewMode = 'history' | 'summary';
+
+const WORKS_VIEW_MODE_STORAGE_KEY = 'lobechat-working-panel-works-view-mode';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ min-height: 0;
+ padding-block: 8px;
+ padding-inline: 8px 12px;
+ `,
+ modeToolbar: css`
+ flex-shrink: 0;
+ align-self: flex-end;
+ `,
+ workCard: css`
+ overflow: hidden;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+ background: ${cssVar.colorFillQuaternary};
+ `,
+}));
+
+const WorksModeToolbar = memo<{
+ mode: WorksViewMode;
+ setMode: (mode: WorksViewMode) => void;
+}>(({ mode, setMode }) => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <Flexbox horizontal className={styles.modeToolbar} gap={4}>
+ <ActionIcon
+ active={mode === 'summary'}
+ icon={ListIcon}
+ size={'small'}
+ title={t('workingPanel.works.viewMode.summary')}
+ onClick={() => setMode('summary')}
+ />
+ <ActionIcon
+ active={mode === 'history'}
+ icon={HistoryIcon}
+ size={'small'}
+ title={t('workingPanel.works.viewMode.history')}
+ onClick={() => setMode('history')}
+ />
+ </Flexbox>
+ );
+});
+
+WorksModeToolbar.displayName = 'WorksModeToolbar';
+
+interface WorksSectionProps {
+ /**
+ * Whether the works tab is actually visible (sidebar open + this tab active).
+ * Gates the history fetch so a collapsed / inactive sidebar never pulls it —
+ * mirrors `ResourcesSection`'s `enabled`. Summary needs no gate: it reads the
+ * message payload already in the store.
+ */
+ active?: boolean;
+}
+
+const WorksSection = memo<WorksSectionProps>(({ active = true }) => {
+ const { t } = useTranslation('chat');
+ const [mode, setMode] = useLocalStorageState<WorksViewMode>(
+ WORKS_VIEW_MODE_STORAGE_KEY,
+ 'summary',
+ );
+ const topicId = useChatStore((s) => s.activeTopicId);
+ const threadId = useChatStore((s) => s.activeThreadId);
+ const agentId = useChatStore((s) => s.activeAgentId);
+ // Is the active conversation's agent runtime still running this round? Work
+ // summaries mutate on every tool_end during a run, but the lazy caches below
+ // are an operation-grained concern — suppress their refresh until the run
+ // settles (done / error / abort all clear this flag).
+ const isRunning = useChatStore(
+ operationSelectors.isAgentRuntimeRunningByContext({ agentId, threadId, topicId }),
+ );
+
+ // Summary rides the message payload — derive it in the selector so we only
+ // re-render when the *works* shape changes, not on every streamed token
+ // (which would thrash `isEqual` over the full `UIChatMessage[]`).
+ const summaryData = useChatStore(
+ // Pass the raw messages array (stable across unrelated store ticks) and let
+ // getAllWorkSummaries scope + memoize by threadId; filtering here would hand
+ // it a fresh array every call and defeat its identity-keyed cache.
+ (s) => getAllWorkSummaries(dbMessageSelectors.activeDbMessages(s), threadId),
+ isEqual,
+ );
+
+ // Runtime transports own their operation-end Work refresh. This watcher only
+ // covers Work changes made outside an agent run (for example, a manual delete):
+ //
+ // 1. While a run is active, suppress refresh. Client registration no longer
+ // revalidates `message:list` per tool; gateway already pulls messages on
+ // tool_end (works may lag one beat until register commits).
+ // 2. When `isRunning` flips false, sync the snapshot without another refresh.
+ // 3. Outside a run, if summary content changes (e.g. document delete), only
+ // the lazy history/version keys need a touch.
+ const wasRunningRef = useRef(false);
+ const prevSummaryRef = useRef(summaryData);
+ useEffect(() => {
+ if (isRunning) {
+ wasRunningRef.current = true;
+ return;
+ }
+
+ if (wasRunningRef.current) {
+ wasRunningRef.current = false;
+ prevSummaryRef.current = summaryData;
+ return;
+ }
+
+ if (isEqual(prevSummaryRef.current, summaryData)) return;
+ prevSummaryRef.current = summaryData;
+ void workService.refreshConversationViews(topicId, threadId);
+ }, [summaryData, isRunning, topicId, threadId]);
+
+ // History (version timeline) is heavier and genuinely on-demand — keep it on
+ // its own lazy fetch, gated so a collapsed / inactive sidebar never pulls it.
+ const {
+ data: historyData = [],
+ error: historyError,
+ isLoading: isHistoryLoading,
+ } = useClientDataSWR<WorkListItem[]>(
+ mode === 'history' && topicId && active
+ ? workKeys.conversation(topicId, threadId ?? null)
+ : null,
+ () => workService.listByConversation({ threadId, topicId }),
+ {
+ fallbackData: [],
+ revalidateOnFocus: false,
+ },
+ );
+
+ const isLoading = mode === 'history' ? isHistoryLoading : false;
+ const error = mode === 'history' ? historyError : undefined;
+ const data = mode === 'summary' ? summaryData : historyData;
+
+ const content = (() => {
+ if (isLoading) {
+ return (
+ <Center flex={1}>
+ <NeuralNetworkLoading size={24} />
+ </Center>
+ );
+ }
+
+ if (error) {
+ return (
+ <Center flex={1}>
+ <Empty description={t('workingPanel.works.error')} icon={ClipboardListIcon} />
+ </Center>
+ );
+ }
+
+ if (data.length === 0) {
+ return (
+ <Center flex={1}>
+ <Empty description={t('workingPanel.works.empty')} icon={ClipboardListIcon} />
+ </Center>
+ );
+ }
+
+ return mode === 'summary'
+ ? summaryData.map((work) => (
+ <WorkSummaryCard className={styles.workCard} item={work} key={work.id} />
+ ))
+ : historyData.map((work) => <WorkVersionHistoryCard key={work.id} work={work} />);
+ })();
+
+ return (
+ <Flexbox className={styles.container} flex={1} gap={12}>
+ <WorksModeToolbar mode={mode} setMode={setMode} />
+ {content}
+ </Flexbox>
+ );
+});
+
+WorksSection.displayName = 'WorksSection';
+
+export default WorksSection;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
index b334e98205a..d431ff5382b 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
@@ -56,6 +56,7 @@ vi.mock('../Review', () => ({ default: () => <div /> }));
vi.mock('../ProgressSection', () => ({ default: () => <div /> }));
vi.mock('../ResourcesSection', () => ({ default: () => <div /> }));
vi.mock('../ParamsSection', () => ({ default: () => <div /> }));
+vi.mock('../WorksSection', () => ({ default: () => <div /> }));
vi.mock('@/store/agent', () => ({
getAgentStoreState: () => agentStore,
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
index 94d361b6899..749667c6c5d 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
@@ -31,6 +31,7 @@ import Files from './Files';
import ProgressSection from './ProgressSection';
import ResourcesSection from './ResourcesSection';
import Review from './Review';
+import WorksSection from './WorksSection';
const ParamsSection = lazy(() => import('./ParamsSection'));
const BrowserPane = lazy(() => import('./Browser'));
@@ -175,6 +176,7 @@ const AgentWorkingSidebar = memo(() => {
const availableTabs = new Set<string>([
'resources',
+ 'works',
...(reviewAvailable ? ['review'] : []),
...(filesAvailable ? ['files'] : []),
...(browserAvailable ? ['browser'] : []),
@@ -258,6 +260,13 @@ const AgentWorkingSidebar = memo(() => {
>
{t('workingPanel.space')}
</button>
+ <button
+ className={`${styles.tab} ${activeTab === 'works' ? styles.tabActive : ''}`}
+ type="button"
+ onClick={() => setWorkingSidebarTab('works')}
+ >
+ {t('workingPanel.works.title')}
+ </button>
{reviewAvailable && (
<button
className={`${styles.tab} ${activeTab === 'review' ? styles.tabActive : ''}`}
@@ -350,6 +359,9 @@ const AgentWorkingSidebar = memo(() => {
enabled={showRightPanel && activeTab === 'resources'}
/>
</Flexbox>
+ <Flexbox className={activeTab === 'works' ? styles.pane : styles.paneHidden}>
+ <WorksSection active={showRightPanel && activeTab === 'works'} />
+ </Flexbox>
</Flexbox>
</Flexbox>
</RightPanel>
diff --git a/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsx b/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsx
index 283d7e90225..d600dd0aa42 100644
--- a/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsx
+++ b/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsx
@@ -1,7 +1,14 @@
'use client';
import { Flexbox } from '@lobehub/ui';
-import { FileText, ImageIcon, LayoutPanelTopIcon, Mic2, SquarePlay } from 'lucide-react';
+import {
+ ClipboardListIcon,
+ FileText,
+ ImageIcon,
+ LayoutPanelTopIcon,
+ Mic2,
+ SquarePlay,
+} from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useLocation } from 'react-router';
@@ -19,6 +26,10 @@ const CategoryMenu = memo(() => {
const navigate = useWorkspaceAwareNavigate();
const businessCategories = useBusinessResourceCategories();
const location = useLocation();
+ // In Work-gallery mode (`?works=`) no file category is selected, so suppress
+ // the category highlight — otherwise "All" reads as active alongside the
+ // active Work entry.
+ const worksActive = new URLSearchParams(location.search).has('works');
const items = useMemo(
() => [
@@ -52,6 +63,14 @@ const CategoryMenu = memo(() => {
title: t('tab.videos'),
url: '/resource?category=videos',
},
+ // Single Works entry (no sub-categories this iteration): switches the
+ // content area to the topic-grouped Work gallery via `?works=all`.
+ {
+ icon: ClipboardListIcon,
+ key: 'works',
+ title: t('work.group'),
+ url: '/resource?works=all',
+ },
...businessCategories.map((category) => ({
icon: category.icon,
key: category.key,
@@ -68,7 +87,11 @@ const CategoryMenu = memo(() => {
<Flexbox gap={1} paddingInline={4}>
{items.map((item) => {
const isBusinessRoute = item.url.startsWith('/resource/');
- const isActive = isBusinessRoute ? location.pathname === item.url : activeKey === item.key;
+ const isActive =
+ item.key === 'works'
+ ? worksActive
+ : !worksActive &&
+ (isBusinessRoute ? location.pathname === item.url : activeKey === item.key);
return (
<Link
key={item.key}
diff --git a/src/routes/(main)/resource/(home)/index.tsx b/src/routes/(main)/resource/(home)/index.tsx
index 5b139467202..ccac04bd4f2 100644
--- a/src/routes/(main)/resource/(home)/index.tsx
+++ b/src/routes/(main)/resource/(home)/index.tsx
@@ -4,6 +4,8 @@ import { memo, useLayoutEffect } from 'react';
import { useLocation, useSearchParams } from 'react-router';
import ResourceManager from '@/features/ResourceManager';
+import WorkGallery from '@/features/WorkGallery';
+import { parseWorkGalleryKey } from '@/features/WorkGallery/const';
import { FilesTabs } from '@/types/files';
import { useInitFileCheck } from '../features/hooks/useInitFileCheck';
@@ -18,6 +20,9 @@ const ResourceHomePage = memo(() => {
]);
const categoryParam = (searchParams.get('category') as FilesTabs) || FilesTabs.All;
+ // `?works=<type>` switches the content area to the cross-topic Work gallery,
+ // independent of the file explorer (which stays keyed on `?category=`).
+ const worksKey = parseWorkGalleryKey(searchParams.get('works'));
// Clear libraryId when on home route using useLayoutEffect
// useLayoutEffect runs synchronously before browser paint, ensuring state is cleared
@@ -46,6 +51,8 @@ const ResourceHomePage = memo(() => {
// Sync file view mode from URL
useInitFileCheck();
+ if (worksKey) return <WorkGallery galleryKey={worksKey} />;
+
return <ResourceManager />;
});
diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.ts
index d87ce63c8b3..89aaa660954 100644
--- a/src/services/agentDocument.ts
+++ b/src/services/agentDocument.ts
@@ -26,8 +26,11 @@ const getDocumentId = (value: unknown) => getStringField(value, 'documentId');
interface AgentDocumentToolContext {
messageId: string;
operationId?: string;
+ rootOperationId?: string;
taskId?: string | null;
+ threadId?: string | null;
toolCallId: string;
+ toolMessageId?: string;
topicId?: string;
}
@@ -132,7 +135,9 @@ class AgentDocumentService {
return lambdaClient.agentDocument.readDocument.query(params);
};
- replaceDocumentContent = async (params: { agentId: string; content: string; id: string }) => {
+ replaceDocumentContent = async (
+ params: { agentId: string; content: string; id: string } & AgentDocumentToolTriggerInput,
+ ) => {
const result = await lambdaClient.agentDocument.replaceDocumentContent.mutate(params);
await invalidateDocumentMutation({
agentDocumentId: params.id,
@@ -144,30 +149,32 @@ class AgentDocumentService {
return result;
};
- modifyNodes = async (params: {
- agentId: string;
- id: string;
- operations: Array<
- | {
- action: 'insert';
- afterId: string;
- litexml: string;
- }
- | {
- action: 'insert';
- beforeId: string;
- litexml: string;
- }
- | {
- action: 'modify';
- litexml: string | string[];
- }
- | {
- action: 'remove';
- id: string;
- }
- >;
- }) => {
+ modifyNodes = async (
+ params: {
+ agentId: string;
+ id: string;
+ operations: Array<
+ | {
+ action: 'insert';
+ afterId: string;
+ litexml: string;
+ }
+ | {
+ action: 'insert';
+ beforeId: string;
+ litexml: string;
+ }
+ | {
+ action: 'modify';
+ litexml: string | string[];
+ }
+ | {
+ action: 'remove';
+ id: string;
+ }
+ >;
+ } & AgentDocumentToolTriggerInput,
+ ) => {
const result = await lambdaClient.agentDocument.modifyNodes.mutate(params);
await invalidateDocumentMutation({
agentDocumentId: params.id,
@@ -179,14 +186,21 @@ class AgentDocumentService {
return result;
};
- removeDocument = async (params: {
- agentId: string;
- documentId?: string;
- id: string;
- topicId?: string;
- }) => {
- const { agentId, documentId, id, topicId } = params;
- const result = await lambdaClient.agentDocument.removeDocument.mutate({ agentId, id });
+ removeDocument = async (
+ params: {
+ agentId: string;
+ documentId?: string;
+ id: string;
+ topicId?: string;
+ } & AgentDocumentToolTriggerInput,
+ ) => {
+ const { agentId, documentId, id, topicId, toolContext, trigger } = params;
+ const result = await lambdaClient.agentDocument.removeDocument.mutate({
+ agentId,
+ id,
+ toolContext,
+ trigger,
+ });
await invalidateDocumentMutation({
agentDocumentId: id,
agentId,
@@ -198,7 +212,9 @@ class AgentDocumentService {
return result;
};
- copyDocument = async (params: { agentId: string; id: string; newTitle?: string }) => {
+ copyDocument = async (
+ params: { agentId: string; id: string; newTitle?: string } & AgentDocumentToolTriggerInput,
+ ) => {
const result = await lambdaClient.agentDocument.copyDocument.mutate(params);
await invalidateDocumentMutation({
agentDocumentId: getAgentDocumentId(result),
@@ -210,7 +226,9 @@ class AgentDocumentService {
return result;
};
- renameDocument = async (params: { agentId: string; id: string; newTitle: string }) => {
+ renameDocument = async (
+ params: { agentId: string; id: string; newTitle: string } & AgentDocumentToolTriggerInput,
+ ) => {
const result = await lambdaClient.agentDocument.renameDocument.mutate(params);
await invalidateDocumentMutation({
agentDocumentId: params.id,
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 607dded308b..e1b0ec339ad 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -34,6 +34,12 @@ export interface MessageQueryContext {
interface MessageReadQueryContext {
agentId?: string | null;
groupId?: string | null;
+ /**
+ * Skip the Work-summary assembly on the server — set by mid-stream
+ * refetches (tool_end / step_complete) so each tool round doesn't re-run
+ * the per-type Work queries. See `QueryMessageParams.skipWorks`.
+ */
+ skipWorks?: boolean;
threadId?: string | null;
topicId?: string | null;
topicShareId?: string;
diff --git a/src/services/work.test.ts b/src/services/work.test.ts
new file mode 100644
index 00000000000..e5c1d2923dd
--- /dev/null
+++ b/src/services/work.test.ts
@@ -0,0 +1,140 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { isMessageListKey, workKeys } from '@/libs/swr/keys';
+
+const mutate = vi.fn();
+
+vi.mock('@/libs/swr', () => ({
+ mutate: (...args: unknown[]) => mutate(...args),
+}));
+
+// work.ts imports the lambda client at module load; stub it so the service
+// module resolves without a real tRPC client.
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { work: {} },
+}));
+
+// Imported after the mocks so the service binds to the stubbed `mutate`.
+const { didToolMutateWorkView, workService } = await import('./work');
+
+beforeEach(() => {
+ mutate.mockClear();
+});
+
+describe('didToolMutateWorkView', () => {
+ it('detects a Work registration intent', () => {
+ expect(
+ didToolMutateWorkView({
+ apiName: 'createIssue',
+ identifier: 'linear',
+ succeeded: true,
+ workRegistration: true,
+ }),
+ ).toBe(true);
+ });
+
+ it('detects task status mutations without a Work registration intent', () => {
+ expect(
+ didToolMutateWorkView({
+ apiName: 'updateTaskStatus',
+ identifier: 'lobe-task',
+ succeeded: true,
+ workRegistration: false,
+ }),
+ ).toBe(true);
+ });
+
+ it('detects a partially successful runTasks result', () => {
+ expect(
+ didToolMutateWorkView({
+ apiName: 'runTasks',
+ identifier: 'lobe-task',
+ result: { state: { succeeded: 1 } },
+ succeeded: false,
+ workRegistration: false,
+ }),
+ ).toBe(true);
+
+ expect(
+ didToolMutateWorkView({
+ apiName: 'runTasks',
+ identifier: 'lobe-task',
+ succeeded: false,
+ workRegistration: false,
+ }),
+ ).toBe(true);
+ });
+
+ it('ignores read-only and failed task calls', () => {
+ expect(
+ didToolMutateWorkView({
+ apiName: 'listTasks',
+ identifier: 'lobe-task',
+ succeeded: true,
+ workRegistration: false,
+ }),
+ ).toBe(false);
+ expect(
+ didToolMutateWorkView({
+ apiName: 'updateTaskStatus',
+ identifier: 'lobe-task',
+ succeeded: false,
+ workRegistration: false,
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('workService.refreshConversation', () => {
+ it('refreshes messages, history, and mounted version timelines once per operation', async () => {
+ await workService.refreshConversation('t1', 'th1');
+
+ expect(mutate).toHaveBeenCalledTimes(3);
+ expect(mutate).toHaveBeenCalledWith(workKeys.conversation('t1', 'th1'));
+
+ const matchers = mutate.mock.calls
+ .map(([key]) => key)
+ .filter((key): key is (cacheKey: unknown) => boolean => typeof key === 'function');
+ expect(matchers.some((matcher) => matcher(['message:list', { topicId: 't1' }, 1]))).toBe(true);
+ expect(matchers.some((matcher) => matcher(workKeys.versions('w1')))).toBe(true);
+ });
+});
+
+describe('workService.refreshConversationViews', () => {
+ it('refreshes the conversation history key and the mounted version timelines', async () => {
+ await workService.refreshConversationViews('t1', 'th1');
+
+ expect(mutate).toHaveBeenCalledTimes(2);
+ // History list: exact conversation key.
+ expect(mutate).toHaveBeenCalledWith(workKeys.conversation('t1', 'th1'));
+ // Expanded version timelines: a matcher over the `work:versions` root.
+ const versionMatcher = mutate.mock.calls[1][0] as (key: unknown) => boolean;
+ expect(typeof versionMatcher).toBe('function');
+ expect(versionMatcher(workKeys.versions('w1'))).toBe(true);
+ expect(versionMatcher(workKeys.conversation('t1', 'th1'))).toBe(false);
+ });
+
+ it('normalizes a missing threadId to null in the conversation key', async () => {
+ await workService.refreshConversationViews('t1');
+
+ expect(mutate).toHaveBeenCalledWith(workKeys.conversation('t1', null));
+ });
+
+ it('never refreshes the message list or the workspace gallery', async () => {
+ await workService.refreshConversationViews('t1', null);
+
+ const versionMatcher = mutate.mock.calls[1][0] as (key: unknown) => boolean;
+ // The version matcher must not select message-list or cross-topic gallery keys —
+ // Work summaries ride the message payload, and the gallery is out of scope here.
+ expect(isMessageListKey(['message:list', { topicId: 't1' }, 1])).toBe(true);
+ expect(versionMatcher(['message:list', { topicId: 't1' }, 1])).toBe(false);
+ expect(versionMatcher(workKeys.workspace(null, 'all', null))).toBe(false);
+ });
+
+ it('is a no-op without a topicId', async () => {
+ await workService.refreshConversationViews(null, 'th1');
+ await workService.refreshConversationViews(undefined);
+
+ expect(mutate).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/services/work.ts b/src/services/work.ts
new file mode 100644
index 00000000000..4dd994398c0
--- /dev/null
+++ b/src/services/work.ts
@@ -0,0 +1,166 @@
+import { TaskApiName, TaskIdentifier } from '@lobechat/builtin-tool-task';
+import type {
+ RegisterDocumentWorkParams,
+ RegisterSkillToolResultWorkParams,
+ RegisterTaskWorkParams,
+ WorkItem,
+ WorkListItem,
+ WorkSkillProvider,
+ WorkSummaryItem,
+ WorkType,
+ WorkVersionEventItem,
+ WorkVersionEventMap,
+ WorkVersionItem,
+} from '@lobechat/types';
+
+import { mutate } from '@/libs/swr';
+import { isMessageListKey, matchDomain, workKeys } from '@/libs/swr/keys';
+import { lambdaClient } from '@/libs/trpc/client';
+
+/** One cursor page of the workspace-wide Work list (resource page 产物 gallery). */
+export interface WorkSummaryPage {
+ items: WorkSummaryItem[];
+ nextCursor: string | null;
+}
+
+const TASK_WORK_VIEW_MUTATIONS = new Set<string>([
+ TaskApiName.runTask,
+ TaskApiName.runTasks,
+ TaskApiName.updateTaskStatus,
+]);
+
+export const didToolMutateWorkView = ({
+ apiName,
+ identifier,
+ result,
+ succeeded,
+ workRegistration,
+}: {
+ apiName?: string;
+ identifier?: string;
+ result?: { state?: unknown };
+ succeeded: boolean;
+ workRegistration: boolean;
+}): boolean => {
+ if (workRegistration) return true;
+ if (identifier !== TaskIdentifier || !apiName || !TASK_WORK_VIEW_MUTATIONS.has(apiName)) {
+ return false;
+ }
+
+ if (apiName === TaskApiName.runTasks) {
+ const succeededCount = (result?.state as { succeeded?: unknown } | undefined)?.succeeded;
+ return typeof succeededCount === 'number' ? succeededCount > 0 : true;
+ }
+
+ return succeeded;
+};
+
+class WorkService {
+ listByConversation = async (params: {
+ limit?: number;
+ threadId?: string | null;
+ topicId?: string | null;
+ }): Promise<WorkListItem[]> => lambdaClient.work.listByConversation.query(params);
+
+ listByWorkspace = async (params: {
+ cursor?: string | null;
+ limit?: number;
+ provider?: WorkSkillProvider;
+ type?: WorkType | null;
+ }): Promise<WorkSummaryPage> => lambdaClient.work.listByWorkspace.query(params);
+
+ listByRootOperation = async (params: {
+ limit?: number;
+ rootOperationId?: string | null;
+ }): Promise<WorkVersionEventItem[]> => lambdaClient.work.listByRootOperation.query(params);
+
+ listByRootOperations = async (params: {
+ limit?: number;
+ rootOperationIds?: string[] | null;
+ }): Promise<WorkVersionEventMap> => lambdaClient.work.listByRootOperations.query(params);
+
+ listVersions = async (workId: string): Promise<WorkVersionItem[]> =>
+ lambdaClient.work.listVersions.query({ workId });
+
+ registerTask = async (params: RegisterTaskWorkParams): Promise<WorkItem | null> =>
+ lambdaClient.work.registerTask.mutate(params);
+
+ registerDocument = async (params: RegisterDocumentWorkParams): Promise<WorkItem | null> =>
+ lambdaClient.work.registerDocument.mutate(params);
+
+ deleteTaskWork = async (params: { taskId: string }): Promise<void> =>
+ lambdaClient.work.deleteTaskWork.mutate(params);
+
+ handleSkillToolResult = async (
+ params: RegisterSkillToolResultWorkParams,
+ ): Promise<WorkItem | null> => lambdaClient.work.handleSkillToolResult.mutate(params);
+
+ /**
+ * Invalidate everything a Work mutation can change for a conversation:
+ * - the topic's `message:list` entries, since Work summaries (in-message chips
+ * and the sidebar summary view) ride the message payload
+ * - the sidebar history and expanded version views
+ */
+ refreshConversation = async (topicId?: string | null, threadId?: string | null) => {
+ if (!topicId) return;
+ await Promise.all([
+ this.refreshConversationMessages(topicId),
+ this.refreshConversationViews(topicId, threadId),
+ ]);
+ };
+
+ /**
+ * Re-pull the message list for a topic so the Work summaries attached to its
+ * message payload become fresh. `mutate` only refetches mounted keys, so this
+ * is a no-op when the topic isn't the active conversation.
+ */
+ refreshConversationMessages = async (topicId: string) => {
+ await mutate((key) => isMessageListKey(key, (context) => context.topicId === topicId));
+ };
+
+ refreshAll = async () => {
+ await mutate(matchDomain('work:'));
+ };
+
+ /**
+ * Refresh only the sidebar's *lazy* Work caches for a conversation — the
+ * history list ({@link workKeys.conversation}) and any expanded version
+ * timelines ({@link workKeys.versions}). Deliberately narrower than
+ * {@link refreshAll}: it never touches the `message:list` payload (Work
+ * summaries ride the message list and are refreshed by the message fetch
+ * itself) nor the cross-topic workspace gallery (`work:workspace`).
+ *
+ * Called once per agent run at operation end by the runtime transports
+ * (gateway: `agent_runtime_end`; client runtime: the afterCompletion callback
+ * via {@link refreshConversation}) instead of on every tool_end — these lazy
+ * views are an operation-grained concern, so a single settle-time refresh
+ * replaces the per-tool `work.listByConversation` flood. WorksSection only
+ * calls it for Work changes made outside a run (e.g. a manual delete).
+ * `mutate` only revalidates mounted keys, so this is a no-op when the
+ * sidebar is collapsed or showing the summary view.
+ */
+ refreshConversationViews = async (topicId?: string | null, threadId?: string | null) => {
+ if (!topicId) return;
+ await Promise.all([
+ mutate(workKeys.conversation(topicId, threadId ?? null)),
+ mutate((key) => Array.isArray(key) && key[0] === workKeys.versions.root),
+ ]);
+ };
+
+ /**
+ * Broad invalidation for Work mutations without a single-topic scope (e.g.
+ * task deletion, which can orphan Works across topics into a "task deleted"
+ * state). Refreshes every mounted `message:list` — since Work summaries ride
+ * the message payload — plus the whole work domain for the sidebar caches.
+ */
+ refreshAllConversations = async () => {
+ await Promise.all([mutate((key) => isMessageListKey(key)), this.refreshAll()]);
+ };
+
+ refreshVersions = async (workId?: string | null) => {
+ if (!workId) return;
+ await mutate(workKeys.versions(workId));
+ };
+}
+
+export const workService = new WorkService();
diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts
index 17245d896bb..bd1b30d5355 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts
@@ -3,7 +3,9 @@ import { type ChatToolPayload } from '@lobechat/types';
import { type Mock } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
+import { registerClientWorkFromIntent } from '@/store/chat/agents/registerClientWorkFromIntent';
import { type OperationCancelContext } from '@/store/chat/slices/operation/types';
+import { stashWorkIntent } from '@/utils/clientWorkIntentStash';
import { createAssistantMessage, createCallToolInstruction, createMockStore } from './fixtures';
import {
@@ -27,6 +29,10 @@ vi.mock('@/utils/localStorage', () => {
return { AsyncLocalStorage };
});
+vi.mock('@/store/chat/agents/registerClientWorkFromIntent', () => ({
+ registerClientWorkFromIntent: vi.fn().mockResolvedValue(undefined),
+}));
+
describe('call_tool executor', () => {
describe('Basic Behavior', () => {
it('should create tool message and execute tool successfully', async () => {
@@ -68,6 +74,204 @@ describe('call_tool executor', () => {
expect(mockStore.internal_invokeDifferentTypePlugin).toHaveBeenCalledTimes(1);
});
+ it('should register the stashed work intent with the accumulated cost after execution', async () => {
+ vi.mocked(registerClientWorkFromIntent).mockClear();
+
+ const mockStore = createMockStore({ registerAfterCompletionCallback: vi.fn() });
+ const context = createTestContext({ operationId: 'root-op-1' });
+
+ const assistantMessage = createAssistantMessage({ groupId: 'group_123' });
+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];
+
+ const toolCall: ChatToolPayload = {
+ apiName: 'search',
+ arguments: JSON.stringify({ query: 'test query' }),
+ id: 'tool_call_usage',
+ identifier: 'lobe-web-browsing',
+ type: 'default',
+ };
+
+ // A registration site (builtin/skill/document dispatch) stashes the intent
+ // while the tool runs; `call_tool` drains it AFTER cost is accumulated.
+ stashWorkIntent('tool_call_usage', {
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: 'task_1', taskIdentifier: 'task-one' }],
+ type: 'task',
+ });
+
+ const instruction = createCallToolInstruction(toolCall, { parentMessageId: 'msg_parent' });
+ const state = createInitialState({
+ cost: {
+ calculatedAt: '2026-06-30T08:00:00.000Z',
+ currency: 'USD',
+ llm: { byModel: [], currency: 'USD', total: 0.01 },
+ tools: { byTool: [], currency: 'USD', total: 0 },
+ total: 0.01,
+ },
+ operationId: 'root-op-1',
+ });
+
+ await executeWithMockContext({
+ executor: 'call_tool',
+ instruction,
+ state,
+ mockStore,
+ context,
+ });
+
+ expect(registerClientWorkFromIntent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ intent: expect.objectContaining({ type: 'task' }),
+ rootOperationId: 'root-op-1',
+ sourceToolCallId: 'tool_call_usage',
+ sourceToolName: 'search',
+ // `newState.cost` carries the tool cost (0.01 base + 0.001 search) so
+ // the version row is written once with its cumulative cost.
+ state: expect.objectContaining({
+ cost: expect.objectContaining({ total: 0.011 }),
+ usage: expect.objectContaining({
+ tools: expect.objectContaining({ totalCalls: 1 }),
+ }),
+ }),
+ }),
+ );
+ expect(mockStore.registerAfterCompletionCallback).toHaveBeenCalledWith(
+ 'root-op-1',
+ expect.any(Function),
+ );
+ });
+
+ it('should not register work when no intent was stashed for the tool call', async () => {
+ vi.mocked(registerClientWorkFromIntent).mockClear();
+
+ const mockStore = createMockStore({ registerAfterCompletionCallback: vi.fn() });
+ const context = createTestContext({ operationId: 'root-op-1' });
+
+ const assistantMessage = createAssistantMessage({ groupId: 'group_123' });
+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];
+
+ const toolCall: ChatToolPayload = {
+ apiName: 'search',
+ arguments: JSON.stringify({ query: 'test query' }),
+ id: 'tool_call_no_intent',
+ identifier: 'lobe-web-browsing',
+ type: 'default',
+ };
+
+ const instruction = createCallToolInstruction(toolCall, { parentMessageId: 'msg_parent' });
+ const state = createInitialState({ operationId: 'root-op-1' });
+
+ await executeWithMockContext({
+ executor: 'call_tool',
+ instruction,
+ state,
+ mockStore,
+ context,
+ });
+
+ expect(registerClientWorkFromIntent).not.toHaveBeenCalled();
+ expect(mockStore.registerAfterCompletionCallback).not.toHaveBeenCalled();
+ });
+
+ it('should await work registration before completing the tool step', async () => {
+ vi.mocked(registerClientWorkFromIntent).mockClear();
+ let resolveRegistration!: () => void;
+ vi.mocked(registerClientWorkFromIntent).mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveRegistration = resolve;
+ }),
+ );
+
+ const mockStore = createMockStore({ registerAfterCompletionCallback: vi.fn() });
+ const context = createTestContext({ operationId: 'root-op-1' });
+
+ const assistantMessage = createAssistantMessage({ groupId: 'group_123' });
+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];
+
+ const toolCall: ChatToolPayload = {
+ apiName: 'search',
+ arguments: JSON.stringify({ query: 'test query' }),
+ id: 'tool_call_blocking',
+ identifier: 'lobe-web-browsing',
+ type: 'default',
+ };
+
+ stashWorkIntent('tool_call_blocking', {
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: 'task_blocking' }],
+ type: 'task',
+ });
+
+ const instruction = createCallToolInstruction(toolCall, { parentMessageId: 'msg_parent' });
+ const state = createInitialState({ operationId: 'root-op-1' });
+
+ let settled = false;
+ const execution = executeWithMockContext({
+ executor: 'call_tool',
+ instruction,
+ state,
+ mockStore,
+ context,
+ }).finally(() => {
+ settled = true;
+ });
+
+ await vi.waitFor(() => {
+ expect(registerClientWorkFromIntent).toHaveBeenCalledWith(
+ expect.objectContaining({ sourceToolCallId: 'tool_call_blocking' }),
+ );
+ });
+ expect(settled).toBe(false);
+
+ resolveRegistration();
+ const result = await execution;
+ expect(result.events).toHaveLength(1);
+ expect(settled).toBe(true);
+ });
+
+ it('should schedule one operation-end refresh for a task status mutation', async () => {
+ vi.mocked(registerClientWorkFromIntent).mockClear();
+
+ const mockStore = createMockStore({ registerAfterCompletionCallback: vi.fn() });
+ const context = createTestContext({ operationId: 'root-op-1' });
+ mockStore.dbMessagesMap[context.messageKey] = [
+ createAssistantMessage({ groupId: 'group_123' }),
+ ];
+ mockStore.internal_invokeDifferentTypePlugin = vi.fn().mockResolvedValue({
+ content: 'Task T-1 status updated to completed.',
+ state: { status: 'completed', success: true },
+ success: true,
+ });
+
+ const instruction = createCallToolInstruction(
+ {
+ apiName: 'updateTaskStatus',
+ arguments: JSON.stringify({ identifier: 'T-1', status: 'completed' }),
+ id: 'tool_call_status',
+ identifier: 'lobe-task',
+ type: 'default',
+ },
+ { parentMessageId: 'msg_parent' },
+ );
+
+ await executeWithMockContext({
+ executor: 'call_tool',
+ instruction,
+ state: createInitialState({ operationId: 'root-op-1' }),
+ mockStore,
+ context,
+ });
+
+ expect(registerClientWorkFromIntent).not.toHaveBeenCalled();
+ expect(mockStore.registerAfterCompletionCallback).toHaveBeenCalledWith(
+ 'root-op-1',
+ expect.any(Function),
+ );
+ });
+
it('should call internal_invokeDifferentTypePlugin with correct parameters', async () => {
// Given
const mockStore = createMockStore();
diff --git a/src/store/chat/agents/__tests__/registerClientWorkFromIntent.test.ts b/src/store/chat/agents/__tests__/registerClientWorkFromIntent.test.ts
new file mode 100644
index 00000000000..f0dbf0b68ae
--- /dev/null
+++ b/src/store/chat/agents/__tests__/registerClientWorkFromIntent.test.ts
@@ -0,0 +1,205 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ deleteTaskWork: vi.fn(),
+ handleSkillToolResult: vi.fn(),
+ refreshConversation: vi.fn(),
+ registerDocument: vi.fn(),
+ registerTask: vi.fn(),
+}));
+
+vi.mock('@/services/work', () => ({
+ workService: {
+ deleteTaskWork: mocks.deleteTaskWork,
+ handleSkillToolResult: mocks.handleSkillToolResult,
+ refreshConversation: mocks.refreshConversation,
+ registerDocument: mocks.registerDocument,
+ registerTask: mocks.registerTask,
+ },
+}));
+
+const { registerClientWorkFromIntent } = await import('../registerClientWorkFromIntent');
+
+const state: Pick<AgentState, 'cost' | 'usage'> = {
+ cost: {
+ calculatedAt: '2026-06-30T08:00:00.000Z',
+ currency: 'USD',
+ llm: { byModel: [], currency: 'USD', total: 0.01 },
+ tools: { byTool: [], currency: 'USD', total: 0.001 },
+ total: 0.011,
+ },
+ usage: {
+ llm: {} as any,
+ tools: { byTool: [], totalCalls: 1, totalTimeMs: 10 },
+ } as any,
+};
+
+const base = {
+ agentId: 'agent-1',
+ rootOperationId: 'op-root',
+ sourceMessageId: 'msg-tool-1',
+ sourceToolCallId: 'tool-call-1',
+ sourceToolIdentifier: 'lobe-task',
+ sourceToolName: 'createTask',
+ state,
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+};
+
+describe('registerClientWorkFromIntent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.registerTask.mockResolvedValue({ id: 'work-1' });
+ mocks.registerDocument.mockResolvedValue({ id: 'doc-work-1' });
+ mocks.deleteTaskWork.mockResolvedValue(undefined);
+ mocks.handleSkillToolResult.mockResolvedValue({ id: 'skill-work-1' });
+ mocks.refreshConversation.mockResolvedValue(undefined);
+ });
+
+ describe('task', () => {
+ it('registers each created target with the cumulative cost without refreshing per tool', async () => {
+ await registerClientWorkFromIntent({
+ ...base,
+ intent: {
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ type: 'task',
+ },
+ });
+
+ expect(mocks.registerTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ cumulativeCost: 0.011,
+ cumulativeUsage: expect.objectContaining({
+ cost: expect.objectContaining({ total: 0.011 }),
+ }),
+ changeType: 'created',
+ messageId: 'msg-tool-1',
+ rootOperationId: 'op-root',
+ taskId: 'task_1',
+ taskIdentifier: 'T-1',
+ threadId: 'thread-1',
+ toolCallId: 'tool-call-1',
+ toolName: 'createTask',
+ topicId: 'topic-1',
+ }),
+ );
+ // The runtime settles Work caches once at operation end — no per-tool flood.
+ expect(mocks.refreshConversation).not.toHaveBeenCalled();
+ });
+
+ it('deletes the task work per target without refreshing the message list', async () => {
+ await registerClientWorkFromIntent({
+ ...base,
+ intent: { action: 'delete', targets: [{ taskId: 'task_1' }], type: 'task' },
+ });
+
+ expect(mocks.deleteTaskWork).toHaveBeenCalledWith({ taskId: 'task_1' });
+ expect(mocks.registerTask).not.toHaveBeenCalled();
+ expect(mocks.refreshConversation).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op for a create/update intent without a changeType', async () => {
+ await registerClientWorkFromIntent({
+ ...base,
+ // deliberately malformed: create intent missing changeType
+ intent: { action: 'create', targets: [{ taskId: 'task_1' }], type: 'task' },
+ });
+
+ expect(mocks.registerTask).not.toHaveBeenCalled();
+ expect(mocks.refreshConversation).not.toHaveBeenCalled();
+ });
+
+ it('swallows registerTask errors (best-effort, never throws)', async () => {
+ mocks.registerTask.mockRejectedValueOnce(new Error('trpc died'));
+
+ await expect(
+ registerClientWorkFromIntent({
+ ...base,
+ intent: {
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: 'task_1' }],
+ type: 'task',
+ },
+ }),
+ ).resolves.toBeUndefined();
+ });
+ });
+
+ describe('document', () => {
+ it('registers a document with the cumulative cost without refreshing per tool', async () => {
+ await registerClientWorkFromIntent({
+ ...base,
+ sourceToolName: 'createDocument',
+ intent: {
+ action: 'register',
+ document: {
+ agentId: 'agent-1',
+ documentId: 'doc_1',
+ changeType: 'created',
+ toolName: 'createDocument',
+ },
+ type: 'document',
+ },
+ });
+
+ expect(mocks.registerDocument).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cumulativeCost: 0.011,
+ documentId: 'doc_1',
+ changeType: 'created',
+ rootOperationId: 'op-root',
+ toolCallId: 'tool-call-1',
+ toolName: 'createDocument',
+ }),
+ );
+ expect(mocks.refreshConversation).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op for a document delete intent (deletes stay lambda-side)', async () => {
+ await registerClientWorkFromIntent({
+ ...base,
+ intent: {
+ action: 'delete',
+ document: { documentId: 'doc_1' },
+ type: 'document',
+ },
+ });
+
+ expect(mocks.registerDocument).not.toHaveBeenCalled();
+ expect(mocks.refreshConversation).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('skill', () => {
+ it('forwards the skill payload to handleSkillToolResult with the cumulative cost', async () => {
+ await registerClientWorkFromIntent({
+ ...base,
+ sourceToolName: 'createIssue',
+ intent: {
+ args: { title: 'x' },
+ data: { url: 'https://linear.app/x' },
+ provider: 'linear',
+ toolName: 'createIssue',
+ type: 'skill',
+ },
+ });
+
+ expect(mocks.handleSkillToolResult).toHaveBeenCalledWith(
+ expect.objectContaining({
+ args: { title: 'x' },
+ cumulativeCost: 0.011,
+ data: { url: 'https://linear.app/x' },
+ provider: 'linear',
+ rootOperationId: 'op-root',
+ toolCallId: 'tool-call-1',
+ toolName: 'createIssue',
+ }),
+ );
+ });
+ });
+});
diff --git a/src/store/chat/agents/registerClientWorkFromIntent.ts b/src/store/chat/agents/registerClientWorkFromIntent.ts
new file mode 100644
index 00000000000..a324a426d10
--- /dev/null
+++ b/src/store/chat/agents/registerClientWorkFromIntent.ts
@@ -0,0 +1,85 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+import { dispatchWorkRegistrationIntent } from '@lobechat/builtin-tools/workRegistration';
+import type { WorkRegistrationIntent } from '@lobechat/types';
+import debug from 'debug';
+
+import { workService } from '@/services/work';
+import { buildWorkVersionCumulativeUsage } from '@/utils/workCumulativeUsage';
+
+const log = debug('lobe-store:client-work-registration');
+
+interface RegisterClientWorkFromIntentParams {
+ agentId?: string | null;
+ intent: WorkRegistrationIntent;
+ rootOperationId?: string;
+ sourceMessageId?: string;
+ sourceToolCallId?: string;
+ /** Tool/plugin identifier supplied by the runtime event that produced this version. */
+ sourceToolIdentifier: string;
+ /** Runtime event's concrete tool name; skills/documents may carry their own. */
+ sourceToolName: string;
+ state: Pick<AgentState, 'cost' | 'usage'>;
+ threadId?: string | null;
+ topicId?: string;
+}
+
+/**
+ * Client (legacy, non-gateway) mirror of the server runtime's
+ * `registerWorkFromIntent`. Persists a Work version from the tool-execution
+ * layer's registration intent, stamping the tool call's cumulative cost/usage
+ * onto the row at insert time.
+ *
+ * Thin wrapper around the shared {@link dispatchWorkRegistrationIntent}: builds
+ * `workService`-backed ports and per-call provenance, then delegates all branch
+ * logic. Replaces the old client "register cost-less during execution, back-fill
+ * cost with a follow-up `updateVersionCumulativeUsage`" two-step: the executors
+ * now only stash the intent (see {@link stashWorkIntent}) and `call_tool` writes
+ * it once here, after `UsageCounter.accumulateTool` has computed the cost.
+ *
+ * Best-effort: any failure is swallowed so Work bookkeeping never breaks the
+ * tool result. `call_tool` awaits the write so its operation-end refresh cannot
+ * race ahead of the persisted Work. No SWR cache is refreshed per tool.
+ */
+export const registerClientWorkFromIntent = async ({
+ agentId,
+ intent,
+ rootOperationId,
+ sourceMessageId,
+ sourceToolCallId,
+ sourceToolIdentifier,
+ sourceToolName,
+ state,
+ threadId,
+ topicId,
+}: RegisterClientWorkFromIntentParams): Promise<void> => {
+ const cumulative = buildWorkVersionCumulativeUsage({ cost: state.cost, usage: state.usage });
+
+ try {
+ await dispatchWorkRegistrationIntent(
+ intent,
+ {
+ // Document deletes are NOT handled client-side — they stay a lambda-side
+ // side-effect of the removeDocument mutation (a deletion carries no cost,
+ // so it needs no cost-stamping defer). Omitting the port makes the
+ // document-delete intent a no-op.
+ deleteTaskWork: (params) => workService.deleteTaskWork(params),
+ handleSkillToolResult: (params) => workService.handleSkillToolResult(params),
+ registerDocument: (params) => workService.registerDocument(params),
+ registerTask: (params) => workService.registerTask(params),
+ },
+ {
+ agentId,
+ ...cumulative,
+ messageId: sourceMessageId,
+ rootOperationId,
+ threadId,
+ toolCallId: sourceToolCallId,
+ toolIdentifier: sourceToolIdentifier,
+ toolName: sourceToolName,
+ topicId,
+ },
+ );
+ } catch (error) {
+ log('registerClientWorkFromIntent failed for toolCallId=%s: %O', sourceToolCallId, error);
+ }
+};
diff --git a/src/store/chat/agents/transports/ClientToolTransport.test.ts b/src/store/chat/agents/transports/ClientToolTransport.test.ts
index 72414cfed37..4452e820538 100644
--- a/src/store/chat/agents/transports/ClientToolTransport.test.ts
+++ b/src/store/chat/agents/transports/ClientToolTransport.test.ts
@@ -1,12 +1,24 @@
import type { ToolRunContext } from '@lobechat/agent-runtime';
import type { ChatToolPayload } from '@lobechat/types';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ChatStore } from '@/store/chat/store';
+import { takeWorkIntent } from '@/utils/clientWorkIntentStash';
import type { ClientMessageTransport } from './ClientMessageTransport';
import { ClientToolTransport } from './ClientToolTransport';
+vi.mock('@/utils/clientWorkIntentStash', () => ({
+ stashWorkIntent: vi.fn(),
+ takeWorkIntent: vi.fn(),
+}));
+
+const takeWorkIntentMock = vi.mocked(takeWorkIntent);
+
+beforeEach(() => {
+ takeWorkIntentMock.mockReset();
+});
+
describe('ClientToolTransport', () => {
it('preserves an explicit unsuccessful tool result without an error', async () => {
const completeOperation = vi.fn();
@@ -76,4 +88,61 @@ describe('ClientToolTransport', () => {
);
expect(store.optimisticCreateMessage).not.toHaveBeenCalled();
});
+
+ it('always drains the stashed Work intent even when the tool invoke throws', async () => {
+ const failOperation = vi.fn();
+ let operationIndex = 0;
+ const store = {
+ completeOperation: vi.fn(),
+ dbMessagesMap: {
+ 'message-key': [{ id: 'assistant-message', parentId: 'user-message', role: 'assistant' }],
+ },
+ failOperation,
+ // The invoke rejects — the stash must still be drained for this toolCallId.
+ internal_invokeDifferentTypePlugin: vi.fn().mockRejectedValue(new Error('invoke boom')),
+ onOperationCancel: vi.fn(),
+ operations: {
+ 'root-operation': {
+ context: { agentId: 'agent-1', messageId: 'assistant-message' },
+ },
+ },
+ optimisticCreateMessage: vi.fn().mockResolvedValue({ id: 'tool-message' }),
+ startOperation: vi.fn(() => ({ operationId: `child-operation-${++operationIndex}` })),
+ updateOperationMetadata: vi.fn(),
+ } as unknown as ChatStore;
+ const messages = {
+ createToolMessageForOperation: vi.fn().mockResolvedValue({ id: 'tool-message' }),
+ } as unknown as ClientMessageTransport;
+ const transport = new ClientToolTransport(
+ () => store,
+ 'message-key',
+ 'root-operation',
+ messages,
+ );
+ const call: ChatToolPayload = {
+ apiName: 'run',
+ arguments: '{}',
+ id: 'tool-call',
+ identifier: 'client-tool',
+ type: 'default',
+ };
+ const context = {
+ callIndex: 1,
+ effectiveManifestMap: {},
+ mode: 'single',
+ operationId: 'root-operation',
+ parentMessageId: 'tool-message',
+ parsedArgs: {},
+ reuseExistingMessage: true,
+ state: {},
+ stepIndex: 0,
+ toolName: 'client-tool/run',
+ } as ToolRunContext;
+
+ await expect(transport.run(call, context)).rejects.toThrow('invoke boom');
+
+ // The stash entry for this toolCallId was drained despite the throw.
+ expect(takeWorkIntentMock).toHaveBeenCalledWith('tool-call');
+ expect(failOperation).toHaveBeenCalled();
+ });
});
diff --git a/src/store/chat/agents/transports/ClientToolTransport.ts b/src/store/chat/agents/transports/ClientToolTransport.ts
index 1162de019d5..364b4cc68f7 100644
--- a/src/store/chat/agents/transports/ClientToolTransport.ts
+++ b/src/store/chat/agents/transports/ClientToolTransport.ts
@@ -3,11 +3,15 @@ import type {
ToolRunExecution,
ToolRunResult,
ToolTransport,
+ ToolWorkRegistration,
} from '@lobechat/agent-runtime';
import type { ChatToolPayload, CreateMessageParams } from '@lobechat/types';
+import { didToolMutateWorkView, workService } from '@/services/work';
import type { ChatStore } from '@/store/chat/store';
+import { takeWorkIntent } from '@/utils/clientWorkIntentStash';
+import { registerClientWorkFromIntent } from '../registerClientWorkFromIntent';
import type { ClientMessageTransport } from './ClientMessageTransport';
const TOOL_PRICING: Record<string, number> = {
@@ -115,11 +119,24 @@ export class ClientToolTransport implements ToolTransport {
});
const startedAt = performance.now();
- const rawResult = await store.internal_invokeDifferentTypePlugin(
- toolMessageId,
- call,
- context.stepContext,
- );
+ let rawResult: Awaited<ReturnType<typeof store.internal_invokeDifferentTypePlugin>>;
+ let workIntent: ReturnType<typeof takeWorkIntent>;
+ try {
+ rawResult = await store.internal_invokeDifferentTypePlugin(
+ toolMessageId,
+ call,
+ context.stepContext,
+ );
+ } finally {
+ // Drain the Work-registration intent stashed during tool execution in a
+ // `finally` so the per-`toolCallId` entry is ALWAYS freed — even when the
+ // invoke throws — otherwise a rejected tool call would leak its stash
+ // entry in the module-level Map forever. On the throw path the drained
+ // intent is simply discarded (the error propagates to the outer catch);
+ // on success the actual write happens later in `registerWork`, once the
+ // executor knows the cumulative cost.
+ workIntent = takeWorkIntent(call.id);
+ }
if (store.operations[executeOperationId]?.abortController.signal.aborted) {
return this.createInterruptedExecution(toolMessageId);
@@ -139,6 +156,22 @@ export class ClientToolTransport implements ToolTransport {
});
}
+ if (rawResult !== undefined && rawResult !== null) {
+ if (workIntent) result.workRegistration = workIntent;
+
+ if (
+ didToolMutateWorkView({
+ apiName: call.apiName,
+ identifier: call.identifier,
+ result,
+ succeeded: result.success,
+ workRegistration: Boolean(workIntent),
+ })
+ ) {
+ this.scheduleWorkRefresh();
+ }
+ }
+
return {
attempts: 1,
result,
@@ -154,6 +187,46 @@ export class ClientToolTransport implements ToolTransport {
}
}
+ /**
+ * Client (legacy, non-gateway) mirror of the server runtime's Work
+ * registration: persists the Work version with the cumulative cost the
+ * executor stamped on the registration.
+ */
+ async registerWork(registration: ToolWorkRegistration) {
+ const opContext = this.get().operations[this.operationId]?.context;
+
+ await registerClientWorkFromIntent({
+ agentId: opContext?.agentId,
+ intent: registration.intent,
+ rootOperationId: this.operationId,
+ sourceMessageId: registration.sourceMessageId,
+ sourceToolCallId: registration.sourceToolCallId,
+ sourceToolIdentifier: registration.sourceToolIdentifier,
+ sourceToolName: registration.sourceToolName,
+ state: registration.state,
+ threadId: opContext?.threadId,
+ topicId: opContext?.topicId ?? undefined,
+ });
+ }
+
+ /**
+ * Settle Work caches once at root-operation end. A fresh transport is built
+ * per tool instruction, so the "scheduled once" flag lives on the root
+ * operation's metadata instead of an instance field.
+ */
+ private scheduleWorkRefresh() {
+ const store = this.get();
+ const operation = store.operations[this.operationId];
+ if (!operation || operation.metadata.workRefreshScheduled) return;
+
+ store.updateOperationMetadata(this.operationId, { workRefreshScheduled: true });
+
+ const { threadId, topicId } = operation.context;
+ store.registerAfterCompletionCallback(this.operationId, () =>
+ workService.refreshConversation(topicId ?? undefined, threadId),
+ );
+ }
+
private async createToolMessage(input: {
assistantGroupId?: string;
call: ChatToolPayload;
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts
index a7080519fc0..6b50b8f5b48 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts
@@ -1,6 +1,9 @@
import type { ToolExecuteData } from '@lobechat/agent-gateway-client';
+import type { WorkRegistrationIntent } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { stashWorkIntent, takeWorkIntent } from '@/utils/clientWorkIntentStash';
+
import { ClientToolExecutionActionImpl } from '../transports/client/clientToolExecution';
// ─── Hoisted mocks ───
@@ -99,7 +102,10 @@ describe('internal_executeClientTool', () => {
});
const { action, sendToolResult } = setup();
- await action.internal_executeClientTool(makeData(), { operationId: 'op-1' });
+ await action.internal_executeClientTool(
+ makeData({ assistantMessageId: 'msg-assistant', toolMessageId: 'msg-tool' }),
+ { operationId: 'op-1' },
+ );
expect(invokeExecutorMock).toHaveBeenCalledWith(
'local-system',
@@ -107,10 +113,14 @@ describe('internal_executeClientTool', () => {
{ path: '/tmp/a.txt' },
expect.objectContaining({
agentId: 'agent-1',
+ anchorMessageId: 'msg-assistant',
documentId: 'documents-row-id',
- messageId: 'call_1',
+ messageId: 'msg-tool',
operationId: 'op-1',
+ rootOperationId: 'op-1',
scope: 'page',
+ toolCallId: 'call_1',
+ toolMessageId: 'msg-tool',
topicId: 'topic-1',
}),
);
@@ -122,6 +132,70 @@ describe('internal_executeClientTool', () => {
});
});
+ it('uses server payload context when the gateway connection id differs from the local operation id', async () => {
+ hasExecutorMock.mockReturnValue(true);
+ invokeExecutorMock.mockResolvedValue({
+ content: 'task created',
+ success: true,
+ });
+ const { action, sendToolResult, state } = setup();
+ state.gatewayConnections['gw-op-server'] = state.gatewayConnections['op-1'];
+ delete state.gatewayConnections['op-1'];
+ state.operations['op-local'] = {
+ abortController: { abort: vi.fn(), signal: { aborted: false } },
+ context: {
+ agentId: 'local-agent',
+ scope: 'session',
+ topicId: 'local-topic',
+ },
+ };
+ delete state.operations['op-1'];
+
+ await action.internal_executeClientTool(
+ makeData({
+ agentId: 'agent-from-server',
+ assistantMessageId: 'msg-assistant',
+ documentId: 'doc-from-server',
+ groupId: 'group-from-server',
+ rootOperationId: 'op-root-server',
+ scope: 'thread',
+ sourceMessageId: 'msg-user',
+ taskId: 'task-from-server',
+ threadId: 'thread-from-server',
+ toolMessageId: 'msg-tool',
+ topicId: 'topic-from-server',
+ }),
+ { localOperationId: 'op-local', operationId: 'gw-op-server' },
+ );
+
+ expect(invokeExecutorMock).toHaveBeenCalledWith(
+ 'local-system',
+ 'readFile',
+ { path: '/tmp/a.txt' },
+ expect.objectContaining({
+ agentId: 'agent-from-server',
+ documentId: 'doc-from-server',
+ groupId: 'group-from-server',
+ messageId: 'msg-tool',
+ operationId: 'gw-op-server',
+ rootOperationId: 'op-root-server',
+ scope: 'thread',
+ sourceMessageId: 'msg-user',
+ taskId: 'task-from-server',
+ threadId: 'thread-from-server',
+ toolCallId: 'call_1',
+ topicId: 'topic-from-server',
+ }),
+ );
+ expect(sendToolResult).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'task created',
+ success: true,
+ toolCallId: 'call_1',
+ }),
+ );
+ });
+
it('sends a failure tool_result when the executor reports error', async () => {
hasExecutorMock.mockReturnValue(true);
invokeExecutorMock.mockResolvedValue({
@@ -159,6 +233,66 @@ describe('internal_executeClientTool', () => {
});
});
+ describe('Work registration relay', () => {
+ it('relays the stashed Work intent on the tool_result and drains the stash', async () => {
+ const intent: WorkRegistrationIntent = {
+ action: 'create',
+ targets: [{ taskId: 't-1' }],
+ type: 'task',
+ };
+ hasExecutorMock.mockReturnValue(true);
+ // Mirror `invokeExecutor` → `stashBuiltinToolWorkIntent`: the executor
+ // stashes the Work intent keyed by toolCallId during execution.
+ invokeExecutorMock.mockImplementation(async (_id, _api, _params, ctx: any) => {
+ stashWorkIntent(ctx.toolCallId, intent);
+ return { content: 'task created', success: true };
+ });
+ const { action, sendToolResult } = setup();
+
+ await action.internal_executeClientTool(makeData(), { operationId: 'op-1' });
+
+ expect(sendToolResult).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'task created',
+ success: true,
+ toolCallId: 'call_1',
+ workRegistration: intent,
+ }),
+ );
+ // The action drained the intent — nothing left in the module-level stash.
+ expect(takeWorkIntent('call_1')).toBeUndefined();
+ });
+
+ it('frees a stashed Work intent via the finally leak guard when the executor throws', async () => {
+ const intent: WorkRegistrationIntent = {
+ action: 'create',
+ targets: [{ taskId: 't-2' }],
+ type: 'task',
+ };
+ hasExecutorMock.mockReturnValue(true);
+ invokeExecutorMock.mockImplementation(async () => {
+ // Stash before throwing, as a mid-execution side-effect would; the normal
+ // drain point is never reached on the throw path.
+ stashWorkIntent('call_1', intent);
+ throw new Error('ipc died');
+ });
+ const { action, sendToolResult } = setup();
+
+ await action.internal_executeClientTool(makeData(), { operationId: 'op-1' });
+
+ // Error result is sent (no workRegistration relayed on the throw path).
+ expect(sendToolResult).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error: expect.objectContaining({ type: 'client_tool_execution_error' }),
+ success: false,
+ toolCallId: 'call_1',
+ }),
+ );
+ // Leak guard in the finally block drained the orphaned entry.
+ expect(takeWorkIntent('call_1')).toBeUndefined();
+ });
+ });
+
describe('error paths never block the server', () => {
it('sends tool_result with parse error when arguments are malformed', async () => {
hasExecutorMock.mockReturnValue(true);
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
index d0fc340f92c..d868788eda4 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
@@ -2,6 +2,8 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { messageService } from '@/services/message';
+import type * as WorkServiceModule from '@/services/work';
+import { workService } from '@/services/work';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
@@ -14,6 +16,15 @@ vi.mock('@/services/message', () => ({
updateMessageError: vi.fn().mockResolvedValue({ success: true }),
},
}));
+vi.mock('@/services/work', async (importOriginal) => {
+ const actual = await importOriginal<typeof WorkServiceModule>();
+ return {
+ ...actual,
+ workService: {
+ refreshConversationViews: vi.fn().mockResolvedValue(undefined),
+ },
+ };
+});
vi.mock('@/store/chat/utils/desktopNotification', () => ({
notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),
}));
@@ -612,6 +623,7 @@ describe('createGatewayEventHandler', () => {
await flush();
expect(store.internal_executeClientTool).toHaveBeenCalledWith(toolExecuteData, {
+ localOperationId: 'op-1',
operationId: 'op-1',
});
});
@@ -628,6 +640,7 @@ describe('createGatewayEventHandler', () => {
await flush();
expect(store.internal_executeClientTool).toHaveBeenCalledWith(toolExecuteData, {
+ localOperationId: 'op-1',
operationId: 'gw-op-server',
});
});
@@ -810,6 +823,33 @@ describe('createGatewayEventHandler', () => {
expect(store.completeOperation).toHaveBeenCalledWith('op-1');
expect(store.replaceMessages).toHaveBeenCalled();
+ expect(workService.refreshConversationViews).not.toHaveBeenCalled();
+ });
+
+ it('should refresh Work views once after a run with a Work-mutating tool', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(
+ makeEvent('tool_end', {
+ isSuccess: true,
+ payload: {
+ parentMessageId: 'msg-parent',
+ toolCalling: {
+ apiName: 'createTask',
+ arguments: '{}',
+ id: 'tool-call-1',
+ identifier: 'lobe-task',
+ },
+ },
+ result: { success: true, workRegistration: { type: 'task' } },
+ }),
+ );
+ handler(makeEvent('agent_runtime_end', { uiMessages: [] }));
+ await flush();
+
+ expect(workService.refreshConversationViews).toHaveBeenCalledTimes(1);
+ expect(workService.refreshConversationViews).toHaveBeenCalledWith('topic-1', undefined);
});
it('should emit runtime end signal with the current assistant message id', async () => {
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index af3abbb1ca7..eee37a9c5a0 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -1495,6 +1495,7 @@ export class ConversationLifecycleActionImpl {
parentOperationId: operationId,
inPortalThread: !!data.createdThreadId,
skipCreateFirstMessage: true,
+ userMessageId: data.userMessageId,
});
}
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts b/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts
index 473b53561eb..2249d1bd153 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts
@@ -7,6 +7,7 @@ import { mcpService } from '@/services/mcp';
import { type ChatStore } from '@/store/chat/store';
import { hasExecutor, invokeExecutor } from '@/store/tool/slices/builtin/executors';
import { type StoreSetter } from '@/store/types';
+import { takeWorkIntent } from '@/utils/clientWorkIntentStash';
import { safeParseJSON } from '@/utils/safeParseJSON';
const log = debug('lobe-store:client-tool-execution');
@@ -63,10 +64,27 @@ export class ClientToolExecutionActionImpl {
internal_executeClientTool = async (
data: ToolExecuteData,
- context: { operationId: string },
+ context: { localOperationId?: string; operationId: string },
): Promise<void> => {
- const { toolCallId, identifier, apiName, arguments: argsString, executionTimeoutMs } = data;
- const { operationId } = context;
+ const {
+ apiName,
+ agentId,
+ arguments: argsString,
+ assistantMessageId,
+ documentId,
+ executionTimeoutMs,
+ groupId,
+ identifier,
+ rootOperationId,
+ scope,
+ sourceMessageId,
+ taskId,
+ threadId,
+ toolCallId,
+ toolMessageId,
+ topicId,
+ } = data;
+ const { localOperationId, operationId } = context;
log(
'[internal_executeClientTool] start toolCallId=%s identifier=%s apiName=%s op=%s timeout=%dms',
@@ -129,22 +147,28 @@ export class ClientToolExecutionActionImpl {
params = parsed ?? {};
}
- const operation = this.#get().operations[operationId];
+ const operation = this.#get().operations[localOperationId ?? operationId];
// ─── Builtin dispatch (via registry) ───
if (hasExecutor(identifier, apiName)) {
const ctx: BuiltinToolContext = {
- agentId: operation?.context?.agentId,
- documentId: operation?.context?.documentId,
- groupId: operation?.context?.groupId,
+ agentId: agentId ?? operation?.context?.agentId,
+ anchorMessageId: assistantMessageId,
+ documentId: documentId ?? operation?.context?.documentId,
+ groupId: groupId ?? operation?.context?.groupId,
// Gateway-side tool messages are persisted on the server; the client
// has no local message id, so reuse toolCallId as the context key.
- messageId: toolCallId,
+ messageId: toolMessageId ?? toolCallId,
operationId,
- scope: operation?.context?.scope,
+ rootOperationId: rootOperationId ?? operationId,
+ scope: scope ?? operation?.context?.scope,
signal: operation?.abortController?.signal,
- sourceMessageId: operation?.context?.messageId,
- topicId: operation?.context?.topicId ?? undefined,
+ sourceMessageId: sourceMessageId ?? operation?.context?.messageId,
+ taskId,
+ threadId: threadId ?? operation?.context?.threadId,
+ topicId: topicId ?? operation?.context?.topicId,
+ toolCallId,
+ toolMessageId,
};
log('[ClientToolCall] execute:start', {
@@ -173,6 +197,14 @@ export class ClientToolExecutionActionImpl {
toolCallId,
});
+ // Drain the Work-registration intent the builtin executor stashed during
+ // `invokeExecutor` and relay it on the result — mirrors
+ // `ClientToolTransport.run`, which attaches the drained intent to the
+ // result whenever one exists (success OR failure). The server registers
+ // the Work version from it once cumulative cost is known; the tool
+ // message persist path never writes this field.
+ const workRegistration = takeWorkIntent(toolCallId);
+
if (result.error) {
send({
content: result.content ?? result.error.message ?? null,
@@ -180,6 +212,7 @@ export class ClientToolExecutionActionImpl {
state: result.state,
success: false,
toolCallId,
+ workRegistration,
});
} else {
send({
@@ -187,6 +220,7 @@ export class ClientToolExecutionActionImpl {
state: result.state,
success: !!result.success,
toolCallId,
+ workRegistration,
});
}
return;
@@ -295,6 +329,10 @@ export class ClientToolExecutionActionImpl {
toolCallId,
});
}
+ // Leak guard: free any Work intent still stashed for this toolCallId (e.g.
+ // the executor threw before the normal drain). Take-on-read is idempotent,
+ // so a double take after a successful drain is a harmless no-op.
+ takeWorkIntent(toolCallId);
this.#setPending(toolCallId, false);
}
};
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index bb2c5c2a946..d13b3c87afd 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -480,6 +480,7 @@ export class StreamingExecutorActionImpl {
* keep their own model.
*/
modelOverride?: { model: string; provider: string };
+ userMessageId?: string;
}): Promise<{ cost?: Cost; model?: string; provider?: string; usage?: Usage } | void> => {
const {
disableTools,
@@ -1010,6 +1011,7 @@ export class StreamingExecutorActionImpl {
parentMessageId: userMessageId,
parentMessageType: 'user',
parentOperationId,
+ userMessageId,
});
// 7. Extract the sub-agent's final assistant output as the tool result
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
index 83d999307ec..317b45cb798 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
@@ -144,8 +144,10 @@ describe('createGatewayEventHandler', () => {
handler(makeEvent('tool_end', { isSuccess: true, skipMessageFetch: true }));
await flush();
- expect(getMessages).toHaveBeenCalledWith(context);
- expect(store.replaceMessages).toHaveBeenCalledWith([], { context });
+ // Mid-stream tool_end refetches skip the Work-summary assembly and graft
+ // previously rendered works back via `preserveWorks`.
+ expect(getMessages).toHaveBeenCalledWith({ ...context, skipWorks: true });
+ expect(store.replaceMessages).toHaveBeenCalledWith([], { context, preserveWorks: true });
});
it('skips hetero execution_complete DB refetch when frontend state is the snapshot', async () => {
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
index ebe49493181..03bd41077cc 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -18,6 +18,7 @@ import { AgentRuntimeErrorType } from '@lobechat/types';
import { isRecord, pickNonEmptyString, toRecord } from '@lobechat/utils/object';
import { messageService } from '@/services/message';
+import { didToolMutateWorkView, workService } from '@/services/work';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';
import type {
AgentRunLifecycle,
@@ -56,9 +57,25 @@ const loadGetExecutor = async () => {
* This updates the ConversationArea component via React subscription:
* dbMessagesMap → ConversationArea (messages prop) → ConversationStore → UI
*/
-const fetchAndReplaceMessages = async (get: () => ChatStore, context: ConversationContext) => {
- const messages = await messageService.getMessages(context);
- get().replaceMessages(messages, { context });
+const fetchAndReplaceMessages = async (
+ get: () => ChatStore,
+ context: ConversationContext,
+ options?: {
+ /**
+ * Mid-stream refetches (stream_start / tool_end / step_complete) skip the
+ * server-side Work-summary assembly — each tool round would otherwise
+ * re-run the per-type Work queries. `preserveWorks` grafts the
+ * already-rendered works back so chips don't flicker; the terminal
+ * agent_runtime_end refetch recomputes them for real.
+ */
+ skipWorks?: boolean;
+ },
+) => {
+ const skipWorks = options?.skipWorks;
+ const messages = await messageService.getMessages(
+ skipWorks ? { ...context, skipWorks } : context,
+ );
+ get().replaceMessages(messages, { context, preserveWorks: skipWorks });
return messages;
};
@@ -394,6 +411,7 @@ export const createGatewayEventHandler = (
// Mutable — switches to new assistant message ID on each stream_start
let currentAssistantMessageId = params.assistantMessageId;
let terminalState: 'completed' | 'error' | undefined;
+ let shouldRefreshWorkViews = false;
// Accumulated content from stream chunks (reset on each stream_start)
let accumulatedContent = '';
@@ -504,7 +522,9 @@ export const createGatewayEventHandler = (
// Older servers send only `{ id }` — fall back to a DB read.
// The row is inserted before stream_start is published, so the
// fetch is guaranteed to bring it into the store.
- await fetchAndReplaceMessages(get, context).catch(console.error);
+ await fetchAndReplaceMessages(get, context, { skipWorks: true }).catch(
+ console.error,
+ );
}
}
}
@@ -533,7 +553,9 @@ export const createGatewayEventHandler = (
// dispatch to it, and (b) resolves the next-step assistant id for
// the `newStep` fallback.
if (!newAssistantMessageId) {
- const messages = await fetchAndReplaceMessages(get, context).catch((error) => {
+ const messages = await fetchAndReplaceMessages(get, context, {
+ skipWorks: true,
+ }).catch((error) => {
console.error(error);
return undefined;
});
@@ -640,7 +662,7 @@ export const createGatewayEventHandler = (
// lands — a fire-and-forget fetch would let the next event overtake
// it and dispatch onto a message the store doesn't have yet.
if ((data as any).toolMessageIds) {
- await fetchAndReplaceMessages(get, context).catch(console.error);
+ await fetchAndReplaceMessages(get, context, { skipWorks: true }).catch(console.error);
}
}
});
@@ -731,7 +753,13 @@ export const createGatewayEventHandler = (
// assistant placeholder while DB fan-out is still in flight, which
// clobbers the in-memory streamed assistantGroup.
if (Array.isArray(data?.uiMessages)) {
- get().replaceMessages(data.uiMessages, { action: 'gateway/step_start', context });
+ // step_start snapshots are fetched with `skipWorks` server-side —
+ // graft the already-rendered works back so chips don't flicker.
+ get().replaceMessages(data.uiMessages, {
+ action: 'gateway/step_start',
+ context,
+ preserveWorks: true,
+ });
}
if (data?.phase === 'human_approval' && data.requiresApproval && data.pendingToolsCalling) {
@@ -768,7 +796,10 @@ export const createGatewayEventHandler = (
// — NOT the local `operationId` used for `dispatchContext`.
const data = event.data as ToolExecuteData | undefined;
if (!data) break;
- void get().internal_executeClientTool(data, { operationId: gatewayOperationId });
+ void get().internal_executeClientTool(data, {
+ localOperationId: operationId,
+ operationId: gatewayOperationId,
+ });
break;
}
@@ -777,11 +808,28 @@ export const createGatewayEventHandler = (
enqueue(async () => {
const maybeRefresh = shouldSkipMessageFetch(event, runtimeType)
? Promise.resolve()
- : fetchAndReplaceMessages(get, context).catch(console.error);
+ : fetchAndReplaceMessages(get, context, { skipWorks: true }).catch(console.error);
+ const payload = unwrapToolPayload(data?.payload);
+ const result = data?.result as
+ { state?: unknown; workRegistration?: unknown } | undefined;
+ if (
+ didToolMutateWorkView({
+ apiName: typeof payload?.apiName === 'string' ? payload.apiName : undefined,
+ identifier: typeof payload?.identifier === 'string' ? payload.identifier : undefined,
+ result,
+ succeeded: data?.isSuccess === true,
+ workRegistration: Boolean(result?.workRegistration),
+ })
+ ) {
+ shouldRefreshWorkViews = true;
+ }
+
await Promise.all([
maybeRefresh,
dispatchOnAfterCall(data, context.topicId ?? undefined).catch(console.error),
]);
+ // Message-backed summaries refresh with the normal tool payload. Lazy
+ // Work views settle once at runtime-end when a mutating tool was seen.
});
break;
}
@@ -841,7 +889,7 @@ export const createGatewayEventHandler = (
sourceType: 'client.gateway.step_complete',
});
if (!shouldSkipMessageFetch(event, runtimeType)) {
- await fetchAndReplaceMessages(get, context).catch(console.error);
+ await fetchAndReplaceMessages(get, context, { skipWorks: true }).catch(console.error);
}
});
}
@@ -913,6 +961,12 @@ export const createGatewayEventHandler = (
await fetchAndReplaceMessages(get, context).catch(console.error);
}
+ if (runtimeType === 'gateway' && shouldRefreshWorkViews) {
+ await workService
+ .refreshConversationViews(context.topicId, context.threadId)
+ .catch(console.error);
+ }
+
// Terminal run lifecycle. `isCompletedRuntimeEnd` is the clean-vs-not
// gate (a mid-stream cancel 'interrupted' or deferred-tool park
// 'waiting_for_async_tool' is NOT a clean completion):
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index 75151920e2a..07ee7f9b400 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -5,7 +5,7 @@ import isEqual from 'fast-deep-equal';
import { type SWRResponse } from 'swr';
import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
-import { messageKeys } from '@/libs/swr/keys';
+import { isMessageListKey } from '@/libs/swr/keys';
import { messageService } from '@/services/message';
import {
getMessageListCacheIdentity,
@@ -69,11 +69,11 @@ export class MessageQueryActionImpl {
// verification window and any older in-flight generation.
invalidateMessageListClientState((ctx) => ctx.agentId === agentId && ctx.topicId === topicId);
- await mutate((key) => {
- if (!Array.isArray(key) || key[0] !== messageKeys.list.root) return false;
- const ctx = key[1] as ConversationContext | undefined;
- return !!ctx && ctx.agentId === agentId && ctx.topicId === topicId;
- });
+ // Invalidate every `message:list` entry for this agent+topic (any scope /
+ // thread / page-size variant).
+ await mutate((key) =>
+ isMessageListKey(key, (ctx) => ctx.agentId === agentId && ctx.topicId === topicId),
+ );
};
prefetchMessages = async (context: ConversationContext): Promise<void> => {
@@ -110,6 +110,15 @@ export class MessageQueryActionImpl {
context?: Partial<ConversationContext>;
operationId?: string;
+
+ /**
+ * Graft `works` from the currently stored messages onto the incoming
+ * ones (by message id). Set when the payload was fetched with
+ * `skipWorks` (mid-stream refetches / step_start snapshots), so
+ * already-rendered Work chips don't flicker away until the terminal
+ * refetch restores them.
+ */
+ preserveWorks?: boolean;
},
): void => {
let ctx: MessageMapKeyInput;
@@ -144,12 +153,28 @@ export class MessageQueryActionImpl {
const messagesKey = messageMapKey(ctx);
+ let incoming = messages;
+ if (params?.preserveWorks) {
+ const worksById = new Map(
+ (this.#get().dbMessagesMap[messagesKey] ?? [])
+ .filter((message) => message.works?.length)
+ .map((message) => [message.id, message.works]),
+ );
+ if (worksById.size > 0) {
+ incoming = messages.map((message) =>
+ !message.works && worksById.has(message.id)
+ ? { ...message, works: worksById.get(message.id) }
+ : message,
+ );
+ }
+ }
+
// Re-link any tool row whose parent assistant lost its tools[] entry before
// it lands in the raw bucket — a stale / out-of-order snapshot can drop the
// link while the tool row survives, which would orphan the tool bubble (see
// reconcileAssistantToolLinks). Keeps dbMessagesMap (SoT) consistent for
// optimistic updates, not just the parsed display.
- const reconciled = reconcileAssistantToolLinks(messages);
+ const reconciled = reconcileAssistantToolLinks(incoming);
// Get raw messages from dbMessagesMap and apply reducer
const nextDbMap = { ...this.#get().dbMessagesMap, [messagesKey]: reconciled };
diff --git a/src/store/chat/slices/message/reducer.test.ts b/src/store/chat/slices/message/reducer.test.ts
index 820ca03959e..c511f7ad45b 100644
--- a/src/store/chat/slices/message/reducer.test.ts
+++ b/src/store/chat/slices/message/reducer.test.ts
@@ -220,6 +220,30 @@ describe('messagesReducer', () => {
const newState = messagesReducer(state, payload);
expect(newState).toEqual(state);
});
+
+ it('treats a repeated identical dispatch as a no-op (immer-draft comparison guard)', () => {
+ const payload: MessageDispatch = {
+ type: 'updatePluginState',
+ id: 'message1',
+ key: 'pluginKey',
+ value: 'pluginValue',
+ };
+
+ // First dispatch writes the value and bumps updatedAt.
+ const firstState = messagesReducer(initialState, payload);
+ const firstMessage = firstState.find((m) => m.id === 'message1')!;
+
+ // Second, identical dispatch must be a no-op. Inside `produce` the
+ // message's pluginState is an immer draft; getComparablePluginState must
+ // unwrap it via `current()` so isEqual sees no change (regression guard —
+ // immer 11.1.9 broke comparing a draft directly, causing spurious
+ // updatedAt bumps / re-renders).
+ const secondState = messagesReducer(firstState, payload);
+ const secondMessage = secondState.find((m) => m.id === 'message1')!;
+
+ expect(secondMessage).toBe(firstMessage);
+ expect(secondMessage.updatedAt).toBe(firstMessage.updatedAt);
+ });
});
describe('updateMessagePlugin', () => {
diff --git a/src/store/chat/slices/message/reducer.ts b/src/store/chat/slices/message/reducer.ts
index 7e142cb6a3f..a3b43686a84 100644
--- a/src/store/chat/slices/message/reducer.ts
+++ b/src/store/chat/slices/message/reducer.ts
@@ -7,7 +7,7 @@ import {
} from '@lobechat/types';
import isEqual from 'fast-deep-equal';
import i18n from 'i18next';
-import { current, produce } from 'immer';
+import { current, isDraft, produce } from 'immer';
import { merge } from '@/utils/merge';
@@ -96,6 +96,13 @@ export type MessageDispatch =
| DeleteMessageTool
| DeleteMessages;
+const getComparablePluginState = (pluginState: UIChatMessage['pluginState']) => {
+ if (!pluginState) return pluginState;
+
+ // Comparing an Immer draft directly can treat { existing: true } -> { existing: true } as changed.
+ return isDraft(pluginState) ? current(pluginState) : pluginState;
+};
+
export const messagesReducer = (
state: UIChatMessage[],
payload: MessageDispatch,
@@ -145,17 +152,15 @@ export const messagesReducer = (
const message = draftState.find((i) => i.id === id);
if (!message) return;
+ const pluginState = getComparablePluginState(message.pluginState);
let newState;
- if (!message.pluginState) {
+ if (!pluginState) {
newState = { [key]: value } as any;
} else {
- newState = merge(message.pluginState, { [key]: value });
+ newState = merge(pluginState, { [key]: value });
}
- // Compare against a plain snapshot, not the raw draft proxy — fast-deep-equal's
- // traversal of an Immer draft is an implementation detail that can change between
- // immer patch releases (e.g. immer 11.1.9 broke this exact comparison vs 11.1.8).
- if (message.pluginState && isEqual(current(message.pluginState), newState)) return;
+ if (isEqual(pluginState, newState)) return;
message.pluginState = newState;
message.updatedAt = Date.now();
diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.ts
index 6edd9eb9123..daa5266c95e 100644
--- a/src/store/chat/slices/operation/selectors.ts
+++ b/src/store/chat/slices/operation/selectors.ts
@@ -73,6 +73,24 @@ const getOperationContextFromMessage =
return operation?.context;
};
+/**
+ * Walk up the parent chain from an operation until the owning AI runtime
+ * operation (see AI_RUNTIME_OPERATION_TYPES) is found. Returns undefined when
+ * the chain has no runtime ancestor (e.g. a standalone tool operation).
+ */
+const findRootRuntimeOperation =
+ (operationId: string) =>
+ (s: ChatStoreState): Operation | undefined => {
+ let currentOp: Operation | undefined = s.operations[operationId];
+ while (currentOp) {
+ if (AI_RUNTIME_OPERATION_TYPES.includes(currentOp.type)) return currentOp;
+
+ const parentId: string | undefined = currentOp.parentOperationId;
+ currentOp = parentId ? s.operations[parentId] : undefined;
+ }
+ return undefined;
+ };
+
/**
* Get operations by message ID
*/
@@ -820,6 +838,7 @@ const getQueuedMessages = (context: MessageMapKeyInput) => (s: ChatStoreState) =
export const operationSelectors = {
canInterrupt,
canSendMessage,
+ findRootRuntimeOperation,
getActiveOperationTypes,
getAllOperations,
getCurrentContextOperations,
diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.ts
index 47df5706dab..e1b68b65efc 100644
--- a/src/store/chat/slices/plugin/action.test.ts
+++ b/src/store/chat/slices/plugin/action.test.ts
@@ -356,9 +356,11 @@ describe('ChatPluginAction', () => {
await result.current.invokeBuiltinTool(messageId, payload);
});
+ expect(capturedContext?.anchorMessageId).toBe('assistant-msg-1');
expect(capturedContext?.messageId).toBe(messageId);
expect(capturedContext?.sourceMessageId).toBe('user-msg-1');
expect(capturedContext?.toolCallId).toBe('tool-call-1');
+ expect(capturedContext?.toolMessageId).toBe(messageId);
});
it('should pass sub-agent context to Tool Store executor', async () => {
diff --git a/src/store/chat/slices/plugin/actions/exector.ts b/src/store/chat/slices/plugin/actions/exector.ts
index 0319eb9ed3e..ca03af9a8ac 100644
--- a/src/store/chat/slices/plugin/actions/exector.ts
+++ b/src/store/chat/slices/plugin/actions/exector.ts
@@ -1,12 +1,17 @@
+import { isWorkSkillProvider } from '@lobechat/types';
+
import { type MCPToolCallResult } from '@/libs/mcp';
import { useToolStore } from '@/store/tool';
import { type ChatToolPayload } from '@/types/message';
+import { stashWorkIntent } from '@/utils/clientWorkIntentStash';
import { safeParseJSON } from '@/utils/safeParseJSON';
/**
* Context for remote tool execution, derived from the invoking message
*/
export interface RemoteToolExecutorContext {
+ /** Stable tool call ID */
+ sourceToolCallId?: string;
/** Topic ID from the message that triggered this tool call */
topicId?: string;
}
@@ -90,6 +95,20 @@ export const lobehubSkillExecutor: RemoteToolExecutor = async (p, context) => {
);
}
+ if (isWorkSkillProvider(provider)) {
+ // Stash the Work-registration intent (carrying the UNTRUNCATED result data)
+ // keyed by toolCallId; `call_tool` drains it and registers the Work ONCE the
+ // tool call's cumulative cost is known, instead of registering cost-less here
+ // and back-filling. The runtime supplies provenance + cost at persist time.
+ stashWorkIntent(context?.sourceToolCallId, {
+ args,
+ data: result.data,
+ provider,
+ toolName: p.apiName,
+ type: 'skill',
+ });
+ }
+
// Convert to MCPToolCallResult format
const content = typeof result.data === 'string' ? result.data : JSON.stringify(result.data);
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index cef94566599..45850a79718 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -9,7 +9,7 @@ import { type MCPToolCallResult } from '@/libs/mcp';
import { mcpService } from '@/services/mcp';
import { messageService } from '@/services/message';
import { archiveToolResultViaServer } from '@/services/toolResultArchive';
-import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation';
+import { operationSelectors } from '@/store/chat/slices/operation';
import { type ChatStore } from '@/store/chat/store';
import { useToolStore } from '@/store/tool';
import { composioStoreSelectors, lobehubSkillStoreSelectors } from '@/store/tool/selectors';
@@ -90,21 +90,11 @@ export class PluginTypesActionImpl {
const operation = operationId ? this.#get().operations[operationId] : undefined;
const context = operationId ? { operationId } : undefined;
- let rootRuntimeOperationId: string | undefined;
- let rootRuntimeOperationContext = operation?.context;
- if (operationId) {
- let currentOp = operation;
- while (currentOp) {
- if (AI_RUNTIME_OPERATION_TYPES.includes(currentOp.type)) {
- rootRuntimeOperationId = currentOp.id;
- rootRuntimeOperationContext = currentOp.context;
- break;
- }
- // Move up to parent operation
- const parentId = currentOp.parentOperationId;
- currentOp = parentId ? this.#get().operations[parentId] : undefined;
- }
- }
+ const rootRuntimeOperation = operationId
+ ? operationSelectors.findRootRuntimeOperation(operationId)(this.#get())
+ : undefined;
+ const rootRuntimeOperationId = rootRuntimeOperation?.id;
+ const rootRuntimeOperationContext = rootRuntimeOperation?.context ?? operation?.context;
// Get agent ID, group ID, topic ID, and page scope from operation context.
// Prefer the concrete tool operation; fall back to the runtime root for
@@ -116,6 +106,9 @@ export class PluginTypesActionImpl {
const viewedTask = operation?.context?.viewedTask ?? rootRuntimeOperationContext?.viewedTask;
const taskId = viewedTask?.type === 'detail' ? viewedTask.taskId : undefined;
const topicId = operation?.context?.topicId ?? rootRuntimeOperationContext?.topicId;
+ const threadId = operation?.context?.threadId ?? rootRuntimeOperationContext?.threadId;
+ const toolMessage = dbMessageSelectors.getDbMessageById(id)(this.#get());
+ const anchorMessageId = toolMessage?.parentId ?? rootRuntimeOperationContext?.messageId;
const isSubAgent =
operation?.context?.isSubAgent ?? rootRuntimeOperationContext?.isSubAgent ?? false;
@@ -194,6 +187,7 @@ export class PluginTypesActionImpl {
isSubAgent,
scope,
taskId,
+ threadId,
topicId,
});
@@ -201,6 +195,7 @@ export class PluginTypesActionImpl {
.getState()
.invokeBuiltinTool(payload.identifier, payload.apiName, params, {
agentId,
+ anchorMessageId,
documentId,
groupId,
groupOrchestration,
@@ -208,6 +203,7 @@ export class PluginTypesActionImpl {
messageId: id,
operationId,
registerAfterCompletion,
+ rootOperationId: rootRuntimeOperationId ?? operationId,
scope,
signal: operation?.abortController?.signal,
sourceMessageId:
@@ -217,7 +213,9 @@ export class PluginTypesActionImpl {
stepContext,
subAgent,
taskId,
+ threadId,
toolCallId: payload.id,
+ toolMessageId: id,
topicId,
});
@@ -412,7 +410,10 @@ export class PluginTypesActionImpl {
try {
// Pass topicId from message context, not global active state
// This ensures tool calls use the correct topic even if user switches topics
- data = await executor(payload, { topicId: message?.topicId });
+ data = await executor(payload, {
+ sourceToolCallId: payload.id,
+ topicId: message?.topicId,
+ });
} catch (error) {
console.error(`[${logPrefix}] Error:`, error);
diff --git a/src/store/chat/utils/evictMessageCache.ts b/src/store/chat/utils/evictMessageCache.ts
index bd48dd1cf59..e719356eb41 100644
--- a/src/store/chat/utils/evictMessageCache.ts
+++ b/src/store/chat/utils/evictMessageCache.ts
@@ -1,7 +1,7 @@
import { type ConversationContext } from '@lobechat/types';
import { mutate } from '@/libs/swr';
-import { messageKeys } from '@/libs/swr/keys';
+import { isMessageListKey } from '@/libs/swr/keys';
/**
* Evict persisted `message:list` cache entries whose conversation context
@@ -27,12 +27,4 @@ import { messageKeys } from '@/libs/swr/keys';
export const evictMessageCache = (
predicate: (ctx: ConversationContext) => boolean,
): Promise<unknown> =>
- mutate(
- (key) => {
- if (!Array.isArray(key) || key[0] !== messageKeys.list.root) return false;
- const ctx = key[1] as ConversationContext | undefined;
- return !!ctx && predicate(ctx);
- },
- undefined,
- { revalidate: false },
- );
+ mutate((key) => isMessageListKey(key, predicate), undefined, { revalidate: false });
diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.ts
index 7d50d14a67a..99fc0f7e588 100644
--- a/src/store/task/slices/detail/action.test.ts
+++ b/src/store/task/slices/detail/action.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { taskService } from '@/services/task';
+import { workService } from '@/services/work';
import { taskDetailSelectors } from '@/store/task/selectors';
import { useTaskStore } from '../../store';
@@ -20,6 +21,12 @@ vi.mock('@/services/task', () => ({
},
}));
+vi.mock('@/services/work', () => ({
+ workService: {
+ refreshAllConversations: vi.fn(),
+ },
+}));
+
vi.mock('@/libs/swr', () => ({
mutate: vi.fn(),
useClientDataSWR: vi.fn(),
@@ -292,6 +299,7 @@ describe('TaskDetailSliceAction', () => {
expect(result?.name).toBe('Test Task');
expect(useTaskStore.getState().taskDetailMap['T-1']).toBeUndefined();
expect(useTaskStore.getState().activeTaskId).toBeUndefined();
+ expect(workService.refreshAllConversations).toHaveBeenCalled();
});
it('should set isDeletingTask during deletion', async () => {
@@ -310,6 +318,28 @@ describe('TaskDetailSliceAction', () => {
expect(useTaskStore.getState().isDeletingTask).toBe(false);
});
+ it('should not rollback delete when work cache refresh fails', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ useTaskStore.setState({
+ taskDetailMap: {
+ 'T-1': { identifier: 'T-1', instruction: 'Test', status: 'backlog' },
+ },
+ });
+
+ vi.mocked(taskService.delete).mockResolvedValue({
+ data: { identifier: 'T-1' },
+ success: true,
+ } as any);
+ vi.mocked(workService.refreshAllConversations).mockRejectedValue(new Error('refresh failed'));
+
+ const result = await useTaskStore.getState().deleteTask('T-1');
+
+ expect(result?.identifier).toBe('T-1');
+ expect(useTaskStore.getState().taskDetailMap['T-1']).toBeUndefined();
+ expect(consoleError).toHaveBeenCalledWith('[task:deleteTask:refreshWork]', expect.any(Error));
+ consoleError.mockRestore();
+ });
+
it('should rollback optimistic delete and propagate error on failure', async () => {
const snapshot = {
identifier: 'T-1',
@@ -325,6 +355,7 @@ describe('TaskDetailSliceAction', () => {
expect(useTaskStore.getState().taskDetailMap['T-1']).toEqual(snapshot);
expect(useTaskStore.getState().isDeletingTask).toBe(false);
+ expect(workService.refreshAllConversations).not.toHaveBeenCalled();
});
});
diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.ts
index f1d69593225..0ace6350c03 100644
--- a/src/store/task/slices/detail/action.ts
+++ b/src/store/task/slices/detail/action.ts
@@ -6,6 +6,7 @@ import { message } from '@/components/AntdStaticMethods';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { taskKeys } from '@/libs/swr/keys';
import { taskService } from '@/services/task';
+import { workService } from '@/services/work';
import type { StoreSetter } from '@/store/types';
import { runMutation } from '@/store/utils/runMutation';
import { saveToast } from '@/store/utils/saveToast';
@@ -196,6 +197,14 @@ export class TaskDetailSliceActionImpl {
}
await this.#get().refreshTaskList();
+ try {
+ // Deleting a task can orphan its Works across topics; the summary chips
+ // ride the message payload, so invalidate message lists too, not just
+ // the work-domain sidebar caches.
+ await workService.refreshAllConversations();
+ } catch (error) {
+ console.error('[task:deleteTask:refreshWork]', error);
+ }
return result.data ?? null;
} catch (error) {
if (snapshot) {
diff --git a/src/store/tool/slices/builtin/executors/__tests__/lobe-agent-documents.test.ts b/src/store/tool/slices/builtin/executors/__tests__/lobe-agent-documents.test.ts
new file mode 100644
index 00000000000..30bce230075
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/__tests__/lobe-agent-documents.test.ts
@@ -0,0 +1,121 @@
+import type { BuiltinToolContext } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { takeWorkIntent } from '@/utils/clientWorkIntentStash';
+
+import { agentDocumentsExecutor } from '../lobe-agent-documents';
+
+const mocks = vi.hoisted(() => ({
+ copyDocument: vi.fn(),
+ createDocument: vi.fn(),
+ createForTopic: vi.fn(),
+ listDocuments: vi.fn(),
+ modifyNodes: vi.fn(),
+ readDocument: vi.fn(),
+ refreshConversation: vi.fn(),
+ removeDocument: vi.fn(),
+ renameDocument: vi.fn(),
+ replaceDocumentContent: vi.fn(),
+ updateLoadRule: vi.fn(),
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ getActiveWorkspaceSlug: vi.fn(),
+}));
+
+vi.mock('@/services/agentDocument', () => ({
+ agentDocumentService: {
+ copyDocument: mocks.copyDocument,
+ createDocument: mocks.createDocument,
+ createForTopic: mocks.createForTopic,
+ listDocuments: mocks.listDocuments,
+ modifyNodes: mocks.modifyNodes,
+ readDocument: mocks.readDocument,
+ removeDocument: mocks.removeDocument,
+ renameDocument: mocks.renameDocument,
+ replaceDocumentContent: mocks.replaceDocumentContent,
+ updateLoadRule: mocks.updateLoadRule,
+ },
+}));
+
+vi.mock('@/services/work', () => ({
+ workService: {
+ refreshConversation: mocks.refreshConversation,
+ },
+}));
+
+describe('agentDocumentsExecutor', () => {
+ const createContext = (overrides?: Partial<BuiltinToolContext>): BuiltinToolContext => ({
+ agentId: 'agent-1',
+ messageId: 'tool-context-key',
+ operationId: 'operation-1',
+ rootOperationId: 'root-operation-1',
+ sourceMessageId: 'user-message-1',
+ threadId: 'thread-1',
+ toolCallId: 'tool-call-1',
+ toolMessageId: 'tool-message-1',
+ topicId: 'topic-1',
+ ...overrides,
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.refreshConversation.mockResolvedValue(undefined);
+ // Drain any leftover so the shared per-toolCallId stash starts clean.
+ takeWorkIntent('tool-call-1');
+ });
+
+ it('stashes a document register intent after attributed document creation', async () => {
+ mocks.createDocument.mockResolvedValue({
+ description: 'A daily brief',
+ documentId: 'document-1',
+ id: 'agent-document-1',
+ title: 'Test Document',
+ });
+
+ const result = await agentDocumentsExecutor.invoke(
+ 'createDocument',
+ {
+ content: 'Body',
+ title: 'Test Document',
+ },
+ createContext(),
+ );
+
+ expect(result.success).toBe(true);
+ expect(mocks.createDocument).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ content: 'Body',
+ title: 'Test Document',
+ toolContext: expect.objectContaining({
+ messageId: 'user-message-1',
+ rootOperationId: 'root-operation-1',
+ threadId: 'thread-1',
+ toolCallId: 'tool-call-1',
+ toolMessageId: 'tool-message-1',
+ topicId: 'topic-1',
+ }),
+ trigger: 'tool',
+ }),
+ );
+
+ // The wrapper no longer refreshes inline; it stashes the register intent for
+ // `call_tool` to write once cost is known.
+ expect(mocks.refreshConversation).not.toHaveBeenCalled();
+ expect(takeWorkIntent('tool-call-1')).toEqual(
+ expect.objectContaining({
+ action: 'register',
+ document: expect.objectContaining({
+ agentDocumentId: 'agent-document-1',
+ agentId: 'agent-1',
+ description: 'A daily brief',
+ documentId: 'document-1',
+ changeType: 'created',
+ toolName: 'createDocument',
+ }),
+ type: 'document',
+ }),
+ );
+ });
+});
diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.ts
index eb9fa1d73df..2fe5ecb5b43 100644
--- a/src/store/tool/slices/builtin/executors/index.ts
+++ b/src/store/tool/slices/builtin/executors/index.ts
@@ -33,6 +33,7 @@ import { topicReferenceExecutor } from './lobe-topic-reference';
import { userInteractionExecutor } from './lobe-user-interaction';
import { webBrowsing } from './lobe-web-browsing';
import { webOnboardingExecutor } from './lobe-web-onboarding';
+import { stashBuiltinToolWorkIntent } from './workRegistration';
/**
* Registry structure: Map<identifier, executor instance>
@@ -121,7 +122,15 @@ export const invokeExecutor = async (
};
}
- return executor.invoke(apiName, params, ctx);
+ const result = await executor.invoke(apiName, params, ctx);
+
+ // Manifest-driven Work registration (best-effort; a no-op unless the API
+ // declares a `work` config). Only STASH the intent here — `call_tool` drains
+ // it and writes the Work version once the tool call's cumulative cost is known
+ // (write-once instead of register-then-backfill).
+ stashBuiltinToolWorkIntent(identifier, apiName, params, ctx, result);
+
+ return result;
};
/**
diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
index cd8b7417d14..f13943d4c9a 100644
--- a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
@@ -7,9 +7,16 @@ import { isDesktop } from '@lobechat/const';
import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { agentDocumentService } from '@/services/agentDocument';
import { invalidateDocumentMutation } from '@/services/document/invalidation';
+import { workService } from '@/services/work';
import { useAgentStore } from '@/store/agent';
import { useElectronStore } from '@/store/electron';
import { electronSyncSelectors } from '@/store/electron/selectors';
+import { stashWorkIntent } from '@/utils/clientWorkIntentStash';
+
+interface DocumentWorkRefreshContext {
+ threadId?: string | null;
+ topicId?: string;
+}
/**
* App origin for share links. Desktop points at the connected remote server so
@@ -20,20 +27,102 @@ const getAppOrigin = (): string | undefined => {
return typeof window === 'undefined' ? undefined : window.location.origin;
};
+/** Build the sharable document URL for the active workspace (stash intent + tool result share both use it). */
+const buildDocumentShareUrl = (agentId: string, documentId: string): string | undefined =>
+ buildAgentDocumentUrl(getAppOrigin(), agentId, documentId, {
+ workspaceSlug: getActiveWorkspaceSlug(),
+ });
+
+const refreshDocumentWorks = async (context?: DocumentWorkRefreshContext) => {
+ if (!context) return;
+
+ // Summary chips + sidebar summary ride the message payload, so refreshing the
+ // conversation (message list + sidebar history) covers them.
+ await workService.refreshConversation(context.topicId, context.threadId).catch((error) => {
+ console.error('[AgentDocumentsExecutor] refresh document works failed:', error);
+ });
+};
+
+const withWorkRefresh = async <T>(operation: Promise<T>, context?: DocumentWorkRefreshContext) => {
+ const result = await operation;
+ await refreshDocumentWorks(context);
+ return result;
+};
+
+/**
+ * Stash a document Work-registration intent for a create/update tool mutation,
+ * keyed by `toolCallId`. `call_tool` drains it and registers the Work ONCE the
+ * tool call's cumulative cost is known — replacing the old lambda-side inline
+ * (cost-less) registration + client cost back-fill. Deletes are NOT stashed:
+ * they remain a lambda side-effect of removeDocument (a delete carries no cost).
+ */
+const stashDocumentRegisterIntent = (input: {
+ agentDocumentId?: string;
+ agentId: string;
+ description?: string | null;
+ documentId?: string;
+ changeType: 'created' | 'updated';
+ toolName: string;
+ toolCallId?: string;
+}) => {
+ if (!input.toolCallId || !input.documentId) return;
+
+ stashWorkIntent(input.toolCallId, {
+ action: 'register',
+ document: {
+ agentDocumentId: input.agentDocumentId,
+ agentId: input.agentId,
+ description: input.description,
+ documentId: input.documentId,
+ changeType: input.changeType,
+ toolName: input.toolName,
+ },
+ type: 'document',
+ });
+};
+
const runtime = new AgentDocumentsExecutionRuntime(
{
- copyDocument: ({ agentId, id, newTitle }) =>
- agentDocumentService.copyDocument({ agentId, id, newTitle }),
- createDocument: ({ agentId, content, hintIsSkill, title, toolContext, trigger }) =>
- agentDocumentService.createDocument({
+ copyDocument: async ({ agentId, id, newTitle, toolContext, trigger }) => {
+ const doc = await agentDocumentService.copyDocument({
+ agentId,
+ id,
+ newTitle,
+ toolContext,
+ trigger,
+ });
+ stashDocumentRegisterIntent({
+ agentDocumentId: doc?.id,
+ agentId,
+ description: doc?.description,
+ documentId: doc?.documentId,
+ changeType: 'created',
+ toolName: 'copyDocument',
+ toolCallId: toolContext?.toolCallId,
+ });
+ return doc;
+ },
+ createDocument: async ({ agentId, content, hintIsSkill, title, toolContext, trigger }) => {
+ const doc = await agentDocumentService.createDocument({
agentId,
content,
hintIsSkill,
title,
toolContext,
trigger,
- }),
- createTopicDocument: ({
+ });
+ stashDocumentRegisterIntent({
+ agentDocumentId: doc?.id,
+ agentId,
+ description: doc?.description,
+ documentId: doc?.documentId,
+ changeType: 'created',
+ toolName: 'createDocument',
+ toolCallId: toolContext?.toolCallId,
+ });
+ return doc;
+ },
+ createTopicDocument: async ({
agentId,
content,
hintIsSkill,
@@ -41,8 +130,8 @@ const runtime = new AgentDocumentsExecutionRuntime(
toolContext,
topicId,
trigger,
- }) =>
- agentDocumentService.createForTopic({
+ }) => {
+ const doc = await agentDocumentService.createForTopic({
agentId,
content,
hintIsSkill,
@@ -50,7 +139,18 @@ const runtime = new AgentDocumentsExecutionRuntime(
toolContext,
topicId,
trigger,
- }),
+ });
+ stashDocumentRegisterIntent({
+ agentDocumentId: doc?.id,
+ agentId,
+ description: doc?.description,
+ documentId: doc?.documentId,
+ changeType: 'created',
+ toolName: 'createForTopic',
+ toolCallId: toolContext?.toolCallId,
+ });
+ return doc;
+ },
listDocuments: async ({ agentId, parentId, sourceType }) => {
// The agent listing tool surfaces archived `.tool-results` so the model can
// discover them; user-facing lists keep the default (filtered) behavior.
@@ -83,16 +183,75 @@ const runtime = new AgentDocumentsExecutionRuntime(
title: d.title,
}));
},
- modifyNodes: ({ agentId, id, operations }) =>
- agentDocumentService.modifyNodes({ agentId, id, operations }),
+ modifyNodes: async ({ agentId, id, operations, toolContext, trigger }) => {
+ const doc = await agentDocumentService.modifyNodes({
+ agentId,
+ id,
+ operations,
+ toolContext,
+ trigger,
+ });
+ stashDocumentRegisterIntent({
+ agentDocumentId: id,
+ agentId,
+ description: doc?.description,
+ documentId: doc?.documentId,
+ changeType: 'updated',
+ toolName: 'modifyNodes',
+ toolCallId: toolContext?.toolCallId,
+ });
+ return doc;
+ },
readDocument: ({ agentId, format, id }) =>
agentDocumentService.readDocument({ agentId, format: format ?? 'xml', id }),
- removeDocument: async ({ agentId, id }) =>
- (await agentDocumentService.removeDocument({ agentId, id })).deleted,
- renameDocument: ({ agentId, id, newTitle }) =>
- agentDocumentService.renameDocument({ agentId, id, newTitle }),
- replaceDocumentContent: ({ agentId, content, id }) =>
- agentDocumentService.replaceDocumentContent({ agentId, content, id }),
+ // Delete stays a lambda side-effect (removeDocument drops the Work server-side);
+ // it carries no cost, so it needs no cost-stamping defer. Keep the immediate
+ // work-cache refresh so the sidebar drops the removed doc.
+ removeDocument: async ({ agentId, id, toolContext, trigger }) =>
+ (
+ await withWorkRefresh(
+ agentDocumentService.removeDocument({ agentId, id, toolContext, trigger }),
+ toolContext,
+ )
+ ).deleted,
+ renameDocument: async ({ agentId, id, newTitle, toolContext, trigger }) => {
+ const doc = await agentDocumentService.renameDocument({
+ agentId,
+ id,
+ newTitle,
+ toolContext,
+ trigger,
+ });
+ stashDocumentRegisterIntent({
+ agentDocumentId: id,
+ agentId,
+ description: doc?.description,
+ documentId: doc?.documentId,
+ changeType: 'updated',
+ toolName: 'renameDocument',
+ toolCallId: toolContext?.toolCallId,
+ });
+ return doc;
+ },
+ replaceDocumentContent: async ({ agentId, content, id, toolContext, trigger }) => {
+ const doc = await agentDocumentService.replaceDocumentContent({
+ agentId,
+ content,
+ id,
+ toolContext,
+ trigger,
+ });
+ stashDocumentRegisterIntent({
+ agentDocumentId: id,
+ agentId,
+ description: doc?.description,
+ documentId: doc?.documentId,
+ changeType: 'updated',
+ toolName: 'replaceDocumentContent',
+ toolCallId: toolContext?.toolCallId,
+ });
+ return doc;
+ },
updateLoadRule: ({ agentId, id, rule }) =>
agentDocumentService.updateLoadRule({
agentId,
@@ -105,10 +264,7 @@ const runtime = new AgentDocumentsExecutionRuntime(
}),
},
{
- getDocumentUrl: ({ agentId, documentId }) =>
- buildAgentDocumentUrl(getAppOrigin(), agentId, documentId, {
- workspaceSlug: getActiveWorkspaceSlug(),
- }),
+ getDocumentUrl: ({ agentId, documentId }) => buildDocumentShareUrl(agentId, documentId),
// Revalidate the documents list after the agent mutates it. `onAfterCall`
// carries no agentId, so resolve the active chat agent — the one whose run
// just produced the tool call. Covers the server-runtime path where the
diff --git a/src/store/tool/slices/builtin/executors/workRegistration.test.ts b/src/store/tool/slices/builtin/executors/workRegistration.test.ts
new file mode 100644
index 00000000000..b590b934319
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/workRegistration.test.ts
@@ -0,0 +1,147 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { takeWorkIntent } from '@/utils/clientWorkIntentStash';
+
+vi.mock('@lobechat/builtin-tools', () => ({
+ builtinTools: [
+ {
+ identifier: 'lobe-task',
+ manifest: {
+ api: [
+ { name: 'createTask', work: { action: 'create', resourceType: 'task' } },
+ { name: 'createTasks', work: { action: 'create', resourceType: 'task' } },
+ { name: 'editTask', work: { action: 'update', resourceType: 'task' } },
+ { name: 'deleteTask', work: { action: 'delete', resourceType: 'task' } },
+ { name: 'listTasks' },
+ ],
+ },
+ },
+ ],
+}));
+
+const { stashBuiltinToolWorkIntent } = await import('./workRegistration');
+
+const ctx = {
+ agentId: 'agent-1',
+ operationId: 'op-child',
+ rootOperationId: 'op-root',
+ threadId: 'thread-1',
+ toolCallId: 'tool-call-1',
+ toolMessageId: 'msg-tool-1',
+ topicId: 'topic-1',
+} as any;
+
+describe('stashBuiltinToolWorkIntent (client dispatch)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Drain any leftover from a prior test so the shared stash starts clean.
+ takeWorkIntent(ctx.toolCallId);
+ });
+
+ it('stashes a created-task intent with the resolved target', () => {
+ stashBuiltinToolWorkIntent('lobe-task', 'createTask', { instruction: 'do', name: 'A' }, ctx, {
+ content: '',
+ state: { identifier: 'T-1', success: true, taskId: 'task_1' },
+ success: true,
+ });
+
+ expect(takeWorkIntent(ctx.toolCallId)).toEqual({
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ type: 'task',
+ });
+ });
+
+ it('stashes an update intent (changeType "updated") resolved via args.identifier', () => {
+ stashBuiltinToolWorkIntent(
+ 'lobe-task',
+ 'editTask',
+ { identifier: 'T-9', name: 'Edited' },
+ ctx,
+ {
+ content: '',
+ success: true,
+ },
+ );
+
+ expect(takeWorkIntent(ctx.toolCallId)).toEqual({
+ action: 'update',
+ changeType: 'updated',
+ targets: [{ taskId: undefined, taskIdentifier: 'T-9' }],
+ type: 'task',
+ });
+ });
+
+ it('stashes only the succeeded items of a partially failed batch', () => {
+ stashBuiltinToolWorkIntent('lobe-task', 'createTasks', { tasks: [] }, ctx, {
+ content: '',
+ state: {
+ failed: 1,
+ results: [
+ { identifier: 'T-A', name: 'A', success: true },
+ { error: 'boom', name: 'B', success: false },
+ ],
+ succeeded: 1,
+ },
+ success: false,
+ });
+
+ expect(takeWorkIntent(ctx.toolCallId)).toEqual({
+ action: 'create',
+ changeType: 'created',
+ targets: [{ taskId: undefined, taskIdentifier: 'T-A' }],
+ type: 'task',
+ });
+ });
+
+ it('stashes a delete intent carrying the resolved target', () => {
+ stashBuiltinToolWorkIntent('lobe-task', 'deleteTask', { identifier: 'T-1' }, ctx, {
+ content: '',
+ state: { identifier: 'T-1', success: true, taskId: 'task_1' },
+ success: true,
+ });
+
+ expect(takeWorkIntent(ctx.toolCallId)).toEqual({
+ action: 'delete',
+ targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ type: 'task',
+ });
+ });
+
+ it('stashes nothing when the delete call failed (no targets)', () => {
+ stashBuiltinToolWorkIntent('lobe-task', 'deleteTask', { identifier: 'T-1' }, ctx, {
+ content: 'boom',
+ success: false,
+ });
+
+ expect(takeWorkIntent(ctx.toolCallId)).toBeUndefined();
+ });
+
+ it('stashes nothing for an API without a work config', () => {
+ stashBuiltinToolWorkIntent('lobe-task', 'listTasks', {}, ctx, { content: '', success: true });
+
+ expect(takeWorkIntent(ctx.toolCallId)).toBeUndefined();
+ });
+
+ it('stashes nothing when the call failed (no targets)', () => {
+ stashBuiltinToolWorkIntent('lobe-task', 'editTask', { identifier: 'T-1' }, ctx, {
+ content: 'boom',
+ success: false,
+ });
+
+ expect(takeWorkIntent(ctx.toolCallId)).toBeUndefined();
+ });
+
+ it('stashes nothing when the tool call has no toolCallId to key by', () => {
+ stashBuiltinToolWorkIntent(
+ 'lobe-task',
+ 'createTask',
+ { name: 'A' },
+ { ...ctx, toolCallId: undefined },
+ { content: '', state: { identifier: 'T-1', success: true }, success: true },
+ );
+
+ expect(takeWorkIntent(ctx.toolCallId)).toBeUndefined();
+ });
+});
diff --git a/src/store/tool/slices/builtin/executors/workRegistration.ts b/src/store/tool/slices/builtin/executors/workRegistration.ts
new file mode 100644
index 00000000000..8695695bd4e
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/workRegistration.ts
@@ -0,0 +1,35 @@
+import { builtinTools } from '@lobechat/builtin-tools';
+import { resolveWorkRegistration } from '@lobechat/builtin-tools/workRegistration';
+
+import { stashWorkIntent } from '@/utils/clientWorkIntentStash';
+
+import type { BuiltinToolContext, BuiltinToolResult } from '../types';
+
+/**
+ * Manifest-driven Work registration intent for the client tool-execution path
+ * (the OSS no-gateway / desktop client-run fallback).
+ *
+ * The executor no longer writes the Work itself: it only RESOLVES what should be
+ * registered (from the API's declarative `work` config + the tool result/args)
+ * and stashes the intent keyed by `toolCallId`. `call_tool` drains it and
+ * persists the Work version ONCE the tool call's cumulative cost is known, so
+ * the version lands with its `cumulativeCost` instead of created cost-less and
+ * back-filled — mirroring the server `resolveBuiltinToolWorkIntent`.
+ *
+ * A no-op for APIs that declare no `work` config or resolve to no targets.
+ */
+export const stashBuiltinToolWorkIntent = (
+ identifier: string,
+ apiName: string,
+ params: unknown,
+ ctx: BuiltinToolContext | undefined,
+ result: BuiltinToolResult,
+): void => {
+ const intent = resolveWorkRegistration(builtinTools, identifier, apiName, {
+ args: params,
+ result,
+ });
+ if (!intent) return;
+
+ stashWorkIntent(ctx?.toolCallId, intent);
+};
diff --git a/src/utils/clientWorkIntentStash.ts b/src/utils/clientWorkIntentStash.ts
new file mode 100644
index 00000000000..e22e620e55a
--- /dev/null
+++ b/src/utils/clientWorkIntentStash.ts
@@ -0,0 +1,43 @@
+import type { WorkRegistrationIntent } from '@lobechat/types';
+
+/**
+ * Per-tool-call hand-off for client (legacy, non-gateway) Work registration.
+ *
+ * The client tool-execution dispatch registers Works in three different places
+ * that do NOT return a rich result object up to `call_tool`:
+ * - task: the builtin executor registry (`invokeExecutor`) — returns the result
+ * object, but the intent is manifest-derived there;
+ * - skill (linear / github): `lobehubSkillExecutor`, whose dispatch returns only
+ * the truncated content STRING;
+ * - document: the agent-documents runtime, whose registration used to be a
+ * server-side side-effect of the lambda mutation.
+ *
+ * None of these can ride the intent back on the tool result (string results,
+ * side-effect registration), so each stashes a {@link WorkRegistrationIntent}
+ * keyed by `toolCallId` while executing, and `call_tool` drains it AFTER the
+ * tool's cumulative cost is known — writing the Work version ONCE with its
+ * `cumulativeCost` instead of registering cost-less then back-filling.
+ *
+ * Keyed by `toolCallId` (unique per call) so concurrent batch tool calls never
+ * collide. `take` deletes on read; `call_tool` drains the entry immediately
+ * after the tool returns — before any aborted/no-result early-return — so an
+ * entry is always freed even when the call is cancelled and never registered.
+ */
+const pendingWorkIntents = new Map<string, WorkRegistrationIntent>();
+
+export const stashWorkIntent = (
+ toolCallId: string | undefined,
+ intent: WorkRegistrationIntent,
+): void => {
+ if (!toolCallId) return;
+ pendingWorkIntents.set(toolCallId, intent);
+};
+
+export const takeWorkIntent = (
+ toolCallId: string | undefined,
+): WorkRegistrationIntent | undefined => {
+ if (!toolCallId) return undefined;
+ const intent = pendingWorkIntents.get(toolCallId);
+ if (intent) pendingWorkIntents.delete(toolCallId);
+ return intent;
+};
diff --git a/src/utils/workCumulativeUsage.test.ts b/src/utils/workCumulativeUsage.test.ts
new file mode 100644
index 00000000000..79c2f8be529
--- /dev/null
+++ b/src/utils/workCumulativeUsage.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildWorkVersionCumulativeUsage } from './workCumulativeUsage';
+
+describe('buildWorkVersionCumulativeUsage', () => {
+ it('returns null snapshots when runtime usage and cost are missing', () => {
+ expect(buildWorkVersionCumulativeUsage({})).toEqual({
+ cumulativeCost: null,
+ cumulativeUsage: null,
+ });
+ });
+
+ it('projects cumulative cost and usage into a stable Work version shape', () => {
+ const snapshot = buildWorkVersionCumulativeUsage({
+ cost: {
+ calculatedAt: '2026-06-30T08:00:00.000Z',
+ currency: 'USD',
+ llm: { byModel: [], currency: 'USD', total: 0.02 },
+ tools: { byTool: [], currency: 'USD', total: 0.01 },
+ total: 0.03,
+ },
+ now: new Date('2026-06-30T08:01:00.000Z'),
+ usage: {
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ llm: {
+ apiCalls: 1,
+ processingTimeMs: 500,
+ tokens: { input: 100, output: 20, total: 120 },
+ },
+ tools: {
+ byTool: [{ calls: 1, errors: 0, name: 'lobe-task/createTask', totalTimeMs: 20 }],
+ totalCalls: 1,
+ totalTimeMs: 20,
+ },
+ },
+ });
+
+ expect(snapshot).toEqual({
+ cumulativeCost: 0.03,
+ cumulativeUsage: {
+ capturedAt: '2026-06-30T08:01:00.000Z',
+ cost: expect.objectContaining({ total: 0.03 }),
+ usage: expect.objectContaining({
+ llm: expect.objectContaining({ apiCalls: 1 }),
+ tools: expect.objectContaining({ totalCalls: 1 }),
+ }),
+ },
+ });
+ });
+});
diff --git a/src/utils/workCumulativeUsage.ts b/src/utils/workCumulativeUsage.ts
new file mode 100644
index 00000000000..96e1b745282
--- /dev/null
+++ b/src/utils/workCumulativeUsage.ts
@@ -0,0 +1,25 @@
+import type { Cost, Usage } from '@lobechat/agent-runtime';
+import type { WorkVersionCumulativeUsage } from '@lobechat/types';
+
+const finiteNumberOrNull = (value: unknown): number | null =>
+ typeof value === 'number' && Number.isFinite(value) ? value : null;
+
+export const buildWorkVersionCumulativeUsage = ({
+ cost,
+ now = new Date(),
+ usage,
+}: {
+ cost?: Cost | null;
+ now?: Date;
+ usage?: Usage | null;
+}): { cumulativeCost: number | null; cumulativeUsage: WorkVersionCumulativeUsage | null } => ({
+ cumulativeCost: finiteNumberOrNull(cost?.total),
+ cumulativeUsage:
+ cost || usage
+ ? {
+ capturedAt: now.toISOString(),
+ cost: cost ?? null,
+ usage: usage ?? null,
+ }
+ : null,
+});
diff --git a/src/utils/workVersionCost.test.ts b/src/utils/workVersionCost.test.ts
new file mode 100644
index 00000000000..93c034badf6
--- /dev/null
+++ b/src/utils/workVersionCost.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+
+import { computeWorkVersionCostDeltas, formatWorkVersionCost } from './workVersionCost';
+
+describe('formatWorkVersionCost', () => {
+ it('hides missing or zero cost', () => {
+ expect(formatWorkVersionCost(null)).toBeNull();
+ expect(formatWorkVersionCost(0)).toBeNull();
+ });
+
+ it('keeps small cumulative costs visible', () => {
+ expect(formatWorkVersionCost(0.000_295)).toBe('$0.0003');
+ expect(formatWorkVersionCost(0.03)).toBe('$0.03');
+ });
+});
+
+describe('computeWorkVersionCostDeltas', () => {
+ it('diffs cumulative snapshots within one operation and keeps the first full', () => {
+ // Mirrors the real shape: v1 in op A, v2 + v3 in op B where v3's
+ // cumulative already contains v2's spend.
+ const deltas = computeWorkVersionCostDeltas([
+ { cumulativeCost: 0.003_747, id: 'v3', rootOperationId: 'op-b', version: 3 },
+ { cumulativeCost: 0.001_83, id: 'v2', rootOperationId: 'op-b', version: 2 },
+ { cumulativeCost: 0.000_306, id: 'v1', rootOperationId: 'op-a', version: 1 },
+ ]);
+
+ expect(deltas.get('v1')).toBeCloseTo(0.000_306, 6);
+ expect(deltas.get('v2')).toBeCloseTo(0.001_83, 6);
+ expect(deltas.get('v3')).toBeCloseTo(0.001_917, 6);
+ // Deltas sum back to the card total (max per operation, summed).
+ const total = [...deltas.values()].reduce((sum: number, cost) => sum + (cost ?? 0), 0);
+ expect(total).toBeCloseTo(0.004_053, 6);
+ });
+
+ it('treats versions without a rootOperationId as independent operations', () => {
+ const deltas = computeWorkVersionCostDeltas([
+ { cumulativeCost: 0.002, id: 'v1', rootOperationId: null, version: 1 },
+ { cumulativeCost: 0.003, id: 'v2', rootOperationId: null, version: 2 },
+ ]);
+
+ expect(deltas.get('v1')).toBe(0.002);
+ expect(deltas.get('v2')).toBe(0.003);
+ });
+
+ it('skips null costs without breaking the running snapshot chain', () => {
+ const deltas = computeWorkVersionCostDeltas([
+ { cumulativeCost: 0.001, id: 'v1', rootOperationId: 'op', version: 1 },
+ { cumulativeCost: null, id: 'v2', rootOperationId: 'op', version: 2 },
+ { cumulativeCost: 0.004, id: 'v3', rootOperationId: 'op', version: 3 },
+ ]);
+
+ expect(deltas.get('v1')).toBe(0.001);
+ expect(deltas.get('v2')).toBeNull();
+ expect(deltas.get('v3')).toBeCloseTo(0.003, 6);
+ });
+
+ it('clamps a decreasing snapshot to zero instead of rendering a negative cost', () => {
+ const deltas = computeWorkVersionCostDeltas([
+ { cumulativeCost: 0.005, id: 'v1', rootOperationId: 'op', version: 1 },
+ { cumulativeCost: 0.004, id: 'v2', rootOperationId: 'op', version: 2 },
+ ]);
+
+ expect(deltas.get('v2')).toBe(0);
+ });
+});
diff --git a/src/utils/workVersionCost.ts b/src/utils/workVersionCost.ts
new file mode 100644
index 00000000000..8684badc7a4
--- /dev/null
+++ b/src/utils/workVersionCost.ts
@@ -0,0 +1,54 @@
+export const formatWorkVersionCost = (cost?: number | null): string | null => {
+ if (!cost || cost <= 0) return null;
+
+ if (cost < 0.01) return `$${cost.toFixed(4)}`;
+
+ return `$${cost.toFixed(2)}`;
+};
+
+interface VersionCostInput {
+ cumulativeCost: number | null;
+ id: string;
+ rootOperationId: string | null;
+ version: number;
+}
+
+/**
+ * Derive each version's own spend from `cumulativeCost`, which is a running
+ * snapshot of the whole operation's spend at write time — NOT a per-version
+ * delta (see `packages/database/src/models/work/cost.ts`). Within one root
+ * operation, a version's cost is its cumulative minus the previous version's
+ * cumulative; the operation's first version keeps the full snapshot. Versions
+ * without a rootOperationId are independent operations. Summing the returned
+ * deltas therefore matches the Work's total cost shown on the summary card.
+ */
+export const computeWorkVersionCostDeltas = (
+ versions: VersionCostInput[],
+): Map<string, number | null> => {
+ const sorted = [...versions].sort((a, b) => a.version - b.version);
+ const deltas = new Map<string, number | null>();
+ const lastCumulativeByOperation = new Map<string, number>();
+
+ for (const version of sorted) {
+ if (version.cumulativeCost === null) {
+ deltas.set(version.id, null);
+ continue;
+ }
+ if (!version.rootOperationId) {
+ deltas.set(version.id, version.cumulativeCost);
+ continue;
+ }
+ const previous = lastCumulativeByOperation.get(version.rootOperationId);
+ // Cumulative snapshots are non-decreasing within an operation; clamp
+ // defensively so a bad row never renders a negative cost.
+ deltas.set(
+ version.id,
+ previous === undefined
+ ? version.cumulativeCost
+ : Math.max(0, version.cumulativeCost - previous),
+ );
+ lastCumulativeByOperation.set(version.rootOperationId, version.cumulativeCost);
+ }
+
+ return deltas;
+};