Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): New Terminal Window loses its project mid-load (PRD-8275) (#3852)
Andrew Mikofalvy6b7bc5769c83
diff --git a/.changeset/new-terminal-window-during-load.md b/.changeset/new-terminal-window-during-load.mdnew file mode 100644index 000000000..e7efc36a3--- /dev/null+++ b/.changeset/new-terminal-window-during-load.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Terminal → New Terminal Window now inherits the project even when the window it was invoked from is still loading. The menu bar is live from the moment a window opens, but the app only recorded which project a window belonged to once that window's editor had finished loading. Invoking the command inside that gap resolved no project at all, so the new terminal opened silently in your home directory with no connection to the project you were looking at. The same gap also affected single-file windows and windows attached to an already-running server. A window is now associated with its project from the moment it is created, so the command resolves the same project throughout.diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex dc0a227f1..b491fe082 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -1032,6 +1032,28 @@ export class WindowManager {*/private readonly windowsByPath = new Map<string, ProjectContext>();+ /**+ * BrowserWindow → its ProjectContext for windows still loading their+ * renderer. Read only through `getContextForBrowserWindow`.+ *+ * `windowsByPath` is authoritative but its entry lands only AFTER+ * `await loadFile` resolves, whereas the window — and the application menu+ * acting on it — exists from the moment `createWindow` returns. Every field+ * of the context is known before that call, so for the whole renderer load+ * this class owned a project window it would not admit to owning, and+ * anything asking "which project is this window's?" got `undefined`.+ *+ * The user-visible cost was Terminal → New Terminal Window during load:+ * `resolveTerminalWindowProject` saw no editor context and opened a+ * project-less HOME-cwd window with an empty collab URL, silently.+ *+ * Deliberately keyed by window rather than project: this answers the+ * window→project question only, and must not widen `windowsByPath`'s+ * meaning (a completed, dedupable, restorable window) to include windows+ * that may still fail to load.+ */+ private readonly loadingContextByWindow = new Map<BrowserWindowLike, ProjectContext>();+/*** canonicalKey → pid of the detached server THIS desktop process spawned* during its lifetime. Survives window closes within the same desktop run@@ -1189,12 +1211,47 @@ export class WindowManager {* map) instead of going through `appState.recentProjects`, which avoids a* stale-state race between `createProjectWindow` resolving and* `addRecentProject` persisting.+ *+ * Falls back to `loadingContextByWindow` so a window whose renderer is still+ * loading resolves too — see that field for why the authoritative map cannot+ * answer during that span. Both maps hold the SAME context object, so callers+ * cannot tell which one answered.+ *+ * Still returns `undefined` for a window mid-`restartAttachedServer`: that+ * path deliberately detaches the originating window from `windowsByPath`, and+ * its context carries the terminated server's `port`/`apiOrigin`. Tracked+ * separately; do not read this function as covering it.*/getContextForBrowserWindow(win: BrowserWindowLike): ProjectContext | undefined {for (const ctx of this.windowsByPath.values()) {if (ctx.window === win) return ctx;}- return undefined;+ // Still loading its renderer — same context object the completed entry+ // will hold, so callers cannot tell the two apart (and must not).+ return this.loadingContextByWindow.get(win);+ }++ /**+ * Publish a freshly-created window's context until its authoritative+ * `windowsByPath` entry lands, and hand back the release.+ *+ * The bracket MUST enclose `windowsByPath.set`, NOT just the load. A+ * `finally` wrapped around only the `await` releases the moment the load+ * settles — before the authoritative entry exists — which reopens the exact+ * window this map was added to close, in the one function that implements the+ * fix. Bracket the whole span: publish, load, `set`, release.+ *+ * Releasing after `set` is safe because both maps hold the SAME object and+ * `getContextForBrowserWindow` reads `windowsByPath` first, so the overlap is+ * invisible. Release is idempotent, so a path that must also release early+ * (the ephemeral reap, which stops a `destroy()`ed window resolving before it+ * awaits teardown) can do that and still keep the bracket as its backstop.+ */+ private publishLoadingContext(context: ProjectContext): () => void {+ this.loadingContextByWindow.set(context.window, context);+ return () => {+ this.loadingContextByWindow.delete(context.window);+ };}/**@@ -2249,32 +2306,6 @@ export class WindowManager {// emitted on timeout.const disposeShowGate = this.deps.showGate.register(window, { kind: 'editor' });- if (this.deps.rendererDevUrl) {- await window.loadURL(this.deps.rendererDevUrl);- } else {- await window.loadFile(this.deps.rendererEntryPath);- }- this.deps.startup?.markLoadUrlResolved?.();-- window.on('closed', () => {- // Drop any stale show-gate state — a window destroyed before either- // signal arrives must not hold a slot in the registry's Map.- disposeShowGate();- // Guard against detached IPC port — the utility may have already exited- // (e.g. crash, parent-death poll beat us) in which case `postMessage`- // throws ERR_IPC_CHANNEL_CLOSED. The utility's shutdown drain +- // parentLifecycleBound takes care of the forked process regardless;- // windowsByPath.delete fires from the utility's exit event above.- try {- utility.postMessage({ type: 'shutdown' });- } catch (err) {- this.deps.log?.warn(- { err, projectPath },- 'utility shutdown IPC failed on window close (likely already exited)',- );- }- });-const context: ProjectContext = {projectPath,canonicalKey,@@ -2285,7 +2316,38 @@ export class WindowManager {utility,ownsServer: true,};- this.windowsByPath.set(canonicalKey, context);+ const releaseLoadingContext = this.publishLoadingContext(context);+ try {+ if (this.deps.rendererDevUrl) {+ await window.loadURL(this.deps.rendererDevUrl);+ } else {+ await window.loadFile(this.deps.rendererEntryPath);+ }+ this.deps.startup?.markLoadUrlResolved?.();++ window.on('closed', () => {+ // Drop any stale show-gate state — a window destroyed before either+ // signal arrives must not hold a slot in the registry's Map.+ disposeShowGate();+ // Guard against detached IPC port — the utility may have already exited+ // (e.g. crash, parent-death poll beat us) in which case `postMessage`+ // throws ERR_IPC_CHANNEL_CLOSED. The utility's shutdown drain ++ // parentLifecycleBound takes care of the forked process regardless;+ // windowsByPath.delete fires from the utility's exit event above.+ try {+ utility.postMessage({ type: 'shutdown' });+ } catch (err) {+ this.deps.log?.warn(+ { err, projectPath },+ 'utility shutdown IPC failed on window close (likely already exited)',+ );+ }+ });++ this.windowsByPath.set(canonicalKey, context);+ } finally {+ releaseLoadingContext();+ }return context;}@@ -2541,28 +2603,6 @@ export class WindowManager {const disposeShowGate = this.deps.showGate.register(window, { kind: 'editor' });- try {- if (this.deps.rendererDevUrl) {- await window.loadURL(this.deps.rendererDevUrl);- } else {- await window.loadFile(this.deps.rendererEntryPath);- }- } catch (err) {- // Renderer load failed AFTER the server spawned + bound its lock. The- // window never reaches the `'closed'` teardown below (it isn't in- // `windowsByPath` yet), so reap here: drop the show gate, destroy the- // never-shown window, and terminate the detached server + remove its temp- // dir. Without this the server pid + `ok-ephemeral-*` temp dir orphan.- disposeShowGate();- window.destroy?.();- await this.teardownEphemeralSession({- projectDir: tempProjectDir,- pid: handle.pid,- lockDir,- });- throw err;- }-const context: ProjectContext = {projectPath: opts.contentDir,canonicalKey,@@ -2574,7 +2614,6 @@ export class WindowManager {ownsServer: false,ephemeral: { projectDir: tempProjectDir, pid: handle.pid, lockDir },};-// Exit-watch handle — shared by the `'closed'` handler (below) and the// liveness poll (further below). The spawner observes the child's `'exit'`// but exposes it only as a pull snapshot (`readExit`), not a push signal to@@ -2589,27 +2628,58 @@ export class WindowManager {if (watchHandle !== undefined) this.deps.clearInterval?.(watchHandle);};- window.on('closed', () => {- // Stop the liveness poll first — the session is going away under the normal- // teardown path; a straggling poll must not fire a second teardown.- stopExitWatch();- disposeShowGate();- // Ownership guard — only tear down if THIS window still owns the slot. A- // focus-dedup re-open or `stopAllOwnedServers` could have replaced/cleared- // the entry; without the guard we'd terminate a sibling's server or double- // free. (Double teardown is itself safe — ESRCH + force-rm — but the guard- // keeps the common path single-pass.)- if (this.windowsByPath.get(canonicalKey) !== context) return;- this.windowsByPath.delete(canonicalKey);- // Fire-and-forget: the `'closed'` event handler is synchronous. Terminate- // the server THEN remove the temp dir (sequential — see- // `teardownEphemeralSession`).- void this.teardownEphemeralSession(- context.ephemeral as NonNullable<ProjectContext['ephemeral']>,- );- });+ const releaseLoadingContext = this.publishLoadingContext(context);++ try {+ try {+ if (this.deps.rendererDevUrl) {+ await window.loadURL(this.deps.rendererDevUrl);+ } else {+ await window.loadFile(this.deps.rendererEntryPath);+ }+ } catch (err) {+ // Stop a window we are about to `destroy()` from resolving to a project+ // before the awaited teardown below; the outer bracket is the backstop.+ releaseLoadingContext();+ // Renderer load failed AFTER the server spawned + bound its lock. The+ // window never reaches the `'closed'` teardown below (it isn't in+ // `windowsByPath` yet), so reap here: drop the show gate, destroy the+ // never-shown window, and terminate the detached server + remove its temp+ // dir. Without this the server pid + `ok-ephemeral-*` temp dir orphan.+ disposeShowGate();+ window.destroy?.();+ await this.teardownEphemeralSession({+ projectDir: tempProjectDir,+ pid: handle.pid,+ lockDir,+ });+ throw err;+ }++ window.on('closed', () => {+ // Stop the liveness poll first — the session is going away under the normal+ // teardown path; a straggling poll must not fire a second teardown.+ stopExitWatch();+ disposeShowGate();+ // Ownership guard — only tear down if THIS window still owns the slot. A+ // focus-dedup re-open or `stopAllOwnedServers` could have replaced/cleared+ // the entry; without the guard we'd terminate a sibling's server or double+ // free. (Double teardown is itself safe — ESRCH + force-rm — but the guard+ // keeps the common path single-pass.)+ if (this.windowsByPath.get(canonicalKey) !== context) return;+ this.windowsByPath.delete(canonicalKey);+ // Fire-and-forget: the `'closed'` event handler is synchronous. Terminate+ // the server THEN remove the temp dir (sequential — see+ // `teardownEphemeralSession`).+ void this.teardownEphemeralSession(+ context.ephemeral as NonNullable<ProjectContext['ephemeral']>,+ );+ });- this.windowsByPath.set(canonicalKey, context);+ this.windowsByPath.set(canonicalKey, context);+ } finally {+ releaseLoadingContext();+ }// Exit-watch: proactively notice a detached server that dies while its window// is still open (kill / crash / idle-shutdown) and reap its throwaway temp@@ -3263,56 +3333,6 @@ export class WindowManager {// on a fast load.const disposeShowGate = this.deps.showGate.register(window, { kind: 'editor' });- if (this.deps.rendererDevUrl) {- await window.loadURL(this.deps.rendererDevUrl);- } else {- await window.loadFile(this.deps.rendererEntryPath);- }- this.deps.startup?.markLoadUrlResolved?.();-- // Open the keepalive WS as soon as the project window mounts. The WS- // counts toward the server's idle-shutdown WS-client tally so a brief- // MCP disconnect (the agent restarts, the IDE reloads its MCP shim,- // etc.) does not trigger idle-shutdown while the user has a project- // window open. Presence-invisibility is enforced by the wired- // `createKeepalive` (which omits `displayName`/`clientName`/- // `colorSeed`); the dep contract documents this constraint.- if (this.deps.createKeepalive) {- const existingKeepalive = this.keepalives.get(canonicalKey);- // Defensive idempotence — a second window for the same project (e.g.- // a deep-link re-open while the previous one is mid-teardown) would- // race the close handler. Drop the old handle before opening a new- // one so we never leak.- if (existingKeepalive) existingKeepalive.close();- const lockDir = getLocalDir(projectPath);- const handle = this.deps.createKeepalive({ lockDir });- this.keepalives.set(canonicalKey, handle);- }-- window.on('closed', () => {- // Drop any stale show-gate state — a window destroyed before either- // signal arrives must not hold a slot in the registry's Map.- disposeShowGate();- // Only release the project's slot if THIS window still owns it. A- // server-restart recreate detaches the originating window from the map- // and replaces it under the same `canonicalKey` before closing the old- // one — without this guard the old window's `'closed'` would delete the- // new window's entry (and its keepalive).- if (this.windowsByPath.get(canonicalKey) !== context) return;- // Close the project's keepalive WS so the server's idle-shutdown- // counter can fall back to whatever MCP clients (if any) are still- // connected. No-op when no keepalive was opened (back-compat tests).- const keepalive = this.keepalives.get(canonicalKey);- if (keepalive) {- keepalive.close();- this.keepalives.delete(canonicalKey);- }- // Drop from our map so a subsequent open either re-attaches (if the- // sibling is still live) or spawns (if it has since exited). Critically,- // NO shutdown IPC — the server is not ours to stop.- this.windowsByPath.delete(canonicalKey);- });-const context: ProjectContext = {projectPath,canonicalKey,@@ -3323,7 +3343,62 @@ export class WindowManager {utility: null,ownsServer: false,};- this.windowsByPath.set(canonicalKey, context);+ const releaseLoadingContext = this.publishLoadingContext(context);+ try {+ if (this.deps.rendererDevUrl) {+ await window.loadURL(this.deps.rendererDevUrl);+ } else {+ await window.loadFile(this.deps.rendererEntryPath);+ }+ this.deps.startup?.markLoadUrlResolved?.();++ // Open the keepalive WS as soon as the project window mounts. The WS+ // counts toward the server's idle-shutdown WS-client tally so a brief+ // MCP disconnect (the agent restarts, the IDE reloads its MCP shim,+ // etc.) does not trigger idle-shutdown while the user has a project+ // window open. Presence-invisibility is enforced by the wired+ // `createKeepalive` (which omits `displayName`/`clientName`/+ // `colorSeed`); the dep contract documents this constraint.+ if (this.deps.createKeepalive) {+ const existingKeepalive = this.keepalives.get(canonicalKey);+ // Defensive idempotence — a second window for the same project (e.g.+ // a deep-link re-open while the previous one is mid-teardown) would+ // race the close handler. Drop the old handle before opening a new+ // one so we never leak.+ if (existingKeepalive) existingKeepalive.close();+ const lockDir = getLocalDir(projectPath);+ const handle = this.deps.createKeepalive({ lockDir });+ this.keepalives.set(canonicalKey, handle);+ }++ window.on('closed', () => {+ // Drop any stale show-gate state — a window destroyed before either+ // signal arrives must not hold a slot in the registry's Map.+ disposeShowGate();+ // Only release the project's slot if THIS window still owns it. A+ // server-restart recreate detaches the originating window from the map+ // and replaces it under the same `canonicalKey` before closing the old+ // one — without this guard the old window's `'closed'` would delete the+ // new window's entry (and its keepalive).+ if (this.windowsByPath.get(canonicalKey) !== context) return;+ // Close the project's keepalive WS so the server's idle-shutdown+ // counter can fall back to whatever MCP clients (if any) are still+ // connected. No-op when no keepalive was opened (back-compat tests).+ const keepalive = this.keepalives.get(canonicalKey);+ if (keepalive) {+ keepalive.close();+ this.keepalives.delete(canonicalKey);+ }+ // Drop from our map so a subsequent open either re-attaches (if the+ // sibling is still live) or spawns (if it has since exited). Critically,+ // NO shutdown IPC — the server is not ours to stop.+ this.windowsByPath.delete(canonicalKey);+ });++ this.windowsByPath.set(canonicalKey, context);+ } finally {+ releaseLoadingContext();+ }return context;}}diff --git a/packages/desktop/tests/main/window-manager-ephemeral.test.ts b/packages/desktop/tests/main/window-manager-ephemeral.test.tsindex b4bb7bbce..35ff9a2a2 100644--- a/packages/desktop/tests/main/window-manager-ephemeral.test.ts+++ b/packages/desktop/tests/main/window-manager-ephemeral.test.ts@@ -465,6 +465,46 @@ describe('createEphemeralWindow', () => {expect(env.windows[0]?.destroy).toHaveBeenCalled();// It was never registered, so no later 'closed' teardown can double-fire.expect(env.killCalls.filter((k) => k.signal === 'SIGTERM')).toHaveLength(1);+ // ...and it stops resolving to a project: the reap released the loading+ // context, so nothing hands New Terminal Window a destroyed window.+ const failed = env.windows[0];+ if (!failed) throw new Error('window was never created');+ expect(wm.getContextForBrowserWindow(failed)).toBeUndefined();+ });++ test('an ephemeral window resolves to its content dir while its renderer loads', async () => {+ // The ephemeral factory carries the same gap as the project factory, and its+ // window is an ordinary editor window as far as New Terminal Window cares.+ let releaseLoad: (() => void) | undefined;+ env.deps.createWindow = (opts) => {+ env.createWindowOpts.push(opts);+ const w = makeWindow();+ w.loadFile = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ releaseLoad = resolve;+ }),+ ) as typeof w.loadFile;+ env.windows.push(w);+ return w;+ };++ const wm = new WindowManager(env.deps);+ const pending = wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ await vi.waitFor(() => {+ expect(releaseLoad).toBeDefined();+ });++ const loading = env.windows[0];+ if (!loading) throw new Error('window was never created');+ expect(wm.getContextForBrowserWindow(loading)?.projectPath).toBe(PARENT);++ releaseLoad?.();+ expect(wm.getContextForBrowserWindow(loading)).toBe(await pending);});test("the 'closed' ownership guard makes teardown single-pass", async () => {diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.tsindex b25608142..2fd3dbe0f 100644--- a/packages/desktop/tests/main/window-manager.test.ts+++ b/packages/desktop/tests/main/window-manager.test.ts@@ -646,6 +646,82 @@ describe('WindowManager', () => {expect(wm.getContextForBrowserWindow(stranger)).toBeUndefined();});+ test('getContextForBrowserWindow resolves a window whose renderer is still loading', async () => {+ // The window exists — and its application menu is live — from the moment+ // `createWindow` returns, but the `windowsByPath` entry lands only once+ // `loadFile` resolves. Anything that asks "which project owns this window"+ // inside that gap used to be told "none", so Terminal -> New Terminal Window+ // opened a HOME-cwd window with an empty collab URL instead of inheriting the+ // project. Hold `loadFile` open and ask mid-load.+ let releaseLoad: (() => void) | undefined;+ env.deps.createWindow = (opts) => {+ env.createWindowOpts.push(opts);+ const w = makeWindow();+ w.loadFile = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ releaseLoad = resolve;+ }),+ ) as typeof w.loadFile;+ env.windows.push(w);+ return w;+ };++ const wm = new WindowManager(env.deps);+ const pending = wm.createProjectWindow({ projectPath: '/tmp/ctx-mid-load' });+ env.utilities[0]?.fire({ type: 'ready', port: 52101, apiOrigin: 'http://localhost:52101' });+ // Let the spawn path run up to (and park on) `await loadFile`.+ await vi.waitFor(() => {+ expect(releaseLoad).toBeDefined();+ });++ const loading = env.windows[0];+ if (!loading) throw new Error('window was never created');+ const midLoad = wm.getContextForBrowserWindow(loading);+ expect(midLoad?.projectPath).toBe('/tmp/ctx-mid-load');+ expect(midLoad?.apiOrigin).toBe('http://localhost:52101');++ releaseLoad?.();+ const settled = await pending;+ // The same object once the load resolves, not a copy that could drift from+ // the authoritative entry.+ expect(wm.getContextForBrowserWindow(loading)).toBe(settled);+ });++ test('a window whose renderer load rejects stops resolving to a project', async () => {+ // The mid-load answer must not outlive a failed load: a window that never+ // came up owns nothing, and a stale entry would hand New Terminal Window a+ // project whose window is already gone.+ let rejectLoad: ((err: Error) => void) | undefined;+ env.deps.createWindow = (opts) => {+ env.createWindowOpts.push(opts);+ const w = makeWindow();+ w.loadFile = vi.fn(+ () =>+ new Promise<void>((_resolve, reject) => {+ rejectLoad = reject;+ }),+ ) as typeof w.loadFile;+ env.windows.push(w);+ return w;+ };++ const wm = new WindowManager(env.deps);+ const pending = wm.createProjectWindow({ projectPath: '/tmp/ctx-load-fails' });+ env.utilities[0]?.fire({ type: 'ready', port: 52102, apiOrigin: 'http://localhost:52102' });+ await vi.waitFor(() => {+ expect(rejectLoad).toBeDefined();+ });++ const loading = env.windows[0];+ if (!loading) throw new Error('window was never created');+ expect(wm.getContextForBrowserWindow(loading)?.projectPath).toBe('/tmp/ctx-load-fails');++ rejectLoad?.(new Error('ERR_FILE_NOT_FOUND'));+ await expect(pending).rejects.toThrow('ERR_FILE_NOT_FOUND');+ expect(wm.getContextForBrowserWindow(loading)).toBeUndefined();+ });+test('onUtilityMessage (when wired) receives post-init utility messages', async () => {const observed: unknown[] = [];env.deps.onUtilityMessage = (msg) => observed.push(msg);@@ -768,6 +844,61 @@ describe('WindowManager', () => {expect(env.createWindowOpts[0]?.projectPath).toBe(ctx.projectPath);});+ test('an attach-mode window resolves to its project while its renderer loads', async () => {+ // Same gap as the spawn path: the attach path also registers in+ // `windowsByPath` only once the renderer load resolves, and an+ // attach-mode window is an ordinary editor window as far as+ // Terminal -> New Terminal Window is concerned.+ enableAttachProbe();+ let releaseLoad: (() => void) | undefined;+ env.deps.createWindow = (opts) => {+ env.createWindowOpts.push(opts);+ const w = makeWindow();+ w.loadFile = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ releaseLoad = resolve;+ }),+ ) as typeof w.loadFile;+ env.windows.push(w);+ return w;+ };++ const wm = new WindowManager(env.deps);+ const pending = wm.createProjectWindow({ projectPath: '/tmp/dragon' });+ await vi.waitFor(() => {+ expect(releaseLoad).toBeDefined();+ });++ const loading = env.windows[0];+ if (!loading) throw new Error('window was never created');+ expect(wm.getContextForBrowserWindow(loading)?.projectPath).toBe('/tmp/dragon');++ releaseLoad?.();+ expect(wm.getContextForBrowserWindow(loading)).toBe(await pending);+ });++ test('a throw between the load and the registry does not strand the loading entry', async () => {+ // `createKeepalive` runs after the renderer load and before+ // `windowsByPath.set`. If that span is not bracketed, a throw there leaves+ // the context — and its strong BrowserWindow reference — in+ // `loadingContextByWindow` for the life of the process, and a destroyed+ // window keeps resolving to a project.+ enableAttachProbe();+ env.deps.createKeepalive = vi.fn(() => {+ throw new Error('keepalive boom');+ }) as unknown as WindowManagerDeps['createKeepalive'];++ const wm = new WindowManager(env.deps);+ await expect(wm.createProjectWindow({ projectPath: '/tmp/dragon' })).rejects.toThrow(+ 'keepalive boom',+ );++ const stranded = env.windows[0];+ if (!stranded) throw new Error('window was never created');+ expect(wm.getContextForBrowserWindow(stranded)).toBeUndefined();+ });+test('attach path injects --ok-fresh-create=1 when freshlyCreated is set (production path)', async () => {// Attach mode — both the direct-attach and detached-spawn callers delegate// here — is the PRODUCTION window path (packaged builds wirediff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.tsindex 20aa0c231..cca865b97 100644--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts@@ -314,15 +314,23 @@ const terminalStatus = (page: Page) => page.locator('[data-terminal-status]');const readinessBanner = (page: Page) => page.getByTestId('terminal-readiness-banner');/**- * Hold until the renderer's main thread is answering promptly.+ * Hold until the renderer's main thread is answering promptly, so a genuinely+ * un-booted app fails HERE with that name rather than as a puzzling downstream+ * timeout.*- * `findEditorWindow` resolves as soon as PRELOAD answers, which is seconds- * ahead of a renderer that has committed its first render. Driving a menu- * action into that gap is what makes this whole family time-dependent: the- * dispatch, the state flip and the mount are all serviced by the one thread- * that is still booting. An idle renderer answers a round-trip in single-digit- * ms, so 100ms is slack rather than a budget; three in a row rules out- * catching a gap between two chunks of boot work.+ * This is a liveness check and nothing more. It is NOT a proxy for the renderer+ * having committed its first render, nor for main having registered the+ * window's project context: `findEditorWindow` resolves as soon as PRELOAD+ * answers, and preload answers from a document that has not finished loading,+ * so all three probes can clear inside the boot window. Measured on a failing+ * Linux run, the three round-trips cost 70ms total and cleared+ * 240ms after the window first became discoverable — the earlier claim that+ * three in a row "rules out catching a gap between two chunks of boot work"+ * was disproven by that trace. Ordering against main's state is main's job, not+ * this helper's.+ *+ * An idle renderer answers a round-trip in single-digit ms; 100ms is slack+ * rather than a budget.*/async function waitForRendererResponsive(page: Page): Promise<void> {await expect(async () => {diff --git a/packages/desktop/tests/smoke/terminal-window.e2e.ts b/packages/desktop/tests/smoke/terminal-window.e2e.tsindex 5fd3e8954..ef4fd49cb 100644--- a/packages/desktop/tests/smoke/terminal-window.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-window.e2e.ts@@ -101,18 +101,21 @@ async function findWindowByMode(}/**- * Hold until the renderer's main thread is answering promptly.+ * Hold until the renderer's main thread is answering promptly, so a genuinely+ * un-booted app fails HERE with that name rather than as a puzzling downstream+ * timeout.*- * `findWindowByMode` resolves as soon as PRELOAD answers, and main registers- * the window's project context only after `loadFile` settles — so between- * those two points the editor window exists and is drivable but main cannot- * yet say which project it belongs to. "New Terminal Window" invoked in that- * gap resolves no project and opens a HOME-cwd window with an empty- * `collabUrl`. A responsive renderer is strictly past load, so this closes it.+ * This is a liveness check and nothing more. It is NOT a proxy for main having+ * registered the window's project context: `findWindowByMode` resolves as soon+ * as PRELOAD answers, and preload answers from a document that has not finished+ * loading, so all three probes can clear inside the boot window. Measured on a+ * failing Linux run, the three round-trips cost 70ms total and cleared 240ms+ * after the window first became discoverable. Ordering the two is main's job —+ * `WindowManager.getContextForBrowserWindow` resolves a window from the moment+ * it exists — not this helper's.** An idle renderer answers a round-trip in single-digit ms; 100ms is slack- * rather than a budget, and three in a row rules out landing in a gap between- * two chunks of boot work.+ * rather than a budget.*/async function waitForRendererResponsive(page: Page): Promise<void> {await expect(async () => {@@ -196,8 +199,9 @@ test.describe('Standalone terminal window — live Electron', () => {const app = await launchApp(s);captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });// The main-process command inherits project context from the source editor.+ // Main resolves that from the moment the window exists, so no ordering is+ // needed here; this only holds until the app is answering.const editor = await findWindowByMode(app, 'editor');- // …but only once main HAS that context; see `waitForRendererResponsive`.await waitForRendererResponsive(editor);const editorWindow = await app.browserWindow(editor);const editorWebContentsId = await editorWindow.evaluate(