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(work): register operation file edits as file works (#17423)

YuTengjing8ce64fe1e1b5
diff --git a/.agents/acceptance/PROJECT.md b/.agents/acceptance/PROJECT.md
index d1340b67cb1..9bb35d84365 100644
--- a/.agents/acceptance/PROJECT.md
+++ b/.agents/acceptance/PROJECT.md
@@ -165,28 +165,52 @@ stale standalone install: a recently added workspace package fails to resolve
- Invocation: from source, no rebuild — `cd apps/cli && bun src/index.ts <cmd>`
(referred to as `$CLI`). CLI-side code changes take effect immediately.
+
- Auth: see §3 CLI. Source the seeded profile first:
`source .records/env/agent-testing-cli.env`. It sets `LOBE_API_KEY` /
`LOBEHUB_CLI_API_KEY`, `LOBEHUB_SERVER=http://localhost:3010`, and
`LOBEHUB_CLI_HOME=.lobehub-dev` for isolated settings.
+
- **Local-run vs publish env distinction:** those seeded overrides are for
_running_ the local backend test. They are WRONG for _publishing_ — a localhost
run yields a verify URL nobody else can open, and the local stub S3 makes
evidence upload fail. Strip them for the publish step (the skill's Step 6 does
`env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME lh verify ingest-report …`
so `lh` uses production defaults + the user's real `~/.lobehub` login).
+
- Standalone install: `cd apps/cli && pnpm install` (root install does not cover it).
-### Web
+- **CLI as the run driver for conversation features (preferred over browser
+ typing):** for any test whose state is produced by an agent run (tool calls,
+ edited-file cards, works, topic content), drive the run with
+
+ ```bash
+ lh agent run -a local --sse --json -p '<prompt>' [-t < agentId > --device < topicId > ]
+ ```
+
+ and use the browser only to capture the rendered evidence afterwards. `--sse`
+ is REQUIRED against a local dev server — without it the run dies with
+ `Gateway auth failed: signature verification failed` (local agent-gateway
+ JWKS mismatch; see `references/probe-field-notes.md` E43). `--json` gives assertable
+ output; reuse `-t` to chain multi-step cases in one topic. This is faster and
+ far more deterministic than typing prompts through agent-browser, and the
+ server-side state it produces is identical.
- Launch: full-stack dev server from §2 (`bun run dev` or `init-dev-env.sh dev`).
+
- Base URL: `$SERVER_URL` (default `http://localhost:3010`).
-- agent-browser session: `lobehub-dev`. Seed it with `setup-auth.sh web-seed`;
- drive it as the sole evidence source (do not use ordinary Chrome screenshots
- or Network records as proof). Full-stack is the one surface where network
- requests and rendered UI are observable together — assert both.
+
+- agent-browser session: `lobehub-dev`. Seed it with `setup-auth.sh web-seed`.
+ It is the sole **evidence** source (do not use ordinary Chrome screenshots or
+ Network records as proof) — but not necessarily the driver: prefer the CLI
+ run driver (§4 CLI) or direct endpoint calls to produce the state, and use
+ the browser for what only it can prove (rendering, interaction). Full-stack
+ is the one surface where network requests and rendered UI are observable
+ together — assert both.
+
- SPA proxying note: Web smoke needs the full-stack `dev` so Next proxies the
SPA HTML from Vite; `dev-next` alone will not serve the SPA.
+
- Local frontend against production backend: `bun run dev:spa` prints a
`_dangerous_local_dev_proxy` URL that loads your local Vite SPA inside the
online environment (HMR against real server config) — for verifying frontend
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index 0fba3bfb4f2..6e3146d827e 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -80,6 +80,22 @@ role × action × scope matrix.
owners explicit workspace variants with stronger confirmation for destructive
operations.
+### L-E4 — Trusting a stripped-env `lh` publish to reach production
+
+**Wrong approach:** publish with `env -u LOBEHUB_SERVER … lh acceptance run
+ingest`, taking a clean-env `lh whoami` showing the user's real profile as proof
+the target is production.
+
+**Why it fails:** `lh login` persists `serverUrl` into `~/.lobehub/settings.json`,
+which env-stripping cannot clear, and the local dev DB carries the user's synced
+real profile — so the ingest lands in the local DB and the published
+`app.lobehub.com/acceptance/<id>` link 404s.
+
+**Correct approach:** discriminate the target with a data probe (query an object
+that exists on only one side) or read `settings.json` directly; to publish
+without clobbering a localhost login, log in to prod under an isolated
+`LOBEHUB_CLI_HOME` and keep that variable set for the ingest.
+
## Environment safety
### L-S1 — Acquiring Electron auth through OAuth
diff --git a/.agents/acceptance/references/probe-field-notes.md b/.agents/acceptance/references/probe-field-notes.md
index a6c4ba28a91..a65572f20c8 100644
--- a/.agents/acceptance/references/probe-field-notes.md
+++ b/.agents/acceptance/references/probe-field-notes.md
@@ -1294,3 +1294,17 @@ active: true, remoteServerUrl: 'http://localhost:<port>', storageMode: 'selfHost
- **Works**: launch the long-lived dev server with sandboxing disabled for that one command
(e.g. the harness's dangerously-disable-sandbox flag). Measured: the same command that died
at \~1–2 min three times survived 60s+ probes and the whole run once unsandboxed.
+
+### E43. `lh agent run` against a local dev server dies with "Gateway auth failed: signature verification failed" — add `--sse`
+
+- **Situation**: driving real agent runs from the CLI against a local dev server
+ (`lh agent run -a <agentId> --device local -p '...'`) to test server-runtime features
+ end-to-end. The run aborts immediately with
+ `Gateway auth failed: signature verification failed` (local agent gateway JWT verify).
+- **Doesn't work**: the default (non-SSE) transport — it goes through the agent gateway
+ worker whose local JWKS config does not match the dev server's signing key.
+- **Works**: `lh agent run -a <agentId> --device local --sse --json -p '...' [-t <topicId>]` —
+ the SSE path skips the failing gateway verification and streams the full run. `--json`
+ gives assertable output; reuse `-t` to keep multi-step cases in one topic.
+ Root cause (local JWKS mismatch) is worth a separate investigation, not a test-run fix.
+ The CLI-as-run-driver methodology this enables lives in PROJECT.md §4 CLI.
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.md
index 5882944cbbf..246252e6c54 100644
--- a/.agents/skills/agent-testing/SKILL.md
+++ b/.agents/skills/agent-testing/SKILL.md
@@ -263,6 +263,18 @@ Which of these surfaces the project actually has, and how each one launches, com
from `PROJECT.md` §4. Escalate, don't duplicate: verify a backend change with the
CLI first; only add a UI pass when the change actually affects the UI.
+**Separate the driver from the evidence surface.** Picking a surface for
+evidence does NOT mean every action must go through it — generating the state
+under test (running a flow, seeding data, triggering a job) and capturing the
+evidence (screenshot, DOM assertion, DB row) are independent choices. Pick the
+cheapest, most deterministic driver the project offers (a CLI run command, an
+API/endpoint call, a seed script — see `PROJECT.md` §4/§5 for what exists), and
+use the evidence surface only for what it alone can prove. Typing long prompts
+or multi-step inputs through browser automation when a CLI/API driver exists is
+a smell: the browser run is slower, flakier, and no more authentic — the
+server-side state it produces is identical. The reverse also holds: a CLI-driven
+state still needs UI evidence when the claim under test is about rendering.
+
**Verify the change runs where you think it does — confirm runtime, don't assume.**
Some features have two execution paths and the UI silently picks one (e.g. a client
runtime vs a server/queue runtime). A test that exercises the wrong path can pass
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 2a7834c2e63..ee974554b64 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -352,6 +352,10 @@ export const messageRouter = router({
agentId: z.string().nullish(),
current: z.number().optional(),
groupId: z.string().nullish(),
+ // Opt-in for `file` work summaries in the payload. Absent → the legacy
+ // set, so already-deployed clients (no `file` descriptor) never receive
+ // a `file` summary that would crash their works UI. New clients set it.
+ includeFileWorks: z.boolean().optional(),
pageSize: z.number().optional(),
sessionId: z.string().nullish(),
// Mid-stream refetches skip the Work-summary assembly — see
diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.ts
index 1f3a6889c77..ea0c096adae 100644
--- a/apps/server/src/routers/lambda/work.ts
+++ b/apps/server/src/routers/lambda/work.ts
@@ -106,6 +106,10 @@ export const workRouter = router({
listByConversation: workProcedure
.input(
z.object({
+ // Opt-in for the `file` work type. Absent → the legacy (pre-`file`) set,
+ // so already-deployed clients whose descriptor table lacks `file` never
+ // receive it (see resolveAllowedWorkTypes in the work registry).
+ includeFileWorks: z.boolean().optional(),
limit: z.number().min(1).max(100).default(50),
threadId: z.string().nullable().optional(),
topicId: z.string().nullable().optional(),
@@ -117,9 +121,10 @@ export const workRouter = router({
.input(
z.object({
cursor: z.string().nullable().optional(),
+ includeFileWorks: z.boolean().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(),
+ type: z.enum(['task', 'document', 'external', 'file']).nullable().optional(),
}),
)
.query(async ({ ctx, input }) => ctx.workModel.listByWorkspace(input)),
@@ -127,12 +132,14 @@ export const workRouter = router({
listByRootOperation: workProcedure
.input(
z.object({
+ includeFileWorks: z.boolean().optional(),
limit: z.number().min(1).max(50).default(20),
rootOperationId: z.string().nullable().optional(),
}),
)
.query(async ({ ctx, input }) =>
ctx.workModel.listByRootOperation({
+ includeFileWorks: input.includeFileWorks,
limit: input.limit,
rootOperationId: input.rootOperationId,
}),
@@ -141,12 +148,14 @@ export const workRouter = router({
listByRootOperations: workProcedure
.input(
z.object({
+ includeFileWorks: z.boolean().optional(),
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({
+ includeFileWorks: input.includeFileWorks,
limit: input.limit,
rootOperationIds: input.rootOperationIds,
}),
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index a94b056988b..e3d2b60db43 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -63,7 +63,8 @@ import { ToolExecutionService } from '@/server/services/toolExecution';
import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';
import { isAbortError, throwIfAborted } from './abort';
-import { CompletionLifecycle } from './CompletionLifecycle';
+import { CompletionLifecycle, isSuccessLikeCompletionReason } from './CompletionLifecycle';
+import { stateHasEntityFileEdits } from './fileWorkRegistration';
import { hookDispatcher } from './hooks';
import { HumanInterventionHandler } from './HumanInterventionHandler';
import { OperationTraceRecorder } from './OperationTraceRecorder';
@@ -1007,6 +1008,7 @@ export class AgentRuntimeService {
// Use agentState.metadata which contains the full app context (topicId, agentId, etc.)
// operationMetadata only contains basic fields (agentConfig, modelRuntimeConfig, userId)
const { runtime } = await this.createAgentRuntime({
+ agentState,
metadata: agentState?.metadata,
operationId,
stepIndex,
@@ -1125,6 +1127,35 @@ export class AgentRuntimeService {
log('[%s][%d] Operation was interrupted during step execution', operationId, stepIndex);
}
+ // Decide whether to schedule next step (hoisted above the save: it also
+ // gates the pre-snapshot file-Work registration below)
+ const shouldContinue = this.shouldContinueExecution(
+ stepResult.newState,
+ stepResult.nextContext,
+ );
+
+ // Register entity-file Works BEFORE the terminal save: `saveStepResult`
+ // publishes `agent_runtime_end`, whose `uiMessages` snapshot the client
+ // adopts as the settled message list — the Work rows must exist by then
+ // or the file-Work card stays absent until a manual refresh. Perceived
+ // loading is not extended: for runs with entity edits the early
+ // `visible_output_end` is suppressed (see `createAgentRuntime`), so
+ // loading covers this export window by design. Idempotent — the
+ // dispatchHooks backstop below no-ops via the state marker.
+ if (!shouldContinue) {
+ const preSaveReason = this.determineCompletionReason(stepResult.newState);
+ // Success-like reasons ONLY — a `waiting_for_human` park must NOT
+ // register: the approval resume continues the SAME operationId
+ // (`processHumanIntervention` reschedules it), so pre-park edits are
+ // covered by the real terminal completion's scan. Registering at the
+ // park would persist the `_fileWorksRegistered` marker into the park
+ // snapshot (skipping the terminal registration entirely) and freeze
+ // per-(op, file) versions at pre-approval content.
+ if (isSuccessLikeCompletionReason(preSaveReason)) {
+ await this.completionLifecycle.registerFileWorks(operationId, stepResult.newState);
+ }
+ }
+
// Save state, coordinator will handle event sending automatically
await this.coordinator.saveStepResult(operationId, {
...stepResult,
@@ -1132,11 +1163,6 @@ export class AgentRuntimeService {
stepIndex, // placeholder
});
- // Decide whether to schedule next step
- const shouldContinue = this.shouldContinueExecution(
- stepResult.newState,
- stepResult.nextContext,
- );
let nextStepScheduled = false;
// Publish step complete event
@@ -2639,11 +2665,19 @@ export class AgentRuntimeService {
* Create Agent Runtime instance
*/
private async createAgentRuntime({
+ agentState,
metadata,
operationId,
stepIndex,
tracingContextEngine,
}: {
+ /**
+ * Current runtime state, when the caller has it. Only consulted to decide
+ * whether the early final-answer `visible_output_end` must be suppressed
+ * (entity-file edits ⇒ completion still has to export + register file
+ * Works, so loading should cover that window).
+ */
+ agentState?: any;
metadata?: any;
operationId: string;
stepIndex: number;
@@ -2681,7 +2715,15 @@ export class AgentRuntimeService {
// The factory may be a Graph-aware dispatcher that still returns the
// default agent for ordinary conversations. Keep the early visible
// output end behavior tied to the actual agent, not factory presence.
- allowEarlyFinalAnswerVisibleOutputEnd: agent instanceof GeneralChatAgent,
+ //
+ // Additionally suppressed once the run edited entity-format files:
+ // completion still exports + registers them as `file` Works BEFORE the
+ // terminal snapshot (see `CompletionLifecycle.registerFileWorks`), and
+ // an early hint would end the visible loading seconds before that card
+ // can exist. Deferring to the terminal `visible_output_end` lets loading
+ // cover the export and the card land with `agent_runtime_end`.
+ allowEarlyFinalAnswerVisibleOutputEnd:
+ agent instanceof GeneralChatAgent && !stateHasEntityFileEdits(agentState),
botContext: metadata?.botContext,
botPlatformContext: metadata?.botPlatformContext,
discordContext: metadata?.discordContext,
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index 335dc606605..532d970e4f9 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -21,10 +21,22 @@ import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observab
import { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';
import { instantiateVerifyPlanOnStart, runVerifyOnCompletion } from '@/server/services/verify';
+import { registerFileWorksForOperation } from './fileWorkRegistration';
import { hookDispatcher, type SerializedHook } from './hooks';
const log = debug('lobe-server:completion-lifecycle');
+/**
+ * Terminal reasons this lifecycle treats as a successful completion: the run
+ * produced a deliverable, even when it was stopped by a step/cost cap rather
+ * than finishing naturally. `persistCompletion` stores all three with
+ * status='done', and success-side effects (assistant-content recovery,
+ * file-Work registration) must cover the capped reasons too — gating them on
+ * `reason === 'done'` alone silently drops capped runs' artifacts.
+ */
+export const isSuccessLikeCompletionReason = (reason: string): boolean =>
+ reason === 'done' || reason === 'max_steps' || reason === 'cost_limit';
+
type SignalEvent = { [key: string]: unknown; type: string };
/**
@@ -493,6 +505,57 @@ export class CompletionLifecycle {
};
}
+ /**
+ * Register entity files edited by this operation (pptx/xlsx/docx/pdf, …) as
+ * `file` Works — one version per operation, exported from the sandbox.
+ *
+ * Idempotent per state object: only when EVERY file registered (the returned
+ * outcome reports `failed === 0`) is a `_fileWorksRegistered` marker stamped
+ * onto `state.metadata` so the dispatchHooks backstop (which receives the same
+ * state later in the request) skips the duplicate scan. A PARTIAL failure
+ * leaves the marker unset so the backstop re-runs and retries just the failed
+ * files — the underlying registration is idempotent per (operation, file) via a
+ * DB existence probe, so already-registered files short-circuit and a QStash
+ * retry that lost the marker is safe.
+ *
+ * The gateway/queue executor calls this BEFORE the terminal
+ * `coordinator.saveStepResult`: that save publishes `agent_runtime_end`,
+ * whose `uiMessages` snapshot the client adopts as the settled message list —
+ * Work rows must exist by then or the file-Work card stays absent until a
+ * manual refresh. When entity edits are present, the executor suppresses the
+ * early `visible_output_end`, so perceived loading covers export and
+ * registration until the terminal snapshot is published.
+ *
+ * Awaited, NOT fire-and-forget: on serverless the runtime can freeze the
+ * moment the response is sent, silently dropping any still-pending background
+ * write. Fully self-guarded — a failure only logs, never throws. Both a thrown
+ * whole-function failure AND a partial per-file failure (outcome `failed > 0`)
+ * leave the marker unset so a later call retries the outstanding files.
+ */
+ async registerFileWorks(operationId: string, state: any): Promise<void> {
+ if (state?.metadata?._fileWorksRegistered) return;
+ try {
+ const outcome = await registerFileWorksForOperation({
+ // Live terminal totals: on the pre-snapshot path the op row's cost/usage
+ // columns are not persisted yet (recordCompletion runs later), so the
+ // registration must not rely on reading them back from the DB.
+ finalCost: state?.cost ?? null,
+ finalUsage: state?.usage ?? null,
+ operationId,
+ serverDB: this.serverDB,
+ userId: state?.metadata?.userId || this.userId,
+ workspaceId: this.workspaceId,
+ });
+ // Stamp the idempotency marker ONLY when nothing failed. A partial failure
+ // (some files exported/registered, others did not) must NOT be recorded as
+ // a completed registration, or the dispatchHooks backstop would skip the
+ // retry and the user gets neither a Work nor the edited-files fallback.
+ if (state?.metadata && outcome.failed === 0) state.metadata._fileWorksRegistered = true;
+ } catch (error) {
+ log('[%s] registerFileWorksForOperation failed (non-fatal): %O', operationId, error);
+ }
+ }
+
/**
* The single terminal-completion entry for every path that does NOT have the
* in-process runtime's rich `state` in hand: heterogeneous CLI exit
@@ -527,8 +590,10 @@ export class CompletionLifecycle {
// status (the async-tool resume CAS reads it) but must NOT fire `onComplete`
// or unregister hooks — the op resumes under this same id and reaches its
// real terminal state later, which is when consumers should be notified.
- // (`waiting_for_human` differs: its resume runs under a NEW operationId, so
- // firing + unregistering on the park is correct there.)
+ // (`waiting_for_human` also resumes under the same operationId, but its
+ // park DOES fire `onComplete` — hook consumers surface the approval request
+ // as the run's outcome; the final completion re-dispatches with the
+ // serialized hooks carried on `metadata._hooks`.)
const isAsyncToolPark = reason === 'waiting_for_async_tool';
try {
@@ -552,7 +617,7 @@ export class CompletionLifecycle {
// like the IM bot callback silently drop the reply. Recover from the DB
// row — the same source of truth the app UI renders — before dispatch.
if (
- (reason === 'done' || reason === 'max_steps' || reason === 'cost_limit') &&
+ isSuccessLikeCompletionReason(reason) &&
!event.lastAssistantContent?.trim() &&
!event.attachments?.length
) {
@@ -625,6 +690,24 @@ export class CompletionLifecycle {
);
}
+ // Register entity files edited this round as `file` Works. On the
+ // gateway/queue path this already ran BEFORE the terminal snapshot (see
+ // `registerFileWorks`) and no-ops via the state marker; here it is the
+ // backstop for every other terminal path (in-process runtime, hetero
+ // completions, already-terminal early exits). Guarded on success-LIKE
+ // reasons, not `done` alone: a run stopped by a step/cost cap still
+ // produced its edits and persists as status='done'.
+ //
+ // `waiting_for_human` deliberately does NOT register: the approval resume
+ // continues the SAME operationId (`processHumanIntervention` reschedules
+ // it), so pre-park edits are covered by the real terminal completion's
+ // scan. Registering at the park would persist `_fileWorksRegistered` into
+ // the park snapshot — skipping the terminal registration entirely — and
+ // freeze per-(op, file) versions at pre-approval content.
+ if (isSuccessLikeCompletionReason(reason)) {
+ await this.registerFileWorks(operationId, state);
+ }
+
if (reason === 'error') {
await hookDispatcher.dispatch(operationId, 'onError', event, metadata._hooks);
diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
index 94e285decbc..f519d2e9359 100644
--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
@@ -6,7 +6,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import * as agentSignalService from '@/server/services/agentSignal';
import * as verifyServices from '@/server/services/verify';
-import { CompletionLifecycle } from '../CompletionLifecycle';
+import { CompletionLifecycle, isSuccessLikeCompletionReason } from '../CompletionLifecycle';
+import { registerFileWorksForOperation } from '../fileWorkRegistration';
import { hookDispatcher } from '../hooks';
// Default async no-op implementation: the production code chains `.catch` on
@@ -21,10 +22,32 @@ vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () => ({
notifyAgentRunCompleted: mockNotifyAgentRunCompleted,
}));
+vi.mock('../fileWorkRegistration', () => ({
+ registerFileWorksForOperation: vi.fn(),
+}));
+
const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0));
const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');
+describe('isSuccessLikeCompletionReason', () => {
+ // Regression: file-Work registration was gated on `reason === 'done'` alone,
+ // silently skipping runs stopped by a step/cost cap even though the lifecycle
+ // persists those as status='done' and recovers their assistant content.
+ it('treats capped runs (max_steps / cost_limit) as successful completions', () => {
+ expect(isSuccessLikeCompletionReason('done')).toBe(true);
+ expect(isSuccessLikeCompletionReason('max_steps')).toBe(true);
+ expect(isSuccessLikeCompletionReason('cost_limit')).toBe(true);
+ });
+
+ it('rejects non-success terminal and parked reasons', () => {
+ expect(isSuccessLikeCompletionReason('error')).toBe(false);
+ expect(isSuccessLikeCompletionReason('interrupted')).toBe(false);
+ expect(isSuccessLikeCompletionReason('waiting_for_human')).toBe(false);
+ expect(isSuccessLikeCompletionReason('waiting_for_async_tool')).toBe(false);
+ });
+});
+
describe('CompletionLifecycle.extractErrorMessage', () => {
it('extracts message from ChatCompletionErrorPayload (InsufficientBudgetForModel)', () => {
const lifecycle = buildLifecycle();
@@ -721,6 +744,49 @@ describe('CompletionLifecycle.dispatchHooks — completion notification', () =>
});
});
+describe('CompletionLifecycle.dispatchHooks — parks do not register file works', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ // Regression: the approval resume continues the SAME operationId
+ // (`processHumanIntervention` reschedules it), so the real terminal
+ // completion's scan covers pre-park edits. Registering at the park would
+ // persist `_fileWorksRegistered` into the park snapshot (skipping the
+ // terminal registration entirely) and freeze per-(op, file) versions at
+ // pre-approval content.
+ it('does NOT register on a human-approval park (same op resumes and registers later)', async () => {
+ const mockRegister = vi.mocked(registerFileWorksForOperation);
+ mockRegister.mockClear();
+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
+ const lifecycle = buildLifecycle();
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});
+
+ const parkedState = { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' };
+ await lifecycle.dispatchHooks('op-1', parkedState, 'waiting_for_human');
+
+ expect(mockRegister).not.toHaveBeenCalled();
+ });
+
+ it('does NOT register on an async-tool park (same op resumes and registers later)', async () => {
+ const mockRegister = vi.mocked(registerFileWorksForOperation);
+ mockRegister.mockClear();
+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
+ const lifecycle = buildLifecycle();
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+
+ const parkedState = {
+ metadata: { _hooks: [], agentId: 'a' },
+ status: 'waiting_for_async_tool',
+ };
+ await lifecycle.dispatchHooks('op-1', parkedState, 'waiting_for_async_tool');
+
+ expect(mockRegister).not.toHaveBeenCalled();
+ });
+});
+
describe('CompletionLifecycle.dispatchHooks — lastAssistantContent DB recovery (LOBE-11632)', () => {
afterEach(() => {
vi.restoreAllMocks();
@@ -966,3 +1032,85 @@ describe('CompletionLifecycle.emitSignalEvents — assistant anchor', () => {
});
});
});
+
+describe('CompletionLifecycle.registerFileWorks', () => {
+ const mockRegister = vi.mocked(registerFileWorksForOperation);
+
+ it('registers once and stamps the state marker so later calls skip', async () => {
+ mockRegister.mockClear();
+ mockRegister.mockResolvedValue({ attempted: 1, failed: 0 });
+ const lifecycle = buildLifecycle();
+ const state = {
+ cost: { total: 1.25 },
+ metadata: { userId: 'user-2' },
+ usage: { llm: { apiCalls: 2 } },
+ } as any;
+
+ await lifecycle.registerFileWorks('op-1', state);
+
+ expect(mockRegister).toHaveBeenCalledTimes(1);
+ // The terminal state's live totals ride along: on the pre-snapshot path the
+ // op row's cost/usage columns are not persisted yet.
+ expect(mockRegister).toHaveBeenCalledWith(
+ expect.objectContaining({
+ finalCost: { total: 1.25 },
+ finalUsage: { llm: { apiCalls: 2 } },
+ operationId: 'op-1',
+ userId: 'user-2',
+ }),
+ );
+ expect(state.metadata._fileWorksRegistered).toBe(true);
+
+ // The dispatchHooks backstop receives the same state later in the request —
+ // the marker must make that second call a no-op (no duplicate scan/export).
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(mockRegister).toHaveBeenCalledTimes(1);
+ });
+
+ it('never throws and leaves the marker unset on failure so a later call retries', async () => {
+ mockRegister.mockClear();
+ mockRegister.mockRejectedValueOnce(new Error('sandbox export failed'));
+ const lifecycle = buildLifecycle();
+ const state = { metadata: {} } as any;
+
+ await expect(lifecycle.registerFileWorks('op-1', state)).resolves.toBeUndefined();
+ expect(state.metadata._fileWorksRegistered).toBeUndefined();
+
+ mockRegister.mockResolvedValueOnce({ attempted: 1, failed: 0 });
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(mockRegister).toHaveBeenCalledTimes(2);
+ expect(state.metadata._fileWorksRegistered).toBe(true);
+ });
+
+ it('leaves the marker unset on a PARTIAL failure, then stamps it once all files land', async () => {
+ // Regression: registerFileWorksForOperation swallows per-file failures and
+ // never rejects, so a partial failure resolves normally. The marker must be
+ // gated on the outcome (`failed === 0`), NOT stamped unconditionally — else
+ // the dispatchHooks backstop skips the retry and the user gets neither a Work
+ // nor the edited-files fallback card for the file that failed to export.
+ mockRegister.mockClear();
+ const lifecycle = buildLifecycle();
+ const state = { metadata: {} } as any;
+
+ // One of two files failed to export/register this round.
+ mockRegister.mockResolvedValueOnce({ attempted: 2, failed: 1 });
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(state.metadata._fileWorksRegistered).toBeUndefined();
+
+ // The backstop retries; the previously-registered file short-circuits on the
+ // DB probe and the failed one now lands → failed=0 → marker set.
+ mockRegister.mockResolvedValueOnce({ attempted: 2, failed: 0 });
+ await lifecycle.registerFileWorks('op-1', state);
+ expect(mockRegister).toHaveBeenCalledTimes(2);
+ expect(state.metadata._fileWorksRegistered).toBe(true);
+ });
+
+ it('tolerates a state without metadata', async () => {
+ mockRegister.mockClear();
+ mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });
+ const lifecycle = buildLifecycle();
+
+ await expect(lifecycle.registerFileWorks('op-1', {} as any)).resolves.toBeUndefined();
+ expect(mockRegister).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index 720f32717d3..6bd81ff5af0 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -269,6 +269,67 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
);
});
+ const sandboxToolCallState = (path: string) => ({
+ messages: [
+ {
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: JSON.stringify({ path }),
+ name: 'lobe-cloud-sandbox____writeFile____builtin',
+ },
+ id: 'call-1',
+ type: 'function',
+ },
+ ],
+ },
+ ],
+ });
+
+ it('suppresses early visible output end once the run edited entity-format files', async () => {
+ // Completion still has to export + register those files as `file` Works
+ // BEFORE the terminal snapshot; an early hint would end the visible loading
+ // seconds before the file-Work card can exist.
+ vi.mocked(createRuntimeExecutors).mockClear();
+ const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });
+
+ await (service as any).createAgentRuntime({
+ agentState: sandboxToolCallState('/work/deck.pptx'),
+ metadata: {
+ agentConfig: {},
+ modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
+ userId: 'user-1',
+ },
+ operationId: 'op-entity-edit',
+ stepIndex: 3,
+ });
+
+ expect(createRuntimeExecutors).toHaveBeenCalledWith(
+ expect.objectContaining({ allowEarlyFinalAnswerVisibleOutputEnd: false }),
+ );
+ });
+
+ it('keeps the early hint when edited files are not entity-format', async () => {
+ vi.mocked(createRuntimeExecutors).mockClear();
+ const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });
+
+ await (service as any).createAgentRuntime({
+ agentState: sandboxToolCallState('/work/notes.md'),
+ metadata: {
+ agentConfig: {},
+ modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
+ userId: 'user-1',
+ },
+ operationId: 'op-plain-edit',
+ stepIndex: 3,
+ });
+
+ expect(createRuntimeExecutors).toHaveBeenCalledWith(
+ expect.objectContaining({ allowEarlyFinalAnswerVisibleOutputEnd: true }),
+ );
+ });
+
it('should NOT skip step when operation status is "running"', async () => {
const service = createService();
@@ -1140,3 +1201,73 @@ describe('AgentRuntimeService.executeStep - step_start uiMessages payload', () =
expect(queryMock).not.toHaveBeenCalled();
});
});
+
+describe('AgentRuntimeService.executeStep - pre-snapshot file-Work registration', () => {
+ const runTerminalStep = async (newState: any) => {
+ const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });
+ const coordinator = (service as any).coordinator;
+ coordinator.loadAgentState = vi.fn().mockResolvedValue({
+ lastModified: new Date().toISOString(),
+ metadata: {},
+ status: 'running',
+ stepCount: 1,
+ });
+ const registerSpy = vi
+ .spyOn((service as any).completionLifecycle, 'registerFileWorks')
+ .mockResolvedValue(undefined);
+ vi.spyOn((service as any).completionLifecycle, 'emitSignalEvents').mockResolvedValue([]);
+ vi.spyOn((service as any).completionLifecycle, 'dispatchHooks').mockResolvedValue(undefined);
+ (service as any).createAgentRuntime = vi.fn().mockResolvedValue({
+ runtime: {
+ step: vi.fn().mockResolvedValue({ events: [], newState, nextContext: undefined }),
+ },
+ });
+
+ await service.executeStep({
+ context: { phase: 'agent_step' } as any,
+ operationId: 'op-order',
+ stepIndex: 2,
+ });
+
+ return { registerSpy, saveStepResult: coordinator.saveStepResult };
+ };
+
+ const doneState = (status: string) => ({
+ lastModified: new Date().toISOString(),
+ messages: [],
+ metadata: {},
+ status,
+ stepCount: 2,
+ });
+
+ it('registers file works BEFORE the terminal saveStepResult publishes the snapshot', async () => {
+ const { registerSpy, saveStepResult } = await runTerminalStep(doneState('done'));
+
+ // The terminal save publishes agent_runtime_end with the uiMessages
+ // snapshot the client adopts — the Work rows must already exist by then.
+ expect(registerSpy).toHaveBeenCalledWith(
+ 'op-order',
+ expect.objectContaining({ status: 'done' }),
+ );
+ expect(saveStepResult).toHaveBeenCalledTimes(1);
+ expect(registerSpy.mock.invocationCallOrder[0]).toBeLessThan(
+ saveStepResult.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('skips pre-save registration for a non-success terminal (error)', async () => {
+ const { registerSpy } = await runTerminalStep(doneState('error'));
+
+ expect(registerSpy).not.toHaveBeenCalled();
+ });
+
+ // Regression: the approval resume continues the SAME operationId, so the
+ // terminal completion's scan covers pre-park edits. Registering at the park
+ // would persist `_fileWorksRegistered` into the park snapshot — skipping the
+ // terminal registration — and freeze versions at pre-approval content.
+ it('skips pre-save registration when parking on waiting_for_human', async () => {
+ const { registerSpy } = await runTerminalStep(doneState('waiting_for_human'));
+
+ expect(registerSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/fileWorkRegistration.test.ts b/apps/server/src/services/agentRuntime/fileWorkRegistration.test.ts
new file mode 100644
index 00000000000..2ee541a2fa9
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/fileWorkRegistration.test.ts
@@ -0,0 +1,920 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ redeployFileWork,
+ registerFileWorksForOperation,
+ stateHasEntityFileEdits,
+} from './fileWorkRegistration';
+
+const {
+ mockFindById,
+ mockListOperationTree,
+ mockListPlugins,
+ mockRegisterFile,
+ mockFindFileVersionByToolCall,
+ mockExportAndUploadFile,
+ mockCreateSandboxService,
+} = vi.hoisted(() => ({
+ mockCreateSandboxService: vi.fn(),
+ mockExportAndUploadFile: vi.fn(),
+ mockFindById: vi.fn(),
+ mockFindFileVersionByToolCall: vi.fn(),
+ mockListOperationTree: vi.fn(),
+ mockListPlugins: vi.fn(),
+ mockRegisterFile: vi.fn(),
+}));
+
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn(() => ({
+ findById: mockFindById,
+ listOperationTree: mockListOperationTree,
+ })),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn(() => ({ listMessagePluginsForOperation: mockListPlugins })),
+}));
+
+vi.mock('@/database/models/work', () => ({
+ WorkModel: vi.fn(() => ({
+ findFileVersionByToolCall: mockFindFileVersionByToolCall,
+ registerFile: mockRegisterFile,
+ })),
+}));
+
+vi.mock('@/server/services/file', () => ({ FileService: vi.fn(() => ({})) }));
+vi.mock('@/server/services/market', () => ({ MarketService: vi.fn(() => ({})) }));
+vi.mock('@/server/services/sandbox', () => ({
+ createSandboxService: mockCreateSandboxService,
+}));
+
+const serverDB = {} as any;
+const baseParams = { operationId: 'op-1', serverDB, userId: 'user-1', workspaceId: undefined };
+
+const rootOp = {
+ agentId: 'agent-1',
+ completedAt: new Date('2026-07-20T00:05:00.000Z'),
+ cost: { total: 0.5 },
+ id: 'op-1',
+ startedAt: new Date('2026-07-20T00:00:00.000Z'),
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ totalCost: 0.5,
+ usage: { tokens: 10 },
+};
+
+/** A sandbox writeFile plugin row for `path`. */
+const writeRow = (id: string, path: string) => ({
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ path }),
+ createdAt: new Date(`2026-07-20T00:0${id.length}:00.000Z`),
+ id,
+ identifier: 'lobe-cloud-sandbox',
+ state: { path, success: true },
+ toolCallId: `tc-${id}`,
+});
+
+/** A successful sandbox exportFile plugin row for `path` (code-generated artifact flow). */
+const exportRow = (id: string, path: string) => ({
+ apiName: 'exportFile',
+ arguments: JSON.stringify({ path }),
+ createdAt: new Date(`2026-07-20T00:0${id.length}:00.000Z`),
+ id,
+ identifier: 'lobe-cloud-sandbox',
+ state: { downloadUrl: `https://f/${id}`, filename: path.split('/').pop(), path },
+ toolCallId: `tc-${id}`,
+});
+
+/** Last path segment — the export identity keys off the file, not the (mangled) upload name. */
+const base = (path: string) => path.split('/').pop() ?? path;
+
+/**
+ * A successful skills-tool exportFile plugin row for `path` (skill-driven
+ * artifact flow, e.g. the pptx skill). Its persisted state carries NO `path` —
+ * only file identity fields — so the path must come from the call arguments.
+ */
+const skillsExportRow = (id: string, path: string) => ({
+ apiName: 'exportFile',
+ arguments: JSON.stringify({ filename: base(path), path }),
+ createdAt: new Date(`2026-07-20T00:0${id.length}:00.000Z`),
+ id,
+ identifier: 'lobe-skills',
+ state: { fileId: `file-${id}`, filename: base(path), url: `https://f/${id}` },
+ toolCallId: `tc-${id}`,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockListOperationTree.mockResolvedValue([rootOp]);
+ // Default: no parent lookup needed (root ops). Sub-op tests override this.
+ mockFindById.mockResolvedValue(null);
+ // No pre-existing version by default, so every entity file exports + registers.
+ mockFindFileVersionByToolCall.mockResolvedValue(null);
+ mockCreateSandboxService.mockReturnValue({ exportAndUploadFile: mockExportAndUploadFile });
+ mockRegisterFile.mockImplementation(async (params: any) => ({
+ currentVersionId: `ver-${params.filePath}`,
+ id: `work-${params.filePath}`,
+ }));
+ // Key the exported identity off the source path's basename (not the upload
+ // filename, which is now prefixed with the op id + a path hash for object-key
+ // uniqueness) so the assertions below stay stable.
+ mockExportAndUploadFile.mockImplementation(async (path: string) => {
+ const filename = base(path);
+ return {
+ fileId: `file-${filename}`,
+ filename,
+ mimeType: 'application/vnd.openxmlformats',
+ size: 2048,
+ success: true,
+ url: `s3://exports/${filename}`,
+ };
+ });
+});
+
+describe('registerFileWorksForOperation', () => {
+ it('registers one file Work version per edited entity file', async () => {
+ mockListPlugins.mockResolvedValue([
+ writeRow('a', '/mnt/data/deck.pptx'),
+ writeRow('bb', '/mnt/data/sheet.xlsx'),
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).toHaveBeenCalledTimes(2);
+ const deck = mockRegisterFile.mock.calls.find(
+ (c) => c[0].filePath === '/mnt/data/deck.pptx',
+ )![0];
+ expect(deck).toMatchObject({
+ agentId: 'agent-1',
+ cumulativeCost: 0.5,
+ filePath: '/mnt/data/deck.pptx',
+ messageId: 'a',
+ rootOperationId: 'op-1',
+ threadId: 'thread-1',
+ title: 'deck.pptx',
+ // Stable dedup key → one version per operation (DB enforces idempotency).
+ toolCallId: 'op:op-1',
+ toolIdentifier: 'lobe-cloud-sandbox',
+ toolName: 'writeFile',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+ expect(deck.metadata).toMatchObject({
+ fileId: 'file-deck.pptx',
+ filePath: '/mnt/data/deck.pptx',
+ fileSize: 2048,
+ fileUrl: 's3://exports/deck.pptx',
+ linesAdded: 0,
+ linesDeleted: 0,
+ mimeType: 'application/vnd.openxmlformats',
+ });
+ expect(deck.cumulativeUsage).toMatchObject({ cost: { total: 0.5 }, usage: { tokens: 10 } });
+ });
+
+ it('skips unexecuted human-intervention rows (pending / rejected approvals)', async () => {
+ /** An approval-parked row: empty result, only `arguments` carries the path. */
+ const parkedRow = (id: string, path: string, status: string) => ({
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ path }),
+ createdAt: new Date('2026-07-20T00:01:00.000Z'),
+ id,
+ identifier: 'lobe-cloud-sandbox',
+ intervention: { status },
+ state: undefined,
+ toolCallId: `tc-${id}`,
+ });
+ mockListPlugins.mockResolvedValue([
+ // Without the filter the scanner falls back from the missing `state.path`
+ // to `arguments.path` and would export a file the user never approved.
+ parkedRow('pending-1', '/mnt/data/parked.docx', 'pending'),
+ parkedRow('rejected-1', '/mnt/data/refused.xlsx', 'rejected'),
+ // Approved rows executed on resume and carry a real result state.
+ { ...writeRow('a', '/mnt/data/deck.pptx'), intervention: { status: 'approved' } },
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).toHaveBeenCalledTimes(1);
+ expect(mockRegisterFile.mock.calls[0][0].filePath).toBe('/mnt/data/deck.pptx');
+ });
+
+ it('collapses multiple edits of the same file into a single version', async () => {
+ mockListPlugins.mockResolvedValue([
+ writeRow('a', '/mnt/data/deck.pptx'),
+ {
+ apiName: 'editFile',
+ arguments: JSON.stringify({ path: '/mnt/data/deck.pptx' }),
+ createdAt: new Date('2026-07-20T00:02:00.000Z'),
+ id: 'edit-2',
+ identifier: 'lobe-cloud-sandbox',
+ state: { linesAdded: 3, linesDeleted: 1, path: '/mnt/data/deck.pptx' },
+ toolCallId: 'tc-edit-2',
+ },
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).toHaveBeenCalledTimes(1);
+ const call = mockRegisterFile.mock.calls[0][0];
+ // Provenance points at the LAST edit of the file.
+ expect(call).toMatchObject({ messageId: 'edit-2', toolName: 'editFile' });
+ expect(call.metadata).toMatchObject({ linesAdded: 3, linesDeleted: 1 });
+ });
+
+ it('skips a file whose sandbox export fails and continues with the rest', async () => {
+ mockListPlugins.mockResolvedValue([
+ writeRow('a', '/mnt/data/broken.pptx'),
+ writeRow('bb', '/mnt/data/ok.xlsx'),
+ ]);
+ mockExportAndUploadFile.mockImplementation(async (path: string) => {
+ const filename = base(path);
+ if (filename === 'broken.pptx') {
+ return { error: { message: 'export boom' }, filename, success: false };
+ }
+ return {
+ fileId: `file-${filename}`,
+ filename,
+ mimeType: 'application/vnd.ms-excel',
+ size: 1024,
+ success: true,
+ url: `s3://exports/${filename}`,
+ };
+ });
+
+ const outcome = await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).toHaveBeenCalledTimes(1);
+ expect(mockRegisterFile.mock.calls[0][0].filePath).toBe('/mnt/data/ok.xlsx');
+ // The outcome summary must report the failed export so the caller withholds
+ // the `_fileWorksRegistered` marker and a later call retries it.
+ expect(outcome).toEqual({ attempted: 2, failed: 1 });
+ });
+
+ it('reports a zero-failure outcome when every entity file registers', async () => {
+ mockListPlugins.mockResolvedValue([
+ writeRow('a', '/mnt/data/deck.pptx'),
+ writeRow('bb', '/mnt/data/sheet.xlsx'),
+ ]);
+
+ const outcome = await registerFileWorksForOperation(baseParams);
+
+ expect(outcome).toEqual({ attempted: 2, failed: 0 });
+ });
+
+ it('counts an idempotent probe skip as a success, not a failure', async () => {
+ mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/deck.pptx')]);
+ // The (op, file) version already exists from a previous attempt.
+ mockFindFileVersionByToolCall.mockResolvedValue({ id: 'ver-existing' });
+
+ const outcome = await registerFileWorksForOperation(baseParams);
+
+ expect(mockExportAndUploadFile).not.toHaveBeenCalled();
+ expect(mockRegisterFile).not.toHaveBeenCalled();
+ expect(outcome).toEqual({ attempted: 1, failed: 0 });
+ });
+
+ it('ignores non-entity files (html / other extensions)', async () => {
+ mockListPlugins.mockResolvedValue([
+ writeRow('a', '/mnt/data/page.html'),
+ writeRow('bb', '/mnt/data/notes.txt'),
+ writeRow('ccc', '/mnt/data/report.docx'),
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).toHaveBeenCalledTimes(1);
+ expect(mockRegisterFile.mock.calls[0][0].filePath).toBe('/mnt/data/report.docx');
+ });
+
+ it('skips entity files whose last edit is NOT sandbox-backed (hetero provenance)', async () => {
+ // A codex (device-side) edit has no counterpart inside the topic's cloud
+ // sandbox — exporting it would fail or pick up a stale same-path file.
+ mockListPlugins.mockResolvedValue([
+ {
+ apiName: 'file_change',
+ arguments: undefined,
+ createdAt: new Date('2026-07-20T00:01:00.000Z'),
+ id: 'hetero-1',
+ identifier: 'codex',
+ state: {
+ changes: [{ kind: 'update', linesAdded: 3, linesDeleted: 1, path: '/x/report.xlsx' }],
+ },
+ toolCallId: 'tc-hetero-1',
+ },
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockExportAndUploadFile).not.toHaveBeenCalled();
+ expect(mockRegisterFile).not.toHaveBeenCalled();
+ });
+
+ it('registers sandbox-backed entities while skipping hetero-provenance ones in the same op', async () => {
+ mockListPlugins.mockResolvedValue([
+ writeRow('a', '/mnt/data/deck.pptx'),
+ {
+ apiName: 'file_change',
+ arguments: undefined,
+ createdAt: new Date('2026-07-20T00:02:00.000Z'),
+ id: 'hetero-1',
+ identifier: 'codex',
+ state: {
+ changes: [{ kind: 'update', linesAdded: 3, linesDeleted: 1, path: '/x/report.xlsx' }],
+ },
+ toolCallId: 'tc-hetero-1',
+ },
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).toHaveBeenCalledTimes(1);
+ expect(mockRegisterFile.mock.calls[0][0].filePath).toBe('/mnt/data/deck.pptx');
+ });
+
+ it('prefers the terminal state totals over the (not-yet-persisted) op row', async () => {
+ // Pre-snapshot registration runs BEFORE recordCompletion writes the op row's
+ // cost/usage columns — the row still reads null on a first completion.
+ mockListOperationTree.mockResolvedValue([
+ { ...rootOp, cost: null, totalCost: null, usage: null },
+ ]);
+ mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/deck.pptx')]);
+
+ await registerFileWorksForOperation({
+ ...baseParams,
+ finalCost: { total: 1.25 },
+ finalUsage: { tokens: 42 },
+ });
+
+ const call = mockRegisterFile.mock.calls[0][0];
+ expect(call.cumulativeCost).toBe(1.25);
+ expect(call.cumulativeUsage).toMatchObject({ cost: { total: 1.25 }, usage: { tokens: 42 } });
+ });
+
+ it('rolls terminal child-op spend into the state-sourced cumulative cost', async () => {
+ // Children complete before their root, so their rows already carry final
+ // totals; the state-sourced figure must match the op row's rolled-up column.
+ mockListOperationTree.mockResolvedValue([
+ { ...rootOp, cost: null, totalCost: null, usage: null },
+ { ...rootOp, id: 'child-1', parentOperationId: 'op-1', totalCost: 0.3 },
+ ]);
+ mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/deck.pptx')]);
+
+ await registerFileWorksForOperation({
+ ...baseParams,
+ finalCost: { total: 1 },
+ finalUsage: { tokens: 42 },
+ });
+
+ expect(mockRegisterFile.mock.calls[0][0].cumulativeCost).toBe(1.3);
+ });
+
+ it('registers a code-generated entity artifact from its exportFile record', async () => {
+ // python-pptx / reportlab artifacts are produced by executeCode (a scanner
+ // blind spot) — the exportFile call is the only record carrying the path.
+ mockListPlugins.mockResolvedValue([
+ {
+ apiName: 'executeCode',
+ arguments: JSON.stringify({ code: 'make_deck()' }),
+ createdAt: new Date('2026-07-20T00:01:00.000Z'),
+ id: 'exec-1',
+ identifier: 'lobe-cloud-sandbox',
+ state: { success: true },
+ toolCallId: 'tc-exec-1',
+ },
+ exportRow('bb', '/workspace/deck.pptx'),
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).toHaveBeenCalledTimes(1);
+ // Re-exported through the collision-proof pipeline, not the exportFile blob.
+ expect(mockExportAndUploadFile.mock.calls[0][0]).toBe('/workspace/deck.pptx');
+ expect(mockRegisterFile.mock.calls[0][0]).toMatchObject({
+ filePath: '/workspace/deck.pptx',
+ messageId: 'bb',
+ title: 'deck.pptx',
+ toolIdentifier: 'lobe-cloud-sandbox',
+ toolName: 'exportFile',
+ });
+ });
+
+ it('registers a skill-generated entity artifact from its lobe-skills exportFile record', async () => {
+ // A skill flow (e.g. the pptx skill) routes generation through the skills
+ // tool: execScript builds the deck, and the skills exportFile — whose
+ // state carries no `path` — is the only record with the artifact's location.
+ mockListPlugins.mockResolvedValue([
+ {
+ apiName: 'execScript',
+ arguments: JSON.stringify({ script: 'node make_deck.mjs' }),
+ createdAt: new Date('2026-07-20T00:01:00.000Z'),
+ id: 'exec-1',
+ identifier: 'lobe-skills',
+ state: { exitCode: 0, success: true },
+ toolCallId: 'tc-exec-1',
+ },
+ skillsExportRow('bb', '/workspace/deck.pptx'),
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).toHaveBeenCalledTimes(1);
+ // Re-exported from the topic sandbox through the collision-proof pipeline.
+ expect(mockExportAndUploadFile.mock.calls[0][0]).toBe('/workspace/deck.pptx');
+ expect(mockRegisterFile.mock.calls[0][0]).toMatchObject({
+ filePath: '/workspace/deck.pptx',
+ messageId: 'bb',
+ title: 'deck.pptx',
+ toolIdentifier: 'lobe-skills',
+ toolName: 'exportFile',
+ });
+ });
+
+ it('ignores failed, stateless, and non-entity lobe-skills exportFile records', async () => {
+ mockListPlugins.mockResolvedValue([
+ skillsExportRow('a', '/workspace/notes.txt'),
+ { ...skillsExportRow('bb', '/workspace/bad.pptx'), error: 'export boom' },
+ // A failed skills export persists no state (success: false, content only).
+ { ...skillsExportRow('ccc', '/workspace/failed.pptx'), state: undefined },
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).not.toHaveBeenCalled();
+ expect(mockExportAndUploadFile).not.toHaveBeenCalled();
+ });
+
+ it('ignores non-entity, failed, and resultless exportFile records', async () => {
+ mockListPlugins.mockResolvedValue([
+ exportRow('a', '/workspace/notes.txt'),
+ { ...exportRow('bb', '/workspace/bad.pptx'), error: 'export boom' },
+ { ...exportRow('ccc', '/workspace/pending.pptx'), state: undefined },
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).not.toHaveBeenCalled();
+ expect(mockExportAndUploadFile).not.toHaveBeenCalled();
+ });
+
+ it('does not double-register a path that was both edited and exported', async () => {
+ mockListPlugins.mockResolvedValue([
+ writeRow('a', '/mnt/data/data.csv'),
+ exportRow('bb', '/mnt/data/data.csv'),
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).toHaveBeenCalledTimes(1);
+ // The edit-scan entry wins (richer provenance/line data).
+ expect(mockRegisterFile.mock.calls[0][0]).toMatchObject({
+ filePath: '/mnt/data/data.csv',
+ toolName: 'writeFile',
+ });
+ });
+
+ it('does not register a deleted entity file', async () => {
+ mockListPlugins.mockResolvedValue([
+ {
+ apiName: 'file_change',
+ arguments: undefined,
+ createdAt: new Date('2026-07-20T00:01:00.000Z'),
+ id: 'del-1',
+ identifier: 'codex',
+ state: {
+ changes: [{ kind: 'delete', linesAdded: 0, linesDeleted: 5, path: '/x/old.pptx' }],
+ },
+ toolCallId: 'tc-del-1',
+ },
+ ]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).not.toHaveBeenCalled();
+ expect(mockExportAndUploadFile).not.toHaveBeenCalled();
+ });
+
+ it('no-ops when the root operation has no topic', async () => {
+ mockListOperationTree.mockResolvedValue([{ ...rootOp, topicId: null }]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockListPlugins).not.toHaveBeenCalled();
+ expect(mockRegisterFile).not.toHaveBeenCalled();
+ });
+
+ it('no-ops for a sub-operation whose parent is still active (root will scan the tree)', async () => {
+ // A normal sub-op completes while its parent is still running; the parent
+ // scans the whole tree on its own completion, so registering here duplicates.
+ mockListOperationTree.mockResolvedValue([{ ...rootOp, parentOperationId: 'parent-1' }]);
+ mockFindById.mockResolvedValue({ status: 'running' });
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockFindById).toHaveBeenCalledWith('parent-1');
+ expect(mockListPlugins).not.toHaveBeenCalled();
+ expect(mockRegisterFile).not.toHaveBeenCalled();
+ });
+
+ it('no-ops for a sub-operation whose parent is parked (waiting_for_async_tool)', async () => {
+ // Parked (waiting_for_human / waiting_for_async_tool) is NON-terminal: the
+ // parent will resume, complete, and scan the whole subtree — so still a no-op.
+ mockListOperationTree.mockResolvedValue([{ ...rootOp, parentOperationId: 'parent-1' }]);
+ mockFindById.mockResolvedValue({ status: 'waiting_for_async_tool' });
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockRegisterFile).not.toHaveBeenCalled();
+ });
+
+ it('registers an auto-repair sub-op once its parent has already reached a terminal state', async () => {
+ // A repair op is spawned AFTER the parent reached a terminal state and ran
+ // its own tree scan; the parent will never re-scan, so the repair must
+ // register its OWN edits (a legitimately new version).
+ mockListOperationTree.mockResolvedValue([{ ...rootOp, parentOperationId: 'parent-1' }]);
+ mockFindById.mockResolvedValue({ status: 'done' });
+ mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/fix.xlsx')]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockFindById).toHaveBeenCalledWith('parent-1');
+ expect(mockRegisterFile).toHaveBeenCalledTimes(1);
+ expect(mockRegisterFile.mock.calls[0][0]).toMatchObject({
+ filePath: '/mnt/data/fix.xlsx',
+ // Dedup key is this op's OWN id — the repair produces a new version.
+ toolCallId: 'op:op-1',
+ });
+ });
+
+ it("scans ONLY the terminal-parent repair op's own records, never the tree", async () => {
+ // The tree also holds a child of the completing op; a terminal-parent repair
+ // path must scan only the completing op's records (tree scanning is reserved
+ // for the root), so the child's edits are NOT swept in.
+ mockListOperationTree.mockResolvedValue([
+ { ...rootOp, parentOperationId: 'parent-1' },
+ { ...rootOp, id: 'child-1', parentOperationId: 'op-1' },
+ ]);
+ mockFindById.mockResolvedValue({ status: 'error' });
+ mockListPlugins.mockImplementation(async ({ operationId }: { operationId: string }) =>
+ operationId === 'op-1'
+ ? [writeRow('a', '/mnt/data/own.xlsx')]
+ : [writeRow('bb', '/mnt/data/child.xlsx')],
+ );
+
+ await registerFileWorksForOperation(baseParams);
+
+ // Only the completing op's plugin window is queried — the child is skipped.
+ expect(mockListPlugins).toHaveBeenCalledTimes(1);
+ expect(mockRegisterFile).toHaveBeenCalledTimes(1);
+ expect(mockRegisterFile.mock.calls[0][0].filePath).toBe('/mnt/data/own.xlsx');
+ });
+
+ it('uploads under a collision-proof storage name while keeping a clean display filename', async () => {
+ mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/deck.pptx')]);
+
+ await registerFileWorksForOperation(baseParams);
+
+ const [path, filename, options] = mockExportAndUploadFile.mock.calls[0];
+ expect(path).toBe('/mnt/data/deck.pptx');
+ // Display/download filename stays the clean basename...
+ expect(filename).toBe('deck.pptx');
+ // ...while the storage key is `${sha1(`${op}:${path}`).slice(0, 16)}-${basename}`.
+ expect(options?.storageName).toMatch(/^[\da-f]{16}-deck\.pptx$/);
+ });
+
+ it('derives distinct storage names for two same-day operations editing the same path', async () => {
+ // Real operationIds share an `op_${Date.now()}` prefix whose first 8 chars
+ // only roll over every ~27.8h — hashing the FULL id (not a prefix) is what
+ // keeps two same-day ops from clobbering each other's uploaded object.
+ mockListOperationTree.mockImplementation(async (opId: string) => [{ ...rootOp, id: opId }]);
+ mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/report.xlsx')]);
+
+ await registerFileWorksForOperation({ ...baseParams, operationId: 'op_1784632944000_abc' });
+ await registerFileWorksForOperation({ ...baseParams, operationId: 'op_1784632999000_def' });
+
+ const first = mockExportAndUploadFile.mock.calls[0][2].storageName;
+ const second = mockExportAndUploadFile.mock.calls[1][2].storageName;
+ expect(first).not.toBe(second);
+ // Both still end in the clean basename.
+ expect(first).toMatch(/^[\da-f]{16}-report\.xlsx$/);
+ expect(second).toMatch(/^[\da-f]{16}-report\.xlsx$/);
+ });
+
+ it('skips export + registration when the version was already registered (retry idempotency)', async () => {
+ mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/deck.pptx')]);
+ mockFindFileVersionByToolCall.mockResolvedValue({ id: 'existing-version' });
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockFindFileVersionByToolCall).toHaveBeenCalledWith({
+ filePath: '/mnt/data/deck.pptx',
+ toolCallId: 'op:op-1',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+ expect(mockExportAndUploadFile).not.toHaveBeenCalled();
+ expect(mockRegisterFile).not.toHaveBeenCalled();
+ });
+
+ it('gathers tool calls across the operation tree (root + sub-op)', async () => {
+ const subOp = {
+ ...rootOp,
+ completedAt: new Date('2026-07-20T00:04:00.000Z'),
+ id: 'sub-1',
+ startedAt: new Date('2026-07-20T00:02:00.000Z'),
+ };
+ mockListOperationTree.mockResolvedValue([rootOp, subOp]);
+ mockListPlugins.mockImplementation(async ({ operationId }: { operationId: string }) =>
+ operationId === 'op-1'
+ ? [writeRow('a', '/mnt/data/root.pptx')]
+ : [writeRow('bb', '/mnt/data/sub.xlsx')],
+ );
+
+ await registerFileWorksForOperation(baseParams);
+
+ expect(mockListPlugins).toHaveBeenCalledTimes(2);
+ expect(mockRegisterFile).toHaveBeenCalledTimes(2);
+ expect(mockRegisterFile.mock.calls.map((c) => c[0].filePath).sort()).toEqual([
+ '/mnt/data/root.pptx',
+ '/mnt/data/sub.xlsx',
+ ]);
+ });
+});
+
+describe('redeployFileWork', () => {
+ it('is a resolved no-op integration seam', async () => {
+ await expect(
+ redeployFileWork({ filePath: '/x/a.pptx', versionId: 'v1', workId: 'w1' }),
+ ).resolves.toBeUndefined();
+ });
+});
+
+describe('stateHasEntityFileEdits', () => {
+ const sandboxCall = (id: string, apiName: string, args: unknown) => ({
+ function: {
+ arguments: JSON.stringify(args),
+ name: `lobe-cloud-sandbox____${apiName}____builtin`,
+ },
+ id,
+ type: 'function',
+ });
+
+ const stateWith = (toolCalls: unknown[]) => ({
+ messages: [
+ { content: 'make me a deck', role: 'user' },
+ { content: '', role: 'assistant', tool_calls: toolCalls },
+ { content: 'ok', role: 'tool', tool_call_id: 't1' },
+ ],
+ });
+
+ it('detects an entity-format sandbox write', () => {
+ expect(
+ stateHasEntityFileEdits(
+ stateWith([sandboxCall('t1', 'writeFile', { path: '/w/deck.pptx' })]),
+ ),
+ ).toBe(true);
+ });
+
+ it('ignores non-entity files (html / md)', () => {
+ expect(
+ stateHasEntityFileEdits(
+ stateWith([
+ sandboxCall('t1', 'writeFile', { path: '/w/index.html' }),
+ sandboxCall('t2', 'editFile', { path: '/w/notes.md' }),
+ ]),
+ ),
+ ).toBe(false);
+ });
+
+ it('ignores non-sandbox tool calls, even with entity-looking arguments', () => {
+ expect(
+ stateHasEntityFileEdits(
+ stateWith([
+ {
+ function: {
+ arguments: JSON.stringify({ file_path: '/w/deck.pptx' }),
+ name: 'claude-code____Write____builtin',
+ },
+ id: 't1',
+ type: 'function',
+ },
+ ]),
+ ),
+ ).toBe(false);
+ });
+
+ it('returns false for empty or malformed state', () => {
+ expect(stateHasEntityFileEdits(undefined)).toBe(false);
+ expect(stateHasEntityFileEdits({})).toBe(false);
+ expect(stateHasEntityFileEdits({ messages: 'nope' })).toBe(false);
+ expect(
+ stateHasEntityFileEdits(
+ stateWith([
+ { function: { arguments: '{not json', name: 'lobe-cloud-sandbox____writeFile' } },
+ ]),
+ ),
+ ).toBe(false);
+ });
+
+ it('detects a moveFiles rename onto an entity destination from its arguments', () => {
+ // moveFiles is only classifiable from its tool RESULT, which the pure state
+ // scan lacks — the predictor over-approximates from the requested
+ // destinations instead (a failed/rejected move still counts).
+ expect(
+ stateHasEntityFileEdits(
+ stateWith([
+ sandboxCall('t1', 'moveFiles', {
+ operations: [{ destination: '/w/deck.pptx', source: '/w/draft.tmp' }],
+ }),
+ ]),
+ ),
+ ).toBe(true);
+ });
+
+ it('ignores moveFiles calls with only non-entity destinations or malformed args', () => {
+ expect(
+ stateHasEntityFileEdits(
+ stateWith([
+ sandboxCall('t1', 'moveFiles', {
+ operations: [{ destination: '/w/archive/notes.md', source: '/w/notes.md' }],
+ }),
+ {
+ function: {
+ arguments: '{not json',
+ name: 'lobe-cloud-sandbox____moveFiles____builtin',
+ },
+ id: 't2',
+ type: 'function',
+ },
+ ]),
+ ),
+ ).toBe(false);
+ });
+
+ it('detects entity edits inside conversation-flow grouped nodes (children[].tools)', () => {
+ // After a tool batch the runtime re-queries state.messages with
+ // `flatten: true`, folding this run's turn into an assistantGroup — the
+ // sandbox calls then live on children[].tools, not message.tool_calls.
+ const grouped = {
+ children: [
+ {
+ tools: [
+ {
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ path: '/w/deck.pptx' }),
+ id: 't1',
+ identifier: 'lobe-cloud-sandbox',
+ result: { state: { path: '/w/deck.pptx', success: true } },
+ },
+ ],
+ },
+ ],
+ role: 'assistantGroup',
+ };
+ expect(
+ stateHasEntityFileEdits({ messages: [{ content: 'make a deck', role: 'user' }, grouped] }),
+ ).toBe(true);
+ });
+
+ it('classifies a grouped moveFiles rename from its result state', () => {
+ const grouped = {
+ children: [
+ {
+ tools: [
+ {
+ apiName: 'moveFiles',
+ arguments: JSON.stringify({
+ operations: [{ destination: '/w/deck.pptx', source: '/w/draft.tmp' }],
+ }),
+ id: 't1',
+ identifier: 'lobe-cloud-sandbox',
+ result: {
+ state: {
+ results: [{ destination: '/w/deck.pptx', source: '/w/draft.tmp', success: true }],
+ },
+ },
+ },
+ ],
+ },
+ ],
+ role: 'assistantGroup',
+ };
+ expect(
+ stateHasEntityFileEdits({ messages: [{ content: 'rename it', role: 'user' }, grouped] }),
+ ).toBe(true);
+ });
+
+ it('ignores entity edits from PREVIOUS turns (before the last user message)', () => {
+ // A past run's entity edit already registered on its own completion —
+ // counting it would permanently disable the early publish for the topic.
+ const pastGroup = {
+ children: [
+ {
+ tools: [
+ {
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ path: '/w/old-deck.pptx' }),
+ id: 't1',
+ identifier: 'lobe-cloud-sandbox',
+ result: { state: { path: '/w/old-deck.pptx', success: true } },
+ },
+ ],
+ },
+ ],
+ role: 'assistantGroup',
+ };
+ expect(
+ stateHasEntityFileEdits({
+ messages: [
+ { content: 'make a deck', role: 'user' },
+ pastGroup,
+ { content: 'now just summarize it', role: 'user' },
+ { content: 'summary...', role: 'assistant' },
+ ],
+ }),
+ ).toBe(false);
+ });
+
+ it('detects an entity exportFile call from its arguments (raw and grouped shapes)', () => {
+ // Raw tool_calls shape.
+ expect(
+ stateHasEntityFileEdits(
+ stateWith([sandboxCall('t1', 'exportFile', { path: '/workspace/deck.pptx' })]),
+ ),
+ ).toBe(true);
+ // Grouped (assistantGroup children[].tools) shape.
+ const grouped = {
+ children: [
+ {
+ tools: [
+ {
+ apiName: 'exportFile',
+ arguments: JSON.stringify({ path: '/workspace/report.pdf' }),
+ id: 't1',
+ identifier: 'lobe-cloud-sandbox',
+ },
+ ],
+ },
+ ],
+ role: 'assistantGroup',
+ };
+ expect(
+ stateHasEntityFileEdits({ messages: [{ content: 'export it', role: 'user' }, grouped] }),
+ ).toBe(true);
+ // Non-entity export keeps the early publish.
+ expect(
+ stateHasEntityFileEdits(
+ stateWith([sandboxCall('t1', 'exportFile', { path: '/workspace/notes.txt' })]),
+ ),
+ ).toBe(false);
+ });
+
+ it('detects an entity lobe-skills exportFile call (raw and grouped shapes)', () => {
+ const skillsCall = (id: string, args: unknown) => ({
+ function: { arguments: JSON.stringify(args), name: 'lobe-skills____exportFile____builtin' },
+ id,
+ type: 'function',
+ });
+ // Raw tool_calls shape.
+ expect(
+ stateHasEntityFileEdits(
+ stateWith([skillsCall('t1', { filename: 'deck.pptx', path: '/workspace/deck.pptx' })]),
+ ),
+ ).toBe(true);
+ // Grouped (assistantGroup children[].tools) shape.
+ const grouped = {
+ children: [
+ {
+ tools: [
+ {
+ apiName: 'exportFile',
+ arguments: JSON.stringify({ filename: 'report.pdf', path: '/workspace/report.pdf' }),
+ id: 't1',
+ identifier: 'lobe-skills',
+ },
+ ],
+ },
+ ],
+ role: 'assistantGroup',
+ };
+ expect(
+ stateHasEntityFileEdits({ messages: [{ content: 'export it', role: 'user' }, grouped] }),
+ ).toBe(true);
+ // Non-entity skills export keeps the early publish.
+ expect(
+ stateHasEntityFileEdits(
+ stateWith([skillsCall('t1', { filename: 'notes.txt', path: '/workspace/notes.txt' })]),
+ ),
+ ).toBe(false);
+ });
+
+ it('detects an entity edit mixed among non-entity edits', () => {
+ expect(
+ stateHasEntityFileEdits(
+ stateWith([
+ sandboxCall('t1', 'writeFile', { path: '/w/notes.md' }),
+ sandboxCall('t2', 'writeFile', { path: '/w/report.xlsx' }),
+ ]),
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/fileWorkRegistration.ts b/apps/server/src/services/agentRuntime/fileWorkRegistration.ts
new file mode 100644
index 00000000000..d107bfa9f77
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/fileWorkRegistration.ts
@@ -0,0 +1,738 @@
+import { createHash } from 'node:crypto';
+
+import { isParkedStatus } from '@lobechat/agent-runtime';
+import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';
+import {
+ classifyEditedFile,
+ CLOUD_SANDBOX_IDENTIFIER,
+ type EditedFileEntry,
+ type FileEditToolCallRecord,
+ getBasename,
+ normalizeScanPath,
+ scanOperationFileEdits,
+} from '@lobechat/builtin-tools/fileEditScan';
+import type { WorkVersionCumulativeUsage, WorkVersionMetadata } from '@lobechat/types';
+import debug from 'debug';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { MessageModel } from '@/database/models/message';
+import { WorkModel } from '@/database/models/work';
+import { type LobeChatDatabase } from '@/database/type';
+import { FileService } from '@/server/services/file';
+import { MarketService } from '@/server/services/market';
+import { createSandboxService } from '@/server/services/sandbox';
+
+const log = debug('lobe-server:file-work-registration');
+
+/** One tool call gathered from the operation tree, tagged for ordering + provenance. */
+type ScannedRecord = FileEditToolCallRecord & { createdAt: Date; id: string };
+
+/** The last-edit tool call for a file, used as the version's provenance. */
+interface FileProvenance {
+ apiName: string;
+ identifier: string;
+ messageId: string;
+}
+
+export interface RegisterFileWorksForOperationParams {
+ /**
+ * Terminal in-memory cost blob of the completing operation (`state.cost`).
+ *
+ * Pass it when available: on the pre-snapshot registration path the
+ * `agent_operations` row's cost/usage columns are NOT persisted yet
+ * (`recordCompletion` runs later in dispatchHooks), so reading the op row
+ * alone would attach null (first completion) or stale (park/resume)
+ * cumulative figures to the registered version.
+ */
+ finalCost?: { total?: number | null } | null;
+ /** Terminal in-memory usage blob of the completing operation (`state.usage`). */
+ finalUsage?: Record<string, unknown> | null;
+ operationId: string;
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Per-operation outcome of {@link registerFileWorksForOperation}. Lets the caller
+ * decide whether the idempotency marker may be stamped: only a run with
+ * `failed === 0` is complete. Files that were already registered (probe
+ * short-circuit) or newly registered count as attempted successes; a failed
+ * sandbox export or a thrown per-file chain counts as `failed`.
+ */
+export interface FileWorksRegistrationOutcome {
+ /** Entity files this completion tried to register (edits + exported paths). */
+ attempted: number;
+ /** How many of `attempted` did not end up registered this round. */
+ failed: number;
+}
+
+/**
+ * Cap the per-entity export fanout. Each entity task fires a sandbox export + a
+ * storage upload + DB writes, and the WHOLE batch is awaited before the terminal
+ * snapshot is published, so unbounded parallelism on an operation touching
+ * hundreds of files would hammer the sandbox / storage / DB and delay the
+ * terminal snapshot (and thus perceived loading end). Keep a small ceiling.
+ */
+const FILE_WORK_EXPORT_CONCURRENCY = 5;
+
+/**
+ * Run `task` over `items` with at most `limit` tasks in flight, collecting
+ * results in input order (a bounded `Promise.allSettled`). `task` is expected to
+ * be self-guarded and never reject; a stray rejection is still captured as a
+ * settled result so one item can never abort the batch. No `p-limit` dependency
+ * exists in this workspace, so this tiny helper stands in for it.
+ */
+const mapWithConcurrency = async <T, R>(
+ items: T[],
+ limit: number,
+ task: (item: T) => Promise<R>,
+): Promise<PromiseSettledResult<R>[]> => {
+ // Index-assigned in worker order, so results stay aligned with `items`.
+ const results: PromiseSettledResult<R>[] = [];
+ let cursor = 0;
+ const worker = async (): Promise<void> => {
+ while (cursor < items.length) {
+ const index = cursor;
+ cursor += 1;
+ try {
+ results[index] = { status: 'fulfilled', value: await task(items[index]) };
+ } catch (error) {
+ results[index] = { reason: error, status: 'rejected' };
+ }
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
+ return results;
+};
+
+/**
+ * Integration seam for file-source deployment (artifact hosting).
+ *
+ * Called once per registered `file` Work version. The implementation — pushing
+ * the exported entity file to a hosted, shareable location — is filled in by a
+ * later change; today this is intentionally a no-op so the registration flow
+ * and its call site are already in place.
+ */
+export const redeployFileWork = async (_params: {
+ fileId?: string;
+ fileUrl?: string;
+ filePath: string;
+ versionId: string | null;
+ workId: string;
+}): Promise<void> => {
+ // 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:
+ * - `lobe-cloud-sandbox` exportFile — `state.path` IS the sandbox location.
+ * Unlike edits, an export carries no other success signal, so the persisted
+ * result state is required.
+ * - `lobe-skills` exportFile — a skill flow (e.g. the pptx skill) routes ALL
+ * its tool calls through the skills tool, so its export is the only record
+ * carrying the artifact's path. Its state has NO `path` field (only
+ * fileId/filename/url…) and a FAILED export persists no state at all
+ * (`SkillsExecutionRuntime.exportFile` returns `success: false` without one),
+ * so state presence is the success signal and the path comes from the call
+ * arguments. A device-routed skills exportFile throws before producing a
+ * state, so a stateful row proves the file lives in THIS topic's cloud
+ * sandbox. (Skills runCommand/execScript rows enter the shell-command scan
+ * only when `state.executionEnv === 'device'` — those edits live on the
+ * device, never register as Works, and are surfaced by the client's
+ * edited-files card instead.)
+ */
+const resolveExportedSandboxPath = (
+ record: Pick<ScannedRecord, 'arguments' | 'identifier' | 'state'>,
+): string | undefined => {
+ // Normalize the resolved path (same lexical rule the scanner applies to edit
+ // paths) so an exported `/work/./deck.pptx` keys against an edited
+ // `/work/deck.pptx` in the dedup below instead of registering a duplicate.
+ if (record.identifier === CLOUD_SANDBOX_IDENTIFIER) {
+ const state = record.state as { path?: unknown } | undefined;
+ const path = typeof state?.path === 'string' ? state.path.trim() : '';
+ return path ? normalizeScanPath(path) : undefined;
+ }
+ if (record.identifier === SkillsIdentifier) {
+ if (typeof record.state !== 'object' || record.state === null) return undefined;
+ try {
+ const path: unknown = JSON.parse(record.arguments ?? '')?.path;
+ const trimmed = typeof path === 'string' ? path.trim() : '';
+ return trimmed ? normalizeScanPath(trimmed) : undefined;
+ } catch {
+ return undefined;
+ }
+ }
+ 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-sensitive
+ * folding resolves correctly across sub-operations.
+ */
+const collectOperationRecords = async (
+ messageModel: MessageModel,
+ tree: Awaited<ReturnType<AgentOperationModel['listOperationTree']>>,
+): Promise<ScannedRecord[]> => {
+ // Fetch every operation's plugin rows in parallel; `Promise.all` preserves the
+ // tree order, so the first-seen-wins dedup below is identical to the previous
+ // sequential loop (and the final sort makes ordering fully deterministic).
+ const rowsPerOp = await Promise.all(
+ tree.map((op) =>
+ // A window needs at least the topic + start bound; ops missing either can't
+ // be located (completedAt falls back to "now" inside the model method).
+ op.topicId && op.startedAt
+ ? messageModel.listMessagePluginsForOperation({
+ completedAt: op.completedAt,
+ operationId: op.id,
+ startedAt: op.startedAt,
+ threadId: op.threadId,
+ topicId: op.topicId,
+ })
+ : Promise.resolve([]),
+ ),
+ );
+
+ const byMessageId = new Map<string, ScannedRecord>();
+ for (const rows of rowsPerOp) {
+ for (const row of rows) {
+ if (byMessageId.has(row.id)) continue;
+ const interventionStatus = (row.intervention as { status?: string } | undefined)?.status;
+ if (interventionStatus && UNEXECUTED_INTERVENTION_STATUSES.has(interventionStatus)) continue;
+ byMessageId.set(row.id, {
+ apiName: row.apiName ?? '',
+ arguments: row.arguments,
+ createdAt: row.createdAt,
+ // A plugin-level error means the edit never landed — the scanner skips
+ // such records (mirrors the client's `tool.result?.error`).
+ error: row.error,
+ id: row.id,
+ identifier: row.identifier,
+ state: row.state,
+ toolCallId: row.toolCallId ?? '',
+ });
+ }
+ }
+
+ return [...byMessageId.values()].sort((a, b) => {
+ const delta = a.createdAt.getTime() - b.createdAt.getTime();
+ return delta === 0 ? a.id.localeCompare(b.id) : delta;
+ });
+};
+
+/**
+ * On operation completion, scan every file edited during the operation (and its
+ * sub-operations), and register each ENTITY-format file (pptx/xlsx/docx/pdf, …)
+ * as a `file` Work — exactly one new version per operation, its content exported
+ * from the sandbox and persisted so the version has a durable, fetchable URL.
+ *
+ * Contract:
+ * - A ROOT operation scans the whole operation tree so a sub-agent's edits are
+ * captured, registering the tree exactly once. A SUB-op normally returns early
+ * (the root already covers it), EXCEPT an auto-repair op whose parent is
+ * already terminal — the parent will never re-scan, so the repair registers
+ * just its OWN edits (a new version). See the scan-scope block below.
+ * - HTML / other files are skipped: HTML rides the artifact-hosting path and the
+ * rest fold into the frontend's aggregate "edited N files" card.
+ * - Besides scanned EDITS, successfully `exportFile`-d entity paths register
+ * too: binary entity formats are produced by sandbox code execution (not by
+ * the text-based write/edit tools), so the export call is the only persisted
+ * record carrying their path. Both export surfaces count — the sandbox
+ * tool's `exportFile` and the skills tool's (`lobe-skills`) `exportFile`.
+ * - `deleted` files are skipped (nothing to persist).
+ * - One version per operation via the dedup key `op:${operationId}`; a retry of
+ * the same operation is idempotent — an existence probe short-circuits before
+ * re-exporting, and the `(workId, toolCallId)` unique guard backs it up.
+ * - Best-effort per file: an export or registration failure for one file is
+ * logged and skipped, never aborting the others.
+ *
+ * Returns a {@link FileWorksRegistrationOutcome} summary (`attempted` / `failed`)
+ * so the caller can gate its idempotency marker: because each file is wrapped in
+ * its own try/catch and folded through `mapWithConcurrency` (a bounded
+ * allSettled), this function NEVER rejects on a per-file failure — the counts are
+ * the only signal a caller has that some files did not register. A run with
+ * `failed > 0` must leave the marker unset so a later call retries (the per-file
+ * DB probe short-circuits the ones that already succeeded). The early no-op paths
+ * (no topic / no records / no candidates) return `attempted: 0, failed: 0`.
+ *
+ * Awaited (not fire-and-forget) by the completion lifecycle so a serverless
+ * response freeze can't drop the background write; the caller still swallows any
+ * whole-function rejection so file-Work registration can never affect operation
+ * completion.
+ */
+export const registerFileWorksForOperation = async (
+ params: RegisterFileWorksForOperationParams,
+): Promise<FileWorksRegistrationOutcome> => {
+ const { operationId, serverDB, userId, workspaceId } = params;
+
+ const operationModel = new AgentOperationModel(serverDB, userId, workspaceId);
+ const tree = await operationModel.listOperationTree(operationId);
+
+ const completingOp = tree.find((op) => op.id === operationId);
+ // The completing op supplies the sandbox session (userId + topicId) and the
+ // resource identity's topic; without a topic there is nothing to register.
+ if (!completingOp?.topicId) {
+ log('[%s] Skipping file Work registration: completing operation has no topic', operationId);
+ return { attempted: 0, failed: 0 };
+ }
+
+ // Which tool calls this completion is responsible for registering.
+ //
+ // ROOT op (no parent): scan the WHOLE operation tree, so a sub-agent's edits
+ // register too. A sub-op always completes before its root (persistCompletion
+ // writes each child row before dispatching the hook that unparks the parent),
+ // so the root registers the whole tree exactly once.
+ //
+ // SUB-op (has a parent): its edits are normally already covered by the root's
+ // tree scan, so re-scanning here under a DIFFERENT `op:${opId}` key would
+ // produce a duplicate version — hence the historical "sub-op is a no-op" rule.
+ // The ONE exception is an auto-repair operation (see repairService): it is
+ // spawned AFTER its parent already reached a terminal state and ran its tree
+ // scan, so the parent will never scan again and the repair's edits would be
+ // lost. Distinguish by the parent's status:
+ // - parent still active (idle / running / parked — waiting_for_human or
+ // waiting_for_async_tool, per isParkedStatus) → it will scan the whole
+ // subtree on its own completion, so no-op here to avoid the duplicate.
+ // - parent already terminal (done / error / interrupted) → register this
+ // op's OWN edits (a legitimately new version for the repair), scanning
+ // ONLY this op's records — tree scanning stays reserved for the root.
+ let scanTree = tree;
+ if (completingOp.parentOperationId) {
+ const parentOp = await operationModel.findById(completingOp.parentOperationId);
+ const parentStatus = parentOp?.status;
+ const parentActive =
+ !parentStatus ||
+ parentStatus === 'idle' ||
+ parentStatus === 'running' ||
+ isParkedStatus(parentStatus);
+ if (parentActive) {
+ log(
+ '[%s] Skipping file Work registration: parent operation is still active (%s)',
+ operationId,
+ parentStatus ?? 'missing',
+ );
+ return { attempted: 0, failed: 0 };
+ }
+ scanTree = tree.filter((op) => op.id === operationId);
+ }
+
+ const topicId = completingOp.topicId;
+
+ const messageModel = new MessageModel(serverDB, userId, workspaceId);
+ const records = await collectOperationRecords(messageModel, scanTree);
+ if (records.length === 0) {
+ log(
+ '[%s] Skipping file Work registration: no plugin records across %d operation(s)',
+ operationId,
+ scanTree.length,
+ );
+ return { attempted: 0, failed: 0 };
+ }
+
+ // Map each tool call to its provenance so a file's version can point at the
+ // message/tool that last edited it.
+ const provenanceByToolCall = new Map<string, FileProvenance>();
+ for (const record of records) {
+ if (!record.toolCallId) continue;
+ provenanceByToolCall.set(record.toolCallId, {
+ apiName: record.apiName,
+ identifier: record.identifier ?? '',
+ messageId: record.id,
+ });
+ }
+
+ const resolveProvenance = (sourceToolCallIds: string[]): FileProvenance | undefined => {
+ // Walk the file's edits newest-first: the last edit that has a persisted
+ // provenance row wins.
+ for (let i = sourceToolCallIds.length - 1; i >= 0; i -= 1) {
+ const found = provenanceByToolCall.get(sourceToolCallIds[i]);
+ if (found) return found;
+ }
+ return undefined;
+ };
+
+ const scannedEntities = scanOperationFileEdits(records).filter(
+ (entry) => entry.kind !== 'deleted' && classifyEditedFile(entry.path).category === 'entity',
+ );
+ const entities = scannedEntities.filter((entry) => {
+ // Only sandbox-backed edits are exportable: the export below reads the file
+ // from THIS topic's cloud sandbox, so a hetero edit (codex / claude-code /
+ // lobe-local-system, including entities detected from shell command text) —
+ // which lives on the executing device, not in the sandbox — would either
+ // fail the export or, worse, pick up an unrelated stale sandbox file at the
+ // same path. Mirrors `stateHasEntityFileEdits`, which also only considers
+ // sandbox tool calls.
+ return resolveProvenance(entry.sourceToolCallIds)?.identifier === CLOUD_SANDBOX_IDENTIFIER;
+ });
+
+ // Entity artifacts GENERATED inside the sandbox (executeCode / runCommand /
+ // a skill's execScript — python-pptx or pptxgenjs decks, reportlab PDFs,
+ // openpyxl sheets, …) never surface through the edit scanner: binary formats
+ // can't be written by the text-based writeFile / editFile, so the only
+ // persisted record carrying their path is the agent's `exportFile` call —
+ // the sandbox tool's, or the skills tool's when a skill drives the flow
+ // (see `resolveExportedSandboxPath`). Treat each successfully exported
+ // entity path as a registerable input too. The file still lives in the
+ // sandbox, so it rides the same probe → collision-proof export → register
+ // pipeline below — the object `exportFile` itself uploaded is NOT reused:
+ // its storage key derives from the basename alone, so a later export of the
+ // same file would clobber it and break version immutability. Last export
+ // per path wins; paths already covered by the edit scan keep their richer
+ // (line-delta) entries.
+ const editedPaths = new Set(entities.map((entry) => entry.path));
+ const exportedByPath = new Map<string, EditedFileEntry>();
+ for (const record of records) {
+ if (record.apiName !== 'exportFile') continue;
+ if (record.error != null && record.error !== '') continue;
+ const path = resolveExportedSandboxPath(record);
+ if (!path || editedPaths.has(path)) continue;
+ if (classifyEditedFile(path).category !== 'entity') continue;
+ exportedByPath.set(path, {
+ diffTexts: [],
+ kind: 'modified',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path,
+ sourceToolCallIds: [record.toolCallId],
+ });
+ }
+ entities.push(...exportedByPath.values());
+ log(
+ '[%s] File Work scan: operations=%d records=%d entityEdits=%d sandboxCandidates=%d exportCandidates=%d',
+ operationId,
+ scanTree.length,
+ records.length,
+ scannedEntities.length,
+ entities.length - exportedByPath.size,
+ exportedByPath.size,
+ );
+ if (entities.length === 0) {
+ log('[%s] Skipping file Work registration: no sandbox-backed entity candidates', operationId);
+ return { attempted: 0, failed: 0 };
+ }
+
+ // The sandbox is derived from userId + topicId and outlives the operation, so
+ // it is safe to build once here for every export.
+ const marketService = new MarketService({ userInfo: { userId } });
+ const fileService = new FileService(serverDB, userId, workspaceId);
+ const sandboxService = createSandboxService({
+ fileService,
+ marketService,
+ serverDB,
+ topicId,
+ userId,
+ });
+
+ const workModel = new WorkModel(serverDB, userId, workspaceId);
+
+ // The whole operation's spend/usage is attached to each version registered
+ // this round (an operation-level, not per-file, figure — the scanner can't
+ // attribute cost to individual files). Prefer the terminal state's live blobs
+ // over the op row: on the pre-snapshot path the row's cost/usage columns are
+ // written only later by `recordCompletion`, so the row reads null/stale here.
+ // The op row's `totalCost` also rolls up terminal child ops; replicate that
+ // from the already-loaded tree (children complete before their root, so their
+ // rows carry final totals) to keep the state-sourced figure equivalent.
+ const childCost = tree
+ .filter((op) => op.id !== operationId)
+ .reduce((sum, op) => sum + (op.totalCost ?? 0), 0);
+ const ownCost = params.finalCost?.total;
+ const cumulativeCost =
+ typeof ownCost === 'number' ? ownCost + childCost : (completingOp.totalCost ?? null);
+ const usageBlob = params.finalUsage ?? completingOp.usage;
+ const cumulativeUsage: WorkVersionCumulativeUsage | null = usageBlob
+ ? {
+ capturedAt: new Date().toISOString(),
+ cost: params.finalCost ?? completingOp.cost ?? undefined,
+ usage: usageBlob,
+ }
+ : null;
+
+ // Register each entity file with bounded parallelism. Every file's own
+ // export → register → redeploy chain stays sequential inside its task, and each
+ // task keeps its own best-effort try/catch (returning 'ok' | 'failed' instead
+ // of throwing), so one file's failure never aborts the others. Parallelism is
+ // safe: `registerFile` keys its version row by `workId` (derived from the file
+ // path), so distinct files touch distinct `works` rows — no shared row-lock
+ // contention within a single operation. The concurrency cap bounds the
+ // sandbox/storage/DB fanout (see FILE_WORK_EXPORT_CONCURRENCY).
+ // One-version-per-operation dedup key; also the object-key prefix below.
+ const toolCallId = `op:${operationId}`;
+
+ const settled = await mapWithConcurrency(
+ entities,
+ FILE_WORK_EXPORT_CONCURRENCY,
+ async (entry): Promise<'failed' | 'ok'> => {
+ const basename = getBasename(entry.path);
+
+ try {
+ // Retry idempotency: if this (op, file) version already exists, the file
+ // was exported + registered on a previous attempt. Skip re-exporting —
+ // a re-export would overwrite the immutable object AND, if registration
+ // then no-op'd on the dedup guard, leave an orphan file record. The probe
+ // is a single joined query (resolve Work + check version by toolCallId).
+ const alreadyRegistered = await workModel.findFileVersionByToolCall({
+ filePath: entry.path,
+ toolCallId,
+ topicId,
+ userId,
+ });
+ if (alreadyRegistered) {
+ log('[%s] Skipping file %s: version already registered (retry)', operationId, entry.path);
+ // Idempotent skip: the file registered on a previous attempt, so it is
+ // a SUCCESS for marker purposes (not a failure to retry).
+ return 'ok';
+ }
+
+ // Object-key uniqueness: the sandbox export key is `date/topicId/storageName`
+ // (see SandboxMiddlewareService.exportAndUploadFile), so same-name files in
+ // different directories — and successive versions of one file — would
+ // clobber each other's uploaded object. Hash the FULL operationId + path
+ // (16 hex ≈ 64-bit) into the storage name so every (operation, path) maps
+ // to a distinct, immutable object. A prefix of `operationId` alone is NOT
+ // enough: real ids are `op_${Date.now()}_…`, whose first 8 chars only
+ // change every ~27.8h, so two ops editing the same path on the same day
+ // would collide. The Work title/metadata and the file record's display
+ // name still use the original basename; only the storage key differs.
+ const storageName = `${createHash('sha1')
+ .update(`${operationId}:${entry.path}`)
+ .digest('hex')
+ .slice(0, 16)}-${basename}`;
+
+ // Export must succeed before we register: the version carries the file's
+ // durable identity (fileId / url), so a failed export means we skip this
+ // file entirely rather than register a version pointing at nothing.
+ // Display name = basename (clean download filename); storage key uses the
+ // unique `storageName` so the object is never clobbered.
+ const exported = await sandboxService.exportAndUploadFile(entry.path, basename, {
+ storageName,
+ });
+ if (!exported.success) {
+ log(
+ '[%s] Skipping file %s: sandbox export failed: %s',
+ operationId,
+ entry.path,
+ exported.error?.message ?? 'unknown error',
+ );
+ // A failed export leaves nothing to register — count it so the caller
+ // withholds the marker and a later call retries this file.
+ return 'failed';
+ }
+
+ const provenance = resolveProvenance(entry.sourceToolCallIds);
+
+ const metadata: WorkVersionMetadata = {
+ fileId: exported.fileId,
+ filePath: entry.path,
+ fileSize: exported.size,
+ fileUrl: exported.url,
+ linesAdded: entry.linesAdded,
+ linesDeleted: entry.linesDeleted,
+ mimeType: exported.mimeType,
+ };
+
+ const work = await workModel.registerFile({
+ agentId: completingOp.agentId,
+ cumulativeCost,
+ cumulativeUsage,
+ filePath: entry.path,
+ messageId: provenance?.messageId,
+ metadata,
+ rootOperationId: operationId,
+ threadId: completingOp.threadId,
+ title: basename,
+ // One version per operation for this file; a retry is short-circuited
+ // by the probe above, and any residual race hits the
+ // (workId, toolCallId) unique guard and is a no-op.
+ toolCallId,
+ toolIdentifier: provenance?.identifier ?? '',
+ toolName: provenance?.apiName ?? '',
+ topicId,
+ userId,
+ });
+
+ await redeployFileWork({
+ fileId: exported.fileId,
+ fileUrl: exported.url,
+ filePath: entry.path,
+ versionId: work.currentVersionId,
+ workId: work.id,
+ });
+ return 'ok';
+ } catch (error) {
+ log(
+ '[%s] Failed to register file Work for %s (non-fatal): %O',
+ operationId,
+ entry.path,
+ error,
+ );
+ return 'failed';
+ }
+ },
+ );
+
+ // `mapWithConcurrency` never rejects (each task is self-guarded), but a stray
+ // rejection would surface as a settled 'rejected' — treat it as a failure too.
+ const failed = settled.filter(
+ (result) => result.status === 'rejected' || result.value === 'failed',
+ ).length;
+ return { attempted: entities.length, failed };
+};
diff --git a/apps/server/src/services/sandbox/__tests__/service.test.ts b/apps/server/src/services/sandbox/__tests__/service.test.ts
index aefdbb02cd2..c51d15742a3 100644
--- a/apps/server/src/services/sandbox/__tests__/service.test.ts
+++ b/apps/server/src/services/sandbox/__tests__/service.test.ts
@@ -79,6 +79,68 @@ describe('SandboxMiddlewareService', () => {
);
});
+ it('keys the object on storageName while keeping filename as the display name', async () => {
+ const { SandboxMiddlewareService: TestSandboxMiddlewareService } = await import('../service');
+ const exportFileToUploadUrl = vi.fn(async () => ({
+ result: { mime_type: 'text/csv' },
+ success: true,
+ }));
+ const provider = {
+ capabilities: {
+ backgroundCommands: true,
+ exportFile: true,
+ files: true,
+ languages: ['python'],
+ persistentSession: true,
+ shell: true,
+ skillScripts: true,
+ },
+ callTool: vi.fn(),
+ exportFileToUploadUrl,
+ kind: 'onlyboxes',
+ } satisfies SandboxProvider;
+
+ const fileService = {
+ createPreSignedUpload: vi.fn(async () => ({
+ headers: {},
+ url: 'https://uploads.example.com/put',
+ })),
+ createFileRecord: vi.fn(async () => ({ fileId: 'file-1', url: '/f/file-1' })),
+ getFileMetadata: vi.fn(async () => ({ contentLength: 42, contentType: 'text/csv' })),
+ } as unknown as FileService;
+
+ const service = new TestSandboxMiddlewareService(provider, {
+ fileService,
+ marketService: {} as MarketService,
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await service.exportAndUploadFile('/workspace/result.csv', 'result.csv', {
+ storageName: 'deadbeefdeadbeef-result.csv',
+ });
+
+ // The returned/display name is the clean basename, never the storage key.
+ expect(result.filename).toBe('result.csv');
+ // The storage key (both the presigned upload key and the file record url)
+ // uses storageName so the object is collision-proof.
+ expect(fileService.createPreSignedUpload).toHaveBeenCalledWith(
+ expect.stringMatching(
+ /^code-interpreter-exports\/\d{4}-\d{2}-\d{2}\/topic-1\/deadbeefdeadbeef-result\.csv$/,
+ ),
+ );
+ expect(fileService.createFileRecord).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: 'result.csv',
+ url: expect.stringMatching(/\/deadbeefdeadbeef-result\.csv$/),
+ }),
+ );
+ // The provider still receives the display filename (unchanged contract).
+ expect(exportFileToUploadUrl).toHaveBeenCalledWith(
+ expect.objectContaining({ filename: 'result.csv', path: '/workspace/result.csv' }),
+ );
+ });
+
it('normalizes provider export failures before storage metadata is read', async () => {
const provider = {
capabilities: {
diff --git a/apps/server/src/services/sandbox/service.ts b/apps/server/src/services/sandbox/service.ts
index 780ad26072f..d1dc408f8f4 100644
--- a/apps/server/src/services/sandbox/service.ts
+++ b/apps/server/src/services/sandbox/service.ts
@@ -102,7 +102,11 @@ export class SandboxMiddlewareService implements SandboxService {
}
}
- async exportAndUploadFile(path: string, filename: string): Promise<SandboxExportFileResult> {
+ async exportAndUploadFile(
+ path: string,
+ filename: string,
+ options?: { storageName?: string },
+ ): Promise<SandboxExportFileResult> {
const { fileService, topicId } = this.options;
if (!fileService) {
@@ -113,12 +117,25 @@ export class SandboxMiddlewareService implements SandboxService {
};
}
- log('Exporting file: %s from path: %s, topicId: %s', filename, path, topicId);
+ // The object's storage key uses `storageName` when provided so callers can
+ // guarantee a collision-proof, immutable object per (operation, path); the
+ // file record's display `name` always stays the user-facing `filename`, so a
+ // download never surfaces the mangled key. Defaults to `filename` for the
+ // common case where display name and key are the same.
+ const storageName = options?.storageName ?? filename;
+
+ log(
+ 'Exporting file: %s (key: %s) from path: %s, topicId: %s',
+ filename,
+ storageName,
+ path,
+ topicId,
+ );
try {
const now = Date.now();
const today = new Date(now).toISOString().split('T')[0];
- const key = `code-interpreter-exports/${today}/${topicId}/${filename}`;
+ const key = `code-interpreter-exports/${today}/${topicId}/${storageName}`;
const upload = await fileService.createPreSignedUpload(key);
const exported = await this.provider.exportFileToUploadUrl({
diff --git a/apps/server/src/services/sandbox/types.ts b/apps/server/src/services/sandbox/types.ts
index 0c6e95c0a7b..bc732bbd52e 100644
--- a/apps/server/src/services/sandbox/types.ts
+++ b/apps/server/src/services/sandbox/types.ts
@@ -47,7 +47,11 @@ export interface SandboxService extends ISandboxService {
}
export interface SandboxFileExporter {
- exportAndUploadFile: (path: string, filename: string) => Promise<SandboxExportFileResult>;
+ exportAndUploadFile: (
+ path: string,
+ filename: string,
+ options?: { storageName?: string },
+ ) => Promise<SandboxExportFileResult>;
}
export interface SandboxProviderFileExportRequest {
diff --git a/locales/ar/chat.json b/locales/ar/chat.json
index d4a7782f8e8..c26b87486d8 100644
--- a/locales/ar/chat.json
+++ b/locales/ar/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "تم النسخ بنجاح",
"duplicateSession.title": "نسخة {{title}}",
"duplicateTitle": "نسخة {{title}}",
+ "editedFiles.title_one": "تم تعديل {{count}} ملف",
+ "editedFiles.title_other": "تم تعديل {{count}} ملفات",
"emptyAgent": "لا يوجد وكلاء بعد. ابدأ بأول وكيل لك — وابنِ نظامك بمرور الوقت.",
"emptyAgentAction": "إنشاء وكيل",
"extendParams.disableContextCaching.desc": "قلل تكلفة إنشاء محادثة واحدة بنسبة تصل إلى 90٪ وزد السرعة حتى 4 أضعاف. <1>اعرف المزيد</1>",
diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.json
index 88652b21498..5481885141a 100644
--- a/locales/bg-BG/chat.json
+++ b/locales/bg-BG/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Копирането е успешно",
"duplicateSession.title": "{{title}} - Копие",
"duplicateTitle": "{{title}} - Копие",
+ "editedFiles.title_one": "Редактиран {{count}} файл",
+ "editedFiles.title_other": "Редактирани {{count}} файла",
"emptyAgent": "Все още няма Агенти. Започнете с първия си Агент — изградете системата си с времето.",
"emptyAgentAction": "Създай Агент",
"extendParams.disableContextCaching.desc": "Намалете до 90% от разходите за генериране на един разговор и постигнете до 4 пъти по-висока скорост. <1>Научете повече</1>",
diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.json
index 7067eb88ee9..c8afd6d9e64 100644
--- a/locales/de-DE/chat.json
+++ b/locales/de-DE/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Kopie erfolgreich",
"duplicateSession.title": "{{title}} – Kopie",
"duplicateTitle": "{{title}} – Kopie",
+ "editedFiles.title_one": "Bearbeitete {{count}} Datei",
+ "editedFiles.title_other": "Bearbeitete {{count}} Dateien",
"emptyAgent": "Noch keine Agenten. Beginnen Sie mit Ihrem ersten Agenten – bauen Sie Ihr System nach und nach auf.",
"emptyAgentAction": "Agent erstellen",
"extendParams.disableContextCaching.desc": "Reduzieren Sie die Kosten für die Generierung eines einzelnen Gesprächs um bis zu 90 % und erreichen Sie eine bis zu 4-fache Geschwindigkeit. <1>Mehr erfahren</1>",
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 3964b00d19d..90a4966062c 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Copy successful",
"duplicateSession.title": "{{title}} Copy",
"duplicateTitle": "{{title}} Copy",
+ "editedFiles.title_one": "Edited {{count}} file",
+ "editedFiles.title_other": "Edited {{count}} files",
"emptyAgent": "No Agents yet. Start with your first Agent—build your system over time.",
"emptyAgentAction": "Create Agent",
"extendParams.disableContextCaching.desc": "Reduce by up to 90% of the cost of generating a single conversation and bring a max of 4x speed. <1>Learn more</1>",
diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.json
index 866ed5e3915..18c2ec7ae4f 100644
--- a/locales/es-ES/chat.json
+++ b/locales/es-ES/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Copia realizada con éxito",
"duplicateSession.title": "Copia de {{title}}",
"duplicateTitle": "Copia de {{title}}",
+ "editedFiles.title_one": "Editado {{count}} archivo",
+ "editedFiles.title_other": "Editados {{count}} archivos",
"emptyAgent": "Aún no hay Agentes. Comienza con tu primer Agente—construye tu sistema con el tiempo.",
"emptyAgentAction": "Crear Agente",
"extendParams.disableContextCaching.desc": "Reduce hasta un 90% el costo de generar una sola conversación y alcanza una velocidad hasta 4 veces mayor. <1>Más información</1>",
diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.json
index 0197cd076db..1c186da35da 100644
--- a/locales/fa-IR/chat.json
+++ b/locales/fa-IR/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "کپی با موفقیت انجام شد",
"duplicateSession.title": "کپی {{title}}",
"duplicateTitle": "کپی {{title}}",
+ "editedFiles.title_one": "ویرایش شده {{count}} فایل",
+ "editedFiles.title_other": "ویرایش شده {{count}} فایل‌ها",
"emptyAgent": "هنوز عاملی وجود ندارد. با اولین عامل خود شروع کنید—سیستم خود را به مرور بسازید.",
"emptyAgentAction": "ایجاد عامل",
"extendParams.disableContextCaching.desc": "تا ۹۰٪ از هزینه تولید یک مکالمه را کاهش دهید و حداکثر تا ۴ برابر سرعت را افزایش دهید. <1>بیشتر بدانید</1>",
diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.json
index 16cbd125001..b164b5783a8 100644
--- a/locales/fr-FR/chat.json
+++ b/locales/fr-FR/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Copie réussie",
"duplicateSession.title": "Copie de {{title}}",
"duplicateTitle": "Copie de {{title}}",
+ "editedFiles.title_one": "Fichier modifié : {{count}}",
+ "editedFiles.title_other": "Fichiers modifiés : {{count}}",
"emptyAgent": "Aucun agent pour le moment. Commencez par créer votre premier agent — construisez votre système au fil du temps.",
"emptyAgentAction": "Créer un agent",
"extendParams.disableContextCaching.desc": "Réduisez jusqu'à 90 % le coût de génération d'une seule conversation et bénéficiez d'une vitesse jusqu'à 4 fois supérieure. <1>En savoir plus</1>",
diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.json
index 9cc2cae29a3..8c4bcc86318 100644
--- a/locales/it-IT/chat.json
+++ b/locales/it-IT/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Copia riuscita",
"duplicateSession.title": "Copia di {{title}}",
"duplicateTitle": "Copia di {{title}}",
+ "editedFiles.title_one": "Modificato {{count}} file",
+ "editedFiles.title_other": "Modificati {{count}} file",
"emptyAgent": "Nessun Agente ancora. Inizia con il tuo primo Agente—costruisci il tuo sistema nel tempo.",
"emptyAgentAction": "Crea Agente",
"extendParams.disableContextCaching.desc": "Riduci fino al 90% il costo di generazione di una singola conversazione e ottieni una velocità fino a 4 volte superiore. <1>Scopri di più</1>",
diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.json
index aadd2d41bce..ee8e624485a 100644
--- a/locales/ja-JP/chat.json
+++ b/locales/ja-JP/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "コピー成功",
"duplicateSession.title": "{{title}} のコピー",
"duplicateTitle": "{{title}} のコピー",
+ "editedFiles.title_one": "{{count}} ファイルを編集しました",
+ "editedFiles.title_other": "{{count}} ファイルを編集しました",
"emptyAgent": "まだアシスタントがいません。最初のアシスタントから始めて、アシスタントシステムを徐々に構築しましょう",
"emptyAgentAction": "アシスタントを作成",
"extendParams.disableContextCaching.desc": "1 回の会話生成コストを最大 90% 削減し、最大 4 倍の速度を実現します。<1>詳細はこちら</1>",
diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.json
index a2a87fff419..b535378c9b8 100644
--- a/locales/ko-KR/chat.json
+++ b/locales/ko-KR/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "복사 성공",
"duplicateSession.title": "{{title}} 복사본",
"duplicateTitle": "{{title}} 복사본",
+ "editedFiles.title_one": "{{count}}개의 파일을 수정했습니다",
+ "editedFiles.title_other": "{{count}}개의 파일들을 수정했습니다",
"emptyAgent": "아직 도우미가 없습니다. 첫 번째 도우미부터 시작해서 도우미 시스템을 점진적으로 구축해 보세요",
"emptyAgentAction": "도우미 만들기",
"extendParams.disableContextCaching.desc": "단일 대화를 생성하는 비용을 최대 90%까지 절감하고 최대 4배 빠른 속도를 제공합니다. <1>자세히 알아보기</1>",
diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.json
index c9505a4df6e..29ada3cda45 100644
--- a/locales/nl-NL/chat.json
+++ b/locales/nl-NL/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Kopiëren gelukt",
"duplicateSession.title": "{{title}} - Kopie",
"duplicateTitle": "{{title}} - Kopie",
+ "editedFiles.title_one": "Bewerkte {{count}} bestand",
+ "editedFiles.title_other": "Bewerkte {{count}} bestanden",
"emptyAgent": "Nog geen Agents. Begin met je eerste Agent—bouw je systeem stap voor stap op.",
"emptyAgentAction": "Agent aanmaken",
"extendParams.disableContextCaching.desc": "Verminder de kosten voor het genereren van een enkel gesprek met tot wel 90% en verhoog de snelheid tot maximaal 4x. <1>Meer informatie</1>",
diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.json
index 77a67e965c2..000439eca18 100644
--- a/locales/pl-PL/chat.json
+++ b/locales/pl-PL/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Skopiowano pomyślnie",
"duplicateSession.title": "Kopia {{title}}",
"duplicateTitle": "Kopia {{title}}",
+ "editedFiles.title_one": "Edytowano {{count}} plik",
+ "editedFiles.title_other": "Edytowano {{count}} pliki",
"emptyAgent": "Brak Agentów. Zacznij od stworzenia pierwszego Agenta — zbuduj swój system z czasem.",
"emptyAgentAction": "Utwórz Agenta",
"extendParams.disableContextCaching.desc": "Zmniejsz koszt generowania jednej rozmowy nawet o 90% i zwiększ prędkość maksymalnie 4-krotnie. <1>Dowiedz się więcej</1>",
diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.json
index c6f29866d2b..238d685711a 100644
--- a/locales/pt-BR/chat.json
+++ b/locales/pt-BR/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Cópia realizada com sucesso",
"duplicateSession.title": "Cópia de {{title}}",
"duplicateTitle": "Cópia de {{title}}",
+ "editedFiles.title_one": "Editado {{count}} arquivo",
+ "editedFiles.title_other": "Editados {{count}} arquivos",
"emptyAgent": "Nenhum Agente ainda. Comece com seu primeiro Agente — construa seu sistema ao longo do tempo.",
"emptyAgentAction": "Criar Agente",
"extendParams.disableContextCaching.desc": "Reduza em até 90% o custo de geração de uma única conversa e aumente a velocidade em até 4x. <1>Saiba mais</1>",
diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.json
index 1c5010eaed4..5ad5b42dab3 100644
--- a/locales/ru-RU/chat.json
+++ b/locales/ru-RU/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Копия успешно создана",
"duplicateSession.title": "Копия {{title}}",
"duplicateTitle": "Копия {{title}}",
+ "editedFiles.title_one": "Отредактирован {{count}} файл",
+ "editedFiles.title_other": "Отредактировано {{count}} файлов",
"emptyAgent": "Пока нет агентов. Начните с первого агента — со временем выстроите свою систему.",
"emptyAgentAction": "Создать агента",
"extendParams.disableContextCaching.desc": "Снизьте затраты на генерацию одного диалога до 90% и увеличьте скорость до 4 раз. <1>Узнать больше</1>",
diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.json
index 8dd7386717a..ba854989c29 100644
--- a/locales/tr-TR/chat.json
+++ b/locales/tr-TR/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Kopyalama başarılı",
"duplicateSession.title": "{{title}} Kopyası",
"duplicateTitle": "{{title}} Kopyası",
+ "editedFiles.title_one": "{{count}} dosya düzenlendi",
+ "editedFiles.title_other": "{{count}} dosya düzenlendi",
"emptyAgent": "Henüz Ajan yok. İlk Ajanınızı oluşturarak sisteminizi zamanla inşa edin.",
"emptyAgentAction": "Ajan Oluştur",
"extendParams.disableContextCaching.desc": "Tek bir konuşma oluşturma maliyetini %90'a kadar azaltın ve 4 kata kadar hız kazanın. <1>Daha fazla bilgi edinin</1>",
diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.json
index 9b50d52f36f..cb7f28cc27b 100644
--- a/locales/vi-VN/chat.json
+++ b/locales/vi-VN/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "Sao chép thành công",
"duplicateSession.title": "Bản sao {{title}}",
"duplicateTitle": "Bản sao {{title}}",
+ "editedFiles.title_one": "Đã chỉnh sửa {{count}} tệp",
+ "editedFiles.title_other": "Đã chỉnh sửa {{count}} tệp",
"emptyAgent": "Chưa có Tác nhân nào. Bắt đầu với Tác nhân đầu tiên của bạn—xây dựng hệ thống theo thời gian.",
"emptyAgentAction": "Tạo Tác nhân",
"extendParams.disableContextCaching.desc": "Giảm tới 90% chi phí tạo một cuộc hội thoại và tăng tốc độ lên đến 4 lần. <1>Tìm hiểu thêm</1>",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 41975bbd19a..d60afb8ec8e 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "复制成功",
"duplicateSession.title": "{{title}} 副本",
"duplicateTitle": "{{title}} 副本",
+ "editedFiles.title_one": "已编辑 {{count}} 个文件",
+ "editedFiles.title_other": "已编辑 {{count}} 个文件",
"emptyAgent": "还没有助理。从第一个助理开始,慢慢搭建你的助理体系",
"emptyAgentAction": "创建助理",
"extendParams.disableContextCaching.desc": "最多可减少90%的单次对话生成成本,并将速度提升至最多4倍。<1>了解更多</1>",
diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.json
index 2167a27a2c6..f40b3f565ee 100644
--- a/locales/zh-TW/chat.json
+++ b/locales/zh-TW/chat.json
@@ -209,6 +209,8 @@
"duplicateSession.success": "複製成功",
"duplicateSession.title": "{{title}} 副本",
"duplicateTitle": "{{title}} 副本",
+ "editedFiles.title_one": "已編輯 {{count}} 個檔案",
+ "editedFiles.title_other": "已編輯 {{count}} 個檔案",
"emptyAgent": "暫無助手",
"emptyAgentAction": "建立助手",
"extendParams.disableContextCaching.desc": "最多可減少 90% 的單次對話生成成本,並將速度提升至最多 4 倍。<1>了解更多</1>",
diff --git a/packages/builtin-tool-cloud-sandbox/src/types/service.ts b/packages/builtin-tool-cloud-sandbox/src/types/service.ts
index d68b24c0096..e45f1077aaa 100644
--- a/packages/builtin-tool-cloud-sandbox/src/types/service.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/types/service.ts
@@ -42,7 +42,17 @@ export interface ISandboxService {
/**
* Export a file from sandbox and upload to cloud storage
* @param path - The file path in the sandbox
- * @param filename - The name of the file to export
+ * @param filename - The user-facing name of the file (persisted as the file
+ * record's display name)
+ * @param options - Optional overrides. `storageName` decouples the uploaded
+ * object's storage key from the display `filename`, so callers that need a
+ * collision-proof object key (e.g. file-Work registration) can supply a
+ * unique name without leaking it into the download filename. Backward
+ * compatible: omitting it keeps `filename` as both display name and key.
*/
- exportAndUploadFile: (path: string, filename: string) => Promise<SandboxExportFileResult>;
+ exportAndUploadFile: (
+ path: string,
+ filename: string,
+ options?: { storageName?: string },
+ ) => Promise<SandboxExportFileResult>;
}
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index c7712d94c25..49d617ded1c 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -15,7 +15,8 @@
"./streamings": "./src/streamings.ts",
"./identifiers": "./src/identifiers.ts",
"./dynamicInterventionAudits": "./src/dynamicInterventionAudits.ts",
- "./workRegistration": "./src/workRegistration.ts"
+ "./workRegistration": "./src/workRegistration.ts",
+ "./fileEditScan": "./src/fileEditScan/index.ts"
},
"main": "./src/index.ts",
"dependencies": {
diff --git a/packages/builtin-tools/src/codex/FileChangeRender.tsx b/packages/builtin-tools/src/codex/FileChangeRender.tsx
index 9de6b8ff703..02d2ab24243 100644
--- a/packages/builtin-tools/src/codex/FileChangeRender.tsx
+++ b/packages/builtin-tools/src/codex/FileChangeRender.tsx
@@ -1,15 +1,20 @@
'use client';
-import { FilePathDisplay } from '@lobechat/shared-tool-ui/components';
+import {
+ FilePathDisplay,
+ getFileLanguage,
+ getFileName,
+ KindDot,
+ LineStats,
+} from '@lobechat/shared-tool-ui/components';
import type { BuiltinRenderProps } from '@lobechat/types';
import { Flexbox, PatchDiff, Text } from '@lobehub/ui';
-import { createStaticStyles, cx } from 'antd-style';
+import { createStaticStyles } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import {
type CodexFileChangeArgs,
- type CodexFileChangeKind,
type CodexFileChangeState,
getFileChangeData,
getFileChangeKind,
@@ -22,38 +27,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
font-size: 13px;
color: ${cssVar.colorTextTertiary};
`,
- kindAdded: css`
- background: ${cssVar.colorSuccess};
- `,
- kindDeleted: css`
- background: ${cssVar.colorError};
- `,
- kindDot: css`
- flex-shrink: 0;
- width: 8px;
- height: 8px;
- border-radius: 999px;
- `,
- kindModified: css`
- background: ${cssVar.colorInfo};
- `,
- kindRenamed: css`
- background: ${cssVar.colorWarning};
- `,
- lineAdded: css`
- color: ${cssVar.colorSuccess};
- `,
- lineDeleted: css`
- color: ${cssVar.colorError};
- `,
- lineStats: css`
- display: inline-flex;
- flex-shrink: 0;
- gap: 6px;
- align-items: center;
-
- font-size: 12px;
- `,
list: css`
gap: 2px;
min-width: 0;
@@ -93,50 +66,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-const getFileName = (filePath: string): string => {
- if (!filePath) return '';
- const normalized = filePath.replaceAll('\\', '/');
- return normalized.split('/').findLast(Boolean) || filePath;
-};
-
-const getFileLanguage = (filePath: string): string | undefined => {
- const fileName = getFileName(filePath);
- const index = fileName.lastIndexOf('.');
- if (index < 0 || index === fileName.length - 1) return;
- return fileName.slice(index + 1).toLowerCase();
-};
-
-const getKindClassName = (kind: CodexFileChangeKind) => {
- switch (kind) {
- case 'added': {
- return styles.kindAdded;
- }
- case 'deleted': {
- return styles.kindDeleted;
- }
- case 'renamed': {
- return styles.kindRenamed;
- }
- default: {
- return styles.kindModified;
- }
- }
-};
-
-const LineStats = memo<{ className?: string; linesAdded?: number; linesDeleted?: number }>(
- ({ className, linesAdded = 0, linesDeleted = 0 }) => {
- if (linesAdded === 0 && linesDeleted === 0) return null;
-
- return (
- <span className={cx(styles.lineStats, className)}>
- <span className={styles.lineAdded}>+{linesAdded}</span>
- <span className={styles.lineDeleted}>-{linesDeleted}</span>
- </span>
- );
- },
-);
-LineStats.displayName = 'CodexFileChangeLineStats';
-
const FileChangeRender = memo<BuiltinRenderProps<CodexFileChangeArgs, CodexFileChangeState>>(
({ args, pluginState }) => {
const { t } = useTranslation('plugin');
@@ -160,7 +89,7 @@ const FileChangeRender = memo<BuiltinRenderProps<CodexFileChangeArgs, CodexFileC
return (
<Flexbox key={`${path}-${index}`}>
<Flexbox horizontal className={styles.row}>
- <span className={cx(styles.kindDot, getKindClassName(kind))} />
+ <KindDot kind={kind} />
<div className={styles.rowMain}>
<div className={styles.path}>
{path ? (
diff --git a/packages/builtin-tools/src/fileEditScan/index.test.ts b/packages/builtin-tools/src/fileEditScan/index.test.ts
new file mode 100644
index 00000000000..07ff854ef03
--- /dev/null
+++ b/packages/builtin-tools/src/fileEditScan/index.test.ts
@@ -0,0 +1,961 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ classifyEditedFile,
+ type FileEditToolCallRecord,
+ getBasename,
+ getFileExtension,
+ normalizeScanPath,
+ scanOperationFileEdits,
+} from './index';
+
+const sandboxWrite = (
+ toolCallId: string,
+ path: string,
+ extra: Partial<{ args: unknown; success: boolean }> = {},
+): FileEditToolCallRecord => ({
+ apiName: 'writeFile',
+ arguments: extra.args === undefined ? JSON.stringify({ path }) : (extra.args as string),
+ identifier: 'lobe-cloud-sandbox',
+ state: { path, success: extra.success ?? true },
+ toolCallId,
+});
+
+const sandboxEdit = (
+ toolCallId: string,
+ path: string,
+ deltas: Partial<{ diffText: string; linesAdded: number; linesDeleted: number }> = {},
+): FileEditToolCallRecord => ({
+ apiName: 'editFile',
+ arguments: JSON.stringify({ path, replace: 'b', search: 'a' }),
+ identifier: 'lobe-cloud-sandbox',
+ state: { path, replacements: 1, ...deltas },
+ toolCallId,
+});
+
+const sandboxMove = (
+ toolCallId: string,
+ results: Array<{ destination?: string; source?: string; success: boolean }>,
+): FileEditToolCallRecord => ({
+ apiName: 'moveFiles',
+ arguments: JSON.stringify({ operations: results }),
+ identifier: 'lobe-cloud-sandbox',
+ state: {
+ results,
+ successCount: results.filter((r) => r.success).length,
+ totalCount: results.length,
+ },
+ toolCallId,
+});
+
+const codexFileChange = (
+ toolCallId: string,
+ changes: Array<{
+ diffText?: string;
+ kind?: string;
+ linesAdded?: number;
+ linesDeleted?: number;
+ path?: string;
+ }>,
+): FileEditToolCallRecord => ({
+ apiName: 'file_change',
+ identifier: 'codex',
+ state: { changes, linesAdded: 0, linesDeleted: 0 },
+ toolCallId,
+});
+
+const claudeCode = (
+ toolCallId: string,
+ apiName: 'Edit' | 'MultiEdit' | 'Write',
+ filePath: string,
+): FileEditToolCallRecord => ({
+ apiName,
+ arguments: JSON.stringify({ file_path: filePath }),
+ identifier: 'claude-code',
+ toolCallId,
+});
+
+/** lobe-local-system structured file call (writeFile / editFile / moveFiles). */
+const localFileCall = (
+ toolCallId: string,
+ apiName: 'writeFile' | 'editFile' | 'moveFiles',
+ state: Record<string, unknown>,
+ args: Record<string, unknown> = {},
+): FileEditToolCallRecord => ({
+ apiName,
+ arguments: JSON.stringify(args),
+ identifier: 'lobe-local-system',
+ state,
+ toolCallId,
+});
+
+/** lobe-local-system runCommand shell call. */
+const localCommand = (
+ toolCallId: string,
+ command: string,
+ extra: Partial<{ exitCode: number; success: boolean }> = {},
+): FileEditToolCallRecord => ({
+ apiName: 'runCommand',
+ arguments: JSON.stringify({ command }),
+ identifier: 'lobe-local-system',
+ state: { isBackground: false, success: extra.success ?? true, ...extra },
+ toolCallId,
+});
+
+/** claude-code Bash shell call. */
+const bashCommand = (toolCallId: string, command: string): FileEditToolCallRecord => ({
+ apiName: 'Bash',
+ arguments: JSON.stringify({ command }),
+ identifier: 'claude-code',
+ toolCallId,
+});
+
+/** codex command_execution shell call. */
+const codexCommand = (
+ toolCallId: string,
+ command: string,
+ extra: Partial<{ exitCode: number; success: boolean }> = {},
+): FileEditToolCallRecord => ({
+ apiName: 'command_execution',
+ arguments: JSON.stringify({ command }),
+ identifier: 'codex',
+ state: { isBackground: false, success: extra.success ?? true, ...extra },
+ toolCallId,
+});
+
+/** lobe-skills runCommand / execScript shell call (script body shares the `command` field). */
+const skillsCommand = (
+ toolCallId: string,
+ command: string,
+ extra: Partial<{
+ apiName: 'runCommand' | 'execScript';
+ executionEnv: 'device' | 'sandbox';
+ exitCode: number;
+ success: boolean;
+ }> = {},
+): FileEditToolCallRecord => ({
+ apiName: extra.apiName ?? 'execScript',
+ arguments: JSON.stringify({ command, description: 'run a script' }),
+ identifier: 'lobe-skills',
+ state: {
+ ...(extra.executionEnv === undefined ? {} : { executionEnv: extra.executionEnv }),
+ exitCode: extra.exitCode ?? 0,
+ success: extra.success ?? true,
+ },
+ toolCallId,
+});
+
+describe('scanOperationFileEdits', () => {
+ describe('per-source extraction', () => {
+ it('extracts a sandbox writeFile as an added file on first appearance', () => {
+ const result = scanOperationFileEdits([sandboxWrite('t1', '/work/a.txt')]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'added',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: '/work/a.txt',
+ sourceToolCallIds: ['t1'],
+ },
+ ]);
+ });
+
+ it('extracts a sandbox editFile with diff + line deltas as modified', () => {
+ const result = scanOperationFileEdits([
+ sandboxEdit('t1', '/work/a.txt', { diffText: '@@ diff', linesAdded: 3, linesDeleted: 1 }),
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: ['@@ diff'],
+ kind: 'modified',
+ linesAdded: 3,
+ linesDeleted: 1,
+ path: '/work/a.txt',
+ sourceToolCallIds: ['t1'],
+ },
+ ]);
+ });
+
+ it('extracts sandbox moveFiles successful results as renames', () => {
+ const result = scanOperationFileEdits([
+ sandboxMove('t1', [
+ { destination: '/work/b.txt', source: '/work/a.txt', success: true },
+ { destination: '/work/fail.txt', source: '/work/x.txt', success: false },
+ ]),
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'renamed',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: '/work/b.txt',
+ previousPath: '/work/a.txt',
+ sourceToolCallIds: ['t1'],
+ },
+ ]);
+ });
+
+ it('extracts codex file_change entries with kind mapping', () => {
+ const result = scanOperationFileEdits([
+ codexFileChange('t1', [
+ { kind: 'add', linesAdded: 5, linesDeleted: 0, path: '/a.txt' },
+ { diffText: 'd', kind: 'update', linesAdded: 2, linesDeleted: 2, path: '/b.txt' },
+ { kind: 'rename', path: '/c.txt' },
+ ]),
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'added',
+ linesAdded: 5,
+ linesDeleted: 0,
+ path: '/a.txt',
+ sourceToolCallIds: ['t1'],
+ },
+ {
+ diffTexts: ['d'],
+ kind: 'modified',
+ linesAdded: 2,
+ linesDeleted: 2,
+ path: '/b.txt',
+ sourceToolCallIds: ['t1'],
+ },
+ // Codex renames carry no source path, so previousPath is absent.
+ {
+ diffTexts: [],
+ kind: 'renamed',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: '/c.txt',
+ sourceToolCallIds: ['t1'],
+ },
+ ]);
+ });
+
+ // Regression: a device run writes its build script via local-system
+ // writeFile (`node build.js` then produces the artifact) — before
+ // local-system joined the structured sources, that script never surfaced
+ // in the edited-files card, unlike the identical sandbox flow.
+ it('extracts local-system writeFile/editFile/moveFiles like the sandbox structured edits', () => {
+ const result = scanOperationFileEdits([
+ localFileCall(
+ 't1',
+ 'writeFile',
+ { path: '/Users/tj/Desktop/demo-ppt/build.js', success: true },
+ {
+ content: 'const pptxgen = require("pptxgenjs");',
+ path: '/Users/tj/Desktop/demo-ppt/build.js',
+ },
+ ),
+ localFileCall(
+ 't2',
+ 'editFile',
+ { diffText: '@@ diff', linesAdded: 2, linesDeleted: 1, path: '/a.md', replacements: 1 },
+ { path: '/a.md', replace: 'y', search: 'x' },
+ ),
+ localFileCall('t3', 'moveFiles', {
+ results: [{ destination: '/b.md', source: '/a.md', success: true }],
+ successCount: 1,
+ totalCount: 1,
+ }),
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'added',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: '/Users/tj/Desktop/demo-ppt/build.js',
+ sourceToolCallIds: ['t1'],
+ },
+ {
+ diffTexts: ['@@ diff'],
+ kind: 'renamed',
+ linesAdded: 2,
+ linesDeleted: 1,
+ path: '/b.md',
+ previousPath: '/a.md',
+ sourceToolCallIds: ['t2', 't3'],
+ },
+ ]);
+ });
+
+ it('skips a failed local-system structured write', () => {
+ expect(
+ scanOperationFileEdits([
+ localFileCall('t1', 'writeFile', { path: '/a.md', success: false }, { path: '/a.md' }),
+ ]),
+ ).toEqual([]);
+ });
+
+ it('extracts claude code Edit/Write/MultiEdit from file_path with 0 deltas', () => {
+ const result = scanOperationFileEdits([
+ claudeCode('t1', 'Write', '/a.txt'),
+ claudeCode('t2', 'Edit', '/b.txt'),
+ claudeCode('t3', 'MultiEdit', '/c.txt'),
+ ]);
+ expect(result.map((r) => [r.path, r.kind])).toEqual([
+ ['/a.txt', 'added'],
+ ['/b.txt', 'modified'],
+ ['/c.txt', 'modified'],
+ ]);
+ expect(result.every((r) => r.diffTexts.length === 0)).toBe(true);
+ });
+ });
+
+ describe('terminal-state folding', () => {
+ it('folds write + edit + edit on one file (kind added, deltas summed)', () => {
+ const result = scanOperationFileEdits([
+ sandboxWrite('t1', '/a.txt'),
+ sandboxEdit('t2', '/a.txt', { diffText: 'd1', linesAdded: 2, linesDeleted: 0 }),
+ sandboxEdit('t3', '/a.txt', { diffText: 'd2', linesAdded: 1, linesDeleted: 4 }),
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: ['d1', 'd2'],
+ kind: 'added',
+ linesAdded: 3,
+ linesDeleted: 4,
+ path: '/a.txt',
+ sourceToolCallIds: ['t1', 't2', 't3'],
+ },
+ ]);
+ });
+
+ it('keeps modified when the file was only edited (not created) this operation', () => {
+ const result = scanOperationFileEdits([
+ sandboxEdit('t1', '/a.txt', { linesAdded: 1, linesDeleted: 0 }),
+ sandboxEdit('t2', '/a.txt', { linesAdded: 1, linesDeleted: 0 }),
+ ]);
+ expect(result[0].kind).toBe('modified');
+ expect(result[0].sourceToolCallIds).toEqual(['t1', 't2']);
+ });
+
+ it('drops an added-then-deleted file (net zero within the operation)', () => {
+ const result = scanOperationFileEdits([
+ sandboxWrite('t1', '/tmp.txt'),
+ codexFileChange('t2', [{ kind: 'delete', path: '/tmp.txt' }]),
+ ]);
+ expect(result).toEqual([]);
+ });
+
+ it('marks a pre-existing file as deleted (modified-then-deleted)', () => {
+ const result = scanOperationFileEdits([
+ sandboxEdit('t1', '/a.txt', { linesAdded: 1 }),
+ codexFileChange('t2', [{ kind: 'delete', path: '/a.txt' }]),
+ ]);
+ expect(result[0].kind).toBe('deleted');
+ expect(result[0].sourceToolCallIds).toEqual(['t1', 't2']);
+ });
+
+ it('follows a rename chain and preserves the earliest source as previousPath', () => {
+ const result = scanOperationFileEdits([
+ sandboxEdit('t1', '/a.txt', { linesAdded: 2 }),
+ sandboxMove('t2', [{ destination: '/b.txt', source: '/a.txt', success: true }]),
+ sandboxMove('t3', [{ destination: '/c.txt', source: '/b.txt', success: true }]),
+ sandboxEdit('t4', '/c.txt', { linesAdded: 1 }),
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'renamed',
+ linesAdded: 3,
+ linesDeleted: 0,
+ path: '/c.txt',
+ previousPath: '/a.txt',
+ sourceToolCallIds: ['t1', 't2', 't3', 't4'],
+ },
+ ]);
+ });
+
+ it('folds a pre-existing file deleted then re-created into modified', () => {
+ const result = scanOperationFileEdits([
+ // No prior `added` for this path → the delete marks a pre-existing file.
+ codexFileChange('t1', [{ kind: 'delete', path: '/a.txt' }]),
+ sandboxWrite('t2', '/a.txt'),
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'modified',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: '/a.txt',
+ sourceToolCallIds: ['t1', 't2'],
+ },
+ ]);
+ });
+
+ it('keeps added→deleted→added as added (the net-new path is unaffected)', () => {
+ const result = scanOperationFileEdits([
+ sandboxWrite('t1', '/a.txt'),
+ codexFileChange('t2', [{ kind: 'delete', path: '/a.txt' }]),
+ sandboxWrite('t3', '/a.txt'),
+ ]);
+ // The added→deleted pair is dropped wholesale, so the re-add is a fresh
+ // net-new entry — only t3 survives as its source.
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'added',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: '/a.txt',
+ sourceToolCallIds: ['t3'],
+ },
+ ]);
+ });
+
+ it('treats a created-then-renamed file as net-new at its destination (no previousPath)', () => {
+ const result = scanOperationFileEdits([
+ sandboxWrite('t1', '/a.txt'),
+ sandboxMove('t2', [{ destination: '/b.txt', source: '/a.txt', success: true }]),
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'added',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: '/b.txt',
+ sourceToolCallIds: ['t1', 't2'],
+ },
+ ]);
+ });
+ });
+
+ describe('skipping and robustness', () => {
+ it('skips a failed call (state.success === false)', () => {
+ const result = scanOperationFileEdits([sandboxWrite('t1', '/a.txt', { success: false })]);
+ expect(result).toEqual([]);
+ });
+
+ it('skips a call whose state carries an error', () => {
+ const result = scanOperationFileEdits([
+ {
+ apiName: 'editFile',
+ identifier: 'lobe-cloud-sandbox',
+ state: { error: 'boom', path: '/a.txt' },
+ toolCallId: 't1',
+ },
+ ]);
+ expect(result).toEqual([]);
+ });
+
+ it('skips a record carrying a plugin-level error even when its state looks fine', () => {
+ const result = scanOperationFileEdits([
+ {
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ path: '/a.txt' }),
+ error: 'plugin exploded',
+ identifier: 'lobe-cloud-sandbox',
+ state: { path: '/a.txt', success: true },
+ toolCallId: 't1',
+ },
+ ]);
+ expect(result).toEqual([]);
+ });
+
+ it('ignores third-party plugins that merely reuse an editing apiName', () => {
+ const result = scanOperationFileEdits([
+ // apiName `file_change` but NOT the codex identifier.
+ {
+ apiName: 'file_change',
+ identifier: 'some-third-party',
+ state: { changes: [{ kind: 'add', path: '/evil.txt' }] },
+ toolCallId: 't1',
+ },
+ // apiName `Edit` but NOT the claude-code identifier.
+ {
+ apiName: 'Edit',
+ arguments: JSON.stringify({ file_path: '/evil2.txt' }),
+ identifier: 'some-third-party',
+ toolCallId: 't2',
+ },
+ ]);
+ expect(result).toEqual([]);
+ });
+
+ it('ignores unknown apiNames (runCommand / Bash / command_execution)', () => {
+ const result = scanOperationFileEdits([
+ {
+ apiName: 'runCommand',
+ identifier: 'lobe-cloud-sandbox',
+ state: { success: true },
+ toolCallId: 't1',
+ },
+ {
+ apiName: 'Bash',
+ identifier: 'claude-code',
+ arguments: JSON.stringify({ command: 'sed -i s/a/b/ f' }),
+ toolCallId: 't2',
+ },
+ {
+ apiName: 'command_execution',
+ identifier: 'codex',
+ state: { success: true },
+ toolCallId: 't3',
+ },
+ ]);
+ expect(result).toEqual([]);
+ });
+
+ it('does not throw on malformed arguments/state and returns the parseable part', () => {
+ const result = scanOperationFileEdits([
+ // malformed JSON arguments, but state.path is readable
+ {
+ apiName: 'writeFile',
+ arguments: '{not json',
+ identifier: 'lobe-cloud-sandbox',
+ state: { path: '/a.txt', success: true },
+ toolCallId: 't1',
+ },
+ // claude code with malformed arguments and no state → skipped, no throw
+ { apiName: 'Edit', arguments: 'nope', identifier: 'claude-code', toolCallId: 't2' },
+ // codex with non-array changes → skipped, no throw
+ {
+ apiName: 'file_change',
+ identifier: 'codex',
+ state: { changes: 'oops' },
+ toolCallId: 't3',
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'added',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: '/a.txt',
+ sourceToolCallIds: ['t1'],
+ },
+ ]);
+ });
+
+ it('normalizes surrounding whitespace but keeps case and does not merge distinct paths', () => {
+ const result = scanOperationFileEdits([
+ sandboxWrite('t1', ' /Work/A.txt '),
+ sandboxEdit('t2', '/Work/A.txt', { linesAdded: 1 }),
+ sandboxWrite('t3', '/work/a.txt'),
+ ]);
+ expect(result.map((r) => r.path)).toEqual(['/Work/A.txt', '/work/a.txt']);
+ expect(result[0].sourceToolCallIds).toEqual(['t1', 't2']);
+ });
+
+ it('merges lexically-equivalent paths (`.` segments / duplicate slashes) into one entry', () => {
+ // Regression: keying by the raw path string treated `/workspace/report.pdf`
+ // and `/workspace/./report.pdf` as two files → duplicate cards / uploads /
+ // Works. Normalizing at the extraction boundary folds them into one.
+ const result = scanOperationFileEdits([
+ sandboxWrite('t1', '/workspace/report.pdf'),
+ sandboxEdit('t2', '/workspace/./report.pdf', { linesAdded: 2 }),
+ sandboxEdit('t3', '/workspace//report.pdf', { linesAdded: 3 }),
+ ]);
+ expect(result.map((r) => r.path)).toEqual(['/workspace/report.pdf']);
+ expect(result[0].sourceToolCallIds).toEqual(['t1', 't2', 't3']);
+ expect(result[0].linesAdded).toBe(5);
+ });
+
+ it('merges a relative `./x` with a bare `x` (leading `.` collapsed, path stays relative)', () => {
+ const result = scanOperationFileEdits([
+ sandboxWrite('t1', './deck.pptx'),
+ sandboxEdit('t2', 'deck.pptx', { linesAdded: 1 }),
+ ]);
+ expect(result.map((r) => r.path)).toEqual(['deck.pptx']);
+ expect(result[0].sourceToolCallIds).toEqual(['t1', 't2']);
+ });
+ });
+
+ describe('hetero-shell command scanning', () => {
+ it('detects `marp -o deck.pptx` via claude-code Bash as one modified entry', () => {
+ const result = scanOperationFileEdits([bashCommand('t1', 'marp slides.md -o deck.pptx')]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'modified',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: 'deck.pptx',
+ sourceToolCallIds: ['t1'],
+ },
+ ]);
+ });
+
+ it('detects an inline heredoc python `.save()` via lobe-local-system runCommand', () => {
+ const command = [
+ "python3 - <<'EOF'",
+ 'from docx import Document',
+ 'doc = Document()',
+ "doc.save('/work/report.docx')",
+ 'EOF',
+ ].join('\n');
+ const result = scanOperationFileEdits([localCommand('t1', command)]);
+ expect(result.map((r) => [r.path, r.kind])).toEqual([['/work/report.docx', 'modified']]);
+ });
+
+ it('detects pptxgenjs `writeFile({ fileName })` via codex command_execution (zsh-wrapped)', () => {
+ const command =
+ 'zsh -c "node -e \'const p=require(\\"pptxgenjs\\"); const d=new p(); d.writeFile({ fileName: \\"deck.pptx\\" })\'"';
+ const result = scanOperationFileEdits([codexCommand('t1', command)]);
+ expect(result.map((r) => r.path)).toEqual(['deck.pptx']);
+ });
+
+ it('detects other inline write-call literals (to_excel / to_csv / write_pdf / reportlab)', () => {
+ expect(
+ scanOperationFileEdits([bashCommand('t1', 'python -c "df.to_excel(\'out.xlsx\')"')]).map(
+ (r) => r.path,
+ ),
+ ).toEqual(['out.xlsx']);
+ expect(
+ scanOperationFileEdits([bashCommand('t2', 'python -c "df.to_csv(\'data.csv\')"')]).map(
+ (r) => r.path,
+ ),
+ ).toEqual(['data.csv']);
+ expect(
+ scanOperationFileEdits([bashCommand('t3', 'python -c "html.write_pdf(\'r.pdf\')"')]).map(
+ (r) => r.path,
+ ),
+ ).toEqual(['r.pdf']);
+ expect(
+ scanOperationFileEdits([
+ bashCommand('t4', 'python -c "c = Canvas(\'canvas.pdf\'); c.save()"'),
+ ]).map((r) => r.path),
+ ).toEqual(['canvas.pdf']);
+ expect(
+ scanOperationFileEdits([
+ bashCommand('t5', 'python -c "doc = SimpleDocTemplate(\'tpl.pdf\')"'),
+ ]).map((r) => r.path),
+ ).toEqual(['tpl.pdf']);
+ });
+
+ it('derives soffice `--convert-to` output (bare basename, filter suffix stripped)', () => {
+ const result = scanOperationFileEdits([
+ bashCommand(
+ 't1',
+ 'soffice --headless --convert-to pdf:writer_pdf_Export /work/report.docx',
+ ),
+ ]);
+ expect(result.map((r) => r.path)).toEqual(['report.pdf']);
+ });
+
+ it('derives soffice `--convert-to` output joined under `--outdir`', () => {
+ const result = scanOperationFileEdits([
+ localCommand('t1', 'libreoffice --convert-to pdf --outdir /out /work/report.docx'),
+ ]);
+ expect(result.map((r) => r.path)).toEqual(['/out/report.pdf']);
+ });
+
+ // Regression: without the control-operator stop, `&&` / `echo` / `done`
+ // would be treated as soffice inputs and derive bogus `&&.pdf` /
+ // `echo.pdf` / `done.pdf` entity entries.
+ it('stops soffice input collection at shell control operators', () => {
+ const result = scanOperationFileEdits([
+ bashCommand('t1', 'soffice --headless --convert-to pdf /work/report.docx && echo done'),
+ ]);
+ expect(result.map((r) => r.path)).toEqual(['report.pdf']);
+ });
+
+ // Regression: without the redirect skip, `2>/dev/null` / `> convert.log` /
+ // `2>&1` would be treated as soffice inputs and derive bogus `null.pdf` /
+ // `>.pdf` / `convert.pdf` / `2>&1.pdf` entity entries.
+ it('skips redirect tokens when collecting soffice inputs', () => {
+ expect(
+ scanOperationFileEdits([
+ bashCommand('t1', 'soffice --headless --convert-to pdf report.docx 2>/dev/null'),
+ ]).map((r) => r.path),
+ ).toEqual(['report.pdf']);
+ expect(
+ scanOperationFileEdits([
+ localCommand('t2', 'soffice --convert-to pdf /work/report.docx > convert.log 2>&1'),
+ ]).map((r) => r.path),
+ ).toEqual(['report.pdf']);
+ });
+
+ it('detects a `>` redirect to an entity path', () => {
+ const result = scanOperationFileEdits([bashCommand('t1', 'generate > data.csv')]);
+ expect(result.map((r) => r.path)).toEqual(['data.csv']);
+ });
+
+ it('ignores fd redirects (`2>&1`, `2> err.log`) and non-entity redirects (`> notes.md`)', () => {
+ expect(scanOperationFileEdits([bashCommand('t1', 'run 2>&1')])).toEqual([]);
+ expect(scanOperationFileEdits([bashCommand('t2', 'run 2> err.log')])).toEqual([]);
+ expect(scanOperationFileEdits([bashCommand('t3', 'echo hi > notes.md')])).toEqual([]);
+ });
+
+ it('produces nothing for read-only commands (pdftotext / load_workbook / ls glob)', () => {
+ expect(scanOperationFileEdits([bashCommand('t1', 'pdftotext report.pdf out.txt')])).toEqual(
+ [],
+ );
+ expect(
+ scanOperationFileEdits([bashCommand('t2', 'python -c "load_workbook(\'data.xlsx\')"')]),
+ ).toEqual([]);
+ expect(scanOperationFileEdits([bashCommand('t3', 'ls *.pptx')])).toEqual([]);
+ });
+
+ it('does not treat a `curl -o report.pdf` download as an edit', () => {
+ const result = scanOperationFileEdits([
+ bashCommand('t1', 'curl -o report.pdf https://example.com/r.pdf'),
+ ]);
+ expect(result).toEqual([]);
+ });
+
+ // Regression: grep's `-o` means only-matching — its operand is a search
+ // PATTERN, not an output file. Same for ps/tar/unzip `-o` meanings.
+ it('does not treat a read-only CLI `-o` operand as an output file', () => {
+ expect(scanOperationFileEdits([bashCommand('t1', "grep -o 'report.pdf' notes.txt")])).toEqual(
+ [],
+ );
+ expect(scanOperationFileEdits([bashCommand('t2', 'rg -o "deck.pptx" log.txt')])).toEqual([]);
+ });
+
+ it('still detects `sort -o` (its `-o` IS an output file)', () => {
+ const result = scanOperationFileEdits([bashCommand('t1', 'sort -o data.csv raw.txt')]);
+ expect(result.map((r) => r.path)).toEqual(['data.csv']);
+ });
+
+ it('does not treat `cp` / `mv` destinations as edits', () => {
+ expect(scanOperationFileEdits([bashCommand('t1', 'cp a.docx b.docx')])).toEqual([]);
+ expect(scanOperationFileEdits([bashCommand('t2', 'mv a.pptx b.pptx')])).toEqual([]);
+ });
+
+ it('ignores the same command run via lobe-cloud-sandbox runCommand (identifier gate)', () => {
+ const result = scanOperationFileEdits([
+ {
+ apiName: 'runCommand',
+ arguments: JSON.stringify({ command: 'marp slides.md -o deck.pptx' }),
+ identifier: 'lobe-cloud-sandbox',
+ state: { isBackground: false, success: true },
+ toolCallId: 't1',
+ },
+ ]);
+ expect(result).toEqual([]);
+ });
+
+ it('skips a shell call that carries a plugin-level error', () => {
+ const result = scanOperationFileEdits([
+ {
+ ...bashCommand('t1', 'marp slides.md -o deck.pptx'),
+ error: 'command failed',
+ },
+ ]);
+ expect(result).toEqual([]);
+ });
+
+ it('skips a shell call whose state reports a non-zero exit code', () => {
+ // `success` left true so the skip is driven by the exitCode guard alone.
+ const result = scanOperationFileEdits([
+ localCommand('t1', 'marp slides.md -o deck.pptx', { exitCode: 2 }),
+ ]);
+ expect(result).toEqual([]);
+ });
+
+ it('folds a path detected twice within one command into a single entry', () => {
+ const result = scanOperationFileEdits([
+ bashCommand('t1', "python -c \"wb.save('/work/a.xlsx'); wb.save('/work/a.xlsx')\""),
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'modified',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: '/work/a.xlsx',
+ sourceToolCallIds: ['t1'],
+ },
+ ]);
+ });
+
+ it('folds a hetero-shell detection with a later sandbox writeFile on the same path', () => {
+ const result = scanOperationFileEdits([
+ bashCommand('t1', 'python -c "doc.save(\'/work/report.docx\')"'),
+ sandboxWrite('t2', '/work/report.docx'),
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ // shell modify then sandbox write on a pre-existing path settles to modified.
+ kind: 'modified',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: '/work/report.docx',
+ sourceToolCallIds: ['t1', 't2'],
+ },
+ ]);
+ });
+
+ it('detects a DEVICE-routed lobe-skills execScript inline `.save()` as one modified entry', () => {
+ const command = [
+ "python3 - <<'EOF'",
+ 'from pptx import Presentation',
+ 'prs = Presentation()',
+ "prs.save('/work/deck.pptx')",
+ 'EOF',
+ ].join('\n');
+ const result = scanOperationFileEdits([
+ skillsCommand('t1', command, { executionEnv: 'device' }),
+ ]);
+ expect(result).toEqual([
+ {
+ diffTexts: [],
+ kind: 'modified',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path: '/work/deck.pptx',
+ sourceToolCallIds: ['t1'],
+ },
+ ]);
+ });
+
+ it('detects a DEVICE-routed lobe-skills runCommand output flag too', () => {
+ const result = scanOperationFileEdits([
+ skillsCommand('t1', 'marp slides.md -o deck.pptx', {
+ apiName: 'runCommand',
+ executionEnv: 'device',
+ }),
+ ]);
+ expect(result.map((r) => r.path)).toEqual(['deck.pptx']);
+ });
+
+ it('ignores SANDBOX-routed and env-less lobe-skills shell calls (executionEnv gate)', () => {
+ const command = 'python -c "doc.save(\'/work/report.docx\')"';
+ // Sandbox delivery rides exportFile registration — never the command scan.
+ expect(
+ scanOperationFileEdits([skillsCommand('t1', command, { executionEnv: 'sandbox' })]),
+ ).toEqual([]);
+ // Legacy rows without the field are ambiguous — excluded.
+ expect(scanOperationFileEdits([skillsCommand('t2', command)])).toEqual([]);
+ });
+
+ it('skips a failed DEVICE-routed lobe-skills call (non-zero exitCode)', () => {
+ const result = scanOperationFileEdits([
+ skillsCommand('t1', 'python -c "doc.save(\'/work/report.docx\')"', {
+ executionEnv: 'device',
+ exitCode: 1,
+ success: false,
+ }),
+ ]);
+ expect(result).toEqual([]);
+ });
+
+ it('ignores non-shell lobe-skills apiNames (exportFile / readReference)', () => {
+ expect(
+ scanOperationFileEdits([
+ {
+ apiName: 'exportFile',
+ arguments: JSON.stringify({ path: '/work/deck.pptx' }),
+ identifier: 'lobe-skills',
+ state: { executionEnv: 'device', success: true },
+ toolCallId: 't1',
+ },
+ ]),
+ ).toEqual([]);
+ });
+ });
+});
+
+describe('classifyEditedFile', () => {
+ it('classifies entity formats into their kind (case-insensitive)', () => {
+ expect(classifyEditedFile('/a.pptx')).toEqual({ category: 'entity', entityKind: 'slides' });
+ expect(classifyEditedFile('/a.PPT')).toEqual({ category: 'entity', entityKind: 'slides' });
+ expect(classifyEditedFile('/a.xlsx')).toEqual({ category: 'entity', entityKind: 'sheet' });
+ expect(classifyEditedFile('/a.xls')).toEqual({ category: 'entity', entityKind: 'sheet' });
+ expect(classifyEditedFile('/a.csv')).toEqual({ category: 'entity', entityKind: 'sheet' });
+ expect(classifyEditedFile('/a.docx')).toEqual({ category: 'entity', entityKind: 'doc' });
+ expect(classifyEditedFile('/a.DOC')).toEqual({ category: 'entity', entityKind: 'doc' });
+ expect(classifyEditedFile('/report.pdf')).toEqual({ category: 'entity', entityKind: 'pdf' });
+ });
+
+ it('classifies html files as html', () => {
+ expect(classifyEditedFile('/index.html')).toEqual({ category: 'html' });
+ expect(classifyEditedFile('/page.HTM')).toEqual({ category: 'html' });
+ });
+
+ it('classifies everything else as other', () => {
+ expect(classifyEditedFile('/notes.md')).toEqual({ category: 'other' });
+ expect(classifyEditedFile('/src/index.ts')).toEqual({ category: 'other' });
+ expect(classifyEditedFile('/Makefile')).toEqual({ category: 'other' });
+ expect(classifyEditedFile('/.env')).toEqual({ category: 'other' });
+ });
+});
+
+describe('getBasename', () => {
+ it('returns the last path segment for POSIX paths', () => {
+ expect(getBasename('/mnt/data/deck.pptx')).toBe('deck.pptx');
+ expect(getBasename('report.pdf')).toBe('report.pdf');
+ });
+
+ it('handles Windows separators', () => {
+ expect(getBasename('C:\\Users\\me\\notes.txt')).toBe('notes.txt');
+ expect(getBasename('a\\b\\c')).toBe('c');
+ });
+
+ it('tolerates a trailing slash by taking the last non-empty segment', () => {
+ expect(getBasename('/mnt/data/')).toBe('data');
+ expect(getBasename('folder\\')).toBe('folder');
+ });
+
+ it('trims surrounding whitespace', () => {
+ expect(getBasename(' /work/a.txt ')).toBe('a.txt');
+ });
+
+ it('returns empty string when there is no usable segment', () => {
+ expect(getBasename('')).toBe('');
+ expect(getBasename('///')).toBe('');
+ });
+
+ it('keeps dotfiles intact', () => {
+ expect(getBasename('/etc/.env')).toBe('.env');
+ });
+});
+
+describe('getFileExtension', () => {
+ it('lowercases the extension without the leading dot', () => {
+ expect(getFileExtension('/a/Report.PDF')).toBe('pdf');
+ expect(getFileExtension('index.HTML')).toBe('html');
+ });
+
+ it('returns empty string when there is no extension', () => {
+ expect(getFileExtension('/a/Makefile')).toBe('');
+ expect(getFileExtension('noext')).toBe('');
+ });
+
+ it('treats a dotfile with no real extension as extension-less', () => {
+ expect(getFileExtension('/etc/.env')).toBe('');
+ expect(getFileExtension('.gitignore')).toBe('');
+ });
+
+ it('resolves the extension from the basename, not an earlier dotted dir', () => {
+ expect(getFileExtension('/my.dir/file')).toBe('');
+ expect(getFileExtension('/my.dir/a.ts')).toBe('ts');
+ });
+});
+
+describe('normalizeScanPath', () => {
+ it('collapses `.` segments and duplicate slashes, preserving case and the leading slash', () => {
+ expect(normalizeScanPath('/workspace/./report.pdf')).toBe('/workspace/report.pdf');
+ expect(normalizeScanPath('/workspace//report.pdf')).toBe('/workspace/report.pdf');
+ expect(normalizeScanPath('/Work/A.txt')).toBe('/Work/A.txt');
+ });
+
+ it('keeps relative paths relative (never made absolute)', () => {
+ expect(normalizeScanPath('./deck.pptx')).toBe('deck.pptx');
+ expect(normalizeScanPath('deck.pptx')).toBe('deck.pptx');
+ expect(normalizeScanPath('a/./b/c')).toBe('a/b/c');
+ });
+
+ it('does NOT collapse `..` (lexical folding is unsafe across symlinks)', () => {
+ expect(normalizeScanPath('/work/a/../b.pdf')).toBe('/work/a/../b.pdf');
+ });
+
+ it('preserves a leading `~` (home) as its own segment', () => {
+ expect(normalizeScanPath('~/docs/./a.docx')).toBe('~/docs/a.docx');
+ expect(normalizeScanPath('~')).toBe('~');
+ });
+
+ it('collapses an all-dot path to the current directory', () => {
+ expect(normalizeScanPath('.')).toBe('.');
+ expect(normalizeScanPath('./')).toBe('.');
+ });
+});
diff --git a/packages/builtin-tools/src/fileEditScan/index.ts b/packages/builtin-tools/src/fileEditScan/index.ts
new file mode 100644
index 00000000000..0204262ea3c
--- /dev/null
+++ b/packages/builtin-tools/src/fileEditScan/index.ts
@@ -0,0 +1,833 @@
+import { CloudSandboxApiName, CloudSandboxIdentifier } from '@lobechat/builtin-tool-cloud-sandbox';
+import { LocalSystemApiName, LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';
+import { SkillsApiName, SkillsIdentifier } from '@lobechat/builtin-tool-skills';
+
+import type {
+ EditedFileCategory,
+ EditedFileChangeKind,
+ EditedFileEntry,
+ FileEditToolCallRecord,
+} from './types';
+
+export type {
+ EditedFileCategory,
+ EditedFileChangeKind,
+ EditedFileEntry,
+ FileEditToolCallRecord,
+} from './types';
+
+/*
+ * ── Source constants ────────────────────────────────────────────────────────
+ * The scanner recognizes two kinds of edit-producing sources: STRUCTURED ones
+ * (cloud-sandbox + local-system writeFile/editFile/moveFiles, codex
+ * file_change, claude-code Edit/Write/MultiEdit) plus HETERO-SHELL command-text
+ * scanning (lobe-local-system runCommand, claude-code Bash, codex
+ * command_execution, device-routed lobe-skills runCommand/execScript) —
+ * see `extractShellCommandOps`. Built-in tool identifiers / apiNames use their
+ * packages' canonical exported contracts; heterogeneous-agent names remain
+ * local because those packages are intentionally not dependencies here.
+ */
+
+/**
+ * Built-in cloud sandbox tool.
+ * Source: `@lobechat/builtin-tool-cloud-sandbox` `CloudSandboxIdentifier` +
+ * `CloudSandboxApiName`. States: `@lobechat/tool-runtime` `WriteFileState`
+ * (`{ path, success }`), `EditFileState` (`{ path, diffText?, linesAdded?,
+ * linesDeleted? }`), `MoveFilesState` (`{ results: [{ source?, destination?,
+ * success }] }`).
+ *
+ * The local-system tool (`@lobechat/builtin-tool-local-system`) exposes the
+ * SAME three file apiNames backed by the same `@lobechat/tool-runtime` states
+ * (its runtime is `LocalSystemExecutionRuntime`), so both identifiers share
+ * one structured extraction — see `STRUCTURED_FILE_APIS` in
+ * `extractRecordOps`. The only difference is downstream: local-system files
+ * live on the user's device, so they never register as Works (server
+ * registration and the client card both key on the sandbox identifier).
+ */
+export const CLOUD_SANDBOX_IDENTIFIER = CloudSandboxIdentifier;
+
+type StructuredFileApiKind = 'edit' | 'move' | 'write';
+
+const CLOUD_SANDBOX_FILE_APIS = new Map<string, StructuredFileApiKind>([
+ [CloudSandboxApiName.writeFile, 'write'],
+ [CloudSandboxApiName.editFile, 'edit'],
+ [CloudSandboxApiName.moveFiles, 'move'],
+]);
+const LOCAL_SYSTEM_FILE_APIS = new Map<string, StructuredFileApiKind>([
+ [LocalSystemApiName.writeFile, 'write'],
+ [LocalSystemApiName.editFile, 'edit'],
+ [LocalSystemApiName.moveFiles, 'move'],
+]);
+
+/**
+ * Codex heterogeneous agent.
+ * Source: `@lobechat/heterogeneous-agents` `adapters/codex.ts` — `toToolPayload`
+ * stamps every Codex tool call with `identifier = 'codex'` (`CODEX_IDENTIFIER`)
+ * and `synthesizeFileChangePluginState` produces apiName `file_change`, state
+ * shape `{ changes: [{ path, kind, diffText?, linesAdded, linesDeleted }] }`
+ * where `kind` is the RAW Codex kind (`add` / `delete` / `remove` / `rename` /
+ * other). Both fields are persisted to `message_plugins`, so the scanner gates
+ * on the identifier too (see `extractRecordOps`) — apiName alone would let any
+ * third-party plugin that happens to name a tool `file_change` slip in.
+ */
+const CODEX_IDENTIFIER = 'codex';
+const CODEX_FILE_CHANGE_API = 'file_change';
+
+/**
+ * Claude Code heterogeneous agent.
+ * Source: `@lobechat/heterogeneous-agents` `adapters/claudeCode.ts` — the
+ * `tool_use` mapping stamps `identifier = 'claude-code'`
+ * (`CLAUDE_CODE_IDENTIFIER`), `apiName = block.name`, and
+ * `arguments = JSON.stringify(input)`. The file-editing tools all carry a single
+ * `file_path` argument (MultiEdit too: one `file_path`, many `edits`). No
+ * line/diff data is surfaced. Gated on the identifier as well as the apiName so
+ * an unrelated plugin exposing an `Edit`/`Write`/`MultiEdit` tool can't slip in.
+ */
+const CLAUDE_CODE_IDENTIFIER = 'claude-code';
+const CLAUDE_CODE_EDIT_APIS = new Set(['Edit', 'Write', 'MultiEdit']);
+
+/**
+ * Hetero-shell command sources — the tools whose raw command text is scanned for
+ * entity-document write markers (see `extractShellCommandOps`). Each carries the
+ * command in its `arguments` JSON as `{ command: string }`.
+ *
+ * - lobe-local-system runCommand. Source: `@lobechat/builtin-tool-local-system`
+ * `LocalSystemIdentifier` + `LocalSystemApiName.runCommand`; state
+ * `@lobechat/tool-runtime` `RunCommandState` (`{ exitCode?, success, … }`).
+ * - claude-code Bash. Source: `@lobechat/heterogeneous-agents`
+ * `transcript/claudeCode.ts` `CLAUDE_CODE_IDENTIFIER` + tool name `Bash`;
+ * failures surface via the tool-result `error` (is_error), not a state field.
+ * - codex command_execution. Source: `@lobechat/heterogeneous-agents`
+ * `adapters/codex.ts` `CODEX_IDENTIFIER` + `CODEX_COMMAND_API`; state pluginState
+ * carries `{ exitCode?, success, … }`.
+ *
+ * - lobe-skills runCommand / execScript, DEVICE rows only. Source:
+ * `@lobechat/builtin-tool-skills` — both APIs carry the shell text in
+ * `arguments.command` (execScript's script body shares the field name), and
+ * the server runtime stamps `state.executionEnv: 'device' | 'sandbox'` on
+ * every persisted result. Only `executionEnv === 'device'` rows are scanned:
+ * a device-run skill behaves exactly like lobe-local-system runCommand (the
+ * file lands on the user's device). Sandbox rows stay excluded for the same
+ * reason as sandbox runCommand below, and rows missing the field (legacy
+ * data) are ambiguous — excluded to preserve the heuristic's precision.
+ *
+ * Deliberately NOT in scope: `lobe-cloud-sandbox` runCommand and SANDBOX-side
+ * `lobe-skills` rows (sandbox delivery is covered by `exportFile` registration;
+ * un-exported sandbox shell output is usually intermediate). Skill-produced
+ * deliverables are still captured: a successful `lobe-skills` exportFile row is
+ * a registration source in the server's file-work registration, alongside the
+ * sandbox tool's exportFile.
+ */
+const CLAUDE_CODE_BASH_API = 'Bash';
+const CODEX_COMMAND_API = 'command_execution';
+const SKILLS_SHELL_APIS = new Set([SkillsApiName.runCommand, SkillsApiName.execScript]);
+
+// ── Structural helpers ───────────────────────────────────────────────────────
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+/**
+ * Lexically normalize a POSIX-style path so equivalent spellings dedupe to one
+ * key: collapse `.` segments and runs of duplicate/leading/trailing slashes
+ * (except the root `/`). Deliberately conservative and pure (no `node:path`, so
+ * this stays browser-safe like the rest of this package):
+ * - `..` is NOT collapsed — lexical `..` folding is wrong across symlinks, and
+ * the goal is only to canonicalize obviously-equivalent spellings.
+ * - relative paths stay relative (never made absolute), symlinks are not
+ * resolved, and a leading `~` (home) survives as its own segment.
+ * Case is preserved. Windows separators are out of scope (sandbox paths are
+ * POSIX). Examples: `/workspace/./report.pdf` → `/workspace/report.pdf`;
+ * `./x` and `x` both → `x`.
+ */
+export const normalizeScanPath = (path: string): string => {
+ const isAbsolute = path.startsWith('/');
+ const segments = path.split('/').filter((segment) => segment !== '' && segment !== '.');
+ const joined = segments.join('/');
+ if (isAbsolute) return `/${joined}`;
+ // Everything collapsed away (e.g. `.` or `./`) → the current directory.
+ return joined || '.';
+};
+
+/**
+ * Trim surrounding whitespace and lexically normalize the path (see
+ * {@link normalizeScanPath}) so equivalent spellings key to the same entry;
+ * preserve case. Returns undefined for empty.
+ */
+const normalizePath = (value: unknown): string | undefined => {
+ if (typeof value !== 'string') return undefined;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? normalizeScanPath(trimmed) : undefined;
+};
+
+/** Coerce an untrusted value into a finite non-NaN number, else 0. */
+const toNumber = (value: unknown): number =>
+ typeof value === 'number' && Number.isFinite(value) ? value : 0;
+
+const nonEmptyString = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.length > 0 ? value : undefined;
+
+/** Parse the raw JSON `arguments` string; tolerate objects and malformed input. */
+const parseArguments = (value: unknown): Record<string, unknown> | undefined => {
+ if (isRecord(value)) return value;
+ if (typeof value !== 'string' || value.trim().length === 0) return undefined;
+ try {
+ const parsed = JSON.parse(value);
+ return isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * A tool call whose `state` explicitly reports failure is skipped wholesale.
+ * `success === false` (write / kill / …) or a non-empty `error` marks a failed
+ * call. Batch tools (moveFiles) carry NO top-level `success`/`error` — their
+ * per-item `success` gates each result instead, so they are never rejected here.
+ */
+const isFailedState = (state: unknown): boolean => {
+ if (!isRecord(state)) return false;
+ if (state.success === false) return true;
+ const error = state.error;
+ return error != null && error !== '';
+};
+
+/**
+ * A shell tool call whose state reports a non-zero exit code failed — the
+ * command's output (and any file it would have written) never landed. Only
+ * `RunCommandState` (lobe-local-system) and the codex `command_execution`
+ * pluginState carry an `exitCode`; the other structured sources never set it,
+ * so this generic guard only fires for the hetero-shell branch.
+ */
+const hasNonZeroExitCode = (state: unknown): boolean =>
+ isRecord(state) && typeof state.exitCode === 'number' && state.exitCode !== 0;
+
+// ── Normalized edit ops (pre-fold) ───────────────────────────────────────────
+
+interface EditOpBase {
+ diffText?: string;
+ linesAdded: number;
+ linesDeleted: number;
+ toolCallId: string;
+}
+
+/** A write with ambiguous create-vs-overwrite semantics (sandbox writeFile / CC Write). */
+interface WriteOp extends EditOpBase {
+ path: string;
+ type: 'write';
+}
+
+/** A change carrying an already-resolved terminal-ish kind (no known rename source). */
+interface ChangeOp extends EditOpBase {
+ kind: EditedFileChangeKind;
+ path: string;
+ type: 'change';
+}
+
+/** A rename with a known source → destination (sandbox moveFiles). */
+interface RenameOp extends EditOpBase {
+ destination: string;
+ source: string;
+ type: 'rename';
+}
+
+type EditOp = ChangeOp | RenameOp | WriteOp;
+
+const emptyDeltas = (
+ record: Record<string, unknown> | undefined,
+): Pick<EditOpBase, 'diffText' | 'linesAdded' | 'linesDeleted'> => ({
+ diffText: record ? nonEmptyString(record.diffText) : undefined,
+ linesAdded: toNumber(record?.linesAdded),
+ linesDeleted: toNumber(record?.linesDeleted),
+});
+
+// ── Per-source extraction ────────────────────────────────────────────────────
+
+/** Structured writeFile / editFile / moveFiles extraction, shared by the
+ * cloud-sandbox and local-system tools (identical apiNames + state shapes). */
+const extractStructuredFileOps = (
+ record: FileEditToolCallRecord,
+ apiKind: StructuredFileApiKind,
+): EditOp[] => {
+ const state = isRecord(record.state) ? record.state : undefined;
+ const { toolCallId } = record;
+
+ // Parse the raw `arguments` JSON lazily: only writeFile/editFile fall back to
+ // it, and only when the resolved `state.path` is missing. Skipping the parse
+ // on the common (state carries the path) path avoids a JSON.parse per record.
+ const pathFromArgs = (): string | undefined =>
+ normalizePath(parseArguments(record.arguments)?.path);
+
+ switch (apiKind) {
+ case 'write': {
+ const path = normalizePath(state?.path) ?? pathFromArgs();
+ if (!path) return [];
+ return [{ linesAdded: 0, linesDeleted: 0, path, toolCallId, type: 'write' }];
+ }
+ case 'edit': {
+ const path = normalizePath(state?.path) ?? pathFromArgs();
+ if (!path) return [];
+ return [{ ...emptyDeltas(state), kind: 'modified', path, toolCallId, type: 'change' }];
+ }
+ case 'move': {
+ const results = Array.isArray(state?.results) ? state.results : [];
+ return results.flatMap((entry): RenameOp[] => {
+ if (!isRecord(entry) || entry.success !== true) return [];
+ const source = normalizePath(entry.source);
+ const destination = normalizePath(entry.destination);
+ if (!source || !destination) return [];
+ return [
+ { destination, linesAdded: 0, linesDeleted: 0, source, toolCallId, type: 'rename' },
+ ];
+ });
+ }
+ }
+};
+
+/** Map a RAW Codex file-change kind onto our terminal kind (mirrors codex adapter). */
+const codexKindToChangeKind = (kind: unknown): EditedFileChangeKind => {
+ switch (kind) {
+ case 'add': {
+ return 'added';
+ }
+ case 'delete':
+ case 'remove': {
+ return 'deleted';
+ }
+ case 'rename': {
+ return 'renamed';
+ }
+ default: {
+ return 'modified';
+ }
+ }
+};
+
+const extractCodexOps = (record: FileEditToolCallRecord): EditOp[] => {
+ const state = isRecord(record.state) ? record.state : undefined;
+ const changes = Array.isArray(state?.changes) ? state.changes : [];
+ const { toolCallId } = record;
+
+ return changes.flatMap((change): ChangeOp[] => {
+ if (!isRecord(change)) return [];
+ const path = normalizePath(change.path);
+ if (!path) return [];
+ // Codex renames carry only a single `path` (no source), so a renamed entry
+ // records the new path with `previousPath` left undefined.
+ return [
+ {
+ ...emptyDeltas(change),
+ kind: codexKindToChangeKind(change.kind),
+ path,
+ toolCallId,
+ type: 'change',
+ },
+ ];
+ });
+};
+
+const extractClaudeCodeOps = (record: FileEditToolCallRecord): EditOp[] => {
+ const args = parseArguments(record.arguments);
+ const path = normalizePath(args?.file_path);
+ if (!path) return [];
+ // CC edit tools surface no line/diff data — record the touch with 0 deltas.
+ // Write is create-or-overwrite (ambiguous), Edit/MultiEdit always modify.
+ if (record.apiName === 'Write') {
+ return [{ linesAdded: 0, linesDeleted: 0, path, toolCallId: record.toolCallId, type: 'write' }];
+ }
+ return [
+ {
+ kind: 'modified',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path,
+ toolCallId: record.toolCallId,
+ type: 'change',
+ },
+ ];
+};
+
+// ── Hetero-shell command-text scanning ───────────────────────────────────────
+/*
+ * Shell commands (runCommand / Bash / command_execution) produce documents two
+ * ways in production: ~77% via INLINE script bodies (heredoc / `python -c`) whose
+ * output path literal sits inside the command string (`doc.save('/work/x.docx')`)
+ * and ~23% via CLI output flags (`marp -o deck.pptx`, `soffice --convert-to`).
+ * ~44% of document-mentioning commands are pure READS (pdftotext, unzip -p, …),
+ * so bare extension matching is forbidden — only WRITE-context matches count, and
+ * we further keep ONLY entity-format paths to bound the heuristic's blast radius
+ * (a false positive shows a nonexistent file as "edited"). Precision over recall.
+ */
+
+/** Skip Rule A output-flag extraction for downloader commands — `curl -o out.pdf`
+ * / `wget -O` write a DOWNLOAD, not an authored document, and downloads must not
+ * count. Command-level (over-approximates: a downloader anywhere in the string
+ * disables `-o`/`--output` for the whole command), which is the accepted cost. */
+const DOWNLOADER_RE = /\b(?:curl|wget|invoke-webrequest)\b/i;
+
+/** Also skip `-o`/`--output` when the command runs a CLI whose `-o` does NOT
+ * name an output file — `grep -o 'report.pdf' notes.txt` (only-matching),
+ * `ps -o`, `tar -o`, `unzip -o` (overwrite) — so the flag's operand is never
+ * mistaken for an authored document. Same command-level over-approximation as
+ * the downloader rule. `sort -o out.csv` is deliberately NOT here: its `-o`
+ * IS an output file. */
+const READ_ONLY_O_FLAG_RE = /\b(?:grep|egrep|fgrep|rg|ag|ack|ps|tar|unzip)\b/i;
+
+/**
+ * Split a command into whitespace-separated tokens, honoring single/double
+ * quotes (quoted spans never split and their quotes are stripped). Good enough
+ * for locating `-o`/`--output`/redirect/`--convert-to` markers; it is NOT a full
+ * shell parser (no escapes, no `$()`), which is fine for this heuristic.
+ */
+const tokenizeCommand = (command: string): string[] => {
+ const tokens: string[] = [];
+ let current = '';
+ let started = false;
+ let quote: "'" | '"' | undefined;
+
+ for (const ch of command) {
+ if (quote) {
+ if (ch === quote) quote = undefined;
+ else current += ch;
+ continue;
+ }
+ if (ch === "'" || ch === '"') {
+ quote = ch;
+ started = true;
+ continue;
+ }
+ if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
+ if (started) tokens.push(current);
+ current = '';
+ started = false;
+ continue;
+ }
+ current += ch;
+ started = true;
+ }
+ if (started) tokens.push(current);
+ return tokens;
+};
+
+/** Replace a basename's extension with `ext` (append when it has none). */
+const replaceExtension = (basename: string, ext: string): string => {
+ const dot = basename.lastIndexOf('.');
+ const stem = dot > 0 ? basename.slice(0, dot) : basename;
+ return `${stem}.${ext}`;
+};
+
+/**
+ * Derive `soffice` / `libreoffice --convert-to <fmt>` output paths: each input
+ * file's basename with its extension replaced by the target format (filter
+ * suffixes like `pdf:writer_pdf_Export` collapse to `pdf`), joined under
+ * `--outdir` when present.
+ */
+const extractSofficeConvertPaths = (tokens: string[]): string[] => {
+ const sofficeIdx = tokens.findIndex((t) => {
+ const bin = getBasename(t).toLowerCase();
+ return bin === 'soffice' || bin === 'libreoffice';
+ });
+ if (sofficeIdx === -1) return [];
+
+ let format: string | undefined;
+ let outdir: string | undefined;
+ const inputs: string[] = [];
+
+ for (let i = sofficeIdx + 1; i < tokens.length; i += 1) {
+ const token = tokens[i];
+ // A shell control operator ends the soffice invocation — without this,
+ // `… report.docx && echo done` would derive bogus `&&.pdf` / `echo.pdf`
+ // outputs from the tokens of the NEXT command in the pipeline.
+ if (/^(?:&&?|\|\|?|;)$/.test(token)) break;
+ // Redirect plumbing is not an input document — without this, `2>/dev/null`
+ // / `> convert.log` / `2>&1` would derive bogus `null.pdf` / `convert.pdf`
+ // / `2>&1.pdf` outputs. A bare operator (`>`, `>>`, `2>`, `<`) also
+ // swallows its target token.
+ if (/^\d*(?:>>?|<)/.test(token)) {
+ if (/^\d*(?:>>?|<)$/.test(token)) i += 1;
+ continue;
+ }
+ if (token === '--convert-to') {
+ format = tokens[i + 1];
+ i += 1;
+ } else if (token.startsWith('--convert-to=')) {
+ format = token.slice('--convert-to='.length);
+ } else if (token === '--outdir') {
+ outdir = tokens[i + 1];
+ i += 1;
+ } else if (token.startsWith('--outdir=')) {
+ outdir = token.slice('--outdir='.length);
+ } else if (!token.startsWith('-')) {
+ // Positional argument → an input document to convert.
+ inputs.push(token);
+ }
+ // Any other `--flag` (e.g. --headless) is valueless — ignored.
+ }
+
+ const fmt = format?.split(':')[0].trim().toLowerCase();
+ if (!fmt) return [];
+
+ return inputs.map((input) => {
+ const derived = replaceExtension(getBasename(input), fmt);
+ return outdir ? `${outdir.replace(/\/+$/, '')}/${derived}` : derived;
+ });
+};
+
+/** Rule A — CLI output markers (tokenized): `-o`/`--output`, shell redirects,
+ * and `soffice --convert-to` derivations. Returns raw (unfiltered) candidates. */
+const extractCliOutputPaths = (command: string): string[] => {
+ const tokens = tokenizeCommand(command);
+ const skipOutputFlags = DOWNLOADER_RE.test(command) || READ_ONLY_O_FLAG_RE.test(command);
+ const paths: string[] = [];
+
+ for (let i = 0; i < tokens.length; i += 1) {
+ const token = tokens[i];
+
+ // Rule A.1 — `-o <path>` / `--output <path>` / `--output=<path>`.
+ if (!skipOutputFlags) {
+ if (token === '-o' || token === '--output') {
+ if (tokens[i + 1]) paths.push(tokens[i + 1]);
+ continue;
+ }
+ if (token.startsWith('--output=')) {
+ paths.push(token.slice('--output='.length));
+ continue;
+ }
+ }
+
+ // Rule A.2 — shell redirect `>` / `>>` (bare or attached `>path`). Ignore fd
+ // redirects (`2>`, `&>`, `2>&1`, `>&1`): those never start with a plain `>`
+ // followed by a filename char.
+ if (token === '>' || token === '>>') {
+ if (tokens[i + 1]) paths.push(tokens[i + 1]);
+ } else if (/^>>?[^&>]/.test(token)) {
+ paths.push(token.replace(/^>>?/, ''));
+ }
+ }
+
+ paths.push(...extractSofficeConvertPaths(tokens));
+ return paths;
+};
+
+/**
+ * Rule B — inline write-call literals, matched over the RAW command text (no
+ * tokenization). Each pattern captures the first quoted string argument of a
+ * known document-writing call; group 2 is the path literal. READ calls
+ * (`load_workbook`, `pdftotext`, …) are deliberately absent.
+ */
+const INLINE_WRITE_PATTERNS: readonly RegExp[] = [
+ // python-pptx / python-docx / openpyxl `.save('…')`
+ /\.save\(\s*(['"])([^'"]+)\1/g,
+ // pandas `.to_excel('…')` / `.to_csv('…')`
+ /\bto_excel\(\s*(['"])([^'"]+)\1/g,
+ /\bto_csv\(\s*(['"])([^'"]+)\1/g,
+ // weasyprint `.write_pdf('…')`
+ /\bwrite_pdf\(\s*(['"])([^'"]+)\1/g,
+ // reportlab `Canvas('…')` / `SimpleDocTemplate('…')`
+ /\bCanvas\(\s*(['"])([^'"]+)\1/g,
+ /\bSimpleDocTemplate\(\s*(['"])([^'"]+)\1/g,
+ // pptxgenjs `writeFile({ fileName: '…' })`
+ /\bwriteFile\(\s*\{[^}]*?\bfileName\s*:\s*(['"])([^'"]+)\1/g,
+];
+
+/** Rule B extraction. Returns raw (unfiltered) path candidates. */
+const extractInlineWritePaths = (command: string): string[] => {
+ // Un-escape shell-escaped quotes (`\"` → `"`) so a wrapped inline script — e.g.
+ // codex's `zsh -c "node -e '…writeFile({ fileName: \"deck.pptx\" })'"` — exposes
+ // its quoted literals to the simple quote-delimited patterns below.
+ const text = command.replaceAll(/\\(["'])/g, '$1');
+ const paths: string[] = [];
+ for (const pattern of INLINE_WRITE_PATTERNS) {
+ for (const match of text.matchAll(pattern)) {
+ if (match[2]) paths.push(match[2]);
+ }
+ }
+ return paths;
+};
+
+/**
+ * Scan a hetero-shell command's text for entity-document write markers (Rules A
+ * + B). Emits one `modified` ChangeOp per distinct ENTITY path (zero line
+ * deltas), mirroring how exportFile-derived entries are synthesized server-side.
+ * Non-entity write positions (html/md/txt/ts/…) are never emitted.
+ */
+const extractShellCommandOps = (record: FileEditToolCallRecord): EditOp[] => {
+ const command = parseArguments(record.arguments)?.command;
+ if (typeof command !== 'string' || command.trim().length === 0) return [];
+
+ const seen = new Set<string>();
+ const ops: ChangeOp[] = [];
+ for (const candidate of [
+ ...extractCliOutputPaths(command),
+ ...extractInlineWritePaths(command),
+ ]) {
+ const path = normalizePath(candidate);
+ if (!path || seen.has(path)) continue;
+ seen.add(path);
+ // Heuristic branch: keep ONLY entity documents (pptx/docx/xlsx/pdf/csv/…).
+ if (classifyEditedFile(path).category !== 'entity') continue;
+ ops.push({
+ kind: 'modified',
+ linesAdded: 0,
+ linesDeleted: 0,
+ path,
+ toolCallId: record.toolCallId,
+ type: 'change',
+ });
+ }
+ return ops;
+};
+
+const extractRecordOps = (record: FileEditToolCallRecord): EditOp[] => {
+ // A plugin-level error means the edit never landed (server:
+ // `message_plugins.error`; client: `tool.result?.error`) — skip the record
+ // wholesale, same as an explicit `state` failure below.
+ if (record.error != null && record.error !== '') return [];
+ if (isFailedState(record.state)) return [];
+ // A shell tool that exited non-zero produced no output file — skip it.
+ if (hasNonZeroExitCode(record.state)) return [];
+
+ // Gate each source on its identifier (all persisted to
+ // `message_plugins.identifier`), not apiName alone: an unrelated third-party
+ // plugin naming a tool `file_change` / `Edit` / `Write` must never be treated
+ // as an editing tool.
+ const structuredApiKind =
+ record.identifier === CloudSandboxIdentifier
+ ? CLOUD_SANDBOX_FILE_APIS.get(record.apiName)
+ : record.identifier === LocalSystemIdentifier
+ ? LOCAL_SYSTEM_FILE_APIS.get(record.apiName)
+ : undefined;
+ if (structuredApiKind) {
+ return extractStructuredFileOps(record, structuredApiKind);
+ }
+ if (record.identifier === CODEX_IDENTIFIER && record.apiName === CODEX_FILE_CHANGE_API) {
+ return extractCodexOps(record);
+ }
+ if (record.identifier === CLAUDE_CODE_IDENTIFIER && CLAUDE_CODE_EDIT_APIS.has(record.apiName)) {
+ return extractClaudeCodeOps(record);
+ }
+
+ // Hetero-shell: lobe-local-system runCommand / claude-code Bash / codex
+ // command_execution / DEVICE-routed lobe-skills runCommand+execScript — scan
+ // the raw command text for entity-document write markers. Gated on
+ // identifier+apiName so lobe-cloud-sandbox runCommand (covered by exportFile
+ // registration) stays out; skills rows additionally require
+ // `state.executionEnv === 'device'` — sandbox skills output is delivered via
+ // exportFile, and legacy rows without the field are ambiguous.
+ if (
+ (record.identifier === LocalSystemIdentifier &&
+ record.apiName === LocalSystemApiName.runCommand) ||
+ (record.identifier === CLAUDE_CODE_IDENTIFIER && record.apiName === CLAUDE_CODE_BASH_API) ||
+ (record.identifier === CODEX_IDENTIFIER && record.apiName === CODEX_COMMAND_API) ||
+ (record.identifier === SkillsIdentifier &&
+ SKILLS_SHELL_APIS.has(record.apiName) &&
+ isRecord(record.state) &&
+ record.state.executionEnv === 'device')
+ ) {
+ return extractShellCommandOps(record);
+ }
+
+ // Any other apiName — still a blind spot. Shell edits are now PARTIALLY
+ // tracked (entity-document write markers only, above); sed / generic non-entity
+ // file writes remain untracked.
+ return [];
+};
+
+// ── Terminal-state folding ───────────────────────────────────────────────────
+
+interface MutableEntry {
+ diffTexts: string[];
+ kind: EditedFileChangeKind;
+ linesAdded: number;
+ linesDeleted: number;
+ path: string;
+ previousPath?: string;
+ sourceToolCallIds: string[];
+}
+
+const newEntry = (path: string, kind: EditedFileChangeKind): MutableEntry => ({
+ diffTexts: [],
+ kind,
+ linesAdded: 0,
+ linesDeleted: 0,
+ path,
+ sourceToolCallIds: [],
+});
+
+const accumulate = (entry: MutableEntry, op: EditOpBase): void => {
+ entry.linesAdded += op.linesAdded;
+ entry.linesDeleted += op.linesDeleted;
+ if (op.diffText) entry.diffTexts.push(op.diffText);
+ entry.sourceToolCallIds.push(op.toolCallId);
+};
+
+/**
+ * Fold a forward (add / modify / rename-without-source) kind onto the running
+ * terminal kind. Order-sensitive per the brief:
+ * - `added` is sticky (added → modified stays `added`; the file is net-new).
+ * - `renamed` is sticky against later modifies (edits follow the new path).
+ * - a re-touch after `deleted` is a net MODIFY: an added→deleted pair is dropped
+ * wholesale in {@link applyDelete}, so a `deleted` running kind here always
+ * means a file that pre-existed the operation and was re-created, i.e. its
+ * content changed rather than being net-new.
+ * - otherwise the running kind settles to `modified`.
+ */
+const foldForwardKind = (
+ prev: EditedFileChangeKind,
+ next: 'added' | 'modified' | 'renamed',
+): EditedFileChangeKind => {
+ if (next === 'renamed') return prev === 'added' ? 'added' : 'renamed';
+ if (prev === 'renamed') return 'renamed';
+ if (prev === 'added') return 'added';
+ if (prev === 'deleted') return 'modified';
+ return 'modified';
+};
+
+const applyDelete = (map: Map<string, MutableEntry>, op: ChangeOp): void => {
+ const existing = map.get(op.path);
+ // added → deleted within one operation is a net no-op: drop it entirely.
+ if (existing?.kind === 'added') {
+ map.delete(op.path);
+ return;
+ }
+ if (existing) {
+ existing.kind = 'deleted';
+ accumulate(existing, op);
+ return;
+ }
+ const entry = newEntry(op.path, 'deleted');
+ accumulate(entry, op);
+ map.set(op.path, entry);
+};
+
+const applyForward = (map: Map<string, MutableEntry>, op: WriteOp | ChangeOp): void => {
+ const incoming: 'added' | 'modified' | 'renamed' =
+ op.type === 'write' ? 'modified' : (op.kind as 'added' | 'modified' | 'renamed');
+ const existing = map.get(op.path);
+
+ if (!existing) {
+ // A first-seen write is `added`; otherwise adopt the incoming kind.
+ const entry = newEntry(op.path, op.type === 'write' ? 'added' : op.kind);
+ accumulate(entry, op);
+ map.set(op.path, entry);
+ return;
+ }
+
+ existing.kind = foldForwardKind(existing.kind, incoming);
+ accumulate(existing, op);
+};
+
+const applyRename = (map: Map<string, MutableEntry>, op: RenameOp): void => {
+ const existing = map.get(op.source);
+
+ if (existing) {
+ map.delete(op.source);
+ if (existing.kind === 'added') {
+ // A file created earlier this operation and then moved stays net-new at
+ // its destination — no `previousPath` (the source never pre-existed).
+ existing.path = op.destination;
+ } else {
+ existing.previousPath = existing.previousPath ?? op.source;
+ existing.path = op.destination;
+ existing.kind = 'renamed';
+ }
+ accumulate(existing, op);
+ map.set(op.destination, existing);
+ return;
+ }
+
+ const entry = newEntry(op.destination, 'renamed');
+ entry.previousPath = op.source;
+ accumulate(entry, op);
+ map.set(op.destination, entry);
+};
+
+const applyOp = (map: Map<string, MutableEntry>, op: EditOp): void => {
+ if (op.type === 'rename') {
+ applyRename(map, op);
+ return;
+ }
+ if (op.type === 'change' && op.kind === 'deleted') {
+ applyDelete(map, op);
+ return;
+ }
+ applyForward(map, op);
+};
+
+/**
+ * Scan every persisted tool call of ONE operation and fold them into the
+ * terminal set of edited files. Records are processed in the given order (their
+ * persisted chronological order), so the folding rules resolve correctly.
+ *
+ * Malformed `arguments` / `state` never throw — the offending record simply
+ * contributes whatever is parseable (often nothing).
+ */
+export const scanOperationFileEdits = (records: FileEditToolCallRecord[]): EditedFileEntry[] => {
+ const map = new Map<string, MutableEntry>();
+
+ for (const record of records) {
+ for (const op of extractRecordOps(record)) applyOp(map, op);
+ }
+
+ return [...map.values()].map((entry) => ({
+ diffTexts: entry.diffTexts,
+ kind: entry.kind,
+ linesAdded: entry.linesAdded,
+ linesDeleted: entry.linesDeleted,
+ path: entry.path,
+ ...(entry.previousPath ? { previousPath: entry.previousPath } : {}),
+ sourceToolCallIds: entry.sourceToolCallIds,
+ }));
+};
+
+// ── Path classification ──────────────────────────────────────────────────────
+
+/** Entity-format extensions that register into the works / work_versions system. */
+const ENTITY_EXTENSIONS: Record<string, 'slides' | 'sheet' | 'doc' | 'pdf'> = {
+ csv: 'sheet',
+ doc: 'doc',
+ docx: 'doc',
+ pdf: 'pdf',
+ ppt: 'slides',
+ pptx: 'slides',
+ xls: 'sheet',
+ xlsx: 'sheet',
+};
+
+const HTML_EXTENSIONS = new Set(['htm', 'html']);
+
+/**
+ * Basename of a POSIX/Windows path: the last non-empty segment with surrounding
+ * whitespace trimmed. Tolerates either separator (`/` or `\`) and a trailing
+ * slash; returns '' when the path has no usable segment.
+ *
+ * Single source of truth for the consumers that used to hand-roll this — the
+ * server `fileWorkRegistration`, the `EditedFilesCard` and `Work/descriptors` UI.
+ */
+export const getBasename = (path: string): string =>
+ path.replaceAll('\\', '/').split('/').findLast(Boolean)?.trim() ?? '';
+
+/**
+ * Lowercased extension of a path's basename, WITHOUT the leading dot, or '' when
+ * there is none. A leading-dot dotfile with no real extension (e.g. `.env`)
+ * returns '' — the dot at index 0 is not an extension separator.
+ */
+export const getFileExtension = (path: string): string => {
+ const basename = getBasename(path);
+ const dotIndex = basename.lastIndexOf('.');
+ if (dotIndex <= 0) return '';
+ return basename.slice(dotIndex + 1).toLowerCase();
+};
+
+/**
+ * Classify an edited file's path so the two consumers can split it: entity
+ * documents get a Work, HTML rides the artifact-hosting path, everything else
+ * folds into the aggregate "edited N files" card. Case-insensitive.
+ */
+export const classifyEditedFile = (path: string): EditedFileCategory => {
+ const extension = getFileExtension(path);
+ const entityKind = ENTITY_EXTENSIONS[extension];
+ if (entityKind) return { category: 'entity', entityKind };
+ if (HTML_EXTENSIONS.has(extension)) return { category: 'html' };
+ return { category: 'other' };
+};
diff --git a/packages/builtin-tools/src/fileEditScan/types.ts b/packages/builtin-tools/src/fileEditScan/types.ts
new file mode 100644
index 00000000000..2e81b8e5f29
--- /dev/null
+++ b/packages/builtin-tools/src/fileEditScan/types.ts
@@ -0,0 +1,62 @@
+/**
+ * Shared types for the per-operation file-edit scanner.
+ *
+ * They describe the minimal, duck-typed shape of ONE persisted tool call as
+ * seen by BOTH consumers, so the same scanner can run on either side:
+ * - server: one `message_plugins` row (its `apiName` / `arguments` /
+ * `identifier` / `state` / `toolCallId` columns).
+ * - client: one tool payload held in the chat store (same fields).
+ *
+ * The scanner reads `state` / `arguments` structurally (duck-typed) and never
+ * imports `@lobechat/tool-runtime` or `@lobechat/heterogeneous-agents`, so this
+ * module stays dependency-light and safe for both bundles.
+ */
+
+/** One persisted tool call within an operation. */
+export interface FileEditToolCallRecord {
+ apiName: string;
+ /** Raw JSON string of tool arguments. */
+ arguments?: string | null;
+ /**
+ * Tool-result error, when the call failed at the plugin layer (server:
+ * `message_plugins.error`; client: `tool.result?.error`). A non-empty value
+ * means the edit never landed, so the scanner skips the whole record — this
+ * is the plugin-level counterpart to a `state`-reported failure.
+ */
+ error?: unknown;
+ /** Plugin/tool identifier, e.g. 'lobe-cloud-sandbox'. */
+ identifier?: string | null;
+ /** Persisted plugin state (tool result state). */
+ state?: unknown;
+ toolCallId: string;
+}
+
+export type EditedFileChangeKind = 'added' | 'modified' | 'deleted' | 'renamed';
+
+/** Terminal-state summary of all edits to one file within an operation. */
+export interface EditedFileEntry {
+ /** Chronological per-edit diffs, only for source tools that provided one. */
+ diffTexts: string[];
+ /** Folded terminal change kind after replaying every edit to this path. */
+ kind: EditedFileChangeKind;
+ linesAdded: number;
+ linesDeleted: number;
+ /** Current (final) path of the file. */
+ path: string;
+ /** Original path before a rename; set only when `kind === 'renamed'`. */
+ previousPath?: string;
+ /** Tool call ids that touched this file, in chronological order. */
+ sourceToolCallIds: string[];
+}
+
+/**
+ * Classification of an edited file's path:
+ * - `entity`: an entity-format document that gets its own Work (slides / sheet /
+ * doc / pdf).
+ * - `html`: an HTML file (rendered by the artifact-hosting path).
+ * - `other`: everything else — folded into the "edited N files" aggregate card.
+ */
+export type EditedFileCategory =
+ | { category: 'entity'; entityKind: 'slides' | 'sheet' | 'doc' | 'pdf' }
+ | { category: 'html' }
+ | { category: 'other' };
diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.ts
index d435de8afa5..cfdf1456167 100644
--- a/packages/database/src/models/__tests__/agentOperation.test.ts
+++ b/packages/database/src/models/__tests__/agentOperation.test.ts
@@ -372,4 +372,31 @@ describe('AgentOperationModel', () => {
expect(result).toBe(0);
});
});
+
+ describe('listOperationTree', () => {
+ it('returns the root op together with its direct children, owner-scoped', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+
+ await serverDB.insert(agentOperations).values([
+ { id: 'root', status: 'done', userId },
+ { id: 'child-a', parentOperationId: 'root', status: 'done', userId },
+ { id: 'child-b', parentOperationId: 'root', status: 'done', userId },
+ // Unrelated op (different parent) must not leak in.
+ { id: 'stranger', parentOperationId: 'other-root', status: 'done', userId },
+ // Another user's child of the same root must not leak in.
+ { id: 'foreign-child', parentOperationId: 'root', status: 'done', userId: otherUserId },
+ ]);
+
+ const tree = await model.listOperationTree('root');
+ expect(tree.map((op) => op.id).sort()).toEqual(['child-a', 'child-b', 'root']);
+ });
+
+ it('returns just the root when it has no children', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ await serverDB.insert(agentOperations).values({ id: 'lonely', status: 'done', userId });
+
+ const tree = await model.listOperationTree('lonely');
+ expect(tree.map((op) => op.id)).toEqual(['lonely']);
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/messages/message.pluginsForOperation.test.ts b/packages/database/src/models/__tests__/messages/message.pluginsForOperation.test.ts
new file mode 100644
index 00000000000..7bb3a22d0ea
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.pluginsForOperation.test.ts
@@ -0,0 +1,182 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { messagePlugins, messages, threads, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'plugins-for-op-user';
+const otherUserId = 'plugins-for-op-other';
+const messageModel = new MessageModel(serverDB, userId);
+
+const T0 = new Date('2026-07-20T00:00:00.000Z');
+const T1 = new Date('2026-07-20T00:01:00.000Z');
+const T2 = new Date('2026-07-20T00:02:00.000Z');
+const T3 = new Date('2026-07-20T00:03:00.000Z');
+
+/** Insert a `tool` message + its plugin row with full control over createdAt. */
+const seedToolCall = async (opts: {
+ apiName?: string;
+ createdAt: Date;
+ id: string;
+ metadata?: Record<string, unknown>;
+ ownerId?: string;
+ threadId?: string | null;
+ toolCallId?: string;
+ topicId: string;
+}) => {
+ const owner = opts.ownerId ?? userId;
+ await serverDB.insert(messages).values({
+ content: '',
+ createdAt: opts.createdAt,
+ id: opts.id,
+ metadata: opts.metadata,
+ role: 'tool',
+ threadId: opts.threadId ?? null,
+ topicId: opts.topicId,
+ userId: owner,
+ });
+ await serverDB.insert(messagePlugins).values({
+ apiName: opts.apiName ?? 'writeFile',
+ arguments: JSON.stringify({ path: `/mnt/data/${opts.id}.pptx` }),
+ id: opts.id,
+ identifier: 'lobe-cloud-sandbox',
+ state: { path: `/mnt/data/${opts.id}.pptx`, success: true },
+ toolCallId: opts.toolCallId ?? `tc-${opts.id}`,
+ userId: owner,
+ });
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(topics).values([
+ { id: 'topic1', userId },
+ { id: 'topic2', userId },
+ ]);
+ await serverDB
+ .insert(threads)
+ .values([{ id: 'thread1', topicId: 'topic1', type: 'continuation', userId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+});
+
+describe('MessageModel.listMessagePluginsForOperation', () => {
+ it('returns tool calls inside the time window, ordered by createdAt', async () => {
+ await seedToolCall({ createdAt: T2, id: 'm-b', threadId: 'thread1', topicId: 'topic1' });
+ await seedToolCall({ createdAt: T1, id: 'm-a', threadId: 'thread1', topicId: 'topic1' });
+
+ const rows = await messageModel.listMessagePluginsForOperation({
+ completedAt: T3,
+ operationId: 'op-1',
+ startedAt: T0,
+ threadId: 'thread1',
+ topicId: 'topic1',
+ });
+
+ expect(rows.map((r) => r.id)).toEqual(['m-a', 'm-b']);
+ expect(rows[0]).toMatchObject({ apiName: 'writeFile', identifier: 'lobe-cloud-sandbox' });
+ expect(rows[0].createdAt.getTime()).toBe(T1.getTime());
+ });
+
+ it('excludes tool calls outside the [startedAt, completedAt] window', async () => {
+ // createdAt earlier than the window start.
+ await seedToolCall({ createdAt: T0, id: 'before', threadId: 'thread1', topicId: 'topic1' });
+ // createdAt later than the window end.
+ await seedToolCall({ createdAt: T3, id: 'after', threadId: 'thread1', topicId: 'topic1' });
+ await seedToolCall({ createdAt: T2, id: 'inside', threadId: 'thread1', topicId: 'topic1' });
+
+ const rows = await messageModel.listMessagePluginsForOperation({
+ completedAt: T2,
+ operationId: 'op-1',
+ startedAt: T1,
+ threadId: 'thread1',
+ topicId: 'topic1',
+ });
+
+ expect(rows.map((r) => r.id)).toEqual(['inside']);
+ });
+
+ it('scopes the window to the same topic and thread', async () => {
+ await seedToolCall({ createdAt: T1, id: 'right', threadId: 'thread1', topicId: 'topic1' });
+ // Same time window, different topic — must not leak in.
+ await seedToolCall({ createdAt: T1, id: 'other-topic', threadId: null, topicId: 'topic2' });
+
+ const rows = await messageModel.listMessagePluginsForOperation({
+ completedAt: T3,
+ operationId: 'op-1',
+ startedAt: T0,
+ threadId: 'thread1',
+ topicId: 'topic1',
+ });
+
+ expect(rows.map((r) => r.id)).toEqual(['right']);
+ });
+
+ it('matches heterogeneous rows by operation metadata even outside the window', async () => {
+ // createdAt sits well after the window, but the metadata op-id must still match.
+ await seedToolCall({
+ createdAt: new Date('2027-01-01T00:00:00.000Z'),
+ id: 'hetero',
+ metadata: { heterogeneousToolStateOperationId: 'op-1' },
+ threadId: 'thread1',
+ topicId: 'topic1',
+ });
+
+ const rows = await messageModel.listMessagePluginsForOperation({
+ completedAt: T3,
+ operationId: 'op-1',
+ startedAt: T0,
+ threadId: 'thread1',
+ topicId: 'topic1',
+ });
+
+ expect(rows.map((r) => r.id)).toEqual(['hetero']);
+ });
+
+ it('falls back to now when completedAt is omitted', async () => {
+ await seedToolCall({
+ createdAt: new Date(),
+ id: 'recent',
+ threadId: 'thread1',
+ topicId: 'topic1',
+ });
+
+ const rows = await messageModel.listMessagePluginsForOperation({
+ operationId: 'op-1',
+ startedAt: T0,
+ threadId: 'thread1',
+ topicId: 'topic1',
+ });
+
+ expect(rows.map((r) => r.id)).toEqual(['recent']);
+ });
+
+ it('is scoped to the owning user', async () => {
+ await seedToolCall({
+ createdAt: T1,
+ id: 'mine',
+ ownerId: userId,
+ threadId: 'thread1',
+ topicId: 'topic1',
+ });
+
+ const asOther = await new MessageModel(serverDB, otherUserId).listMessagePluginsForOperation({
+ completedAt: T3,
+ operationId: 'op-1',
+ startedAt: T0,
+ threadId: 'thread1',
+ topicId: 'topic1',
+ });
+
+ expect(asOther).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index fa145fa119d..af04cc1681f 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -1,5 +1,5 @@
import type { VerifyRunStatus } from '@lobechat/types';
-import { and, eq, gte, isNotNull, sql } from 'drizzle-orm';
+import { and, eq, gte, isNotNull, or, sql } from 'drizzle-orm';
import { today } from '@/utils/time';
@@ -224,6 +224,28 @@ export class AgentOperationModel {
return row ?? null;
}
+ /**
+ * Load an operation together with its direct child operations (`callSubAgent`
+ * children / isolated group members) — the (at most) two-layer operation
+ * tree. File-Work registration gathers every op in this tree so a round's
+ * tool calls, including those a sub-agent produced, are scanned together.
+ * Owner-scoped. The root op (`id === operationId`) is included in the result.
+ */
+ async listOperationTree(operationId: string) {
+ return this.db
+ .select()
+ .from(agentOperations)
+ .where(
+ and(
+ this.ownership(),
+ or(
+ eq(agentOperations.id, operationId),
+ eq(agentOperations.parentOperationId, operationId),
+ ),
+ ),
+ );
+ }
+
/**
* Longest single operation (agent run) wall-clock execution time over the last
* year, in seconds. Wall clock (`completedAt - startedAt`) is the most faithful
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index e18aaa3101d..40462804336 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -101,6 +101,11 @@ export interface QueryMessagesOptions {
* Current page number (0-indexed)
*/
current?: number;
+ /**
+ * Opt-in for `file` work summaries in the payload (see
+ * `QueryMessageParams.includeFileWorks`).
+ */
+ includeFileWorks?: boolean;
/**
* Number of messages per page
*/
@@ -371,6 +376,7 @@ export class MessageModel {
{
agentId,
current = 0,
+ includeFileWorks,
pageSize = 1000,
sessionId,
skipWorks,
@@ -421,6 +427,7 @@ export class MessageModel {
);
const messageItems = await this.queryWithWhere({
current,
+ includeFileWorks,
pageSize,
postProcessUrl: options.postProcessUrl,
skipWorks,
@@ -447,6 +454,7 @@ export class MessageModel {
const messageItems = await this.queryWithWhere({
current,
+ includeFileWorks,
pageSize,
postProcessUrl: options.postProcessUrl,
skipWorks,
@@ -471,6 +479,7 @@ export class MessageModel {
const messageItems = await this.queryWithWhere({
current,
+ includeFileWorks,
pageSize,
postProcessUrl: options.postProcessUrl,
skipWorks,
@@ -583,6 +592,7 @@ export class MessageModel {
const {
where,
current = 0,
+ includeFileWorks,
pageSize = 1000,
postProcessUrl,
skipWorks,
@@ -741,7 +751,7 @@ export class MessageModel {
this.queryMessageThreadRelations(taskMessageIds, timing),
skipWorks
? ({} as Record<string, WorkSummaryItem[]>)
- : this.queryMessageWorkSummaries(result, timing),
+ : this.queryMessageWorkSummaries(result, includeFileWorks, timing),
]);
if (messageIds.length === 0 && messageGroupNodes.length === 0) {
@@ -1097,6 +1107,7 @@ export class MessageModel {
*/
private queryMessageWorkSummaries = async (
rows: { id: unknown; metadata: unknown }[],
+ includeFileWorks?: boolean,
timing?: ModelTimingContext,
): Promise<Record<string, WorkSummaryItem[]>> => {
const anchorByRootId = new Map<string, string>();
@@ -1111,6 +1122,7 @@ export class MessageModel {
'db.message.queryWithWhere.workSummaries',
() =>
new WorkModel(this.db, this.userId, this.workspaceId).listSummariesByRootOperations({
+ includeFileWorks,
rootOperationIds: Array.from(anchorByRootId.keys()),
}),
{ rootOperationCount: anchorByRootId.size },
@@ -2668,6 +2680,80 @@ export class MessageModel {
}));
};
+ /**
+ * List the tool/plugin rows produced by ONE agent operation, for the
+ * per-operation file-edit scan.
+ *
+ * An operation has no direct foreign key on `message_plugins`, so its rows are
+ * bracketed two ways, OR-ed together:
+ * 1. Time window — same `topicId` + `threadId`, with the owning message's
+ * `createdAt` inside `[startedAt, completedAt]` (`completedAt` falls back to
+ * now for an op still finalizing). The primary path for in-process runs.
+ * 2. Heterogeneous match — the message carries
+ * `metadata.heterogeneousToolStateOperationId === operationId` directly,
+ * which a CLI-backed run stamps regardless of when the row lands. Mirrors
+ * the jsonb predicate in {@link findVerifyMessageByOperationId}.
+ *
+ * TRADE-OFF (v1): the time window is racy — two operations running
+ * concurrently in the SAME topic+thread can bleed each other's tool calls into
+ * the window. Accepted for now; the heterogeneous path is exact where it
+ * applies. Rows carry `createdAt` so the caller can globally order tool calls
+ * merged across an operation tree before folding them.
+ */
+ listMessagePluginsForOperation = async (params: {
+ completedAt?: Date | null;
+ operationId: string;
+ startedAt: Date;
+ threadId?: string | null;
+ topicId: string;
+ }): Promise<Array<MessagePluginItem & { createdAt: Date }>> => {
+ const completedAt = params.completedAt ?? new Date();
+
+ const withinWindow = and(
+ eq(messages.topicId, params.topicId),
+ params.threadId ? eq(messages.threadId, params.threadId) : isNull(messages.threadId),
+ gte(messages.createdAt, params.startedAt),
+ lte(messages.createdAt, completedAt),
+ );
+
+ const heterogeneousMatch = sql`${messages.metadata}->>'heterogeneousToolStateOperationId' = ${params.operationId}`;
+
+ const rows = await this.db
+ .select({
+ apiName: messagePlugins.apiName,
+ arguments: messagePlugins.arguments,
+ clientId: messagePlugins.clientId,
+ 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(this.ownership(), this.pluginsOwnership(), or(withinWindow, heterogeneousMatch)))
+ .orderBy(asc(messages.createdAt), asc(messages.id));
+
+ return rows.map((row) => ({
+ apiName: row.apiName ?? undefined,
+ arguments: row.arguments ?? undefined,
+ clientId: row.clientId ?? 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,
+ }));
+ };
+
/**
* Update tool message with content, metadata, pluginState, and pluginError in a single transaction
* This prevents race conditions when updating multiple fields
diff --git a/packages/database/src/models/work/__tests__/file.test.ts b/packages/database/src/models/work/__tests__/file.test.ts
new file mode 100644
index 00000000000..fc270d89ca7
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/file.test.ts
@@ -0,0 +1,161 @@
+// @vitest-environment node
+import type { RegisterFileWorkParams } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { works } from '../../../schemas';
+import { WorkModel } from '..';
+import {
+ agentId,
+ cleanupWorkTestData,
+ seedWorkTestData,
+ serverDB,
+ threadId,
+ topicId,
+ userId,
+ userId2,
+} from './_fixtures';
+
+beforeEach(seedWorkTestData);
+afterEach(cleanupWorkTestData);
+
+const baseFileParams = (
+ overrides: Partial<RegisterFileWorkParams> = {},
+): RegisterFileWorkParams => ({
+ agentId,
+ filePath: '/mnt/data/deck.pptx',
+ metadata: {
+ fileId: 'file-123',
+ filePath: '/mnt/data/deck.pptx',
+ fileSize: 2048,
+ fileUrl: 'https://cdn.example.com/deck.pptx',
+ linesAdded: 0,
+ linesDeleted: 0,
+ mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ },
+ rootOperationId: 'op-file-1',
+ threadId,
+ title: 'deck.pptx',
+ toolCallId: 'op:op-file-1',
+ toolIdentifier: 'lobe-cloud-sandbox',
+ toolName: 'writeFile',
+ topicId,
+ userId,
+ ...overrides,
+});
+
+describe('WorkModel · file', () => {
+ it('keys resource identity on userId:topicId:filePath and denormalizes path + url', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+
+ const work = await workModel.registerFile(baseFileParams());
+
+ expect(work).toMatchObject({
+ // The sandbox is per user+topic, so the resource id carries the user.
+ resourceId: `${userId}:${topicId}:/mnt/data/deck.pptx`,
+ resourceType: 'file',
+ type: 'file',
+ visibility: 'private',
+ });
+ // Denormalized display columns so list rows render without version metadata.
+ expect(work.title).toBe('deck.pptx');
+ expect(work.description).toBe('/mnt/data/deck.pptx');
+ expect(work.url).toBe('https://cdn.example.com/deck.pptx');
+ // `identifier` is denormalized to the basename (the file's "human reference")
+ // so the sidebar's fallback label shows the filename, not the internal
+ // `resourceId` (`userId:topicId:filePath`).
+ expect(work.identifier).toBe('deck.pptx');
+
+ const versions = await workModel.listVersions(work.id);
+ expect(versions).toHaveLength(1);
+ expect(versions[0]).toMatchObject({
+ changeType: 'created',
+ description: '/mnt/data/deck.pptx',
+ // The basename identifier is stamped on the version row too.
+ identifier: 'deck.pptx',
+ metadata: { fileId: 'file-123', filePath: '/mnt/data/deck.pptx' },
+ title: 'deck.pptx',
+ toolCallId: 'op:op-file-1',
+ });
+ });
+
+ it('adds a version to the same Work when the file is re-edited in a later operation', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+
+ const first = await workModel.registerFile(baseFileParams());
+ const second = await workModel.registerFile(
+ baseFileParams({ rootOperationId: 'op-file-2', toolCallId: 'op:op-file-2' }),
+ );
+
+ expect(second.id).toBe(first.id);
+
+ const rows = await serverDB.select().from(works);
+ expect(rows).toHaveLength(1);
+
+ const versions = await workModel.listVersions(first.id);
+ expect(versions.map((v) => v.version)).toEqual([2, 1]);
+ // A later registration is `updated`, not `created`.
+ expect(versions[0].changeType).toBe('updated');
+ });
+
+ it('does not collide across users editing the same path in a shared topic', async () => {
+ const ownerWorks = new WorkModel(serverDB, userId);
+ const memberWorks = new WorkModel(serverDB, userId2);
+
+ const ownerWork = await ownerWorks.registerFile(baseFileParams());
+ // Member B registers the same path — distinct resource identity via userId,
+ // so it must create a SEPARATE Work rather than clash on the workspace
+ // unique index (which does not include userId).
+ const memberWork = await memberWorks.registerFile(
+ baseFileParams({ agentId: undefined, userId: userId2 }),
+ );
+
+ expect(memberWork.id).not.toBe(ownerWork.id);
+ expect(memberWork.resourceId).toBe(`${userId2}:${topicId}:/mnt/data/deck.pptx`);
+
+ const rows = await serverDB.select().from(works);
+ expect(rows).toHaveLength(2);
+ });
+
+ describe('findFileVersionByToolCall', () => {
+ it('returns the version once a (op) registration exists, null before', async () => {
+ const workModel = new WorkModel(serverDB, userId);
+
+ const probeParams = {
+ filePath: '/mnt/data/deck.pptx',
+ toolCallId: 'op:op-file-1',
+ topicId,
+ userId,
+ };
+
+ expect(await workModel.findFileVersionByToolCall(probeParams)).toBeNull();
+
+ await workModel.registerFile(baseFileParams());
+
+ const found = await workModel.findFileVersionByToolCall(probeParams);
+ expect(found).not.toBeNull();
+ expect(typeof found?.id).toBe('string');
+
+ // A different operation's dedup key has no version yet.
+ expect(
+ await workModel.findFileVersionByToolCall({ ...probeParams, toolCallId: 'op:op-file-2' }),
+ ).toBeNull();
+ });
+
+ it('is scoped to the owning user', async () => {
+ const ownerWorks = new WorkModel(serverDB, userId);
+ const memberWorks = new WorkModel(serverDB, userId2);
+
+ await ownerWorks.registerFile(baseFileParams());
+
+ // Member B probing with their own userId resolves a different resourceId.
+ expect(
+ await memberWorks.findFileVersionByToolCall({
+ filePath: '/mnt/data/deck.pptx',
+ toolCallId: 'op:op-file-1',
+ topicId,
+ userId: userId2,
+ }),
+ ).toBeNull();
+ });
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/queries.test.ts b/packages/database/src/models/work/__tests__/queries.test.ts
index f003252b842..db507c3991e 100644
--- a/packages/database/src/models/work/__tests__/queries.test.ts
+++ b/packages/database/src/models/work/__tests__/queries.test.ts
@@ -86,13 +86,16 @@ describe('WorkModel · queries', () => {
const selectSpy = vi.spyOn(serverDB, 'select');
try {
+ // Opt in so the fan-out covers every registered type (default excludes the
+ // gated `file` type — see the includeFileWorks gating test below).
const byOperations = await workModel.listByRootOperations({
+ includeFileWorks: true,
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);
+ // One query per work type across all ids, not per (id x type). Four
+ // registered types now: document / external / file / task.
+ expect(selectSpy).toHaveBeenCalledTimes(4);
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([]);
@@ -370,4 +373,74 @@ describe('WorkModel · queries', () => {
const [stored] = await serverDB.select().from(works).where(eq(works.id, row.id));
expect(stored.resourceId).toBeNull();
});
+
+ it('gates the file work type behind the includeFileWorks opt-in', async () => {
+ // Regression for the deployed-client skew: requests WITHOUT the opt-in must
+ // never see `file` works (old clients whose descriptor table lacks `file`
+ // crash on them); opted-in requests receive every type.
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+
+ const task = await taskModel.create({ instruction: 'Legacy task', name: 'Legacy task' });
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-gate',
+ taskId: task.id,
+ toolCallId: 'gate-task-call',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ topicId,
+ });
+ // No threadId: the version's threadId stays null so the default (no-thread)
+ // conversation query surfaces it alongside the task work.
+ await workModel.registerFile({
+ agentId,
+ filePath: '/mnt/data/report.pptx',
+ metadata: {
+ fileId: 'file-gate',
+ filePath: '/mnt/data/report.pptx',
+ fileUrl: 'https://cdn.example.com/report.pptx',
+ },
+ rootOperationId: 'op-gate',
+ title: 'report.pptx',
+ toolCallId: 'op:op-gate',
+ toolIdentifier: 'lobe-cloud-sandbox',
+ toolName: 'writeFile',
+ topicId,
+ userId,
+ });
+
+ const types = (items: { type: string }[]) => items.map((item) => item.type).sort();
+
+ // Default request → legacy set only.
+ const defaultEvents = await workModel.listByRootOperations({ rootOperationIds: ['op-gate'] });
+ expect(types(defaultEvents['op-gate'])).toEqual(['task']);
+ const defaultSummaries = await workModel.listSummariesByRootOperations({
+ rootOperationIds: ['op-gate'],
+ });
+ expect(types(defaultSummaries['op-gate'])).toEqual(['task']);
+ const defaultConversation = await workModel.listByConversation({ topicId });
+ expect(types(defaultConversation)).toEqual(['task']);
+ const defaultWorkspace = await workModel.listByWorkspace({});
+ expect(types(defaultWorkspace.items)).toEqual(['task']);
+
+ // Opted-in request → both types surface.
+ const optedEvents = await workModel.listByRootOperations({
+ includeFileWorks: true,
+ rootOperationIds: ['op-gate'],
+ });
+ expect(types(optedEvents['op-gate'])).toEqual(['file', 'task']);
+ const optedSummaries = await workModel.listSummariesByRootOperations({
+ includeFileWorks: true,
+ rootOperationIds: ['op-gate'],
+ });
+ expect(types(optedSummaries['op-gate'])).toEqual(['file', 'task']);
+ const optedConversation = await workModel.listByConversation({
+ includeFileWorks: true,
+ topicId,
+ });
+ expect(types(optedConversation)).toEqual(['file', 'task']);
+ const optedWorkspace = await workModel.listByWorkspace({ includeFileWorks: true });
+ expect(types(optedWorkspace.items)).toEqual(['file', 'task']);
+ });
});
diff --git a/packages/database/src/models/work/file.ts b/packages/database/src/models/work/file.ts
new file mode 100644
index 00000000000..d4b66c5c068
--- /dev/null
+++ b/packages/database/src/models/work/file.ts
@@ -0,0 +1,149 @@
+import type { RegisterFileWorkParams, WorkItem } from '@lobechat/types';
+import { and, eq } from 'drizzle-orm';
+
+import { works, workVersions } from '../../schemas/work';
+import { type WorkContext, workOwnership } from './context';
+import { createDisplayWorkAdapter } from './displayWork';
+import { registerWorkVersion } from './writes';
+
+/**
+ * File Works are fully display-backed (like document / external): their list
+ * and summary rows come straight from the `works` display columns, with the
+ * per-version file identity carried in the version `metadata`. No live table
+ * join, so the shared display adapter covers every query path.
+ *
+ * Registration (turning an operation's edited entity files into file Works) is
+ * wired by the server-side consumer; this adapter only serves the read side.
+ */
+export const fileWorkAdapter = createDisplayWorkAdapter({ type: 'file' });
+
+/**
+ * Resource identity of a `file` Work: `${userId}:${topicId}:${filePath}`.
+ *
+ * The sandbox a file is edited in is derived per (userId, topicId), so a file's
+ * identity intrinsically includes its owning user. `userId` is part of the key
+ * (not just the ownership predicate) because the workspace unique index is
+ * `(workspaceId, resourceType, resourceId)` — it does NOT include userId. In a
+ * shared topic, two members editing a same-named path would otherwise collide on
+ * one private Work that only the first registrant can resolve.
+ */
+export const fileWorkResourceId = (userId: string, topicId: string, filePath: string): string =>
+ `${userId}:${topicId}:${filePath}`;
+
+/**
+ * Last path segment of a file path, tolerating either separator (`/` or `\`) and
+ * a trailing slash; '' when the path has no usable segment. Mirrors the
+ * builtin-tools `getBasename` without pulling that package into the DB layer —
+ * used to denormalize the `identifier` display column (see {@link registerFileWork}).
+ */
+const fileBasename = (filePath: string): string =>
+ filePath.replaceAll('\\', '/').split('/').findLast(Boolean)?.trim() ?? '';
+
+/**
+ * Existence probe for the one-version-per-operation dedup key (`op:${operationId}`).
+ * Resolves the file Work by its resource identity and checks for a version with
+ * the given `toolCallId` in a SINGLE joined query, so the server-side consumer
+ * can short-circuit BEFORE re-exporting/uploading the file on a retry (the
+ * export overwrites the object and the register would otherwise leave an orphan
+ * file record). Returns the matching version id, or null when none exists.
+ */
+export const findFileWorkVersionByToolCall = async (
+ ctx: WorkContext,
+ params: { filePath: string; toolCallId: string; topicId: string; userId: string },
+): Promise<{ id: string } | null> => {
+ const resourceId = fileWorkResourceId(params.userId, params.topicId, params.filePath);
+
+ const [version] = await ctx.db
+ .select({ id: workVersions.id })
+ .from(workVersions)
+ .innerJoin(works, eq(works.id, workVersions.workId))
+ .where(
+ and(
+ workOwnership(ctx),
+ eq(works.resourceType, 'file'),
+ eq(works.resourceId, resourceId),
+ eq(workVersions.toolCallId, params.toolCallId),
+ ),
+ )
+ .limit(1);
+
+ return version ?? null;
+};
+
+/**
+ * Register an entity file edited during an operation as a `file` Work.
+ *
+ * Identity: `resourceId = ${userId}:${topicId}:${filePath}` (see
+ * {@link fileWorkResourceId}), so re-editing the same file in a later operation
+ * adds a new version to the same Work. `changeType` is derived here from whether
+ * that Work already exists — a first registration is `created`, any later one
+ * `updated`.
+ *
+ * The existence probe is a best-effort read OUTSIDE the version transaction, so
+ * a rare concurrent first-registration race could mislabel one row's
+ * `changeType`; the version write itself stays correct regardless (the
+ * `(workId, toolCallId)` unique guard inside {@link registerWorkVersion} makes a
+ * same-operation retry idempotent).
+ *
+ * The denormalized `description` (file path) and `url` (uploaded file URL)
+ * display columns are written alongside the basename `title` so list consumers
+ * (Working Sidebar / Gallery) can render the path and open the file without
+ * expanding the version metadata.
+ */
+export const registerFileWork = async (
+ ctx: WorkContext,
+ params: RegisterFileWorkParams,
+): Promise<WorkItem> => {
+ const resourceId = fileWorkResourceId(params.userId, params.topicId, params.filePath);
+
+ const [existing] = await ctx.db
+ .select({ id: works.id })
+ .from(works)
+ .where(
+ and(workOwnership(ctx), eq(works.resourceType, 'file'), eq(works.resourceId, resourceId)),
+ )
+ .limit(1);
+
+ const changeType = existing ? 'updated' : 'created';
+
+ return registerWorkVersion(
+ ctx,
+ {
+ resourceId,
+ resourceType: 'file',
+ type: 'file',
+ userId: params.userId,
+ visibility: params.visibility ?? 'private',
+ },
+ {
+ agentId: params.agentId,
+ changeType,
+ cumulativeCost: params.cumulativeCost,
+ cumulativeUsage: params.cumulativeUsage,
+ messageId: params.messageId,
+ rootOperationId: params.rootOperationId,
+ threadId: params.threadId,
+ toolCallId: params.toolCallId,
+ toolIdentifier: params.toolIdentifier,
+ toolName: params.toolName,
+ topicId: params.topicId,
+ },
+ () => ({
+ // Layer-3 `content` stays null — the file itself is the deliverable,
+ // opened via the metadata fileUrl; the card only needs its basename.
+ // `description`/`url` are denormalized so list rows (which don't carry
+ // version metadata) can still show the path and an open target.
+ // `identifier` is denormalized to the file's basename (its "human
+ // reference", written to both the works row and the version row) so the
+ // sidebar's fallback label renders the filename instead of leaking the
+ // internal `resourceId` (`userId:topicId:filePath`).
+ display: {
+ description: params.filePath,
+ identifier: fileBasename(params.filePath) || null,
+ title: params.title,
+ url: params.metadata.fileUrl ?? null,
+ },
+ metadata: params.metadata,
+ }),
+ );
+};
diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.ts
index e71bc8846e8..586b2c45efe 100644
--- a/packages/database/src/models/work/index.ts
+++ b/packages/database/src/models/work/index.ts
@@ -4,6 +4,7 @@ import {
isWorkSkillProvider,
type RegisterDocumentWorkParams,
type RegisterExternalWorkParams,
+ type RegisterFileWorkParams,
type RegisterSkillToolResultWorkParams,
type RegisterTaskWorkParams,
type SkillToolResultWorkInput,
@@ -15,6 +16,7 @@ import type { LobeChatDatabase } from '../../type';
import type { WorkContext } from './context';
import { registerDocumentWork } from './document';
import { registerExternalWork } from './external';
+import { findFileWorkVersionByToolCall, registerFileWork } from './file';
import { normalizeGithubToolResult } from './githubToolResult';
import { normalizeLinearToolResult } from './linearToolResult';
import * as queries from './queries';
@@ -58,6 +60,21 @@ export class WorkModel {
registerExternal = (params: RegisterExternalWorkParams): Promise<WorkItem | null> =>
registerExternalWork(this.ctx, params);
+ registerFile = (params: RegisterFileWorkParams): Promise<WorkItem> =>
+ registerFileWork(this.ctx, params);
+
+ /**
+ * Existence probe for a file Work's one-version-per-operation dedup key, so
+ * the server consumer can skip a redundant export/upload on a retry. See
+ * {@link findFileWorkVersionByToolCall}.
+ */
+ findFileVersionByToolCall = (params: {
+ filePath: string;
+ toolCallId: string;
+ topicId: string;
+ userId: string;
+ }): Promise<{ id: string } | null> => findFileWorkVersionByToolCall(this.ctx, params);
+
handleSkillToolResult = async (
params: RegisterSkillToolResultWorkParams,
): Promise<WorkItem | null> => {
@@ -78,18 +95,26 @@ export class WorkModel {
deleteTaskWork = (params: DeleteTaskWorkParams): Promise<void> =>
writes.deleteTaskWork(this.ctx, params);
- listByRootOperation = (params: { limit?: number; rootOperationId?: string | null }) =>
- queries.listByRootOperation(this.ctx, params);
+ listByRootOperation = (params: {
+ includeFileWorks?: boolean;
+ limit?: number;
+ rootOperationId?: string | null;
+ }) => queries.listByRootOperation(this.ctx, params);
- listByRootOperations = (params: { limit?: number; rootOperationIds?: string[] | null }) =>
- queries.listByRootOperations(this.ctx, params);
+ listByRootOperations = (params: {
+ includeFileWorks?: boolean;
+ limit?: number;
+ rootOperationIds?: string[] | null;
+ }) => queries.listByRootOperations(this.ctx, params);
listSummariesByRootOperations = (params: {
+ includeFileWorks?: boolean;
limit?: number;
rootOperationIds?: string[] | null;
}) => queries.listSummariesByRootOperations(this.ctx, params);
listByConversation = (params: {
+ includeFileWorks?: boolean;
limit?: number;
threadId?: string | null;
topicId?: string | null;
diff --git a/packages/database/src/models/work/internal.ts b/packages/database/src/models/work/internal.ts
index baaea741ee6..883e450277f 100644
--- a/packages/database/src/models/work/internal.ts
+++ b/packages/database/src/models/work/internal.ts
@@ -180,7 +180,7 @@ export interface TaskWorkSummaryQueryRow {
* 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';
+export type DisplayWorkType = 'document' | 'external' | 'file';
/** Version-event row for display-backed types (each mutation event, no live join). */
export interface DisplayVersionEventRow {
diff --git a/packages/database/src/models/work/queries.ts b/packages/database/src/models/work/queries.ts
index 26f64caed35..2eb9990783b 100644
--- a/packages/database/src/models/work/queries.ts
+++ b/packages/database/src/models/work/queries.ts
@@ -25,7 +25,12 @@ import {
currentWorkListFields,
taskSummaryJoin,
} from './internal';
-import { WORK_TYPE_ADAPTERS, workTypeAdapters } from './registry';
+import {
+ resolveAllowedWorkTypes,
+ resolveWorkTypeAdapters,
+ WORK_TYPE_ADAPTERS,
+ workTypeAdapters,
+} from './registry';
/**
* Conversation queries still fan out once per registered Work type, then
@@ -43,6 +48,8 @@ const MAX_SUMMARY_ROW_LIMIT = 1000;
export const listByRootOperation = async (
ctx: WorkContext,
params: {
+ /** Opt-in gate for the `file` work type; see {@link resolveAllowedWorkTypes}. */
+ includeFileWorks?: boolean;
limit?: number;
rootOperationId?: string | null;
},
@@ -50,6 +57,7 @@ export const listByRootOperation = async (
if (!params.rootOperationId) return [];
const map = await listByRootOperations(ctx, {
+ includeFileWorks: params.includeFileWorks,
limit: params.limit,
rootOperationIds: [params.rootOperationId],
});
@@ -60,6 +68,8 @@ export const listByRootOperation = async (
export const listByRootOperations = async (
ctx: WorkContext,
params: {
+ /** Opt-in gate for the `file` work type; see {@link resolveAllowedWorkTypes}. */
+ includeFileWorks?: boolean;
limit?: number;
rootOperationIds?: string[] | null;
},
@@ -80,7 +90,9 @@ export const listByRootOperations = async (
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)),
+ resolveWorkTypeAdapters(params.includeFileWorks).map((adapter) =>
+ adapter.listVersionEvents(ctx, filters, rowLimit),
+ ),
);
const items = itemsByType
@@ -100,6 +112,8 @@ export const listByRootOperations = async (
export const listSummariesByRootOperations = async (
ctx: WorkContext,
params: {
+ /** Opt-in gate for the `file` work type; see {@link resolveAllowedWorkTypes}. */
+ includeFileWorks?: boolean;
limit?: number;
rootOperationIds?: string[] | null;
},
@@ -127,7 +141,14 @@ export const listSummariesByRootOperations = async (
})
.from(workVersions)
.innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))
- .where(inArray(workVersions.rootOperationId, rootOperationIds))
+ // Gate `file` works out of the anchor set for un-opted-in requests, so a
+ // gated type can never anchor a summary card (see resolveAllowedWorkTypes).
+ .where(
+ and(
+ inArray(workVersions.rootOperationId, rootOperationIds),
+ inArray(works.type, resolveAllowedWorkTypes(params.includeFileWorks)),
+ ),
+ )
.orderBy(desc(workVersions.createdAt))
.limit(rowLimit);
@@ -177,6 +198,8 @@ export const listSummariesByRootOperations = async (
export const listByConversation = async (
ctx: WorkContext,
params: {
+ /** Opt-in gate for the `file` work type; see {@link resolveAllowedWorkTypes}. */
+ includeFileWorks?: boolean;
limit?: number;
threadId?: string | null;
topicId?: string | null;
@@ -190,7 +213,7 @@ export const listByConversation = async (
: isNull(workVersions.threadId);
const rowsByType = await Promise.all(
- workTypeAdapters.map((adapter) =>
+ resolveWorkTypeAdapters(params.includeFileWorks).map((adapter) =>
adapter.listConversationRows(ctx, {
rowLimit: limit * WORK_TYPE_COUNT,
threadFilter,
@@ -234,6 +257,8 @@ const WORKSPACE_WORK_LIMIT = 30;
export interface ListByWorkspaceParams {
cursor?: string | null;
+ /** Opt-in gate for the `file` work type; see {@link resolveAllowedWorkTypes}. */
+ includeFileWorks?: boolean;
limit?: number;
/** Narrow the `external` type to a single skill provider's resource types. */
provider?: WorkSkillProvider | null;
@@ -284,7 +309,12 @@ export const listByWorkspace = async (
): Promise<WorkSummaryPage> => {
const limit = params.limit ?? WORKSPACE_WORK_LIMIT;
- const filters: SQL[] = [workOwnership(ctx)];
+ const filters: SQL[] = [
+ workOwnership(ctx),
+ // Row-level gate: un-opted-in requests never see `file` works, even in the
+ // combined (no `type`) view (see resolveAllowedWorkTypes).
+ inArray(works.type, resolveAllowedWorkTypes(params.includeFileWorks)),
+ ];
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.
diff --git a/packages/database/src/models/work/registry.ts b/packages/database/src/models/work/registry.ts
index 5e65692c041..ef8b4162c8b 100644
--- a/packages/database/src/models/work/registry.ts
+++ b/packages/database/src/models/work/registry.ts
@@ -2,6 +2,7 @@ import type { WorkType } from '@lobechat/types';
import { documentWorkAdapter } from './document';
import { externalWorkAdapter } from './external';
+import { fileWorkAdapter } from './file';
import type { WorkTypeAdapter } from './internal';
import { taskWorkAdapter } from './task';
@@ -14,6 +15,7 @@ import { taskWorkAdapter } from './task';
export const WORK_TYPE_ADAPTERS = {
document: documentWorkAdapter,
external: externalWorkAdapter,
+ file: fileWorkAdapter,
task: taskWorkAdapter,
} satisfies Record<WorkType, WorkTypeAdapter>;
@@ -21,3 +23,29 @@ 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[];
+
+/**
+ * Work types gated behind an explicit client opt-in on the read path. `file` was
+ * added after most clients shipped (Electron updates lag weeks): their bundled
+ * descriptor table has no `file` entry, so a `file` work in the payload makes the
+ * works UI look it up, get `undefined`, and throw on `descriptor.getIcon`. A
+ * request that does not opt in therefore receives the pre-`file` set, keeping
+ * every already-deployed client byte-identically safe; new clients opt in.
+ */
+const OPT_IN_WORK_TYPES = new Set<WorkType>(['file']);
+
+/** The pre-`file` type set every already-deployed client is known to render. */
+export const LEGACY_WORK_TYPES = WORK_TYPES.filter((type) => !OPT_IN_WORK_TYPES.has(type));
+
+/**
+ * Resolve the Work types a read request may return. Absent opt-in → the legacy
+ * set (the read-path chokepoint that preserves old clients); opt-in → every
+ * registered type. Used both for SQL row-level gating and to derive the adapter
+ * fan-out below.
+ */
+export const resolveAllowedWorkTypes = (includeFileWorks?: boolean): WorkType[] =>
+ includeFileWorks ? WORK_TYPES : LEGACY_WORK_TYPES;
+
+/** Adapter fan-out list narrowed to the types the request is allowed to return. */
+export const resolveWorkTypeAdapters = (includeFileWorks?: boolean): WorkTypeAdapter[] =>
+ resolveAllowedWorkTypes(includeFileWorks).map((type) => WORK_TYPE_ADAPTERS[type]);
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 8bf5b220837..148e197e9bf 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -197,6 +197,8 @@ export default {
'duplicateSession.success': 'Copy successful',
'duplicateSession.title': '{{title}} Copy',
'duplicateTitle': '{{title}} Copy',
+ 'editedFiles.title_one': 'Edited {{count}} file',
+ 'editedFiles.title_other': 'Edited {{count}} files',
'emptyAgent': 'No Agents yet. Start with your first Agent—build your system over time.',
'emptyAgentAction': 'Create Agent',
'extendParams.disableContextCaching.desc':
diff --git a/packages/shared-tool-ui/src/components/FileChangeStats/index.tsx b/packages/shared-tool-ui/src/components/FileChangeStats/index.tsx
new file mode 100644
index 00000000000..20d8c00ed28
--- /dev/null
+++ b/packages/shared-tool-ui/src/components/FileChangeStats/index.tsx
@@ -0,0 +1,110 @@
+'use client';
+
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { memo } from 'react';
+
+/**
+ * Shared UI primitives for rendering a file change (a colored kind dot + a
+ * `+added -deleted` line-stat pill) plus the path helpers they need. Downed here
+ * from the codex `FileChangeRender` and the conversation `EditedFilesCard`, which
+ * both consume this package, so the two stop hand-rolling the same styles.
+ */
+
+/** Change kind shared by the codex file-change and edited-files renderers. */
+export type FileChangeKind = 'added' | 'deleted' | 'modified' | 'renamed';
+
+const styles = createStaticStyles(({ css }) => ({
+ kindAdded: css`
+ background: ${cssVar.colorSuccess};
+ `,
+ kindDeleted: css`
+ background: ${cssVar.colorError};
+ `,
+ kindDot: css`
+ flex-shrink: 0;
+ width: 8px;
+ height: 8px;
+ border-radius: 999px;
+ `,
+ kindModified: css`
+ background: ${cssVar.colorInfo};
+ `,
+ kindRenamed: css`
+ background: ${cssVar.colorWarning};
+ `,
+ lineAdded: css`
+ color: ${cssVar.colorSuccess};
+ `,
+ lineDeleted: css`
+ color: ${cssVar.colorError};
+ `,
+ lineStats: css`
+ display: inline-flex;
+ flex-shrink: 0;
+ gap: 6px;
+ align-items: center;
+
+ font-size: 12px;
+ `,
+}));
+
+const KIND_CLASS: Record<FileChangeKind, string> = {
+ added: styles.kindAdded,
+ deleted: styles.kindDeleted,
+ modified: styles.kindModified,
+ renamed: styles.kindRenamed,
+};
+
+/** A small color-coded dot indicating a file's change kind. */
+export const KindDot = memo<{ className?: string; kind: FileChangeKind }>(({ className, kind }) => (
+ <span className={cx(styles.kindDot, KIND_CLASS[kind], className)} />
+));
+KindDot.displayName = 'FileChangeKindDot';
+
+interface LineStatsProps {
+ className?: string;
+ /**
+ * When set, a zero side is hidden individually (only render `+N` when N > 0
+ * and `-M` when M > 0). Default renders both sides whenever either is non-zero.
+ */
+ hideZeroDeltas?: boolean;
+ linesAdded?: number;
+ linesDeleted?: number;
+}
+
+/** A `+added -deleted` git-diff-stat pill; renders nothing when both are zero. */
+export const LineStats = memo<LineStatsProps>(
+ ({ className, hideZeroDeltas, linesAdded = 0, linesDeleted = 0 }) => {
+ if (linesAdded === 0 && linesDeleted === 0) return null;
+
+ const showAdded = !hideZeroDeltas || linesAdded > 0;
+ const showDeleted = !hideZeroDeltas || linesDeleted > 0;
+
+ return (
+ <span className={cx(styles.lineStats, className)}>
+ {showAdded && <span className={styles.lineAdded}>+{linesAdded}</span>}
+ {showDeleted && <span className={styles.lineDeleted}>-{linesDeleted}</span>}
+ </span>
+ );
+ },
+);
+LineStats.displayName = 'FileChangeLineStats';
+
+/** Display file name: the last non-empty path segment, falling back to the input. */
+export const getFileName = (filePath: string): string => {
+ if (!filePath) return '';
+ const normalized = filePath.replaceAll('\\', '/');
+ return normalized.split('/').findLast(Boolean) || filePath;
+};
+
+/**
+ * Best-effort language hint (lowercased extension) for syntax highlighting a
+ * file's diff, or undefined when there is none. A leading-dot dotfile with no
+ * real extension (e.g. `.env`) has no language.
+ */
+export const getFileLanguage = (filePath: string): string | undefined => {
+ const fileName = getFileName(filePath);
+ const index = fileName.lastIndexOf('.');
+ if (index <= 0 || index === fileName.length - 1) return undefined;
+ return fileName.slice(index + 1).toLowerCase();
+};
diff --git a/packages/shared-tool-ui/src/components/index.ts b/packages/shared-tool-ui/src/components/index.ts
index fc2e1ec8c0b..5cd3370b96a 100644
--- a/packages/shared-tool-ui/src/components/index.ts
+++ b/packages/shared-tool-ui/src/components/index.ts
@@ -1,3 +1,10 @@
export { AnimatedNumber } from './AnimatedNumber';
+export {
+ type FileChangeKind,
+ getFileLanguage,
+ getFileName,
+ KindDot,
+ LineStats,
+} from './FileChangeStats';
export { FilePathDisplay } from './FilePathDisplay';
export { OptionCard, type OptionCardProps } from './OptionCard';
diff --git a/packages/types/src/message/db/params.ts b/packages/types/src/message/db/params.ts
index d04b86b31d3..d47b2e1f6f0 100644
--- a/packages/types/src/message/db/params.ts
+++ b/packages/types/src/message/db/params.ts
@@ -26,6 +26,13 @@ export interface QueryMessageParams {
agentId?: string | null;
current?: number;
groupId?: string | null;
+ /**
+ * Opt-in for `file` work summaries embedded in the message payload. Absent →
+ * the legacy set, so already-deployed clients (whose descriptor table lacks
+ * `file`) never receive a `file` summary that would crash their works UI. New
+ * clients set it. Ignored when `skipWorks` is set.
+ */
+ includeFileWorks?: boolean;
pageSize?: number;
sessionId?: string | null;
/**
diff --git a/packages/types/src/work.ts b/packages/types/src/work.ts
index c307f96b5ed..151615546dd 100644
--- a/packages/types/src/work.ts
+++ b/packages/types/src/work.ts
@@ -1,11 +1,11 @@
import type { TaskStatus } from './task';
-export type WorkType = 'document' | 'external' | 'task';
+export type WorkType = 'document' | 'external' | 'file' | '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 WorkResourceType = 'document' | ExternalWorkResourceType | 'file' | 'task';
export type WorkVisibility = 'private' | 'public';
/**
* How a version changed the Work. Not derivable from `version === 1`: updating
@@ -25,6 +25,24 @@ export type WorkDisplayField =
export interface WorkVersionMetadata {
agentDocumentId?: string;
+ /**
+ * `file` Work — the edited file's identity in the file store, when the entity
+ * file was persisted. `filePath` is always present for a file Work; the
+ * remaining fields are populated only once the file is registered/uploaded.
+ */
+ fileId?: string;
+ /** `file` Work — the edited file's path within the operation (its resource identity). */
+ filePath?: string;
+ /** `file` Work — size in bytes of the edited file. */
+ fileSize?: number;
+ /** `file` Work — durable, fetchable URL of the persisted file. */
+ fileUrl?: string;
+ /** `file` Work — lines added by this version's edit (0 when the source tool reports none). */
+ linesAdded?: number;
+ /** `file` Work — lines deleted by this version's edit (0 when the source tool reports none). */
+ linesDeleted?: number;
+ /** `file` Work — MIME type of the edited file. */
+ mimeType?: string;
}
export interface WorkVersionCumulativeUsage {
@@ -163,7 +181,21 @@ export interface ExternalWorkListItem extends WorkListBaseItem {
type: 'external';
}
-export type WorkListItem = DocumentWorkListItem | ExternalWorkListItem | TaskWorkListItem;
+/**
+ * A file Work: an entity-format file (pptx/xlsx/docx/pdf, …) edited during an
+ * operation. Its resource identity is `${userId}:${topicId}:${filePath}` (the
+ * sandbox is per user+topic, so file identity intrinsically includes the user).
+ * Its display columns come entirely from the `works` row — the per-version file
+ * identity (path, fileId, url, line deltas) lives in {@link WorkVersionMetadata}.
+ * Fully display-backed like document/external (no live table join).
+ */
+export interface FileWorkListItem extends WorkListBaseItem {
+ resourceType: 'file';
+ type: 'file';
+}
+
+export type WorkListItem =
+ DocumentWorkListItem | ExternalWorkListItem | FileWorkListItem | TaskWorkListItem;
export interface TaskWorkVersionEventItem extends TaskWorkListItem {
version: WorkVersionPreview;
@@ -177,8 +209,15 @@ export interface ExternalWorkVersionEventItem extends ExternalWorkListItem {
version: WorkVersionPreview;
}
+export interface FileWorkVersionEventItem extends FileWorkListItem {
+ version: WorkVersionPreview;
+}
+
export type WorkVersionEventItem =
- DocumentWorkVersionEventItem | ExternalWorkVersionEventItem | TaskWorkVersionEventItem;
+ | DocumentWorkVersionEventItem
+ | ExternalWorkVersionEventItem
+ | FileWorkVersionEventItem
+ | TaskWorkVersionEventItem;
export type WorkVersionEventMap = Record<string, WorkVersionEventItem[]>;
export interface TaskWorkSummaryItem extends TaskWorkListItem {
@@ -199,8 +238,14 @@ export interface ExternalWorkSummaryItem extends ExternalWorkListItem {
version: Pick<WorkVersionItem, 'createdAt' | 'id' | 'version'> | null;
}
+export interface FileWorkSummaryItem extends FileWorkListItem {
+ event: WorkVersionPreview;
+ totalCost: number | null;
+ version: Pick<WorkVersionItem, 'createdAt' | 'id' | 'version'> | null;
+}
+
export type WorkSummaryItem =
- DocumentWorkSummaryItem | ExternalWorkSummaryItem | TaskWorkSummaryItem;
+ DocumentWorkSummaryItem | ExternalWorkSummaryItem | FileWorkSummaryItem | TaskWorkSummaryItem;
export type WorkSummaryMap = Record<string, WorkSummaryItem[]>;
export interface RegisterDocumentWorkParams {
@@ -222,6 +267,43 @@ export interface RegisterDocumentWorkParams {
topicId?: string | null;
}
+/**
+ * Register (or add a version to) a `file` Work — an entity-format file
+ * (pptx/xlsx/docx/pdf, …) edited during an operation. Its resource identity is
+ * `${userId}:${topicId}:${filePath}`, so re-editing the same file in a later
+ * operation adds a version to the same Work. The card shows only the basename
+ * `title`; the per-version file identity (fileId / url / mime / size / line
+ * deltas) rides in {@link WorkVersionMetadata}.
+ *
+ * `changeType` is NOT part of the params: the DB layer derives it from whether
+ * the Work already exists (first registration → `created`, any later one →
+ * `updated`).
+ */
+export interface RegisterFileWorkParams {
+ agentId?: string | null;
+ cumulativeCost?: number | null;
+ cumulativeUsage?: WorkVersionCumulativeUsage | null;
+ /** The edited file's path within the operation — half of the resource identity. */
+ filePath: string;
+ messageId?: string | null;
+ /** Per-version file identity + line deltas persisted into the version metadata. */
+ metadata: WorkVersionMetadata;
+ rootOperationId?: string | null;
+ threadId?: string | null;
+ /** Card title — the edited file's basename. */
+ title: string;
+ /** Dedup key for one-version-per-operation (`op:${operationId}`). */
+ toolCallId?: string | null;
+ /** Tool/plugin identifier that produced this version. */
+ toolIdentifier: string;
+ toolName: string;
+ /** Owning topic; combined with `filePath` into the Work resource identity. */
+ topicId: string;
+ userId: string;
+ /** Defaults to `private` when omitted — edited files are user-private. */
+ visibility?: WorkVisibility;
+}
+
export interface DeleteDocumentWorkParams {
agentDocumentId?: string | null;
agentId?: string | null;
diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsx
index 4f7b282545f..5f0edaa5aa2 100644
--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx
@@ -36,6 +36,8 @@ import {
useSetMessageItemActionElementPortialContext,
useSetMessageItemActionTypeContext,
} from '../Contexts/message-action-context';
+import EditedFilesCard from '../EditedFilesCard';
+import { useOperationEditedFiles } from '../EditedFilesCard/useOperationEditedFiles';
import MessageWorks from '../MessageWorks';
import SignalCallbacks from '../SignalCallbacks';
import FileListViewer from '../User/components/FileListViewer';
@@ -119,6 +121,21 @@ const GroupMessage = memo<GroupMessageProps>(
() => findLatestWorkRootOperationId(metadata, children, taskCompletions),
[children, metadata, taskCompletions],
);
+ // Codex-style aggregate of files edited this round. Purely derived from the
+ // group's tool calls (entity-format files are excluded — they surface as
+ // `file` Works below), so it rides the same afterActions slot as Works.
+ // The card is a turn-end artifact, so skip the scan entirely while the group
+ // (or any child block) is still streaming: `children` changes on every token,
+ // and the finished card is all users see anyway.
+ const isGroupGenerating = useConversationStore(
+ messageStateSelectors.isAssistantGroupItemGenerating(id),
+ );
+ const editedFiles = useOperationEditedFiles(
+ isGroupGenerating ? undefined : children,
+ // The sandbox-entity → Work handoff only happens on server-runtime rounds
+ // (the work anchor marks them); without it the card keeps every entry.
+ !!workRootOperationId,
+ );
const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
const [toggleSystemRole] = useGlobalStore((s) => [s.toggleSystemRole]);
@@ -230,7 +247,18 @@ const GroupMessage = memo<GroupMessageProps>(
)
}
afterActions={
- workRootOperationId ? <MessageWorks rootOperationId={workRootOperationId} /> : undefined
+ // Wrap in a Flexbox only when the edited-files card is present: the
+ // work anchor is stamped on every tool round while `MessageWorks`
+ // renders null when that round has no works, so the wrapper would
+ // otherwise mount as an empty container on plain tool-only turns.
+ editedFiles.length > 0 ? (
+ <Flexbox gap={8}>
+ <EditedFilesCard entries={editedFiles} />
+ {workRootOperationId && <MessageWorks rootOperationId={workRootOperationId} />}
+ </Flexbox>
+ ) : workRootOperationId ? (
+ <MessageWorks rootOperationId={workRootOperationId} />
+ ) : undefined
}
customAvatarRender={
isSupervisor
diff --git a/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.test.ts b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.test.ts
new file mode 100644
index 00000000000..b840544a26c
--- /dev/null
+++ b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.test.ts
@@ -0,0 +1,229 @@
+import type { AssistantContentBlock, ChatToolPayloadWithResult } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ collectFileEditToolCallRecords,
+ deriveOperationEditedFiles,
+ summarizeEditedFilesTotals,
+} from './deriveEditedFiles';
+
+/** Build a display tool payload with a resolved plugin state (result.state). */
+const tool = (
+ partial: Partial<ChatToolPayloadWithResult> & { apiName: string; id: string },
+): ChatToolPayloadWithResult => ({
+ arguments: '{}',
+ identifier: 'lobe-cloud-sandbox',
+ type: 'builtin',
+ ...partial,
+});
+
+const block = (tools: ChatToolPayloadWithResult[]): AssistantContentBlock => ({
+ content: '',
+ id: `block-${Math.random()}`,
+ tools,
+});
+
+const sandboxWrite = (id: string, path: string) =>
+ tool({
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ path }),
+ id,
+ result: { content: '', id: `${id}-r`, state: { path, success: true } },
+ });
+
+const sandboxEdit = (
+ id: string,
+ path: string,
+ deltas: { diffText?: string; linesAdded?: number; linesDeleted?: number } = {},
+) =>
+ tool({
+ apiName: 'editFile',
+ arguments: JSON.stringify({ path }),
+ id,
+ result: { content: '', id: `${id}-r`, state: { path, ...deltas } },
+ });
+
+describe('collectFileEditToolCallRecords', () => {
+ it('flattens block tools into scanner records, surfacing result.state', () => {
+ const records = collectFileEditToolCallRecords([
+ block([sandboxWrite('t1', '/work/a.ts')]),
+ block([sandboxEdit('t2', '/work/a.ts', { linesAdded: 2 })]),
+ ]);
+
+ expect(records).toEqual([
+ {
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ path: '/work/a.ts' }),
+ identifier: 'lobe-cloud-sandbox',
+ state: { path: '/work/a.ts', success: true },
+ toolCallId: 't1',
+ },
+ {
+ apiName: 'editFile',
+ arguments: JSON.stringify({ path: '/work/a.ts' }),
+ identifier: 'lobe-cloud-sandbox',
+ state: { linesAdded: 2, path: '/work/a.ts' },
+ toolCallId: 't2',
+ },
+ ]);
+ });
+
+ it('tolerates empty blocks / tool lists', () => {
+ expect(collectFileEditToolCallRecords([])).toEqual([]);
+ expect(collectFileEditToolCallRecords([block([])])).toEqual([]);
+ });
+
+ // Regression: a tool call with no merged result never executed (pending
+ // human approval, or the run was interrupted first). Forwarding it would let
+ // the scanner fall back to `arguments.path` and show a file as edited that
+ // was never actually written.
+ it('drops tool calls that have no result yet', () => {
+ const records = collectFileEditToolCallRecords([
+ block([
+ tool({ apiName: 'writeFile', arguments: JSON.stringify({ path: '/work/a.ts' }), id: 't1' }),
+ sandboxWrite('t2', '/work/b.ts'),
+ ]),
+ ]);
+
+ expect(records.map((record) => record.toolCallId)).toEqual(['t2']);
+ });
+});
+
+describe('deriveOperationEditedFiles', () => {
+ it('aggregates multi-file edits across blocks', () => {
+ const entries = deriveOperationEditedFiles([
+ block([sandboxWrite('t1', '/work/a.ts')]),
+ block([
+ sandboxEdit('t2', '/work/a.ts', { diffText: '@@ a', linesAdded: 3, linesDeleted: 1 }),
+ sandboxWrite('t3', '/work/b.ts'),
+ ]),
+ ]);
+
+ expect(entries.map((e) => [e.path, e.kind])).toEqual([
+ ['/work/a.ts', 'added'],
+ ['/work/b.ts', 'added'],
+ ]);
+ // Deltas fold onto the write→edit chain for a.ts.
+ expect(entries[0]).toMatchObject({ diffTexts: ['@@ a'], linesAdded: 3, linesDeleted: 1 });
+ });
+
+ it('drops entity-format files (they surface as file Works) but keeps html + other', () => {
+ const entries = deriveOperationEditedFiles(
+ [
+ block([
+ sandboxWrite('t1', '/work/deck.pptx'),
+ sandboxWrite('t2', '/work/data.xlsx'),
+ sandboxWrite('t3', '/work/report.pdf'),
+ sandboxWrite('t4', '/work/index.html'),
+ sandboxWrite('t5', '/work/notes.md'),
+ ]),
+ ],
+ true,
+ );
+
+ expect(entries.map((e) => e.path)).toEqual(['/work/index.html', '/work/notes.md']);
+ });
+
+ it('keeps sandbox entity files when the round has no work surface (legacy client runtime)', () => {
+ // Without a work anchor no file Work registers, so dropping the entry
+ // would make the file invisible on both surfaces — the card keeps it.
+ const entries = deriveOperationEditedFiles([
+ block([sandboxWrite('t1', '/work/deck.pptx'), sandboxWrite('t2', '/work/notes.md')]),
+ ]);
+
+ expect(entries.map((e) => e.path)).toEqual(['/work/deck.pptx', '/work/notes.md']);
+ });
+
+ it('keeps a hetero-edited entity file in the card (no file Work covers it)', () => {
+ // Registration only exports from the cloud sandbox, so a codex-edited
+ // entity file registers no Work — the card is the only place it can show.
+ const codexCsv = tool({
+ apiName: 'file_change',
+ id: 't2',
+ identifier: 'codex',
+ result: {
+ content: '',
+ id: 't2-r',
+ state: {
+ changes: [{ kind: 'update', linesAdded: 2, linesDeleted: 1, path: '/repo/data.csv' }],
+ },
+ },
+ });
+
+ const entries = deriveOperationEditedFiles(
+ [block([sandboxWrite('t1', '/work/deck.pptx'), codexCsv])],
+ true,
+ );
+
+ expect(entries.map((e) => e.path)).toEqual(['/repo/data.csv']);
+ });
+
+ it('drops an entity file only when its LAST edit is sandbox-backed', () => {
+ // Sandbox writes it, codex re-edits it → the Work provenance rule keys off
+ // the last edit, so no Work registers and the card must keep the file.
+ const codexReEdit = tool({
+ apiName: 'file_change',
+ id: 't2',
+ identifier: 'codex',
+ result: {
+ content: '',
+ id: 't2-r',
+ state: {
+ changes: [{ kind: 'update', linesAdded: 1, linesDeleted: 0, path: '/work/deck.pptx' }],
+ },
+ },
+ });
+
+ const entries = deriveOperationEditedFiles(
+ [block([sandboxWrite('t1', '/work/deck.pptx'), codexReEdit])],
+ true,
+ );
+
+ expect(entries.map((e) => e.path)).toEqual(['/work/deck.pptx']);
+ });
+
+ it('drops a tool call whose result carries an error', () => {
+ const entries = deriveOperationEditedFiles([
+ block([
+ tool({
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ path: '/work/a.ts' }),
+ id: 't1',
+ result: { content: '', error: 'boom', id: 't1-r', state: { path: '/work/a.ts' } },
+ }),
+ ]),
+ ]);
+ expect(entries).toEqual([]);
+ });
+
+ it('returns an empty list when the operation touched no files', () => {
+ expect(deriveOperationEditedFiles([])).toEqual([]);
+ expect(
+ deriveOperationEditedFiles([
+ block([
+ tool({
+ apiName: 'runCommand',
+ id: 't1',
+ result: { content: '', id: 'r', state: { success: true } },
+ }),
+ ]),
+ ]),
+ ).toEqual([]);
+ });
+});
+
+describe('summarizeEditedFilesTotals', () => {
+ it('sums per-file line deltas', () => {
+ const entries = deriveOperationEditedFiles([
+ block([
+ sandboxEdit('t1', '/a.ts', { linesAdded: 3, linesDeleted: 1 }),
+ sandboxEdit('t2', '/b.ts', { linesAdded: 4, linesDeleted: 2 }),
+ ]),
+ ]);
+ expect(summarizeEditedFilesTotals(entries)).toEqual({ linesAdded: 7, linesDeleted: 3 });
+ });
+
+ it('is zero for an empty list', () => {
+ expect(summarizeEditedFilesTotals([])).toEqual({ linesAdded: 0, linesDeleted: 0 });
+ });
+});
diff --git a/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.ts b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.ts
new file mode 100644
index 00000000000..2f4551df5b5
--- /dev/null
+++ b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.ts
@@ -0,0 +1,101 @@
+import {
+ classifyEditedFile,
+ CLOUD_SANDBOX_IDENTIFIER,
+ type EditedFileEntry,
+ type FileEditToolCallRecord,
+ scanOperationFileEdits,
+} from '@lobechat/builtin-tools/fileEditScan';
+import type { AssistantContentBlock } from '@lobechat/types';
+
+/**
+ * Map the display-layer tool payloads of one assistant round into the shared
+ * scanner's record shape. Each `block.tools` entry is a
+ * `ChatToolPayloadWithResult`, so its persisted `pluginState` is surfaced at
+ * `tool.result.state` (see `FlatListBuilder.createAssistantGroupMessage`) — the
+ * exact `state` the scanner reads for sandbox / codex / claude-code edits.
+ */
+export const collectFileEditToolCallRecords = (
+ blocks: AssistantContentBlock[] = [],
+): FileEditToolCallRecord[] =>
+ blocks.flatMap((block) =>
+ (block.tools ?? [])
+ // A tool call with NO merged result never executed (still pending human
+ // approval, or the run was interrupted first) — FlatListBuilder only
+ // attaches `result` once a tool message exists. Without this guard the
+ // scanner would fall back to `arguments.path` for sandbox write/edit
+ // calls and show a file as edited that was never actually written.
+ .filter((tool) => tool.result != null)
+ .map((tool) => ({
+ apiName: tool.apiName,
+ arguments: tool.arguments,
+ // A failed tool call surfaces its error on the merged result, mirroring
+ // the server's `message_plugins.error`; the scanner skips such records.
+ error: tool.result?.error,
+ identifier: tool.identifier,
+ state: tool.result?.state,
+ toolCallId: tool.id,
+ })),
+ );
+
+/**
+ * Derive the aggregated edited-file entries for one operation's "edited N files"
+ * card. Scans every tool call in the assistant group's blocks, then drops
+ * entity-format files (pptx / xlsx / docx / pdf / …) whose last edit is
+ * sandbox-backed — those surface through the `file` Work system (WorksSection /
+ * WorkGallery) instead. An entity file last edited by a hetero source (codex /
+ * claude-code / lobe-local-system / device-routed lobe-skills commands, including
+ * entities detected from shell command text) registers NO file Work (registration
+ * only exports from the cloud sandbox, see server `fileWorkRegistration`), so it
+ * stays in the card — the only place it remains visible. HTML (artifact hosting) and every other file stay in the card
+ * too.
+ *
+ * The sandbox-entity drop only applies when `hasWorkSurface` is true — i.e. the
+ * round carries a work anchor (server-runtime operation), so a `file` Work can
+ * actually exist. Legacy client-runtime rounds have no work registration; for
+ * them the drop would make the file invisible on BOTH surfaces, so entries are
+ * kept in the card instead.
+ *
+ * Purely derived from the message payload already in the store — nothing is
+ * persisted. Callers must memoize on the blocks reference (see
+ * {@link useOperationEditedFiles}) so the scan runs once per snapshot.
+ */
+export const deriveOperationEditedFiles = (
+ blocks: AssistantContentBlock[] = [],
+ hasWorkSurface = false,
+): EditedFileEntry[] => {
+ const records = collectFileEditToolCallRecords(blocks);
+ if (records.length === 0) return [];
+
+ const entries = scanOperationFileEdits(records);
+ if (!hasWorkSurface) return entries;
+
+ const sandboxToolCallIds = new Set(
+ records
+ .filter((record) => record.identifier === CLOUD_SANDBOX_IDENTIFIER)
+ .map((record) => record.toolCallId),
+ );
+
+ return entries.filter((entry) => {
+ if (classifyEditedFile(entry.path).category !== 'entity') return true;
+ // Mirrors the server's provenance rule: a Work version's provenance is the
+ // file's LAST edit, so the card drops the entry only when that edit came
+ // from the sandbox (→ a Work card covers it).
+ const lastSourceToolCallId = entry.sourceToolCallIds.at(-1);
+ return !(lastSourceToolCallId && sandboxToolCallIds.has(lastSourceToolCallId));
+ });
+};
+
+export interface EditedFilesTotals {
+ linesAdded: number;
+ linesDeleted: number;
+}
+
+/** Sum the per-file line deltas for the card's git-diff-stat style header. */
+export const summarizeEditedFilesTotals = (entries: EditedFileEntry[]): EditedFilesTotals =>
+ entries.reduce<EditedFilesTotals>(
+ (totals, entry) => ({
+ linesAdded: totals.linesAdded + entry.linesAdded,
+ linesDeleted: totals.linesDeleted + entry.linesDeleted,
+ }),
+ { linesAdded: 0, linesDeleted: 0 },
+ );
diff --git a/src/features/Conversation/Messages/EditedFilesCard/index.tsx b/src/features/Conversation/Messages/EditedFilesCard/index.tsx
new file mode 100644
index 00000000000..9f369d8c692
--- /dev/null
+++ b/src/features/Conversation/Messages/EditedFilesCard/index.tsx
@@ -0,0 +1,212 @@
+'use client';
+
+import type { EditedFileEntry } from '@lobechat/builtin-tools/fileEditScan';
+import {
+ FilePathDisplay,
+ getFileLanguage,
+ getFileName,
+ KindDot,
+ LineStats,
+} from '@lobechat/shared-tool-ui/components';
+import { Flexbox, PatchDiff, Text } from '@lobehub/ui';
+import { createStaticStyles, cx } from 'antd-style';
+import { ChevronDownIcon, ChevronRightIcon, FilePenLineIcon } from 'lucide-react';
+import { type KeyboardEvent, memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { summarizeEditedFilesTotals } from './deriveEditedFiles';
+
+/** Fire a toggle on Enter/Space so the div-based expander is keyboard operable. */
+const toggleOnKey = (toggle: () => void) => (event: KeyboardEvent<HTMLDivElement>) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ toggle();
+ }
+};
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ card: css`
+ overflow: hidden;
+
+ width: 100%;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+
+ background: ${cssVar.colorBgElevated};
+ `,
+ header: css`
+ cursor: pointer;
+ padding-block: 10px;
+ padding-inline: 12px;
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+ headerIcon: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ chevron: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ title: css`
+ min-width: 0;
+ font-size: 14px;
+ font-weight: 500;
+ `,
+ stats: css`
+ font-weight: 500;
+ `,
+ list: css`
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ row: css`
+ padding-block: 6px;
+ padding-inline: 12px;
+ `,
+ rowMain: css`
+ min-height: 24px;
+ `,
+ rowClickable: css`
+ cursor: pointer;
+ border-radius: 6px;
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+ path: css`
+ overflow: hidden;
+ display: flex;
+ flex: 1;
+ align-items: center;
+
+ min-width: 0;
+ `,
+ patch: css`
+ overflow: hidden;
+ margin-block-start: 6px;
+ padding-inline-start: 18px;
+ `,
+}));
+
+const EditedFileRow = memo<{ entry: EditedFileEntry }>(({ entry }) => {
+ const [expanded, setExpanded] = useState(false);
+ const hasDiff = entry.diffTexts.length > 0;
+ const fileName = getFileName(entry.path);
+ const language = getFileLanguage(entry.path);
+
+ return (
+ <Flexbox className={cx(styles.row, hasDiff && styles.rowClickable)}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ aria-expanded={hasDiff ? expanded : undefined}
+ className={styles.rowMain}
+ gap={10}
+ role={hasDiff ? 'button' : undefined}
+ tabIndex={hasDiff ? 0 : undefined}
+ onClick={hasDiff ? () => setExpanded((prev) => !prev) : undefined}
+ onKeyDown={hasDiff ? toggleOnKey(() => setExpanded((prev) => !prev)) : undefined}
+ >
+ <KindDot kind={entry.kind} />
+ <div className={styles.path}>
+ <FilePathDisplay filePath={entry.path} />
+ </div>
+ <LineStats
+ hideZeroDeltas
+ className={styles.stats}
+ linesAdded={entry.linesAdded}
+ linesDeleted={entry.linesDeleted}
+ />
+ {hasDiff &&
+ (expanded ? (
+ <ChevronDownIcon className={styles.chevron} size={14} />
+ ) : (
+ <ChevronRightIcon className={styles.chevron} size={14} />
+ ))}
+ </Flexbox>
+ {hasDiff && expanded && (
+ <div className={styles.patch}>
+ {entry.diffTexts.map((patch, index) => (
+ <PatchDiff
+ fileName={fileName}
+ key={index}
+ language={language}
+ patch={patch}
+ showHeader={false}
+ variant={'borderless'}
+ viewMode={'unified'}
+ />
+ ))}
+ </div>
+ )}
+ </Flexbox>
+ );
+});
+EditedFileRow.displayName = 'EditedFileRow';
+
+interface EditedFilesCardProps {
+ entries: EditedFileEntry[];
+}
+
+/**
+ * Codex-style aggregate card mounted at the tail of an assistant round: "edited
+ * N files +x -y" with an expandable per-file list. Data is purely derived from
+ * the round's tool calls (see {@link useOperationEditedFiles}) — never persisted.
+ * Renders nothing when the round edited no (non-entity) files.
+ */
+const EditedFilesCard = memo<EditedFilesCardProps>(({ entries }) => {
+ const { t } = useTranslation('chat');
+ const [expanded, setExpanded] = useState(false);
+
+ if (entries.length === 0) return null;
+
+ const totals = summarizeEditedFilesTotals(entries);
+
+ return (
+ <Flexbox className={styles.card}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ aria-expanded={expanded}
+ className={styles.header}
+ gap={8}
+ role={'button'}
+ tabIndex={0}
+ onClick={() => setExpanded((prev) => !prev)}
+ onKeyDown={toggleOnKey(() => setExpanded((prev) => !prev))}
+ >
+ {expanded ? (
+ <ChevronDownIcon className={styles.chevron} size={16} />
+ ) : (
+ <ChevronRightIcon className={styles.chevron} size={16} />
+ )}
+ <FilePenLineIcon className={styles.headerIcon} size={16} />
+ <Text ellipsis className={styles.title}>
+ {t('editedFiles.title', { count: entries.length })}
+ </Text>
+ <Flexbox flex={1} />
+ <LineStats
+ hideZeroDeltas
+ className={styles.stats}
+ linesAdded={totals.linesAdded}
+ linesDeleted={totals.linesDeleted}
+ />
+ </Flexbox>
+ {expanded && (
+ <Flexbox className={styles.list}>
+ {entries.map((entry) => (
+ <EditedFileRow entry={entry} key={entry.path} />
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+EditedFilesCard.displayName = 'EditedFilesCard';
+
+export default EditedFilesCard;
diff --git a/src/features/Conversation/Messages/EditedFilesCard/useOperationEditedFiles.ts b/src/features/Conversation/Messages/EditedFilesCard/useOperationEditedFiles.ts
new file mode 100644
index 00000000000..ebd7cc9d638
--- /dev/null
+++ b/src/features/Conversation/Messages/EditedFilesCard/useOperationEditedFiles.ts
@@ -0,0 +1,27 @@
+import type { EditedFileEntry } from '@lobechat/builtin-tools/fileEditScan';
+import type { AssistantContentBlock } from '@lobechat/types';
+import { useMemo } from 'react';
+
+import { deriveOperationEditedFiles } from './deriveEditedFiles';
+
+/**
+ * Derived, non-persisted list of files edited across one assistant round.
+ *
+ * Pass the assistant group's `children` blocks — the display selector returns a
+ * stable reference across unrelated store ticks (guarded by `isEqual`), so the
+ * scan runs once per real message snapshot instead of on every streamed token.
+ *
+ * The card is a turn-end product, so callers should gate this on generation
+ * state and pass `undefined` (→ empty result, no card) while the round is still
+ * streaming: `children` is rebuilt on every token during generation, which would
+ * otherwise re-run the scan continuously for a card nobody sees until the end.
+ *
+ * `hasWorkSurface` — whether the round carries a work anchor (server-runtime
+ * operation): only then are sandbox-entity edits dropped in favor of their
+ * `file` Work card (see {@link deriveOperationEditedFiles}).
+ */
+export const useOperationEditedFiles = (
+ blocks?: AssistantContentBlock[],
+ hasWorkSurface?: boolean,
+): EditedFileEntry[] =>
+ useMemo(() => deriveOperationEditedFiles(blocks ?? [], hasWorkSurface), [blocks, hasWorkSurface]);
diff --git a/src/features/Work/descriptors.test.ts b/src/features/Work/descriptors.test.ts
new file mode 100644
index 00000000000..a06735b5e1a
--- /dev/null
+++ b/src/features/Work/descriptors.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+
+import { getWorkTypeDescriptor } from './descriptors';
+
+describe('getWorkTypeDescriptor', () => {
+ it('returns a usable fallback descriptor for an unknown work type', () => {
+ // Simulate a Work type the server registry gained after this client shipped:
+ // the lookup must degrade to a generic descriptor instead of returning
+ // undefined and crashing the works UI on `descriptor.getIcon(item)`.
+ const item = {
+ description: 'A brand new kind of work',
+ id: 'work-future-1',
+ identifier: 'FUTURE-1',
+ resourceId: 'resource-1',
+ title: 'Future Work',
+ type: 'future-type-not-yet-known',
+ } as any;
+
+ const descriptor = getWorkTypeDescriptor(item);
+
+ expect(() => descriptor.getIcon(item)).not.toThrow();
+ expect(descriptor.getIcon(item)).toBeTruthy();
+ expect(descriptor.getTitle(item)).toBe('Future Work');
+ expect(descriptor.getIdentifier(item)).toBe('FUTURE-1');
+ expect(descriptor.getDescription(item)).toBe('A brand new kind of work');
+ // Unknown types expose no open action, so their cards render inert.
+ expect(descriptor.getOpenTarget(item)).toBeNull();
+ });
+
+ it('still resolves a known type to its concrete descriptor', () => {
+ const item = {
+ description: 'Doc body',
+ id: 'work-doc-1',
+ identifier: 'DOC-1',
+ resourceId: 'doc-1',
+ title: 'A document',
+ type: 'document',
+ } as any;
+
+ const descriptor = getWorkTypeDescriptor(item);
+ expect(descriptor.getOpenTarget(item)).toEqual({
+ agentDocumentId: undefined,
+ documentId: 'doc-1',
+ kind: 'document',
+ });
+ });
+});
diff --git a/src/features/Work/descriptors.tsx b/src/features/Work/descriptors.tsx
index 508e4f4d9e7..a750d6cb252 100644
--- a/src/features/Work/descriptors.tsx
+++ b/src/features/Work/descriptors.tsx
@@ -1,12 +1,22 @@
+import { classifyEditedFile, getBasename } from '@lobechat/builtin-tools/fileEditScan';
import {
type WorkListItem,
workProviderOfResourceType,
type WorkSkillProvider,
type WorkSummaryItem,
type WorkType,
+ type WorkVersionMetadata,
} from '@lobechat/types';
import { Github } from '@lobehub/icons';
-import { ClipboardListIcon, FileTextIcon, LinkIcon } from 'lucide-react';
+import {
+ ClipboardListIcon,
+ FileBoxIcon,
+ FileSpreadsheetIcon,
+ FileTextIcon,
+ FileTypeIcon,
+ LinkIcon,
+ PresentationIcon,
+} from 'lucide-react';
import type { ComponentType } from 'react';
import LinearIcon from './icons/LinearIcon';
@@ -85,6 +95,29 @@ interface WorkTypeDescriptor<Item extends WorkListItem | WorkSummaryItem> {
getTitle: (item: Item) => string | null;
}
+/**
+ * Entity-format icon per {@link classifyEditedFile} kind. `pdf` gets its own
+ * glyph; everything unclassifiable falls back to the generic file-text icon.
+ */
+const FILE_WORK_ICONS: Record<'slides' | 'sheet' | 'doc' | 'pdf', WorkIcon> = {
+ doc: FileTextIcon,
+ pdf: FileTypeIcon,
+ sheet: FileSpreadsheetIcon,
+ slides: PresentationIcon,
+};
+
+/**
+ * The per-version file identity (path / url / line deltas) lives in the version
+ * metadata, which only summary rows carry (`event.metadata`); plain list rows
+ * fall back to their denormalized `works` columns.
+ */
+const getFileWorkMetadata = (item: WorkItemOfType<'file'>): WorkVersionMetadata | undefined =>
+ 'event' in item ? (item.event?.metadata ?? undefined) : undefined;
+
+/** The edited file's path — from the version metadata, else the denormalized description. */
+const getFileWorkPath = (item: WorkItemOfType<'file'>): string | null =>
+ getFileWorkMetadata(item)?.filePath ?? item.description?.trim() ?? null;
+
export const WORK_TYPE_DESCRIPTORS: {
[T in WorkType]: WorkTypeDescriptor<WorkItemOfType<T>>;
} = {
@@ -106,6 +139,40 @@ export const WORK_TYPE_DESCRIPTORS: {
: null,
getTitle: (item) => item.title,
},
+ // Entity-format file Work (pptx / xlsx / docx / pdf, …). Non-entity edits
+ // never register as a Work — they surface in the in-chat "edited N files"
+ // aggregate card instead. The version metadata carries the file identity
+ // (path / url); plain list rows fall back to the denormalized `works` columns.
+ file: {
+ // Subtitle is the file path (metadata), falling back to the denormalized
+ // description column for list rows without version metadata.
+ getDescription: (item) => getFileWorkPath(item),
+ // Pick the icon from the file's entity kind; unclassifiable paths (or a
+ // path-less list row) fall back to the generic file-text glyph.
+ getIcon: (item) => {
+ const path = getFileWorkPath(item);
+ const classified = path ? classifyEditedFile(path) : undefined;
+ return classified?.category === 'entity'
+ ? FILE_WORK_ICONS[classified.entityKind]
+ : FileTextIcon;
+ },
+ getIdentifier: (item) => item.identifier,
+ // Open/download the persisted file when a durable URL exists — prefer the
+ // version metadata's fileUrl, else the denormalized `url` column. Gated on
+ // http(s) so Electron only ever hands safe URLs to shell.openExternal.
+ getOpenTarget: (item) => {
+ const fileUrl = getFileWorkMetadata(item)?.fileUrl ?? item.url;
+ return isSafeExternalUrl(fileUrl) ? { kind: 'external', url: fileUrl } : null;
+ },
+ // Title is the file name (basename of the path), falling back to the
+ // denormalized title column.
+ getTitle: (item) => {
+ const path = getFileWorkPath(item);
+ // `getBasename` returns '' for a segment-less path; fall through to the
+ // denormalized title in that case (matching the previous null-coalescing).
+ return (path ? getBasename(path) : '') || item.title;
+ },
+ },
external: {
getDescription: (item) => (item.description || item.status)?.trim() ?? null,
// Resolve the brand icon from the item's provider; unknown providers fall
@@ -140,12 +207,47 @@ export const WORK_TYPE_DESCRIPTORS: {
},
};
+/**
+ * Generic descriptor for a Work type this client build doesn't know — a type
+ * added to the server registry after this client shipped. Reads only the
+ * denormalized base columns (present on every Work item) and never resolves an
+ * open target, so an unfamiliar type renders as an inert generic card instead of
+ * crashing. The card call sites already fall through to `resourceId` / `id` when
+ * these are null.
+ */
+const FALLBACK_WORK_TYPE_DESCRIPTOR: WorkTypeDescriptor<WorkListItem | WorkSummaryItem> = {
+ getDescription: (item) => item.description?.trim() ?? null,
+ getIcon: () => FileBoxIcon,
+ getIdentifier: (item) => item.identifier,
+ getOpenTarget: () => null,
+ getTitle: (item) => item.title,
+};
+
/**
* 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.
+ *
+ * Total by construction: an unknown `item.type` (a type the server registry
+ * gained after this client shipped) resolves to {@link FALLBACK_WORK_TYPE_DESCRIPTOR}
+ * rather than `undefined`. Deployed clients lag — Electron by weeks — so a Work
+ * enum addition must DEGRADE, not crash: the previous partial lookup returned
+ * `undefined` and the next `descriptor.getIcon(item)` threw a TypeError that took
+ * down the whole works UI. The server also gates new types out of un-opted-in
+ * responses (see `resolveAllowedWorkTypes`), but this is the client-side
+ * belt-and-suspenders for the next type before that gating exists.
*/
export const getWorkTypeDescriptor = <Item extends WorkListItem | WorkSummaryItem>(
item: Item,
-): WorkTypeDescriptor<Item> =>
- WORK_TYPE_DESCRIPTORS[item.type] as unknown as WorkTypeDescriptor<Item>;
+): WorkTypeDescriptor<Item> => {
+ // Look up through a widened index type: at runtime `item.type` can be a Work
+ // type the server registry gained after this build shipped, so the entry may
+ // genuinely be missing even though the compile-time map looks total. The
+ // re-narrowing casts are safe — a registry entry keyed by `item.type` accepts
+ // exactly that type's item, which `Item` is.
+ const descriptors = WORK_TYPE_DESCRIPTORS as Record<
+ WorkType,
+ WorkTypeDescriptor<Item> | undefined
+ >;
+ return descriptors[item.type] ?? (FALLBACK_WORK_TYPE_DESCRIPTOR as WorkTypeDescriptor<Item>);
+};
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 4c8f53bfca0..436b0e195b9 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -146,7 +146,14 @@ export class MessageService {
};
getMessages = async (params: MessageReadQueryContext): Promise<UIChatMessage[]> => {
- const data = await lambdaClient.message.getMessages.query(params);
+ // Opt into `file` (and any future gated) work summaries in the message
+ // payload. This client ships the descriptor fallback; clients that predate
+ // the `file` type run the old service without the flag and stay on the
+ // legacy set. See resolveAllowedWorkTypes.
+ const data = await lambdaClient.message.getMessages.query({
+ ...params,
+ includeFileWorks: true,
+ });
return data as unknown as UIChatMessage[];
};
diff --git a/src/services/message/server.test.ts b/src/services/message/server.test.ts
index 61ed5b2edba..3577acd7bae 100644
--- a/src/services/message/server.test.ts
+++ b/src/services/message/server.test.ts
@@ -31,7 +31,11 @@ describe('MessageService', () => {
await service.getMessages(params);
- expect(lambdaClient.message.getMessages.query).toHaveBeenCalledWith(params);
+ // The service opts in to file-type works; everything else passes through untouched.
+ expect(lambdaClient.message.getMessages.query).toHaveBeenCalledWith({
+ ...params,
+ includeFileWorks: true,
+ });
});
it('keeps independent service reads available to strong-consistency callers', async () => {
diff --git a/src/services/work.ts b/src/services/work.ts
index 4dd994398c0..d713025c3af 100644
--- a/src/services/work.ts
+++ b/src/services/work.ts
@@ -56,28 +56,37 @@ export const didToolMutateWorkView = ({
};
class WorkService {
+ // This client ships the descriptor fallback for every registered Work type, so
+ // it always opts into the `file` type (and any future gated type). The flag is
+ // set here at the service boundary rather than per call site — an
+ // already-deployed client that predates the `file` type runs the old service
+ // without it and stays on the legacy set. See resolveAllowedWorkTypes.
listByConversation = async (params: {
limit?: number;
threadId?: string | null;
topicId?: string | null;
- }): Promise<WorkListItem[]> => lambdaClient.work.listByConversation.query(params);
+ }): Promise<WorkListItem[]> =>
+ lambdaClient.work.listByConversation.query({ ...params, includeFileWorks: true });
listByWorkspace = async (params: {
cursor?: string | null;
limit?: number;
provider?: WorkSkillProvider;
type?: WorkType | null;
- }): Promise<WorkSummaryPage> => lambdaClient.work.listByWorkspace.query(params);
+ }): Promise<WorkSummaryPage> =>
+ lambdaClient.work.listByWorkspace.query({ ...params, includeFileWorks: true });
listByRootOperation = async (params: {
limit?: number;
rootOperationId?: string | null;
- }): Promise<WorkVersionEventItem[]> => lambdaClient.work.listByRootOperation.query(params);
+ }): Promise<WorkVersionEventItem[]> =>
+ lambdaClient.work.listByRootOperation.query({ ...params, includeFileWorks: true });
listByRootOperations = async (params: {
limit?: number;
rootOperationIds?: string[] | null;
- }): Promise<WorkVersionEventMap> => lambdaClient.work.listByRootOperations.query(params);
+ }): Promise<WorkVersionEventMap> =>
+ lambdaClient.work.listByRootOperations.query({ ...params, includeFileWorks: true });
listVersions = async (workId: string): Promise<WorkVersionItem[]> =>
lambdaClient.work.listVersions.query({ workId });
diff --git a/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts b/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
index 6c7a18c0411..27d17863c1a 100644
--- a/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
@@ -27,6 +27,10 @@ const runtime = new SkillsExecutionRuntime({
timeout: undefined,
});
return {
+ // Desktop commands run on the user's machine — stamp the execution env
+ // so the file-edit scanner treats produced files as device-local (the
+ // server runtime stamps the same field for gateway-dispatched runs).
+ executionEnv: 'device' as const,
exitCode: result.exit_code ?? 1,
output: result.stdout || result.output || '',
stderr: result.stderr,
diff --git a/src/store/tool/slices/builtin/executors/lobe-skills.ts b/src/store/tool/slices/builtin/executors/lobe-skills.ts
index f5df804d188..5f1cf342d49 100644
--- a/src/store/tool/slices/builtin/executors/lobe-skills.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-skills.ts
@@ -39,6 +39,7 @@ const runtime = new SkillsExecutionRuntime({
if (!result.success) {
return {
+ executionEnv: 'sandbox' as const,
exitCode: 1,
output: '',
stderr: result.error?.message || 'Command execution failed',
@@ -49,6 +50,11 @@ const runtime = new SkillsExecutionRuntime({
const sandboxResult = result.result || {};
return {
+ // Web-client commands execute in the cloud sandbox — stamp the
+ // execution env so the file-edit scanner excludes these rows
+ // (sandbox delivery goes through exportFile, not the card), matching
+ // the server runtime's stamping.
+ executionEnv: 'sandbox' as const,
exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),
output: sandboxResult.stdout || sandboxResult.output || '',
stderr: sandboxResult.stderr || '',
@@ -58,6 +64,7 @@ const runtime = new SkillsExecutionRuntime({
};
} catch (error) {
return {
+ executionEnv: 'sandbox' as const,
exitCode: 1,
output: '',
stderr: (error as Error).message || 'Command execution failed',
@@ -114,6 +121,7 @@ const runtime = new SkillsExecutionRuntime({
if (!result.success) {
return {
+ executionEnv: 'sandbox' as const,
exitCode: 1,
output: '',
stderr: result.error?.message || 'Command execution failed',
@@ -125,6 +133,7 @@ const runtime = new SkillsExecutionRuntime({
const sandboxResult = result.result || {};
return {
+ executionEnv: 'sandbox' as const,
exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),
output: sandboxResult.stdout || sandboxResult.output || '',
stderr: sandboxResult.stderr || '',
@@ -134,6 +143,7 @@ const runtime = new SkillsExecutionRuntime({
};
} catch (error) {
return {
+ executionEnv: 'sandbox' as const,
exitCode: 1,
output: '',
stderr: (error as Error).message || 'Command execution failed',