Skip to content

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

fix(composer): integrate line references with native file metadata

Linuxdazhao691928e3d7f8
diff --cc apps/desktop/electron/main/prompt-attachments.ts
index 0770bc201,2d9d0ce12..48fa156d3
--- a/apps/desktop/electron/main/prompt-attachments.ts
+++ b/apps/desktop/electron/main/prompt-attachments.ts
@@@ -18,10 -18,11 +18,13 @@@ import
} from "node:fs";
import { copyFile, readFile } from "node:fs/promises";
import { isAbsolute, join, relative, resolve } from "node:path";
+import { resolveComposerFileReference } from "./composer-file-references.ts";
import {
ErrorCodes,
+ appendLocalFileReferenceContext,
+ fileLineLabel,
+ MAX_FILE_LINE_REFERENCES,
+ parseFileLineRange,
formatFileInsert,
formatPromptPathText,
imageExceedsInlineDimensions,
@@@ -249,18 -254,21 +256,38 @@@ export async function preparePromptAtta
attachments.map((attachment) => attachment.path),
);
for (const [index, attachment] of attachments.entries()) {
+ if (attachment.lineRange !== undefined) {
++ if (attachment.localReference !== undefined) {
++ throw Object.assign(new Error("File references cannot combine a line range and local reference"), {
++ errorCode: ErrorCodes.INVALID_ARGUMENT,
++ });
++ }
+ const lineRange = parseFileLineRange(attachment.lineRange);
+ if (!lineRange || attachment.kind !== "file" || !fileLinePathInProject(attachment.path, projectPath ?? null)) {
+ throw Object.assign(new Error("Invalid file line reference for the session project"), {
+ errorCode: ErrorCodes.INVALID_ARGUMENT,
+ });
+ }
+ const name = attachment.name || attachment.path.split(/[\\/]/).at(-1) || "file";
+ const inlinePath = fileLineLabel(attachment.path, lineRange);
+ prepared.push({
+ message: { kind: "file", name, ref: attachment.path, lineRange, inlinePath },
+ fallbackPath: attachment.path,
+ });
+ continue;
+ }
+ if (attachment.localReference !== undefined) {
+ const file = await resolveComposerFileReference(dataRoot, projectPath, attachment.path, attachment.localReference);
+ prepared.push({
+ message: {
+ kind: "file", name: file.name, ref: file.path, mimeType: file.mimeType,
+ size: file.size, localReference: file.localReference,
+ ...(inlineSpans[index] ? { inlinePath: formatPromptPathText(file.path) } : {}),
+ },
+ fallbackPath: file.path,
+ });
+ continue;
+ }
const source = resolvePromptPath(dataRoot, sessionId, projectPath, attachment.path);
if (!source) {
throw Object.assign(new Error(`Attachment path is outside the session roots: ${attachment.path}`), {
@@@ -361,7 -369,7 +388,7 @@@ export function appendPromptFallbackPat
attachments: readonly PreparedPromptAttachment[],
): string {
const paths = attachments
- .filter((attachment) => !attachment.inlineData && !attachment.message.localReference)
- .filter((attachment) => !attachment.inlineData && !attachment.message.lineRange)
++ .filter((attachment) => !attachment.inlineData && !attachment.message.localReference && !attachment.message.lineRange)
// A path the prompt already names at the user's own position needs no second
// copy at the end; a rewritten fallback (a replayed copy) still travels.
.filter(
diff --cc apps/desktop/src/features/chat/composer/editor.ts
index 7ecf55b25,2250ae9a5..bf3ccf7c0
--- a/apps/desktop/src/features/chat/composer/editor.ts
+++ b/apps/desktop/src/features/chat/composer/editor.ts
@@@ -60,10 -60,9 +62,11 @@@ export function createFileReference
? (preferredName ?? "")
: fileReferenceLabel(path, preferredName),
kind: metadata?.kind ?? (isImageFilePath(path) ? "image" : "file"),
+ ...(metadata?.size !== undefined ? { size: metadata.size } : {}),
+ ...(metadata?.localReference ? { localReference: metadata.localReference } : {}),
...(metadata?.mimeType ? { mimeType: metadata.mimeType } : {}),
...(metadata?.token ? { token: metadata.token } : {}),
+ ...(metadata?.lineRange ? { lineRange: metadata.lineRange } : {}),
...(metadata?.plugin ? { plugin: metadata.plugin } : {}),
};
}
@@@ -287,8 -287,7 +291,8 @@@ function chipSvg(key: string, size = 13
}
export function isEditableTextReference(reference: ComposerFileReference): boolean {
- if (reference.localReference) return false;
- if (isPluginMark(reference) || reference.kind === "directory" || reference.kind === "agent" || reference.lineRange) return false;
++ if (reference.localReference || reference.lineRange) return false;
+ if (isPluginMark(reference) || reference.kind === "directory" || reference.kind === "agent") return false;
return reference.mimeType?.toLowerCase() === "text/plain" || /\.txt$/i.test(reference.name);
}
@@@ -356,14 -356,7 +361,14 @@@ function buildChipElement
const nameSpan = document.createElement("span");
nameSpan.className = "composer-chip-name";
- nameSpan.textContent = reference.name;
+ nameSpan.textContent = label;
+ if (reference.localReference && reference.size !== undefined) {
+ const unit = Math.min(3, Math.floor(Math.log2(Math.max(1, reference.size)) / 10));
+ const size = reference.size / 1024 ** unit;
+ nameSpan.textContent += ` · ${Number(size.toFixed(1))} ${["B", "KiB", "MiB", "GiB"][unit]}`;
+ chip.title += ` (${reference.size} B)`;
+ chip.setAttribute("aria-label", `${reference.name} — ${chip.title}`);
+ }
const remove = document.createElement("button");
remove.type = "button";
diff --cc apps/desktop/src/features/chat/composer/model.ts
index fdc2bd1c9,b060fd9f9..ddc7bb51e
--- a/apps/desktop/src/features/chat/composer/model.ts
+++ b/apps/desktop/src/features/chat/composer/model.ts
@@@ -59,8 -59,7 +59,9 @@@ export type ComposerPrefill =
};
export type ComposerFileReference = {
+ size?: number;
+ localReference?: string;
+ lineRange?: import("@pi-desktop/shared").FileLineRange;
id: string;
sessionId: string;
path: string;
diff --cc apps/desktop/src/lib/composer-draft-cache.ts
index 795853e91,2c9939ce4..ea9c417bb
--- a/apps/desktop/src/lib/composer-draft-cache.ts
+++ b/apps/desktop/src/lib/composer-draft-cache.ts
@@@ -21,8 -21,7 +21,9 @@@ type CachedComposerDraft = ComposerDraf
export const HOME_DRAFT_KEY = "__home__";
export type ComposerDraftFileInput = {
+ size?: number;
+ localReference?: string;
+ lineRange?: import("@pi-desktop/shared").FileLineRange;
sessionId?: string;
path: string;
name: string;
@@@ -42,10 -39,9 +43,11 @@@ export function draftFileReference(
mimeType,
token,
plugin,
+ lineRange,
}: ComposerDraftFileInput): ComposerDraftFileReference {
return {
+ ...(size !== undefined ? { size } : {}),
+ ...(localReference ? { localReference } : {}),
path,
name,
kind,
@@@ -78,9 -75,9 +81,11 @@@ export function sameDraftFileReference
a.name === b.name &&
a.kind === b.kind &&
a.mimeType === b.mimeType &&
+ a.size === b.size &&
+ a.localReference === b.localReference &&
a.token === b.token &&
+ a.lineRange?.start === b.lineRange?.start &&
+ a.lineRange?.end === b.lineRange?.end &&
samePluginPart(a.plugin, b.plugin)
);
}
diff --cc apps/desktop/src/lib/composer-input-history.ts
index cc5019c95,613ab6869..e7ba63602
--- a/apps/desktop/src/lib/composer-input-history.ts
+++ b/apps/desktop/src/lib/composer-input-history.ts
@@@ -1,3 -1,3 +1,4 @@@
++import { parseFileLineRange } from "@pi-desktop/shared";
import type { ComposerDraftSnapshot } from "./composer-smart-stop";
/**
@@@ -40,12 -40,10 +41,14 @@@ function readReference(value: unknown)
const row = value as Record<string, unknown>;
if (typeof row.path !== "string" || !row.path || typeof row.name !== "string") return null;
const kind = row.kind === "image" || row.kind === "file" || row.kind === "directory" ? row.kind : undefined;
++ const lineRange = parseFileLineRange(row.lineRange);
return {
path: row.path,
name: row.name,
kind,
+ ...(typeof row.size === "number" && Number.isSafeInteger(row.size) && row.size >= 0 ? { size: row.size } : {}),
+ ...(typeof row.localReference === "string" ? { localReference: row.localReference } : {}),
++ ...(lineRange ? { lineRange } : {}),
...(typeof row.mimeType === "string" && row.mimeType ? { mimeType: row.mimeType } : {}),
...(typeof row.token === "string" && row.token ? { token: row.token } : {}),
};
diff --cc apps/desktop/src/lib/composer-smart-stop.ts
index 40e07a640,365a713f7..9b0cb23ce
--- a/apps/desktop/src/lib/composer-smart-stop.ts
+++ b/apps/desktop/src/lib/composer-smart-stop.ts
@@@ -23,8 -23,7 +23,9 @@@ export type ComposerPluginPart
};
export type ComposerDraftFileReference = {
+ size?: number;
+ localReference?: string;
+ lineRange?: import("@pi-desktop/shared").FileLineRange;
path: string;
name: string;
kind?: "image" | "file" | "session" | "directory" | "agent";
diff --cc apps/desktop/src/stores/helpers/store-helpers.ts
index 638064fd0,c70a8dec6..ee2043b17
--- a/apps/desktop/src/stores/helpers/store-helpers.ts
+++ b/apps/desktop/src/stores/helpers/store-helpers.ts
@@@ -37,14 -37,13 +37,15 @@@ export function promptAttachmentsFromDr
// Inline chips use tokens for both files and images. Ordinary file chips
// already serialize to @path text (the model can Read them); only image
// chips need the structured transport for vision/fallback handling.
- if (reference.token && kind !== "image" && !reference.localReference) return [];
- if (reference.token && kind !== "image" && !reference.lineRange) return [];
++ if (reference.token && kind !== "image" && !reference.localReference && !reference.lineRange) return [];
return [
{
path: reference.path,
name: reference.name,
kind,
+ ...(reference.size !== undefined ? { size: reference.size } : {}),
+ ...(reference.localReference ? { localReference: reference.localReference } : {}),
+ ...(reference.lineRange ? { lineRange: reference.lineRange } : {}),
...(reference.mimeType ? { mimeType: reference.mimeType } : {}),
},
];
@@@ -62,9 -61,9 +63,10 @@@ export function promptAttachmentsFromMe
path: attachment.ref,
name: attachment.name,
kind: attachment.kind,
+ ...(attachment.lineRange ? { lineRange: attachment.lineRange } : {}),
...(attachment.mimeType ? { mimeType: attachment.mimeType } : {}),
...(attachment.size !== undefined ? { size: attachment.size } : {}),
+ ...(attachment.localReference ? { localReference: attachment.localReference } : {}),
}));
}
diff --cc apps/desktop/test/composer-file-reference-draft.test.mjs
index f372a8a94,000000000..432994097
mode 100644,000000..100644
--- a/apps/desktop/test/composer-file-reference-draft.test.mjs
+++ b/apps/desktop/test/composer-file-reference-draft.test.mjs
@@@ -1,57 -1,0 +1,72 @@@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import vm from "node:vm";
+import test from "node:test";
+import ts from "typescript";
- import { isRenderableAttachment } from "@pi-desktop/shared";
++import { fileLineLabel, isRenderableAttachment } from "@pi-desktop/shared";
+import { snapshotComposerDraft } from "../src/lib/composer-draft-cache.ts";
+
+function loadFunction(path, name, globals = {}) {
+ const source = readFileSync(new URL(path, import.meta.url), "utf8");
+ const tree = ts.createSourceFile("module.ts", source, ts.ScriptTarget.Latest, true);
+ const node = tree.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === name);
+ assert.ok(node, name);
+ const code = ts.transpileModule(node.getText(tree).replace(/^export\s+/, ""), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ return vm.runInNewContext(`${code}\n${name};`, globals);
+}
+
+const reference = {
+ path: "/outside/large.bin", name: "large.bin", kind: "file", token: "\ue001",
+ localReference: "11111111-2222-4333-8444-555555555555", size: 67108865,
+};
+
+test("draft snapshot and dispatch preserve reference identity and exact size", () => {
+ const draft = snapshotComposerDraft("Inspect \ue001", [{ ...reference, sessionId: "source" }], "source");
+ assert.deepEqual(draft.fileReferences, [reference]);
+ const fromDraft = loadFunction("../src/stores/helpers/store-helpers.ts", "promptAttachmentsFromDraft");
+ const [attachment] = fromDraft(draft.fileReferences);
+ assert.equal(attachment.localReference, reference.localReference);
+ assert.equal(attachment.size, reference.size);
+ const fromMessage = loadFunction("../src/stores/helpers/store-helpers.ts", "promptAttachmentsFromMessage", { isRenderableAttachment });
+ const [retry] = fromMessage([{ ...attachment, ref: reference.path }]);
+ assert.equal(retry.localReference, reference.localReference);
+ assert.equal(retry.size, reference.size);
+});
+
++test("mixed draft dispatch and message retry retain both reference contracts", () => {
++ const line = { path: "/project/gpt.py", name: "gpt.py", kind: "file", token: "\ue002", lineRange: { start: 85, end: 86 } };
++ const draft = snapshotComposerDraft("Compare \ue001 and \ue002", [reference, line].map(row => ({ ...row, sessionId: "source" })), "source");
++ const fromDraft = loadFunction("../src/stores/helpers/store-helpers.ts", "promptAttachmentsFromDraft");
++ const attachments = fromDraft(draft.fileReferences);
++ assert.equal(attachments.length, 2);
++ assert.equal(attachments[0].localReference, reference.localReference);
++ assert.equal(attachments[0].size, reference.size);
++ assert.deepEqual({ ...attachments[1].lineRange }, line.lineRange);
++ const fromMessage = loadFunction("../src/stores/helpers/store-helpers.ts", "promptAttachmentsFromMessage", { isRenderableAttachment });
++ const retry = fromMessage(attachments.map(row => ({ ...row, ref: row.path })));
++ assert.equal(retry[0].localReference, reference.localReference);
++ assert.deepEqual({ ...retry[1].lineRange }, line.lineRange);
++});
++
+test("file card shows size, remains removable, and does not expand or preview contents", () => {
+ function element() {
+ return { dataset: {}, attrs: {}, events: {}, children: [], title: "", textContent: "",
+ setAttribute(key, value) { this.attrs[key] = value; },
+ addEventListener(key, handler) { this.events[key] = handler; },
+ append(...items) { this.children.push(...items); },
+ };
+ }
- const globals = { document: { createElement: element }, chipIconKey: () => "file", chipSvg: () => "", isPluginMark: () => false };
++ const globals = { document: { createElement: element }, chipIconKey: () => "file", chipSvg: () => "", isPluginMark: () => false, fileLineLabel };
+ globals.isEditableTextReference = loadFunction("../src/features/chat/composer/editor.ts", "isEditableTextReference", globals);
+ const build = loadFunction("../src/features/chat/composer/editor.ts", "buildChipElement", globals);
+ let removed;
+ const chip = build(reference, reference.token, "Remove", token => { removed = token; });
+ assert.equal(chip.children[1].textContent, "large.bin · 64 MiB");
+ assert.ok(chip.title.includes("67108865 B"));
+ assert.equal(chip.attrs.role, "listitem");
+ assert.equal(chip.dataset.image, undefined);
+ chip.children[2].events.click({ stopPropagation() {} });
+ assert.equal(removed, reference.token);
+});
diff --cc apps/desktop/test/composer-file-references.test.mjs
index d5e0002cb,000000000..8289129dc
mode 100644,000000..100644
--- a/apps/desktop/test/composer-file-references.test.mjs
+++ b/apps/desktop/test/composer-file-references.test.mjs
@@@ -1,102 -1,0 +1,122 @@@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import vm from "node:vm";
+import ts from "typescript";
+import { mkdir, mkdtemp, open, readdir, realpath, rename, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { referenceComposerFiles, resolveComposerFileReference } from "../electron/main/composer-file-references.ts";
+import { preparePromptAttachments, appendPromptFallbackPaths } from "../electron/main/prompt-attachments.ts";
+import { appendLocalFileReferenceContext } from "@pi-desktop/shared";
+import { consumeComposerPickerSelection, rememberComposerPickerSelection } from "../electron/main/composer-picker.ts";
+
+async function fixture(t) {
+ const root = await realpath(await mkdtemp(join(tmpdir(), "pi-file-reference-")));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const data = join(root, "data"), project = join(root, "project"), other = join(root, "other");
+ await Promise.all([data, project, other].map(path => mkdir(path)));
+ const path = join(root, "outside project & 中文.bin");
+ const file = await open(path, "w");
+ await file.truncate(64 * 1024 * 1024 + 1);
+ await file.close();
+ return { root, data, project, other, path };
+}
+
+test("large disk file becomes metadata, survives a new session, and refreshes size on send", async t => {
+ const { data, project, path } = await fixture(t);
+ const [reference] = await referenceComposerFiles(data, "source", project, [path]);
+ assert.equal(reference.path, path);
+ assert.equal(reference.size, 67108865);
+ assert.equal(reference.kind, "file");
+ assert.deepEqual(await readdir(data), ["composer-file-references"], "no scratch copy or content-addressed blob");
+ await writeFile(path, "changed");
+ const [prepared] = await preparePromptAttachments(data, "restored", project, [{ ...reference, size: 1 }], true, `Review @"${path}"`);
+ assert.equal(prepared.message.size, 7, "renderer size is not authoritative");
+ assert.equal(prepared.message.localReference, reference.localReference);
+ assert.equal(prepared.inlineData, undefined);
+ const prompt = appendPromptFallbackPaths("Review", [prepared]);
+ assert.ok(prompt.includes(path));
+ assert.ok(prompt.includes("7 bytes"));
+ assert.equal(appendLocalFileReferenceContext(prompt, [{ ...prepared.message, path }]), prompt, "history replay is idempotent");
+ assert.deepEqual(await readdir(data), ["composer-file-references"]);
+});
+
++test("disk metadata and project line ranges remain distinct in a mixed prompt", async t => {
++ const { data, project, path } = await fixture(t);
++ const [reference] = await referenceComposerFiles(data, "source", project, [path]);
++ const source = join(project, "gpt.py");
++ await writeFile(source, "first\nsecond\n");
++ const line = { kind: "file", path: source, name: "gpt.py", lineRange: { start: 1, end: 2 } };
++ const prepared = await preparePromptAttachments(data, "source", project, [reference, line], false, "Compare");
++ assert.equal(prepared.length, 2);
++ assert.equal(prepared[0].message.localReference, reference.localReference);
++ assert.equal(prepared[0].message.size, 67108865);
++ assert.deepEqual(prepared[1].message.lineRange, line.lineRange);
++ const prompt = appendPromptFallbackPaths("Compare", prepared);
++ assert.ok(prompt.includes("67108865 bytes"));
++ assert.ok(!prompt.includes(source), "line ranges are resolved by the scoped runtime Read");
++ assert.deepEqual(await readdir(data), ["composer-file-references"]);
++ for (const attachment of [{ ...reference, lineRange: line.lineRange }, { ...line, localReference: reference.localReference }]) {
++ await assert.rejects(preparePromptAttachments(data, "source", project, [attachment], false, "Inspect"), { errorCode: "INVALID_ARGUMENT" });
++ }
++});
++
+test("selection records reject forged paths, another project, remote context, and redirected files", async t => {
+ const { data, project, other, path, root } = await fixture(t);
+ const [reference] = await referenceComposerFiles(data, "source", project, [path]);
+ const resolve = (projectPath, source = path, id = reference.localReference) => resolveComposerFileReference(data, projectPath, source, id);
+ await assert.rejects(resolve(other), /does not belong/);
+ await assert.rejects(resolve(undefined), /unavailable/);
+ await assert.rejects(resolve(project, path, "../../escape"), /unavailable/);
+ await assert.rejects(resolve(project, join(root, "forged")), /does not belong/);
+ const moved = join(root, "moved.bin");
+ await rename(path, moved);
+ await assert.rejects(resolve(project), /Referenced file is unavailable/);
+ await symlink(moved, path);
+ await assert.rejects(resolve(project), /Referenced file is unavailable/);
+});
+
+test("a reference to an image remains metadata and never hydrates outside-project image bytes", async t => {
+ const { data, project, path } = await fixture(t);
+ const image = path + ".png";
+ await rename(path, image);
+ const [reference] = await referenceComposerFiles(data, "source", project, [image]);
+ const [prepared] = await preparePromptAttachments(data, "source", project, [reference], true, "Inspect");
+ assert.equal(prepared.message.kind, "file");
+ assert.equal(prepared.inlineData, undefined);
+ await assert.rejects(preparePromptAttachments(data, "source", project, [{ ...reference, localReference: undefined }], true, "Inspect"), /outside the session roots/);
+});
+
+test("native selection IPC binds sender and session before registering and dispatching a large reference", async t => {
+ const { data, project, path } = await fixture(t);
+ const source = readFileSync(new URL("../electron/main/ipc/workspace-ipc.ts", import.meta.url), "utf8");
+ const tree = ts.createSourceFile("workspace.ts", source, ts.ScriptTarget.Latest, true);
+ let callback;
+ function visit(node) {
+ if (ts.isCallExpression(node) && node.arguments[0]?.getText(tree) === "IPC.invoke.composerImportFiles") callback = node.arguments[1];
+ ts.forEachChild(node, visit);
+ }
+ visit(tree);
+ assert.ok(callback);
+ const code = ts.transpileModule(`(${callback.getText(tree)})`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const host = { call: async (_method, input) => ({ session: input.id === "source" ? { projectPath: project } : null }) };
+ const handler = vm.runInNewContext(code, {
+ host, getHost: () => host, dataDir: data,
+ assertMainWindowSender: event => assert.equal(event.sender.id, 1, "main sender required"),
+ consumeComposerPickerSelection, referenceComposerFiles,
+ importComposerFiles: () => assert.fail("reference must not invoke the byte importer"),
+ ErrorCodes: { NOT_FOUND: "NOT_FOUND", INVALID_ARGUMENT: "INVALID_ARGUMENT" },
+ });
+ const input = { sessionId: "source", token: rememberComposerPickerSelection([path], 1), reference: true };
+ await assert.rejects(handler({ sender: { id: 2 } }, input), /main sender/);
+ await assert.rejects(handler({ sender: { id: 1 } }, { ...input, sessionId: "deleted" }), /session not found/);
+ const { files } = await handler({ sender: { id: 1 } }, input);
+ assert.equal(files[0].path, path);
+ assert.equal(files[0].size, 67108865);
+ await assert.rejects(handler({ sender: { id: 1 } }, input), /selection is unavailable/);
+ const [prepared] = await preparePromptAttachments(data, "source", project, files, false, "Inspect");
+ assert.equal(prepared.message.size, 67108865);
+ assert.ok(appendPromptFallbackPaths("Inspect", [prepared]).includes("67108865 bytes"));
+ assert.deepEqual(await readdir(data), ["composer-file-references"]);
+});
diff --cc apps/desktop/test/composer-input-history.test.mjs
index 75e23faad,12cc004c5..0d3b37bcc
--- a/apps/desktop/test/composer-input-history.test.mjs
+++ b/apps/desktop/test/composer-input-history.test.mjs
@@@ -79,21 -79,6 +79,34 @@@ test("records per conversation, newest-
assert.deepEqual(texts("s1"), ["b", "a"]);
});
+test("local file history restores path, size and reference metadata without a source snapshot", () => {
+ const storage = installStorage();
+ const reference = {
+ path: "/synthetic/unavailable-large-file.bin", name: "large-file.bin", kind: "file",
+ size: 67108865, localReference: "11111111-2222-4333-8444-555555555555", token: "\ue001",
+ };
+ rememberComposerInput("source", snap("Inspect \ue001", [reference]));
+ assert.deepEqual(loadComposerInputHistory("source")[0].fileReferences, [reference]);
+ const stored = JSON.parse(storage.get(KEY)).sessions[0].entries[0].fileReferences[0];
+ assert.deepEqual(stored, reference, "history stores only the live reference metadata");
+ const harness = createHarness("store", { sessionId: "source" });
+ harness.run("older", { draftEmpty: true });
+ assert.deepEqual(harness.state.applied[0].references, [{ ...reference, attached: true }]);
+});
+
++test("input recall preserves line selections alongside local disk references", () => {
++ installStorage();
++ const references = [
++ { path: "/project/gpt.py", name: "gpt.py", kind: "file", token: "\ue001", lineRange: { start: 85, end: 86 } },
++ { path: "/outside/large.bin", name: "large.bin", kind: "file", token: "\ue002", size: 67108865, localReference: "11111111-2222-4333-8444-555555555555" },
++ ];
++ rememberComposerInput("source", snap("Compare \ue001 and \ue002", references));
++ assert.deepEqual(loadComposerInputHistory("source")[0].fileReferences, references);
++ const harness = createHarness("store", { sessionId: "source" });
++ harness.run("older", { draftEmpty: true });
++ assert.deepEqual(harness.state.applied[0].references, references.map(row => ({ ...row, attached: true })));
++});
++
test("a conversation never recalls another conversation's prompts (AC1)", () => {
installStorage();
rememberComposerInput("s1", snap("from A"));
diff --cc crates/host-core/src/sessions.rs
index aca114058,47482ec09..fbeaa7e63
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@@ -5956,45 -5962,33 +5971,60 @@@ mod tests
);
}
+ #[test]
+ fn local_file_attachments_roundtrip_as_canonical_blocks() {
+ let db = test_db();
+ let session = create_session(&db, None, None, None, None, None).unwrap();
+ let mut user = user_msg(
+ "local-file",
+ "Inspect the reference",
+ "2026-11-13T00:00:00Z",
+ );
+ user.attachments = Some(vec![MessageAttachment {
+ local_reference: Some("11111111-2222-4333-8444-555555555555".into()),
++ line_range: None,
+ kind: "file".into(),
+ name: "large.bin".into(),
+ reference: "/synthetic/large.bin".into(),
+ mime_type: None,
+ size: Some(67_108_865),
+ text: None,
+ inline_path: Some("@/synthetic/large.bin".into()),
+ }]);
+ append_message(&db, &session.id, &user, None).unwrap();
+ let detail = get_session(&db, &session.id).unwrap().unwrap();
+ assert_eq!(detail.messages[0].attachments, user.attachments);
+ }
+
#[test]
fn user_attachments_roundtrip_as_canonical_blocks() {
let db = test_db();
let session = create_session(&db, None, None, None, None, None).unwrap();
let mut user = user_msg("image-1", "这是什么", "2025-05-01T00:00:00Z");
- user.attachments = Some(vec![MessageAttachment {
- local_reference: None,
- kind: "image".into(),
- name: "image.png".into(),
- reference: "attachments/abc123".into(),
- mime_type: Some("image/png".into()),
- size: Some(42),
- text: None,
- inline_path: Some("@/scratch/pasted/image.png".into()),
- }]);
+ user.attachments = Some(vec![
+ MessageAttachment {
++ local_reference: None,
+ kind: "image".into(),
+ name: "image.png".into(),
+ reference: "attachments/abc123".into(),
+ mime_type: Some("image/png".into()),
+ size: Some(42),
+ text: None,
+ inline_path: Some("@/scratch/pasted/image.png".into()),
+ line_range: None,
+ },
+ MessageAttachment {
++ local_reference: None,
+ kind: "file".into(),
+ name: "gpt.py".into(),
+ reference: "/project/src/gpt.py".into(),
+ mime_type: None,
+ size: None,
+ text: None,
+ inline_path: Some("/project/src/gpt.py (85:86)".into()),
+ line_range: Some(FileLineRange { start: 85, end: 86 }),
+ },
+ ]);
append_message(&db, &session.id, &user, None).unwrap();
diff --cc docs/adr/file-manager-line-references.md
index 000000000,f42f9567c..97c1b5af6
mode 000000,100644..100644
--- a/docs/adr/file-manager-line-references.md
+++ b/docs/adr/file-manager-line-references.md
@@@ -1,0 -1,37 +1,42 @@@
+ # ADR: File Manager line references
+
+ - Status: Implemented candidate
+ - Date: 2026-11-06
+
+ ## Context
+
+ The File Manager knows the source file and CodeMirror selection range.
+ The Composer owns draft mutation and the Host owns file access. A text-only
+ clipboard cannot carry the source identity independently from the selection.
+
+ ## Decision
+
+ The source view places plain text and path/range metadata in the clipboard.
+ The explicit context-menu action uses a panel invocation gated to the visible,
+ enabled File Manager view, its existing view and read grants, the active
+ project, and the selected session. The registered File Manager can be bundled
+ or installed. Both paths create the same draft reference. Composer events
+ confer no file permission.
+
+ The view capability advertises bridge support from the loaded instance and
+ its grants. Registration is authorized on invocation, with a bounded Host
+ query, so a Host restart cannot delay opening the view or freeze a transient
+ registry failure into its preload capability.
+
+ The selected text is never used as the model payload for a reference. Main
+ validates the reference path against the Session project folders. At prompt
+ execution, the Agent runtime invokes the existing Read tool with the inclusive
+ range converted to its zero-based offset and line count. The Host continues
+ to authorize the tool call and enforce its output limits. A successful result
+ is included as file context. A blocked or failed read is reported separately
+ in the provider prompt. Prefetches do not create assistant tool history.
+
+ ## Consequences
+
+ References are initially available for local project source views with one
+ selection. Rendered and remote previews retain their clipboard behavior.
++
++Line ranges coexist with native disk-file references in one prompt and input
++history. Each attachment has one reference kind: line selections retain their
++scoped Read path, while registered disk files retain metadata-only dispatch.
++Combining `lineRange` and `localReference` on one attachment is invalid.
diff --cc docs/spec/04-ux/08-component-spec.md
index 8ee2fa60d,9762b5e2a..422747dae
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@@ -4826,3 -4826,24 +4826,29 @@@ The bundled File Manager validates eac
### 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).
++
++Line ranges coexist with native disk-file references in one prompt and input
++history. Each attachment has one reference kind: line selections retain their
++scoped Read path, while registered disk files retain metadata-only dispatch.
++Combining `lineRange` and `localReference` on one attachment is invalid.
diff --cc docs/spec/06-delivery/04-e2e-test-plan.md
index c74157719,d3a408bb3..44e637a36
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@@ -20785,3 -20748,55 +20785,63 @@@ does not qualify native Electron intera
#### 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`.
+
++Add a line selection and a native disk-file reference to the same draft. Recall
++it from input history and verify the range, disk identity and byte size remain.
++Send and restart: the model context retains the scoped file-lines block and the
++disk path/size metadata, with no synthetic tool history or eager disk-file read.
++An attachment combining `lineRange` and `localReference` is rejected before any
++Read. Coverage: `composer-input-history.test.mjs`, `composer-file-reference-draft.test.mjs`,
++`composer-file-references.test.mjs` and `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/04-ux/08-component-spec.md
index 37f7faade,4863e1576..a78207074
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@@ -3152,3 -3152,16 +3152,21 @@@ default nor provider configuration. OAu
### 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).
++
++Line ranges coexist with native disk-file references in one prompt and input
++history. Each attachment has one reference kind: line selections retain their
++scoped Read path, while registered disk files retain metadata-only dispatch.
++Combining `lineRange` and `localReference` on one attachment is invalid.
diff --cc docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 3e44b643a,603b5ab3a..11b501fb5
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@@ -10617,3 -10617,30 +10617,38 @@@ does not qualify native Electron intera
#### 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.
+
++Add a line selection and a native disk-file reference to the same draft. Recall
++it from input history and verify the range, disk identity and byte size remain.
++Send and restart: the model context retains the scoped file-lines block and the
++disk path/size metadata, with no synthetic tool history or eager disk-file read.
++An attachment combining `lineRange` and `localReference` is rejected before any
++Read. Coverage: `composer-input-history.test.mjs`, `composer-file-reference-draft.test.mjs`,
++`composer-file-references.test.mjs` and `runtime.test.ts`.
++
+ ### 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 packages/agent-runtime/src/runtime.test.ts
index de67f3f21,fb6d7b8be..805de727d
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@@ -227,6 -228,127 +228,135 @@@ 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 } };
++ const local = { kind: "file" as const, path: "/external/large.bin", name: "large.bin", size: 67108865, localReference: "11111111-2222-4333-8444-555555555555" };
+ try {
- await runtime.prompt({ text: "Explain these lines", attachments: [reference, reference] }, "prompt", "turn");
++ await runtime.prompt({ text: "Explain these lines", attachments: [reference, reference, local] }, "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(model).toHaveBeenCalledWith(expect.objectContaining({ content: expect.stringContaining("/external/large.bin (67108865 bytes)") }));
+ 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 } },
+ ] },
++ { label: "ambiguous local and line", attachments: [
++ { kind: "file" as const, path: "/project/a.txt", name: "a.txt", lineRange: { start: 1, end: 2 }, localReference: "11111111-2222-4333-8444-555555555555" },
++ ] },
+ ])("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" }],
++ lineRange: { start: 85, end: 86 }, text: "recorded saved excerpt" },
++ { kind: "file", ref: "/external/large.bin", name: "large.bin", size: 67108865,
++ localReference: "11111111-2222-4333-8444-555555555555" }],
+ }] });
+ 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);
++ expect(messages.find(message => message.role === "user")?.content).toContain("/external/large.bin (67108865 bytes)");
+ } 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 b9bc9565f,ef7da8540..7a8a49895
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@@ -370,13 -374,24 +375,25 @@@ export type RuntimePrompt =
* from the provider request would be context the user never got.
*/
function promptText(input: RuntimePrompt): string {
- const references = (input.attachments ?? [])
+ const attachments = input.attachments ?? [];
+ const sessions = attachments
+ .filter(attachment => attachment.kind === "session")
.map((attachment) => sessionReferenceBlock(attachment))
.filter((block): block is string => block !== null);
+ const fileLines = attachments.filter(attachment => attachment.lineRange && attachment.text !== undefined)
+ .slice(0, MAX_FILE_LINE_REFERENCES)
+ .map(attachment => {
+ const source = escapeAttribute(fileLineLabel(attachment.path, attachment.lineRange!));
+ const text = attachment.text!.replaceAll("<", "&lt;");
+ return attachment.fileReferenceError
+ ? `<file_reference_error source="${source}" status="${attachment.fileReferenceError}">\n${text}\n</file_reference_error>`
+ : `<file_lines source="${source}">\n${text}\n</file_lines>`;
+ });
+ const references = [...sessions, ...fileLines];
- return references.length
+ const text = references.length
? `${input.text}\n\n${references.join("\n\n")}`.trim()
: input.text;
+ return appendLocalFileReferenceContext(text, input.attachments ?? []);
}
/** One provider image block for an attachment whose bytes crossed this turn. */
@@@ -9398,6 -9420,64 +9423,64 @@@ Do not invent objections or turn specul
});
}
+ /** 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))) {
++ if (references.some(attachment => attachment.kind !== "file" || attachment.localReference !== undefined || !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[] = [];
+ const seen = new Set<string>();
+ for (const attachment of input.attachments) {
+ if (attachment.lineRange === undefined) {
+ attachments.push(attachment);
+ continue;
+ }
+ const range = parseFileLineRange(attachment.lineRange)!;
+ const key = JSON.stringify([attachment.path, range.start, range.end]);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ if (this.runCancelled || this.disposed || turnId !== this.turnId) throw turnAbortedError("Turn ended during file reference reads");
+ const args = {
+ path: attachment.path,
+ offset: range.start - 1,
+ limit: range.end - range.start + 1,
+ };
+ const toolCall = { type: "toolCall" as const, id: randomUUID(), name: "Read", arguments: args };
+ const timestamp = Date.now();
+ const tools = read ? [read] : [];
+ const prefetch = { blocked: !read };
+ this.fileLineReadCalls.set(toolCall.id, prefetch);
+ const { result, isError } = await runToolCall(toolCall, {
+ tools,
+ assistantMessage: {
+ role: "assistant", content: [toolCall], api: this.model.api, provider: this.model.provider,
+ model: this.model.id, usage: usageToPi(undefined), stopReason: "toolUse", timestamp,
+ },
+ context: { messages: this.agent.state.messages, tools },
+ beforeToolCall: async context => {
+ const decision = await this.beforeToolCall(context);
+ if (decision?.block) prefetch.blocked = true;
+ return decision;
+ },
+ afterToolCall: context => this.afterToolCall(context),
+ }).finally(() => this.fileLineReadCalls.delete(toolCall.id));
+ const text = result.content.flatMap(part => part.type === "text" ? [part.text] : []).join("\n");
+ if (this.runCancelled || this.disposed || turnId !== this.turnId) throw turnAbortedError("Turn ended during file reference reads");
+ attachments.push({
+ ...attachment, lineRange: range, text,
+ fileReferenceError: isError ? (prefetch.blocked ? "blocked" : "failed") : undefined,
+ });
+ }
+ return { ...input, attachments };
+ }
+
private async promptTurn(
input: string | RuntimePrompt,
userMessageId: string | undefined,
diff --cc packages/shared/src/types/messages.ts
index 81f6e8f69,a34706991..bcb5f908d
--- a/packages/shared/src/types/messages.ts
+++ b/packages/shared/src/types/messages.ts
@@@ -70,10 -70,10 +70,11 @@@ export type SessionUsageCost =
export { addUsage, contextOccupancyTokens, withUsageIdentity } from "../message-usage.js";
export type MessageAttachment = {
+ localReference?: string;
+ lineRange?: import("../file-line-reference.js").FileLineRange;
kind: "image" | "file" | "session";
name: string;
- /** Workspace-relative path, session-scratch absolute path, or a session id. */
+ /** Workspace-relative path, absolute scratch or project line-reference path, or a session id. */
ref: string;
mimeType?: string;
size?: number;