Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

chore(composer): refresh file line references against main

Linuxdazhao5f314811d876
diff --cc docs/adr/README.md
index 9ec1f958b,f91cf42d7..e4d45e91d
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@@ -21,9 -21,9 +21,10 @@@ Each ADR includes
| ID | Title | Status |
|---|---|---|
+| mode-definitions | [User-definable modes as staged workflows](mode-definitions.md) | Proposed |
| sidebar-layout-recovery | [Recover sidebar layout independently of Chromium storage](sidebar-layout-recovery.md) | Accepted |
| steering-local-tool-interruption | [Steering waits for confirmed tool settlement](steering-local-tool-interruption.md) | Accepted |
+ | file-manager-line-references | [File Manager line references](file-manager-line-references.md) | Implemented candidate |
| composer-pasted-directory-references | [Composer pasted directory references](composer-pasted-directory-references.md) | Accepted |
| plugin-projects-list | [Read-only durable project enumeration for plugins](plugin-projects-list.md) | Accepted |
| append-only-review-state | [Append-only review state](append-only-review-state.md) | Implemented candidate |
diff --cc docs/spec/04-ux/08-component-spec.md
index 1c42236c6,50d543b14..1b6150920
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@@ -4787,11 -4749,23 +4787,32 @@@ Closing the connected Browser tab clear
### Issue #2164 correction
While a checkpoint estimate supplies context occupancy, use its recorded provider/model capacity, or the current exact session binding for legacy checkpoints. Keep historical request usage unchanged. Unknown capacity is marked approximate. Verify 20,619 / 1,000,000 = 2%, unknown routes, legacy records and usage after a newer request with `compaction-context-usage.test.mjs`.
+
+### File Manager mutation validation (#2184)
+
+The bundled File Manager validates each create/rename name before filesystem writes. Valid names return canonical entry metadata after create, rename or move. Empty names, dot segments, separators, control characters, Windows-reserved names and trailing dots fail with INVALID_NAME. Existing destinations fail with EXISTS; containment and protected-path gates remain enforced.
+
+### Native Pi file references (#1853)
+
+User-initiated file reads, directory listings, reference resolution and file search use the native session's sidecar-projected project path. Native identities never query Desktop session storage or fall back to the selected workspace. Missing/replaced sources fail closed. Existing local file containment and explicit external-file rules still apply; this grants no model tools or attachments. Native sessions have no Desktop scratch directory.
++
+ ### File Manager line references
+
+ Select a saved range in the local File Manager's source editor. **Add to chat**
+ and copying then pasting into the Composer insert the same removable
+ `gpt.py (85:86)` chip. A single selected line displays as `gpt.py (85)`.
+ Only the file path and inclusive source line numbers enter the draft. Other
+ clipboard consumers still receive the original plain text. Unsaved edits allow
+ plain-text copy and suppress line references until the file is saved or reloaded.
+ At the four-reference limit, another paste shows the limit warning and inserts
+ the plain text instead of consuming it without changing the draft.
+ Selections longer than 4,000 lines or outside positive signed 32-bit line
+ coordinates use plain-text paste. Main applies the same workspace spelling
+ normalization as Composer (separators and trailing slash), while retaining
+ the lexical and real-path project containment checks.
+
+ At turn execution the Agent calls the existing Host Read for each distinct
+ range and adds its bounded result to the model request. Read uses the saved
+ file at execution time, including for queued sends. Source views with no
+ project file identity and clipboard data from another project use normal text
+ copy/paste. See [File Manager line references ADR](../../adr/file-manager-line-references.md).
diff --cc docs/spec/06-delivery/04-e2e-test-plan.md
index f7347948c,3fd9cb2bf..8945ed3de
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@@ -20449,85 -20371,51 +20449,137 @@@ Bounded tail pages include compactions
#### E2E-ISSUE-2164
While a checkpoint estimate supplies context occupancy, use its recorded provider/model capacity, or the current exact session binding for legacy checkpoints. Keep historical request usage unchanged. Unknown capacity is marked approximate. Verify 20,619 / 1,000,000 = 2%, unknown routes, legacy records and usage after a newer request with `compaction-context-usage.test.mjs`.
+
+
+## User-defined mode workflow acceptance
+
+Candidate command: `PI_DESKTOP_HOST_BIN=<candidate-host> node scripts/e2e-mode-definitions.mjs`
+with `PI_SCRATCH_DIR` set to an isolated test directory. No model API is called.
+
+1. Configure a session with a two-stage definition snapshot. Start a durable
+ turn and claim the first contract stage.
+2. Request completion without its required artifact; observe a failed gate.
+3. Supply the artifact through stage completion; verify its exact disk content
+ and the waiting-for-approval state.
+4. Settle the first turn, approve with the current revision and claim the next
+ stage with approval provenance.
+5. Submit the stage's command gate. A changed command must fail with
+ `MODE_GATE_MISMATCH` before execution.
+6. Execute the exact command through `tools.execute`; consume the Host-recorded
+ result and observe finished, no open run, and session mode Agent.
+
+Companion tests: `mode_runs::*` and `rpc::modes_rpc::tests::*` cover migration,
+recovery, CAS, budget and permission caps; desktop `mode-definitions-user-path`,
+`mode-definitions-renderer` and `mode-runs-main` cover source editing, selection,
+run controls and Main dispatch. Runtime `modes/*` covers stage completion and
+compaction injection.
+
+### Goal run controls with a live model (opt-in, paid)
+
+Command: `PI_LIVE_BASE_URL=<url> PI_LIVE_MODEL=<model> PI_LIVE_API_KEY=<key>
+PI_DESKTOP_HOST_BIN=<candidate-host> node scripts/e2e-goal-live.mjs` with
+`PI_SCRATCH_DIR` set (`PI_LIVE_SECRETS_DIR` + `PI_LIVE_SECRET_REF` may replace
+the key; only the machine key and that one secret file are copied). It calls a
+paid model API and needs the account owner's authorization. Real pieces: an
+isolated Host, the production runtime loop and Electron main's run coordinator.
+
+1. With `goalBudget { maxTurns: 6 }` set, a Goal run starts with 6 turns, does
+ the work, calls `CompleteStage` with the three-heading artifact, finishes,
+ and the session returns to Agent.
+2. During the first turn, Edit the objective and budget, then Pause: the turn
+ receives the closeout notice and ends within 3 more model requests; the run
+ stays paused and no turn starts. Resume starts an approval turn with the
+ edited objective, which the run meets before it finishes.
+3. During a turn, Remove: the turn is not interrupted, finishes in Agent
+ without `CompleteStage`, no Host-started turn follows, and no open run is
+ left.
+#### E2E-ISSUE-2173: Redundant delegation job selectors
+
+- Entry: build shared/agent-runtime/host-runtime and Host, then run
+ `PI_DESKTOP_HOST_BIN=<candidate-host> node scripts/e2e-task-job-selectors.mjs`.
+- Preconditions: isolated Host data/workspace and a deterministic localhost
+ provider; production parent and delegate loops, with no external model account.
+- Steps: start a delegate; wait with both its job reference and matching
+ delegationIds; re-read with empty delegationIds and single-job mode/minCompleted;
+ start another delegate, hold its provider response, stop it with both selectors,
+ and confirm its stopped state through TaskWait.
+- Expected: reports remain readable, redundant selectors do not cause errors,
+ single-job mode/minCompleted are ignored, and cancellation settles the target.
+ Unit tests also reject conflicting/malformed IDs and mixed Bash selectors.
+- Specs: `03-runtime/02-agent-runtime.md`, Session job controls.
+- Acceptance: wait, report re-read and running-delegate cancellation complete
+ through the real tool loop. Milestone: maintenance. Status: automated.
+
+#### E2E-ISSUE-1707
+
+Use synthetic Darwin x64/arm64 uname responses through production SSH bootstrap, serialize its code/details as IPC does, and resolve the renderer error. The platform explanation appears, no checksum or upload occurs. Linux and other bootstrap failures keep existing messages. Coverage: remote-host-ssh-bootstrap.test.mjs and remote-host-errors.test.mjs.
+
+#### E2E-ISSUE-2184
+
+Load the actual bundled plugin in an isolated workspace. Create a file and Unicode directory, rename and move the file; verify disk entries and response metadata. Invalid create/rename names fail before writing, and duplicate destinations are refused. Coverage: apps/desktop/test/file-manager-mutations.test.mjs. Existing Electron directory-location path also passes.
+
+### E2E-NATIVE-workspace-file-routing
+
+Run `node scripts/e2e-native-workspace-files.mjs`: isolated Electron Main,
+production workspace IPC, synthetic sidecar session metadata and real fixture
+files. Select an unrelated Desktop workspace; list, read and resolve a native
+file, then reject a missing native session. The test asserts no native session
+or scratch RPC reaches Desktop storage. `native-workspace-files.test.mjs`
+additionally rejects replaced sidecars. No provider execution or native user
+session data is used.
+
+#### E2E-ISSUE-1926-scratch-prefix
+
+Build two actual runtimes with identical configuration and different scratch directories. Their leading runtime system sections match; each trailing context retains its own path. Check PowerShell/POSIX guidance and custom system prompt behavior. Coverage: runtime.test.ts. No paid provider requests or cache-hit claims.
++
+ ### E2E-FILE-LINES — File Manager selections in Composer
+
+ Install the File Manager normally. In a temporary local project, open a source
+ file with two distinct lines and select both. Verify **Add to chat** adds one
+ removable `gpt.py (85:86)` chip
+ without sending. Delete it, copy the selection, and paste into the Composer:
+ the same chip appears, while paste into an ordinary editor yields the selected
+ text. End a selection at the start of the next line and verify that line is
+ excluded. A one-line selection displays one line number.
+
+ Open the same view from a development-loaded File Manager and verify that
+ the host does not advertise `composerFileLines`.
+
+ With the Host unavailable, open an eligible installed File Manager view.
+ Verify opening completes immediately and `composerFileLines` remains true.
+ **Add to chat** reports Host unavailability. Reconnect the Host and retry
+ from the same view. The selection is added after registration is checked.
+
+ Insert an unsaved line before the range. Copying still pastes the original
+ text and the selection menu has no **Add to chat** action. Save the file and
+ verify that both actions use the new saved line numbers.
+
+ Change the saved text after adding the chip, then send it. Observe one scoped
+ Read with offset 84 and limit 2 and the saved result in the model request.
+ Restart and verify the reference is still visible and there is no synthetic
+ Read in the transcript or restored model history. Submit again after deleting
+ the file and verify a failed reference marker in the model request. Repeat
+ with Read permission denied and verify a blocked marker. Neither marker is
+ quoted as file content. Repeat with a queued turn and a project switch. A
+ different project's clipboard metadata cannot add the chip.
+ Fill the draft with four distinct line references, then paste another range.
+ Verify a limit warning, four unchanged references, and the pasted plain text.
+ Paste metadata for a 4,001-line selection or an out-of-bounds line number and
+ verify ordinary text paste. A trailing workspace separator must behave the same
+ for the context-menu and clipboard paths; another workspace must still fail.
+ Submit five references or a malformed range directly to the prompt boundary
+ and runtime boundary: both reject with `INVALID_ARGUMENT` before any Read.
+ Restore a historical attachment with range metadata and a recorded excerpt;
+ verify the excerpt remains a file-lines block without an assistant tool call.
++Repeat a file-reference prompt in a staged Goal run: the current objective is
++already in the system prompt when the scoped Read executes, and the provider
++input retains the file context. Controlled coverage: `runtime.test.ts`.
+
+ ### E2E-BROWSER-CAPTURE-window-manager-readiness
+
+ On Linux/Xvfb, start the browser capture/resize suite through
+ `sh scripts/e2e/with-openbox.sh node scripts/e2e-browser-capture-resize.mjs`.
+ Delay Openbox startup and verify the suite waits for its EWMH root-window
+ claim before requesting maximize/restore/fullscreen. All capture, viewport,
+ and lifecycle assertions must still pass. A missing or failed window manager
+ fails within ten seconds. A failed native probe prints its last progress stages.
diff --cc docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index 84014ad7c,e010adcdb..5e9ff217e
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@@ -125,6 -118,6 +125,18 @@@ pi 消费排队输入时保留渲染器
草稿里的 `pi-desktop://session/<id>` 链接在同一步骤里解析成有界摘录附件:只限
同一项目,当前对话在任何读取之前就被跳过;运行时随后把它作为一个
`<session_reference name="…" session="…">` 块排在用户自己的话之前引用给模型
++ A validated File Manager `lineRange` travels as file attachment metadata.
++ Inclusive line numbers are positive 32-bit signed integers and each range
++ spans at most 4,000 lines, matching the Host Read line budget. Unsupported
++ clipboard selections retain plain-text paste rather than changing the range.
++ Main and runtime reject malformed references or more than four references
++ with `INVALID_ARGUMENT` before any prefetch; neither silently drops a chip.
++ The runtime executes one workspace-only Read per distinct range through
++ the normal tool hooks and quotes its bounded result as file context for
++ the provider turn. Permission blocks and read failures use a separate
++ `file_reference_error` block with a `blocked` or `failed` status. The
++ prefetch runs outside assistant tool batches and creates no tool transcript
++ row. Restoring the reference preserves its path and range metadata.
7. 为本回合快照有效的 shell ID 与方言
8. 用解析出的会话配置和有效思考级别启动 pi 回合;HTTP 429 的建连与流式失败
使用运行时自有的静默 10 次重试预算,其他瞬时的 transport/provider 失败则在
diff --cc docs/zh-CN/spec/04-ux/08-component-spec.md
index 01a4366a4,d0671fb71..f9c484bd1
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@@ -3127,11 -3106,3 +3127,24 @@@ default nor provider configuration. OAu
### Issue #2164 修正
压缩估算作为占用时使用检查点模型容量,旧检查点使用当前会话完整绑定;历史请求用量不变,未知容量标记估算。验证 20,619 / 1,000,000 为 2%、未知路由、旧记录及新请求恢复。
+
+### 文件管理器名称校验(#2184)
+
+新建和重命名前校验名称,创建、重命名和移动后返回正确条目信息。空名称、点路径、分隔符、控制字符、Windows 保留名及尾点返回 INVALID_NAME;已有目标返回 EXISTS。路径边界和受保护路径检查保持生效。
+
+### Native Pi 文件引用(#1853)
+
+用户发起的文件读取、目录列表、引用解析和文件搜索使用 sidecar 投影的 native 会话项目路径。Native 身份不查询 Desktop 会话存储,也不回退到当前选中的工作区。来源丢失或更换时拒绝请求。现有本地文件范围和显式外部文件规则继续生效,不增加模型工具或附件权限。Native 会话没有 Desktop scratch 目录。
++
++### File Manager line references
++
++Saved local source selections use **Add to chat** or clipboard paste to insert
++the same removable `gpt.py (85:86)` chip; one line displays as `gpt.py (85)`.
++The draft carries only path and inclusive line numbers. Ordinary clipboard
++consumers keep the selected text. Unsaved selections, ranges over 4,000 lines,
++invalid signed 32-bit coordinates and another project's metadata use plain text.
++At four references, another paste warns and inserts plain text without removing
++the existing chips. Main and Composer normalize workspace spelling consistently;
++lexical and real-path containment remain mandatory. The runtime reads the saved
++range at execution time through the scoped Host Read, including queued sends.
++See [File Manager line references ADR](../../adr/file-manager-line-references.md).
diff --cc docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 4f7f956b8,918e091b6..6a2565886
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@@ -10473,83 -10420,3 +10473,110 @@@ MCP All 在创建、导入、安装时�
#### E2E-ISSUE-2164
压缩估算作为占用时使用检查点模型容量,旧检查点使用当前会话完整绑定;历史请求用量不变,未知容量标记估算。验证 20,619 / 1,000,000 为 2%、未知路由、旧记录及新请求恢复。
+
+
+## User-defined mode workflow acceptance
+
+Candidate command: `PI_DESKTOP_HOST_BIN=<candidate-host> node scripts/e2e-mode-definitions.mjs`
+with `PI_SCRATCH_DIR` set to an isolated test directory. No model API is called.
+
+1. Configure a session with a two-stage definition snapshot. Start a durable
+ turn and claim the first contract stage.
+2. Request completion without its required artifact; observe a failed gate.
+3. Supply the artifact through stage completion; verify its exact disk content
+ and the waiting-for-approval state.
+4. Settle the first turn, approve with the current revision and claim the next
+ stage with approval provenance.
+5. Submit the stage's command gate. A changed command must fail with
+ `MODE_GATE_MISMATCH` before execution.
+6. Execute the exact command through `tools.execute`; consume the Host-recorded
+ result and observe finished, no open run, and session mode Agent.
+
+Companion tests: `mode_runs::*` and `rpc::modes_rpc::tests::*` cover migration,
+recovery, CAS, budget and permission caps; desktop `mode-definitions-user-path`,
+`mode-definitions-renderer` and `mode-runs-main` cover source editing, selection,
+run controls and Main dispatch. Runtime `modes/*` covers stage completion and
+compaction injection.
+
+### Goal run controls with a live model (opt-in, paid)
+
+Command: `PI_LIVE_BASE_URL=<url> PI_LIVE_MODEL=<model> PI_LIVE_API_KEY=<key>
+PI_DESKTOP_HOST_BIN=<candidate-host> node scripts/e2e-goal-live.mjs` with
+`PI_SCRATCH_DIR` set (`PI_LIVE_SECRETS_DIR` + `PI_LIVE_SECRET_REF` may replace
+the key; only the machine key and that one secret file are copied). It calls a
+paid model API and needs the account owner's authorization. Real pieces: an
+isolated Host, the production runtime loop and Electron main's run coordinator.
+
+1. With `goalBudget { maxTurns: 6 }` set, a Goal run starts with 6 turns, does
+ the work, calls `CompleteStage` with the three-heading artifact, finishes,
+ and the session returns to Agent.
+2. During the first turn, Edit the objective and budget, then Pause: the turn
+ receives the closeout notice and ends within 3 more model requests; the run
+ stays paused and no turn starts. Resume starts an approval turn with the
+ edited objective, which the run meets before it finishes.
+3. During a turn, Remove: the turn is not interrupted, finishes in Agent
+ without `CompleteStage`, no Host-started turn follows, and no open run is
+ left.
+#### E2E-ISSUE-2173: Redundant delegation job selectors
+
+- Entry: build shared/agent-runtime/host-runtime and Host, then run
+ `PI_DESKTOP_HOST_BIN=<candidate-host> node scripts/e2e-task-job-selectors.mjs`.
+- Preconditions: isolated Host data/workspace and a deterministic localhost
+ provider; production parent and delegate loops, with no external model account.
+- Steps: start a delegate; wait with both its job reference and matching
+ delegationIds; re-read with empty delegationIds and single-job mode/minCompleted;
+ start another delegate, hold its provider response, stop it with both selectors,
+ and confirm its stopped state through TaskWait.
+- Expected: reports remain readable, redundant selectors do not cause errors,
+ single-job mode/minCompleted are ignored, and cancellation settles the target.
+ Unit tests also reject conflicting/malformed IDs and mixed Bash selectors.
+- Specs: `03-runtime/02-agent-runtime.md`, Session job controls.
+- Acceptance: wait, report re-read and running-delegate cancellation complete
+ through the real tool loop. Milestone: maintenance. Status: automated.
+#### E2E-ISSUE-1707
+
+生产 SSH 引导使用合成 Darwin 目标,按 IPC 形态传递错误并解析界面提示:显示 Linux 安装包范围,不下载或上传。Linux 及其他安装失败提示保持原行为。
+
+#### E2E-ISSUE-2184
+
+隔离项目加载真实内置插件,创建文件和中文目录,重命名并移动文件,核查磁盘与返回元数据;非法名称及重复目标拒绝。覆盖 file-manager-mutations.test.mjs 和原有 Electron 目录定位路径。
+
+### E2E-NATIVE-workspace-file-routing
+
+运行 `node scripts/e2e-native-workspace-files.mjs`:使用隔离 Electron Main、
+生产 workspace IPC、合成 sidecar 会话元数据和真实测试文件。选中无关的
+Desktop 工作区后,列出、读取和解析 native 文件,再拒绝不存在的 native 会话。
+断言 native 会话及 scratch 请求不会进入 Desktop 存储。
+`native-workspace-files.test.mjs` 另验证 sidecar 更换后拒绝旧响应。
+不执行模型或访问用户 native 会话。
+
+#### E2E-ISSUE-1926-scratch-prefix
+
+创建配置相同但 scratch 不同的真实 runtime,基础提示段相同且尾部各保留自身路径;验证 shell 语法和自定义提示兼容,不调用真实供应商。
++
++### E2E-FILE-LINES — File Manager selections in Composer
++
++Install File Manager normally in an isolated local project. Select saved source
++lines and verify **Add to chat** and clipboard paste create the same removable
++range chip without sending; ordinary editors receive plain text. One-line and
++next-line-boundary selections retain exact inclusive coordinates. Unsaved edits
++suppress references until saved. Development-loaded views receive no capability.
++Opening an eligible view with an unavailable Host must not wait for a registry
++query; Add to chat reports unavailability, and the same view works after recovery.
++Change saved content before sending and verify the scoped Read uses execution-time
++bytes. Restart, queue and switch projects: ranges survive, another project's
++metadata is rejected, and no synthetic assistant Read is persisted or restored.
++Denied/missing files use blocked/failed reference markers rather than file content.
++Four-reference overflow warns and preserves pasted text; unsupported coordinates
++or over-4,000-line metadata use text. Invalid or over-four direct prompt/runtime
++inputs fail with `INVALID_ARGUMENT` before reads. Workspace trailing separators
++behave consistently. A staged Goal prompt retains both its refreshed objective
++and file context (`runtime.test.ts`). Installed-plugin acceptance follows the
++host-first sequence in plugin PR #10.
++
++### E2E-BROWSER-CAPTURE-window-manager-readiness
++
++On Linux/Xvfb, run `sh scripts/e2e/with-openbox.sh node scripts/e2e-browser-capture-resize.mjs`.
++Delayed Openbox startup must wait for its EWMH root-window claim before window
++transitions. Capture/viewport/lifecycle checks pass; absent or failed window
++managers fail within ten seconds and native failures print their progress stages.
diff --cc docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md
index ce219c749,ce219c749..75ccda39a
--- a/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md
+++ b/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md
@@@ -130,6 -130,6 +130,21 @@@ host-core 的 `plugin.installProgress`
`themes.list` 和 `themes.setVariables`,均需要 `ui.theme`。
`projects.list` 只提供项目元数据,不需要权限,也不会授予文件或会话访问权限。
++The docked File Manager (`pi.file-manager/manager`) receives
++`pluginBridge.capabilities.composerFileLines` when its loaded instance holds
++both `ui.view` and `fs.read` and is not development-loaded or disposing.
++This flag describes bridge support. Opening a view requires no Host registry
++query. Each invocation checks the enabled registry entry and loaded version
++with a five-second RPC timeout. An unavailable Host returns `HOST_UNAVAILABLE`;
++a later invocation can retry after reconnection in the same view.
++An eligible view can invoke
++`composer.addFileLines` with `{ workspace, path, start, end }`, where paths are
++absolute and lines are one-based and inclusive. The host requires the visible
++view of an enabled, registered File Manager with `ui.view` and `fs.read`, a
++matching workspace, and a path contained by a local folder of the selected
++session's project. The action inserts a draft reference. Sending the draft
++uses normal tool permissions.
++
## 4.1 事件(主机→插件进程)
调用代理还会向插件的 `utilityProcess` 推送单向消息帧:
diff --cc packages/agent-runtime/src/runtime.test.ts
index 90e1328ff,9ccd88db3..5ced8133c
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@@ -29,6 -29,6 +29,7 @@@ import
type RuntimeProviderConfig,
} from "./runtime.js";
import { estimateOutputCapInputTokens } from "./output-cap.js";
++import { builtinModeDefinition } from "./mode-definitions.js";
import { COMPACTION_SUMMARY_MAX_RETRIES } from "./compaction-summary-input.js";
import { loadInstructionChain, type ProjectInstructions } from "./project-instructions.js";
@@@ -227,6 -227,100 +228,127 @@@ function createRuntime
});
}
+ it("reads each explicit file line range once before passing its text to the model", async () => {
+ const call = vi.fn(async (method: string, _params: unknown) => {
+ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: true };
+ if (method === "tools.fileBatchRegister") return { ticket: "test-ticket" };
+ if (method === "tools.fileBatchSeal") return { ok: true };
+ if (method === "tools.execute") return { ok: true, content: { content: "85: saved first\n86: saved second", totalLines: 100 } };
+ });
+ const onEvent = vi.fn();
+ const runtime = createRuntime({ host: { call }, onEvent, projectPath: "/project", workspaceRoot: "/project" });
+ const agent = (runtime as unknown as { agent: Agent }).agent;
+ const model = vi.spyOn(agent, "prompt").mockResolvedValue(undefined);
+ const reference = { kind: "file" as const, path: "/project/src/gpt.py", name: "gpt.py", lineRange: { start: 85, end: 86 } };
+ try {
+ await runtime.prompt({ text: "Explain these lines", attachments: [reference, reference] }, "prompt", "turn");
+ expect(call.mock.calls.filter(([method]) => method === "tools.execute")).toEqual([
+ ["tools.execute", expect.objectContaining({
+ toolName: "Read",
+ turnId: "turn",
+ workspaceOnly: true,
+ args: { path: "/project/src/gpt.py", offset: 84, limit: 2 },
+ })],
+ ]);
+ expect(model).toHaveBeenCalledWith(expect.objectContaining({
+ role: "user",
+ content: expect.stringContaining("85: saved first"),
+ }));
+ expect(model).toHaveBeenCalledWith(expect.objectContaining({ content: expect.stringContaining("86: saved second") }));
+ expect(call.mock.calls.map(([method]) => method)).not.toContain("tools.fileBatchRegister");
+ expect(onEvent.mock.calls.map(([event]) => event.type)).not.toContain("tool_end");
+ } finally {
+ await runtime.dispose();
+ }
+ });
+
++it("refreshes the staged objective before reading file references for the same prompt", async () => {
++ let readSystemPrompt: string | undefined;
++ const call = vi.fn(async (method: string) => {
++ if (method === "project.instructions.resolve") readSystemPrompt = agent.state.systemPrompt;
++ if (method === "tools.execute") {
++ return { ok: true, content: { content: "saved review line" } };
++ }
++ });
++ const runtime = createRuntime({ host: { call }, projectPath: "/project", workspaceRoot: "/project" });
++ runtime.setMode("goal", builtinModeDefinition("goal"));
++ const agent = (runtime as unknown as { agent: Agent }).agent;
++ const model = vi.spyOn(agent, "prompt").mockResolvedValue(undefined);
++ try {
++ await runtime.prompt({
++ text: "Review this line",
++ modeTurn: { runId: "run", stageId: "work", origin: "user", enteredStage: true,
++ input: "Review snapshot objective", artifactPaths: { goal: ".pi/goals/run.md" } },
++ attachments: [{ kind: "file", path: "/project/review.txt", name: "review.txt", lineRange: { start: 2, end: 2 } }],
++ }, "prompt", "turn");
++ expect(model).toHaveBeenCalledWith(expect.objectContaining({ content: expect.stringContaining("saved review line") }));
++ expect(readSystemPrompt).toContain("Review snapshot objective");
++ expect(call).toHaveBeenCalledWith("tools.execute", expect.objectContaining({ workspaceOnly: true, mode: "goal" }));
++ } finally {
++ await runtime.dispose();
++ }
++});
++
+ it.each([
+ { label: "too many", attachments: Array.from({ length: 5 }, (_, index) => ({
+ kind: "file" as const, path: `/project/${index}.txt`, name: `${index}.txt`, lineRange: { start: 1, end: 1 },
+ })) },
+ { label: "invalid", attachments: [
+ { kind: "file" as const, path: "/project/a.txt", name: "a.txt", lineRange: { start: 2, end: 1 } },
+ ] },
+ ])("rejects $label file references before any Host read", async ({ attachments }) => {
+ const call = vi.fn();
+ const runtime = createRuntime({ host: { call }, projectPath: "/project", workspaceRoot: "/project" });
+ try {
+ await expect(runtime.resolveFileLineReferences({ text: "Review", attachments }))
+ .rejects.toMatchObject({ errorCode: "INVALID_ARGUMENT" });
+ expect(call.mock.calls.filter(([method]) => method === "tools.execute")).toEqual([]);
+ } finally {
+ await runtime.dispose();
+ }
+ });
+
+ it("restores a recorded line-range excerpt without synthesizing an assistant tool call", async () => {
+ const runtime = createRuntime({ history: [{
+ id: "file-lines", role: "user", content: "Review /project/a.txt (85:86)",
+ createdAt: "2026-11-08T00:00:00.000Z",
+ attachments: [{ kind: "file", ref: "/project/a.txt", name: "a.txt",
+ lineRange: { start: 85, end: 86 }, text: "recorded saved excerpt" }],
+ }] });
+ try {
+ const messages = (runtime as unknown as { agent: Agent }).agent.state.messages;
+ expect(messages.filter(message => message.role === "user")).toEqual([expect.objectContaining({
+ role: "user", content: expect.stringContaining('<file_lines source="/project/a.txt (85:86)">\nrecorded saved excerpt\n</file_lines>'),
+ })]);
+ expect(messages.some(message => message.role === "assistant" || message.role === "toolResult")).toBe(false);
+ } finally {
+ await runtime.dispose();
+ }
+ });
+
+ it.each([
+ { denied: true, status: "blocked", reason: "Read denied" },
+ { denied: false, status: "failed", reason: "File not found" },
+ ])("labels a $status file reference separately from file content", async ({ denied, status, reason }) => {
+ const call = vi.fn(async (method: string) => {
+ if (method === "tools.execute") return { ok: false, denied, content: reason };
+ });
+ const runtime = createRuntime({ host: { call }, projectPath: "/project", workspaceRoot: "/project" });
+ const agent = (runtime as unknown as { agent: Agent }).agent;
+ const model = vi.spyOn(agent, "prompt").mockResolvedValue(undefined);
+ const reference = { kind: "file" as const, path: "/project/sample.txt", name: "sample.txt", lineRange: { start: 2, end: 2 } };
+ try {
+ await runtime.prompt({ text: "Explain this line", attachments: [reference] });
+ const message = model.mock.calls[0]?.[0];
+ expect(message).toMatchObject({
+ content: expect.stringContaining(`status="${status}">\n${reason}\n</file_reference_error>`),
+ });
+ expect(message).not.toMatchObject({ content: expect.stringContaining("<file_lines") });
+ } finally {
+ await runtime.dispose();
+ }
+ });
+
function runtimeTool(runtime: DesktopAgentRuntime, name: string): AgentTool {
const internal = runtime as unknown as { agent: { state: { tools: AgentTool[] } } };
const tool = internal.agent.state.tools.find((entry) => entry.name === name);
diff --cc packages/agent-runtime/src/runtime.ts
index 67e782e78,37c854490..82bc4a522
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@@ -3703,14 -3675,9 +3723,15 @@@ Do not invent objections or turn specul
toolCallId,
toolName,
args: params,
+ ...(this.fileLineReadCalls.has(toolCallId) ? { workspaceOnly: true } : {}),
...(this.batchPlanner.ticket(toolCallId) ? { fileBatchTicket: this.batchPlanner.ticket(toolCallId) } : {}),
mode: this.mode,
+ // A staged mode's `run` exit gate (ADR mode-definitions): the
+ // Host checks the command against the snapshot and records the
+ // exit code under this call id for `modes.gateResult`.
+ ...(isBash && this.modeGateCalls.has(toolCallId)
+ ? { modeGate: this.modeGateCalls.get(toolCallId) }
+ : {}),
...(isBash
? {
expectedCommandShellId: this.commandShell.id,
@@@ -9418,7 -9364,9 +9501,10 @@@
this.resetDeferredToolsForPrompt();
if (selectedTools.length) this.activateDeferredTools(selectedTools);
this.setAgentTools(this.activeTools());
+ if (modePromptChanged) this.setAgentSystemPrompt(this.composeSystemPrompt());
+ if (typeof modelInput !== "string" && modelInput.attachments?.some(attachment => attachment.lineRange !== undefined)) {
+ modelInput = await this.resolveFileLineReferences(modelInput);
+ }
const content = promptContent(modelInput);
const incomingUserMessage: AgentMessage = {
role: "user",