Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(composer): validate and restore file line references
Linuxdazhao30de3043d1e8
diff --git a/apps/desktop/electron/main/file-line-reference.ts b/apps/desktop/electron/main/file-line-reference.tsindex 547e98618..ca1ceb4c9 100644--- a/apps/desktop/electron/main/file-line-reference.ts+++ b/apps/desktop/electron/main/file-line-reference.ts@@ -1,6 +1,6 @@import { realpathSync } from "node:fs";import { isAbsolute, relative } from "node:path";-import { parseFileLineReference, type FileLineReference } from "@pi-desktop/shared";+import { normalizeProjectPath, parseFileLineReference, type FileLineReference } from "@pi-desktop/shared";import type { HostProcess } from "./host-process";import type { PluginRuntime } from "./plugin-runtime";import type { PluginViewHost } from "./plugin-view-host";@@ -41,7 +41,7 @@ export async function addFileLinesFromView(!selected || !canUseFileLineView(loaded) ||!bridge.pluginViews.isVisibleViewSender(senderId, FILE_LINES_VIEW_KEY) ||!bridge.pluginActiveInProject(pluginId, selected.projectPath) ||- reference.workspace !== bridge.getWorkspacePath()+ normalizeProjectPath(reference.workspace) !== normalizeProjectPath(bridge.getWorkspacePath())) return null;return { loaded, selected };};diff --git a/apps/desktop/test/file-line-bridge.test.mjs b/apps/desktop/test/file-line-bridge.test.mjsindex 3eb28b919..0ccf8ef8c 100644--- a/apps/desktop/test/file-line-bridge.test.mjs+++ b/apps/desktop/test/file-line-bridge.test.mjs@@ -54,6 +54,11 @@ test("an installed File Manager can add lines only to the session that authorizeassert.deepEqual(await addFileLinesFromView(pluginId, 123, payload, bridge), { ok: true });assert.deepEqual(deliveries, [{ sessionId: "selected", reference: payload }]);+ const normalizedPayload = { ...payload, workspace: `${workspace}/` };+ assert.deepEqual(await addFileLinesFromView(pluginId, 123, normalizedPayload, bridge), { ok: true });+ await assert.rejects(addFileLinesFromView(pluginId, 123, { ...payload, workspace: `${workspace}-other` }, bridge), /no longer active/);+ assert.deepEqual(deliveries.at(-1), { sessionId: "selected", reference: normalizedPayload });+await assert.rejects(addFileLinesFromView(pluginId, 321, payload, bridge), /no longer active/);loaded.permissions.delete("fs.read");await assert.rejects(addFileLinesFromView(pluginId, 123, payload, bridge), /no longer active/);@@ -68,5 +73,5 @@ test("an installed File Manager can add lines only to the session that authorizeconst pending = addFileLinesFromView(pluginId, 123, payload, bridge);pluginSession.setActiveSession({ ...session, sessionId: "different" });await assert.rejects(pending, /no longer active/);- assert.equal(deliveries.length, 1);+ assert.equal(deliveries.length, 2);});diff --git a/apps/desktop/test/prompt-inline-attachments.test.mjs b/apps/desktop/test/prompt-inline-attachments.test.mjsindex c9adabdff..24833da59 100644--- a/apps/desktop/test/prompt-inline-attachments.test.mjs+++ b/apps/desktop/test/prompt-inline-attachments.test.mjs@@ -120,6 +120,17 @@ test("line ranges stay deferred and cannot escape the session project", async (tassert.equal(prepared.inlineData, undefined);assert.equal(appendPromptFallbackPaths("Review this", [prepared]), "Review this");+ for (const references of [+ Array.from({ length: 5 }, () => attachment),+ [{ ...attachment, lineRange: { start: 1, end: 9e15 } }],+ [{ ...attachment, lineRange: { start: 1, end: 4001 } }],+ ]) {+ await assert.rejects(+ preparePromptAttachments(data, sessionId, project, references, false, "Review this"),+ { errorCode: "INVALID_ARGUMENT" },+ );+ }+for (const invalidPath of [outside, escape]) {await assert.rejects(preparePromptAttachments(data, sessionId, project, [{ ...attachment, path: invalidPath }], false, ""),diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 885a47df4..cfa2a12da 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -160,6 +160,11 @@ transcript-read API. The core runs no title completion of its own.as one `<session_reference name="…" session="…">` block ahead of the user'sown wordsA 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 throughthe normal tool hooks and quotes its bounded result as file context forthe provider turn. Permission blocks and read failures use a separatediff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 2b823b6c5..50d543b14 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -4759,6 +4759,10 @@ clipboard consumers still receive the original plain text. Unsaved edits allowplain-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 insertsthe 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 distinctrange and adds its bounded result to the model request. Read uses the saveddiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 2379d6532..2b1f04ffd 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -20403,3 +20403,10 @@ quoted as file content. Repeat with a queued turn and a project switch. Adifferent 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.diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex df13fc22a..9ccd88db3 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -261,6 +261,43 @@ it("reads each explicit file line range once before passing its text to the mode}});+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" },diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex e1ba81b1f..37c854490 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -434,6 +434,7 @@ function runtimeAttachmentFromMessage(// Recorded placement: the message content names this image at that spot, so// the restored prompt keeps the block there too....(attachment.inlinePath ? { inlinePath: attachment.inlinePath } : {}),+ ...(attachment.lineRange ? { lineRange: attachment.lineRange } : {}),...(data ? { data } : {}),};}@@ -9265,6 +9266,13 @@ Do not invent objections or turn speculative risks into blockers. Stop when the/** Execute the ordinary Host Read for explicit composer references before model input. */async resolveFileLineReferences(input: RuntimePrompt): Promise<RuntimePrompt> {if (!input.attachments?.some(attachment => attachment.lineRange !== undefined)) return input;+ const references = input.attachments.filter(attachment => attachment.lineRange !== undefined);+ if (references.length > MAX_FILE_LINE_REFERENCES) {+ throw Object.assign(new Error("Too many file line references"), { errorCode: "INVALID_ARGUMENT" });+ }+ if (references.some(attachment => attachment.kind !== "file" || !parseFileLineRange(attachment.lineRange))) {+ throw Object.assign(new Error("Invalid file line reference"), { errorCode: "INVALID_ARGUMENT" });+ }const read = this.activeTools().find(tool => tool.name === "Read" && this.builtinTools.has(tool));const turnId = this.turnId;const attachments: RuntimePromptAttachment[] = [];@@ -9274,8 +9282,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theattachments.push(attachment);continue;}- const range = parseFileLineRange(attachment.lineRange);- if (!range || attachment.kind !== "file" || seen.size >= MAX_FILE_LINE_REFERENCES) continue;+ const range = parseFileLineRange(attachment.lineRange)!;const key = JSON.stringify([attachment.path, range.start, range.end]);if (seen.has(key)) continue;seen.add(key);diff --git a/packages/shared/src/file-line-reference.test.ts b/packages/shared/src/file-line-reference.test.tsnew file mode 100644index 000000000..819d52c36--- /dev/null+++ b/packages/shared/src/file-line-reference.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from "vitest";+import { parseFileLineRange, parseFileLineReference } from "./file-line-reference.js";++describe("file line selection bounds", () => {+ it("accepts a bounded selection at the largest supported line number", () => {+ expect(parseFileLineRange({ start: 2_147_483_646, end: 2_147_483_647 }))+ .toEqual({ start: 2_147_483_646, end: 2_147_483_647 });+ expect(parseFileLineRange({ start: 85, end: 4084 })).toEqual({ start: 85, end: 4084 });+ });++ it.each([+ { start: 1, end: 9e15 },+ { start: 2_147_483_648, end: 2_147_483_648 },+ { start: 85, end: 4085 },+ { start: 0, end: 1 },+ { start: 2, end: 1 },+ { start: 1, end: 1.5 },+ ])("rejects an unsupported selection $start:$end without relabelling it", (range) => {+ expect(parseFileLineRange(range)).toBeUndefined();+ expect(parseFileLineReference({ ...range, path: "/project/a.ts", workspace: "/project" })).toBeUndefined();+ });+});diff --git a/packages/shared/src/file-line-reference.ts b/packages/shared/src/file-line-reference.tsindex 07bbb1ca6..8157131d9 100644--- a/packages/shared/src/file-line-reference.ts+++ b/packages/shared/src/file-line-reference.ts@@ -1,6 +1,9 @@export const FILE_LINES_CLIPBOARD_TYPE = "application/x-pi-desktop-file-lines";export const FILE_LINES_ADD_CHANNEL = "composer.addFileLines";export const MAX_FILE_LINE_REFERENCES = 4;+export const MAX_FILE_LINE_NUMBER = 2_147_483_647;+// Match the Host Read line budget; oversized selections retain plain-text paste.+export const MAX_FILE_LINE_RANGE_LINES = 4_000;export type FileLineRange = { start: number; end: number };export type FileLineReference = FileLineRange & { path: string; workspace: string };@@ -10,7 +13,8 @@ export function parseFileLineRange(value: unknown): FileLineRange | undefined {const { start, end } = value as Partial<FileLineRange>;if (typeof start !== "number" || typeof end !== "number" ||!Number.isSafeInteger(start) || !Number.isSafeInteger(end) ||- start < 1 || end < start) return;+ start < 1 || end < start || end > MAX_FILE_LINE_NUMBER ||+ end - start + 1 > MAX_FILE_LINE_RANGE_LINES) return;return { start, end };}