Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(composer): integrate line references with current main
Linuxdazhao7933e18984e6
diff --cc apps/desktop/src/features/chat/composer/editor.tsindex b344fc3d9,92b458ac8..2250ae9a5--- a/apps/desktop/src/features/chat/composer/editor.ts+++ b/apps/desktop/src/features/chat/composer/editor.ts@@@ -39,9 -40,10 +40,10 @@@ export function createFileReferencepreferredName?: string,sessionId = "",metadata?: {- kind?: "image" | "file" | "session" | "directory";+ kind?: "image" | "file" | "session" | "directory" | "agent";mimeType?: string;token?: string;+ lineRange?: FileLineRange;plugin?: ComposerPluginPart;},): ComposerFileReference {@@@ -263,8 -264,8 +266,9 @@@ function chipIconKey(reference: Composeif (reference.plugin?.kind === "mark") return "plugin";if (reference.plugin?.kind === "fold") return "fold";if (reference.kind === "session") return "session";+ if (reference.kind === "agent") return "agent";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;@@@ -283,7 -284,7 +287,7 @@@ function chipSvg(key: string, size = 13}export function isEditableTextReference(reference: ComposerFileReference): boolean {- if (isPluginMark(reference) || reference.kind === "directory" || reference.kind === "agent") return false;- if (isPluginMark(reference) || reference.kind === "directory" || reference.lineRange) return false;++ if (isPluginMark(reference) || reference.kind === "directory" || reference.kind === "agent" || reference.lineRange) return false;return reference.mimeType?.toLowerCase() === "text/plain" || /\.txt$/i.test(reference.name);}diff --cc apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.tsindex 29ed1f8f2,666409da2..e5043bc7e--- a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts@@@ -93,6 -95,39 +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;++ return false;+ }+ 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;diff --cc apps/desktop/src/lib/composer-smart-stop.tsindex f90bbcaaa,9d2e3b31f..365a713f7--- a/apps/desktop/src/lib/composer-smart-stop.ts+++ b/apps/desktop/src/lib/composer-smart-stop.ts@@@ -23,9 -23,10 +23,10 @@@ export type ComposerPluginPart};export type ComposerDraftFileReference = {+ lineRange?: import("@pi-desktop/shared").FileLineRange;path: string;name: string;- kind?: "image" | "file" | "session" | "directory";+ kind?: "image" | "file" | "session" | "directory" | "agent";mimeType?: string;/** Visible inline token for a generated large-text paste reference. */token?: string;diff --cc apps/desktop/test/composer-file-reference-display.test.mjsindex f9ced8813,2b66d088b..927e48c70--- a/apps/desktop/test/composer-file-reference-display.test.mjs+++ b/apps/desktop/test/composer-file-reference-display.test.mjs@@@ -75,12 -75,10 +75,13 @@@ test("composer renders atomic inline chassert.match(composer, /chip\.contentEditable = "false"/);assert.match(composer, /chip\.dataset\.token = token/);assert.match(composer, /composer-chip-name/);- assert.match(composer, /nameSpan\.textContent = reference\.name/);+ assert.match(composer, /const label = reference\.lineRange \? fileLineLabel\(reference\.name, reference\.lineRange\) : reference\.name/);+ assert.match(composer, /nameSpan\.textContent = label/);// A file chip's title is its path; a plugin mark's is its plugin.- assert.match(composer, /isPluginMark\(reference\) \? \(reference\.plugin\?\.pluginId \?\? ""\) : reference\.path/);+ assert.match(+ composer,+ /isPluginMark\(reference\)\s*\? \(reference\.plugin\?\.pluginId \?\? ""\)\s*: reference\.kind === "agent"\s*\? `@\$\{reference\.path\}`\s*: reference\.path/,+ );assert.match(composer, /chip\.title = origin/);assert.match(composer,diff --cc docs/adr/README.mdindex eabb145fb,4b048b528..3b65397d0--- a/docs/adr/README.md+++ b/docs/adr/README.md@@@ -21,7 -21,7 +21,8 @@@ Each ADR includes| ID | Title | Status ||---|---|---|+| steering-local-tool-interruption | [Steering waits for confirmed tool settlement](steering-local-tool-interruption.md) | Accepted |+ | file-manager-line-references | [File Manager line references](file-manager-line-references.md) | Implemented candidate || composer-pasted-directory-references | [Composer pasted directory references](composer-pasted-directory-references.md) | Accepted || plugin-projects-list | [Read-only durable project enumeration for plugins](plugin-projects-list.md) | Accepted || append-only-review-state | [Append-only review state](append-only-review-state.md) | Implemented candidate |diff --cc docs/spec/04-ux/08-component-spec.mdindex d719f966e,c8a6def11..ccab5a037--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@@ -4741,3 -4727,18 +4741,20 @@@ introducing nested vertical scrolling.historical 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 the four-reference limit, another paste shows the limit warning and inserts++the plain text instead of consuming it without changing the draft.++ At turn execution the Agent calls the existing Host Read for each distinct+ range and adds its bounded result to the model request. Read uses the saved+ file at execution time, including for queued sends. Source views with no+ project file identity and clipboard data from another project use normal text+ copy/paste. See [File Manager line references ADR](../../adr/file-manager-line-references.md).diff --cc docs/spec/06-delivery/04-e2e-test-plan.mdindex f7041b3ad,e0f35fcca..f818b722a--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@@ -20137,25 -20103,33 +20137,58 @@@ Scenario: E2E-REVIEW-ROUNDS (local desk- Milestone: maintenance. Traceability: acceptance criteria 1–9 of the approvednative round-review enhancement map to this scenario and the tests above.++### E2E-TOOLS-session-background-jobs++- Entry: build shared/agent-runtime/host-runtime and Host, then run+ `PI_DESKTOP_HOST_BIN=<candidate-host> node scripts/e2e-session-background-jobs.mjs`.+- Environment: isolated Host data and workspace, production runtime and pi tool+ loop, deterministic localhost HTTP provider. No external model account.+- Sequence: start a background test, list it, wait for failure and Unicode+ output tails; start a service, time out waiting, call default stop, then+ explicitly stop and wait for the same job.+- Expected: correct exit code and both final tails, per-stream UTF-8 limits,+ cross-session list/read/stop isolation, timeout and default stop preserve Bash,+ explicit stop reaches terminal state, repeated reads and desktop output agree.+ Plan-mode access is rejected.+- Runtime tests cover new input/parent abort during a pending Host wait, late+ Host rejection, old Host/remote capability behavior, mixed selector rejection,+ existing delegation controls and registration without a subagent catalog.+- Host tests cover pre-settled observation, repeatable output, Unicode clipping,+ ownership lookup, idempotent stop and stop acknowledgement before termination.+ Existing Windows child/grandchild cleanup tests remain required; record native+ failures separately from protocol success.+- Exercise a late stop with an already reaped child before the supervisor drains the pipes. Verify the original exit outcome, final output and stable elapsed time across reads. Stall capability discovery or the first Host observation to exercise the overall wait deadline. The Electron transcript fixture renders a pending Bash stop and a mixed job list.+++ ### 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.diff --cc packages/agent-runtime/src/runtime.tsindex 8be2fca77,e07551e8e..c590af476--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@@ -2031,7 -2047,7 +2048,8 @@@ export class DesktopAgentRuntime* signal it was handed never fires, or the stop RPC stays pending forever.*/private activeToolAborts = new Set<() => void>();+ private readonly steeringToolAborts = new Map<string, () => void>();+ private fileLineReadCalls = new Map<string, { blocked: boolean }>();private hostCloseUnsubscribe?: () => void;private turnSubagentUsage?: MessageUsage;private compactionRequestShape?: CompactionRequestShape;diff --cc packages/shared/src/composer-trigger.test.tsindex 81ea7eccf,67928f537..ab9abd32d--- a/packages/shared/src/composer-trigger.test.ts+++ b/packages/shared/src/composer-trigger.test.ts@@@ -17,6 -14,6 +17,16 @@@ importstripInlineComposerFileReferenceTokens,} from "./composer-trigger.js";++it("serializes agent mentions and saved line references in the same draft", () => {++ const text = serializeInlineComposerFileReferences("\uE001 explain \uE002", [++ { path: "reviewer", kind: "agent", token: "\uE001" },++ { path: "/project/sample.txt", kind: "file", token: "\uE002", lineRange: { start: 2, end: 3 } },++ ]);++ expect(text).toContain("@reviewer explain /project/sample.txt (2:3)");++ expect(text).not.toContain("\uE001");++ expect(text).not.toContain("\uE002");++});++describe("splitComposerDirectoryPrompt", () => {const path = "/tmp/a & <b> <";diff --cc packages/shared/src/composer-trigger.tsindex 6f7cfbf58,36598a32a..a88a371cb--- a/packages/shared/src/composer-trigger.ts+++ b/packages/shared/src/composer-trigger.ts@@@ -306,16 -249,15 +307,18 @@@ export function serializeInlineComposerconst token = reference.token?.trim();if (!token || !content.includes(token)) continue;const send = reference.plugin?.send;+ const agent = reference.kind === "agent";- const insert = typeof send === "string"+ const insert = reference.lineRange+ ? fileLineLabel(reference.path, reference.lineRange)+ : typeof send === "string"? send- : reference.kind === "session"- ? formatSessionLink(reference.path)- : reference.kind === "directory"- ? directoryPromptReference(reference.path)- : formatFileInsert(reference.path, "file").trim();+ : agent+ ? `@${reference.path}`+ : reference.kind === "session"+ ? formatSessionLink(reference.path)+ : reference.kind === "directory"+ ? directoryPromptReference(reference.path)+ : formatFileInsert(reference.path, "file").trim();let index = content.indexOf(token);while (index !== -1) {const nextChar = content[index + token.length];diff --cc scripts/e2e/composer-paste.tsxindex c50fd2642,3683d66e9..11f561564--- a/scripts/e2e/composer-paste.tsx+++ b/scripts/e2e/composer-paste.tsx@@@ -241,6 -243,22 +243,29 @@@ 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");++ for (let start = 1; start <= 3; start++) {++ await dispatchPaste(lineEditor, "saved line selection", [], { workspace, path: workspace + "/gpt.py", start, end: start });++ }++ assert(controller.snapshotReferences("paste-a").length === 4, "file range limit fixture did not fill");++ await dispatchPaste(lineEditor, "limit fallback text", [], { workspace, path: workspace + "/gpt.py", start: 4, end: 4 });++ assert(lineEditor.textContent?.includes("limit fallback text"), "file range limit swallowed the pasted plain text");++ assert(controller.snapshotReferences("paste-a").length === 4, "file range limit added an extra chip");+ 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,