Skip to content

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

fix(composer): search past a truncated file index for @ mentions

zszz331caf50d0ad8
diff --git a/apps/desktop/electron/main/fs-index.ts b/apps/desktop/electron/main/fs-index.ts
index bf41f117d..4dbb8ba2f 100644
--- a/apps/desktop/electron/main/fs-index.ts
+++ b/apps/desktop/electron/main/fs-index.ts
@@ -1 +1 @@
-export { FS_INDEX_MAX_ENTRIES, getWorkspaceFileIndex } from "@pi-desktop/host-runtime";
+export { FS_INDEX_MAX_ENTRIES, getWorkspaceFileIndex, searchWorkspaceFiles } from "@pi-desktop/host-runtime";
diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.ts
index 57d7b5979..dbb604bea 100644
--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts
+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts
@@ -40,7 +40,7 @@ import {
} from "@pi-desktop/host-runtime";
import { openableMp4Path } from "../open-attachment-video";
import { isChatRefOutsideRoots, resolveChatFileRef } from "../chat-ref-resolve";
-import { getWorkspaceFileIndex } from "../fs-index";
+import { getWorkspaceFileIndex, searchWorkspaceFiles } from "../fs-index";
import {
projectFolderPaths,
refreshProjectGroups,
@@ -984,6 +984,15 @@ export function registerWorkspaceIpc({
return getWorkspaceFileIndex(root);
});
+ handle(IPC.invoke.fsSearch, async (input: { sessionId?: string; query?: string } = {}) => {
+ // The remote file protocol has no search operation, so a remote session
+ // keeps answering from its truncated snapshot.
+ if (await remoteFileWorkspace(input.sessionId)) return { entries: [], truncated: true };
+ const root = await optionalWorkspaceRoot(input.sessionId);
+ if (!root) return { entries: [], truncated: false };
+ return searchWorkspaceFiles(root, String(input.query ?? ""));
+ });
+
/**
* Resolve a file reference from chat to a real file (D320 follow-up).
* The renderer knows the workspace but not where a session keeps its scratch
diff --git a/apps/desktop/src/hooks/use-composer-autocomplete.ts b/apps/desktop/src/hooks/use-composer-autocomplete.ts
index 00292f44b..683dcc86a 100644
--- a/apps/desktop/src/hooks/use-composer-autocomplete.ts
+++ b/apps/desktop/src/hooks/use-composer-autocomplete.ts
@@ -24,13 +24,16 @@ import { useAppStore } from "../stores/app-store";
/**
* Composer autocomplete state machine (D123–D125): trigger detection over
- * draft+cursor, lazily fetched command/file sources, local fuzzy filtering,
- * and insert-on-accept. IME freezing and key routing live in the Composer;
+ * draft+cursor, lazily fetched command/file sources, local fuzzy filtering
+ * (with a main-process search past a truncated file index, D665), and
+ * insert-on-accept. IME freezing and key routing live in the Composer;
* this hook only refuses to update while `composing` is true.
*/
const MAX_FILE_ITEMS = 50;
const SOURCE_TTL_MS = 10_000;
+/** Typing pause before a query searches past a truncated file index. */
+const FILE_SEARCH_DEBOUNCE_MS = 150;
export type AutocompleteItem =
| { kind: "command"; command: ComposerCommand; match: FuzzyMatch }
@@ -102,9 +105,13 @@ function filterCommands(
function filterFiles(entries: FsIndexEntry[], query: string): AutocompleteItem[] {
const matched: Array<{ entry: FsIndexEntry; match: FuzzyMatch }> = [];
+ // Rows found by the main-process search may repeat index entries.
+ const seen = new Set<string>();
for (const entry of entries) {
const match = fuzzyMatchPath(query, entry.path, entry.kind);
- if (match) matched.push({ entry, match });
+ if (!match || seen.has(entry.path)) continue;
+ seen.add(entry.path);
+ matched.push({ entry, match });
}
// The index can hold thousands of entries while the menu shows at most
// MAX_FILE_ITEMS, so only the bounded top slice is ever ordered.
@@ -174,6 +181,11 @@ export function useComposerAutocomplete({
entries: FsIndexEntry[];
truncated: boolean;
} | null>(null);
+ const [found, setFound] = useState<{
+ scope: string;
+ entries: FsIndexEntry[];
+ truncated: boolean;
+ } | null>(null);
const [highlight, setHighlight] = useState(0);
const [dismissedKey, setDismissedKey] = useState<string | null>(null);
const frozenRef = useRef<ComposerTrigger | null>(null);
@@ -251,6 +263,41 @@ export function useComposerAutocomplete({
};
}, [trigger?.mode, dismissed, workspaceKey, hasWorkspace, sessionId]);
+ // A truncated index keeps only the shallowest entries, so a deep file of a
+ // large tree matches nothing in it. Once typing pauses, the query also
+ // searches the main process's full listing (D665); the answer belongs to
+ // this `@` token and its rows merge with the index's.
+ const fileQuery =
+ trigger?.mode === "file" && !dismissed && files?.truncated ? trigger.query : "";
+ const searchScope = `${sessionId ?? ""}\n${workspaceKey}\n${triggerKey ?? ""}`;
+ useEffect(() => {
+ if (!fileQuery) return;
+ let cancelled = false;
+ const timer = setTimeout(() => {
+ void api
+ .fsSearch(sessionId, fileQuery)
+ .then((res) => {
+ if (!cancelled) setFound({ scope: searchScope, ...res });
+ })
+ .catch(() => {
+ // The index's rows still answer; the truncation note stays.
+ if (!cancelled) setFound({ scope: searchScope, entries: [], truncated: true });
+ });
+ }, FILE_SEARCH_DEBOUNCE_MS);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [fileQuery, searchScope, sessionId]);
+ // A later `@` at the same offset is a new token and must not inherit rows.
+ useEffect(() => {
+ if (!triggerKey) setFound(null);
+ }, [triggerKey]);
+ // A bare `@` lists the index alone; searched rows belong to a typed query.
+ const foundHere = fileQuery !== "" && found?.scope === searchScope ? found : null;
+ const fileTruncated =
+ (files?.truncated ?? false) && (!fileQuery || !foundHere || foundHere.truncated);
+
// Warm the `/` source once bootstrap settles, so the first slash of a session
// does not wait for a cold host round trip (#1543). Waiting for `ready` keeps
// the pre-warm off the pre-hydration empty workspace key, which would spend a
@@ -265,8 +312,12 @@ export function useComposerAutocomplete({
if (trigger.mode === "slash") {
return commands ? filterCommands(commands, trigger.query, trigger.tokenStart > 0) : [];
}
- return files ? filterFiles(files.entries, trigger.query) : [];
- }, [trigger, dismissed, commands, files]);
+ if (!files) return [];
+ return filterFiles(
+ foundHere ? [...foundHere.entries, ...files.entries] : files.entries,
+ trigger.query,
+ );
+ }, [trigger, dismissed, commands, files, foundHere]);
// New query or mode restarts keyboard navigation at the top hit.
const itemsKey = trigger ? `${trigger.mode}:${trigger.query}` : "";
@@ -322,7 +373,7 @@ export function useComposerAutocomplete({
hasItems: open && items.length > 0,
highlight,
setHighlight,
- truncated: open && trigger?.mode === "file" ? (files?.truncated ?? false) : false,
+ truncated: open && trigger?.mode === "file" ? fileTruncated : false,
noWorkspace: open && trigger?.mode === "file" && !hasWorkspace,
close,
accept,
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 85810d88a..23af03e78 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -1596,6 +1596,8 @@ export const api = {
fsOpen: (path: string, mimeType?: string, sessionId?: string) =>
invoke(IPC.invoke.fsOpen, { path, mimeType, ...(sessionId ? { sessionId } : {}) }),
fsIndex: (sessionId?: string) => invoke<FsIndexResult>(IPC.invoke.fsIndex, { ...(sessionId ? { sessionId } : {}) }),
+ fsSearch: (sessionId: string | undefined, query: string) =>
+ invoke<FsIndexResult>(IPC.invoke.fsSearch, { ...(sessionId ? { sessionId } : {}), query }),
/**
* Complete a file reference from chat text to a real file (D320 follow-up).
* The main process owns the root order — project, session scratch,
diff --git a/apps/desktop/test/composer-deep-file-search-user-path.test.mjs b/apps/desktop/test/composer-deep-file-search-user-path.test.mjs
new file mode 100644
index 000000000..9aa64680b
--- /dev/null
+++ b/apps/desktop/test/composer-deep-file-search-user-path.test.mjs
@@ -0,0 +1,258 @@
+/**
+ * Issue #1781: in a large tree the `@` menu could not reach deep files.
+ *
+ * The file index keeps only the shallowest 8000 entries, so a script deep in a
+ * Unity project matched nothing however much of its name was typed. This drives
+ * the composer pieces the app wires together — draft, completions, input, menu —
+ * against a truncated index and a main-process search the test answers itself.
+ */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";
+
+const root = repositoryRoot();
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+
+test("the search channel runs main's listing search and leaves remote sessions on their snapshot", async () => {
+ const [protocol, api, workspaceIpc] = await Promise.all([
+ readFile(join(root, "packages/shared/src/protocol.ts"), "utf8"),
+ readFile(join(root, "apps/desktop/src/lib/api.ts"), "utf8"),
+ readFile(join(root, "apps/desktop/electron/main/ipc/workspace-ipc.ts"), "utf8"),
+ ]);
+ assert.match(protocol, /fsSearch: "pi-desktop\/fs\/search"/);
+ assert.match(api, /invoke<FsIndexResult>\(IPC\.invoke\.fsSearch, \{ \.\.\.\(sessionId \? \{ sessionId \} : \{\}\), query \}\)/);
+ const handler = workspaceIpc.match(/handle\(IPC\.invoke\.fsSearch,[\s\S]*?\n {2}\}\);/)?.[0];
+ assert.ok(handler, "main must register the search channel");
+ assert.match(handler, /remoteFileWorkspace\(input\.sessionId\)\) return \{ entries: \[\], truncated: true \}/);
+ assert.match(handler, /return searchWorkspaceFiles\(root, String\(input\.query \?\? ""\)\)/);
+});
+
+const fixture = String.raw`
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
+import { useComposerDraft } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerDraft";
+import { useComposerCompletions } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerCompletions";
+import { ComposerInput } from "../../apps/desktop/src/features/chat/composer/ComposerInput";
+import { ComposerAutocomplete } from "../../apps/desktop/src/components/ComposerAutocomplete";
+import { setEditorCaret } from "../../apps/desktop/src/features/chat/composer/editor";
+import { api } from "../../apps/desktop/src/lib/api";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+
+const DEEP = "Assets/_Game/Scripts/Gameplay/Player/Controllers/FeatureController.cs";
+const SAVE = "Assets/_Game/Scripts/Systems/Save/SaveSlots.cs";
+const STALE = "Assets/Stale/SaveFeature.cs";
+// Short enough to rank inside the bare @ menu if a searched row leaked into it.
+const SHORT = "a.cs";
+// The shallowest 8000 entries of a large tree; the deep scripts are not among them.
+const shallow = Array.from({ length: 8000 }, (_, index) => ({
+ path: "Assets/Art/Group" + Math.floor(index / 300) + "/asset_" + index + ".png",
+ kind: "file",
+}));
+let fileIndex = { entries: shallow, truncated: true };
+const searches = [];
+api.fsIndex = async () => fileIndex;
+api.fsSearch = (sessionId, query) =>
+ new Promise((resolve, reject) => searches.push({ sessionId, query, resolve, reject }));
+
+await i18n.use(initReactI18next).init({ lng: "en", keySeparator: false,
+ resources: { en: { translation: flattenCatalog(catalogs.en) } },
+ interpolation: { escapeValue: false } });
+useAppStore.setState({ activeSessionId: "s1", workspace: { path: "/large", name: "large" } });
+
+const noop = () => {};
+let draft;
+function Fixture() {
+ draft = useComposerDraft({
+ variant: "docked", activeSessionId: "s1", workspacePath: "/large",
+ sessions: [{ id: "s1" }], composerPrefill: null, clearComposerPrefill: noop,
+ t: (key) => key, invalidateComposerTransforms: noop, inputBlocked: false,
+ });
+ const completions = useComposerCompletions({
+ value: draft.value, cursor: draft.cursor, composing: draft.composing, enabled: true,
+ referenceSessionId: "s1", fileReferencesRef: draft.fileReferencesRef,
+ applyEditorDraft: draft.applyEditorDraft, handleInput: draft.handleInput,
+ invalidateComposerTransforms: noop,
+ });
+ return <>
+ <ComposerInput inputRef={draft.ref} value={draft.value} placeholderText="" placeholderKey="fixture"
+ inputBlocked={false} pasting={false} enterToSend={false} runActive={false}
+ composerAc={completions.ac} onPaste={noop} onAcceptCompletion={completions.acceptCompletion}
+ onSubmit={noop} onInsertNewline={noop} onHistoryNavigate={() => false}
+ onInput={(source, caret) => completions.handleInput(source, caret)}
+ onCompositionStart={() => draft.setComposing(true)}
+ onCompositionEnd={() => draft.setComposing(false)}
+ onSettledInput={() => draft.setComposing(false)} onFocus={noop} onBlur={noop} />
+ <ComposerAutocomplete anchorRef={draft.ref} ac={completions.ac} onAccept={completions.acceptCompletion} />
+ </>;
+}
+
+const rootNode = createRoot(document.getElementById("root"));
+const settle = async () => {
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+};
+const editor = () => document.querySelector(".composer-input");
+const rows = () => [...document.querySelectorAll('[role="option"] .composer-ac-path')].map((row) => row.textContent);
+const noteShown = () => document.querySelector(".composer-ac-truncated") !== null;
+function check(condition, message) { if (!condition) throw new Error(message + " rows=" + JSON.stringify(rows().slice(0, 5))); }
+async function until(predicate, message) {
+ for (let n = 0; n < 300; n += 1) {
+ if (predicate()) return;
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ check(false, message);
+}
+async function type(text) {
+ const el = editor();
+ el.textContent = text;
+ setEditorCaret(el, text.length);
+ await settle();
+ el.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: text }));
+ await settle();
+}
+
+window.deepFileSearchProbe = async () => {
+ flushSync(() => rootNode.render(<Fixture />));
+ await settle();
+ editor().focus();
+
+ await type("@");
+ await until(() => rows().length > 0, "the @ menu did not open");
+ check(noteShown(), "a truncated index must say so");
+ check(searches.length === 0, "an empty query must not search");
+
+ await type("@FeatureController");
+ check(!rows().includes(DEEP), "the truncated index cannot know the deep file");
+ await until(() => searches.length === 1, "the query was not searched after the pause");
+ check(searches[0].query === "FeatureController" && searches[0].sessionId === "s1",
+ "searched the wrong query or session: " + searches[0].query);
+ searches[0].resolve({ entries: [{ path: DEEP, kind: "file" }], truncated: false });
+ await until(() => rows().includes(DEEP), "the searched deep file did not appear");
+ check(!noteShown(), "a complete search must clear the truncation note");
+ check(searches.length === 1, "one pause must search once");
+
+ editor().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ await settle();
+ check(draft.fileReferencesRef.current.some((reference) => reference.path === DEEP),
+ "accepting the row did not reference the deep file");
+
+ await type("@Feat");
+ check(!rows().includes(DEEP), "a new @ token inherited the previous token's rows");
+ await until(() => searches.length === 2, "the second query was not searched");
+ await type("@Save");
+ await until(() => searches.length === 3, "the third query was not searched");
+ searches[2].resolve({ entries: [{ path: SAVE, kind: "file" }, { path: SHORT, kind: "file" }], truncated: false });
+ await until(() => rows().includes(SAVE), "the current answer did not appear");
+ searches[1].resolve({ entries: [{ path: STALE, kind: "file" }], truncated: false });
+ await settle();
+ check(!rows().includes(STALE), "an answer for an earlier query replaced the current one");
+
+ await type("@");
+ await settle();
+ check(!rows().includes(SHORT), "a bare @ listed rows searched for an earlier query");
+ check(noteShown(), "a bare @ must report that the index alone is incomplete");
+
+ await type("@Missing");
+ await until(() => searches.length === 4, "the incomplete query was not searched");
+ searches[3].resolve({ entries: [], truncated: true });
+ await settle();
+ check(noteShown(), "an incomplete search must keep the truncation note");
+
+ await type("@Broken");
+ await until(() => searches.length === 5, "the failing query was not searched");
+ searches[4].reject(new Error("search failed"));
+ await settle();
+ check(noteShown(), "a failed search must keep the truncation note");
+
+ fileIndex = { entries: [{ path: "README.md", kind: "file" }], truncated: false };
+ useAppStore.setState({ workspace: { path: "/small", name: "small" } });
+ await type("");
+ await type("@nothing");
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ check(searches.length === 5, "a complete index must not search");
+ check(!noteShown(), "a complete index has no truncation note");
+
+ flushSync(() => rootNode.unmount());
+ return { passed: true, queries: searches.map((search) => search.query) };
+};
+`;
+
+test("an @ query reaches deep files past a truncated file index", {
+ skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,
+}, async () => {
+ const temp = await mkdtemp(join(tmpdir(), "pi-deep-file-search-ui-"));
+ try {
+ await build({
+ stdin: { contents: fixture, resolveDir: join(root, "scripts/e2e"), loader: "tsx" },
+ outfile: join(temp, "renderer.js"),
+ bundle: true,
+ platform: "browser",
+ format: "esm",
+ jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"' },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),
+ "@pi-desktop/shared": join(root, "packages/shared/src"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ i18next: join(root, "apps/desktop/node_modules/i18next"),
+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(join(temp, "index.html"),
+ '<!doctype html><meta charset="utf-8"><div id="root"></div><script type="module" src="renderer.js"></script>');
+ await writeFile(join(temp, "main.cjs"), `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({ show: false, width: 900, height: 700,
+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ win.webContents.on("console-message", (event) => console.error(event.message));
+ try {
+ await win.loadFile(path.join(__dirname, "index.html"));
+ console.log("DEEP_FILE_SEARCH_PROBE " + JSON.stringify(await win.webContents.executeJavaScript("window.deepFileSearchProbe()")));
+ app.exit(0);
+ } catch (error) { console.error(error?.stack ?? error); app.exit(1); }
+});`);
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], {
+ env,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) {
+ stream.setEncoding("utf8");
+ stream.on("data", (chunk) => { output += chunk; });
+ }
+ const timer = setTimeout(() => child.kill("SIGKILL"), 60_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+ assert.equal(code, 0, output.slice(-6000));
+ const line = output.split(/\r?\n/).find((item) => item.startsWith("DEEP_FILE_SEARCH_PROBE "));
+ assert.ok(line, output.slice(-6000));
+ const result = JSON.parse(line.slice("DEEP_FILE_SEARCH_PROBE ".length));
+ assert.equal(result.passed, true);
+ assert.deepEqual(result.queries, ["FeatureController", "Feat", "Save", "Missing", "Broken"]);
+ } finally {
+ await rm(temp, { recursive: true, force: true });
+ }
+});
diff --git a/docs/adr/0024-composer-commands-and-file-references.md b/docs/adr/0024-composer-commands-and-file-references.md
index cfdf9958f..391f8c3b0 100644
--- a/docs/adr/0024-composer-commands-and-file-references.md
+++ b/docs/adr/0024-composer-commands-and-file-references.md
@@ -62,6 +62,9 @@ exported by the installed package and directly reusable.
fallback, short TTL cache); `pi-desktop/composer/commands` returns the
merged command list. Both fail soft without a workspace. These
Electron-only channels do not change the host RPC protocol version.
+ *(Amended by D665: while that index is truncated, a typed query is also
+ answered from the full listing by the read-only `pi-desktop/fs/search`,
+ because the shallow-first cap leaves deep files of a large tree out.)*
## Alternatives considered
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 64c0fa905..6b07edd63 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -2153,7 +2153,7 @@ reservation, and background artifacts cannot change visible window geometry.
## 13c. Composer input APIs (D123/D124/D197, ADR 0024/0059)
Electron-only channels backing composer autocomplete and file references.
-`composer/commands` and `fs/index` are read-only and fail soft;
+`composer/commands`, `fs/index`, and `fs/search` are read-only and fail soft;
`composer/pickFiles` opens the unified native picker used by the Composer and
returns a one-shot token; the legacy `composer/pickPhotos` channel remains
available for compatibility but is not exposed by the Composer UI.
@@ -2207,7 +2207,28 @@ Workspace-rooted relative paths for the `@` menu: `git ls-files -co
--exclude-standard` fast path, ignore-set recursive walk fallback,
directories derived from file paths, 8000-entry cap with `truncated: true`,
short TTL cache per root. Fails closed to an empty list without a
-workspace. Fuzzy filtering happens renderer-side.
+workspace. Fuzzy filtering happens renderer-side; a truncated index keeps
+only the shallowest entries, so a query against it is also sent to
+`fs/search`.
+
+### fs/search
+
+```ts
+fs/search({ sessionId?, query }) -> { entries: FsIndexEntry[]; truncated: boolean }
+```
+
+The `@` menu calls this only while its `fs/index` snapshot is truncated and
+the query is non-empty, after a short typing pause, then merges the answer
+with its own matches (D665). Main ranks the query with the renderer's fuzzy
+scorer over the root's full listing and returns the best 50 entries. The
+listing is the `git ls-files` list behind the index, or — when the index came
+from the walk — a deeper ignore-set walk of at most 200,000 entries or two
+seconds. It shares the index's TTL cache and is released when that expires.
+`truncated: true` means the search itself was capped. The query is trimmed and
+bounded to 256 characters; an empty query returns no entries. A remote session
+returns `{ entries: [], truncated: true }` without contacting its host — the
+remote file protocol has no search operation — so the menu keeps filtering
+the remote snapshot alone.
### composer/pickFiles and composer/pickPhotos
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 82b7fba02..8f1f78ef5 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -3454,9 +3454,13 @@ Anatomy:
at the caret — the same sentinel-backed chip as a pasted file — whose
canonical value is the original `entry.path`; the menu closes and that Enter
does not send. Accepting a directory keeps the literal path in the draft so
- completion can continue. Entries come from `fs/index` (D124, D209, D362). A
- truncation footnote appears when the index is capped; without a workspace the
- menu shows an "open a project" empty state.
+ completion can continue. Entries come from `fs/index` (D124, D209, D362).
+ When that index is capped, a typed query is also searched over the whole
+ listing through `fs/search` once typing pauses, and the found rows merge
+ with the local matches (D665). A truncation footnote appears while the list
+ may be incomplete — the bare `@`, until the first search for the token
+ answers, and when a search is itself capped or unavailable, as in remote
+ sessions; without a workspace the menu shows an "open a project" empty state.
- Accepting commands and directories inserts text (`/name ` / `@dir/`);
accepting a completed file inserts the inline chip rather than deleting the
trigger. Immediately
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 5b00986fa..69f9b00f2 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -8764,6 +8764,40 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
layout covered by `scripts/e2e-composer-autocomplete.mjs`; full UI journey
Draft (run only in a capable environment when this surface changes)
+#### E2E-COMPOSER-deep-file-mentions: `@` reaches deep files in a large workspace
+
+- **Preconditions**: The app is running with an Agent session in a workspace
+ whose index is truncated (more than 8000 files and directories), with a
+ script several folders below thousands of shallow assets — for example a
+ Unity project's `Assets/_Game/Scripts/Gameplay/Player/FeatureController.cs`.
+ Run once with the workspace under git and once without.
+- **Steps**: 1) Type `@` and inspect the footnote. 2) Type the script's name
+ and pause. 3) Accept the script's row with Enter. 4) Edit the query quickly
+ through several prefixes. 5) Repeat in a small workspace and in a remote
+ session.
+- **Expected**:
+ - The bare `@` lists the index and shows the truncation footnote.
+ - After the pause the deep script appears as a row, ranked like any other
+ match, and the footnote disappears once that search has answered; files
+ excluded by `.gitignore` or the ignore set never appear.
+ - Accepting it inserts the same file chip as any other reference.
+ - Rows never belong to an earlier query. The menu keeps the local matches
+ while a search is pending.
+ - A small workspace issues no search request; a remote session keeps its
+ snapshot and footnote.
+- **Specs linked**: `04-ux/08-component-spec.md` §11.8,
+ `03-runtime/01-ipc-protocol.md` §13c, `08-meta/decisions-log.md` (D124,
+ D665), ADR 0024
+- **Acceptance**: C (conversation & stream), Quality
+- **Milestone**: M5
+- **Status**: Unit-covered (`packages/host-runtime/src/fs-index.test.ts`
+ covers the git and walk listings, ignore rules, directories, and the result
+ limit); the renderer journey — search after the pause, merge, accept, stale
+ answers, the footnote, and the complete-index path — is covered by
+ `apps/desktop/test/composer-deep-file-search-user-path.test.mjs` in a real
+ Electron renderer. The full desktop journey against a large real tree is
+ Draft (run only in a capable environment when this surface changes).
+
#### E2E-102b: Unanswered Stop restores compact file-reference drafts
- **Preconditions**: An Agent session can delay its first assistant event. The
@@ -10227,6 +10261,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| C / Quality / Security (Conversation MP4 attachments) | E2E-CHAT-mp4-attachment-opens-in-system-player |
| G — Plugins (Chat file references) | E2E-CHAT-file-ref-opens-the-surface-that-owns-it, E2E-PLUGIN-file-view-collapse-persists |
| Quality (Chat file references) | E2E-CHAT-shorthand-file-ref-opens-the-matching-file, E2E-CHAT-file-ref-opens-the-surface-that-owns-it, E2E-PLUGIN-file-view-collapse-persists |
+| C / Quality (Composer deep file mentions) | E2E-COMPOSER-deep-file-mentions |
| G — Plugins (project folder roots) | E2E-PLUGIN-file-view-switches-folder-per-project |
| Security (project folder roots) | E2E-PLUGIN-file-view-switches-folder-per-project |
| Quality (project folder roots) | E2E-PLUGIN-file-view-switches-folder-per-project |
@@ -10264,6 +10299,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| M6+ (Windows updater cache) | E2E-260 |
| M6+ (Independent session communication) | E2E-SESSION-independent-top-level-communication, E2E-SESSION-hover-card-model-and-links |
| M5 (Chat file references) | E2E-CHAT-shorthand-file-ref-opens-the-matching-file, E2E-CHAT-file-ref-opens-the-surface-that-owns-it |
+| M5 (Composer deep file mentions) | E2E-COMPOSER-deep-file-mentions |
| M5 (Conversation MP4 attachments) | E2E-CHAT-mp4-attachment-opens-in-system-player |
| M6+ (Chat file references) | E2E-PLUGIN-file-view-collapse-persists |
| M6+ (project folder roots) | E2E-PLUGIN-file-view-switches-folder-per-project |
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 057e6fc9a..757538dbf 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -72,6 +72,7 @@ This log freezes previously open questions into concrete decisions.
| D021 | First-run onboarding | **Inline checklist (not modal wizard)** |
| D022 | Local telemetry | **Local logs only in MVP (no remote telemetry)** |
| D664 | Sidebar running activity defaults | **When unset, the master and Count badge resolve on while Activity rail resolves off. Explicit saved values remain authoritative. The master continues gating both affordances; turning it off does not rewrite either child preference. No schema or migration change.** |
+| D665 | `@` queries search past a truncated file index | **Amend D124: while the 8000-entry `fs/index` snapshot is truncated, a non-empty `@` query is also searched over the root's full listing through the read-only Electron channel `pi-desktop/fs/search` once typing pauses, and its best 50 rows merge with the local matches. A complete index never searches. Remote sessions keep their snapshot. No host RPC, storage, or schema change.** |
## C. Provider & model coverage decisions (0.3.4)
@@ -7778,3 +7779,26 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
default. Settings reads apply these defaults through renderer API
normalization; no persisted schema or migration change is required. See
`04-ux/01-ui-ia.md`, `04-ux/06-settings-ia.md`, and E2E-266.
+
+## 2026-10-19 — `@` queries search past a truncated file index (D665)
+
+- The `fs/index` snapshot keeps the shallowest 8000 entries, and the menu
+ fuzzy-filtered only that snapshot. In a large tree — a Unity project, where
+ every asset has a `.meta` sibling — scripts several folders deep were never
+ in it, so no query could reach them even though the truncation footnote
+ invited refining the query (issue #1781).
+- While the snapshot is truncated, a non-empty query is now also sent to
+ `fs/search` after a 150 ms typing pause. Main ranks it with the renderer's
+ scorer over the listing it already built for the index (`git ls-files`), or
+ over a deeper ignore-set walk (at most 200,000 entries or two seconds) when
+ the index came from the walk, and returns the best 50 rows. The menu merges
+ them with its local matches; an answer for an earlier query is dropped.
+- A complete index never searches, so small projects behave as before. The
+ footnote stays while the list may be incomplete. Remote sessions keep their
+ snapshot because the remote file protocol has no search operation. Bundling
+ a native lister (ripgrep, bfs) was not needed: git already lists the whole
+ repository, and searching 60,000 paths takes a few milliseconds.
+- Covered by `packages/host-runtime/src/fs-index.test.ts` and
+ `apps/desktop/test/composer-deep-file-search-user-path.test.mjs`. See
+ `03-runtime/01-ipc-protocol.md` §13c, `04-ux/08-component-spec.md` §11.8,
+ and E2E-COMPOSER-deep-file-mentions.
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index 79a7716a2..10c9a8395 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -1618,7 +1618,7 @@ Electron 报告的右侧角)改变的是面板目标。Main 通过
## 13c. Composer 输入 API(D123/D124/D197、ADR 0024/0059)
仅电子通道支持输入框自动完成和剪贴板文件
-参考。 `composer/commands` 和 `fs/index` 是只读且软故障;
+参考。 `composer/commands`、`fs/index` 和 `fs/search` 是只读且软故障;
`composer/pasteFiles` 仅写入原始会话的 Electron 拥有的
暂存目录。 None 添加主机 RPC 方法或更改主机协议
版本。
@@ -1664,7 +1664,23 @@ type FsIndexEntry = { path: string; kind: "file" | "dir" };
--exclude-standard`快速路径,忽略设置递归行走回退,
从文件路径派生的目录,8000 个条目上限,`truncated: true`,
每个根的短 TTL 缓存。无法关闭到空列表而没有
-工作区。模糊过滤发生在渲染器端。
+工作区。模糊过滤发生在渲染器端;被截断的索引只保留最浅的条目,因此针对它的
+查询还会发给 `fs/search`。
+
+### fs/search
+
+```ts
+fs/search({ sessionId?, query }) -> { entries: FsIndexEntry[]; truncated: boolean }
+```
+
+只有当 `fs/index` 快照被截断且查询非空时,`@` 菜单才会在输入短暂停顿后调用它,
+并把结果与自己的匹配合并(D665)。主进程用与渲染器相同的模糊打分,在该根目录的
+完整清单上排序,返回最好的 50 个条目。清单就是索引背后的 `git ls-files` 列表;
+若索引来自目录遍历,则改为一次更深的遍历(遵守同一忽略集,最多 200,000 个条目或
+2 秒)。清单与索引共用 TTL 缓存,过期即释放。`truncated: true` 表示搜索本身被截断。
+查询会去掉首尾空白并限制在 256 个字符内;空查询不返回条目。远程会话直接返回
+`{ entries: [], truncated: true }`,不联系远程主机——远程文件协议没有搜索操作——
+菜单继续只在远程快照里过滤。
### composer/pickFiles 和 composer/pickPhotos
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index 07d75aa4e..4afd8c37c 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -2290,8 +2290,11 @@ Live Voice 受现有开发者模式和开发构建门控约束,包含四种展
(Enter、Tab 或点击)会把 `@` 标记替换为光标处的行内叶名芯片
—— 与粘贴文件相同的哨兵芯片 —— 其规范值为原始 `entry.path`;
菜单关闭且这次 Enter 不会发送。接受目录会将文字路径保留在草稿中,
- 以便完成可以继续。条目来自 `fs/index`(D124、D209、D362)。一个
- 当索引被限制时出现截断脚注;没有工作空间
+ 以便完成可以继续。条目来自 `fs/index`(D124、D209、D362)。
+ 索引被截断时,输入停顿后查询还会通过 `fs/search` 在完整清单中搜索,
+ 搜到的行与本地匹配合并(D665)。列表可能不完整时显示截断脚注——
+ 只输入 `@` 时、该标记的第一次搜索返回之前,以及搜索本身被截断或不可用
+ (如远程会话)时;没有工作空间
菜单显示“打开项目”空状态。
- 接受命令和目录插入文本(`/name ` / `@dir/`);
接受完成的文件会插入行内芯片,而不是删除触发符。立即
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 1bf5205a0..086d23b4e 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -5288,6 +5288,32 @@ eleven-tool-round desktop paths are verified by
布局由 `scripts/e2e-composer-autocomplete.mjs` 覆盖;完整的用户界面
旅程草稿(适用变更合入前需在具备条件的环境中运行 E2E)
+#### E2E-COMPOSER-deep-file-mentions:`@` 能找到大型工作区里的深层文件
+
+- **先决条件**:应用程序正在一个索引被截断(超过 8000 个文件和目录)的工作区中使用
+ Agent 会话运行,其中有一个脚本位于数千个浅层资源之下的几层目录里——例如 Unity
+ 项目的 `Assets/_Game/Scripts/Gameplay/Player/FeatureController.cs`。工作区在 git
+ 管理下和不在 git 管理下各运行一次。
+- **步骤**:1) 输入 `@` 并检查脚注。2) 输入脚本名称后停顿。3) 用 Enter 接受该脚本的行。
+ 4) 快速把查询改成几个不同的前缀。5) 在小工作区和远程会话中重复。
+- **预期**:
+ - 只输入 `@` 时列出索引并显示截断脚注。
+ - 停顿后深层脚本作为一行出现,排序与其他匹配一致;这次搜索返回后脚注消失;被
+ `.gitignore` 或忽略集排除的文件从不出现。
+ - 接受后插入与其他引用相同的文件芯片。
+ - 行永远不属于更早的查询。搜索进行中菜单保留本地匹配。
+ - 小工作区不发出搜索请求;远程会话保持使用快照并保留脚注。
+- **链接规格**:`04-ux/08-component-spec.md` §11.8、`03-runtime/01-ipc-protocol.md`
+ §13c、`08-meta/decisions-log.md`(D124、D665)、ADR 0024
+- **接受**:C(对话和直播),质量
+- **里程碑**:M5
+- **状态**:单元覆盖(`packages/host-runtime/src/fs-index.test.ts` 覆盖 git 与遍历两种
+ 清单、忽略规则、目录以及结果上限);渲染层旅程——停顿后搜索、合并、接受、过期
+ 结果、脚注以及完整索引路径——由
+ `apps/desktop/test/composer-deep-file-search-user-path.test.mjs` 在真实 Electron
+ 渲染器中覆盖。针对大型真实目录树的完整桌面旅程为草稿(适用变更合入前需在具备
+ 条件的环境中运行 E2E)。
+
#### E2E-102b:未答复的停止恢复紧凑的文件参考草稿
- **先决条件**:Agent 会话可以延迟其第一个辅助事件。的
@@ -5806,6 +5832,7 @@ eleven-tool-round desktop paths are verified by
| C / 质量 / 安全(对话 MP4 附件) | E2E-CHAT-mp4-attachment-opens-in-system-player |
| G——插件(聊天文件引用) | E2E-CHAT-file-ref-opens-the-surface-that-owns-it、E2E-PLUGIN-file-view-collapse-persists |
| 品质(聊天文件引用) | E2E-CHAT-shorthand-file-ref-opens-the-matching-file、E2E-CHAT-file-ref-opens-the-surface-that-owns-it、E2E-PLUGIN-file-view-collapse-persists |
+| C / 品质(Composer 深层文件引用) | E2E-COMPOSER-deep-file-mentions |
| G——插件(项目文件夹根) | E2E-PLUGIN-file-view-switches-folder-per-project |
| 安全性(项目文件夹根) | E2E-PLUGIN-file-view-switches-folder-per-project |
| 品质(项目文件夹根) | E2E-PLUGIN-file-view-switches-folder-per-project |
@@ -5860,6 +5887,7 @@ eleven-tool-round desktop paths are verified by
| M6+(Windows 更新缓存) | E2E-260 |
| M6+(独立会话通信) | E2E-SESSION-independent-top-level-communication、E2E-SESSION-hover-card-model-and-links |
| M5(聊天文件引用) | E2E-CHAT-shorthand-file-ref-opens-the-matching-file、E2E-CHAT-file-ref-opens-the-surface-that-owns-it |
+| M5(Composer 深层文件引用) | E2E-COMPOSER-deep-file-mentions |
| M5(对话 MP4 附件) | E2E-CHAT-mp4-attachment-opens-in-system-player |
| M6+(聊天文件引用) | E2E-PLUGIN-file-view-collapse-persists |
| M6+(项目文件夹根) | E2E-PLUGIN-file-view-switches-folder-per-project |
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index c5792d558..1b25b35aa 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -74,6 +74,7 @@
| D021 | 首次运行新手引导 | **内联清单(不是模式向导)** |
| D022 | 本地遥测 | **仅在 MVP 中记录本地日志(无远程遥测)** |
| D664 | 侧边栏运行活动默认值 | **未设置时,总开关和数量徽标默认开启,活动流光默认关闭。已保存的值优先生效。总开关仍控制两种提示;关闭总开关不会改写任一子开关偏好。不更改 schema 或执行迁移。** |
+| D665 | `@` 查询越过被截断的文件索引 | **修订 D124:8000 条的 `fs/index` 快照被截断时,非空的 `@` 查询会在输入停顿后,通过只读的 Electron 通道 `pi-desktop/fs/search` 在该根目录的完整清单中搜索,最好的 50 行与本地匹配合并。完整的索引从不搜索。远程会话保持使用快照。不改变主机 RPC、存储或 schema。** |
## C. 提供商和模型覆盖决策 (0.3.4)
@@ -5488,3 +5489,20 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
- 数量徽标保留运行状态的可发现性,同时避免动画轨道成为默认界面。不需要更改持久化
schema 或迁移。设置读取通过渲染层 API 规范化应用这些默认值。见
`04-ux/01-ui-ia.md`、`04-ux/06-settings-ia.md` 与 E2E-266。
+
+## 2026-10-19 —— `@` 查询越过被截断的文件索引(D665)
+
+- `fs/index` 快照只保留最浅的 8000 个条目,菜单也只在这份快照里模糊过滤。在大项目里
+ ——例如每个资源都带一个 `.meta` 文件的 Unity 项目——藏在几层目录下的脚本根本不在
+ 快照中,无论怎么输入都找不到,尽管截断脚注提示用户继续输入(issue #1781)。
+- 快照被截断时,非空查询现在会在输入停顿 150 ms 后同时发给 `fs/search`。主进程用与
+ 渲染器相同的打分,在它为索引已经构建好的清单(`git ls-files`)上排序;若索引来自
+ 目录遍历,则改为一次更深的遍历(遵守同一忽略集,最多 200,000 个条目或 2 秒),
+ 返回最好的 50 行。菜单把它们与本地匹配合并;较早查询的结果会被丢弃。
+- 完整的索引从不搜索,小项目行为不变。列表可能不完整时截断脚注保留。远程会话继续
+ 使用快照,因为远程文件协议没有搜索操作。不需要打包原生列文件工具(ripgrep、bfs):
+ git 本来就能列出整个仓库,搜索 60,000 个路径只需几毫秒。
+- 由 `packages/host-runtime/src/fs-index.test.ts` 与
+ `apps/desktop/test/composer-deep-file-search-user-path.test.mjs` 覆盖。见
+ `03-runtime/01-ipc-protocol.md` §13c、`04-ux/08-component-spec.md` §11.8 与
+ E2E-COMPOSER-deep-file-mentions。
diff --git a/packages/host-runtime/src/fs-index.test.ts b/packages/host-runtime/src/fs-index.test.ts
new file mode 100644
index 000000000..ffe96c1d0
--- /dev/null
+++ b/packages/host-runtime/src/fs-index.test.ts
@@ -0,0 +1,87 @@
+import { spawnSync } from "node:child_process";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { afterAll, expect, it } from "vitest";
+import {
+ FS_INDEX_MAX_ENTRIES,
+ getWorkspaceFileIndex,
+ searchWorkspaceFiles,
+} from "./fs-index.js";
+
+const DEEP_SCRIPT = "Assets/_Game/Scripts/Gameplay/Player/Controllers/FeatureController.cs";
+
+const temps: string[] = [];
+afterAll(async () => {
+ await Promise.all(temps.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
+});
+
+async function writeFiles(root: string, paths: string[]): Promise<void> {
+ for (let at = 0; at < paths.length; at += 500) {
+ await Promise.all(
+ paths.slice(at, at + 500).map(async (path) => {
+ await mkdir(dirname(join(root, path)), { recursive: true });
+ await writeFile(join(root, path), "x");
+ }),
+ );
+ }
+}
+
+/** A Unity-like tree: more shallow assets than the snapshot holds, one deep script. */
+async function largeTree(prefix: string): Promise<string> {
+ const root = await mkdtemp(join(tmpdir(), prefix));
+ temps.push(root);
+ const assets = Array.from(
+ { length: FS_INDEX_MAX_ENTRIES + 100 },
+ (_, index) => `Assets/Art/Group${Math.floor(index / 300)}/asset_${index}.png`,
+ );
+ await writeFiles(root, [...assets, DEEP_SCRIPT, "node_modules/pkg/FeatureController.cs"]);
+ return root;
+}
+
+function gitAvailable(): boolean {
+ return spawnSync("git", ["--version"]).status === 0;
+}
+
+it("finds a deep file that the truncated snapshot leaves out", async () => {
+ const root = await largeTree("pi-fs-search-walk-");
+
+ const index = await getWorkspaceFileIndex(root);
+ expect(index.truncated).toBe(true);
+ expect(index.entries).toHaveLength(FS_INDEX_MAX_ENTRIES);
+ expect(index.entries.some((entry) => entry.path === DEEP_SCRIPT)).toBe(false);
+
+ const found = await searchWorkspaceFiles(root, "FeatureController");
+ expect(found.truncated).toBe(false);
+ expect(found.entries[0]).toEqual({ path: DEEP_SCRIPT, kind: "file" });
+ expect(found.entries.some((entry) => entry.path.startsWith("node_modules/"))).toBe(false);
+});
+
+it("searches a git repository's full listing and keeps its ignore rules", async (ctx) => {
+ if (!gitAvailable()) ctx.skip();
+ const root = await largeTree("pi-fs-search-git-");
+ await writeFiles(root, ["Generated/FeatureController.cs"]);
+ await writeFile(join(root, ".gitignore"), "Generated/\n");
+ expect(spawnSync("git", ["init", "-q"], { cwd: root }).status).toBe(0);
+
+ const index = await getWorkspaceFileIndex(root);
+ expect(index.truncated).toBe(true);
+ expect(index.entries.some((entry) => entry.path === DEEP_SCRIPT)).toBe(false);
+
+ const found = await searchWorkspaceFiles(root, "FeatureController");
+ expect(found.truncated).toBe(false);
+ expect(found.entries.map((entry) => entry.path)).toEqual([DEEP_SCRIPT]);
+});
+
+it("returns directories and honors the result limit", async () => {
+ const root = await largeTree("pi-fs-search-limit-");
+
+ const dirs = await searchWorkspaceFiles(root, "Controllers");
+ expect(dirs.entries[0]).toEqual({
+ path: "Assets/_Game/Scripts/Gameplay/Player/Controllers",
+ kind: "dir",
+ });
+
+ const limited = await searchWorkspaceFiles(root, "asset_", 5);
+ expect(limited.entries).toHaveLength(5);
+});
diff --git a/packages/host-runtime/src/fs-index.ts b/packages/host-runtime/src/fs-index.ts
index 5f4673a28..5a63abab2 100644
--- a/packages/host-runtime/src/fs-index.ts
+++ b/packages/host-runtime/src/fs-index.ts
@@ -1,7 +1,12 @@
import { spawn } from "node:child_process";
import { readdir } from "node:fs/promises";
import { join } from "node:path";
-import type { FsIndexEntry, FsIndexResult } from "@pi-desktop/shared";
+import {
+ fuzzyMatchPath,
+ selectBestMatches,
+ type FsIndexEntry,
+ type FsIndexResult,
+} from "@pi-desktop/shared";
import { isIgnoredName } from "./workspace-files.js";
/**
@@ -10,16 +15,33 @@ import { isIgnoredName } from "./workspace-files.js";
* Served from the main process like the files tab (ADR 0019): user-driven
* browsing must not round-trip agent tools or permission prompts. The index
* prefers `git ls-files` for exact gitignore semantics and falls back to a
- * bounded walk over the panel's ignore set. Fuzzy filtering happens in the
- * renderer; this only snapshots relative paths.
+ * bounded walk over the panel's ignore set. The renderer fuzzy-filters the
+ * snapshot itself; when the snapshot is truncated, a query is also answered
+ * here from the full listing (D665).
*/
export const FS_INDEX_MAX_ENTRIES = 8000;
+/** Most entries a query searches when the snapshot is truncated. */
+const FS_SEARCH_MAX_ENTRIES = 200_000;
+/** The composer menu shows at most this many file rows. */
+const FS_SEARCH_MAX_RESULTS = 50;
+/** `fuzzyMatchPath` lowercases the query once per entry. */
+const FS_SEARCH_MAX_QUERY = 256;
+const SEARCH_WALK_TIMEOUT_MS = 2000;
const CACHE_TTL_MS = 15_000;
const GIT_TIMEOUT_MS = 4000;
const MAX_GIT_BUFFER = 32 * 1024 * 1024;
-type CacheSlot = { at: number; result: FsIndexResult };
+/** Shallow-first entries; `complete` is false when a cap or timeout cut them short. */
+type Listing = { entries: FsIndexEntry[]; complete: boolean };
+type CacheSlot = {
+ at: number;
+ index: FsIndexResult;
+ listing: Listing;
+ /** The listing came from the snapshot-sized walk, so a query may deepen it. */
+ walked: boolean;
+ deeper?: Promise<Listing>;
+};
const cache = new Map<string, CacheSlot>();
function hasIgnoredSegment(path: string): boolean {
@@ -66,13 +88,18 @@ function gitListFiles(root: string): Promise<string[] | null> {
async function walkFiles(
root: string,
budget: number,
+ deadline = Number.POSITIVE_INFINITY,
): Promise<{ files: string[]; dirs: string[]; exhausted: boolean }> {
const files: string[] = [];
const dirs: string[] = [];
let exhausted = false;
const queue: string[] = [""];
- while (queue.length > 0) {
- const rel = queue.shift()!;
+ for (let next = 0; next < queue.length; next += 1) {
+ if (Date.now() > deadline) {
+ exhausted = true;
+ break;
+ }
+ const rel = queue[next]!;
let dirents;
try {
dirents = await readdir(join(root, rel), { withFileTypes: true });
@@ -124,46 +151,57 @@ function compareEntries(a: FsIndexEntry, b: FsIndexEntry): number {
return a.path.localeCompare(b.path);
}
-async function buildIndex(root: string): Promise<FsIndexResult> {
- const viaGit = await gitListFiles(root);
- let files: string[];
- let dirs: string[];
- let exhausted = false;
- if (viaGit) {
- // -o lists untracked-but-not-ignored files; repos without a .gitignore
- // would still surface build output, so the panel ignore set applies too.
- files = viaGit.filter((p) => !hasIgnoredSegment(p));
- dirs = dirsFromFilePaths(files);
- } else {
- const walked = await walkFiles(root, FS_INDEX_MAX_ENTRIES + 1);
- files = walked.files;
- dirs = walked.dirs;
- exhausted = walked.exhausted;
- }
-
+function toListing(files: string[], dirs: string[], complete: boolean): Listing {
const entries: FsIndexEntry[] = [
...dirs.map((path): FsIndexEntry => ({ path, kind: "dir" })),
...files.map((path): FsIndexEntry => ({ path, kind: "file" })),
].sort(compareEntries);
+ if (entries.length > FS_SEARCH_MAX_ENTRIES) {
+ return { entries: entries.slice(0, FS_SEARCH_MAX_ENTRIES), complete: false };
+ }
+ return { entries, complete };
+}
- if (entries.length > FS_INDEX_MAX_ENTRIES) {
- return { entries: entries.slice(0, FS_INDEX_MAX_ENTRIES), truncated: true };
+async function walkListing(root: string, budget: number, deadline?: number): Promise<Listing> {
+ const walked = await walkFiles(root, budget, deadline);
+ return toListing(walked.files, walked.dirs, !walked.exhausted);
+}
+
+async function buildSlot(root: string): Promise<CacheSlot> {
+ const viaGit = await gitListFiles(root);
+ let listing: Listing;
+ if (viaGit) {
+ // -o lists untracked-but-not-ignored files; repos without a .gitignore
+ // would still surface build output, so the panel ignore set applies too.
+ const files = viaGit.filter((p) => !hasIgnoredSegment(p));
+ listing = toListing(files, dirsFromFilePaths(files), true);
+ } else {
+ listing = await walkListing(root, FS_INDEX_MAX_ENTRIES + 1);
}
- return { entries, truncated: exhausted };
+ const { entries, complete } = listing;
+ const index =
+ entries.length > FS_INDEX_MAX_ENTRIES
+ ? { entries: entries.slice(0, FS_INDEX_MAX_ENTRIES), truncated: true }
+ : { entries, truncated: !complete };
+ return { at: Date.now(), index, listing, walked: !viaGit };
}
-/** TTL-cached workspace index; concurrent calls share one build. */
-const pending = new Map<string, Promise<FsIndexResult>>();
+/** TTL-cached workspace listing; concurrent calls share one build. */
+const pending = new Map<string, Promise<CacheSlot>>();
-export async function getWorkspaceFileIndex(root: string): Promise<FsIndexResult> {
+function slotFor(root: string): Promise<CacheSlot> {
const cached = cache.get(root);
- if (cached && Date.now() - cached.at < CACHE_TTL_MS) return cached.result;
+ if (cached && Date.now() - cached.at < CACHE_TTL_MS) return Promise.resolve(cached);
const inFlight = pending.get(root);
if (inFlight) return inFlight;
- const build = buildIndex(root)
- .then((result) => {
- cache.set(root, { at: Date.now(), result });
- return result;
+ const build = buildSlot(root)
+ .then((slot) => {
+ cache.set(root, slot);
+ // A large tree's listing is held for the TTL only, not until the next build.
+ setTimeout(() => {
+ if (cache.get(root) === slot) cache.delete(root);
+ }, CACHE_TTL_MS).unref();
+ return slot;
})
.finally(() => {
pending.delete(root);
@@ -171,3 +209,46 @@ export async function getWorkspaceFileIndex(root: string): Promise<FsIndexResult
pending.set(root, build);
return build;
}
+
+export async function getWorkspaceFileIndex(root: string): Promise<FsIndexResult> {
+ return (await slotFor(root)).index;
+}
+
+/**
+ * The best `limit` entries for an "@" query over the whole listing, ranked
+ * like the renderer ranks the snapshot. A truncated snapshot keeps the
+ * shallowest entries, so deep files of a large tree can only be found here
+ * (#1781). A listing from the snapshot-sized walk is deepened once per slot.
+ */
+export async function searchWorkspaceFiles(
+ root: string,
+ query: string,
+ limit = FS_SEARCH_MAX_RESULTS,
+): Promise<FsIndexResult> {
+ const needle = query.trim().slice(0, FS_SEARCH_MAX_QUERY);
+ if (!needle) return { entries: [], truncated: false };
+ const slot = await slotFor(root);
+ const listing =
+ slot.walked && !slot.listing.complete
+ ? await (slot.deeper ??= walkListing(
+ root,
+ FS_SEARCH_MAX_ENTRIES,
+ Date.now() + SEARCH_WALK_TIMEOUT_MS,
+ ))
+ : slot.listing;
+ const best = selectBestMatches(matchEntries(listing.entries, needle), limit, (hit) => ({
+ score: hit.score,
+ text: hit.entry.path,
+ }));
+ return { entries: best.map((hit) => hit.entry), truncated: !listing.complete };
+}
+
+function* matchEntries(
+ entries: FsIndexEntry[],
+ query: string,
+): Generator<{ entry: FsIndexEntry; score: number }> {
+ for (const entry of entries) {
+ const match = fuzzyMatchPath(query, entry.path, entry.kind);
+ if (match) yield { entry, score: match.score };
+ }
+}
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index 763584524..761fcb4bb 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -417,6 +417,7 @@ export const IPC = {
fsReveal: "pi-desktop/fs/reveal",
fsOpen: "pi-desktop/fs/open",
fsIndex: "pi-desktop/fs/index",
+ fsSearch: "pi-desktop/fs/search",
fsResolveRef: "pi-desktop/fs/resolveRef",
windowSetWorkPanelReservation:
"pi-desktop/window/setWorkPanelReservation",