Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Open only the requested file on a cold single-file launch (PRD-7970) (#3523)

serafin-garcia2323637cd093
diff --git a/.changeset/cold-single-file-launch.md b/.changeset/cold-single-file-launch.md
new file mode 100644
index 000000000..018e0c9cc
--- /dev/null
+++ b/.changeset/cold-single-file-launch.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Opening a standalone Markdown file or a share link while OpenKnowledge is fully closed no longer reopens your previous session's project windows alongside it. The cold launch now opens only the window the link resolves to, and does not start the servers for unrelated projects.
+
+Those previous windows are not held back for a later launch either. The saved session is cleared on the launch that suppresses it, so your next ordinary launch opens your most recent project and the rest stay reachable from File → Recent project (loose files from File → Recent files). Launching from the Dock or the app icon still restores your full window set exactly as before.
diff --git a/packages/desktop/playwright.packaged.config.ts b/packages/desktop/playwright.packaged.config.ts
index f046af819..84cdf5f73 100644
--- a/packages/desktop/playwright.packaged.config.ts
+++ b/packages/desktop/playwright.packaged.config.ts
@@ -24,8 +24,14 @@ import { defineConfig } from '@playwright/test';
* is the smallest set that proves a DMG boots, reaches the renderer, and can
* complete the first-run flow. Widening or narrowing it is a deliberate act —
* `tests/unit/playwright-packaged-config.test.ts` pins the list.
+ *
+ * `cold-single-file-launch.e2e.ts` is here because it is packaged-ONLY in a
+ * stronger sense than the rest: it starts the app through Launch Services
+ * rather than launching Electron itself, so there is no unpackaged shape of it
+ * to run. It is the only tier that observes the cold Apple-Event boot path.
*/
export const PACKAGED_SMOKE_SUBSET = [
+ 'cold-single-file-launch.e2e.ts',
'consent-dialog.e2e.ts',
'create-new-project.e2e.ts',
'mcp-wiring.e2e.ts',
diff --git a/packages/desktop/src/main/boot-restore-decision.settle.test.ts b/packages/desktop/src/main/boot-restore-decision.settle.test.ts
index ea5ec3b4a..6b0758e10 100644
--- a/packages/desktop/src/main/boot-restore-decision.settle.test.ts
+++ b/packages/desktop/src/main/boot-restore-decision.settle.test.ts
@@ -4,8 +4,9 @@ import { describe, expect, test } from 'vitest';
// delivery has SETTLED, then reads the launch flag, then delegates to the pure
// `bootRestoreDecision`. On macOS the `open-url` Apple Event is delivered
// asynchronously and can land after the synchronous boot read, so the flag must
-// not be read until the settle await resolves — otherwise a cold-start share is
-// buried by the `lastOpenedProject` restore. These tests pin that contract.
+// not be read until the settle await resolves. Otherwise a cold-start share is
+// buried by whichever default it should have outranked: the clean-exit restore
+// snapshot, or `lastOpenedProject`. These tests pin that contract.
import { resolveBootRestoreDecision } from './boot-restore-decision.ts';
import { registerProtocolHandler } from './url-scheme.ts';
@@ -140,8 +141,8 @@ describe('resolveBootRestoreDecision (cold-start URL settle barrier)', () => {
});
});
- test('an update-relaunch snapshot still beats a URL delivered during the settle window', async () => {
- const { control, deliver } = makeHandler();
+ test('no URL during the settle window still restores a non-empty snapshot', async () => {
+ const { control } = makeHandler();
const settle = manualSettle();
const decisionPromise = resolveBootRestoreDecision({
@@ -153,11 +154,10 @@ describe('resolveBootRestoreDecision (cold-start URL settle barrier)', () => {
waitForUrlLaunchSettled: settle.waitForUrlLaunchSettled,
});
- // A share lands mid-settle, but the pure ranking is unchanged: the
- // update-relaunch snapshot outranks a URL claim, through the coordinator too.
- deliver(SHARE_URL);
- expect(control.urlLaunchOwnsWindow()).toBe(true);
-
+ // The ordinary icon launch, through the coordinator. The launch flag is the
+ // single input that can now erase a whole session, so the coordinator must
+ // not infer a claim from anything else it holds: a settle that merely timed
+ // out, or the presence of a snapshot, must still restore every window.
settle.release();
const decision = await decisionPromise;
@@ -168,6 +168,53 @@ describe('resolveBootRestoreDecision (cold-start URL settle barrier)', () => {
});
});
+ test('a share delivered during the settle window suppresses a non-empty restore snapshot (action none)', async () => {
+ const { control, deliver } = makeHandler();
+ const settle = manualSettle();
+
+ const decisionPromise = resolveBootRestoreDecision({
+ pendingRestore: [{ kind: 'project', projectPath: '/projects/a' }],
+ lastOpenedProject: '/projects/last',
+ optionHeld: false,
+ pathExists: () => true,
+ urlLaunchOwnsWindow: control.urlLaunchOwnsWindow,
+ waitForUrlLaunchSettled: settle.waitForUrlLaunchSettled,
+ });
+
+ // A share lands mid-settle and claims the launch. It outranks the clean-exit
+ // snapshot, through the coordinator too, so the previous window set is NOT
+ // restored and the snapshot is still consumed (`clearSnapshot`).
+ deliver(SHARE_URL);
+ expect(control.urlLaunchOwnsWindow()).toBe(true);
+
+ settle.release();
+ const decision = await decisionPromise;
+
+ expect(decision).toEqual({ clearSnapshot: true, action: 'none' });
+ });
+
+ test('a single-file URL delivered during the settle window suppresses a non-empty restore snapshot (action none)', async () => {
+ const { control, deliver } = makeHandler();
+ const settle = manualSettle();
+
+ const decisionPromise = resolveBootRestoreDecision({
+ pendingRestore: [{ kind: 'project', projectPath: '/projects/a' }],
+ lastOpenedProject: '/projects/last',
+ optionHeld: false,
+ pathExists: () => true,
+ urlLaunchOwnsWindow: control.urlLaunchOwnsWindow,
+ waitForUrlLaunchSettled: settle.waitForUrlLaunchSettled,
+ });
+
+ deliver(SINGLE_FILE_URL);
+ expect(control.urlLaunchOwnsWindow()).toBe(true);
+
+ settle.release();
+ const decision = await decisionPromise;
+
+ expect(decision).toEqual({ clearSnapshot: true, action: 'none' });
+ });
+
test('reads the launch flag STRICTLY AFTER the settle await resolves', async () => {
const { control } = makeHandler();
diff --git a/packages/desktop/src/main/boot-restore-decision.test.ts b/packages/desktop/src/main/boot-restore-decision.test.ts
index 59ea348fe..137e298db 100644
--- a/packages/desktop/src/main/boot-restore-decision.test.ts
+++ b/packages/desktop/src/main/boot-restore-decision.test.ts
@@ -142,8 +142,9 @@ describe('bootRestoreDecision', () => {
expect(decision).toEqual({ clearSnapshot: false, action: 'navigator' });
});
- // urlLaunch — a single-file deep-link (`ok <file>`) claims the launch, so the
- // boot path opens NO default window (the URL flush owns it).
+ // urlLaunch: a launch-claiming URL (single-file deep-link or valid share) owns
+ // the window, so the boot path opens NO default window (the URL flush owns it),
+ // outranking even a non-empty snapshot.
test('urlLaunch suppresses lastOpened restore (action none)', () => {
const decision = bootRestoreDecision({
pendingRestore: null,
@@ -166,10 +167,15 @@ describe('bootRestoreDecision', () => {
expect(decision).toEqual({ clearSnapshot: false, action: 'none' });
});
- test('urlLaunch does NOT override a snapshot restore (snapshot wins)', () => {
- // A real update relaunch carries no deep-link, so this combo is theoretical
- // — but the restore must never be dropped, so the snapshot ranks above
- // urlLaunch.
+ test('urlLaunch overrides a non-empty snapshot restore (action none, snapshot still consumed)', () => {
+ // An explicit file or share open is a deliberate "view just this" intent, so
+ // it wins over the clean-exit snapshot and the previous session's windows
+ // stay closed. The snapshot is still consumed (`clearSnapshot`) so it cannot
+ // resurface on the next boot.
+ //
+ // The only case here that pins that ranking: rank the snapshot first again
+ // and this is the one assertion that flips (to `restore`). Don't fold it
+ // into the Option-held sibling below, which passes under either ordering.
const decision = bootRestoreDecision({
pendingRestore: [proj('/projects/a'), proj('/projects/b')],
lastOpenedProject: '/projects/last',
@@ -177,11 +183,23 @@ describe('bootRestoreDecision', () => {
pathExists: existsIn(['/projects/a', '/projects/b']),
urlLaunch: true,
});
- expect(decision).toEqual({
- clearSnapshot: true,
- action: 'restore',
- windows: [proj('/projects/a'), proj('/projects/b')],
+ expect(decision).toEqual({ clearSnapshot: true, action: 'none' });
+ });
+
+ test('urlLaunch with the Option key held still suppresses restore (action none)', () => {
+ // Two suppressors at once. Neither cancels the other and neither promotes
+ // the snapshot: the boot opens nothing and still consumes it. Says nothing
+ // about the URL-vs-snapshot ranking, since Option already empties
+ // `restorable` and this passes under either ordering. See the sibling above
+ // for that guard.
+ const decision = bootRestoreDecision({
+ pendingRestore: [proj('/projects/a'), proj('/projects/b')],
+ lastOpenedProject: '/projects/last',
+ optionHeld: true,
+ pathExists: existsIn(['/projects/a', '/projects/b']),
+ urlLaunch: true,
});
+ expect(decision).toEqual({ clearSnapshot: true, action: 'none' });
});
});
diff --git a/packages/desktop/src/main/boot-restore-decision.ts b/packages/desktop/src/main/boot-restore-decision.ts
index 1130c3ac1..ecbe36ec0 100644
--- a/packages/desktop/src/main/boot-restore-decision.ts
+++ b/packages/desktop/src/main/boot-restore-decision.ts
@@ -7,13 +7,14 @@ export interface BootRestoreInput {
pathExists: (p: string) => boolean;
/**
* `true` when a launch-claiming URL that opens its own window has been seen
- * this run — a single-file deep-link (`ok <file>` → `openknowledge://open?file=`)
- * OR a valid share. The URL flush owns the initial window, so the boot path
- * opens NO default window — restoring the previous project / Navigator
- * alongside the URL-driven window both clutters the launch and races it for
- * focus (the reported "two windows, one is the splash"). Ranked below the
- * clean-exit window-restore snapshot (which must never be dropped) and above
- * `lastOpenedProject` / Navigator.
+ * this run: a single-file deep-link (`ok <file>` → `openknowledge://open?file=`)
+ * or a valid share. The URL flush owns the initial window, so the boot path
+ * opens NO default window. Restoring the previous project / Navigator alongside
+ * the URL-driven window both clutters the launch and races it for focus (two
+ * overlapping windows, one of them the splash). Ranked ABOVE the clean-exit
+ * window-restore snapshot: an explicit file or share open is a deliberate "view
+ * just this" intent, so the prior session's windows stay closed. The snapshot
+ * is still consumed (`clearSnapshot`) so it cannot resurface on the next boot.
*/
urlLaunch: boolean;
}
@@ -24,19 +25,29 @@ export type BootRestoreDecision =
| { clearSnapshot: boolean; action: 'navigator' }
| { clearSnapshot: boolean; action: 'none' };
-// Pure boot-restore decision. A non-null `pendingRestore` means the previous
-// run exited cleanly and snapshotted its window set — every clean exit writes
-// one (normal quit, "Relaunch now" update, and install-on-quit alike), not just
-// update relaunches. It is always consumed (`clearSnapshot`) even when Option
-// suppresses the actual restore. A non-null-but-empty/all-missing snapshot
-// opens the Navigator and deliberately does NOT fall through to
-// `lastOpenedProject` — the relaunch is honored as "nothing was open" rather
-// than reopening a stale project. A null snapshot is the cold-boot path that
-// restores `lastOpenedProject`. When a single-file deep-link claims the
-// launch (`urlLaunch`), open no default window — the URL flush owns it.
+// Pure boot-restore decision. Priority order: a launch-claiming URL first, then
+// a surviving clean-exit snapshot, then `lastOpenedProject`, then Navigator.
+//
+// When a launch-claiming URL owns the window (`urlLaunch`, a single-file
+// deep-link or a valid share), open no default window: the URL flush owns the
+// initial window set, so restoring the previous project / Navigator on top would
+// only clutter and race it. A non-null `pendingRestore` means the previous run
+// exited cleanly and snapshotted its window set. Every clean exit writes one
+// (normal quit, "Relaunch now" update, and install-on-quit alike), not just
+// update relaunches. It is always consumed (`clearSnapshot`) even when Option or
+// a URL launch suppresses the actual restore. A non-null-but-empty/all-missing
+// snapshot opens the Navigator and deliberately does NOT fall through to
+// `lastOpenedProject`: the relaunch is honored as "nothing was open" rather than
+// reopening a stale project. A null snapshot is the cold-boot path that restores
+// `lastOpenedProject`.
export function bootRestoreDecision(input: BootRestoreInput): BootRestoreDecision {
const { pendingRestore, lastOpenedProject, optionHeld, pathExists, urlLaunch } = input;
const clearSnapshot = pendingRestore !== null;
+
+ if (urlLaunch) {
+ return { clearSnapshot, action: 'none' };
+ }
+
// Filter each entry by whether its target still exists on disk — a project
// folder or loose file deleted/moved since the snapshot is silently skipped
// (`windowRestoreKey` is the project path or the canonical file path). The
@@ -51,9 +62,6 @@ export function bootRestoreDecision(input: BootRestoreInput): BootRestoreDecisio
if (restorable.length > 0) {
return { clearSnapshot, action: 'restore', windows: restorable };
}
- if (urlLaunch) {
- return { clearSnapshot, action: 'none' };
- }
if (
pendingRestore === null &&
lastOpenedProject !== null &&
@@ -159,9 +167,11 @@ export interface SettledBootRestoreInput extends Omit<BootRestoreInput, 'urlLaun
* cold-start URL delivery has settled, then reads the launch flag and delegates
* to the pure `bootRestoreDecision`. This closes the ordering race where the
* boot path read `urlLaunchOwnsWindow` before the macOS Apple Event carrying a
- * share was delivered — leaving a cold-start share buried by the
- * `lastOpenedProject` restore. The producer (OS event delivery) cannot be
- * ordered from here, so the barrier lives on this consumer boundary.
+ * share was delivered, leaving a cold-start share buried by whichever default
+ * it should have outranked: the clean-exit window-restore snapshot (the common
+ * case, since every clean quit writes one) or `lastOpenedProject`. The producer
+ * (OS event delivery) cannot be ordered from here, so the barrier lives on this
+ * consumer boundary.
*/
export async function resolveBootRestoreDecision(
input: SettledBootRestoreInput,
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index e2b1c9357..a19c26a5e 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -2746,12 +2746,28 @@ async function openEphemeralFile(filePath: string): Promise<void> {
try {
plan = prepareSingleFileOpen(filePath);
} catch (err) {
+ // The dialog is the user's copy; this is the operator's. Without it a
+ // "launched `ok <file>` and got the Navigator" report has no trace naming
+ // which file was attempted or which error class fired, while the sibling
+ // catch below is fully diagnosable. `warn` rather than `error` because the
+ // common cause is a file the user should not have opened (missing, or not
+ // markdown), not a fault in the app.
+ getLogger('project').warn({ file: filePath, err }, 'single-file open could not be prepared');
// Typed user-facing errors (missing / not-a-file / not-markdown) render a
// native dialog rather than a stack trace.
dialog.showErrorBox(
'Cannot open this file',
`${filePath}\n\n${err instanceof Error ? err.message : String(err)}`,
);
+ // Same zero-window fallback as the create-window catch below. The launch
+ // claim is recorded when the URL is parsed, before any window exists, so a
+ // cold `ok <file>` has already suppressed the boot restore by the time this
+ // throws. Without the fallback the app is left running with no window at
+ // all, which off macOS is unrecoverable: `window-all-closed` fires only
+ // when a window closes, and none was ever created.
+ if (BrowserWindow.getAllWindows().length === 0) {
+ openNavigator();
+ }
return;
}
@@ -7468,6 +7484,16 @@ function bootPrimaryInstance(): void {
}
return 'connect';
}
+ // Neither remaining choice opens a window, and a valid share claims the
+ // launch at parse time, before any window exists, so a cold launch has
+ // already suppressed its boot restore by the time this is answered.
+ // Declining would otherwise leave the app running with no window at all,
+ // which off macOS is unrecoverable: `window-all-closed` fires only when a
+ // window closes, and none was ever created. Same recovery as the Connect
+ // branch above.
+ if (BrowserWindow.getAllWindows().length === 0) {
+ openNavigator();
+ }
if (response === 1) {
// Route through the outbound-scheme allowlist rather than calling
// shell.openExternal directly: sharedUrl comes from an untrusted deep
@@ -7732,16 +7758,21 @@ function bootPrimaryInstance(): void {
applyHarvestedAuthSock(process.env, await authSockHarvest, shellEnvLogger);
// Every project open spawns a NEW editor window. Boot restore order:
- // 1. A clean exit left a `pendingWindowRestore` snapshot — open EVERY
- // project that was open before, not just the last one. The snapshot
- // is consumed unconditionally (cleared to null + persisted) before
- // any window opens, so a crash mid-restore can't loop it. A
- // non-null-but-empty/all-missing snapshot opens the Navigator and
- // deliberately does NOT fall through to `lastOpenedProject` — the
- // relaunch is honored as "nothing was open" rather than reopening a
- // stale project.
- // 2. Otherwise restore `lastOpenedProject` into one editor window.
- // 3. Holding Option (`--navigator`) or having nothing to restore
+ // 1. A launch-claiming single-file or share URL owns the initial window
+ // set, so no default restore window opens. Any snapshot is still
+ // consumed on this path (cleared to null + persisted like every
+ // other), so the suppressed window set is discarded permanently
+ // rather than held back for the next boot.
+ // 2. Otherwise, a clean exit left a `pendingWindowRestore` snapshot —
+ // open EVERY project that was open before, not just the last one.
+ // The snapshot is consumed unconditionally (cleared to null +
+ // persisted) before any window opens, so a crash mid-restore can't
+ // loop it. A non-null-but-empty/all-missing snapshot opens the
+ // Navigator and deliberately does NOT fall through to
+ // `lastOpenedProject` — the relaunch is honored as "nothing was
+ // open" rather than reopening a stale project.
+ // 3. Otherwise restore `lastOpenedProject` into one editor window.
+ // 4. Holding Option (`--navigator`) or having nothing to restore
// opens the Navigator instead.
const decision = await resolveBootRestoreDecision({
pendingRestore: appState.pendingWindowRestore,
@@ -7757,21 +7788,33 @@ function bootPrimaryInstance(): void {
urlLaunchOwnsWindow: protocolControl.urlLaunchOwnsWindow,
waitForUrlLaunchSettled: protocolControl.waitForUrlLaunchSettled,
});
+ // Size of the snapshot this boot is about to consume, read BEFORE the
+ // clear below overwrites it. On the URL-claim path the snapshot is
+ // discarded without being restored, so this is the only record of how
+ // much the launch threw away.
+ const snapshotWindowCount = appState.pendingWindowRestore?.length ?? 0;
// Field signal distinguishing "a URL owned the launch" from "restored
// despite an inbound share" — the settled flag/decision pair is otherwise
- // unobservable outside a debugger.
+ // unobservable outside a debugger. Carrying the count keeps a suppressed
+ // boot (`action: 'none'`) distinguishable from one that simply had
+ // nothing to restore.
getLogger('startup').info(
- { urlLaunch: protocolControl.urlLaunchOwnsWindow(), action: decision.action },
+ {
+ urlLaunch: protocolControl.urlLaunchOwnsWindow(),
+ action: decision.action,
+ snapshotWindowCount,
+ },
'boot-restore decision',
);
if (decision.clearSnapshot) {
appState = { ...appState, pendingWindowRestore: null };
if (!saveAppState(appState)) {
// Persisting the cleared snapshot failed, so it may replay on the
- // next boot. The existsSync filter limits the blast radius to
- // projects that still exist on disk.
+ // next boot. This is the raw entry count: the replaying boot re-runs
+ // the existsSync filter, which limits the blast radius to projects
+ // that still exist on disk.
console.warn('[main] failed to persist cleared window-restore snapshot', {
- windowCount: decision.action === 'restore' ? decision.windows.length : 0,
+ windowCount: snapshotWindowCount,
});
}
}
diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.ts
index 1f1b3aea4..c7e3cff26 100644
Binary files a/packages/desktop/src/main/state-store.ts and b/packages/desktop/src/main/state-store.ts differ
diff --git a/packages/desktop/tests/smoke/cold-single-file-launch.e2e.ts b/packages/desktop/tests/smoke/cold-single-file-launch.e2e.ts
new file mode 100644
index 000000000..97e599de9
--- /dev/null
+++ b/packages/desktop/tests/smoke/cold-single-file-launch.e2e.ts
@@ -0,0 +1,259 @@
+/**
+ * Cold-launch boot-restore smoke — the ONE tier that can observe what a Finder
+ * "Open With" actually does to the initial window set.
+ *
+ * **Why this file does not use `_electron.launch`.** Every other smoke file
+ * launches Electron directly and then fires `open(1)` at the already-running
+ * app. That exercises the warm `open-url` path. It structurally CANNOT exercise
+ * the cold one: a direct launch delivers the target via `process.argv` (the
+ * `second-instance` path), never as the `open-file` / `open-url` Apple Event
+ * that macOS sends when Launch Services starts a not-yet-running app. The
+ * boot-restore decision reads its launch flag behind a settle barrier built for
+ * exactly that asynchronous Apple-Event delivery, so a direct launch tests the
+ * barrier's fast path and nothing else. Here the app is started BY `open(1)`,
+ * which is the real thing.
+ *
+ * **The precondition is produced by the app, not written by the test.** Each
+ * case first launches with a file that lives inside a project, then quits
+ * cleanly so the app writes its own `pendingWindowRestore` snapshot. Only then
+ * does the case do the launch under test.
+ *
+ * Two earlier revisions wrote `state.json` directly instead. Both failed in CI
+ * with `snapshotWindowCount: 0` — the app booted from a different `state.json`
+ * than the one seeded, so the precedence under test was never exercised. The
+ * first revision moved `userData` by overriding `HOME`; removing that override
+ * did not fix it, which means the test cannot reliably predict where a packaged
+ * build resolves `app.getPath('userData')` on an arbitrary machine. Letting the
+ * app produce and consume its own snapshot removes the need to know: wherever
+ * it keeps state, it is the same place across the two launches.
+ *
+ * That also buys real coverage the seeded version never had — the clean-exit
+ * snapshot WRITE path is now exercised, not assumed — and it means the suite no
+ * longer reads or rewrites the developer's own `state.json`.
+ *
+ * **The oracle is the main process's structured log, not the renderer.** The
+ * app is not ours to attach to, so each case asserts on `boot-restore decision`
+ * (`urlLaunch`, `action`, `snapshotWindowCount`). The log is shared across
+ * launches, so entries are selected by recency against a timestamp taken
+ * immediately before each launch.
+ *
+ * Packaged-only by construction: an unpackaged `out/main/index.js` has no
+ * bundle for Launch Services to start.
+ */
+
+import { execFileSync } from 'node:child_process';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { basename, join } from 'node:path';
+import { expect, test } from '@playwright/test';
+import { resolveDesktopTarget } from './_helpers/launch-desktop';
+
+const TARGET = resolveDesktopTarget({ requirePackaged: true });
+const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';
+const DARWIN = process.platform === 'darwin';
+
+/** `OpenKnowledge.app` → `OpenKnowledge`, the process name `pkill`/`pgrep` use. */
+const APP_NAME = TARGET.appPath ? basename(TARGET.appPath, '.app') : 'OpenKnowledge';
+/** Shared across launches; entries are selected by recency, never by isolation. */
+const LOG_DIR = join(process.env.HOME ?? '', '.ok', 'logs');
+
+/** A cold launch is only cold if nothing holds the single-instance lock. */
+function appIsRunning(): boolean {
+ try {
+ execFileSync('pgrep', ['-x', APP_NAME], { stdio: 'pipe' });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function waitForExit(): void {
+ const deadline = Date.now() + 15_000;
+ while (appIsRunning() && Date.now() < deadline) {
+ execFileSync('sleep', ['0.25']);
+ }
+}
+
+/**
+ * Quit via AppleScript rather than a signal. The snapshot this suite depends on
+ * is written on the app's clean-exit path; a `pkill` is not guaranteed to reach
+ * it, and a missed snapshot would look like a precedence failure.
+ */
+function quitAppCleanly(): void {
+ try {
+ execFileSync('osascript', ['-e', `tell application "${APP_NAME}" to quit`], { stdio: 'pipe' });
+ } catch {
+ // Not running, or refused the Apple Event. The force path below covers it.
+ }
+ waitForExit();
+ if (appIsRunning()) {
+ try {
+ execFileSync('pkill', ['-x', APP_NAME], { stdio: 'pipe' });
+ } catch {
+ // Already gone.
+ }
+ waitForExit();
+ }
+}
+
+/**
+ * A project with one markdown file in it. Opening that file cold gives the app
+ * a project window, which is what the clean-exit snapshot then records.
+ */
+function makeProjectFixture(): { dir: string; file: string } {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-cold-launch-project-')));
+ mkdirSync(join(dir, '.ok'), { recursive: true });
+ writeFileSync(join(dir, '.ok', 'config.yml'), "content:\n dir: '.'\n");
+ const file = join(dir, 'note.md');
+ writeFileSync(file, '# Project note\n');
+ return { dir, file };
+}
+
+function makeLooseFile(): { dir: string; file: string } {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-cold-launch-loose-')));
+ const file = join(dir, 'standalone.md');
+ writeFileSync(file, '# Standalone\n\nOutside every project.\n');
+ return { dir, file };
+}
+
+interface BootRestoreDecisionLog {
+ urlLaunch: boolean;
+ action: string;
+ snapshotWindowCount: number;
+}
+
+function readLogLinesSince(sinceMs: number): Array<Record<string, unknown>> {
+ if (!existsSync(LOG_DIR)) return [];
+ return readdirSync(LOG_DIR)
+ .filter((f) => f.startsWith('desktop.'))
+ .flatMap((f) =>
+ readFileSync(join(LOG_DIR, f), 'utf8')
+ .split('\n')
+ .flatMap((line) => {
+ if (line.trim().length === 0) return [];
+ try {
+ const entry = JSON.parse(line) as Record<string, unknown>;
+ const t = typeof entry.time === 'string' ? Date.parse(entry.time) : Number.NaN;
+ return Number.isFinite(t) && t >= sinceMs ? [entry] : [];
+ } catch {
+ return [];
+ }
+ }),
+ );
+}
+
+async function waitForBootDecision(sinceMs: number): Promise<BootRestoreDecisionLog> {
+ let found: Record<string, unknown> | undefined;
+ await expect(() => {
+ found = readLogLinesSince(sinceMs).find((e) => e.msg === 'boot-restore decision');
+ expect(
+ found,
+ `no boot-restore decision logged since ${new Date(sinceMs).toISOString()}`,
+ ).toBeDefined();
+ }).toPass({ timeout: 60_000, intervals: [500] });
+ return found as unknown as BootRestoreDecisionLog;
+}
+
+function launchViaLaunchServices(target: string): number {
+ const since = Date.now();
+ execFileSync('open', ['-a', TARGET.appPath as string, target], { stdio: 'pipe' });
+ return since;
+}
+
+/**
+ * Give the app a non-empty clean-exit snapshot: open a file inside a project so
+ * a project window exists, then quit cleanly so that window is recorded.
+ * Returns nothing — the snapshot lives in the app's own userData, wherever that
+ * is, which is precisely what this test declines to assume.
+ */
+async function establishRestoreSnapshot(projectFile: string): Promise<void> {
+ quitAppCleanly();
+ const since = launchViaLaunchServices(projectFile);
+ await waitForBootDecision(since);
+ // The window opens after the decision is logged; give it a moment to exist so
+ // the clean exit has something to record.
+ execFileSync('sleep', ['6']);
+ quitAppCleanly();
+}
+
+test.describe('cold launch with an explicit target owns the initial window set', () => {
+ test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');
+ test.skip(!DARWIN, 'Launch Services + Apple Events are macOS-only.');
+ test.skip(!TARGET.exists, TARGET.missingReason);
+ test.skip(
+ () => appIsRunning(),
+ `${APP_NAME} is already running — a second launch takes the single-instance path and never makes a boot-restore decision.`,
+ );
+
+ test('a cold single-file open suppresses a non-empty restore snapshot', async () => {
+ test.setTimeout(180_000);
+
+ const project = makeProjectFixture();
+ const loose = makeLooseFile();
+
+ try {
+ await establishRestoreSnapshot(project.file);
+
+ const since = launchViaLaunchServices(loose.file);
+ const decision = await waitForBootDecision(since);
+
+ // Load-bearing: with an empty snapshot a single-file launch still yields
+ // `action: none`, so without this the case passes while proving nothing.
+ // A 0 here means the precondition never took, NOT that precedence broke.
+ expect(
+ decision.snapshotWindowCount,
+ 'the app booted with an empty snapshot, so the suppression under test was never exercised',
+ ).toBeGreaterThanOrEqual(1);
+ expect(decision.urlLaunch).toBe(true);
+ expect(decision.action).toBe('none');
+ } finally {
+ quitAppCleanly();
+ rmSync(project.dir, { recursive: true, force: true });
+ rmSync(loose.dir, { recursive: true, force: true });
+ }
+ });
+
+ test('a cold launch that opens no window of its own still lands on the Navigator', async () => {
+ test.setTimeout(180_000);
+
+ // A share for a repo this machine does not hold takes the foreign-host
+ // gate, and every remaining branch there declines without opening a
+ // window. Suppressing the restore removed what used to mask that, so the
+ // boot must recover to the Navigator. Left unhandled the app runs with no
+ // window at all, which off macOS is unrecoverable: `window-all-closed`
+ // fires only when a window closes, and none was ever created.
+ const project = makeProjectFixture();
+ const share = 'openknowledge://share?url=https://github.com/inkeep/not-cloned-repo/tree/main';
+
+ try {
+ await establishRestoreSnapshot(project.file);
+
+ const since = launchViaLaunchServices(share);
+ const decision = await waitForBootDecision(since);
+ expect(
+ decision.snapshotWindowCount,
+ 'the app booted with an empty snapshot, so the suppression under test was never exercised',
+ ).toBeGreaterThanOrEqual(1);
+ expect(decision.action).toBe('none');
+
+ await expect(() => {
+ const opened = readLogLinesSince(since).some(
+ (e) => e.subsystem === 'navigator' && e.msg === 'opening window',
+ );
+ expect(opened, 'boot suppressed the restore but opened no window').toBe(true);
+ }).toPass({ timeout: 30_000, intervals: [500] });
+ } finally {
+ quitAppCleanly();
+ rmSync(project.dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/desktop/tests/smoke/deep-link.e2e.ts b/packages/desktop/tests/smoke/deep-link.e2e.ts
index bd9bc1dc9..2af49c785 100644
--- a/packages/desktop/tests/smoke/deep-link.e2e.ts
+++ b/packages/desktop/tests/smoke/deep-link.e2e.ts
@@ -61,19 +61,16 @@ test.describe('deep-link warm-start smoke (M4 US-009 / AC7)', () => {
test.skip(!DARWIN, 'Deep-link URL scheme is macOS-only in v0 (D51 NOT NOW).');
test.skip(!TARGET.exists, TARGET.missingReason);
- // Explicit visibility of the coverage gap — appears in test-run output as
- // a named skip so the missing coverage can't be overlooked when scanning
- // CI logs (signed DMG + Launch Services binding required).
- test.skip('cold-start Apple-Event delivery — deferred until signed DMG enables Launch Services binding', () => {
- // Intentionally empty. Implementation requires:
- // 1. Signed + notarized DMG so macOS Launch Services binds
- // `openknowledge://` to this bundle instead of the generic
- // Electron shell.
- // 2. A harness that fires `open openknowledge://...` against a
- // not-yet-running installed .app (i.e. no `_electron.launch`
- // pre-boot) and asserts the queue-then-flush path catches the
- // Apple Event that fires before `whenReady`.
- });
+ // Cold-start Apple-Event delivery is covered by
+ // `cold-single-file-launch.e2e.ts`, which runs in the packaged tier.
+ //
+ // That coverage was long deferred on the belief that it needed a signed +
+ // notarized DMG so Launch Services would bind `openknowledge://` to this
+ // bundle rather than the generic Electron shell. Naming the bundle directly
+ // (`open -a <bundle> <target>`) sidesteps scheme resolution entirely, and a
+ // document open involves no scheme at all — so an ad-hoc-signed local build
+ // delivers real `open-file` and `open-url` Apple Events. Signing gates
+ // Gatekeeper, not Apple-Event delivery.
test('open(1) shell-out post-launch routes extension-less docName to renderer hash', async ({
captureStderrFor,
diff --git a/packages/desktop/tests/unit/playwright-packaged-config.test.ts b/packages/desktop/tests/unit/playwright-packaged-config.test.ts
index 28bc83b0f..2613f7492 100644
--- a/packages/desktop/tests/unit/playwright-packaged-config.test.ts
+++ b/packages/desktop/tests/unit/playwright-packaged-config.test.ts
@@ -17,11 +17,13 @@ describe('playwright.packaged.config', () => {
// makes the gate weaker than the spec says it is. Either direction should
// require editing this assertion on purpose.
expect([...PACKAGED_SMOKE_SUBSET]).toEqual([
+ 'cold-single-file-launch.e2e.ts',
'consent-dialog.e2e.ts',
'create-new-project.e2e.ts',
'mcp-wiring.e2e.ts',
]);
expect(packagedConfig.testMatch).toEqual([
+ '**/cold-single-file-launch.e2e.ts',
'**/consent-dialog.e2e.ts',
'**/create-new-project.e2e.ts',
'**/mcp-wiring.e2e.ts',