Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): cold-start share link no longer buried by last-project restore (#2430)
miles-kt-inkeep5beff8243c40
diff --git a/.changeset/cold-start-share-clone-race.md b/.changeset/cold-start-share-clone-race.mdnew file mode 100644index 000000000..95c363de8--- /dev/null+++ b/.changeset/cold-start-share-clone-race.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge": patch+---++Opening a share link with the app fully closed now reliably lands on the shared target. Previously, if macOS delivered the link a beat after launch, the app restored your last-open project first and the clone dialog for a repo you don't have locally was immediately buried behind that restored window.++The desktop boot path now waits for cold-start link delivery to settle (a short grace window that ends early the moment a link claims the launch) before deciding whether to restore the previous project. A launch without any link still restores your last project as before; the wait overlaps startup work, so it adds no noticeable delay.diff --git a/packages/desktop/src/main/boot-restore-decision.settle.test.ts b/packages/desktop/src/main/boot-restore-decision.settle.test.tsnew file mode 100644index 000000000..495d64562--- /dev/null+++ b/packages/desktop/src/main/boot-restore-decision.settle.test.ts@@ -0,0 +1,202 @@+import { describe, expect, test } from 'bun:test';+// `resolveBootRestoreDecision` is the boot-orchestration seam: an async+// coordinator that withholds the boot-restore decision until cold-start URL+// 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.+import { resolveBootRestoreDecision } from './boot-restore-decision.ts';+import { registerProtocolHandler } from './url-scheme.ts';++// A valid share for a repo NOT held locally (the reported clone flow). It parses+// to a launch-claiming `kind:'ok'` share, so delivering it flips+// `urlLaunchOwnsWindow` to true.+const SHARE_URL = 'openknowledge://share?url=https://github.com/inkeep/not-cloned-repo/tree/main';+// A single-file deep-link (`ok <file>` → `openknowledge://open?file=<abs>`). The+// single-file path rides the SAME `urlLaunchOwnsWindow` read at the same seam,+// so one settle barrier covers both share and single-file cold-start URLs.+const SINGLE_FILE_URL = 'openknowledge://open?file=/Users/me/notes/scratch.md';++// Spin a REAL `registerProtocolHandler` and capture its `open-url` listener so a+// test controls the exact moment the macOS Apple Event is "delivered" relative+// to the settle await. `whenReady` never resolves, so the handler's internal+// auto-flush loop never runs — the flag is observed purely as a function of+// delivery timing.+function makeHandler() {+ let openUrlListener: ((event: { preventDefault: () => void }, url: string) => void) | null = null;+ const neverReady = new Promise<void>(() => {});+ const control = registerProtocolHandler({+ app: {+ // biome-ignore lint/suspicious/noExplicitAny: minimal test double for electron.app.+ on(event: string, cb: any) {+ if (event === 'open-url') openUrlListener = cb;+ },+ whenReady: () => neverReady,+ isPackaged: true,+ setAsDefaultProtocolClient: () => true,+ removeAsDefaultProtocolClient: () => true,+ // biome-ignore lint/suspicious/noExplicitAny: only the listeners above are exercised.+ } as any,+ focusWindowForProject: () => null,+ openProject: async () => null,+ sendDeepLink: () => {},+ getAnyReadyWindow: () => null,+ getInitialArgv: () => [],+ // Pin non-darwin so the settle source resolves immediately (non-darwin fast+ // path) rather than hanging on the grace timer that never fires (whenReady =+ // neverReady). The darwin settle path is covered by url-scheme.settle.test.ts.+ platform: 'linux',+ });+ return {+ control,+ deliver: (url: string) => openUrlListener?.({ preventDefault: () => {} }, url),+ };+}++// A settle barrier the test releases by hand, so delivery can be interleaved+// deterministically inside the window (no wall-clock, no sleeps).+function manualSettle() {+ let release!: () => void;+ const promise = new Promise<void>((res) => {+ release = res;+ });+ return { waitForUrlLaunchSettled: () => promise, release };+}++describe('resolveBootRestoreDecision (cold-start URL settle barrier)', () => {+ test('a share URL delivered DURING the settle window wins the launch (action none, not lastOpened)', async () => {+ const { control, deliver } = makeHandler();+ const settle = manualSettle();++ const decisionPromise = resolveBootRestoreDecision({+ pendingRestore: null,+ lastOpenedProject: '/projects/last',+ optionHeld: false,+ pathExists: () => true,+ urlLaunchOwnsWindow: control.urlLaunchOwnsWindow,+ waitForUrlLaunchSettled: settle.waitForUrlLaunchSettled,+ });++ // At decision time the Apple Event has not been delivered — the flag is stale.+ expect(control.urlLaunchOwnsWindow()).toBe(false);++ // The cold-start `open-url` Apple Event lands mid-settle; the flag flips.+ deliver(SHARE_URL);+ expect(control.urlLaunchOwnsWindow()).toBe(true);++ // Only now may the coordinator read the flag and decide.+ settle.release();+ const decision = await decisionPromise;++ // The share owns the launch; the previously-opened project must NOT be restored.+ expect(decision).toEqual({ clearSnapshot: false, action: 'none' });+ });++ test('a single-file URL delivered DURING the settle window wins the launch (action none)', async () => {+ const { control, deliver } = makeHandler();+ const settle = manualSettle();++ const decisionPromise = resolveBootRestoreDecision({+ pendingRestore: null,+ lastOpenedProject: '/projects/last',+ optionHeld: false,+ pathExists: () => true,+ urlLaunchOwnsWindow: control.urlLaunchOwnsWindow,+ waitForUrlLaunchSettled: settle.waitForUrlLaunchSettled,+ });++ expect(control.urlLaunchOwnsWindow()).toBe(false);+ deliver(SINGLE_FILE_URL);+ expect(control.urlLaunchOwnsWindow()).toBe(true);++ settle.release();+ const decision = await decisionPromise;++ expect(decision).toEqual({ clearSnapshot: false, action: 'none' });+ });++ test('no URL during the settle window still restores lastOpenedProject (normal restore preserved)', async () => {+ const { control } = makeHandler();+ const settle = manualSettle();++ const decisionPromise = resolveBootRestoreDecision({+ pendingRestore: null,+ lastOpenedProject: '/projects/last',+ optionHeld: false,+ pathExists: () => true,+ urlLaunchOwnsWindow: control.urlLaunchOwnsWindow,+ waitForUrlLaunchSettled: settle.waitForUrlLaunchSettled,+ });++ // Settle completes with no URL delivered — the flag never flips.+ settle.release();+ const decision = await decisionPromise;++ expect(decision).toEqual({+ clearSnapshot: false,+ action: 'lastOpened',+ project: '/projects/last',+ });+ });++ test('an update-relaunch snapshot still beats a URL delivered during the settle window', async () => {+ const { control, deliver } = makeHandler();+ const settle = manualSettle();++ const decisionPromise = resolveBootRestoreDecision({+ pendingRestore: ['/projects/a'],+ lastOpenedProject: '/projects/last',+ optionHeld: false,+ pathExists: () => true,+ urlLaunchOwnsWindow: control.urlLaunchOwnsWindow,+ 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);++ settle.release();+ const decision = await decisionPromise;++ expect(decision).toEqual({+ clearSnapshot: true,+ action: 'restore',+ projects: ['/projects/a'],+ });+ });++ test('reads the launch flag STRICTLY AFTER the settle await resolves', async () => {+ const { control } = makeHandler();++ let settleResolved = false;+ // Resolve on a microtask so a coordinator that reads the flag before awaiting+ // settle observes `settleResolved === false` at read time.+ const settled = new Promise<void>((res) => {+ queueMicrotask(() => {+ settleResolved = true;+ res();+ });+ });++ let flagReadAfterSettle: boolean | null = null;+ const reader = () => {+ flagReadAfterSettle = settleResolved;+ return control.urlLaunchOwnsWindow();+ };++ await resolveBootRestoreDecision({+ pendingRestore: null,+ lastOpenedProject: '/projects/last',+ optionHeld: false,+ pathExists: () => true,+ urlLaunchOwnsWindow: reader,+ waitForUrlLaunchSettled: () => settled,+ });++ // The flag was read only after settling completed.+ expect(flagReadAfterSettle).toBe(true);+ });+});diff --git a/packages/desktop/src/main/boot-restore-decision.ts b/packages/desktop/src/main/boot-restore-decision.tsindex 8d0b65a7f..3674fa785 100644--- a/packages/desktop/src/main/boot-restore-decision.ts+++ b/packages/desktop/src/main/boot-restore-decision.ts@@ -52,3 +52,43 @@ export function bootRestoreDecision(input: BootRestoreInput): BootRestoreDecisio}return { clearSnapshot, action: 'navigator' };}++/**+ * Coordinator input for the async boot-restore seam. Mirrors `BootRestoreInput`+ * but replaces the eager `urlLaunch: boolean` with a settle-then-read pair:+ * `waitForUrlLaunchSettled` is awaited BEFORE `urlLaunchOwnsWindow` is read, so+ * the launch flag reflects cold-start URL delivery rather than a stale snapshot.+ */+export interface SettledBootRestoreInput extends Omit<BootRestoreInput, 'urlLaunch'> {+ /** Read AFTER `waitForUrlLaunchSettled` resolves, never before. */+ urlLaunchOwnsWindow: () => boolean;+ /**+ * Resolves once cold-start URL delivery has settled — a launch-claiming URL+ * flipped the flag, or a bounded grace window elapsed. On macOS the `open-url`+ * Apple Event is delivered asynchronously and can land after the boot path's+ * synchronous read; awaiting this orders the flag read after that delivery.+ */+ waitForUrlLaunchSettled: () => Promise<void>;+}++/**+ * Async coordinator for the boot-restore decision. Withholds the decision until+ * 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.+ */+export async function resolveBootRestoreDecision(+ input: SettledBootRestoreInput,+): Promise<BootRestoreDecision> {+ await input.waitForUrlLaunchSettled();+ return bootRestoreDecision({+ pendingRestore: input.pendingRestore,+ lastOpenedProject: input.lastOpenedProject,+ optionHeld: input.optionHeld,+ pathExists: input.pathExists,+ urlLaunch: input.urlLaunchOwnsWindow(),+ });+}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex f6078249d..22ada0ef7 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -133,7 +133,7 @@ import {channelFromVersion,type StartAutoUpdaterHandle,} from './auto-updater.ts';-import { bootRestoreDecision } from './boot-restore-decision.ts';+import { resolveBootRestoreDecision } from './boot-restore-decision.ts';import { runBootstrap } from './bootstrap.ts';import {type BranchInfoProxyDeps,@@ -4292,17 +4292,27 @@ function bootPrimaryInstance(): void {// 2. Otherwise restore `lastOpenedProject` into one editor window.// 3. Holding Option (`--navigator`) or having nothing to restore// opens the Navigator instead.- const decision = bootRestoreDecision({+ const decision = await resolveBootRestoreDecision({pendingRestore: appState.pendingWindowRestore,lastOpenedProject: appState.lastOpenedProject,optionHeld: process.argv.includes('--navigator'),pathExists: existsSync,// A launch-claiming URL that opens its own window — a single-file open// (`ok <file>`) OR a valid share — suppresses the default boot-restore- // window so the URL flush owns the launch. Without this a cold-start- // share opens the previously-opened project instead of the shared target.- urlLaunch: protocolControl.urlLaunchOwnsWindow(),+ // window so the URL flush owns the launch. Read AFTER the settle barrier+ // resolves: on macOS the `open-url` Apple Event can land after this point+ // in the boot chain, so reading the flag synchronously here would miss a+ // cold-start share and open the previously-opened project instead.+ urlLaunchOwnsWindow: protocolControl.urlLaunchOwnsWindow,+ waitForUrlLaunchSettled: protocolControl.waitForUrlLaunchSettled,});+ // 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.+ getLogger('startup').info(+ { urlLaunch: protocolControl.urlLaunchOwnsWindow(), action: decision.action },+ 'boot-restore decision',+ );if (decision.clearSnapshot) {appState = { ...appState, pendingWindowRestore: null };if (!saveAppState(appState)) {diff --git a/packages/desktop/src/main/url-scheme.settle.test.ts b/packages/desktop/src/main/url-scheme.settle.test.tsnew file mode 100644index 000000000..0f5224b41--- /dev/null+++ b/packages/desktop/src/main/url-scheme.settle.test.ts@@ -0,0 +1,194 @@+import { describe, expect, test } from 'bun:test';+// `waitForUrlLaunchSettled` is the REAL settle SOURCE the boot coordinator+// (`resolveBootRestoreDecision`) awaits before reading the launch flag. It lives+// on the `ProtocolHandlerControl` returned by `registerProtocolHandler` — the+// module that owns the flag/queue and the `open-url` listener. On macOS the+// cold-start Apple Event is delivered asynchronously, so the settle promise must+// resolve on WHICHEVER comes first: the flag flipping (a launch-claiming URL+// arrived — early resolve, ~0 wait) OR a bounded grace window elapsing (the+// safety net for a late Apple Event, armed at `whenReady`). Off macOS there is+// no Apple Event, so it resolves immediately; likewise when the launch is+// already claimed before the settle is awaited. These tests pin that timing+// contract at the public control interface. The grace bound is exercised through+// the injectable `deps.setTimeout` seam the module already exposes, so no+// wall-clock is involved and the tests are deterministic.+import { resolveBootRestoreDecision } from './boot-restore-decision.ts';+import { registerProtocolHandler } from './url-scheme.ts';++// A valid share for a repo NOT held locally. Parses to a launch-claiming+// `kind:'ok'` share, so delivering it flips `urlLaunchOwnsWindow` to true.+const SHARE_URL = 'openknowledge://share?url=https://github.com/inkeep/not-cloned-repo/tree/main';+// A single-file deep-link (`ok <file>` -> `openknowledge://open?file=<abs>`).+// The single-file path is the OTHER launch-claiming kind that flips the flag.+const SINGLE_FILE_URL = 'openknowledge://open?file=/Users/me/notes/scratch.md';++// Drain the microtask queue so any settle `.then` callbacks run. Every settle+// resolution in these tests is driven by an explicit event we trigger (deliver /+// resolveReady / fireScheduled); this only lets those resolutions propagate. No+// wall-clock, no fixed-duration waits.+async function flushMicrotasks(): Promise<void> {+ for (let i = 0; i < 8; i++) await Promise.resolve();+}++// Spin a REAL `registerProtocolHandler` with controllable boundary deps:+// - `whenReady` resolves by hand (`resolveReady`) so the grace timer's+// arm-at-whenReady moment is deterministic.+// - `open-url` listener is captured (`deliver`) so a test controls the exact+// instant the Apple Event "lands" relative to the settle await.+// - `setTimeout` is captured (`scheduled` / `fireScheduled`) so the bounded+// grace window elapses on command, never on wall-clock time.+// - `platform` selects the darwin vs non-darwin gate.+// `getInitialArgv` is empty, so the URL queue starts empty and the auto-flush+// loop drains immediately without scheduling — the only timer that lands in+// `scheduled` is the grace window.+function makeHandler(opts: { platform: NodeJS.Platform }) {+ let openUrlListener: ((event: { preventDefault: () => void }, url: string) => void) | null = null;+ let resolveReady!: () => void;+ const ready = new Promise<void>((res) => {+ resolveReady = res;+ });+ const scheduled: Array<() => void> = [];++ const control = registerProtocolHandler({+ app: {+ // biome-ignore lint/suspicious/noExplicitAny: minimal test double for electron.app.+ on(event: string, cb: any) {+ if (event === 'open-url') openUrlListener = cb;+ },+ whenReady: () => ready,+ isPackaged: true,+ setAsDefaultProtocolClient: () => true,+ removeAsDefaultProtocolClient: () => true,+ // biome-ignore lint/suspicious/noExplicitAny: only the listeners above are exercised.+ } as any,+ focusWindowForProject: () => null,+ openProject: async () => null,+ sendDeepLink: () => {},+ getAnyReadyWindow: () => null,+ getInitialArgv: () => [],+ setTimeout: (cb: () => void, _ms: number) => {+ scheduled.push(cb);+ return scheduled.length;+ },+ // Injectable darwin gate — the settle source resolves immediately off macOS+ // (no Apple Event to wait for). Optional dep the fix adds.+ platform: opts.platform,+ });++ return {+ control,+ deliver: (url: string) => openUrlListener?.({ preventDefault: () => {} }, url),+ resolveReady,+ scheduled,+ // Elapse every armed timer (the grace window) exactly once.+ fireScheduled: () => {+ const snapshot = scheduled.splice(0, scheduled.length);+ for (const cb of snapshot) cb();+ },+ };+}++describe('ProtocolHandlerControl.waitForUrlLaunchSettled (cold-start URL settle source)', () => {+ test('(a) a launch-claiming URL flipping the flag early-resolves settle, before the grace window elapses', async () => {+ const h = makeHandler({ platform: 'darwin' });++ let settled = false;+ void h.control.waitForUrlLaunchSettled().then(() => {+ settled = true;+ });++ h.resolveReady(); // arm the bounded grace window at whenReady+ await flushMicrotasks();+ // No URL yet and the grace window has not elapsed -> settle stays pending.+ expect(settled).toBe(false);+ // A bounded grace wait was genuinely armed (via the injectable setTimeout),+ // so resolving now is an EARLY resolve, not an unconditional immediate one.+ expect(h.scheduled.length).toBeGreaterThan(0);++ h.deliver(SHARE_URL); // Apple Event lands mid-window; flips the flag+ expect(h.control.urlLaunchOwnsWindow()).toBe(true);+ await flushMicrotasks();++ // Early-resolved on the flag flip — and we never fired the grace timer,+ // so this cannot be the grace-timeout path.+ expect(settled).toBe(true);+ });++ test('(b) with no URL, settle resolves when the grace window elapses (armed at whenReady)', async () => {+ const h = makeHandler({ platform: 'darwin' });++ let settled = false;+ void h.control.waitForUrlLaunchSettled().then(() => {+ settled = true;+ });++ h.resolveReady();+ await flushMicrotasks();+ // Grace armed but not yet elapsed, and no URL arrived -> still pending.+ expect(settled).toBe(false);+ expect(h.control.urlLaunchOwnsWindow()).toBe(false);++ h.fireScheduled(); // the grace window elapses+ await flushMicrotasks();+ expect(settled).toBe(true);+ });++ test('(c) on a non-darwin platform settle resolves immediately (no Apple Event exists)', async () => {+ const h = makeHandler({ platform: 'linux' });++ let settled = false;+ void h.control.waitForUrlLaunchSettled().then(() => {+ settled = true;+ });++ // No whenReady resolution, no URL delivery, no grace timer fired: the only+ // path to resolution is the non-darwin immediate gate.+ await flushMicrotasks();+ expect(settled).toBe(true);+ });++ test('(d) when the launch is already claimed, settle resolves immediately', async () => {+ const h = makeHandler({ platform: 'darwin' });++ // A launch-claiming URL flips the flag BEFORE settle is ever awaited (the+ // Apple Event / cold-start argv beat the boot read).+ h.deliver(SINGLE_FILE_URL);+ expect(h.control.urlLaunchOwnsWindow()).toBe(true);++ let settled = false;+ void h.control.waitForUrlLaunchSettled().then(() => {+ settled = true;+ });++ // No whenReady resolution, no grace timer fired: resolution can only come+ // from the already-claimed fast path.+ await flushMicrotasks();+ expect(settled).toBe(true);+ });++ test('(e) composition: the coordinator wired to the REAL settle source lets a mid-window share win', async () => {+ const h = makeHandler({ platform: 'darwin' });++ // Wire resolveBootRestoreDecision to the real control — no manualSettle+ // override. This is the production wiring shape from the boot path; the+ // coordinator suite covers ordering with an injected barrier, this pins the+ // two halves actually composed.+ const decisionPromise = resolveBootRestoreDecision({+ pendingRestore: null,+ lastOpenedProject: '/projects/last',+ optionHeld: false,+ pathExists: () => true,+ urlLaunchOwnsWindow: h.control.urlLaunchOwnsWindow,+ waitForUrlLaunchSettled: h.control.waitForUrlLaunchSettled,+ });++ h.resolveReady(); // arm the grace window at whenReady+ await flushMicrotasks();++ // The share lands mid-window (grace never fired); early-resolve releases+ // the coordinator, which reads the flipped flag and suppresses the restore.+ h.deliver(SHARE_URL);+ const decision = await decisionPromise;+ expect(decision).toEqual({ clearSnapshot: false, action: 'none' });+ });+});diff --git a/packages/desktop/src/main/url-scheme.ts b/packages/desktop/src/main/url-scheme.tsindex 94df93ac3..9070bd04a 100644--- a/packages/desktop/src/main/url-scheme.ts+++ b/packages/desktop/src/main/url-scheme.ts@@ -670,6 +670,13 @@ interface ProtocolHandlerDeps {getInitialArgv?: () => readonly string[];/** Test injection for `setTimeout`. Defaults to the global. */setTimeout?: (cb: () => void, ms: number) => unknown;+ /**+ * Host platform, for the cold-start settle gate. Off macOS there is no+ * `open-url` Apple Event (argv is scanned synchronously before `whenReady`),+ * so `waitForUrlLaunchSettled` resolves immediately. Defaults to+ * `process.platform`; tests inject `'linux'` to exercise the non-darwin gate.+ */+ platform?: NodeJS.Platform;/** Test injection for the dedup clock. Defaults to `Date.now`. */now?: () => number;/** Optional structured logger. */@@ -732,6 +739,16 @@ interface ProtocolHandlerControl {* Subject to the same near-simultaneous-duplicate dedup as every other share.*/routeUrl(url: string): void;+ /**+ * Resolves once cold-start URL delivery has settled — the settle SOURCE the+ * boot coordinator (`resolveBootRestoreDecision`) awaits before reading+ * `urlLaunchOwnsWindow`. Resolves on WHICHEVER comes first: a launch-claiming+ * URL flipping the flag (early resolve — a URL launch pays ~0 wait) OR a+ * bounded grace window elapsing (`URL_LAUNCH_SETTLE_GRACE_MS`, armed at+ * `whenReady` — the safety net for a late Apple Event). Off macOS, or when the+ * launch is already claimed before this is awaited, it resolves immediately.+ */+ waitForUrlLaunchSettled(): Promise<void>;}/**@@ -745,6 +762,19 @@ const SHARE_DEDUP_WINDOW_MS = 10_000;const QUEUE_FLUSH_MAX_ATTEMPTS = 10;const QUEUE_FLUSH_INTERVAL_MS = 500;+/**+ * Bounded grace the cold-start boot path waits before committing the default+ * boot-restore window, so a macOS `open-url` Apple Event that lands slightly+ * after `whenReady` still flips `urlLaunchOwnsWindow` in time to suppress it.+ * Armed at `whenReady` so it overlaps `migrateLegacyUserDataDir` + `runBootstrap`+ * — on a normal no-URL cold start bootstrap usually exhausts it, so the marginal+ * added delay is typically ~0; a launch-claiming URL early-resolves it. A+ * calibration knob: larger values catch later Apple Events at the cost of more+ * no-URL delay. The residual is inherently unbounded (OS delivery has no upper+ * latency bound), so this narrows the race window rather than closing it.+ */+const URL_LAUNCH_SETTLE_GRACE_MS = 250;+/*** Wire `open-url` + `second-instance` handlers synchronously. Call from the* main-process entry BEFORE `app.whenReady()` — on macOS the `open-url` Apple@@ -757,6 +787,7 @@ const QUEUE_FLUSH_INTERVAL_MS = 500;*/export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHandlerControl {const schedule = deps.setTimeout ?? ((cb, ms) => setTimeout(cb, ms));+ const platform = deps.platform ?? process.platform;const urlQueue: string[] = [];// Canonical-sharedUrl → last-routed timestamp, for SHARE_DEDUP_WINDOW_MS// near-simultaneous-duplicate suppression (deferred redemption vs splash@@ -776,6 +807,23 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand// Superset of `singleFileLaunch`; same sticky/never-reset rationale.let urlLaunchOwnsWindow = false;+ // Cold-start settle barrier (the source `waitForUrlLaunchSettled` exposes).+ // Resolves once — on the flag flip (a launch-claiming URL arrived) or the+ // grace window elapsing at `whenReady`, whichever comes first. Created eagerly+ // so `settleResolve` is bound synchronously before any `open-url` listener can+ // fire; idempotent via the `settled` guard.+ let settled = false;+ let settleResolve: (() => void) | null = null;+ const settlePromise = new Promise<void>((res) => {+ settleResolve = res;+ });+ const settleNow = (): void => {+ if (settled) return;+ settled = true;+ settleResolve?.();+ settleResolve = null;+ };+// Dev-mode registration — unpackaged Electron's Info.plist belongs to the// Electron.app shell, not this app, so Launch Services has no binding.// `setAsDefaultProtocolClient` writes a runtime binding so `open@@ -1227,6 +1275,10 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand// double-parse pattern as the single-file branch above.if (isSingleFile || parseShareUrl(url)?.kind === 'ok') {urlLaunchOwnsWindow = true;+ // A launch-claiming URL arrived — early-resolve the cold-start settle+ // barrier so the boot path commits its (suppressed-window) decision now,+ // rather than waiting out the full grace window.+ settleNow();}if (flushed) {routeUrl(url);@@ -1311,6 +1363,14 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand// booting would either crash or vanish; the 10 × 500ms retry is the VS// Code `ElectronURLListener` convention.void deps.app.whenReady().then(() => {+ // Arm the bounded cold-start settle grace (darwin only — off macOS there is+ // no Apple Event, so settle resolves immediately without a timer). If no+ // launch-claiming URL flips the flag before it elapses, `settleNow` releases+ // the boot path to its normal `lastOpenedProject` restore. Uses the same+ // injectable `schedule` as the flush loop, so tests fire it deterministically.+ if (platform === 'darwin') {+ schedule(() => settleNow(), URL_LAUNCH_SETTLE_GRACE_MS);+ }const tryFlush = (attempt: number): void => {if (urlQueue.length === 0 || deps.getAnyReadyWindow()) {drainAll();@@ -1335,5 +1395,14 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand// the empty queue; otherwise drains immediately for the suppress path.drainQueuedUrls: () => drainAll(),routeUrl: (url) => enqueueOrRoute(url),+ waitForUrlLaunchSettled: () => {+ // Non-darwin: no Apple Event exists (argv is scanned synchronously before+ // `whenReady`), so there is nothing to wait for.+ if (platform !== 'darwin') return Promise.resolve();+ // The launch is already claimed — a URL flipped the flag before the boot+ // path awaited settle, so commit immediately without a grace wait.+ if (urlLaunchOwnsWindow) return Promise.resolve();+ return settlePromise;+ },};}diff --git a/packages/desktop/tests/main/url-scheme-handler.test.ts b/packages/desktop/tests/main/url-scheme-handler.test.tsindex a14f6215d..edd4935a4 100644--- a/packages/desktop/tests/main/url-scheme-handler.test.ts+++ b/packages/desktop/tests/main/url-scheme-handler.test.ts@@ -435,6 +435,10 @@ describe('registerProtocolHandler — queue-then-flush', () => {sendDeepLink: env.sendDeepLink,getAnyReadyWindow: env.getAnyReadyWindow,setTimeout: (cb, ms) => env.timers.push({ cb, ms }),+ // Pin non-darwin so the darwin-only cold-start settle grace does not arm+ // an extra timer in this shared queue — the flush-retry loop under test is+ // platform-independent; the grace behavior is covered by the settle suite.+ platform: 'linux',});env.app.fireOpenUrl('openknowledge://open?project=/tmp/p&doc=a.md');env.app.resolveReady();@@ -635,6 +639,10 @@ describe('registerProtocolHandler — single-file launch control', () => {sendDeepLink: env.sendDeepLink,getAnyReadyWindow: env.getAnyReadyWindow,setTimeout: (cb, ms) => env.timers.push({ cb, ms }),+ // Pin non-darwin so the darwin-only cold-start settle grace does not arm+ // an extra timer in this shared queue — the suppress-path drain under test+ // is platform-independent; the grace behavior is covered by the settle suite.+ platform: 'linux',});env.app.fireOpenUrl(FILE_URL);env.app.resolveReady();