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(agent-runtime): keep admitted sessionDir sessions openable
Frank-zhu20000b0e83e476b9
diff --git a/apps/desktop/electron/main/ipc/session-ipc.ts b/apps/desktop/electron/main/ipc/session-ipc.tsindex 326a3d2d5..31cc924cd 100644--- a/apps/desktop/electron/main/ipc/session-ipc.ts+++ b/apps/desktop/electron/main/ipc/session-ipc.ts@@ -203,19 +203,16 @@ export function registerSessionIpc({});handle(IPC.invoke.sessionList, async () => {if (!host) throw new Error("host unavailable");- const projectPathsPromise = localNativeProjectPaths(host);- const desktopPromise = host.call<{ sessions: RuntimeSession[] }>("session.list");- const capabilityPromise = sessionCapabilityContext();- const projectPaths = await projectPathsPromise;- const [result, native, { providers, defaults }] = await Promise.all([- desktopPromise,- sidecar- ? sidecar- .call<{ sessions: RuntimeSession[] }>("native.session.list", { projectPaths })- .catch(() => ({ sessions: [] }))- : Promise.resolve({ sessions: [] }),- capabilityPromise,+ const [projectPaths, result, { providers, defaults }] = await Promise.all([+ localNativeProjectPaths(host),+ host.call<{ sessions: RuntimeSession[] }>("session.list"),+ sessionCapabilityContext(),]);+ const native = sidecar+ ? await sidecar+ .call<{ sessions: RuntimeSession[] }>("native.session.list", { projectPaths })+ .catch(() => ({ sessions: [] as RuntimeSession[] }))+ : { sessions: [] as RuntimeSession[] };return {...result,sessions: [diff --git a/apps/desktop/electron/main/live-voice/live-work-backend-port.ts b/apps/desktop/electron/main/live-voice/live-work-backend-port.tsindex d7b49d36d..0d8944083 100644--- a/apps/desktop/electron/main/live-voice/live-work-backend-port.ts+++ b/apps/desktop/electron/main/live-voice/live-work-backend-port.ts@@ -56,16 +56,14 @@ export async function listLiveWorkSessions(input: {if (!host) throw Object.assign(new Error("Local Host is unavailable"), { errorCode: "LIVE_WORK_NOT_READY" });const sidecar = input.getSidecar();const remoteHosts = input.getRemoteHosts();- const projectPathsPromise = localNativeProjectPaths(host);- const desktopPromise = host.call<{ sessions?: Array<Record<string, unknown>> }>("session.list");- const projectPaths = await projectPathsPromise;- const [desktopResult, nativeResult, remoteResult] = await Promise.all([- desktopPromise,- sidecar- ? sidecar.call<{ sessions?: Array<Record<string, unknown>> }>("native.session.list", { projectPaths })- : Promise.resolve({ sessions: [] as Array<Record<string, unknown>> }),+ const [projectPaths, desktopResult, remoteResult] = await Promise.all([+ localNativeProjectPaths(host),+ host.call<{ sessions?: Array<Record<string, unknown>> }>("session.list"),remoteHosts ? remoteHosts.listSessions() : Promise.resolve([]),]);+ const nativeResult = sidecar+ ? await sidecar.call<{ sessions?: Array<Record<string, unknown>> }>("native.session.list", { projectPaths })+ : { sessions: [] as Array<Record<string, unknown>> };const desktop: LiveWorkSessionRecord[] = (desktopResult.sessions ?? []).flatMap((session) => {if (typeof session.id !== "string" || !session.id.trim() || (session.source !== undefined && session.source !== "desktop")) return [];return [{diff --git a/apps/desktop/electron/main/services/session-search.ts b/apps/desktop/electron/main/services/session-search.tsindex c56ce3710..1f5110d3b 100644--- a/apps/desktop/electron/main/services/session-search.ts+++ b/apps/desktop/electron/main/services/session-search.ts@@ -28,7 +28,8 @@ export async function localNativeProjectPaths(host: NativeProjectHost): Promise<if (paths.length >= MAX_NATIVE_PROJECT_PATHS) break;}return paths;- } catch {+ } catch (error) {+ console.warn("[session-search] projects.list failed; native sessionDir discovery skipped", error);return [];}}diff --git a/apps/desktop/test/live-work-scope.test.mjs b/apps/desktop/test/live-work-scope.test.mjsindex 6bbd0d312..84077db96 100644--- a/apps/desktop/test/live-work-scope.test.mjs+++ b/apps/desktop/test/live-work-scope.test.mjs@@ -283,11 +283,28 @@ test("fresh live work catalog resolves Composer targets from all backends and re});t.after(() => server.close());const { listLiveWorkSessions, requireLiveWorkSession } = await server.ssrLoadModule("/electron/main/live-voice/live-work-backend-port.ts");+ const sidecarCalls = [];const sessions = await listLiveWorkSessions({- getHost: () => ({ call: async () => ({ sessions: [{ id: "desktop-1", source: "desktop", title: "Desktop", projectId: "project-1", projectPath: "/work/demo" }] }) }),- getSidecar: () => ({ call: async () => ({ sessions: [{ id: "native-pi:1", title: "Native", capabilities: { canPrompt: true } }] }) }),+ getHost: () => ({+ call: async (method) => {+ if (method === "projects.list") {+ return { projects: [{ path: "/work/demo" }, { path: " " }, { path: "remote-project:office" }] };+ }+ return { sessions: [{ id: "desktop-1", source: "desktop", title: "Desktop", projectId: "project-1", projectPath: "/work/demo" }] };+ },+ }),+ getSidecar: () => ({+ call: async (method, input) => {+ sidecarCalls.push({ method, input });+ return { sessions: [{ id: "native-pi:1", title: "Native", capabilities: { canPrompt: true } }] };+ },+ }),getRemoteHosts: () => ({ listSessions: async () => [{ id: "remote-1", title: "Remote", hostLabel: "Office", workspaceLabel: "repo", mode: "agent" }] }),});+ assert.deepEqual(sidecarCalls, [{+ method: "native.session.list",+ input: { projectPaths: ["/work/demo"] },+ }]);assert.equal(requireLiveWorkSession(sessions, "desktop-1").source, "desktop");assert.equal(requireLiveWorkSession(sessions, "desktop-1").projectId, "project-1");@@ -300,3 +317,48 @@ test("fresh live work catalog resolves Composer targets from all backends and re});assert.throws(() => requireLiveWorkSession(sessions, "missing"), { errorCode: "LIVE_WORK_SESSION_UNAVAILABLE" });});++test("live work attaches the desktop list before projects.list settles (#1732)", async (t) => {+ const server = await createServer({+ root: fileURLToPath(new URL("..", import.meta.url)),+ configFile: false,+ server: { middlewareMode: true, hmr: false, ws: false },+ appType: "custom",+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ t.after(() => server.close());+ const { listLiveWorkSessions } = await server.ssrLoadModule("/electron/main/live-voice/live-work-backend-port.ts");+ let releaseProjects;+ const projectsGate = new Promise((resolve) => {+ releaseProjects = resolve;+ });+ const rejections = [];+ const onRejection = (error) => {+ rejections.push(error);+ };+ process.on("unhandledRejection", onRejection);+ try {+ const pending = listLiveWorkSessions({+ getHost: () => ({+ call: async (method) => {+ if (method === "projects.list") return projectsGate;+ if (method === "session.list") throw new Error("session list failed");+ return {};+ },+ }),+ getSidecar: () => ({ call: async () => ({ sessions: [] }) }),+ getRemoteHosts: () => ({ listSessions: async () => [] }),+ }).then(+ () => "resolved",+ (error) => error,+ );+ await new Promise((resolve) => setTimeout(resolve, 30));+ assert.deepEqual(rejections.map((error) => error.message), []);+ releaseProjects({ projects: [] });+ const outcome = await pending;+ assert.equal(outcome instanceof Error, true);+ assert.match(outcome.message, /session list failed/);+ } finally {+ process.off("unhandledRejection", onRejection);+ }+});diff --git a/apps/desktop/test/native-pi-sessions.test.mjs b/apps/desktop/test/native-pi-sessions.test.mjsindex 6f6c3067a..a6af9c6d4 100644--- a/apps/desktop/test/native-pi-sessions.test.mjs+++ b/apps/desktop/test/native-pi-sessions.test.mjs@@ -332,6 +332,86 @@ test("session list forwards local project paths to native discovery (#1732)", asassert.deepEqual(hostCalls.map((call) => call.method), ["projects.list", "session.list"]);});+test("a failed projects.list keeps Desktop sessions and logs the skip (#1732)", async () => {+ const warnings = [];+ const original = console.warn;+ console.warn = (...args) => {+ warnings.push(args);+ };+ try {+ const { list, sidecarCalls } = forkHarness({+ host: () => ({+ call: async (method) => {+ if (method === "projects.list") throw new Error("index down");+ if (method === "session.list") {+ return { sessions: [{ id: "desktop-1", updatedAt: "2026-09-14T00:00:01.000Z" }] };+ }+ return {};+ },+ }),+ sidecar: (calls) => ({+ call: async (method, input) => {+ calls.push({ method, input });+ return { sessions: [] };+ },+ }),+ });+ const result = await list();+ assert.deepEqual(result.sessions.map((session) => session.id), ["desktop-1"]);+ assert.deepEqual(sidecarCalls, [{+ method: "native.session.list",+ input: { projectPaths: [] },+ }]);+ assert.ok(+ warnings.some((args) => String(args[0]).includes("projects.list failed")),+ "expected a projects.list warning",+ );+ } finally {+ console.warn = original;+ }+});++test("session list attaches host handlers before projects.list settles (#1732)", async () => {+ let releaseProjects;+ const projectsGate = new Promise((resolve) => {+ releaseProjects = resolve;+ });+ const rejections = [];+ const onRejection = (error) => {+ rejections.push(error);+ };+ process.on("unhandledRejection", onRejection);+ try {+ const { list } = forkHarness({+ host: () => ({+ call: async (method) => {+ if (method === "projects.list") return projectsGate;+ if (method === "session.list") throw new Error("session list failed");+ return {};+ },+ }),+ sidecar: (calls) => ({+ call: async (method, input) => {+ calls.push({ method, input });+ return { sessions: [] };+ },+ }),+ });+ const pending = list().then(+ () => "resolved",+ (error) => error,+ );+ await new Promise((resolve) => setTimeout(resolve, 30));+ assert.deepEqual(rejections.map((error) => error.message), []);+ releaseProjects({ projects: [] });+ const outcome = await pending;+ assert.equal(outcome instanceof Error, true);+ assert.match(outcome.message, /session list failed/);+ } finally {+ process.off("unhandledRejection", onRejection);+ }+});+test("native fork routes to the sidecar and never to the Desktop host", async () => {const { handle, hostCalls, sidecarCalls } = forkHarness({host: () => ({ call: () => { throw new Error("native fork must not call the host"); } }),diff --git a/docs/adr/0254-native-pi-session-continuation.md b/docs/adr/0254-native-pi-session-continuation.mdindex 6081c09d1..e2e3c5146 100644--- a/docs/adr/0254-native-pi-session-continuation.md+++ b/docs/adr/0254-native-pi-session-continuation.md@@ -102,8 +102,15 @@ addition to the default agent session root (`<agentDir>/sessions`).At most 500 local project paths are considered.- Custom directories are scanned non-recursively, matching Pi's flat `*.jsonl`layout. A file is admitted only when its real path stays inside the default- root or a resolved `sessionDir`. Symlink escapes are dropped.-- Detail, prompt, and fork use those same roots. A fork still publishes the- child beside its parent. Trust and provider gates are unchanged: a session- discovered through a project `.pi/settings.json` stays browseable and- read-only until that project is trusted.+ root or a resolved `sessionDir`. Symlink escapes are dropped. An in-directory+ symlink is not a second copy of its target. A nested file is omitted only+ when the custom directory is outside the default root; a directory inside+ that root is not scanned again, and the recursive default walk can still+ list nested JSONL there.+- Detail, prompt, and fork authorize the file against the default root, the+ session directories for the current project list, and any session directory+ that already admitted a file. A later empty project list does not revoke+ that directory. A fork still publishes the child beside its parent. Trust+ and provider gates are unchanged and follow the session header cwd, not+ which settings file pointed at the directory. Untrusted project resources+ stay browseable and read-only. Ancestor trust counts as trusted.diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 7b94f9a96..a08e06939 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -1820,9 +1820,16 @@ project's working directory, not from the Desktop process cwd. Remote projectids are skipped, and at most 500 local project paths are considered. Aconfigured directory whose real path is the default root, or is inside it, isnot scanned again. A file is listed only when its real path stays inside the-default root or one of those directories; a symlink that escapes, and a nested-file under a custom `sessionDir`, are omitted. Detail, prompt, and fork use the-same roots. A child fork is still published beside its parent. A project Desktop+default root or one of those directories. A symlink that escapes is omitted, and+an in-directory symlink alias of a session file is not a second row. A nested+file under a custom `sessionDir` is omitted when that directory is outside the+default root. A `sessionDir` inside the default root is not scanned again, and+the recursive default walk can still list nested JSONL there. Detail, prompt,+and fork authorize a file against the default root, the session directories for+the current project list, and any session directory that already admitted a+file in this process, so a later empty project list does not revoke an open of+a session that was already discovered. A child fork is still published beside+its parent. A project Desktophas not yet recorded does not contribute a relative `sessionDir`. An absoluteglobal `sessionDir` is scanned even when no project is known.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex e6f16dbab..5f92cdb2b 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -16717,7 +16717,8 @@ plugin-form fixtures in an isolated temporary directory at runtime.Untrusted project resources stay browseable and read-only.- **Specs:** runtime §12; storage §12; security §12; ADR 0254.- **Status:** Source-regression covered by- `packages/agent-runtime/src/native-pi-session.test.ts` and+ `packages/agent-runtime/src/native-pi-session.test.ts` (the project fixture+ asserts `readOnlyReason: project-untrusted` and `canPrompt: false`) and`apps/desktop/test/native-pi-sessions.test.mjs`; full Desktop journey Draft.### E2E-SUBAGENT-ordered-model-fallback-preserves-workdiff --git a/packages/agent-runtime/src/native-pi-session.test.ts b/packages/agent-runtime/src/native-pi-session.test.tsindex e5be00e52..11fe81ad0 100644--- a/packages/agent-runtime/src/native-pi-session.test.ts+++ b/packages/agent-runtime/src/native-pi-session.test.ts@@ -104,6 +104,8 @@ describe("NativePiSessionService", () => {const local = sessions.find((session) => session.title === "project local session");expect(local?.projectPath).toBe(f.project);+ expect(local?.readOnlyReason).toBe("project-untrusted");+ expect(local?.capabilities?.canPrompt).toBe(false);const detail = service.detail(local!.id);expect(detail?.messages.map((message) => message.content)).toEqual(["project local session"]);expect(readFileSync(join(customDir, "local.jsonl"), "utf8")).toBe(localText);@@ -143,6 +145,53 @@ describe("NativePiSessionService", () => {expect(sessions.map((session) => session.title)).toContain("relative global session");});+ it("lists one openable row when a custom sessionDir aliases a file inside itself (#1732)", async () => {+ const f = fixture();+ const customDir = join(f.project, ".pi", "sessions");+ mkdirSync(customDir, { recursive: true });+ writeFileSync(join(f.project, ".pi", "settings.json"), `${JSON.stringify({ sessionDir: ".pi/sessions" })}\n`);+ writeFileSync(join(customDir, "local.jsonl"), sessionText("local-id", f.project, "project local session"));+ symlinkSync(join(customDir, "local.jsonl"), join(customDir, "latest.jsonl"));+ const service = new NativePiSessionService({ agentDir: f.agentDir, sessionRoot: f.sessionRoot });+ const sessions = await service.list({ projectPaths: [f.project] });+ const matches = sessions.filter((session) => session.title === "project local session");+ expect(matches).toHaveLength(1);+ expect(new Set(matches.map((session) => session.id)).size).toBe(1);+ expect(service.detail(matches[0].id)?.messages.map((message) => message.content)).toEqual(["project local session"]);+ });++ it("opens a project sessionDir session after a later empty project list (#1732)", async () => {+ const f = fixture();+ const customDir = join(f.project, ".pi", "sessions");+ mkdirSync(customDir, { recursive: true });+ writeFileSync(join(f.project, ".pi", "settings.json"), `${JSON.stringify({ sessionDir: ".pi/sessions" })}\n`);+ writeFileSync(join(customDir, "local.jsonl"), sessionText("local-id", f.project, "project local session"));+ const service = new NativePiSessionService({ agentDir: f.agentDir, sessionRoot: f.sessionRoot });+ const listed = await service.list({ projectPaths: [f.project] });+ const local = listed.find((session) => session.title === "project local session");+ expect(local).toBeTruthy();+ const again = await service.list({ projectPaths: [] });+ expect(again.map((session) => session.title)).not.toContain("project local session");+ expect(service.detail(local!.id)?.messages.map((message) => message.content)).toEqual(["project local session"]);+ expect(service.fork({ id: local!.id }).messages.map((message) => message.content)).toContain("project local session");+ });++ it("logs an unreadable sessionDir settings file once per path and still lists the default root (#1732)", async () => {+ const f = fixture();+ writeFileSync(join(f.agentDir, "settings.json"), "{");+ mkdirSync(join(f.root, "other-project"));+ const warnings: unknown[][] = [];+ vi.spyOn(console, "warn").mockImplementation((...args: unknown[]) => {+ warnings.push(args);+ });+ const service = new NativePiSessionService({ agentDir: f.agentDir, sessionRoot: f.sessionRoot });+ const sessions = await service.list({ projectPaths: [f.project, join(f.root, "other-project")] });+ expect(sessions.map((session) => session.title)).toContain("hello");+ const settingsWarnings = warnings.filter((args) => String(args[0]).includes("sessionDir settings unreadable"));+ expect(settingsWarnings).toHaveLength(1);+ expect(String(settingsWarnings[0]?.[1])).toContain("settings.json");+ });+it("collapses copied session files onto one entry per native id (#1359)", async () => {const f = fixture();diff --git a/packages/agent-runtime/src/native-pi-session.ts b/packages/agent-runtime/src/native-pi-session.tsindex 73b5caebb..21d84c189 100644--- a/packages/agent-runtime/src/native-pi-session.ts+++ b/packages/agent-runtime/src/native-pi-session.ts@@ -108,23 +108,43 @@ function normalizeProjectPaths(paths: readonly string[] | undefined): string[] {return normalized;}-function rawSessionDir(cwd: string, agentDir: string): string | undefined {+function warnSessionDirErrors(+ cwd: string,+ errors: ReadonlyArray<{ path?: string; scope: string; error: unknown }>,+ seen: Set<string>,+): void {+ for (const entry of errors) {+ const key = entry.path ?? `${cwd}\0${entry.scope}`;+ if (seen.has(key)) continue;+ seen.add(key);+ console.warn("[native-pi] sessionDir settings unreadable", key, entry.error);+ }+}++function rawSessionDir(cwd: string, agentDir: string, seen: Set<string>): string | undefined {try {- return SettingsManager.create(cwd, agentDir).getSessionDir() || undefined;- } catch {+ const manager = SettingsManager.create(cwd, agentDir);+ warnSessionDirErrors(cwd, manager.drainErrors(), seen);+ return manager.getSessionDir() || undefined;+ } catch (error) {+ const key = `throw\0${cwd}\0${agentDir}`;+ if (!seen.has(key)) {+ seen.add(key);+ console.warn("[native-pi] sessionDir resolution failed", cwd, error);+ }return undefined;}}/** Absolute `sessionDir` from global settings. Relative values stay project-scoped. */-function globalAbsoluteSessionDir(agentDir: string): string | undefined {- const raw = rawSessionDir(agentDir, agentDir);+function globalAbsoluteSessionDir(agentDir: string, seen: Set<string>): string | undefined {+ const raw = rawSessionDir(agentDir, agentDir, seen);return raw && isAbsolute(raw) ? resolve(raw) : undefined;}/** Pi resolves a relative `sessionDir` from the project working directory. */-function projectSessionDir(projectPath: string, agentDir: string): string | undefined {- const raw = rawSessionDir(projectPath, agentDir);+function projectSessionDir(projectPath: string, agentDir: string, seen: Set<string>): string | undefined {+ const raw = rawSessionDir(projectPath, agentDir, seen);if (!raw) return undefined;return isAbsolute(raw) ? resolve(raw) : resolve(projectPath, raw);}@@ -134,8 +154,8 @@ function topLevelJsonl(dir: string): string[] {try {const files: string[] = [];for (const entry of readdirSync(dir, { withFileTypes: true })) {- if (entry.isDirectory()) continue;- if (entry.name.endsWith(".jsonl")) files.push(join(dir, entry.name));+ // `isFile()` is false for a symlink, same as the default-root walk.+ if (entry.isFile() && entry.name.endsWith(".jsonl")) files.push(join(dir, entry.name));}return files;} catch {@@ -519,6 +539,8 @@ export class NativePiSessionService {private modelRuntime?: ModelRuntime;private readonly modelRuntimeFactory: () => Promise<ModelRuntime>;private projectPaths: string[] = [];+ /** Real directories that already admitted a file. Open and fork keep them after a later empty project list. */+ private readonly admittedRoots: string[] = [];constructor(options: {agentDir?: string;@@ -541,6 +563,7 @@ export class NativePiSessionService {private configuredSessionDirs(): string[] {const dirs: string[] = [];const seen = new Set<string>();+ const settingsErrors = new Set<string>();const add = (dir: string | undefined) => {if (!dir) return;const resolved = resolve(dir);@@ -548,8 +571,8 @@ export class NativePiSessionService {seen.add(resolved);dirs.push(resolved);};- add(globalAbsoluteSessionDir(this.agentDir));- for (const projectPath of this.projectPaths) add(projectSessionDir(projectPath, this.agentDir));+ add(globalAbsoluteSessionDir(this.agentDir, settingsErrors));+ for (const projectPath of this.projectPaths) add(projectSessionDir(projectPath, this.agentDir, settingsErrors));return dirs;}@@ -565,6 +588,7 @@ export class NativePiSessionService {};add(this.root);for (const dir of this.configuredSessionDirs()) add(dir);+ for (const dir of this.admittedRoots) add(dir);return roots;}@@ -588,6 +612,9 @@ export class NativePiSessionService {}if (!defaultRoot && extraRoots.length === 0) return [];const allowed = [...(defaultRoot ? [defaultRoot] : []), ...extraRoots];+ for (const root of allowed) {+ if (!this.admittedRoots.includes(root)) this.admittedRoots.push(root);+ }const seenCandidates = new Set<string>();const candidates = [...(defaultRoot ? walkJsonl(defaultRoot) : []),@@ -692,13 +719,20 @@ export class NativePiSessionService {const record = this.records.get(summary.id);if (!record) continue;if (seenNativeIds.has(record.nativeId)) {- this.records.delete(summary.id);+ // Two directory names can resolve to one file and share this id.+ // Deleting it would drop the winner while both rows stay listed.+ if (!winnerIds.has(summary.id)) this.records.delete(summary.id);continue;}seenNativeIds.add(record.nativeId);winnerIds.add(summary.id);}- deduped.push(...summaries.filter((summary) => summary && winnerIds.has(summary.id)));+ const emittedIds = new Set<string>();+ deduped.push(...summaries.filter((summary) => {+ if (!summary || !winnerIds.has(summary.id) || emittedIds.has(summary.id)) return false;+ emittedIds.add(summary.id);+ return true;+ }));return deduped.filter((session): session is SessionSummary => Boolean(session)).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));