Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(composer): accept file manager line references
Linuxdazhaoa38f49990f25
diff --git a/apps/desktop/electron/main/file-line-reference.ts b/apps/desktop/electron/main/file-line-reference.tsnew file mode 100644index 000000000..ed50c6481--- /dev/null+++ b/apps/desktop/electron/main/file-line-reference.ts@@ -0,0 +1,76 @@+import { realpathSync } from "node:fs";+import { isAbsolute, relative } from "node:path";+import { 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";+import type { PluginSessionContext } from "./services/plugin-session-context";+import { projectFolderPaths } from "./workspace-roots.ts";++export const FILE_LINES_VIEW_KEY = "pi.file-manager/manager";++type FileLineBridge = {+ plugins: Pick<PluginRuntime, "getLoaded">;+ pluginViews: Pick<PluginViewHost, "isVisibleViewSender">;+ pluginSession: Pick<PluginSessionContext, "snapshot">;+ pluginActiveInProject: (pluginId: string, projectPath: string | null) => boolean;+ getHost: () => Pick<HostProcess, "call"> | null;+ getWorkspacePath: () => string | null;+ publish: (selection: { sessionId: string; reference: FileLineReference }) => void;+};++export async function addFileLinesFromView(+ pluginId: string,+ senderId: number | undefined,+ payload: unknown,+ bridge: FileLineBridge,+): Promise<{ ok: true }> {+ const reference = parseFileLineReference(payload);+ const currentTarget = () => {+ const loaded = bridge.plugins.getLoaded(pluginId);+ const selected = bridge.pluginSession.snapshot();+ if (+ !reference || !selected || !loaded || loaded.development || loaded.disposing ||+ !loaded.permissions.has("fs.read") || !loaded.permissions.has("ui.view") ||+ !bridge.pluginViews.isVisibleViewSender(senderId, FILE_LINES_VIEW_KEY) ||+ !bridge.pluginActiveInProject(pluginId, selected.projectPath) ||+ reference.workspace !== bridge.getWorkspacePath() ||+ !fileLinePathInProject(reference.path, selected.projectPath)+ ) return null;+ return { loaded, selected };+ };+ const target = currentTarget();+ if (!reference || !target) throw new Error("The file selection is outside the active project or session.");++ const host = bridge.getHost();+ const registry = await host?.call<{+ plugins: Array<{ id: string; enabled: boolean; version: string }>;+ }>("plugins.list");+ const current = currentTarget();+ if (+ bridge.getHost() !== host || !current || current.loaded !== target.loaded ||+ current.selected.sessionId !== target.selected.sessionId ||+ current.selected.projectPath !== target.selected.projectPath ||+ !registry?.plugins.some(item =>+ item.id === pluginId && item.enabled && item.version === target.loaded.manifest.version+ )+ ) throw new Error("The File Manager or target session is no longer active.");++ bridge.publish({ sessionId: target.selected.sessionId, reference });+ return { ok: true };+}++export function fileLinePathInProject(path: string, projectPath: string | null): boolean {+ if (typeof path !== "string" || !isAbsolute(path) || path.length > 4096 || /[\0\r\n]/.test(path)) return false;+ const canonical = (value: string) => {+ try { return realpathSync(value); } catch { return value; }+ };+ const target = canonical(path);+ return projectFolderPaths(projectPath).some(root => {+ const contains = (base: string, candidate: string) => {+ const child = relative(base, candidate);+ return child !== "" && child !== ".." && !/^\.\.[/\\]/.test(child) && !isAbsolute(child);+ };+ return contains(root, path) && contains(canonical(root), target);+ });+}diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.tsindex cac93579b..3700349b4 100644--- a/apps/desktop/electron/main/ipc/agent-ipc.ts+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts@@ -176,9 +176,10 @@ export function registerAgentIpc({sessionId: req.sessionId, expectedTurnId: req.expectedTurnId, message,content: appendPromptFallbackPaths(steerContent, prepared),...(mcpExpansion ? { mcpServerIds: mcpExpansion.mcpServerIds, mcpToolNames: mcpExpansion.mcpToolNames } : {}),- attachments: prepared.filter((attachment) => attachment.inlineData).map((attachment) => ({+ attachments: prepared.filter((attachment) => attachment.inlineData || attachment.message.lineRange).map((attachment) => ({path: attachment.message.ref, name: attachment.message.name, kind: attachment.message.kind,mimeType: attachment.message.mimeType, size: attachment.message.size, data: attachment.inlineData,+ ...(attachment.message.lineRange ? { lineRange: attachment.message.lineRange } : {}),...(attachment.message.inlinePath ? { inlinePath: attachment.message.inlinePath } : {}),})),});@@ -544,7 +545,7 @@ export function registerAgentIpc({...(sessionMessage ? { sessionMessage: sessionMessage.origin } : {}),attachments: [...preparedAttachments- .filter((attachment) => attachment.inlineData)+ .filter((attachment) => attachment.inlineData || attachment.message.lineRange).map((attachment) => ({path: attachment.message.ref,name: attachment.message.name,@@ -552,6 +553,7 @@ export function registerAgentIpc({mimeType: attachment.message.mimeType,size: attachment.message.size,data: attachment.inlineData,+ ...(attachment.message.lineRange ? { lineRange: attachment.message.lineRange } : {}),...(attachment.message.inlinePath? { inlinePath: attachment.message.inlinePath }: {}),diff --git a/apps/desktop/electron/main/plugin-panel-host.ts b/apps/desktop/electron/main/plugin-panel-host.tsindex de687224b..b8a3471ef 100644--- a/apps/desktop/electron/main/plugin-panel-host.ts+++ b/apps/desktop/electron/main/plugin-panel-host.ts@@ -91,7 +91,7 @@ type BridgeHandler = (pluginId: string,channel: string,payload?: Record<string, unknown>,- context?: { droppedPath?: string },+ context?: { droppedPath?: string; senderId?: number },) => Promise<unknown>;/** Reports an egress attempt a panel was not allowed to make. */@@ -256,7 +256,7 @@ export class PluginPanelHost {channel === "fs.registerDropped"? this.consumeDroppedPath(event.sender.id, payload?.path): undefined;- return this.bridge(pluginId, channel, payload, droppedPath ? { droppedPath } : undefined);+ return this.bridge(pluginId, channel, payload, { senderId: event.sender.id, ...(droppedPath ? { droppedPath } : {}) });},);diff --git a/apps/desktop/electron/main/plugin-view-host.ts b/apps/desktop/electron/main/plugin-view-host.tsindex 72baf263c..57deb5e78 100644--- a/apps/desktop/electron/main/plugin-view-host.ts+++ b/apps/desktop/electron/main/plugin-view-host.ts@@ -27,10 +27,12 @@ import {type PluginPanelBlockedRequest,} from "./plugin-panel-host";import {+ PLUGIN_PANEL_COMPOSER_FILE_LINES_ARGUMENT,PLUGIN_PANEL_EMBEDDED_ARGUMENT,PLUGIN_PANEL_LOCALE_ARGUMENT_PREFIX,type PluginPanelTheme,} from "../shared/plugin-panel-chrome";+import { FILE_LINES_VIEW_KEY } from "./file-line-reference";/*** Re-exported so the location contract stays addressable through the module@@ -222,6 +224,10 @@ export class PluginViewHost {return this.views.has(pluginViewKey(pluginId, viewId));}+ isVisibleViewSender(senderId: number | undefined, key: string): boolean {+ return senderId !== undefined && this.visibleKey === key && this.views.get(key)?.view.webContents.id === senderId;+ }+/*** The plugin owning a web contents, so `PluginPanelHost` can accept bridge* calls from docked views on the same channel it serves panel windows.@@ -531,6 +537,9 @@ export class PluginViewHost {`${PLUGIN_PANEL_LOCALE_ARGUMENT_PREFIX}${encodeURIComponent(request.locale)}`,`--pi-plugin-panel-theme=${request.theme}`,PLUGIN_PANEL_EMBEDDED_ARGUMENT,+ ...(pluginViewKey(request.pluginId, request.viewId) === FILE_LINES_VIEW_KEY+ ? [PLUGIN_PANEL_COMPOSER_FILE_LINES_ARGUMENT]+ : []),],},});diff --git a/apps/desktop/electron/main/prompt-attachments.ts b/apps/desktop/electron/main/prompt-attachments.tsindex 7063434b1..2d9d0ce12 100644--- a/apps/desktop/electron/main/prompt-attachments.ts+++ b/apps/desktop/electron/main/prompt-attachments.ts@@ -20,6 +20,9 @@ import { copyFile, readFile } from "node:fs/promises";import { isAbsolute, join, relative, resolve } from "node:path";import {ErrorCodes,+ fileLineLabel,+ MAX_FILE_LINE_REFERENCES,+ parseFileLineRange,formatFileInsert,formatPromptPathText,imageExceedsInlineDimensions,@@ -31,6 +34,7 @@ import {type AgentPromptAttachment,type MessageAttachment,} from "@pi-desktop/shared";+import { fileLinePathInProject } from "./file-line-reference.ts";export { MAX_INLINE_IMAGE_BYTES } from "@pi-desktop/shared";@@ -240,6 +244,9 @@ export async function preparePromptAttachments(promptContent: string,): Promise<PreparedPromptAttachment[]> {const prepared: PreparedPromptAttachment[] = [];+ if (attachments.filter(attachment => attachment.lineRange !== undefined).length > MAX_FILE_LINE_REFERENCES) {+ throw Object.assign(new Error("Too many file line references"), { errorCode: ErrorCodes.INVALID_ARGUMENT });+ }// Reference order is the user's order, so each entry takes the next matching// `@path` text the prompt holds.const inlineSpans = locateInlinePromptPaths(@@ -247,6 +254,21 @@ export async function preparePromptAttachments(attachments.map((attachment) => attachment.path),);for (const [index, attachment] of attachments.entries()) {+ if (attachment.lineRange !== undefined) {+ 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;+ }const source = resolvePromptPath(dataRoot, sessionId, projectPath, attachment.path);if (!source) {throw Object.assign(new Error(`Attachment path is outside the session roots: ${attachment.path}`), {@@ -347,7 +369,7 @@ export function appendPromptFallbackPaths(attachments: readonly PreparedPromptAttachment[],): string {const paths = attachments- .filter((attachment) => !attachment.inlineData)+ .filter((attachment) => !attachment.inlineData && !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 --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.tsindex 5e78660eb..a5630661c 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -5,6 +5,7 @@ import { createPluginWorkspaceReader } from "../remote/plugin-workspace-files";import {IPC,ErrorCodes,+ FILE_LINES_ADD_CHANNEL,type ActivationScope,type AppSettings,type BrowserState,@@ -64,6 +65,8 @@ import { createComposerSuggestionRelay } from "./composer-suggestion";import type { Logger } from "../logger";import type { PluginAppearance } from "../../shared/plugin-panel-chrome";+import { addFileLinesFromView } from "../file-line-reference";+export type PluginServicesDependencies = {dataDir: string;logger: Logger;@@ -131,8 +134,13 @@ export function createPluginServices({(error as { errorCode?: string } | null | undefined)?.errorCode ===ErrorCodes.HOST_UNAVAILABLE;const pluginPanels = new PluginPanelHost(- async (pluginId, channel, payload, context) =>- plugins.invokePanelBridge(pluginId, channel, payload, context),+ async (pluginId, channel, payload, context) => {+ if (channel !== FILE_LINES_ADD_CHANNEL) return plugins.invokePanelBridge(pluginId, channel, payload, context);+ return addFileLinesFromView(pluginId, context?.senderId, payload, {+ plugins, pluginViews, pluginSession, pluginActiveInProject, getHost, getWorkspacePath,+ publish: (selection) => sendToRenderer(IPC.event.composerFileLines, selection),+ });+ },// A panel reaching for an undeclared host is the shape an exfiltration// attempt takes, so it is logged like a denied API call rather than dropped// silently in the network layer.diff --git a/apps/desktop/electron/preload/plugin-panel.ts b/apps/desktop/electron/preload/plugin-panel.tsindex a7cd53f28..d809e8699 100644--- a/apps/desktop/electron/preload/plugin-panel.ts+++ b/apps/desktop/electron/preload/plugin-panel.ts@@ -4,6 +4,7 @@ import {PLUGIN_PANEL_CHROME_META_NAME,PLUGIN_PANEL_CHROME_VERSION,PLUGIN_PANEL_CHROME_PAINT_THROUGH_VERSION,+ PLUGIN_PANEL_COMPOSER_FILE_LINES_ARGUMENT,PLUGIN_PANEL_EMBEDDED_ARGUMENT,PLUGIN_PANEL_WIDGET_ARGUMENT,PLUGIN_PANEL_LAUNCH_EVENT,@@ -40,6 +41,9 @@ ipcRenderer.on(`pi-plugin-panel-event:${PLUGIN_PANEL_LAUNCH_EVENT}`, (};});const bridge = {+ ...(process.argv.includes(PLUGIN_PANEL_COMPOSER_FILE_LINES_ARGUMENT)+ ? { capabilities: { composerFileLines: true } }+ : {}),invoke: async (channel: string, payload?: Record<string, unknown>) => {return ipcRenderer.invoke("pi-plugin-panel-invoke", channel, payload ?? {});},diff --git a/apps/desktop/electron/shared/plugin-panel-chrome.ts b/apps/desktop/electron/shared/plugin-panel-chrome.tsindex f4ec89468..da19c1735 100644--- a/apps/desktop/electron/shared/plugin-panel-chrome.ts+++ b/apps/desktop/electron/shared/plugin-panel-chrome.ts@@ -45,10 +45,11 @@ export const PLUGIN_PANEL_LOCALE_ARGUMENT_PREFIX = "--pi-plugin-panel-locale=";** An embedded view has no window to minimize, maximize, or drag, so the preload* skips the control capsule and the 46px safe area entirely and reports a- * titlebar height of 0. `window.pluginBridge` is identical either way, so the+ * titlebar height of 0. Both placements use the same panel bridge, so the* same HTML entry works in both placements (ADR 0092 §2 addendum).*/export const PLUGIN_PANEL_EMBEDDED_ARGUMENT = "--pi-plugin-panel-embedded=1";+export const PLUGIN_PANEL_COMPOSER_FILE_LINES_ARGUMENT = "--pi-plugin-panel-composer-file-lines=1";/*** Marks a plugin surface as a floating widget: a transparent, frameless windowdiff --git a/apps/desktop/src/features/chat/composer/editor.ts b/apps/desktop/src/features/chat/composer/editor.tsindex c6e5322bb..14ecda8fa 100644--- a/apps/desktop/src/features/chat/composer/editor.ts+++ b/apps/desktop/src/features/chat/composer/editor.ts@@ -4,6 +4,7 @@ import {} from "@pi-desktop/shared";import type { ComposerPluginPart } from "../../../lib/composer-smart-stop";import type { ComposerFileReference } from "./model";+import { fileLineLabel, type FileLineRange } from "@pi-desktop/shared";export { type ComposerFileReference } from "./model";@@ -42,6 +43,7 @@ export function createFileReference(kind?: "image" | "file" | "session" | "directory";mimeType?: string;token?: string;+ lineRange?: FileLineRange;plugin?: ComposerPluginPart;},): ComposerFileReference {@@ -60,6 +62,7 @@ export function createFileReference(kind: metadata?.kind ?? (isImageFilePath(path) ? "image" : "file"),...(metadata?.mimeType ? { mimeType: metadata.mimeType } : {}),...(metadata?.token ? { token: metadata.token } : {}),+ ...(metadata?.lineRange ? { lineRange: metadata.lineRange } : {}),...(metadata?.plugin ? { plugin: metadata.plugin } : {}),};}@@ -262,6 +265,7 @@ function chipIconKey(reference: ComposerFileReference): string {if (reference.plugin?.kind === "fold") return "fold";if (reference.kind === "session") return "session";if (reference.kind === "directory") return "dir";+ if (reference.lineRange) return "file";const mime = reference.mimeType ?? "";if (reference.kind === "image" || mime.startsWith("image/")) return "image";const name = reference.name;@@ -280,7 +284,7 @@ function chipSvg(key: string, size = 13): string {}export function isEditableTextReference(reference: ComposerFileReference): boolean {- if (isPluginMark(reference) || reference.kind === "directory") return false;+ if (isPluginMark(reference) || reference.kind === "directory" || reference.lineRange) return false;return reference.mimeType?.toLowerCase() === "text/plain" || /\.txt$/i.test(reference.name);}@@ -320,7 +324,8 @@ function buildChipElement(? () => onOpenSession(token): undefined;chip.setAttribute("role", activate ? "button" : "listitem");- chip.setAttribute("aria-label", `${reference.name} — ${origin}`);+ const label = reference.lineRange ? fileLineLabel(reference.name, reference.lineRange) : reference.name;+ chip.setAttribute("aria-label", `${label} — ${origin}`);if (activate) {chip.tabIndex = 0;// Only a text reference expands into editable text; an image chip opens@@ -346,7 +351,7 @@ function buildChipElement(const nameSpan = document.createElement("span");nameSpan.className = "composer-chip-name";- nameSpan.textContent = reference.name;+ nameSpan.textContent = label;const remove = document.createElement("button");remove.type = "button";diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.tsindex 48df11308..a8fd892c1 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts@@ -1,12 +1,13 @@import { readComposerDraft, readComposerDraftRevision } from "../../../../lib/composer-draft-cache";import {+ useEffect,useState,useRef,type ClipboardEvent,type DragEvent as ReactDragEvent,} from "react";import type { TFunction } from "i18next";-import { parseSessionLinks, sessionLinkSpans } from "@pi-desktop/shared";+import { FILE_LINES_CLIPBOARD_TYPE, MAX_FILE_LINE_REFERENCES, parseFileLineReference, parseSessionLinks, sessionLinkSpans, type FileLineReference } from "@pi-desktop/shared";import { materializeDraftSession, useAppStore } from "../../../../stores/app-store";import { api } from "../../../../lib/api";import {@@ -34,6 +35,7 @@ import {type ComposerFileReference,} from "../editor";import type { ComposerDraftController } from "./useComposerDraft";+import { normalizeProjectPath } from "../../../../lib/sidebar-session-groups";type UseComposerAttachmentsOptions = {inputBlocked: boolean;@@ -93,6 +95,39 @@ export function useComposerAttachments({const snapshotReferences = (sourceSessionId: string) =>draft.snapshotReferences(sourceSessionId);+ const addFileLineReference = (reference: FileLineReference, editor: HTMLDivElement) => {+ const state = useAppStore.getState();+ if (isInputBlocked || state.activeSessionId !== activeSessionId || !state.activeProjectPath ||+ normalizeProjectPath(reference.workspace) !== normalizeProjectPath(state.activeProjectPath)) return false;+ const owner = activeSessionId ?? "";+ const previous = snapshotReferences(owner);+ if (previous.some(item => item.path === reference.path && item.lineRange?.start === reference.start && item.lineRange.end === reference.end)) return true;+ if (previous.filter(item => item.lineRange).length >= MAX_FILE_LINE_REFERENCES) {+ state.showToast(t("chat.fileLineReferenceLimit", { count: MAX_FILE_LINE_REFERENCES }), { variant: "error" });+ return true;+ }+ const { start, end } = editorSelectionRange(editor);+ const source = readEditorValue(editor);+ const token = nextChipToken();+ const chip = createFileReference(reference.path, undefined, owner, {+ kind: "file",+ lineRange: { start: reference.start, end: reference.end },+ token,+ });+ const text = source.slice(0, start) + token + source.slice(end);+ const references = [...previous.map(item => createFileReference(item.path, item.name, owner, item)), chip];+ writeComposerDraft(draftKey, { text, fileReferences: references.map(draftFileReference) }, state.activeProjectPath);+ draft.applyEditorDraft(text, references, start + token.length);+ return true;+ };+ const fileLineInput = useRef({ activeSessionId, draft, addFileLineReference });+ fileLineInput.current = { activeSessionId, draft, addFileLineReference };+ useEffect(() => api.onComposerFileLines(({ sessionId, reference }) => {+ const current = fileLineInput.current;+ const editor = current.draft.ref.current;+ if (editor && sessionId === current.activeSessionId && current.addFileLineReference(reference, editor)) editor.focus();+ }), []);+const pickAndAttach = async () => {// The ref closes the gap before React re-renders the disabled button.if (pickerInFlight.current || isInputBlocked) return;@@ -226,6 +261,15 @@ export function useComposerAttachments({return;}if (isInputBlocked) return;+ const fileLines = event.clipboardData.getData(FILE_LINES_CLIPBOARD_TYPE);+ if (fileLines && fileLines.length <= 9000) {+ let reference: FileLineReference | undefined;+ try { reference = parseFileLineReference(JSON.parse(fileLines)); } catch { /* Plain text remains available. */ }+ if (reference && addFileLineReference(reference, event.currentTarget)) {+ event.preventDefault();+ return;+ }+ }const text = event.clipboardData.getData("text/plain");const pastedFiles = clipboardFiles(event.clipboardData);const preferText = preferClipboardText(text, pastedFiles, api.getDroppedFilePath);diff --git a/apps/desktop/src/features/chat/composer/model.ts b/apps/desktop/src/features/chat/composer/model.tsindex b56bce388..70958bd75 100644--- a/apps/desktop/src/features/chat/composer/model.ts+++ b/apps/desktop/src/features/chat/composer/model.ts@@ -57,6 +57,7 @@ export type ComposerPrefill = {};export type ComposerFileReference = {+ lineRange?: import("@pi-desktop/shared").FileLineRange;id: string;sessionId: string;path: string;diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex b641325f9..705f958a3 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -1932,6 +1932,8 @@ export const api = {* only the renderer knows whether the draft can take it. A malformed message* is ignored — nothing here decides whether a plugin's suggestion is valid.*/+ onComposerFileLines: (listener: (payload: { sessionId: string; reference: import("@pi-desktop/shared").FileLineReference }) => void) =>+ window.piDesktop?.on?.(IPC.event.composerFileLines, (payload) => listener(payload as Parameters<typeof listener>[0])) ?? (() => {}),onPluginComposerSuggestion: (listener: (event:diff --git a/apps/desktop/src/lib/composer-draft-cache.ts b/apps/desktop/src/lib/composer-draft-cache.tsindex 8362b10ca..4282d963b 100644--- a/apps/desktop/src/lib/composer-draft-cache.ts+++ b/apps/desktop/src/lib/composer-draft-cache.ts@@ -21,6 +21,7 @@ type CachedComposerDraft = ComposerDraftSnapshot & {export const HOME_DRAFT_KEY = "__home__";export type ComposerDraftFileInput = {+ lineRange?: import("@pi-desktop/shared").FileLineRange;sessionId?: string;path: string;name: string;@@ -38,6 +39,7 @@ export function draftFileReference({mimeType,token,plugin,+ lineRange,}: ComposerDraftFileInput): ComposerDraftFileReference {return {path,@@ -46,6 +48,7 @@ export function draftFileReference({...(mimeType ? { mimeType } : {}),...(token ? { token } : {}),...(plugin ? { plugin } : {}),+ ...(lineRange ? { lineRange } : {}),};}@@ -73,6 +76,8 @@ export function sameDraftFileReference(a.kind === b.kind &&a.mimeType === b.mimeType &&a.token === b.token &&+ a.lineRange?.start === b.lineRange?.start &&+ a.lineRange?.end === b.lineRange?.end &&samePluginPart(a.plugin, b.plugin));}diff --git a/apps/desktop/src/lib/composer-smart-stop.ts b/apps/desktop/src/lib/composer-smart-stop.tsindex 24d5becfc..9d2e3b31f 100644--- a/apps/desktop/src/lib/composer-smart-stop.ts+++ b/apps/desktop/src/lib/composer-smart-stop.ts@@ -23,6 +23,7 @@ export type ComposerPluginPart =};export type ComposerDraftFileReference = {+ lineRange?: import("@pi-desktop/shared").FileLineRange;path: string;name: string;kind?: "image" | "file" | "session" | "directory";diff --git a/apps/desktop/src/stores/helpers/store-helpers.ts b/apps/desktop/src/stores/helpers/store-helpers.tsindex b9dc108ee..71c3294e6 100644--- a/apps/desktop/src/stores/helpers/store-helpers.ts+++ b/apps/desktop/src/stores/helpers/store-helpers.ts@@ -36,12 +36,13 @@ export function promptAttachmentsFromDraft(// 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") return [];+ if (reference.token && kind !== "image" && !reference.lineRange) return [];return [{path: reference.path,name: reference.name,kind,+ ...(reference.lineRange ? { lineRange: reference.lineRange } : {}),...(reference.mimeType ? { mimeType: reference.mimeType } : {}),},];@@ -59,6 +60,7 @@ export function promptAttachmentsFromMessage(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 } : {}),}));diff --git a/apps/desktop/src/stores/slices/queue-slice.ts b/apps/desktop/src/stores/slices/queue-slice.tsindex aea3b8d1d..e4ccf4698 100644--- a/apps/desktop/src/stores/slices/queue-slice.ts+++ b/apps/desktop/src/stores/slices/queue-slice.ts@@ -1,5 +1,5 @@import i18n from "i18next";-import { formatFileInsert } from "@pi-desktop/shared";+import { fileLineLabel, formatFileInsert } from "@pi-desktop/shared";import type {AgentQueueChangedEvent,AgentPromptAttachment,@@ -86,7 +86,9 @@ export function createQueueSlice({draft: queuedDrafts.get(entry.id) ?? {text: entry.content,fileReferences: (entry.attachments ?? []).map((attachment) => {- const token = formatFileInsert(attachment.path, "file").trim();+ const token = attachment.lineRange+ ? fileLineLabel(attachment.path, attachment.lineRange)+ : formatFileInsert(attachment.path, "file").trim();return {...attachment,// Keep restored inline files removable with their visible @path.diff --git a/apps/desktop/test/file-line-bridge.test.mjs b/apps/desktop/test/file-line-bridge.test.mjsnew file mode 100644index 000000000..998e8462d--- /dev/null+++ b/apps/desktop/test/file-line-bridge.test.mjs@@ -0,0 +1,58 @@+import assert from "node:assert/strict";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { addFileLinesFromView } from "../electron/main/file-line-reference.ts";+import { createPluginSessionContext } from "../electron/main/services/plugin-session-context.ts";++const pluginId = "pi.file-manager";++test("an installed File Manager can add lines only to the session that authorized the request", async (t) => {+ const workspace = await mkdtemp(join(tmpdir(), "pi-file-line-bridge-"));+ t.after(() => rm(workspace, { recursive: true, force: true }));+ const path = join(workspace, "sample.txt");+ await writeFile(path, "first\nsecond\n");+ const payload = { workspace, path, start: 2, end: 2 };+ const loaded = {+ development: false,+ disposing: false,+ permissions: new Set(["fs.read", "ui.view"]),+ manifest: { version: "0.9.0" },+ };+ const pluginSession = createPluginSessionContext({ getActiveTurn: () => null, announce() {} });+ const session = { sessionId: "selected", projectPath: workspace };+ pluginSession.setActiveSession(session);+ const deliveries = [];+ const record = { id: pluginId, version: "0.9.0", enabled: true, source: "marketplace" };+ const host = {+ async call(method) {+ assert.equal(method, "plugins.list");+ return { plugins: [record] };+ },+ };+ const bridge = {+ plugins: { getLoaded: (id) => id === pluginId ? loaded : undefined },+ pluginViews: { isVisibleViewSender: (id, key) => id === 123 && key === "pi.file-manager/manager" },+ pluginSession,+ pluginActiveInProject: (id, projectPath) => id === pluginId && projectPath === workspace,+ getHost: () => host,+ getWorkspacePath: () => workspace,+ publish: (delivery) => deliveries.push(delivery),+ };+ assert.deepEqual(await addFileLinesFromView(pluginId, 123, payload, bridge), { ok: true });+ assert.deepEqual(deliveries, [{ sessionId: "selected", reference: payload }]);++ await assert.rejects(addFileLinesFromView(pluginId, 321, payload, bridge), /outside the active project or session/);+ loaded.permissions.delete("fs.read");+ await assert.rejects(addFileLinesFromView(pluginId, 123, payload, bridge), /outside the active project or session/);+ loaded.permissions.add("fs.read");+ record.enabled = false;+ await assert.rejects(addFileLinesFromView(pluginId, 123, payload, bridge), /no longer active/);+ record.enabled = true;++ const pending = addFileLinesFromView(pluginId, 123, payload, bridge);+ pluginSession.setActiveSession({ ...session, sessionId: "different" });+ await assert.rejects(pending, /no longer active/);+ assert.equal(deliveries.length, 1);+});diff --git a/apps/desktop/test/prompt-inline-attachments.test.mjs b/apps/desktop/test/prompt-inline-attachments.test.mjsindex dbaf3f52c..c9adabdff 100644--- a/apps/desktop/test/prompt-inline-attachments.test.mjs+++ b/apps/desktop/test/prompt-inline-attachments.test.mjs@@ -1,7 +1,7 @@import assert from "node:assert/strict";-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";-import { join } from "node:path";+import { dirname, join } from "node:path";import test from "node:test";import { appendPromptFallbackPaths, preparePromptAttachments } from "../electron/main/prompt-attachments.ts";@@ -103,3 +103,27 @@ test("a replayed copy still travels for the path the prompt names", async (t) =>assert.notEqual(prepared.fallbackPath, ref);assert.ok(text.includes(prepared.fallbackPath));});++test("line ranges stay deferred and cannot escape the session project", async (t) => {+ const { data, path: outside } = await fixture(t);+ const project = join(dirname(data), "project");+ const path = join(project, "sample.txt");+ const escape = join(project, "escape.png");+ await mkdir(project);+ await writeFile(path, "before\nselected\nafter\n");+ await symlink(outside, escape, "file");+ const range = { start: 2, end: 2 };+ const attachment = { path, name: "sample.txt", kind: "file", lineRange: range };+ const [prepared] = await preparePromptAttachments(data, sessionId, project, [attachment], false, "Review this");+ assert.deepEqual(prepared.message.lineRange, range);+ assert.equal(prepared.message.ref, path);+ assert.equal(prepared.inlineData, undefined);+ assert.equal(appendPromptFallbackPaths("Review this", [prepared]), "Review this");++ for (const invalidPath of [outside, escape]) {+ await assert.rejects(+ preparePromptAttachments(data, sessionId, project, [{ ...attachment, path: invalidPath }], false, ""),+ /Invalid file line reference/,+ );+ }+});diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 3bd331bd4..27414e121 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -4126,6 +4126,7 @@ async fn handle_request(let call_started = std::time::Instant::now();let p: ToolsExecuteParams = serde_json::from_value(params.clone()).map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;+ let workspace_only = p.tool_name == "Read" && p.workspace_only;let _pending_file_call = if let Some(ticket) = p.file_batch_ticket.as_deref() {Some(state@@ -4312,11 +4313,15 @@ async fn handle_request(None => resolve_tool_workspace_for_call(&st, &p.session_id, &p.args)?,};let scratch = scratch::session_dir(&st.data_dir, &p.session_id);- let contained_roots = local_contained_roots(- &st.data_dir,- &p.session_id,- remote_workspace.is_some(),- );+ let contained_roots = if workspace_only {+ ContainedRoots::new()+ } else {+ local_contained_roots(+ &st.data_dir,+ &p.session_id,+ remote_workspace.is_some(),+ )+ };let external_path_permission = if remote_workspace.is_some() {remote_tools::requires_external_permission(ws.as_deref(),@@ -4331,6 +4336,18 @@ async fn handle_request(&p.args,)};+ if workspace_only+ && (remote_workspace.is_some()+ || ws.is_none()+ || ws.as_deref().map(Path::new) == scratch.as_deref()+ || external_path_permission)+ {+ return Err(rpc_err(+ 1003,+ "File line references require a local project path",+ "PATH_OUTSIDE_WORKSPACE",+ ));+ }let mut auto = st.permissions.evaluate_auto_with_permission_mode_and_risk_and_path(@@ -4803,15 +4820,17 @@ async fn handle_request(} else {let execute = tools::execute_tool_with_file_lease(ws_path.as_deref(),- scratch_path.as_deref(),+ scratch_path.as_deref().filter(|_| !workspace_only),&p.tool_name,&p.args,tools::ToolExecutionOptions {timeout_ms: execution_timeout_ms,bash_options,- allow_external_paths: external_path_permission,+ allow_external_paths: external_path_permission && !workspace_only,hashline: Some(hashline_ctx),- visualization_root: visualization_path.as_deref(),+ visualization_root: visualization_path+ .as_deref()+ .filter(|_| !workspace_only),},Some(tool_permit.clone()),file_resources.clone(),@@ -10390,6 +10409,51 @@ mod tests {.unwrap();assert_eq!(auto["ok"], true);assert_eq!(auto["content"]["root"], "external");++ let scoped = handle_request(+ state.clone(),+ "tools.execute",+ json!({+ "sessionId": session.id,+ "toolCallId": "outside-composer-read",+ "toolName": "Read",+ "args": { "path": outside_file.to_string_lossy(), "offset": 0, "limit": 1 },+ "workspaceOnly": true,+ "mode": "agent"+ }),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap_err();+ assert_eq!(+ scoped.message,+ "File line references require a local project path"+ );++ let project_file = project.join("note.txt");+ fs::write(&project_file, "before\nselected line\nafter\n").unwrap();+ let scoped = handle_request(+ state,+ "tools.execute",+ json!({+ "sessionId": session.id,+ "toolCallId": "inside-composer-read",+ "toolName": "Read",+ "args": { "path": project_file.to_string_lossy(), "offset": 1, "limit": 1 },+ "workspaceOnly": true,+ "mode": "agent"+ }),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ assert_eq!(scoped["ok"], true);+ let content = scoped["content"]["content"].as_str().unwrap();+ assert!(content.contains("selected line"), "{content}");+ assert!(+ !content.contains("before") && !content.contains("after"),+ "{content}"+ );}#[tokio::test]diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 834a6d483..d4e6cf2d7 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -169,6 +169,13 @@ pub struct MessageUsage {pub accounting: serde_json::Map<String, Value>,}+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FileLineRange {+ pub start: u64,+ pub end: u64,+}+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct MessageAttachment {@@ -190,6 +197,8 @@ pub struct MessageAttachment {/// at that position instead of appending it after the body.#[serde(skip_serializing_if = "Option::is_none")]pub inline_path: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub line_range: Option<FileLineRange>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -530,6 +539,9 @@ pub(crate) fn ui_to_record(message: &UiMessage) -> (MessageRecord, Option<Stringif let Some(inline_path) = &attachment.inline_path {block.insert("inlinePath".into(), json!(inline_path));}+ if let Some(range) = &attachment.line_range {+ block.insert("lineRange".into(), json!(range));+ }blocks.push(Value::Object(block));}}@@ -676,6 +688,9 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {.get("inlinePath").and_then(|v| v.as_str()).map(str::to_string),+ line_range: block+ .get("lineRange")+ .and_then(|value| serde_json::from_value(value.clone()).ok()),})}).collect::<Vec<_>>();@@ -5809,15 +5824,28 @@ mod tests {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 {- 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 {+ 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 {+ 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();@@ -5835,6 +5863,7 @@ mod tests {assert_eq!(blocks[1]["ref"], "attachments/abc123");assert_eq!(blocks[1]["inlinePath"], "@/scratch/pasted/image.png");assert!(blocks[1].get("data").is_none());+ assert_eq!(blocks[2]["lineRange"], json!({ "start": 85, "end": 86 }));}#[test]diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex 9f67bf355..024f0eb06 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -649,6 +649,9 @@ pub struct ToolsExecuteParams {pub tool_call_id: String,pub tool_name: String,pub args: Value,+ /// Restrict an automatic composer Read to the local project.+ #[serde(default)]+ pub workspace_only: bool,/// Host-issued source-order binding, not a permission or resource claim.#[serde(default)]pub file_batch_ticket: Option<String>,diff --git a/docs/adr/file-manager-line-references.md b/docs/adr/file-manager-line-references.mdnew file mode 100644index 000000000..33b24ab72--- /dev/null+++ b/docs/adr/file-manager-line-references.md@@ -0,0 +1,25 @@+# File Manager line references++- Status: Accepted+- Date: 2026-11-06++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.++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 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. The bounded result+or read failure is included as file context in the provider prompt.++References are initially available for local project source views with one+selection. Rendered and remote previews retain their clipboard behavior.diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 3bfab39d1..f06ae9b1f 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -159,6 +159,10 @@ transcript-read API. The core runs no title completion of its own.conversation dropped before any read, and the runtime quotes it to the modelas one `<session_reference name="…" session="…">` block ahead of the user'sown words+ A validated File Manager `lineRange` travels as file attachment metadata.+ 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. Restoring the reference does not run a Read.7. snapshot the effective shell ID and dialect for the turn8. start pi turn with the resolved session configuration and effectivethinking level; HTTP 429 setup and stream failures use the runtime-owneddiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 1ddd71640..a28aa72b4 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -4722,3 +4722,18 @@ introducing nested vertical scrolling. Unsupportedhistorical context has an explicit explanation and retains recorded evidence.Remote Review retains its existing presentation. Chat inline review rows retaintheir default layout and hash-guarded rollback; no Git or model behavior changes.++### 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 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 --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 7a3b422a1..460f392f5 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -20088,3 +20088,22 @@ Scenario: E2E-REVIEW-ROUNDS (local desktop, implemented)- Specs: ADR 0043; runtime RPC/storage specs; component spec Round review reader.- Milestone: maintenance. Traceability: acceptance criteria 1–9 of the approvednative round-review enhancement map to this scenario and the tests above.++### 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.++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, the saved result in the model request, and a+normal failure when the file disappears. Repeat with a queued turn and a+project switch. A different project's clipboard metadata cannot add the chip.diff --git a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.mdindex 9747e9edb..59dbe8aa4 100644--- a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md+++ b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md@@ -144,6 +144,15 @@ Panel bridge fixed channels also include `app.setTheme`, `themes.upsert`,`projects.list` is read-only project metadata and needs no permission; it grantsno file or session access.+The docked File Manager (`pi.file-manager/manager`) receives+`pluginBridge.capabilities.composerFileLines`. It 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 Events (host → plugin process)The broker also pushes one-way frames down to a plugin's `utilityProcess`:diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 1e6e76ef8..4f091f75b 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -227,6 +227,34 @@ 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) => method === "tools.execute"+ ? { ok: true, content: { content: "85: saved first\n86: saved second", totalLines: 100 } }+ : undefined);+ 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/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") }));+ } 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 --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 379630f24..c13cbb991 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -32,6 +32,7 @@ import {} from "./delegation-message.js";import {Agent,+ runToolCall,type AgentContext,type AgentEvent,type AgentLoopTurnUpdate,@@ -319,6 +320,8 @@ import {type ProviderTransportHealth,} from "./provider-transport-recovery.js";+import { fileLineLabel, MAX_FILE_LINE_REFERENCES, parseFileLineRange } from "@pi-desktop/shared";+export type { RuntimeProviderConfig } from "./provider-binding.js";export type RuntimePromptAttachment = Omit<AgentPromptAttachment, "kind"> & {@@ -349,9 +352,15 @@ 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 => `<file_lines source="${escapeAttribute(fileLineLabel(attachment.path, attachment.lineRange!))}">\n${attachment.text!.replaceAll("<", "<")}\n</file_lines>`);+ const references = [...sessions, ...fileLines];return references.length? `${input.text}\n\n${references.join("\n\n")}`.trim(): input.text;@@ -2030,6 +2039,7 @@ export class DesktopAgentRuntime {* signal it was handed never fires, or the stop RPC stays pending forever.*/private activeToolAborts = new Set<() => void>();+ private fileLineReadCalls = new Set<string>();private hostCloseUnsubscribe?: () => void;private turnSubagentUsage?: MessageUsage;private compactionRequestShape?: CompactionRequestShape;@@ -3631,6 +3641,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetoolCallId,toolName,args: params,+ ...(this.fileLineReadCalls.has(toolCallId) ? { workspaceOnly: true } : {}),...(this.batchPlanner.ticket(toolCallId) ? { fileBatchTicket: this.batchPlanner.ticket(toolCallId) } : {}),mode: this.mode,...(isBash@@ -9156,13 +9167,59 @@ 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 read = this.activeTools().find(tool => tool.name === "Read");+ 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);+ if (!range || attachment.kind !== "file" || seen.size >= MAX_FILE_LINE_REFERENCES) continue;+ 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] : [];+ this.emit({ type: "tool_start", toolCallId: toolCall.id, toolName: toolCall.name, args }, turnId);+ this.fileLineReadCalls.add(toolCall.id);+ 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: context => this.beforeToolCall(context),+ afterToolCall: context => this.afterToolCall(context),+ }).finally(() => this.fileLineReadCalls.delete(toolCall.id));+ this.emit({ type: "tool_end", toolCallId: toolCall.id, result, isError }, turnId);+ 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 });+ }+ return { ...input, attachments };+ }+private async promptTurn(input: string | RuntimePrompt,userMessageId: string | undefined,durableTurnId: string,): Promise<{ turnId: string }> {const selectedTools = this.selectedMcpTools(input);- const modelInput = typeof input !== "string" && input.sessionMessage+ let modelInput = typeof input !== "string" && input.sessionMessage? { ...input, text: formatSessionMessage(input.text, input.sessionMessage), sessionMessage: undefined }: input;this.retainPendingSteering();@@ -9199,6 +9256,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.resetDeferredToolsForPrompt();if (selectedTools.length) this.activateDeferredTools(selectedTools);this.setAgentTools(this.activeTools());+ 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",diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.tsindex 28eac1f98..a8f20fe9f 100644--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@ -512,8 +512,18 @@ async function handle(method: string, params: any): Promise<unknown> {}const expectedTurnId = String(params.expectedTurnId ?? "");if (method === "agent.steeringContext") return runtime.steeringContext(expectedTurnId);+ const prompt: RuntimePrompt = {+ text: String(params.content ?? ""),+ attachments: Array.isArray(params.attachments) ? params.attachments : undefined,+ mcpServerIds: parseMcpServerIds(params.mcpServerIds),+ mcpToolNames: parseMcpToolNames(params.mcpToolNames),+ };+ if (prompt.attachments?.some(attachment => attachment.lineRange !== undefined)) {+ runtime.steeringContext(expectedTurnId);+ return runtime.steer(await runtime.resolveFileLineReferences(prompt), expectedTurnId, params.message);+ }return runtime.steer(- { text: String(params.content ?? ""), attachments: params.attachments, mcpServerIds: parseMcpServerIds(params.mcpServerIds), mcpToolNames: parseMcpToolNames(params.mcpToolNames) },+ prompt,expectedTurnId,params.message,);diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex cadb0f5b7..9288dc497 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -335,6 +335,7 @@ export const de = {sessionMissing: "Diese Sitzung existiert nicht mehr",},"chat": {+ fileLineReferenceLimit: "Pro Nachricht sind bis zu {{count}} Verweise auf Dateizeilen möglich.",promptRetractionFailed: "Der Entwurf konnte nicht sicher wiederhergestellt werden. Der Gesprächsverlauf bleibt erhalten.","tableActions": "Tabellenaktionen","markdownPlainTextFallback": "Große Antworten werden zur besseren Reaktionsfähigkeit als Klartext angezeigt.",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex b2b50cfea..828c534c5 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -377,6 +377,7 @@ export const en = {suggestionHint: "Tab to accept · Esc to ignore",addFiles: "Add files",filesAttached: "Added {{count}} item(s) to the draft",+ fileLineReferenceLimit: "Add up to {{count}} file line references per message.",filesPasted: "Saved {{count}} pasted file(s) to the session scratch folder",largeTextPasted: "Saved large pasted text as @{{name}}",slashMenu: "Commands",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 61e67697b..adee11a98 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -335,6 +335,7 @@ export const es = {sessionMissing: "Esa sesión ya no existe",},"chat": {+ fileLineReferenceLimit: "Puedes añadir hasta {{count}} referencias a líneas de archivo por mensaje.",promptRetractionFailed: "No se pudo restaurar el borrador de forma segura. Se ha conservado la conversación.","tableActions": "Acciones de tabla","markdownPlainTextFallback": "La respuesta extensa se muestra como texto sin formato para mantener la fluidez.",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 80a20969c..f190e5758 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -335,6 +335,7 @@ export const fr = {sessionMissing: "Cette session n'existe plus",},"chat": {+ fileLineReferenceLimit: "Vous pouvez ajouter jusqu’à {{count}} références à des lignes de fichier par message.",promptRetractionFailed: "Impossible de restaurer le brouillon en toute sécurité. La conversation a été conservée.","tableActions": "Actions du tableau","markdownPlainTextFallback": "La réponse volumineuse est affichée en texte brut pour préserver la réactivité.",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex cd651e12b..04f730739 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -379,6 +379,7 @@ export const ko = {suggestionHint: "Tab 수락 · Esc 무시",addFiles: "파일 추가",filesAttached: "초안에 항목 {{count}}개 추가됨",+ fileLineReferenceLimit: "메시지 하나에 파일 줄 참조를 최대 {{count}}개 추가할 수 있습니다.",filesPasted: "붙여넣은 파일 {{count}}개를 세션 임시 폴더에 저장함",largeTextPasted: "큰 붙여넣기 텍스트를 @{{name}}으로 저장함",slashMenu: "명령",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 66a8d3686..945e56de9 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -369,6 +369,7 @@ export const ptBR = {suggestionHint: "Tab aceitar · Esc descartar",addFiles: "Adicionar arquivos",filesAttached: "{{count}} item(ns) adicionado(s) ao rascunho",+ fileLineReferenceLimit: "Adicione até {{count}} referências a linhas de arquivo por mensagem.",filesPasted: "{{count}} arquivo(s) colado(s) salvo(s) na pasta temporária da sessão",largeTextPasted: "Texto longo colado salvo como @{{name}}",slashMenu: "Comandos",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex a27b6fb26..3d14b0f2c 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -379,6 +379,7 @@ export const tr = {suggestionHint: "Tab kabul · Esc yoksay",addFiles: "Dosya ekle",filesAttached: "Taslağa {{count}} öğe eklendi",+ fileLineReferenceLimit: "Her mesaja en fazla {{count}} dosya satırı başvurusu ekleyebilirsiniz.",filesPasted: "Yapıştırılan {{count}} dosya oturum klasörüne kaydedildi",largeTextPasted: "Uzun yapıştırılan metin @{{name}} olarak kaydedildi",slashMenu: "Komutlar",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 513fc3ea6..8882f0a68 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -372,6 +372,7 @@ export const zhCN = {suggestionHint: "Tab 接受 · Esc 忽略",addFiles: "添加文件",filesAttached: "已将 {{count}} 项加入草稿",+ fileLineReferenceLimit: "每条消息最多可添加 {{count}} 处文件行引用。",filesPasted: "已将 {{count}} 个粘贴文件保存到会话临时目录",largeTextPasted: "已将大段粘贴文本保存为 @{{name}}",slashMenu: "指令",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 98fbb1f72..d15ede92d 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -372,6 +372,7 @@ export const zhTW = {suggestionHint: "Tab 接受 · Esc 忽略",addFiles: "新增檔案等內容",filesAttached: "已將 {{count}} 項加入草稿",+ fileLineReferenceLimit: "每則訊息最多可新增 {{count}} 處檔案行引用。",filesPasted: "已將 {{count}} 個貼上檔案儲存到會話臨時目錄",largeTextPasted: "已將大段貼上文本儲存為 @{{name}}",slashMenu: "指令",diff --git a/packages/shared/src/composer-trigger.ts b/packages/shared/src/composer-trigger.tsindex 8cd8a4dfc..351d81aa3 100644--- a/packages/shared/src/composer-trigger.ts+++ b/packages/shared/src/composer-trigger.ts@@ -1,4 +1,5 @@import { formatSessionLink } from "./session-link.js";+import { fileLineLabel, type FileLineRange } from "./file-line-reference.js";/*** Trigger detection and completion insertion for the composer autocomplete@@ -208,14 +209,16 @@ function directoryPromptReference(path: string): string {*/export function serializeInlineComposerFileReferences(draft: string,- references: ReadonlyArray<{ path: string; kind?: string; token?: string; plugin?: ComposerReferencePluginPart }>,+ references: ReadonlyArray<{ path: string; kind?: string; token?: string; lineRange?: FileLineRange; plugin?: ComposerReferencePluginPart }>,): string {let content = draft;for (const reference of references) {const token = reference.token?.trim();if (!token || !content.includes(token)) continue;const send = reference.plugin?.send;- const insert = typeof send === "string"+ const insert = reference.lineRange+ ? fileLineLabel(reference.path, reference.lineRange)+ : typeof send === "string"? send: reference.kind === "session"? formatSessionLink(reference.path)diff --git a/packages/shared/src/file-line-reference.ts b/packages/shared/src/file-line-reference.tsnew file mode 100644index 000000000..07bbb1ca6--- /dev/null+++ b/packages/shared/src/file-line-reference.ts@@ -0,0 +1,29 @@+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 type FileLineRange = { start: number; end: number };+export type FileLineReference = FileLineRange & { path: string; workspace: string };++export function parseFileLineRange(value: unknown): FileLineRange | undefined {+ if (!value || typeof value !== "object") return;+ 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;+ return { start, end };+}++export function parseFileLineReference(value: unknown): FileLineReference | undefined {+ const range = parseFileLineRange(value);+ if (!range) return;+ const { path, workspace } = value as Partial<FileLineReference>;+ if (typeof path !== "string" || typeof workspace !== "string" ||+ !path || !workspace || path.length > 4096 || workspace.length > 4096 ||+ /[\0\r\n]/.test(path) || /[\0\r\n]/.test(workspace)) return;+ return { path, workspace, ...range };+}++export function fileLineLabel(name: string, { start, end }: FileLineRange): string {+ return `${name} (${start === end ? start : `${start}:${end}`})`;+}diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 17cb048b2..a71728a0a 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -9,6 +9,7 @@ export * from "./transcript-truncation.js";export * from "./keyboard-shortcuts.js";export * from "./changelog.js";export * from "./composer-trigger.js";+export * from "./file-line-reference.js";export * from "./inline-attachments.js";export * from "./session-link.js";export * from "./fuzzy.js";diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 37a4ec962..04c5174d1 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -522,6 +522,7 @@ export const IPC = {* `pluginComposerSuggestionResult`.*/pluginComposerSuggestion: "pi-desktop/plugin/composer/event/suggestion",+ composerFileLines: "pi-desktop/composer/event/fileLines",windowMaximized: "pi-desktop/window/event/maximized",windowFullScreen: "pi-desktop/window/event/fullscreen",windowWorkPanelResize: "pi-desktop/window/event/workPanelResize",diff --git a/packages/shared/src/types/agent.ts b/packages/shared/src/types/agent.tsindex 6d3e1bf90..945ac1017 100644--- a/packages/shared/src/types/agent.ts+++ b/packages/shared/src/types/agent.ts@@ -64,6 +64,7 @@ export type AgentPromptAttachment = {path: string;name: string;kind: "image" | "file";+ lineRange?: import("../file-line-reference.js").FileLineRange;mimeType?: string;size?: number;/**diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.tsindex 0ee958184..c82336a52 100644--- a/packages/shared/src/types/messages.ts+++ b/packages/shared/src/types/messages.ts@@ -49,6 +49,7 @@ export type UsageOperation = Omit<MessageUsage, "operations" | "aggregation"> &export { addUsage, contextOccupancyTokens, withUsageIdentity } from "../message-usage.js";export type MessageAttachment = {+ lineRange?: import("../file-line-reference.js").FileLineRange;kind: "image" | "file" | "session";name: string;/** Workspace-relative path, session-scratch absolute path, or a session id. */diff --git a/scripts/e2e/composer-paste.tsx b/scripts/e2e/composer-paste.tsxindex 1dad3a27c..9e5e6ec9a 100644--- a/scripts/e2e/composer-paste.tsx+++ b/scripts/e2e/composer-paste.tsx@@ -202,6 +202,7 @@ globalThis.composerPasteProbe = async () => {editor: HTMLDivElement,text: string,files: File[],+ fileLines?: { workspace: string; path: string; start: number; end: number },) => {const data = new DataTransfer();if (text) {@@ -209,6 +210,7 @@ globalThis.composerPasteProbe = async () => {data.setData("text/html", `<b>${text}</b>`);}for (const file of files) data.items.add(file);+ if (fileLines) data.setData("application/x-pi-desktop-file-lines", JSON.stringify(fileLines));const event = new ClipboardEvent("paste", {clipboardData: data,bubbles: true,@@ -237,6 +239,22 @@ globalThis.composerPasteProbe = async () => {selection.addRange(range);};try {+ const lineEditor = await reset();+ const workspace = "/fixture/project";+ useAppStore.setState({ activeProjectPath: workspace });+ await dispatchPaste(lineEditor, "saved line selection", [], { workspace, path: workspace + "/gpt.py", start: 85, end: 86 });+ const lineChip = lineEditor.querySelector(".composer-chip");+ assert(lineChip?.textContent?.includes("gpt.py (85:86)"), "file range paste did not create a line chip");+ assert(!lineEditor.textContent?.includes("saved line selection"), "file range paste inserted source text");+ assert(controller.snapshotReferences("paste-a")[0]?.lineRange?.start === 85, "file range did not reach the draft");+ const otherProjectEditor = await reset();+ await dispatchPaste(otherProjectEditor, "foreign selection", [], {+ workspace: "/fixture/other", path: "/fixture/other/gpt.py", start: 85, end: 86,+ });+ assert(!otherProjectEditor.querySelector(".composer-chip"), "another project's paste created a file line chip");+ assert(otherProjectEditor.textContent?.includes("foreign selection"), "another project's paste lost the plain text");+ useAppStore.setState({ activeProjectPath: null });+useAppStore.setState({ sessions: [{id: "paste-a", title: "Folder paste fixture", source: "desktop", mode: "agent",permissionMode: "inherit", thinkingLevel: "off", messageCount: 0,