feat(open): open mentioned files beside Pi
ce496d6ddff10911590dfa1202dfbff1aefda571
Oliver Krylow <o.krylow@isp-insoft.de> ·
SSH signature · not checked
- Parent 1: 0144fb4bb5f9
bugabingas pi extensions
ce496d6ddff10911590dfa1202dfbff1aefda571
Oliver Krylow <o.krylow@isp-insoft.de> ·
SSH signature · not checked
+835 / −0 text lines
+1 / −0 text lines
| `neko` | Tiny animated editor cat for Pi. Pointless. Correct. | [README](extensions/neko/README.md) || `notes` | Session-backed pending prompt notes for Pi. | [README](extensions/notes/README.md) || `open` | Open mentioned files in Neovim beside Pi. | [README](extensions/open/README.md) |new file mode 100644+36 / −0 text lines
# openOpen mentioned files in Neovim beside Pi.## Install / loadLoaded through the root `pi-ext` package.See [root README](../../README.md).## Commands / tools / settingsCommands:- `/open PATH` opens an existing file directly.- `/open` opens the sole recent file or a fuzzy picker for multiple files.Tools:none.Hooks:- `session_start` reports missing WezTerm, `$EDITOR`, or pane context.Settings:none.## Behavior`/open` reads the current session branch when invoked.It ranks existing file mentions by source: user, assistant, edit, then write.Paths are deduplicated and limited to 20.The picker keeps paths prominent and shows the source as its description.The selected file opens through `$EDITOR` in a new right-hand WezTerm split using 69 percent of Pi's pane.The editor starts in the project root and receives an absolute file path.Launch is asynchronous; the pane closes when the editor exits.new file mode 100644+287 / −0 text lines
import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync,} from "node:fs";import { tmpdir } from "node:os";import { delimiter, join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { createTestSession, type TestSession } from "../../../test/harness";import openExtension, { __test, type FileCandidate } from "../index.ts";const roots: string[] = [];let session: TestSession | undefined;function tempRoot(): string { const root = mkdtempSync(join(tmpdir(), "pi-open-test-")); roots.push(root); return root;}function file(root: string, path: string): string { const absolute = join(root, path); mkdirSync(join(absolute, ".."), { recursive: true }); writeFileSync(absolute, path); return absolute;}function entry(message: unknown): unknown { return { type: "message", message };}function fakeExecutable(bin: string, name: string): string { const path = join(bin, process.platform === "win32" ? `${name}.exe` : name); copyFileSync(process.execPath, path); if (process.platform !== "win32") chmodSync(path, 0o700); return path;}async function linesEventually(path: string, count: number): Promise<string[]> { for (let attempt = 0; attempt < 100; attempt++) { try { const lines = readFileSync(path, "utf8").trim().split("\n"); if (lines.length >= count) return lines; } catch {} await new Promise((resolveWait) => setTimeout(resolveWait, 10)); } throw new Error(`Timed out waiting for ${path}`);}afterEach(() => { session?.dispose(); session = undefined; for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 20, });});describe("open candidates", () => { it("extracts existing path forms", () => { const root = tempRoot(); const markdown = file(root, "docs/with space.md"); const backtick = file(root, "src/backtick.ts"); const atPath = file(root, "TODO.md"); const plain = file(root, "plain.json"); expect( __test.extractTextPaths( "plain.json then `src/backtick.ts`, @TODO.md, and [docs](docs/with space.md); missing.ts", root, ), ).toEqual([plain, backtick, atPath, markdown]); }); it("ranks source first, recency second, and deduplicates paths", () => { const root = tempRoot(); const userOld = file(root, "user-old.ts"); const userNew = file(root, "user-new.ts"); const assistant = file(root, "assistant.ts"); const edited = file(root, "edited.ts"); const written = file(root, "written.ts"); const entries = [ entry({ role: "user", content: "@user-old.ts" }), entry({ role: "assistant", content: [ { type: "text", text: "`assistant.ts` and `user-new.ts`" }, { type: "toolCall", name: "write", arguments: { path: "written.ts" }, }, { type: "toolCall", name: "edit", arguments: { path: "edited.ts" } }, ], }), entry({ role: "user", content: "Use @user-new.ts" }), ]; expect(__test.collectCandidates(entries, root)).toEqual([ { path: userNew, displayPath: "user-new.ts", source: "user" }, { path: userOld, displayPath: "user-old.ts", source: "user" }, { path: assistant, displayPath: "assistant.ts", source: "assistant" }, { path: edited, displayPath: "edited.ts", source: "edit" }, { path: written, displayPath: "written.ts", source: "write" }, ]); }); it("limits scanning to the 20 newest existing files", () => { const root = tempRoot(); const entries = Array.from({ length: 25 }, (_, index) => { const name = `file-${index}.ts`; file(root, name); return entry({ role: "user", content: `@${name}` }); }); const candidates = __test.collectCandidates(entries, root); expect(candidates).toHaveLength(20); expect(candidates[0]?.displayPath).toBe("file-24.ts"); expect(candidates.at(-1)?.displayPath).toBe("file-5.ts"); }); it("fuzzy-picks by path while keeping the path prominent", async () => { const candidates: FileCandidate[] = [ { path: "/a/other.ts", displayPath: "src/other.ts", source: "user" }, { path: "/a/about-this.ts", displayPath: "src/about-this.ts", source: "assistant", }, ]; let rows: string[] = []; const selected = await __test.chooseCandidate(candidates, { mode: "tui", ui: { custom: async (factory: any) => { let result: string | undefined; const component = await factory( { requestRender() {} }, { fg: (_color: string, text: string) => text }, { matches: (data: string, action: string) => action === "tui.select.confirm" && data === "\r", }, (value: string | undefined) => { result = value; }, ); for (const key of ["a", "b", "t"]) component.handleInput(key); rows = component.render(120); component.handleInput("\r"); return result; }, }, } as any); expect(selected).toEqual(candidates[1]); expect(rows.join("\n")).toContain("src/about-this.ts"); }); it("uses the standard selector outside TUI mode", async () => { const candidates: FileCandidate[] = [ { path: "/a/one.ts", displayPath: "one.ts", source: "user" }, { path: "/a/two.ts", displayPath: "two.ts", source: "assistant" }, ]; const selected = await __test.chooseCandidate(candidates, { mode: "rpc", ui: { select: async () => "two.ts" }, } as any); expect(selected).toEqual(candidates[1]); });});describe("open extension", () => { it("launches explicit and sole-mentioned files through a detached WezTerm split", async () => { const root = tempRoot(); const bin = join(root, "bin"); mkdirSync(bin); const wezterm = fakeExecutable(bin, "wezterm"); const editor = fakeExecutable(bin, "nvim"); const marker = join(root, "launches.jsonl"); const preload = join(root, "record.cjs"); writeFileSync( preload, `require("node:fs").appendFileSync(${JSON.stringify(marker)}, JSON.stringify(process.argv.slice(1)) + "\\n"); process.exit(0);\n`, ); const explicit = file(root, "explicit file.ts"); const mentioned = file(root, "mentioned.ts"); session = await createTestSession({ cwd: root, extensionFactories: [openExtension], env: { PATH: `${bin}${delimiter}${process.env.PATH ?? ""}`, EDITOR: "nvim", WEZTERM_PANE: "7", NODE_OPTIONS: `--require=${preload}`, }, }); const extension = session.session.extensionRunner.extensions[0]; const command = extension.commands.get("open"); const context = session.session.extensionRunner.createCommandContext(); expect(command).toBeDefined(); await command.handler('"explicit file.ts"', context); session.session.sessionManager.appendMessage({ role: "user", content: "Check @mentioned.ts", timestamp: Date.now(), }); await command.handler("", context); const launches = (await linesEventually(marker, 2)).map((line) => JSON.parse(line), ); const prefix = [ join(root, "cli"), "split-pane", "--pane-id", "7", "--right", "--percent", "69", "--cwd", root, "--", editor, ]; expect(launches).toEqual([ [...prefix, explicit], [...prefix, mentioned], ]); expect(wezterm).toContain("wezterm"); }); it("warns when its required host context is unavailable", async () => { const root = tempRoot(); session = await createTestSession({ cwd: root, extensionFactories: [openExtension], env: { PATH: "", EDITOR: undefined, WEZTERM_PANE: undefined }, }); expect( session.events.uiCallsFor("notify").map((call) => call.args), ).toEqual([ ["/open: wezterm is not on PATH", "warning"], ["/open: EDITOR is not set", "warning"], ["/open: WEZTERM_PANE is not set", "warning"], ]); }); it("reports missing files without launching", async () => { const root = tempRoot(); const bin = join(root, "bin"); mkdirSync(bin); fakeExecutable(bin, "wezterm"); fakeExecutable(bin, "nvim"); session = await createTestSession({ cwd: root, extensionFactories: [openExtension], env: { PATH: bin, EDITOR: "nvim", WEZTERM_PANE: "7", }, }); const extension = session.session.extensionRunner.extensions[0]; await extension.commands .get("open") .handler( "missing.ts", session.session.extensionRunner.createCommandContext(), ); expect(session.events.uiCallsFor("notify").at(-1)?.args).toEqual([ "Not a file: missing.ts", "error", ]); });});new file mode 100644+444 / −0 text lines
import { spawn } from "node:child_process";import { accessSync, constants, statSync } from "node:fs";import { delimiter, extname, isAbsolute, join, relative, resolve, sep,} from "node:path";import type { ExtensionAPI, ExtensionContext, SessionEntry,} from "@earendil-works/pi-coding-agent";import { Container, fuzzyFilter, Input, SelectList,} from "@earendil-works/pi-tui";const MAX_CANDIDATES = 20;const SOURCE_ORDER = ["user", "assistant", "edit", "write"] as const;const SPLIT_PERCENT = "69";type CandidateSource = (typeof SOURCE_ORDER)[number];export interface FileCandidate { path: string; displayPath: string; source: CandidateSource;}function envValue( env: NodeJS.ProcessEnv, key: string, platform: NodeJS.Platform,): string | undefined { if (platform !== "win32") return env[key]; const actual = Object.keys(env).find( (candidate) => candidate.toLowerCase() === key.toLowerCase(), ); return actual ? env[actual] : undefined;}function executableNames(command: string, platform: NodeJS.Platform): string[] { if (platform !== "win32" || extname(command)) return [command]; return [command, `${command}.exe`, `${command}.com`];}function executableOnPath( command: string, env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform,): string | undefined { const pathValue = envValue(env, "PATH", platform); const directories = command.includes("/") || command.includes("\\") ? [""] : (pathValue ?? "").split(delimiter).filter(Boolean); for (const directory of directories) { for (const name of executableNames(command, platform)) { const candidate = directory ? join(directory.replace(/^"|"$/gu, ""), name) : resolve(name); try { accessSync( candidate, platform === "win32" ? constants.F_OK : constants.X_OK, ); if (statSync(candidate).isFile()) return candidate; } catch { // Keep searching PATH. } } } return undefined;}function existingFile(rawPath: string, cwd: string): string | undefined { const trimmed = rawPath.trim().replace(/^(["'])(.*)\1$/u, "$2"); if (!trimmed) return undefined; const path = resolve(cwd, trimmed); try { return statSync(path).isFile() ? path : undefined; } catch { return undefined; }}function displayPath(path: string, cwd: string): string { const local = relative(cwd, path); return local && !local.startsWith(`..${sep}`) && !isAbsolute(local) ? local : path;}function pathLike(token: string): boolean { return ( token.includes("/") || token.includes("\\") || token.startsWith(".") || /^[^\s.][^/\\\s]*\.[A-Za-z0-9_-]+$/u.test(token) );}function trimToken(token: string): string { return token .trim() .replace(/^[@`'"<([{]+/u, "") .replace(/[`'">)\]},;!?]+$/u, "") .replace(/[.:]+$/u, "");}function extractTextPaths(text: string, cwd: string): string[] { const raw: Array<{ value: string; structured: boolean; index: number }> = []; for (const match of text.matchAll(/\]\(([^)\n]+)\)/gu)) { raw.push({ value: match[1], structured: true, index: match.index }); } for (const match of text.matchAll(/`([^`\n]+)`/gu)) { raw.push({ value: match[1], structured: true, index: match.index }); } for (const match of text.matchAll(/\S+/gu)) { raw.push({ value: match[0], structured: false, index: match.index }); } raw.sort( (left, right) => left.index - right.index || Number(right.structured) - Number(left.structured), ); const paths: string[] = []; const seen = new Set<string>(); for (const item of raw) { const token = trimToken(item.value); if (!token || (!item.structured && !pathLike(token))) continue; const path = existingFile(token, cwd); if (!path || seen.has(path)) continue; seen.add(path); paths.push(path); } return paths;}function textFromContent(content: unknown): string[] { if (typeof content === "string") return [content]; if (!Array.isArray(content)) return []; return content.flatMap((part) => part && typeof part === "object" && "type" in part && part.type === "text" && "text" in part && typeof part.text === "string" ? [part.text] : [], );}function toolPath( block: unknown,): { source: "edit" | "write"; path: string } | undefined { if (!block || typeof block !== "object" || !("type" in block)) return undefined; if (block.type !== "toolCall" || !("name" in block)) return undefined; if (block.name !== "edit" && block.name !== "write") return undefined; if ( !("arguments" in block) || !block.arguments || typeof block.arguments !== "object" ) return undefined; if (!("path" in block.arguments) || typeof block.arguments.path !== "string") return undefined; return { source: block.name, path: block.arguments.path };}function collectCandidates( entries: readonly SessionEntry[] | readonly unknown[], cwd: string,): FileCandidate[] { const buckets = new Map( SOURCE_ORDER.map((source) => [source, new Map<string, FileCandidate>()]), ); const found = new Set<string>(); const add = (path: string, source: CandidateSource): void => { const bucket = buckets.get(source); if (!bucket || bucket.has(path)) return; bucket.set(path, { path, displayPath: displayPath(path, cwd), source }); found.add(path); }; for (let index = entries.length - 1; index >= 0; index--) { const entry = entries[index]; if (!entry || typeof entry !== "object" || !("type" in entry)) continue; if (entry.type !== "message" || !("message" in entry)) continue; const message = entry.message; if (!message || typeof message !== "object" || !("role" in message)) continue; if (message.role === "user" && "content" in message) { for (const text of textFromContent(message.content).toReversed()) { for (const path of extractTextPaths(text, cwd).toReversed()) add(path, "user"); } if (found.size >= MAX_CANDIDATES) break; continue; } if (message.role !== "assistant" || !("content" in message)) continue; for (const block of Array.isArray(message.content) ? message.content.toReversed() : []) { const touched = toolPath(block); if (touched) { const path = existingFile(touched.path, cwd); if (path) add(path, touched.source); continue; } for (const text of textFromContent([block])) { for (const path of extractTextPaths(text, cwd).toReversed()) add(path, "assistant"); } } if (found.size >= MAX_CANDIDATES) break; } const candidates: FileCandidate[] = []; const seen = new Set<string>(); for (const source of SOURCE_ORDER) { for (const candidate of buckets.get(source)?.values() ?? []) { if (seen.has(candidate.path)) continue; seen.add(candidate.path); candidates.push(candidate); if (candidates.length === MAX_CANDIDATES) return candidates; } } return candidates;}function fuzzyCandidates( candidates: readonly FileCandidate[], query: string,): FileCandidate[] { return fuzzyFilter( [...candidates], query, (candidate) => candidate.displayPath, );}async function chooseCandidate( candidates: readonly FileCandidate[], ctx: Pick<ExtensionContext, "mode" | "ui">,): Promise<FileCandidate | undefined> { if (ctx.mode !== "tui") { const selected = await ctx.ui.select( "Open", candidates.map((candidate) => candidate.displayPath), ); return candidates.find((candidate) => candidate.displayPath === selected); } const selectedPath = await ctx.ui.custom<string | undefined>( (tui, theme, keybindings, done) => { const container = new Container(); const input = new Input(); input.focused = true; let list: SelectList; function rebuild(): void { const filtered = fuzzyCandidates(candidates, input.getValue()); list = new SelectList( filtered.map((candidate) => ({ value: candidate.path, label: candidate.displayPath, description: candidate.source, })), Math.min(Math.max(filtered.length, 1), 8), { selectedPrefix: (text) => theme.fg("accent", text), selectedText: (text) => theme.fg("accent", text), description: (text) => theme.fg("dim", text), scrollInfo: (text) => theme.fg("dim", text), noMatch: (text) => theme.fg("warning", text), }, ); list.onSelect = (item) => done(item.value); list.onCancel = () => done(undefined); container.clear(); container.addChild(input); container.addChild(list); } rebuild(); let focused = true; return { get focused() { return focused; }, set focused(value: boolean) { focused = value; input.focused = value; }, render: (width: number) => container.render(width), invalidate: () => container.invalidate(), handleInput(data: string) { if ( keybindings.matches(data, "tui.select.up") || keybindings.matches(data, "tui.select.down") ) { list.handleInput(data); tui.requestRender(); return; } if (keybindings.matches(data, "tui.select.confirm")) { const selected = list.getSelectedItem(); if (selected) done(selected.value); return; } if (keybindings.matches(data, "tui.select.cancel")) { done(undefined); return; } const previous = input.getValue(); input.handleInput(data); if (input.getValue() !== previous) rebuild(); tui.requestRender(); }, }; }, ); return candidates.find((candidate) => candidate.path === selectedPath);}function splitArguments( paneId: string, cwd: string, editor: string, path: string,): string[] { return [ "cli", "split-pane", "--pane-id", paneId, "--right", "--percent", SPLIT_PERCENT, "--cwd", cwd, "--", editor, path, ];}async function launchInSplit( wezterm: string, editor: string, paneId: string, cwd: string, path: string,): Promise<void> { await new Promise<void>((resolveLaunch, reject) => { const child = spawn(wezterm, splitArguments(paneId, cwd, editor, path), { cwd, detached: true, stdio: "ignore", windowsHide: true, }); child.once("error", reject); child.once("spawn", () => { child.unref(); resolveLaunch(); }); });}export default function openExtension(pi: ExtensionAPI): void { const wezterm = executableOnPath("wezterm"); const editorName = process.env.EDITOR?.trim(); const editor = editorName ? executableOnPath(editorName) : undefined; pi.on("session_start", (_event, ctx) => { if (!wezterm) ctx.ui.notify("/open: wezterm is not on PATH", "warning"); if (!editorName) ctx.ui.notify("/open: EDITOR is not set", "warning"); else if (!editor) ctx.ui.notify(`/open: EDITOR '${editorName}' is not on PATH`, "warning"); if (!process.env.WEZTERM_PANE) ctx.ui.notify("/open: WEZTERM_PANE is not set", "warning"); }); pi.registerCommand("open", { description: "Open a file in a Neovim WezTerm split", async handler(args, ctx) { const paneId = process.env.WEZTERM_PANE; if (!wezterm || !editor || !paneId) { ctx.ui.notify("/open unavailable; see startup warnings", "error"); return; } let path: string | undefined; if (args.trim()) { path = existingFile(args, ctx.cwd); if (!path) { ctx.ui.notify(`Not a file: ${args.trim()}`, "error"); return; } } else { const candidates = collectCandidates( ctx.sessionManager.getBranch(), ctx.cwd, ); if (candidates.length === 0) { ctx.ui.notify("No mentioned files", "info"); return; } path = candidates.length === 1 ? candidates[0].path : (await chooseCandidate(candidates, ctx))?.path; } if (!path) return; try { await launchInSplit(wezterm, editor, paneId, ctx.cwd, path); } catch (error) { ctx.ui.notify( `/open failed: ${error instanceof Error ? error.message : String(error)}`, "error", ); } }, });}export const __test = { chooseCandidate, collectCandidates, executableOnPath, extractTextPaths, fuzzyCandidates, splitArguments,};new file mode 100644+31 / −0 text lines
[tasks.fmt]description = "Format open extension"depends = ["//:install"]run = [ "biome check --write .", "rumdl fmt README.md", "taplo format mise.toml",][tasks.lint]description = "Lint open extension"depends = ["//:install"]run = [ "biome ci --config-path ../.. .", "rumdl check --config ../../.rumdl.toml .", "taplo format --check --config ../../.taplo.toml mise.toml",][tasks.test]description = "Test open extension"depends = ["//:install"]run = [ { task = "//:test", args = ["extensions/open"] },][tasks.check]description = "Check open extension"depends = ["//:install"]run = [ { task = "//:build", args = ["open"] },]new file mode 100644+20 / −0 text lines
{ "name": "@bugabinga/pi-ext-open", "type": "module", "main": "index.ts", "peerDependencies": { "@earendil-works/pi-coding-agent": "*", "@earendil-works/pi-tui": "*" }, "license": "MIT", "description": "Open mentioned files in Neovim beside Pi.", "keywords": [ "pi", "pi-extension" ], "devDependencies": { "@marcfargas/pi-test-harness": "^0.6.1", "vitest": "^4.1.9" }, "private": true}+16 / −0 text lines