Skip to content

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

fix(composer): pre-warm the slash command source at launch

vastsa89dc43057b53
diff --git a/apps/desktop/src/hooks/use-composer-autocomplete.ts b/apps/desktop/src/hooks/use-composer-autocomplete.ts
index 2d651cd9f..13ea7f339 100644
--- a/apps/desktop/src/hooks/use-composer-autocomplete.ts
+++ b/apps/desktop/src/hooks/use-composer-autocomplete.ts
@@ -15,6 +15,11 @@ import {
type FuzzyMatch,
} from "@pi-desktop/shared";
import { api } from "../lib/api";
+import {
+ fetchComposerCommands,
+ prewarmComposerCommands,
+ readComposerCommandsCache,
+} from "../lib/composer-command-source";
import { useAppStore } from "../stores/app-store";
/**
@@ -31,9 +36,11 @@ export type AutocompleteItem =
| { kind: "command"; command: ComposerCommand; match: FuzzyMatch }
| { kind: "path"; entry: FsIndexEntry; match: FuzzyMatch };
-/** Module-level TTL caches so re-triggering stays IPC-free. */
-let commandsCache: { key: string; at: number; commands: ComposerCommand[] } | null =
- null;
+/**
+ * Module-level TTL cache so re-triggering stays IPC-free. The `/` command
+ * source itself lives in `lib/composer-command-source`, because the launch
+ * pre-warm (#1543) must seed it before this hook mounts.
+ */
let filesCache: {
key: string;
at: number;
@@ -130,14 +137,10 @@ export async function resolveComposerCommand(
name: string,
): Promise<ComposerCommandResolution> {
const key = useAppStore.getState().workspace?.path ?? "";
- if (
- !commandsCache ||
- commandsCache.key !== key ||
- Date.now() - commandsCache.at > SOURCE_TTL_MS
- ) {
+ let commands = readComposerCommandsCache(key);
+ if (!commands) {
try {
- const res = await api.composerCommands();
- commandsCache = { key, at: Date.now(), commands: res.commands };
+ commands = await fetchComposerCommands(key);
} catch (error) {
// Deliberately leaves the cache cold: the next attempt re-reads the
// source, which is what makes the refusal retriable.
@@ -147,7 +150,7 @@ export async function resolveComposerCommand(
};
}
}
- const command = commandsCache.commands.find((c) => c.name === name);
+ const command = commands.find((c) => c.name === name);
return command ? { status: "resolved", command } : { status: "unknown" };
}
@@ -164,6 +167,7 @@ export function useComposerAutocomplete({
}) {
const workspaceKey = useAppStore((s) => s.workspace?.path ?? "");
const hasWorkspace = workspaceKey !== "";
+ const ready = useAppStore((s) => s.ready);
const [commands, setCommands] = useState<ComposerCommand[] | null>(null);
const [files, setFiles] = useState<{
entries: FsIndexEntry[];
@@ -197,20 +201,15 @@ export function useComposerAutocomplete({
if (!trigger || dismissed) return;
const now = Date.now();
if (trigger.mode === "slash") {
- if (
- commandsCache &&
- commandsCache.key === workspaceKey &&
- now - commandsCache.at < SOURCE_TTL_MS
- ) {
- setCommands(commandsCache.commands);
+ const cached = readComposerCommandsCache(workspaceKey);
+ if (cached) {
+ setCommands(cached);
return;
}
let cancelled = false;
- void api
- .composerCommands()
- .then((res) => {
- commandsCache = { key: workspaceKey, at: Date.now(), commands: res.commands };
- if (!cancelled) setCommands(res.commands);
+ void fetchComposerCommands(workspaceKey)
+ .then((commands) => {
+ if (!cancelled) setCommands(commands);
})
.catch(() => {
if (!cancelled) setCommands([]);
@@ -251,6 +250,15 @@ export function useComposerAutocomplete({
};
}, [trigger?.mode, dismissed, workspaceKey, hasWorkspace]);
+ // 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
+ // full host assembly and then be discarded.
+ useEffect(() => {
+ if (!enabled || !ready) return;
+ return prewarmComposerCommands(workspaceKey);
+ }, [enabled, ready, workspaceKey]);
+
const items = useMemo<AutocompleteItem[]>(() => {
if (!trigger || dismissed) return [];
if (trigger.mode === "slash") {
diff --git a/apps/desktop/src/lib/composer-command-source.ts b/apps/desktop/src/lib/composer-command-source.ts
new file mode 100644
index 000000000..4dcab9b5b
--- /dev/null
+++ b/apps/desktop/src/lib/composer-command-source.ts
@@ -0,0 +1,100 @@
+/**
+ * The merged `/` command source (builtin + template + plugin + extension + MCP
+ * + skill) behind one short TTL cache, shared by the composer menu and the
+ * send-time resolver.
+ *
+ * The cache lives outside React so the launch pre-warm (#1543) can seed it
+ * before the user types the first `/`: the host assembles that list from a cold
+ * MCP/skill read, so paying for it on the keystroke is what made the menu feel
+ * absent on a fresh launch.
+ */
+import type { ComposerCommand } from "@pi-desktop/shared";
+import { api } from "./api";
+
+/** Menu and resolver share one window; both re-read after it lapses. */
+const SOURCE_TTL_MS = 10_000;
+/** Attempts spend their wait on a booting sidecar, so keep the cadence short. */
+const PREWARM_RETRY_MS = 2_000;
+const PREWARM_MAX_ATTEMPTS = 10;
+
+type CommandCache = { key: string; at: number; commands: ComposerCommand[] };
+
+let cache: CommandCache | null = null;
+let inFlight: { key: string; promise: Promise<ComposerCommand[]> } | null = null;
+/** Read order of the last cache write, so a late answer cannot win. */
+let cacheWriteSeq = 0;
+
+/**
+ * The warm list for `key`, or `null` when the cache is cold or holds another
+ * workspace. Callers treat `null` as "read the source".
+ */
+export function readComposerCommandsCache(
+ key: string,
+ now = Date.now(),
+): ComposerCommand[] | null {
+ if (!cache || cache.key !== key || now - cache.at >= SOURCE_TTL_MS) return null;
+ return cache.commands;
+}
+
+/**
+ * Read the source, sharing one RPC between concurrent callers (the pre-warm and
+ * a typed `/` can overlap). A failed read leaves the cache cold, so the next
+ * attempt re-reads instead of serving an empty menu forever.
+ */
+export function fetchComposerCommands(key: string): Promise<ComposerCommand[]> {
+ const cached = readComposerCommandsCache(key);
+ if (cached) return Promise.resolve(cached);
+ if (inFlight && inFlight.key === key) return inFlight.promise;
+ const seq = ++cacheWriteSeq;
+ const tracked = api
+ .composerCommands()
+ .then((res) => {
+ // A read that started later owns the cache: a late answer for a previous
+ // workspace must not re-cold the current one.
+ if (!cache || cacheWriteSeq === seq) {
+ cache = { key, at: Date.now(), commands: res.commands };
+ }
+ return res.commands;
+ })
+ .finally(() => {
+ // Identity, not key: an older read for the same key must not clear the
+ // newer one that replaced it in `inFlight`.
+ if (inFlight?.promise === tracked) inFlight = null;
+ });
+ inFlight = { key, promise: tracked };
+ return tracked;
+}
+
+/**
+ * Seed the cache while the app starts, so the first `/` of a session opens
+ * without a host round trip (#1543). A launch races a booting sidecar, so a
+ * failed attempt retries on a short cadence; the lazy menu path stays the
+ * fallback and the host list is re-read once the TTL lapses either way.
+ *
+ * @returns the cancel handle for the caller's effect cleanup.
+ */
+export function prewarmComposerCommands(key: string): () => void {
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let cancelled = false;
+ let attempts = 0;
+ const attempt = (): void => {
+ void fetchComposerCommands(key).catch(() => {
+ // Expected while the host is still booting; the menu re-reads on demand.
+ if (cancelled || attempts >= PREWARM_MAX_ATTEMPTS) return;
+ attempts += 1;
+ timer = setTimeout(attempt, PREWARM_RETRY_MS);
+ });
+ };
+ if (!readComposerCommandsCache(key)) attempt();
+ return () => {
+ cancelled = true;
+ if (timer !== null) clearTimeout(timer);
+ };
+}
+
+/** Test seam: forget the TTL window, any tracked read and the write order. */
+export function resetComposerCommandCache(): void {
+ cache = null;
+ inFlight = null;
+ cacheWriteSeq = 0;
+}
diff --git a/apps/desktop/test/composer-command-prewarm.test.mjs b/apps/desktop/test/composer-command-prewarm.test.mjs
new file mode 100644
index 000000000..c442cedda
--- /dev/null
+++ b/apps/desktop/test/composer-command-prewarm.test.mjs
@@ -0,0 +1,271 @@
+/**
+ * Issue #1543: the first `/` of a session must not wait for a cold host read.
+ *
+ * The composer reads the merged command source on the keystroke, so a fresh
+ * launch opened an empty (or late) menu until the host answered. The pre-warm
+ * seeds the same TTL cache while the app starts; these tests lock its retry,
+ * coalescing, cancel, ceiling and failure behaviour.
+ */
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { register } from "node:module";
+import test from "node:test";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
+
+const load = (relative) => import(pathToFileURL(join(here, relative)).href);
+
+const { api } = await load("../src/lib/api.ts");
+const {
+ fetchComposerCommands,
+ prewarmComposerCommands,
+ readComposerCommandsCache,
+ resetComposerCommandCache,
+} = await load("../src/lib/composer-command-source.ts");
+
+const COMMANDS = [
+ { name: "compact", kind: "builtin", title: "Compact", id: "builtin.agent.compact" },
+];
+
+/** Let the pending promise callbacks of the pre-warm run. */
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+
+/** Run `body` with `api.composerCommands` replaced, restoring it afterwards. */
+async function withCommandSource(replacement, body) {
+ const original = api.composerCommands;
+ api.composerCommands = replacement;
+ try {
+ return await body();
+ } finally {
+ api.composerCommands = original;
+ }
+}
+
+test.afterEach(() => resetComposerCommandCache());
+
+test("the pre-warm seeds the cache before the user types a slash", async () => {
+ await withCommandSource(
+ async () => ({ commands: COMMANDS }),
+ async () => {
+ const cancel = prewarmComposerCommands("/pi-1543-warm");
+ await flush();
+ cancel();
+
+ const cached = readComposerCommandsCache("/pi-1543-warm");
+ assert.ok(cached, "the pre-warm must leave a warm cache");
+ assert.equal(cached[0].id, "builtin.agent.compact");
+
+ let reads = 0;
+ await withCommandSource(
+ async () => {
+ reads += 1;
+ return { commands: [] };
+ },
+ async () => {
+ const commands = await fetchComposerCommands("/pi-1543-warm");
+ assert.equal(commands[0].id, "builtin.agent.compact");
+ assert.equal(reads, 0, "a warm cache must not re-read the host");
+ },
+ );
+ },
+ );
+});
+
+test("the cache is keyed by workspace and expires on the TTL", async () => {
+ await withCommandSource(
+ async () => ({ commands: COMMANDS }),
+ async () => {
+ const cancel = prewarmComposerCommands("/pi-1543-ttl");
+ await flush();
+ cancel();
+
+ const now = Date.now();
+ assert.ok(readComposerCommandsCache("/pi-1543-ttl", now));
+ assert.equal(
+ readComposerCommandsCache("/pi-1543-ttl", now + 10_001),
+ null,
+ "a lapsed window reads as cold",
+ );
+ assert.equal(
+ readComposerCommandsCache("/pi-1543-other", now),
+ null,
+ "another workspace never reuses the list",
+ );
+ },
+ );
+});
+
+test("a pre-warm retries while the host is still booting", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ let attempts = 0;
+ await withCommandSource(
+ async () => {
+ attempts += 1;
+ if (attempts === 1) throw new Error("HOST_UNAVAILABLE");
+ return { commands: COMMANDS };
+ },
+ async () => {
+ const cancel = prewarmComposerCommands("/pi-1543-boot");
+ await flush();
+ assert.equal(attempts, 1);
+ assert.equal(
+ readComposerCommandsCache("/pi-1543-boot"),
+ null,
+ "a failed read must stay cold so the menu retries",
+ );
+
+ t.mock.timers.tick(2_000);
+ await flush();
+ assert.equal(attempts, 2, "the pre-warm retries after the host answers");
+ assert.ok(readComposerCommandsCache("/pi-1543-boot"), "the retry seeds the cache");
+ cancel();
+ },
+ );
+});
+
+test("the pre-warm gives up after its attempt ceiling", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ let attempts = 0;
+ await withCommandSource(
+ async () => {
+ attempts += 1;
+ throw new Error("HOST_UNAVAILABLE");
+ },
+ async () => {
+ const cancel = prewarmComposerCommands("/pi-1543-ceiling");
+ await flush();
+ for (let round = 0; round < 15; round += 1) {
+ t.mock.timers.tick(2_000);
+ await flush();
+ }
+ assert.equal(attempts, 11, "one initial attempt plus ten retries");
+ cancel();
+ },
+ );
+});
+
+test("cancelling the pre-warm stops the retry loop", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ let attempts = 0;
+ await withCommandSource(
+ async () => {
+ attempts += 1;
+ throw new Error("HOST_UNAVAILABLE");
+ },
+ async () => {
+ const cancel = prewarmComposerCommands("/pi-1543-cancel");
+ await flush();
+ cancel();
+
+ t.mock.timers.tick(60_000);
+ await flush();
+ assert.equal(attempts, 1, "a cancelled pre-warm must stop retrying");
+ },
+ );
+});
+
+test("a slash typed during the pre-warm shares its host read", async () => {
+ let reads = 0;
+ let release;
+ const gate = new Promise((resolve) => {
+ release = resolve;
+ });
+ await withCommandSource(
+ async () => {
+ reads += 1;
+ await gate;
+ return { commands: COMMANDS };
+ },
+ async () => {
+ const cancel = prewarmComposerCommands("/pi-1543-share");
+ const typed = fetchComposerCommands("/pi-1543-share");
+ release();
+
+ const commands = await typed;
+ assert.equal(reads, 1, "the pre-warm and the typed slash share one read");
+ assert.equal(commands[0].id, "builtin.agent.compact");
+ cancel();
+ },
+ );
+});
+
+test("the composer hook wires the pre-warm and leaves the cache to the source module", async () => {
+ const source = await readFile(
+ new URL("../src/hooks/use-composer-autocomplete.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ source,
+ /prewarmComposerCommands\(workspaceKey\)/,
+ "the hook must seed the source while the app starts",
+ );
+ assert.doesNotMatch(
+ source,
+ /\bcommandsCache\b/,
+ "the `/` source cache belongs to lib/composer-command-source",
+ );
+});
+
+test("a late answer never replaces a fresher workspace entry", async () => {
+ const pending = [];
+ await withCommandSource(
+ () =>
+ new Promise((resolve) => {
+ pending.push(resolve);
+ }),
+ async () => {
+ const previous = fetchComposerCommands("/pi-1543-previous");
+ const current = fetchComposerCommands("/pi-1543-current");
+ assert.equal(pending.length, 2, "each workspace reads on its own");
+
+ pending[1]({ commands: COMMANDS });
+ await current;
+ assert.ok(
+ readComposerCommandsCache("/pi-1543-current"),
+ "the current workspace is warm",
+ );
+
+ pending[0]({ commands: [] });
+ await previous;
+ assert.ok(
+ readComposerCommandsCache("/pi-1543-current"),
+ "a late answer for the previous workspace must not re-cold the current one",
+ );
+ },
+ );
+});
+
+test("an older read does not clear the newer in-flight read for the same key", async () => {
+ const pending = [];
+ await withCommandSource(
+ () =>
+ new Promise((resolve, reject) => {
+ pending.push({ resolve, reject });
+ }),
+ async () => {
+ const stale = fetchComposerCommands("/pi-1543-repeat");
+ const elsewhere = fetchComposerCommands("/pi-1543-elsewhere");
+ const current = fetchComposerCommands("/pi-1543-repeat");
+ assert.equal(pending.length, 3);
+
+ pending[0].reject(new Error("HOST_UNAVAILABLE"));
+ await stale.catch(() => undefined);
+
+ const shared = fetchComposerCommands("/pi-1543-repeat");
+ assert.equal(
+ pending.length,
+ 3,
+ "the newer read for that key stays the shared one",
+ );
+
+ pending[2].resolve({ commands: COMMANDS });
+ await Promise.all([current, shared]);
+ assert.ok(readComposerCommandsCache("/pi-1543-repeat"));
+ pending[1].resolve({ commands: [] });
+ await elsewhere;
+ },
+ );
+});