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(sessions): share pending creation across first inputs
Linuxdazhao86fe1e5db5a2
diff --git a/apps/desktop/src/lib/remote-project-session.ts b/apps/desktop/src/lib/remote-project-session.tsindex 27dd63bb1..24b0a1a11 100644--- a/apps/desktop/src/lib/remote-project-session.ts+++ b/apps/desktop/src/lib/remote-project-session.ts@@ -22,7 +22,7 @@ export async function openRemoteProjectSession(): Promise<void> {const scope = `remote-project:${JSON.stringify([project.hostKey, project.projectId])}`;const pending = runtime.pendingNewSessionRequests.get(scope);- if (pending) return pending;+ if (pending) { await pending; return; }const intent = runtime.beginNavigationIntent();const request = (async () => {const state = get();@@ -39,7 +39,7 @@ export async function openRemoteProjectSession(// RACP list summaries do not publish a durable message count. Read the// actual bounded history before treating a cold catalog row as empty.const detail = await api.getSession(latest.id);- if (!runtime.navigationIntentIsCurrent(intent)) return;+ if (!runtime.navigationIntentIsCurrent(intent)) return null;const current = get();const candidate = current.sessions.find((session) => session.id === latest.id);if (candidate && !sessionIsArchived(candidate.id, current.sessionMeta)@@ -49,7 +49,7 @@ export async function openRemoteProjectSession(submitted: runtime.submittedComposerDrafts.has(latest.id),})) {await get().selectSession(latest.id, { navigationIntent: intent });- return;+ return runtime.navigationIntentIsCurrent(intent) ? latest.id : null;}}const result = await api.createRemoteSession({ hostKey: project.hostKey,@@ -57,8 +57,9 @@ export async function openRemoteProjectSession(const session = safeSessionSummary(result.session);// Preserve a successful creation even if the user navigated away while it ran.set((current) => ({ sessions: [session, ...current.sessions.filter((item) => item.id !== session.id)] }));- if (!runtime.navigationIntentIsCurrent(intent)) return;+ if (!runtime.navigationIntentIsCurrent(intent)) return null;await get().selectSession(session.id, { navigationIntent: intent });+ return runtime.navigationIntentIsCurrent(intent) ? session.id : null;})();runtime.pendingNewSessionRequests.set(scope, request);try { await request; }diff --git a/apps/desktop/src/stores/runtime/session-coordination.ts b/apps/desktop/src/stores/runtime/session-coordination.tsindex c79d263fd..015386573 100644--- a/apps/desktop/src/stores/runtime/session-coordination.ts+++ b/apps/desktop/src/stores/runtime/session-coordination.ts@@ -349,11 +349,17 @@ export function createSessionCoordination({const scopeKey = runtime.newSessionScopeKey(state.workspace?.path ?? null);const pending = runtime.pendingNewSessionRequests.get(scopeKey);if (pending) {- await pending;- const activeId = get().activeSessionId;- if (activeId) return activeId;+ return await pending;+ }+ const request = persistSessionAndSelect({ intent });+ runtime.pendingNewSessionRequests.set(scopeKey, request);+ try {+ return await request;+ } finally {+ if (runtime.pendingNewSessionRequests.get(scopeKey) === request) {+ runtime.pendingNewSessionRequests.delete(scopeKey);+ }}- return persistSessionAndSelect({ intent });}return {diff --git a/apps/desktop/src/stores/runtime/session-runtime.ts b/apps/desktop/src/stores/runtime/session-runtime.tsindex b879617d9..a7e541ab4 100644--- a/apps/desktop/src/stores/runtime/session-runtime.ts+++ b/apps/desktop/src/stores/runtime/session-runtime.ts@@ -48,7 +48,7 @@ export type SessionConfiguration = Pick<export type SessionSelection = { id: string; intent: number };export type SessionRuntime = {- readonly pendingNewSessionRequests: Map<string, Promise<void>>;+ readonly pendingNewSessionRequests: Map<string, Promise<string | null>>;readonly sessionTranscriptCache: Map<string, UiMessage[]>;readonly liveSessionTranscripts: Set<string>;readonly sessionHistoryCache: Map<string, SessionHistoryWindow>;@@ -126,7 +126,7 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntimelet pendingSessionSelection: SessionSelection | null = null;let sessionWorkspaceQueue: Promise<unknown> = Promise.resolve();- const pendingNewSessionRequests = new Map<string, Promise<void>>();+ const pendingNewSessionRequests = new Map<string, Promise<string | null>>();const sessionTranscriptCache = new Map<string, UiMessage[]>();const liveSessionTranscripts = new Set<string>();const sessionHistoryCache = new Map<string, SessionHistoryWindow>();diff --git a/apps/desktop/src/stores/slices/queue-slice.ts b/apps/desktop/src/stores/slices/queue-slice.tsindex f602b0ea1..aea3b8d1d 100644--- a/apps/desktop/src/stores/slices/queue-slice.ts+++ b/apps/desktop/src/stores/slices/queue-slice.ts@@ -371,8 +371,7 @@ export function createQueueSlice({return false;}if (!sessionId) {- const intent = runtime.beginNavigationIntent();- const createdId = await materializeDraftSession(intent);+ const createdId = await materializeDraftSession();if (!createdId) return false;sessionId = createdId;const key = `session:${createdId}`;diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.tsindex eaeef6821..86b79529c 100644--- a/apps/desktop/src/stores/slices/session-slice.ts+++ b/apps/desktop/src/stores/slices/session-slice.ts@@ -687,12 +687,12 @@ export function createSessionSlice({const workspace = await get().activateProject(requestedProjectPath, {navigationIntent: intent,});- if (!runtime.navigationIntentIsCurrent(intent)) return;+ if (!runtime.navigationIntentIsCurrent(intent)) return null;if (!workspace) throw new Error(i18n.t("errors.workspaceActivationFailed"));}if (requestedProjectPath === null && get().workspace) {await get().clearProject({ navigationIntent: intent });- if (!runtime.navigationIntentIsCurrent(intent)) return;+ if (!runtime.navigationIntentIsCurrent(intent)) return null;}const latest = runtime.latestSessionInScope(@@ -709,12 +709,12 @@ export function createSessionSlice({submitted: runtime.submittedComposerDrafts.has(latest.id),})) {- if (get().activeSessionId === latest.id && get().page === "chat") return;+ if (get().activeSessionId === latest.id && get().page === "chat") return latest.id;await get().selectSession(latest.id, { navigationIntent: intent });- return;+ return runtime.navigationIntentIsCurrent(intent) ? latest.id : null;}- await persistSessionAndSelect({+ return await persistSessionAndSelect({intent,projectPath: requestedProjectPath,draftConfiguration: null,diff --git a/apps/desktop/test/session-draft-materialization.test.mjs b/apps/desktop/test/session-draft-materialization.test.mjsnew file mode 100644index 000000000..801e55c0c--- /dev/null+++ b/apps/desktop/test/session-draft-materialization.test.mjs@@ -0,0 +1,112 @@+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { api } = await import("../src/lib/api.ts");+const { createSessionRuntime } = await import("../src/stores/runtime/session-runtime.ts");+const { createSessionCoordination } = await import("../src/stores/runtime/session-coordination.ts");+const { createSessionSlice } = await import("../src/stores/slices/session-slice.ts");+const { createQueueSlice } = await import("../src/stores/slices/queue-slice.ts");++function fixture(t) {+ const gate = Promise.withResolvers();+ let created = 0;+ let state = {+ activeSessionId: undefined, page: "chat", sessions: [], messages: [],+ sessionMeta: {}, pendingPlans: {}, planCheckpoints: {}, planningStates: {},+ runningSessions: {}, agentStatuses: {}, latestTurnResults: {}, sessionOutcomes: {},+ sessionCompactions: {}, sessionHistory: {}, retainedSessionIds: [], retainedTranscripts: {},+ workPanelContexts: {}, workPanelTabs: [], activeWorkPanelTabId: null,+ workPanelOpen: false, workPanelFileRequest: null, navStack: [], navIndex: -1,+ settings: {}, providers: [], providerModels: {}, recentModels: [], draftConfiguration: null,+ workspace: { path: "/synthetic/project" }, activeProjectPath: "/synthetic/project",+ defaultProjectPath: "/synthetic/project", queuedPrompts: {},+ refreshSessions: async () => {}, rememberModel: () => {}, showToast: () => {},+ };+ const get = () => state;+ const set = update => { state = { ...state, ...(typeof update === "function" ? update(state) : update) }; };+ const runtime = createSessionRuntime({ get, set });+ const withoutRecordKey = (record, key) => { const result = { ...record }; delete result[key]; return result; };+ t.mock.method(api, "createSession", async () => {+ const id = `created-${++created}`;+ await gate.promise;+ return { session: { id, title: "New task", mode: "agent", messageCount: 0,+ projectPath: "/synthetic/project", updatedAt: "2026-11-02T00:00:00Z" } };+ });+ t.mock.method(api, "prompt", async () => ({}));+ t.mock.method(api, "deriveSessionTitle", async () => ({ updated: false }));+ const coordination = createSessionCoordination({+ get, set, runtime, decorateSessions: rows => rows, withoutRecordKey,+ untitledTaskTitle: () => "New task",+ });+ Object.assign(state, createSessionSlice({+ get, set, runtime, decorateSessions: rows => rows, withoutRecordKey,+ ...coordination, getBootstrapGeneration: () => 0,+ }));+ Object.assign(state, createQueueSlice({+ get, set, runtime, materializeDraftSession: coordination.materializeDraftSession,+ recordSubmittedInput: async () => {}, insertOptimisticUserMessage: runtime.insertOptimisticUserMessage,+ retractOptimisticUserMessage: runtime.retractOptimisticUserMessage,+ promptAttachmentsFromDraft: () => [], withoutRecordKey,+ sessionTranscriptCache: runtime.sessionTranscriptCache,+ submittedComposerDrafts: runtime.submittedComposerDrafts,+ viewingSessionIdForPrompt: () => null,+ messageErrorFromUnknown: error => ({ code: "FAILED", message: error.message }),+ assistantErrorMessage: error => ({ id: "error", role: "assistant", content: "", error }),+ }));+ return { get, set, runtime, coordination, gate, created: () => created };+}++test("first prompt during New Task creation uses the same durable row", async t => {+ const f = fixture(t);+ const creation = f.get().newSession({ projectPath: "/synthetic/project" });+ const sending = f.get().sendPrompt("Synthetic first prompt");+ f.gate.resolve();+ await creation;+ assert.equal(await sending, true);+ assert.equal(f.created(), 1, "sending must not invalidate and replace the pending New Task");+ assert.deepEqual(f.get().sessions.map(session => session.id), ["created-1"]);+ assert.equal(f.get().activeSessionId, "created-1");+ assert.equal(f.runtime.pendingNewSessionRequests.size, 0);+});++test("overlapping first inputs share one creation result", async t => {+ const f = fixture(t);+ const first = f.coordination.materializeDraftSession();+ const second = f.coordination.materializeDraftSession();+ f.gate.resolve();+ assert.deepEqual(await Promise.all([first, second]), ["created-1", "created-1"]);+ assert.equal(f.created(), 1);+ assert.equal(f.get().sessions.length, 1);+ assert.equal(f.runtime.pendingNewSessionRequests.size, 0);+});++test("superseded creation never targets a different selected session", async t => {+ const f = fixture(t);+ const creation = f.get().newSession({ projectPath: "/synthetic/project" });+ const input = f.coordination.materializeDraftSession();+ f.runtime.beginNavigationIntent();+ f.set({ activeSessionId: "unrelated-session" });+ f.gate.resolve();+ await creation;+ assert.equal(await input, null);+ assert.equal(f.created(), 1);+ assert.equal(f.get().activeSessionId, "unrelated-session");+});++test("failed creation rejects all waiters and releases the slot for retry", async t => {+ const f = fixture(t);+ const first = f.coordination.materializeDraftSession();+ const second = f.coordination.materializeDraftSession();+ const settled = Promise.allSettled([first, second]);+ f.gate.reject(new Error("synthetic creation failure"));+ const results = await settled;+ assert.ok(results.every(result => result.status === "rejected"));+ assert.equal(f.runtime.pendingNewSessionRequests.size, 0);+ t.mock.method(api, "createSession", async () => ({ session: {+ id: "retry", title: "New task", mode: "agent", messageCount: 0,+ projectPath: "/synthetic/project", updatedAt: "2026-11-02T00:00:00Z",+ } }));+ assert.equal(await f.coordination.materializeDraftSession(), "retry");+});diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex 7a75caa64..1a4d6ac18 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -363,6 +363,10 @@ may be retained while exactly one workspace supplies the visible shell context.transcript on the same frame rather than waiting for `session.get`. Thedurable row is inserted from the `session.create` summary; send and paste waitfor that in-flight create instead of opening a second slot (ADR 0154).+ Concurrent first-input materializations share the same project-scoped+ creation result, including cancellation and failure. A first send does not+ supersede an in-flight New Task's navigation intent or adopt an unrelated+ session selected while waiting. A failed create releases the slot for retry.- A first-opened session settles at its newest turn. A revisited pane returns tothe offset the user left, and a pane still pinned re-anchors to the bottom;activation no longer resets manual-scroll state for a revisit (ADR 0137).diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 5adefab0a..75a61bcca 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -2815,18 +2815,22 @@ identify the platform validation still needed.- **Steps**: 1) Click New Task (sidebar, top bar, or Cmd/Ctrl+N). 2) Observethe chat surface on the next frame, before the new sidebar row is requiredto exist. 3) Type in the composer during that interval. 4) Wait for the new- row and send.+ row and send. Also send while creation is still pending, and overlap two+ first-input materialization requests with the host response delayed.- **Expected**: A's transcript is gone on the first frame (empty home, idleSend). The composer does not stay on A's draft. After `session.create` thesame empty session is selected, any text typed during the wait belongs tothat session, and sending does not create a second row. Repeating New Taskbefore sending reuses the row. The host is not asked to `session.list` or- `session.get` before the empty destination is visible.+ `session.get` before the empty destination is visible. Overlapping inputs+ share one creation and its session id; the first send does not invalidate+ New Task navigation. Superseded creation returns no target to waiting inputs,+ and a failed create releases the slot so retry can succeed.- **Specs linked**: `04-ux/09-interaction-patterns.md` (§1.6),`04-ux/08-component-spec.md` (§11), ADR 0154- **Acceptance**: C (session creation), Quality- **Milestone**: M2-- **Status**: Source-level regression covered (`session-create.test.mjs`,+- **Status**: Source-level regression covered (`session-draft-materialization.test.mjs`, `session-create.test.mjs`,`session-switch-performance.test.mjs`); full UI scenario Draft