π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(work): register shell works for desktop-local hetero runs (#18488)
YuTengjingb0c732b13202
diff --git a/.agents/skills/agent-work/SKILL.md b/.agents/skills/agent-work/SKILL.mdindex 6297377c473..e240a6194b5 100644--- a/.agents/skills/agent-work/SKILL.md+++ b/.agents/skills/agent-work/SKILL.md@@ -26,8 +26,8 @@ Four write paths, two timing classes:| Path | When | Where || ----------------------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- || Skill structured tools + sandbox `runCommand` (github / linear) | at tool execution | `WorkModel.handleSkillToolResult`, called from server `toolExecution` and the client executor (`registerClientWorkFromIntent.ts` on the legacy non-gateway runtime) |-| Shell Work scan (hetero codex/claude-code + device `lobe-local-system`) | at operation completion | `apps/server/src/services/agentRuntime/shellWorkRegistration.ts` via `registerWorksForOperation` |-| File Work scan (sandbox entity files) | at operation completion | `apps/server/src/services/agentRuntime/workRegistration.ts` |+| Shell Work scan (hetero codex/claude-code + device `lobe-local-system`) | at operation completion | `apps/server/src/services/workRegistration/shellWorkRegistration.ts` via `registerWorksForOperation` |+| File Work scan (sandbox entity files) | at operation completion | `apps/server/src/services/workRegistration/registerWorksForOperation.ts` || Task / document works | at creation by their owning feature | `WorkModel.registerTask` / `registerDocument` |### Execution-time: skill providers@@ -41,7 +41,7 @@ A normalizer turns one tool result into `ExternalToolWorkOperation | null` β nHeterogeneous CLI agents (codex, claude-code) and the device `lobe-local-system` tool run CLIs like `gh` through their own shell surfaces, which never pass the skill-tool hook. `registerWorksForOperation` recovers their Works at completion from the persisted command text + stdout. Layering:```-registerWorksForOperation (workRegistration.ts)+registerWorksForOperation (registerWorksForOperation.ts)ββ collectOperationRecords one pass over the operation tree, shared by both scansββ registerShellWorks (shellWorkRegistration.ts β the ENGINE, command-agnostic)β ββ SHELL_COMMAND_SOURCES identifierβapiName scoping of shell surfaces@@ -98,7 +98,7 @@ The whole scan returns `{attempted, failed}` and the completion backstop (`Compl**New shell CLI scanner, e.g. `linear` CLI or `vercel deploy`:**1. Add a normalizer in `packages/database/src/models/work/` reusing `parseShellCommandSegments`, plus a `WorkModel.registerShell<X>Result` facade method.-2. Add `apps/server/src/services/agentRuntime/shellWorkScanners/<name>.ts` with `{ matches, name, register }` β `matches` stays a cheap substring check.+2. Add `apps/server/src/services/workRegistration/shellWorkScanners/<name>.ts` with `{ matches, name, register }` β `matches` stays a cheap substring check.3. Append it to `SHELL_WORK_SCANNERS` in `shellWorkScanners/index.ts`. The engine needs zero changes.4. Pin the parsing edge cases in `packages/database/src/models/work/__tests__/` (wrapper unwrap, chained segments, failed/read-only commands must not register).@@ -111,14 +111,15 @@ The whole scan returns `{attempted, failed}` and the completion backstop (`Compl## File map-| Concern | Path |-| ---------------------------------------------------- | ---------------------------------------------------------------- |-| Schema | `packages/database/src/schemas/work.ts` |-| Type registry + read gate | `packages/database/src/models/work/registry.ts` |-| WorkModel facade + provider normalizer map | `packages/database/src/models/work/index.ts` |-| gh CLI + structured github normalizer | `packages/database/src/models/work/githubToolResult.ts` |-| Command-agnostic shell parsing | `packages/database/src/models/work/shellCommandParsing.ts` |-| Completion scan orchestrator (file + shell + anchor) | `apps/server/src/services/agentRuntime/workRegistration.ts` |-| Shell scan engine | `apps/server/src/services/agentRuntime/shellWorkRegistration.ts` |-| Per-CLI scanners | `apps/server/src/services/agentRuntime/shellWorkScanners/` |-| Client (non-gateway) registration | `src/store/chat/agents/registerClientWorkFromIntent.ts` |+| Concern | Path |+| ---------------------------------------------------- | ------------------------------------------------------------------------ |+| Schema | `packages/database/src/schemas/work.ts` |+| Type registry + read gate | `packages/database/src/models/work/registry.ts` |+| WorkModel facade + provider normalizer map | `packages/database/src/models/work/index.ts` |+| gh CLI + structured github normalizer | `packages/database/src/models/work/githubToolResult.ts` |+| Command-agnostic shell parsing | `packages/database/src/models/work/shellCommandParsing.ts` |+| Completion scan orchestrator (file + shell + anchor) | `apps/server/src/services/workRegistration/registerWorksForOperation.ts` |+| Shell scan engine | `apps/server/src/services/workRegistration/shellWorkRegistration.ts` |+| Desktop-local run scan (client-reported) | `apps/server/src/services/workRegistration/localRunWorkRegistration.ts` |+| Per-CLI scanners | `apps/server/src/services/workRegistration/shellWorkScanners/` |+| Client (non-gateway) registration | `src/store/chat/agents/registerClientWorkFromIntent.ts` |diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.tsindex d823958b076..b229305c764 100644--- a/apps/server/src/routers/lambda/work.ts+++ b/apps/server/src/routers/lambda/work.ts@@ -9,9 +9,11 @@ import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { MessageModel } from '@/database/models/message';import { WorkModel } from '@/database/models/work';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { registerShellWorksForLocalRun } from '@/server/services/workRegistration';const workProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -19,6 +21,7 @@ const workProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>return opts.next({ctx: {+ messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),workModel: new WorkModel(ctx.serverDB, ctx.userId, wsId),},});@@ -182,4 +185,30 @@ export const workRouter = router({handleSkillToolResult: skillWorkProcedureWrite.input(registerSkillToolResultSchema).mutation(async ({ ctx, input }) => ctx.workModel.handleSkillToolResult(input)),++ // Completion-time shell Work scan for desktop-LOCAL hetero runs (Claude+ // Code / Codex with execution target `local`). Those runs create no+ // `agent_operations` row and never call `heteroFinish`, so the server-side+ // completion scan (`registerWorksForOperation`) structurally cannot fire β+ // the client executor reports the run's persisted tool message ids here+ // instead. Everything is re-read ownership- and topic-scoped from the DB, so+ // the caller can only ever scan rows it already owns. Same write gate as the+ // other external-provider registrations.+ registerShellWorksForRun: skillWorkProcedureWrite+ .input(+ z.object({+ anchorMessageId: z.string().min(1),+ messageIds: z.array(z.string()).min(1).max(500),+ topicId: z.string().min(1),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ registerShellWorksForLocalRun({+ anchorMessageId: input.anchorMessageId,+ messageIds: input.messageIds,+ messageModel: ctx.messageModel,+ topicId: input.topicId,+ workModel: ctx.workModel,+ }),+ ),});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex fc34a0ad841..e3a14f3598b 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -61,6 +61,7 @@ import { QueueService } from '@/server/services/queue';import { LocalQueueServiceImpl } from '@/server/services/queue/impls';import { ToolExecutionService } from '@/server/services/toolExecution';import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';+import { stateHasEntityFileEdits } from '@/server/services/workRegistration';import { isAbortError, throwIfAborted } from './abort';import {@@ -93,7 +94,6 @@ import {type StepCompletionReason,type SubAgentBridgeParams,} from './types';-import { stateHasEntityFileEdits } from './workRegistration';if (process.env.VERCEL) {// Route debug output to stdout (`console.info`) instead of stderr, whichdiff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex c8334a57268..533983af8ab 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -19,10 +19,10 @@ import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';import { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';import { instantiateVerifyPlanOnStart, runVerifyOnCompletion } from '@/server/services/verify';+import { registerWorksForOperation } from '@/server/services/workRegistration';import { after } from '@/server/utils/scheduleAfterResponse';import { CriticalHookDeliveryError, hookDispatcher, type SerializedHook } from './hooks';-import { registerWorksForOperation } from './workRegistration';const log = debug('lobe-server:completion-lifecycle');diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex 48944b1ffe7..38e4e73b824 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -5,10 +5,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import * as agentSignalService from '@/server/services/agentSignal';import * as verifyServices from '@/server/services/verify';+import { registerWorksForOperation } from '@/server/services/workRegistration';import { CompletionLifecycle, isSuccessLikeCompletionReason } from '../CompletionLifecycle';import { CriticalHookDeliveryError, hookDispatcher } from '../hooks';-import { registerWorksForOperation } from '../workRegistration';// Default async no-op implementation: the production code chains `.catch` on// the returned promise, so a bare vi.fn() (returning undefined) would throw@@ -22,7 +22,7 @@ vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () => ({notifyAgentRunCompleted: mockNotifyAgentRunCompleted,}));-vi.mock('../workRegistration', () => ({+vi.mock('@/server/services/workRegistration', () => ({registerWorksForOperation: vi.fn(),}));diff --git a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.tsindex 19159877ab1..ac0e6b627eb 100644--- a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts@@ -12,7 +12,7 @@ vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after }));vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () => ({notifyAgentRunCompleted: vi.fn(async () => {}),}));-vi.mock('../workRegistration', () => ({ registerWorksForOperation: vi.fn() }));+vi.mock('@/server/services/workRegistration', () => ({ registerWorksForOperation: vi.fn() }));/*** Regression: the completion-time verify gate used to be launched with a barediff --git a/apps/server/src/services/workRegistration/constants.ts b/apps/server/src/services/workRegistration/constants.tsnew file mode 100644index 00000000000..d74f0e5349d--- /dev/null+++ b/apps/server/src/services/workRegistration/constants.ts@@ -0,0 +1,13 @@+/**+ * Human-intervention statuses whose tool NEVER executed. `requestHumanApprove`+ * persists an EMPTY tool row (`content: ''`, no result state) with+ * `intervention.status='pending'` when it parks; a rejected/aborted approval+ * leaves that row unexecuted too (rejection writes only content text, no state+ * and no plugin error). The scanner's sandbox writeFile/editFile branch falls+ * back from a missing `state.path` to `arguments.path`, so without this filter+ * an unexecuted row would register β and export stale sandbox content for β a+ * file the user never approved writing. `approved` rows execute on resume and+ * carry a real result state, so they pass through. Shared by every record+ * collection that feeds the Work scans (operation-tree and local-run).+ */+export const UNEXECUTED_INTERVENTION_STATUSES = new Set(['pending', 'rejected', 'aborted']);diff --git a/apps/server/src/services/workRegistration/index.ts b/apps/server/src/services/workRegistration/index.tsnew file mode 100644index 00000000000..085ce67b7a0--- /dev/null+++ b/apps/server/src/services/workRegistration/index.ts@@ -0,0 +1,29 @@+/**+ * Work registration service β turns what an agent run produced into durable+ * Work rows (`works` / `work_versions`) and stamps the display anchor that+ * makes the cards render.+ *+ * - `registerWorksForOperation` β completion-time scan of a server operation+ * tree: entity `file` Works (sandbox export pipeline) + the shell Work scan+ * (gh CLI runs from codex / claude-code / device `lobe-local-system`).+ * - `registerShellWorksForLocalRun` β the same shell scan replayed for+ * desktop-LOCAL hetero runs, which have no `agent_operations` row and are+ * reported by the client executor instead.+ * - `stateHasEntityFileEdits` β pure per-step predicate over the in-memory+ * runtime state, used to suppress the early `visible_output_end` when+ * completion will export files.+ *+ * Execution-time registrations (skill structured tools, task / document+ * works) live with their owning features β see `WorkModel` and the agent-work+ * skill's file map.+ */+export {+ type LocalRunShellWorksResult,+ registerShellWorksForLocalRun,+} from './localRunWorkRegistration';+export {+ registerWorksForOperation,+ type RegisterWorksForOperationParams,+ type WorksRegistrationOutcome,+} from './registerWorksForOperation';+export { stateHasEntityFileEdits } from './stateHasEntityFileEdits';diff --git a/apps/server/src/services/workRegistration/localRunWorkRegistration.test.ts b/apps/server/src/services/workRegistration/localRunWorkRegistration.test.tsnew file mode 100644index 00000000000..46a08723bdd--- /dev/null+++ b/apps/server/src/services/workRegistration/localRunWorkRegistration.test.ts@@ -0,0 +1,148 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { registerShellWorksForLocalRun } from './localRunWorkRegistration';++const anchor = {+ agentId: 'agent-1',+ id: 'msg-anchor',+ metadata: null as Record<string, any> | null,+ role: 'assistant',+ threadId: null,+ topicId: 'topic-1',+};++/** A claude-code Bash tool row whose stdout carries a gh-created PR URL. */+const ghCreateRow = (id: string) => ({+ apiName: 'Bash',+ arguments: JSON.stringify({ command: 'gh pr create --title test' }),+ content: 'https://github.com/acme/repo/pull/7\n',+ createdAt: new Date('2026-08-17T08:30:46.000Z'),+ error: undefined,+ id,+ identifier: 'claude-code',+ state: undefined,+ toolCallId: `call-${id}`,+ type: 'default',+ userId: 'user-1',+});++const createModels = () => {+ const messageModel = {+ findById: vi.fn(async () => ({ ...anchor })),+ listMessagePluginsByIds: vi.fn(async () => [ghCreateRow('msg-tool-1')]),+ update: vi.fn(async () => ({ success: true })),+ };+ const workModel = {+ registerShellGithubResult: vi.fn(async () => ({ id: 'wk-1' })),+ };+ return { messageModel: messageModel as any, workModel: workModel as any };+};++const baseParams = (models: ReturnType<typeof createModels>) => ({+ anchorMessageId: 'msg-anchor',+ messageIds: ['msg-tool-1'],+ topicId: 'topic-1',+ ...models,+});++describe('registerShellWorksForLocalRun', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('registers a github work from a gh create row and stamps the anchor', async () => {+ const models = createModels();++ const result = await registerShellWorksForLocalRun(baseParams(models));++ expect(result).toEqual({+ failed: 0,+ registered: 1,+ rootOperationId: 'localrun_msg-anchor',+ });+ expect(models.workModel.registerShellGithubResult).toHaveBeenCalledWith(+ expect.objectContaining({+ // Local runs carry no server-side usage snapshot β cost must stay+ // unknown (null), never zero.+ cumulativeCost: null,+ data: expect.objectContaining({ command: 'gh pr create --title test' }),+ messageId: 'msg-tool-1',+ rootOperationId: 'localrun_msg-anchor',+ toolCallId: 'call-msg-tool-1',+ topicId: 'topic-1',+ }),+ );+ expect(models.messageModel.update).toHaveBeenCalledWith('msg-anchor', {+ metadata: { work: { rootOperationId: 'localrun_msg-anchor' } },+ });+ });++ it('rejects an anchor that is missing, foreign-topic, or not an assistant message', async () => {+ for (const badAnchor of [+ undefined,+ { ...anchor, topicId: 'topic-other' },+ { ...anchor, role: 'user' },+ ]) {+ const models = createModels();+ models.messageModel.findById.mockResolvedValue(badAnchor as any);++ const result = await registerShellWorksForLocalRun(baseParams(models));++ expect(result).toEqual({ failed: 0, registered: 0, rootOperationId: null });+ expect(models.messageModel.listMessagePluginsByIds).not.toHaveBeenCalled();+ expect(models.workModel.registerShellGithubResult).not.toHaveBeenCalled();+ }+ });++ it('reuses an already-stamped rootOperationId and does not re-stamp', async () => {+ const models = createModels();+ models.messageModel.findById.mockResolvedValue({+ ...anchor,+ metadata: { work: { rootOperationId: 'localrun_prior' } },+ } as any);++ const result = await registerShellWorksForLocalRun(baseParams(models));++ expect(result.rootOperationId).toBe('localrun_prior');+ expect(models.workModel.registerShellGithubResult).toHaveBeenCalledWith(+ expect.objectContaining({ rootOperationId: 'localrun_prior' }),+ );+ expect(models.messageModel.update).not.toHaveBeenCalled();+ });++ it('registers nothing and never stamps when rows carry no registerable command', async () => {+ const models = createModels();+ models.messageModel.listMessagePluginsByIds.mockResolvedValue([+ { ...ghCreateRow('msg-tool-1'), arguments: JSON.stringify({ command: 'ls -la' }) },+ ] as any);++ const result = await registerShellWorksForLocalRun(baseParams(models));++ expect(result).toEqual({ failed: 0, registered: 0, rootOperationId: null });+ expect(models.workModel.registerShellGithubResult).not.toHaveBeenCalled();+ expect(models.messageModel.update).not.toHaveBeenCalled();+ });++ it('skips failed commands and unexecuted intervention rows', async () => {+ const models = createModels();+ models.messageModel.listMessagePluginsByIds.mockResolvedValue([+ { ...ghCreateRow('msg-err'), error: { message: 'boom' } },+ { ...ghCreateRow('msg-pending'), intervention: { status: 'pending' } },+ ] as any);++ const result = await registerShellWorksForLocalRun(baseParams(models));++ expect(result.registered).toBe(0);+ expect(models.workModel.registerShellGithubResult).not.toHaveBeenCalled();+ });++ it('counts a failed anchor stamp into failed', async () => {+ const models = createModels();+ models.messageModel.update.mockResolvedValue({ success: false } as any);++ const result = await registerShellWorksForLocalRun(baseParams(models));++ expect(result.registered).toBe(1);+ expect(result.failed).toBe(1);+ });+});diff --git a/apps/server/src/services/workRegistration/localRunWorkRegistration.ts b/apps/server/src/services/workRegistration/localRunWorkRegistration.tsnew file mode 100644index 00000000000..e5d3678117c--- /dev/null+++ b/apps/server/src/services/workRegistration/localRunWorkRegistration.ts@@ -0,0 +1,119 @@+import debug from 'debug';++import type { MessageModel } from '@/database/models/message';+import type { WorkModel } from '@/database/models/work';++import { UNEXECUTED_INTERVENTION_STATUSES } from './constants';+import { registerShellWorks } from './shellWorkRegistration';++const log = debug('lobe-server:local-run-work-registration');++/**+ * Prefix for the synthetic root operation id minted for desktop-local hetero+ * runs. Local runs are entirely client-driven (no `agent_operations` row, no+ * `CompletionLifecycle`), yet the Works read path joins strictly on+ * `work_versions.rootOperationId = metadata.work.rootOperationId` β so the scan+ * needs SOME stable id to key both sides. Deriving it from the anchor message+ * id keeps retries idempotent without persisting extra state; the column has no+ * FK, so a non-operation id is safe.+ */+const LOCAL_RUN_OPERATION_PREFIX = 'localrun';++export interface LocalRunShellWorksResult {+ failed: number;+ registered: number;+ /** The rootOperationId works were registered under (echoed for client-side refresh). */+ rootOperationId: string | null;+}++/**+ * Completion-time shell Work scan for a DESKTOP-LOCAL heterogeneous run+ * (Claude Code / Codex with execution target `local`).+ *+ * Those runs never reach `registerWorksForOperation` β the sole caller of the+ * shell scan β because they create no server operation and never call+ * `heteroFinish`; their `gh pr create` output lands as plain persisted tool+ * messages that nothing inspects (LOBE-12514). The client executor therefore+ * reports the run's persisted tool message ids at clean completion, and this+ * service replays the SAME scan engine over those rows:+ *+ * 1. Verify the anchor assistant message belongs to the caller + topic.+ * 2. Load the tool rows ownership- and topic-scoped (`listMessagePluginsByIds`).+ * 3. Run `registerShellWorks` under a synthetic anchor-derived rootOperationId.+ * 4. Stamp `metadata.work.rootOperationId` on the anchor so the card renders.+ *+ * Cost is intentionally null: local runs have no server-side usage snapshot+ * (hetero CLI spend is not metered per tool call), and null renders as+ * "unknown", never $0.00.+ *+ * Idempotent end to end: the version write dedupes on `(workId, toolCallId)`+ * and re-stamping the same rootOperationId is a metadata deep-merge no-op.+ */+export const registerShellWorksForLocalRun = async (params: {+ anchorMessageId: string;+ messageIds: string[];+ messageModel: MessageModel;+ topicId: string;+ workModel: WorkModel;+}): Promise<LocalRunShellWorksResult> => {+ const { anchorMessageId, messageIds, messageModel, topicId, workModel } = params;++ const anchor = await messageModel.findById(anchorMessageId);+ // The anchor must be an assistant message of the claimed topic β anything+ // else (missing, foreign, wrong role) makes the whole report untrustworthy.+ if (!anchor || anchor.topicId !== topicId || anchor.role !== 'assistant') {+ log('Rejected local run scan: invalid anchor %s for topic %s', anchorMessageId, topicId);+ return { failed: 0, registered: 0, rootOperationId: null };+ }++ const rows = await messageModel.listMessagePluginsByIds({ ids: messageIds, topicId });+ const records = rows+ .filter((row) => {+ const interventionStatus = (row.intervention as { status?: string } | undefined)?.status;+ return !(interventionStatus && UNEXECUTED_INTERVENTION_STATUSES.has(interventionStatus));+ })+ .map((row) => ({+ apiName: row.apiName ?? '',+ arguments: row.arguments,+ content: row.content,+ error: row.error,+ id: row.id,+ identifier: row.identifier,+ state: row.state,+ toolCallId: row.toolCallId ?? '',+ }));+ if (records.length === 0) return { failed: 0, registered: 0, rootOperationId: null };++ // Reuse an id a prior (retried) scan already stamped so versions and anchor+ // stay on one key; otherwise derive it from the anchor message id.+ const stampedRootId = (anchor.metadata as { work?: { rootOperationId?: string } } | null)?.work+ ?.rootOperationId;+ const rootOperationId = stampedRootId ?? `${LOCAL_RUN_OPERATION_PREFIX}_${anchorMessageId}`;++ const outcome = await registerShellWorks({+ agentId: anchor.agentId,+ cumulativeCost: null,+ cumulativeUsage: null,+ operationId: rootOperationId,+ records,+ threadId: anchor.threadId,+ topicId,+ workModel,+ });++ if (outcome.registered > 0 && !stampedRootId) {+ const stamp = await messageModel.update(anchorMessageId, {+ metadata: { work: { rootOperationId } },+ });+ if (!stamp.success) {+ outcome.failed += 1;+ log('Failed to stamp local run work anchor on %s', anchorMessageId);+ }+ }++ return {+ failed: outcome.failed,+ registered: outcome.registered,+ rootOperationId: outcome.registered > 0 ? rootOperationId : null,+ };+};diff --git a/apps/server/src/services/agentRuntime/workRegistration.test.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.test.tssimilarity index 99%rename from apps/server/src/services/agentRuntime/workRegistration.test.tsrename to apps/server/src/services/workRegistration/registerWorksForOperation.test.tsindex 764171fa017..a035a068df6 100644--- a/apps/server/src/services/agentRuntime/workRegistration.test.ts+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts@@ -1,10 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import {- redeployFileWork,- registerWorksForOperation,- stateHasEntityFileEdits,-} from './workRegistration';+import { redeployFileWork, registerWorksForOperation } from './registerWorksForOperation';+import { stateHasEntityFileEdits } from './stateHasEntityFileEdits';const {mockFindById,diff --git a/apps/server/src/services/agentRuntime/workRegistration.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.tssimilarity index 79%rename from apps/server/src/services/agentRuntime/workRegistration.tsrename to apps/server/src/services/workRegistration/registerWorksForOperation.tsindex c648d88275c..0e4363dd76c 100644--- a/apps/server/src/services/agentRuntime/workRegistration.ts+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.ts@@ -22,6 +22,7 @@ import { FileService } from '@/server/services/file';import { MarketService } from '@/server/services/market';import { createSandboxService } from '@/server/services/sandbox';+import { UNEXECUTED_INTERVENTION_STATUSES } from './constants';import { registerShellWorks } from './shellWorkRegistration';const log = debug('lobe-server:file-work-registration');@@ -134,124 +135,6 @@ export const redeployFileWork = async (_params: {// No-op: file-source deployment is implemented in a follow-up.};-/**- * Predict from the in-memory runtime state whether this operation edited any- * entity-format file (pptx / xlsx / docx / pdf, β¦) β i.e. whether completion- * will register `file` Works and export them from the sandbox.- *- * Used per step when computing `allowEarlyFinalAnswerVisibleOutputEnd`: when- * an entity edit is present, the early `visible_output_end` is suppressed so- * the client's loading state honestly covers the export/registration window- * and the file-Work card arrives together with `agent_runtime_end`'s terminal- * snapshot instead of popping in after loading already ended.- *- * Deliberately a pure, best-effort scan over `state.messages`. TWO message- * shapes must be handled (mirrors `messageSelectors.collectToolInvocations`):- * raw in-memory assistant rows carrying OpenAI-style `tool_calls` (wire names- * follow `identifier____apiName[____type]`, see ToolNameResolver;- * `lobe-cloud-sandbox` and its apiNames survive normalization verbatim), and- * conversation-flow grouped nodes β the runtime re-queries `state.messages`- * with `flatten: true` after every tool batch (see `callToolsBatch`), which- * folds this run's turn into `assistantGroup`/`supervisor` nodes whose tool- * calls live on `children[].tools[]` (with the result re-attached as- * `result.state`). At the final-answer step the sandbox edits are therefore- * usually in the GROUPED shape; scanning `tool_calls` alone would miss them.- *- * Scoped to the CURRENT run: only messages after the LAST `user` row are- * scanned β an operation always answers the latest user turn, and earlier- * turns' entity edits registered on their own completion. Counting them would- * permanently disable the early publish for every later run in the topic.- *- * Best-effort by design:- * - Only sandbox calls are considered β hetero (codex / claude-code) edits- * need result state this scan doesn't have, and hetero runs don't go- * through this executor path anyway.- * - For raw `tool_calls` no result exists yet, so a FAILED entity write still- * returns true: the only cost is a delayed loading end for that rare case,- * while a false `false` would resurrect the card-after-loading glitch.- * - `moveFiles` renames are only classifiable from the tool RESULT- * (`state.results`); when it is absent, over-approximate from the requested- * `operations[].destination` arguments instead β same accepted cost.- * - `exportFile` calls targeting an entity path count too β code-generated- * artifacts (python-pptx / reportlab / β¦) never appear as edits, and their- * export is exactly what completion will register as a file Work. This- * includes the skills tool's export surface (`lobe-skills` exportFile),- * which skill-driven flows (e.g. the pptx skill) use instead of the sandbox- * tool's.- * - Any malformed shape returns false β today's early-publish behavior.- */-export const stateHasEntityFileEdits = (state: any): boolean => {- const allMessages: any[] = Array.isArray(state?.messages) ? state.messages : [];- const lastUserIndex = allMessages.findLastIndex((message: any) => message?.role === 'user');- const messages = allMessages.slice(lastUserIndex + 1);-- const sandboxPrefix = `${CLOUD_SANDBOX_IDENTIFIER}____`;- const skillsExportPrefix = `${SkillsIdentifier}____exportFile`;- const records: FileEditToolCallRecord[] = [];-- for (const message of messages) {- // Shape 1: raw assistant rows appended in-memory during the current step.- if (message?.role === 'assistant' && Array.isArray(message.tool_calls)) {- for (const call of message.tool_calls) {- const name: unknown = call?.function?.name;- if (typeof name !== 'string') continue;- const rawArguments =- typeof call?.function?.arguments === 'string' ? call.function.arguments : '';- // Skills export surface: only exportFile is relevant (its runCommand /- // execScript never carry an output path), and args-only entity checks- // over-approximate success just like the sandbox exportFile below.- if (name.startsWith(skillsExportPrefix) && exportArgsTargetEntityFile(rawArguments))- return true;- if (!name.startsWith(sandboxPrefix)) continue;- const apiName = name.split('____')[1] ?? '';- if (apiName === 'moveFiles' && moveArgsTargetEntityFile(rawArguments)) return true;- if (apiName === 'exportFile' && exportArgsTargetEntityFile(rawArguments)) return true;- records.push({- apiName,- arguments: rawArguments,- identifier: CLOUD_SANDBOX_IDENTIFIER,- toolCallId: typeof call?.id === 'string' ? call.id : '',- });- }- }-- // Shape 2: conversation-flow grouped nodes (assistantGroup / supervisor)- // with parsed tool payloads on `children[].tools[]`.- if (!Array.isArray(message?.children)) continue;- for (const child of message.children) {- if (!Array.isArray(child?.tools)) continue;- for (const tool of child.tools) {- if (- tool?.identifier === SkillsIdentifier &&- tool.apiName === 'exportFile' &&- exportArgsTargetEntityFile(typeof tool.arguments === 'string' ? tool.arguments : '')- )- return true;- if (tool?.identifier !== CLOUD_SANDBOX_IDENTIFIER) continue;- const apiName = typeof tool.apiName === 'string' ? tool.apiName : '';- const rawArguments = typeof tool.arguments === 'string' ? tool.arguments : '';- const resultState = tool.result?.state;- if (apiName === 'moveFiles' && !resultState && moveArgsTargetEntityFile(rawArguments))- return true;- if (apiName === 'exportFile' && exportArgsTargetEntityFile(rawArguments)) return true;- records.push({- apiName,- arguments: rawArguments,- error: tool.result?.error,- identifier: CLOUD_SANDBOX_IDENTIFIER,- state: resultState,- toolCallId: typeof tool.id === 'string' ? tool.id : '',- });- }- }- }- if (records.length === 0) return false;-- return scanOperationFileEdits(records).some(- (entry) => classifyEditedFile(entry.path).category === 'entity',- );-};-/*** Sandbox location of a successful `exportFile` call, across both export* surfaces:@@ -295,44 +178,6 @@ const resolveExportedSandboxPath = (return undefined;};-/** Whether a sandbox `exportFile` call's arguments target an entity file. */-const exportArgsTargetEntityFile = (rawArguments: string): boolean => {- try {- const path: unknown = JSON.parse(rawArguments)?.path;- return typeof path === 'string' && classifyEditedFile(path).category === 'entity';- } catch {- return false;- }-};--/** Whether a sandbox `moveFiles` call's arguments request an entity-file destination. */-const moveArgsTargetEntityFile = (rawArguments: string): boolean => {- try {- const operations: unknown = JSON.parse(rawArguments)?.operations;- if (!Array.isArray(operations)) return false;- return operations.some(- (op: any) =>- typeof op?.destination === 'string' &&- classifyEditedFile(op.destination).category === 'entity',- );- } catch {- return false;- }-};--/**- * Human-intervention statuses whose tool NEVER executed. `requestHumanApprove`- * persists an EMPTY tool row (`content: ''`, no result state) with- * `intervention.status='pending'` when it parks; a rejected/aborted approval- * leaves that row unexecuted too (rejection writes only content text, no state- * and no plugin error). The scanner's sandbox writeFile/editFile branch falls- * back from a missing `state.path` to `arguments.path`, so without this filter- * an unexecuted row would register β and export stale sandbox content for β a- * file the user never approved writing. `approved` rows execute on resume and- * carry a real result state, so they pass through.- */-const UNEXECUTED_INTERVENTION_STATUSES = new Set(['pending', 'rejected', 'aborted']);-/*** Collect every tool call of the operation tree, de-duplicated by message id and* ordered by the owning message's `createdAt` so the scanner's order-sensitivediff --git a/apps/server/src/services/agentRuntime/shellWorkRegistration.ts b/apps/server/src/services/workRegistration/shellWorkRegistration.tssimilarity index 100%rename from apps/server/src/services/agentRuntime/shellWorkRegistration.tsrename to apps/server/src/services/workRegistration/shellWorkRegistration.tsdiff --git a/apps/server/src/services/agentRuntime/shellWorkScanners/github.ts b/apps/server/src/services/workRegistration/shellWorkScanners/github.tssimilarity index 100%rename from apps/server/src/services/agentRuntime/shellWorkScanners/github.tsrename to apps/server/src/services/workRegistration/shellWorkScanners/github.tsdiff --git a/apps/server/src/services/agentRuntime/shellWorkScanners/index.ts b/apps/server/src/services/workRegistration/shellWorkScanners/index.tssimilarity index 100%rename from apps/server/src/services/agentRuntime/shellWorkScanners/index.tsrename to apps/server/src/services/workRegistration/shellWorkScanners/index.tsdiff --git a/apps/server/src/services/agentRuntime/shellWorkScanners/types.ts b/apps/server/src/services/workRegistration/shellWorkScanners/types.tssimilarity index 100%rename from apps/server/src/services/agentRuntime/shellWorkScanners/types.tsrename to apps/server/src/services/workRegistration/shellWorkScanners/types.tsdiff --git a/apps/server/src/services/workRegistration/stateHasEntityFileEdits.ts b/apps/server/src/services/workRegistration/stateHasEntityFileEdits.tsnew file mode 100644index 00000000000..0ec3ee332b4--- /dev/null+++ b/apps/server/src/services/workRegistration/stateHasEntityFileEdits.ts@@ -0,0 +1,150 @@+import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';+import {+ classifyEditedFile,+ CLOUD_SANDBOX_IDENTIFIER,+ type FileEditToolCallRecord,+ scanOperationFileEdits,+} from '@lobechat/builtin-tools/fileEditScan';++/** Whether a sandbox `exportFile` call's arguments target an entity file. */+const exportArgsTargetEntityFile = (rawArguments: string): boolean => {+ try {+ const path: unknown = JSON.parse(rawArguments)?.path;+ return typeof path === 'string' && classifyEditedFile(path).category === 'entity';+ } catch {+ return false;+ }+};++/** Whether a sandbox `moveFiles` call's arguments request an entity-file destination. */+const moveArgsTargetEntityFile = (rawArguments: string): boolean => {+ try {+ const operations: unknown = JSON.parse(rawArguments)?.operations;+ if (!Array.isArray(operations)) return false;+ return operations.some(+ (op: any) =>+ typeof op?.destination === 'string' &&+ classifyEditedFile(op.destination).category === 'entity',+ );+ } catch {+ return false;+ }+};++/**+ * Predict from the in-memory runtime state whether this operation edited any+ * entity-format file (pptx / xlsx / docx / pdf, β¦) β i.e. whether completion+ * will register `file` Works and export them from the sandbox.+ *+ * Used per step when computing `allowEarlyFinalAnswerVisibleOutputEnd`: when+ * an entity edit is present, the early `visible_output_end` is suppressed so+ * the client's loading state honestly covers the export/registration window+ * and the file-Work card arrives together with `agent_runtime_end`'s terminal+ * snapshot instead of popping in after loading already ended.+ *+ * Deliberately a pure, best-effort scan over `state.messages`. TWO message+ * shapes must be handled (mirrors `messageSelectors.collectToolInvocations`):+ * raw in-memory assistant rows carrying OpenAI-style `tool_calls` (wire names+ * follow `identifier____apiName[____type]`, see ToolNameResolver;+ * `lobe-cloud-sandbox` and its apiNames survive normalization verbatim), and+ * conversation-flow grouped nodes β the runtime re-queries `state.messages`+ * with `flatten: true` after every tool batch (see `callToolsBatch`), which+ * folds this run's turn into `assistantGroup`/`supervisor` nodes whose tool+ * calls live on `children[].tools[]` (with the result re-attached as+ * `result.state`). At the final-answer step the sandbox edits are therefore+ * usually in the GROUPED shape; scanning `tool_calls` alone would miss them.+ *+ * Scoped to the CURRENT run: only messages after the LAST `user` row are+ * scanned β an operation always answers the latest user turn, and earlier+ * turns' entity edits registered on their own completion. Counting them would+ * permanently disable the early publish for every later run in the topic.+ *+ * Best-effort by design:+ * - Only sandbox calls are considered β hetero (codex / claude-code) edits+ * need result state this scan doesn't have, and hetero runs don't go+ * through this executor path anyway.+ * - For raw `tool_calls` no result exists yet, so a FAILED entity write still+ * returns true: the only cost is a delayed loading end for that rare case,+ * while a false `false` would resurrect the card-after-loading glitch.+ * - `moveFiles` renames are only classifiable from the tool RESULT+ * (`state.results`); when it is absent, over-approximate from the requested+ * `operations[].destination` arguments instead β same accepted cost.+ * - `exportFile` calls targeting an entity path count too β code-generated+ * artifacts (python-pptx / reportlab / β¦) never appear as edits, and their+ * export is exactly what completion will register as a file Work. This+ * includes the skills tool's export surface (`lobe-skills` exportFile),+ * which skill-driven flows (e.g. the pptx skill) use instead of the sandbox+ * tool's.+ * - Any malformed shape returns false β today's early-publish behavior.+ */+export const stateHasEntityFileEdits = (state: any): boolean => {+ const allMessages: any[] = Array.isArray(state?.messages) ? state.messages : [];+ const lastUserIndex = allMessages.findLastIndex((message: any) => message?.role === 'user');+ const messages = allMessages.slice(lastUserIndex + 1);++ const sandboxPrefix = `${CLOUD_SANDBOX_IDENTIFIER}____`;+ const skillsExportPrefix = `${SkillsIdentifier}____exportFile`;+ const records: FileEditToolCallRecord[] = [];++ for (const message of messages) {+ // Shape 1: raw assistant rows appended in-memory during the current step.+ if (message?.role === 'assistant' && Array.isArray(message.tool_calls)) {+ for (const call of message.tool_calls) {+ const name: unknown = call?.function?.name;+ if (typeof name !== 'string') continue;+ const rawArguments =+ typeof call?.function?.arguments === 'string' ? call.function.arguments : '';+ // Skills export surface: only exportFile is relevant (its runCommand /+ // execScript never carry an output path), and args-only entity checks+ // over-approximate success just like the sandbox exportFile below.+ if (name.startsWith(skillsExportPrefix) && exportArgsTargetEntityFile(rawArguments))+ return true;+ if (!name.startsWith(sandboxPrefix)) continue;+ const apiName = name.split('____')[1] ?? '';+ if (apiName === 'moveFiles' && moveArgsTargetEntityFile(rawArguments)) return true;+ if (apiName === 'exportFile' && exportArgsTargetEntityFile(rawArguments)) return true;+ records.push({+ apiName,+ arguments: rawArguments,+ identifier: CLOUD_SANDBOX_IDENTIFIER,+ toolCallId: typeof call?.id === 'string' ? call.id : '',+ });+ }+ }++ // Shape 2: conversation-flow grouped nodes (assistantGroup / supervisor)+ // with parsed tool payloads on `children[].tools[]`.+ if (!Array.isArray(message?.children)) continue;+ for (const child of message.children) {+ if (!Array.isArray(child?.tools)) continue;+ for (const tool of child.tools) {+ if (+ tool?.identifier === SkillsIdentifier &&+ tool.apiName === 'exportFile' &&+ exportArgsTargetEntityFile(typeof tool.arguments === 'string' ? tool.arguments : '')+ )+ return true;+ if (tool?.identifier !== CLOUD_SANDBOX_IDENTIFIER) continue;+ const apiName = typeof tool.apiName === 'string' ? tool.apiName : '';+ const rawArguments = typeof tool.arguments === 'string' ? tool.arguments : '';+ const resultState = tool.result?.state;+ if (apiName === 'moveFiles' && !resultState && moveArgsTargetEntityFile(rawArguments))+ return true;+ if (apiName === 'exportFile' && exportArgsTargetEntityFile(rawArguments)) return true;+ records.push({+ apiName,+ arguments: rawArguments,+ error: tool.result?.error,+ identifier: CLOUD_SANDBOX_IDENTIFIER,+ state: resultState,+ toolCallId: typeof tool.id === 'string' ? tool.id : '',+ });+ }+ }+ }+ if (records.length === 0) return false;++ return scanOperationFileEdits(records).some(+ (entry) => classifyEditedFile(entry.path).category === 'entity',+ );+};diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex 626fc101511..0a478b16218 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -2886,6 +2886,71 @@ export class MessageModel {}));};+ /**+ * Load specific tool-call rows by their message ids, ownership-scoped and+ * pinned to one topic. Serves the LOCAL hetero run work scan+ * (`work.registerShellWorksForRun`): a desktop-local CLI run has no+ * `agent_operations` row, so the client reports the exact tool message ids it+ * persisted instead of the server reconstructing an operation window. The+ * topic pin means a caller can never scan rows outside the conversation it+ * claims to complete.+ */+ listMessagePluginsByIds = async (params: {+ ids: string[];+ topicId: string;+ }): Promise<Array<MessagePluginItem & { content?: string; createdAt: Date }>> => {+ if (params.ids.length === 0) return [];++ const rows = await this.db+ .select({+ apiName: messagePlugins.apiName,+ arguments: messagePlugins.arguments,+ clientId: messagePlugins.clientId,+ // The tool message's text body β claude-code Bash persists the+ // command's stdout here (see listMessagePluginsForOperation).+ content: messages.content,+ createdAt: messages.createdAt,+ error: messagePlugins.error,+ id: messagePlugins.id,+ identifier: messagePlugins.identifier,+ intervention: messagePlugins.intervention,+ state: messagePlugins.state,+ toolCallId: messagePlugins.toolCallId,+ type: messagePlugins.type,+ userId: messagePlugins.userId,+ })+ .from(messagePlugins)+ .innerJoin(messages, eq(messagePlugins.id, messages.id))+ .where(+ and(+ inArray(messagePlugins.id, params.ids),+ eq(messages.topicId, params.topicId),+ this.ownership(),+ this.pluginsOwnership(),+ ),+ );++ const sorted = [...rows].sort(+ (a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id),+ );++ return sorted.map((row) => ({+ apiName: row.apiName ?? undefined,+ arguments: row.arguments ?? undefined,+ clientId: row.clientId ?? undefined,+ content: row.content ?? undefined,+ createdAt: row.createdAt,+ error: row.error ?? undefined,+ id: row.id,+ identifier: row.identifier ?? undefined,+ intervention: row.intervention ?? undefined,+ state: row.state ?? undefined,+ toolCallId: row.toolCallId ?? undefined,+ type: row.type ?? 'default',+ userId: row.userId,+ }));+ };+/*** Resolve the tool result message id for a toolCallId β the stable identifier* the model emitted for the call. Lets server-side services push async statediff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsxindex 1c76dfc0b23..1e0d90e4fa9 100644--- a/src/features/Portal/LocalFile/Body.tsx+++ b/src/features/Portal/LocalFile/Body.tsx@@ -494,11 +494,16 @@ const ActiveFileView = memo<ActiveFileViewProps>(if (preview.type === 'document') {return (<Suspense fallback={<Loading />}>+ {/* Key by source + path: without a remount, switching between two files of+ the same document type reuses the pane instance, whose local+ loading/parse state isn't reset on blob change β the previous file's+ rendered content lingers until the new one finishes (LOBE-13010). */}<DocumentPreviewblob={preview.blob}contentType={preview.contentType}filePath={filePath}isLocalFile={!sandboxTopicId && !deviceId && isDesktop}+ key={`${sandboxTopicId ?? deviceId ?? 'local'}:${filePath}`}/></Suspense>);diff --git a/src/features/Work/WorkSummaryCard.tsx b/src/features/Work/WorkSummaryCard.tsxindex 70c2adc6dea..4ce64032fad 100644--- a/src/features/Work/WorkSummaryCard.tsx+++ b/src/features/Work/WorkSummaryCard.tsx@@ -39,6 +39,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({min-width: 0;color: ${cssVar.colorTextTertiary};`,+ identifier: css`+ flex-shrink: 0;+ color: ${cssVar.colorTextTertiary};+ `,icon: css`flex-shrink: 0;@@ -78,6 +82,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({font-size: 11px;color: ${cssVar.colorTextTertiary};`,+ inlineIdentifier: css`+ flex-shrink: 0;+ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ color: ${cssVar.colorTextTertiary};+ `,inlineIcon: css`flex-shrink: 0;color: ${cssVar.colorTextSecondary};@@ -129,6 +139,11 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(descriptor.getIdentifier(item) ||item.resourceId ||item.id;+ // Mirrors WorkVersionHistoryCard's label: surface the resource identifier+ // (e.g. `QA-1989`, `owner/repo#2`) on the card itself, unless the title+ // already fell back to it.+ const identifier = descriptor.getIdentifier(item);+ const showIdentifier = !!identifier && identifier !== title;const description = descriptor.getDescription(item);const openTarget = descriptor.getOpenTarget(item);// The backing task was deleted outside the tool path: the Work lingers as an@@ -180,6 +195,7 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(<Text ellipsis className={styles.inlineTitle}>{title}</Text>+ {showIdentifier && <span className={styles.inlineIdentifier}>{identifier}</span>}{taskDeleted && (<Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>{t('workingPanel.works.taskDeleted')}@@ -218,6 +234,11 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(<Text ellipsis className={styles.title}>{title}</Text>+ {showIdentifier && (+ <Text code className={styles.identifier} fontSize={12}>+ {identifier}+ </Text>+ )}{taskDeleted && (<Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>{t('workingPanel.works.taskDeleted')}diff --git a/src/services/work.ts b/src/services/work.tsindex b5bb0f7ff20..188bba0d5e6 100644--- a/src/services/work.ts+++ b/src/services/work.ts@@ -107,6 +107,19 @@ class WorkService {params: RegisterSkillToolResultWorkParams,): Promise<WorkItem | null> => lambdaClient.work.handleSkillToolResult.mutate(params);+ /**+ * Report a finished desktop-LOCAL hetero run's tool messages for the+ * server-side shell Work scan (gh CLI β github Work cards). Local runs have+ * no `agent_operations` row, so the server's completion scan never fires for+ * them β the executor calls this at clean completion instead.+ */+ registerShellWorksForRun = async (params: {+ anchorMessageId: string;+ messageIds: string[];+ topicId: string;+ }): Promise<{ failed: number; registered: number; rootOperationId: string | null }> =>+ lambdaClient.work.registerShellWorksForRun.mutate(params);+/*** Invalidate everything a Work mutation can change for a conversation:* - the topic's `message:list` entries, since Work summaries (in-message chipsdiff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 0c4ee564a5f..4255fcf5b70 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -58,6 +58,7 @@ import {messageService,} from '@/services/message';import { threadService } from '@/services/thread';+import { workService } from '@/services/work';import { topicSelectors } from '@/store/chat/selectors';import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';import {@@ -2248,6 +2249,37 @@ export const executeHeterogeneousAgent = async (runScope,runtimeType: 'hetero',});++ // Shell Work scan for this LOCAL run: no server operation exists, so+ // the completion-time scan (`registerWorksForOperation`) can never+ // fire β report the run's persisted tool message ids to the server,+ // which replays the same scan (gh CLI β github Work cards) under a+ // synthetic anchor-derived rootOperationId. Best-effort and+ // idempotent server-side; a failure only costs the card, never the+ // run. Mirrors the gateway path's error-skip: only clean completions+ // scan. Capped to the server's input limit β a >500-tool run keeps+ // its most recent calls, which are the ones that own trailing+ // create/edit output.+ const toolMessageIds = [...new Set(toolMsgIdByCallId.values())].slice(-500);+ // Topicless runs can't scan: the server validates the anchor against+ // the claimed topic, and a card has no conversation to render in.+ if (toolMessageIds.length > 0 && mainState.currentAssistantId && context.topicId) {+ try {+ const scan = await workService.registerShellWorksForRun({+ anchorMessageId: mainState.currentAssistantId,+ messageIds: toolMessageIds,+ topicId: context.topicId,+ });+ if (scan.registered > 0) {+ // Re-pull the message list so the anchor's fresh+ // `metadata.work.rootOperationId` (and its works payload)+ // renders without a manual refresh.+ await workService.refreshConversation(context.topicId);+ }+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to register shell works:', err);+ }+ }}});},diff --git a/src/utils/workVersionCost.test.ts b/src/utils/workVersionCost.test.tsindex 93c034badf6..65a0ad4412e 100644--- a/src/utils/workVersionCost.test.ts+++ b/src/utils/workVersionCost.test.ts@@ -3,9 +3,14 @@ import { describe, expect, it } from 'vitest';import { computeWorkVersionCostDeltas, formatWorkVersionCost } from './workVersionCost';describe('formatWorkVersionCost', () => {- it('hides missing or zero cost', () => {+ it('hides unknown cost but renders known-zero as $0.00', () => {expect(formatWorkVersionCost(null)).toBeNull();- expect(formatWorkVersionCost(0)).toBeNull();+ expect(formatWorkVersionCost(undefined)).toBeNull();+ expect(formatWorkVersionCost(0)).toBe('$0.00');+ });++ it('hides negative cost defensively', () => {+ expect(formatWorkVersionCost(-0.01)).toBeNull();});it('keeps small cumulative costs visible', () => {diff --git a/src/utils/workVersionCost.ts b/src/utils/workVersionCost.tsindex 8684badc7a4..eab38cbf3c4 100644--- a/src/utils/workVersionCost.ts+++ b/src/utils/workVersionCost.ts@@ -1,7 +1,10 @@export const formatWorkVersionCost = (cost?: number | null): string | null => {- if (!cost || cost <= 0) return null;+ // null/undefined means the cost is unknown (no snapshot recorded) β hide it.+ // A literal 0 is a known-zero spend (e.g. a same-operation version whose+ // cumulative snapshot didn't advance) and must render as $0.00, not blank.+ if (cost === null || cost === undefined || cost < 0) return null;- if (cost < 0.01) return `$${cost.toFixed(4)}`;+ if (cost > 0 && cost < 0.01) return `$${cost.toFixed(4)}`;return `$${cost.toFixed(2)}`;};