Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

perf(desktop): unify main window loading and avoid cold-resume offline flash

shoudi zheng4d60b47acd23
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index 54435338..e78578d0 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -284,6 +284,25 @@ Gateway and runs Agents. The daemon exits with the app.
Dock, the tray) shows setup until the computer is enrolled
(`app-window.ts`), the main window after. The main window's server form
without a server says Back to Setup instead of Cancel.
+ Main window loading policy (`windowLoadDecision` in `src/main/navigation.ts`):
+ all server loads (`boot`, `local_ready`, `resume_ready`, `server_changed`,
+ `port_moved`, `retry`, `prewarm`) pass through one decision helper so
+ duplicate `loadURL` calls on hot start are skipped when the target origin is
+ already loaded or pending without a shell page or load failure. `BaseWindow`
+ is created with `show: false` and revealed on the first `did-finish-load` or
+ `did-fail-load` after `show()`, with a short 1500 ms timeout fallback so a
+ stalled load still reveals the window; `preloadAuthenticated` loads the
+ enrolled server in the hidden window without showing it, and `prewarmAssets`
+ warms `/` and `/assets/*` in `session.defaultSession`'s HTTP cache. On
+ launch the window loads `serverUrl` without a blocking HTTP probe; if
+ `did-fail-load` fires and `localServer.resumable(serverUrl)` sees an active
+ resume or a valid matching `local-server.json`, it shows the
+ Starting page instead of `offline.html`. `window.did_finish_load` logs
+ `{ reason, duration_ms, target }` with origin + pathname only (never query or
+ hash), and `LocalServer` resume emits `local_server.resume_started`,
+ `local_server.resume_stage` (`stage`, `ms`), `local_server.resume_succeeded`
+ (`total_ms`), and `local_server.resume_failed` (`stage`, `total_ms`,
+ redacted `error` bounded to 500 chars with query/hash stripped).
- `src/shell/*.html`: app-owned pages (title bar, offline/setup page). They
have no network access and talk to the main process via `src/preload/shell.ts`.
- `src/preload/index.ts`: the only SPA API, `window.lingerDesktop`. Its
diff --git a/apps/desktop/src/main/enrollment.test.ts b/apps/desktop/src/main/enrollment.test.ts
index fde34508..363aa200 100644
--- a/apps/desktop/src/main/enrollment.test.ts
+++ b/apps/desktop/src/main/enrollment.test.ts
@@ -393,6 +393,7 @@ describe("EnrollmentModule", () => {
serverOverrides: ServerOverrides = {},
initialServerUrl = "https://linger.example.com",
initialConfig: Partial<DesktopConfig> = {},
+ ensureDefault: () => Promise<void> = async () => {},
) => {
const dir = tempDirectory();
const daemonIdentityFile = path.join(dir, "daemon-identity.json");
@@ -408,7 +409,14 @@ describe("EnrollmentModule", () => {
fetch: server.fetch,
});
const host = testHost(
- [stubModule("Config"), enrollment],
+ [
+ stubModule("Config"),
+ {
+ ...stubModule("WorkspaceGrants", ["Config"]),
+ ensureDefault,
+ } as never,
+ enrollment,
+ ],
{ serverUrl: initialServerUrl, ...initialConfig },
bus,
);
@@ -609,4 +617,25 @@ describe("EnrollmentModule", () => {
).toBeUndefined();
await host.stop("quit");
});
+
+ it("ensures default workspace grant before emitting computer.changed", async () => {
+ const order: string[] = [];
+ const { enrollment, host, bus } = setupModule(
+ {},
+ "https://linger.example.com",
+ {},
+ async () => {
+ order.push("ensureDefault");
+ },
+ );
+ bus.on("computer.changed", (computerId) => {
+ if (computerId) order.push("computer.changed");
+ });
+
+ await host.start();
+ await enrollment.enroll();
+
+ expect(order).toEqual(["ensureDefault", "computer.changed"]);
+ await host.stop("quit");
+ });
});
diff --git a/apps/desktop/src/main/enrollment.ts b/apps/desktop/src/main/enrollment.ts
index 398282fb..f61a07ec 100644
--- a/apps/desktop/src/main/enrollment.ts
+++ b/apps/desktop/src/main/enrollment.ts
@@ -6,6 +6,7 @@ import type { components } from "@linger/wire-contracts/teamhub-public/types";
import type { CredentialStore } from "./computer-credential.js";
import type { SavedEnrollment } from "./config.js";
import type { Module, ModuleContext } from "./modules.js";
+import type { WorkspaceGrantsModule } from "./workspace-grants.js";
type Schemas = components["schemas"];
type CreateRequest = Schemas["LocalComputerEnrollmentCreateRequest"];
@@ -557,6 +558,9 @@ export class EnrollmentModule implements Module {
daemonId: enrolled.daemonId,
...(nextSaved ? { savedEnrollments: nextSaved } : {}),
});
+ // Populate the default workspace grant before emitting computer.changed
+ // so the daemon starts with workspace_grants ready for first-online setup.
+ await ctx.get<WorkspaceGrantsModule>("WorkspaceGrants").ensureDefault();
ctx.bus.emit("computer.changed", enrolled.computerId);
ctx.log.info("enrollment.completed", { computer_id: enrolled.computerId });
return { computerId: enrolled.computerId };
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index b1220d56..4d31186f 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -139,38 +139,8 @@ async function main(): Promise<void> {
log,
);
- // Until this computer is connected, the setup window comes first.
- const needsSetup = !config.get().computerId;
- const windows = new WindowManagerModule({
- preload: path.join(here, "../preload/index.cjs"),
- shellPreload: path.join(here, "../preload/shell.cjs"),
- background: background || needsSetup,
- });
- const setup = new SetupWindowModule({
- preload: path.join(here, "../preload/setup.cjs"),
- version: VERSION,
- defaultDisplayName,
- show: !background && needsSetup,
- loginItem: {
- get: () => app.getLoginItemSettings().openAtLogin,
- set: (on) =>
- app.setLoginItemSettings({ openAtLogin: on, args: ["--background"] }),
- },
- ...(process.platform === "darwin"
- ? {
- permissions: new MacPermissions({
- home: app.getPath("home"),
- asked: () => config.get().permissionsAsked,
- markAsked: (id) => {
- const asked = config.get().permissionsAsked;
- if (!asked.includes(id))
- config.update({ permissionsAsked: [...asked, id] });
- },
- }),
- }
- : {}),
- });
- const status = new StatusModule();
+ // The default LINGER_HOME of the installer.
+ const home = lingerHome();
// The cookie header of the window's session for a server.
const webSessionCookie = async (
serverUrl: string,
@@ -182,8 +152,6 @@ async function main(): Promise<void> {
? cookies.map((c) => `${c.name}=${c.value}`).join("; ")
: undefined;
};
- // The default LINGER_HOME of the installer.
- const home = lingerHome();
const localServer = new LocalServerModule({
home,
version: VERSION,
@@ -205,6 +173,39 @@ async function main(): Promise<void> {
sessionCookie: webSessionCookie,
openExternal: (url) => shell.openExternal(url),
});
+ // Until this computer is connected, the setup window comes first.
+ const needsSetup = !config.get().computerId;
+ const windows = new WindowManagerModule({
+ preload: path.join(here, "../preload/index.cjs"),
+ shellPreload: path.join(here, "../preload/shell.cjs"),
+ background: background || needsSetup,
+ localServerResumable: (url) => localServer.resumable(url),
+ });
+ const setup = new SetupWindowModule({
+ preload: path.join(here, "../preload/setup.cjs"),
+ version: VERSION,
+ defaultDisplayName,
+ show: !background && needsSetup,
+ loginItem: {
+ get: () => app.getLoginItemSettings().openAtLogin,
+ set: (on) =>
+ app.setLoginItemSettings({ openAtLogin: on, args: ["--background"] }),
+ },
+ ...(process.platform === "darwin"
+ ? {
+ permissions: new MacPermissions({
+ home: app.getPath("home"),
+ asked: () => config.get().permissionsAsked,
+ markAsked: (id) => {
+ const asked = config.get().permissionsAsked;
+ if (!asked.includes(id))
+ config.update({ permissionsAsked: [...asked, id] });
+ },
+ }),
+ }
+ : {}),
+ });
+ const status = new StatusModule();
// Set once the bundle was swapped, so quitting relaunches the new version.
let relaunch = false;
// Set once the setup program of an update runs; it starts the new version.
diff --git a/apps/desktop/src/main/local-server-resume.test.ts b/apps/desktop/src/main/local-server-resume.test.ts
new file mode 100644
index 00000000..3aace3ac
--- /dev/null
+++ b/apps/desktop/src/main/local-server-resume.test.ts
@@ -0,0 +1,200 @@
+import { mkdirSync, symlinkSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+import { describe, expect, it, vi } from "vitest";
+
+import { NODE_RUNTIME_VERSION } from "../../../../scripts/local-computer-node-distributions.mjs";
+import { ConfigStore } from "./config.js";
+import { LocalServerModule } from "./local-server.js";
+import { EventBus, ModuleHost } from "./modules.js";
+import { stubModule, tempDirectory } from "./test-support.js";
+
+function setupResumeFixture(installerScript: string) {
+ const root = tempDirectory();
+ const home = path.join(root, "home");
+ const installerDirectory = path.join(root, "installer");
+ mkdirSync(installerDirectory, { recursive: true });
+ writeFileSync(path.join(installerDirectory, "installer.js"), installerScript);
+ writeFileSync(
+ path.join(installerDirectory, "package.json"),
+ '{"type":"commonjs"}',
+ );
+ const node = path.join(home, "desktop", "node", `v${NODE_RUNTIME_VERSION}`);
+ mkdirSync(path.join(node, "bin"), { recursive: true });
+ symlinkSync(process.execPath, path.join(node, "bin", "node"));
+ mkdirSync(path.join(home, "desktop"), { recursive: true });
+ writeFileSync(
+ path.join(home, "desktop", "local-server.json"),
+ JSON.stringify({
+ home,
+ repo: "/source",
+ origin: "http://localhost:3000",
+ }),
+ );
+
+ const logs: Array<{
+ level: string;
+ event: string;
+ fields?: Record<string, unknown>;
+ }> = [];
+ const setServer = vi.fn(() => true);
+ const showStarting = vi.fn();
+ const showUpdating = vi.fn();
+ const showStartFailed = vi.fn();
+ const bus = new EventBus();
+ const config = new ConfigStore(path.join(root, "config.json"), {
+ serverUrl: "http://localhost:3000",
+ computerId: "cmp_1",
+ });
+
+ const module = new LocalServerModule({
+ home,
+ version: "0.16.20",
+ installerDirectory,
+ platform: "linux",
+ arch: "x64",
+ pollMs: 10,
+ signIn: async () => {},
+ fetch: (async () => {
+ throw new Error("offline");
+ }) as typeof fetch,
+ });
+
+ const host = new ModuleHost(
+ [
+ {
+ ...stubModule("WindowManager"),
+ setServer,
+ showStarting,
+ showUpdating,
+ showStartFailed,
+ } as never,
+ stubModule("Enrollment"),
+ module,
+ ],
+ {
+ config,
+ bus,
+ log: {
+ info: (event, fields) => logs.push({ level: "info", event, fields }),
+ warn: (event, fields) => logs.push({ level: "warn", event, fields }),
+ error: (event, fields) => logs.push({ level: "error", event, fields }),
+ },
+ },
+ );
+
+ return {
+ home,
+ module,
+ host,
+ logs,
+ setServer,
+ showStarting,
+ showStartFailed,
+ };
+}
+
+describe("LocalServerModule resume coordination", () => {
+ it("tracks resuming(), passes resume_ready, and emits structured stage logs", async () => {
+ const f = setupResumeFixture(`
+ setTimeout(() => {
+ process.stdout.write(JSON.stringify({ code: 0, details: { origin: "http://localhost:3000" } }) + "\\n");
+ }, 40);
+ `);
+
+ await f.host.start();
+ expect(f.module.resuming()).toBe(true);
+
+ await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));
+ expect(f.module.resuming()).toBe(false);
+ expect(f.showStarting).toHaveBeenCalledOnce();
+ expect(f.setServer).toHaveBeenCalledWith(
+ "http://localhost:3000",
+ "http://localhost:3000",
+ { reason: "resume_ready" },
+ );
+
+ const events = f.logs.map((entry) => entry.event);
+ expect(events).toContain("local_server.resume_started");
+ expect(events).toContain("local_server.resume_succeeded");
+ const stages = f.logs
+ .filter((entry) => entry.event === "local_server.resume_stage")
+ .map((entry) => entry.fields?.stage);
+ expect(stages).toEqual([
+ "fast_ready_check",
+ "ensure_node",
+ "installer_resume",
+ ]);
+
+ const succeeded = f.logs.find(
+ (entry) => entry.event === "local_server.resume_succeeded",
+ );
+ expect(typeof succeeded?.fields?.total_ms).toBe("number");
+ await f.host.stop("quit");
+ });
+
+ it("redacts query, hash, and secrets and bounds resume_failed errors to 500 chars", async () => {
+ const longPadding = "x".repeat(600);
+ const f = setupResumeFixture(`
+ process.stdout.write(JSON.stringify({
+ code: 1,
+ message: "Failed at https://linger.example.com/auth?token=secret123#frag with Bearer super-secret-token-123 ${longPadding}"
+ }) + "\\n");
+ `);
+
+ await f.host.start();
+ await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));
+ expect(f.module.resuming()).toBe(false);
+
+ const failed = f.logs.find(
+ (entry) => entry.event === "local_server.resume_failed",
+ );
+ expect(failed).toBeDefined();
+ expect(failed?.fields?.stage).toBe("installer_resume");
+ expect(typeof failed?.fields?.total_ms).toBe("number");
+ const errorText = String(failed?.fields?.error ?? "");
+ expect(errorText.length).toBeLessThanOrEqual(500);
+ expect(errorText).not.toContain("token=secret123");
+ expect(errorText).not.toContain("#frag");
+ expect(errorText).not.toContain("super-secret-token-123");
+ await f.host.stop("quit");
+ });
+
+ it("reports resumable() true while resuming, true for a valid matching record, and false for malformed or incomplete records", async () => {
+ const f = setupResumeFixture(`
+ setTimeout(() => {
+ process.stdout.write(JSON.stringify({ code: 0, details: { origin: "http://localhost:3000" } }) + "\\n");
+ }, 60);
+ `);
+
+ await f.host.start();
+ expect(f.module.resuming()).toBe(true);
+ await expect(f.module.resumable("http://localhost:9999")).resolves.toBe(
+ true,
+ );
+
+ await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));
+ expect(f.module.resuming()).toBe(false);
+ await expect(
+ f.module.resumable("http://localhost:3000/rooms/1"),
+ ).resolves.toBe(true);
+ await expect(f.module.resumable("http://localhost:3001")).resolves.toBe(
+ false,
+ );
+
+ const recordFile = path.join(f.home, "desktop", "local-server.json");
+ writeFileSync(recordFile, "{not json");
+ await expect(f.module.resumable("http://localhost:3000")).resolves.toBe(
+ false,
+ );
+
+ writeFileSync(
+ recordFile,
+ JSON.stringify({ home: f.home, origin: "http://localhost:3000" }),
+ );
+ await expect(f.module.resumable("http://localhost:3000")).resolves.toBe(
+ false,
+ );
+ await f.host.stop("quit");
+ });
+});
diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts
index bd812df4..b9ca15b1 100644
--- a/apps/desktop/src/main/local-server.test.ts
+++ b/apps/desktop/src/main/local-server.test.ts
@@ -422,6 +422,8 @@ const fixture = (
showStarting,
showStartFailed,
loadServer,
+ prewarmAssets: vi.fn(async () => {}),
+ preloadAuthenticated: vi.fn(),
} as never,
{
...stubModule("Enrollment"),
@@ -676,6 +678,7 @@ describe("LocalServerModule", () => {
expect(f.setServer).toHaveBeenCalledWith(
"http://localhost:3000",
undefined,
+ { reason: "local_ready" },
);
expect(f.enroll).toHaveBeenCalled();
expect(f.module.status()).toMatchObject({
@@ -2105,6 +2108,7 @@ describe("LocalServerModule", () => {
expect(f.setServer).toHaveBeenCalledWith(
"http://localhost:3000",
"http://localhost:2999",
+ { reason: "local_ready" },
);
expect(f.unenroll).not.toHaveBeenCalled();
await f.host.stop("quit");
@@ -2348,6 +2352,7 @@ describe("LocalServerModule after a restart", () => {
expect(f.setServer).toHaveBeenCalledWith(
"http://localhost:3000",
"http://localhost:3000",
+ { reason: "resume_ready" },
);
// The services were down, so the window waited on the starting page.
expect(f.showStarting).toHaveBeenCalledOnce();
@@ -2375,6 +2380,7 @@ describe("LocalServerModule after a restart", () => {
expect(f.setServer).toHaveBeenCalledWith(
"http://localhost:3001",
"http://localhost:3000",
+ { reason: "resume_ready" },
);
expect(f.unenroll).not.toHaveBeenCalled();
expect(
@@ -2585,6 +2591,7 @@ describe("LocalServerModule after a restart", () => {
expect(f.setServer).toHaveBeenCalledWith(
"http://localhost:3000",
"http://localhost:3000",
+ { reason: "resume_ready" },
);
expect(
JSON.parse(
@@ -2833,6 +2840,7 @@ describe("LocalServerModule after a restart", () => {
expect(f.setServer).toHaveBeenCalledWith(
"http://localhost:3000",
"http://localhost:3000",
+ { reason: "resume_ready" },
);
await f.host.stop("quit");
});
@@ -3305,6 +3313,12 @@ describe("LocalServerModule after a restart", () => {
showStarting: vi.fn(),
showStartFailed: vi.fn(),
loadServer: vi.fn(),
+ prewarmAssets: vi.fn(async () => {}),
+ preloadAuthenticated: vi.fn(),
+ } as never,
+ {
+ ...stubModule("WorkspaceGrants", ["Config"]),
+ ensureDefault: vi.fn(async () => {}),
} as never,
enrollment,
module,
diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts
index ee63e2a8..2009f660 100644
--- a/apps/desktop/src/main/local-server.ts
+++ b/apps/desktop/src/main/local-server.ts
@@ -57,6 +57,7 @@ import {
installTeamhubBinaries,
TEAMHUB_BINARY_DIRECTORY,
} from "@linger/local-installation/teamhub-binaries";
+import { redact } from "@linger/local-installation/redaction";
import { adoptUserEnvironment } from "@linger/local-installation/user-environment";
import {
@@ -66,7 +67,11 @@ import {
} from "../../../../scripts/local-computer-node-distributions.mjs";
import type { Logger } from "./log.js";
import type { Module, ModuleContext, StopReason } from "./modules.js";
-import { parseServerUrl, sameOrigin } from "./navigation.js";
+import {
+ type WindowLoadReason,
+ parseServerUrl,
+ sameOrigin,
+} from "./navigation.js";
import { humanTenant, type EnrollmentModule } from "./enrollment.js";
import { compareVersions } from "./update-manifest.js";
import type { WindowManagerModule } from "./window-manager.js";
@@ -419,8 +424,10 @@ export class LocalServerModule implements Module {
// Counts installations started, so the setup page restarts its timers.
#attempt = 0;
#origin: string | undefined;
+ #resuming = false;
#running: Promise<void> | undefined;
#check: LocalModelsCheck = { state: "unchecked" };
+ #checkedAt: number | undefined;
// Read once from the bundled installer's distribution.
#nativePostgres: boolean | undefined;
// Where an installation goes unless the setup page chose another folder:
@@ -577,6 +584,16 @@ export class LocalServerModule implements Module {
}
}
+ resuming(): boolean {
+ return this.#resuming;
+ }
+
+ async resumable(serverUrl: string): Promise<boolean> {
+ if (this.#resuming) return true;
+ const record = await this.#readRecord();
+ return record !== undefined && sameOrigin(record.origin, serverUrl);
+ }
+
status(): LocalServerStatus {
// The services run natively, so the build must carry PostgreSQL for
// this computer.
@@ -655,9 +672,11 @@ export class LocalServerModule implements Module {
)
return;
this.#check = { state: "checking" };
+ this.#checkedAt = undefined;
this.#ctx?.bus.emit("local-server.changed");
const started = Date.now();
const signal = this.#abort.signal;
+ if (!signal.aborted) void this.#ensureNode(signal).catch(() => undefined);
void this.#inspect(signal, (download) => {
if (this.#check.state !== "checking") return;
this.#check = { state: "checking", download };
@@ -677,6 +696,7 @@ export class LocalServerModule implements Module {
...(reasonLog.length ? { reasons: reasonLog } : {}),
});
this.#check = check;
+ this.#checkedAt = Date.now();
},
(error: unknown) => {
this.#ctx?.log.warn("local_server.inspect_failed", {
@@ -684,12 +704,11 @@ export class LocalServerModule implements Module {
error: error instanceof Error ? error.message : String(error),
});
this.#check = { state: "unavailable" };
+ this.#checkedAt = undefined;
},
)
.then(() => {
this.#ctx?.bus.emit("local-server.changed");
- if (!signal.aborted)
- void this.#ensureNode(signal).catch(() => undefined);
});
}
@@ -1010,22 +1029,46 @@ export class LocalServerModule implements Module {
this.#launchInstaller(node, home, repo, signal),
);
const runInstaller = (next: LocalServerPlan, fresh = false) =>
- installer.run(
- next,
- signal,
- (stage, share, text, transfer) =>
- this.#advance(stage, share, text, transfer),
- fresh,
+ this.#timed("installer_job", () =>
+ installer.run(
+ next,
+ signal,
+ (stage, share, text, transfer) =>
+ this.#advance(stage, share, text, transfer),
+ fresh,
+ ),
);
+ // Reuse a fresh non-local recommendation from the setup window check
+ // instead of running a duplicate setup inspection.
+ const inspectedRuntime =
+ plan.runtime === "recommended" &&
+ !plan.byok &&
+ !this.#location &&
+ !keysChanged &&
+ this.#check.state === "checked" &&
+ this.#checkedAt !== undefined &&
+ Date.now() - this.#checkedAt < 60_000 &&
+ this.#check.recommendation &&
+ this.#check.recommendation !== "local-models"
+ ? this.#check.recommendation
+ : undefined;
+ const effectivePlan: LocalServerPlan = inspectedRuntime
+ ? { ...plan, runtime: inspectedRuntime }
+ : plan;
// Changed keys reach the services only when the installation runs
// again, even after one that finished.
- let job = await runInstaller(plan, keysChanged || Boolean(plan.byok));
+ let job = await runInstaller(
+ effectivePlan,
+ keysChanged || Boolean(plan.byok),
+ );
// The runtime is installed but has no sign-in here: the server would
// never create the Another Me, so ask for it now. Another runtime
// reruns the installation for it.
for (;;) {
const nextChoice = job.signInRequired
- ? await this.#awaitSignIn(installer, signal)
+ ? await this.#timed("await_signin", () =>
+ this.#awaitSignIn(installer, signal),
+ )
: undefined;
if (!nextChoice) break;
this.#endSignIn();
@@ -1048,6 +1091,11 @@ export class LocalServerModule implements Module {
true,
);
}
+ // Prewarm main-window assets in the background as soon as the server
+ // origin is known.
+ void this.#ctx
+ ?.get<WindowManagerModule>("WindowManager")
+ .prewarmAssets(job.origin);
// The desktop's Computer runs the runtime this installer set up, with
// its profile, rather than whatever its PATH finds.
const runtime = await installer.runtime();
@@ -1079,7 +1127,9 @@ export class LocalServerModule implements Module {
}
this.#advance("connect", 0, "Connecting this computer…");
const login = await installer.login();
- await this.#signInAs(home, job.origin, login.email, login.password);
+ await this.#timed("sign_in_as", () =>
+ this.#signInAs(home, job.origin, login.email, login.password),
+ );
// The installation this window used in the same location is the same
// server, at another origin when the installer moved its web port.
const previous = await this.#readRecord();
@@ -1097,9 +1147,16 @@ export class LocalServerModule implements Module {
previous?.home === home ? previous.origin : undefined,
);
this.#daemonConnection = undefined;
- await this.#ctx!.get<EnrollmentModule>("Enrollment").enroll();
+ await this.#timed("enroll", () =>
+ this.#ctx!.get<EnrollmentModule>("Enrollment").enroll(),
+ );
+ this.#ctx
+ ?.get<WindowManagerModule>("WindowManager")
+ .preloadAuthenticated(job.origin);
this.#advance("agents", 0, "Preparing your agents…");
- await this.#awaitAgents(job.origin, signal);
+ await this.#timed("await_agents", () =>
+ this.#awaitAgents(job.origin, signal),
+ );
this.#set("ready", "Linger is running on this computer.");
} catch (error) {
this.#endSignIn();
@@ -2170,11 +2227,15 @@ export class LocalServerModule implements Module {
}
// `previous` is the origin this installation answered at before.
- #ready(origin: string, previous?: string): void {
+ #ready(
+ origin: string,
+ previous?: string,
+ reason: WindowLoadReason = "local_ready",
+ ): void {
this.#origin = origin;
this.#ctx
?.get<WindowManagerModule>("WindowManager")
- ?.setServer(origin, previous);
+ ?.setServer(origin, previous, { reason });
}
// The server sets up the Another Me once this computer offers a signed-in
@@ -2301,6 +2362,10 @@ export class LocalServerModule implements Module {
// version, and the older services would serve the older interface.
async #resume(record: LocalRecord, signal: AbortSignal): Promise<void> {
this.#origin = record.origin;
+ this.#resuming = true;
+ const startedAt = Date.now();
+ let stage = "fast_ready_check";
+ this.#ctx?.log.info("local_server.resume_started");
const windows = this.#ctx?.get<WindowManagerModule>("WindowManager");
try {
const update = this.#sourceUpdate(record);
@@ -2311,7 +2376,13 @@ export class LocalServerModule implements Module {
} else {
this.#set("preparing", "Starting Linger on this computer…");
// The window would show the server as unreachable until it is back.
- if (!(await this.#reachable(record.origin))) windows?.showStarting();
+ const checkStartedAt = Date.now();
+ const reachable = await this.#reachable(record.origin);
+ this.#ctx?.log.info("local_server.resume_stage", {
+ stage: "fast_ready_check",
+ ms: Date.now() - checkStartedAt,
+ });
+ if (!reachable) windows?.showStarting();
}
// A source folder the installer no longer runs is unpacked again from
// this app's package: one removed since (by hand, or a cleanup that an
@@ -2326,7 +2397,9 @@ export class LocalServerModule implements Module {
)))
? await this.#ensureSource(record.home, signal)
: record.repo;
- const serving = await this.#runResume(record, repo, signal);
+ const serving = await this.#runResume(record, repo, signal, (next) => {
+ stage = next;
+ });
// The installer moves the web port off one another program took. The
// record and the window follow the origin together (a launch resumes
// only while they agree), and so does this computer's enrollment: it
@@ -2356,14 +2429,23 @@ export class LocalServerModule implements Module {
source: path.basename(repo),
from: record.version,
});
- this.#ready(origin, record.origin);
+ this.#ready(origin, record.origin, "resume_ready");
this.#set("ready", "Linger is running on this computer.");
+ this.#ctx?.log.info("local_server.resume_succeeded", {
+ total_ms: Date.now() - startedAt,
+ });
} catch (error) {
if (signal.aborted) return;
const message = error instanceof Error ? error.message : String(error);
- this.#ctx?.log.warn("local_server.resume_failed", { error: message });
+ this.#ctx?.log.warn("local_server.resume_failed", {
+ stage,
+ total_ms: Date.now() - startedAt,
+ error: this.#formatResumeError(message),
+ });
this.#set("failed", message);
windows?.showStartFailed(message);
+ } finally {
+ this.#resuming = false;
}
}
@@ -2433,9 +2515,18 @@ export class LocalServerModule implements Module {
record: LocalRecord,
repo: string,
signal: AbortSignal,
+ onStage?: (stage: string) => void,
): Promise<{ source?: string; origin?: string }> {
await this.#adoptSourceKeys(record.home);
+ onStage?.("ensure_node");
+ const nodeStartedAt = Date.now();
const node = await this.#ensureNode(signal);
+ this.#ctx?.log.info("local_server.resume_stage", {
+ stage: "ensure_node",
+ ms: Date.now() - nodeStartedAt,
+ });
+ onStage?.("installer_resume");
+ const resumeStartedAt = Date.now();
const outcome = await new Promise<ResumeOutcome>((resolve, reject) => {
const child = spawn(
node,
@@ -2473,6 +2564,10 @@ export class LocalServerModule implements Module {
}
});
});
+ this.#ctx?.log.info("local_server.resume_stage", {
+ stage: "installer_resume",
+ ms: Date.now() - resumeStartedAt,
+ });
if (outcome.code !== 0) {
const { code, reasons } = outcome.details ?? {};
const action =
@@ -2506,6 +2601,14 @@ export class LocalServerModule implements Module {
};
}
+ #formatResumeError(message: string): string {
+ const stripped = message
+ .replace(/(https?:\/\/[^\s?#]+)\?[^\s#]*/g, "$1")
+ .replace(/(https?:\/\/[^\s#]+)#[^\s#]*/g, "$1");
+ const redacted = redact(stripped);
+ return redacted.length > 500 ? `${redacted.slice(0, 497)}...` : redacted;
+ }
+
// Every resume reports the runtime and localmodels tool paths, so an
// install from before the Computer knew one gains it. A change restarts
// the Computer once its running tasks end.
diff --git a/apps/desktop/src/main/navigation.test.ts b/apps/desktop/src/main/navigation.test.ts
index 8ffc65d4..626361c3 100644
--- a/apps/desktop/src/main/navigation.test.ts
+++ b/apps/desktop/src/main/navigation.test.ts
@@ -6,6 +6,7 @@ import {
parseServerUrl,
permissionAllowed,
serverSwitch,
+ windowLoadDecision,
} from "./navigation.js";
const server = "https://linger.example.com";
@@ -134,3 +135,138 @@ describe("framableHeaders", () => {
});
});
});
+
+describe("windowLoadDecision", () => {
+ const local = "http://localhost:3000";
+ const moved = "http://localhost:3001";
+
+ it("loads on initial boot and skips duplicate hot-start loads", () => {
+ expect(
+ windowLoadDecision(
+ { showingShellPage: "none", loadFailed: false },
+ local,
+ local,
+ { reason: "boot" },
+ ),
+ ).toEqual({ action: "load", targetUrl: local, reason: "boot" });
+
+ expect(
+ windowLoadDecision(
+ {
+ pendingTargetOrigin: local,
+ showingShellPage: "none",
+ loadFailed: false,
+ },
+ local,
+ local,
+ { reason: "local_ready" },
+ ),
+ ).toEqual({ action: "noop", reason: "local_ready" });
+
+ expect(
+ windowLoadDecision(
+ {
+ currentUrl: `${local}/rooms/1`,
+ showingShellPage: "none",
+ loadFailed: false,
+ },
+ local,
+ local,
+ { reason: "resume_ready" },
+ ),
+ ).toEqual({ action: "noop", reason: "resume_ready" });
+ });
+
+ it("reloads when recovering from a shell page, failure, or explicit retry", () => {
+ expect(
+ windowLoadDecision(
+ {
+ currentUrl: "app://offline/?starting=1",
+ showingShellPage: "starting",
+ loadFailed: false,
+ },
+ local,
+ local,
+ { reason: "resume_ready" },
+ ),
+ ).toEqual({ action: "load", targetUrl: local, reason: "resume_ready" });
+
+ expect(
+ windowLoadDecision(
+ {
+ currentUrl: `${local}/`,
+ showingShellPage: "none",
+ loadFailed: true,
+ },
+ local,
+ local,
+ { reason: "resume_ready" },
+ ),
+ ).toEqual({ action: "load", targetUrl: local, reason: "resume_ready" });
+
+ expect(
+ windowLoadDecision(
+ {
+ currentUrl: `${local}/`,
+ showingShellPage: "none",
+ loadFailed: false,
+ },
+ local,
+ local,
+ { reason: "retry" },
+ ),
+ ).toEqual({ action: "load", targetUrl: local, reason: "retry" });
+ });
+
+ it("reloads on port move and keeps a user-selected remote server", () => {
+ expect(
+ windowLoadDecision(
+ {
+ currentUrl: `${local}/`,
+ showingShellPage: "none",
+ loadFailed: false,
+ },
+ local,
+ moved,
+ { movedFrom: local },
+ ),
+ ).toEqual({ action: "load", targetUrl: moved, reason: "port_moved" });
+
+ expect(
+ windowLoadDecision(
+ {
+ currentUrl: `${server}/`,
+ showingShellPage: "none",
+ loadFailed: false,
+ },
+ server,
+ moved,
+ { movedFrom: local, reason: "resume_ready" },
+ ),
+ ).toEqual({ action: "noop", reason: "resume_ready" });
+
+ expect(
+ windowLoadDecision(
+ {
+ currentUrl: `${local}/`,
+ showingShellPage: "none",
+ loadFailed: false,
+ },
+ local,
+ server,
+ { reason: "server_changed" },
+ ),
+ ).toEqual({ action: "load", targetUrl: server, reason: "server_changed" });
+ });
+
+ it("rejects invalid origins as noop", () => {
+ expect(
+ windowLoadDecision(
+ { showingShellPage: "none", loadFailed: false },
+ local,
+ "javascript:alert(1)",
+ { reason: "server_changed" },
+ ),
+ ).toEqual({ action: "noop", reason: "server_changed" });
+ });
+});
diff --git a/apps/desktop/src/main/navigation.ts b/apps/desktop/src/main/navigation.ts
index 74601cab..e36d0cca 100644
--- a/apps/desktop/src/main/navigation.ts
+++ b/apps/desktop/src/main/navigation.ts
@@ -37,6 +37,82 @@ export function serverSwitch(
};
}
+export type WindowLoadReason =
+ | "boot"
+ | "local_ready"
+ | "resume_ready"
+ | "server_changed"
+ | "port_moved"
+ | "retry"
+ | "prewarm";
+
+export interface WindowLoadState {
+ readonly currentUrl?: string;
+ readonly pendingTargetOrigin?: string;
+ readonly showingShellPage: "none" | "starting" | "offline" | "start-failed";
+ readonly loadFailed: boolean;
+}
+
+export interface WindowLoadDecision {
+ readonly action: "load" | "noop";
+ readonly targetUrl?: string;
+ readonly reason: WindowLoadReason;
+}
+
+// Decides whether the main window should load `nextOrigin` or treat it as a
+// no-op, avoiding duplicate reloads on hot start while recovering from shell
+// pages or failed loads.
+export function windowLoadDecision(
+ state: WindowLoadState,
+ currentServerUrl: string | undefined,
+ nextOrigin: string,
+ options?: { movedFrom?: string; reason?: WindowLoadReason },
+): WindowLoadDecision {
+ const targetOrigin = parseServerUrl(nextOrigin);
+ const sw = targetOrigin
+ ? serverSwitch(currentServerUrl, targetOrigin, options?.movedFrom)
+ : undefined;
+ const reason: WindowLoadReason =
+ options?.reason ??
+ (sw?.moved &&
+ currentServerUrl !== undefined &&
+ options?.movedFrom !== undefined &&
+ sameOrigin(currentServerUrl, options.movedFrom)
+ ? "port_moved"
+ : "server_changed");
+ if (!targetOrigin) return { action: "noop", reason };
+
+ // Keep the current server when a non-explicit load targets another server,
+ // such as a background local resume while the user is on a remote server.
+ if (
+ currentServerUrl !== undefined &&
+ !sameOrigin(currentServerUrl, targetOrigin) &&
+ reason !== "server_changed" &&
+ reason !== "local_ready" &&
+ !(
+ sw?.moved &&
+ options?.movedFrom !== undefined &&
+ sameOrigin(currentServerUrl, options.movedFrom)
+ )
+ ) {
+ return { action: "noop", reason };
+ }
+
+ if (
+ reason !== "retry" &&
+ !state.loadFailed &&
+ state.showingShellPage === "none" &&
+ ((state.currentUrl !== undefined &&
+ sameOrigin(state.currentUrl, targetOrigin)) ||
+ (state.pendingTargetOrigin !== undefined &&
+ sameOrigin(state.pendingTargetOrigin, targetOrigin)))
+ ) {
+ return { action: "noop", reason };
+ }
+
+ return { action: "load", targetUrl: targetOrigin, reason };
+}
+
export type NavigationDecision = "allow" | "external" | "deny";
// App pages are reachable only from app pages: the server's pages must not
diff --git a/apps/desktop/src/main/setup-window.ts b/apps/desktop/src/main/setup-window.ts
index d7eb778e..6bad886a 100644
--- a/apps/desktop/src/main/setup-window.ts
+++ b/apps/desktop/src/main/setup-window.ts
@@ -349,6 +349,7 @@ export class SetupWindowModule implements Module {
}
case "finish":
this.#window?.close();
+ windows.markOpenFromSetup();
windows.show();
return;
}
diff --git a/apps/desktop/src/main/window-manager.test.ts b/apps/desktop/src/main/window-manager.test.ts
new file mode 100644
index 00000000..03ae98d4
--- /dev/null
+++ b/apps/desktop/src/main/window-manager.test.ts
@@ -0,0 +1,484 @@
+import path from "node:path";
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => {
+ /* eslint-disable @typescript-eslint/no-require-imports */
+ const { EventEmitter } =
+ require("node:events") as typeof import("node:events");
+ /* eslint-enable @typescript-eslint/no-require-imports */
+ const windows: MockBaseWindow[] = [];
+ const views: MockWebContentsView[] = [];
+ const netFetch = vi.fn();
+
+ class MockWebContents extends EventEmitter {
+ readonly id = 1;
+ readonly navigationHistory = {
+ canGoBack: () => false,
+ canGoForward: () => false,
+ goBack: () => {},
+ goForward: () => {},
+ };
+ url = "";
+ loading = false;
+ destroyed = false;
+ readonly loadURL = vi.fn(async (nextUrl: string) => {
+ this.url = nextUrl;
+ this.loading = true;
+ });
+ readonly reload = vi.fn();
+ readonly focus = vi.fn();
+ readonly send = vi.fn();
+ readonly close = vi.fn(() => {
+ this.destroyed = true;
+ });
+ readonly setWindowOpenHandler = vi.fn();
+ getURL(): string {
+ return this.url;
+ }
+ isLoading(): boolean {
+ return this.loading;
+ }
+ isDestroyed(): boolean {
+ return this.destroyed;
+ }
+ }
+
+ class MockWebContentsView {
+ readonly webContents = new MockWebContents();
+ readonly setBackgroundColor = vi.fn();
+ readonly setBounds = vi.fn();
+ constructor() {
+ views.push(this);
+ }
+ }
+
+ class MockBaseWindow extends EventEmitter {
+ readonly contentView = { addChildView: vi.fn() };
+ readonly show = vi.fn(() => {
+ this.visible = true;
+ });
+ readonly hide = vi.fn(() => {
+ this.visible = false;
+ });
+ readonly focus = vi.fn();
+ readonly restore = vi.fn();
+ readonly minimize = vi.fn();
+ readonly maximize = vi.fn();
+ readonly unmaximize = vi.fn();
+ readonly close = vi.fn();
+ readonly destroy = vi.fn(() => {
+ this.destroyed = true;
+ });
+ readonly getContentBounds = () => ({ width: 1280, height: 820 });
+ readonly getNormalBounds = () => ({ x: 0, y: 0, width: 1280, height: 820 });
+ readonly isMinimized = () => false;
+ readonly isMaximized = () => false;
+ readonly isFocused = () => true;
+ readonly isDestroyed = () => this.destroyed;
+ visible: boolean;
+ destroyed = false;
+ readonly options: Record<string, unknown>;
+
+ constructor(options: Record<string, unknown>) {
+ super();
+ this.options = options;
+ this.visible = options.show !== false;
+ windows.push(this);
+ }
+ }
+
+ return { windows, views, netFetch, MockBaseWindow, MockWebContentsView };
+});
+
+vi.mock("electron", () => ({
+ BaseWindow: state.MockBaseWindow,
+ WebContentsView: state.MockWebContentsView,
+ ipcMain: {
+ handle: vi.fn(),
+ on: vi.fn(),
+ removeHandler: vi.fn(),
+ removeAllListeners: vi.fn(),
+ },
+ nativeImage: {
+ createFromBuffer: vi.fn(() => ({})),
+ },
+ net: {
+ fetch: (...args: unknown[]) => state.netFetch(...args),
+ },
+ protocol: {
+ registerSchemesAsPrivileged: vi.fn(),
+ handle: vi.fn(),
+ unhandle: vi.fn(),
+ },
+ session: {
+ defaultSession: {
+ setPermissionRequestHandler: vi.fn(),
+ setPermissionCheckHandler: vi.fn(),
+ webRequest: { onHeadersReceived: vi.fn() },
+ },
+ },
+ shell: {
+ openExternal: vi.fn(async () => {}),
+ },
+}));
+
+vi.mock("../../resources/icon.png", () => ({
+ default: new Uint8Array([1, 2]),
+}));
+vi.mock("../shell/offline.html", () => ({ default: "<html>offline</html>" }));
+vi.mock("../shell/titlebar.html", () => ({ default: "<html>title</html>" }));
+
+import { ConfigStore } from "./config.js";
+import { EventBus, ModuleHost, type Module } from "./modules.js";
+import { tempDirectory } from "./test-support.js";
+import { WindowManagerModule } from "./window-manager.js";
+
+const flush = (): Promise<void> =>
+ new Promise((resolve) => setImmediate(resolve));
+
+function setup(
+ configPatch: Record<string, unknown> = {},
+ options: {
+ background?: boolean;
+ localServerResumable?: (serverUrl: string) => Promise<boolean>;
+ } = {},
+) {
+ const logs: Array<{
+ level: string;
+ event: string;
+ fields?: Record<string, unknown>;
+ }> = [];
+ const bus = new EventBus();
+ const config = new ConfigStore(
+ path.join(tempDirectory(), "config.json"),
+ configPatch,
+ );
+ const diagnosticsStub: Module = {
+ name: "Diagnostics",
+ dependsOn: [],
+ start: async () => {},
+ stop: async () => {},
+ };
+ Object.assign(diagnosticsStub, { uploadUrl: () => undefined });
+ const manager = new WindowManagerModule({
+ preload: "/preload.cjs",
+ shellPreload: "/shell.cjs",
+ background: options.background ?? false,
+ ...(options.localServerResumable
+ ? { localServerResumable: options.localServerResumable }
+ : {}),
+ });
+ const host = new ModuleHost(
+ [
+ {
+ name: "Config",
+ dependsOn: [],
+ start: async () => {},
+ stop: async () => {},
+ },
+ diagnosticsStub,
+ manager,
+ ],
+ {
+ config,
+ bus,
+ log: {
+ info: (event, fields) => logs.push({ level: "info", event, fields }),
+ warn: (event, fields) => logs.push({ level: "warn", event, fields }),
+ error: (event, fields) => logs.push({ level: "error", event, fields }),
+ },
+ },
+ );
+ return { manager, host, config, bus, logs };
+}
+
+function contentView() {
+ return state.views.at(-1)!;
+}
+
+describe("WindowManagerModule", () => {
+ beforeEach(() => {
+ state.windows.length = 0;
+ state.views.length = 0;
+ state.netFetch.mockReset();
+ });
+
+ it("skips duplicate loadURL on hot start when local_ready matches boot origin", async () => {
+ const local = "http://localhost:3000";
+ const { manager, host } = setup({ serverUrl: local });
+ await host.start();
+
+ const content = contentView().webContents;
+ expect(content.loadURL).toHaveBeenCalledTimes(1);
+ expect(content.loadURL).toHaveBeenCalledWith(local);
+
+ manager.setServer(local, undefined, { reason: "local_ready" });
+ await flush();
+ expect(content.loadURL).toHaveBeenCalledTimes(1);
+ await host.stop("quit");
+ });
+
+ it("shows starting instead of offline on cold resume failure and reloads once ready", async () => {
+ const local = "http://localhost:3000";
+ const { manager, host } = setup(
+ { serverUrl: local },
+ { localServerResumable: async () => true },
+ );
+ await host.start();
+
+ const content = contentView().webContents;
+ expect(content.loadURL).toHaveBeenCalledTimes(1);
+
+ content.emit(
+ "did-fail-load",
+ {},
+ -102,
+ "ERR_CONNECTION_REFUSED",
+ local,
+ true,
+ );
+ await flush();
+ expect(content.loadURL).toHaveBeenCalledTimes(2);
+ expect(content.loadURL).toHaveBeenLastCalledWith(
+ "app://offline/?starting=1",
+ );
+
+ manager.setServer(local, local, { reason: "resume_ready" });
+ await flush();
+ expect(content.loadURL).toHaveBeenCalledTimes(3);
+ expect(content.loadURL).toHaveBeenLastCalledWith(local);
+ await host.stop("quit");
+ });
+
+ it("reloads on port move and keeps a user-selected remote server", async () => {
+ const local = "http://localhost:3000";
+ const moved = "http://localhost:3001";
+ const remote = "https://remote.example.com";
+ const { manager, host, bus, config } = setup({ serverUrl: local });
+ const movedListener = vi.fn();
+ bus.on("server.moved", movedListener);
+ await host.start();
+
+ const content = contentView().webContents;
+ content.loading = false;
+ content.emit("did-finish-load");
+
+ manager.setServer(moved, local, { reason: "resume_ready" });
+ await flush();
+ expect(movedListener).toHaveBeenCalledWith(local, moved);
+ expect(config.get().serverUrl).toBe(moved);
+ expect(content.loadURL).toHaveBeenLastCalledWith(moved);
+
+ manager.setServer(remote, undefined, { reason: "server_changed" });
+ await flush();
+ expect(config.get().serverUrl).toBe(remote);
+ expect(content.loadURL).toHaveBeenLastCalledWith(remote);
+
+ const loadsBefore = content.loadURL.mock.calls.length;
+ manager.setServer(moved, local, { reason: "resume_ready" });
+ await flush();
+ expect(config.get().serverUrl).toBe(remote);
+ expect(content.loadURL).toHaveBeenCalledTimes(loadsBefore);
+ await host.stop("quit");
+ });
+
+ it("reloads on retry after start-failed or remote offline failure", async () => {
+ const remote = "https://remote.example.com";
+ const { manager, host } = setup(
+ { serverUrl: remote },
+ { localServerResumable: async () => false },
+ );
+ await host.start();
+
+ const content = contentView().webContents;
+ content.emit(
+ "did-fail-load",
+ {},
+ -105,
+ "ERR_NAME_NOT_RESOLVED",
+ remote,
+ true,
+ );
+ await flush();
+ expect(content.loadURL).toHaveBeenLastCalledWith(
+ `app://offline/?server=${encodeURIComponent(remote)}&error=ERR_NAME_NOT_RESOLVED`,
+ );
+
+ manager.loadServer("retry");
+ expect(content.loadURL).toHaveBeenLastCalledWith(remote);
+
+ manager.showStartFailed("broken");
+ expect(content.loadURL).toHaveBeenLastCalledWith(
+ "app://offline/?failed=broken",
+ );
+
+ manager.loadServer("retry");
+ expect(content.loadURL).toHaveBeenLastCalledWith(remote);
+ await host.stop("quit");
+ });
+
+ it("logs window.did_finish_load without query or hash and records zero setup-to-load when already loaded", async () => {
+ const remote = "https://remote.example.com";
+ const { manager, host, logs } = setup({ serverUrl: remote });
+ await host.start();
+
+ const content = contentView().webContents;
+ content.url = `${remote}/rooms/1?token=secret#frag`;
+ content.loading = false;
+ content.emit("did-finish-load");
+
+ expect(logs).toContainEqual({
+ level: "info",
+ event: "window.did_finish_load",
+ fields: {
+ reason: "boot",
+ duration_ms: expect.any(Number),
+ target: `${remote}/rooms/1`,
+ },
+ });
+
+ manager.markOpenFromSetup();
+ expect(logs).toContainEqual({
+ level: "info",
+ event: "local_server.timing",
+ fields: { step: "open_linger_to_load", ms: 0 },
+ });
+ await host.stop("quit");
+ });
+
+ it("preloads authenticated window hidden and reveals it on show without reloading", async () => {
+ const local = "http://localhost:3000";
+ const { manager, host } = setup(
+ { serverUrl: local, computerId: "cmp_1" },
+ { background: true },
+ );
+ await host.start();
+ expect(state.windows).toHaveLength(0);
+
+ manager.preloadAuthenticated(local);
+ expect(state.windows).toHaveLength(1);
+ const win = state.windows[0]!;
+ expect(win.options.show).toBe(false);
+ expect(win.show).not.toHaveBeenCalled();
+
+ const content = contentView().webContents;
+ expect(content.loadURL).toHaveBeenCalledTimes(1);
+ expect(content.loadURL).toHaveBeenCalledWith(local);
+
+ content.loading = false;
+ content.emit("did-finish-load");
+ expect(win.show).not.toHaveBeenCalled();
+
+ manager.setServer(local, local, { reason: "resume_ready" });
+ await flush();
+ expect(content.loadURL).toHaveBeenCalledTimes(1);
+
+ manager.show();
+ expect(win.show).toHaveBeenCalledTimes(1);
+ expect(content.loadURL).toHaveBeenCalledTimes(1);
+ await host.stop("quit");
+ });
+
+ it("prewarms / and /assets/* static assets and swallows errors", async () => {
+ const local = "http://localhost:3000";
+ const { manager, host } = setup({ serverUrl: local }, { background: true });
+ await host.start();
+
+ state.netFetch.mockImplementation(async (url: string) => {
+ if (url === `${local}/`) {
+ return new Response(
+ '<html><head><link rel="modulepreload" href="/assets/vendor.js"><link href="/assets/app.css" rel="stylesheet"></head><body><script type="module" src="/assets/index.js"></script></body></html>',
+ { status: 200 },
+ );
+ }
+ return new Response(new Uint8Array([1, 2, 3]), { status: 200 });
+ });
+
+ await manager.prewarmAssets(local);
+ expect(state.netFetch.mock.calls.map((c) => c[0])).toEqual([
+ `${local}/`,
+ `${local}/assets/index.js`,
+ `${local}/assets/vendor.js`,
+ `${local}/assets/app.css`,
+ ]);
+
+ state.netFetch.mockRejectedValueOnce(new Error("offline"));
+ await expect(manager.prewarmAssets(local)).resolves.toBeUndefined();
+ await host.stop("quit");
+ });
+
+ it("registers no ready-to-show listener on BaseWindow and reveals on did-finish-load", async () => {
+ const remote = "https://remote.example.com";
+ const { host } = setup({ serverUrl: remote });
+ await host.start();
+
+ const win = state.windows[0]!;
+ expect(win.listenerCount("ready-to-show")).toBe(0);
+ expect(win.show).not.toHaveBeenCalled();
+
+ const content = contentView().webContents;
+ content.loading = false;
+ content.emit("did-finish-load");
+
+ expect(win.show).toHaveBeenCalledTimes(1);
+ expect(win.focus).toHaveBeenCalledTimes(1);
+
+ // Subsequent loads do not re-reveal the window.
+ content.emit("did-finish-load");
+ expect(win.show).toHaveBeenCalledTimes(1);
+ await host.stop("quit");
+ });
+
+ it("reveals the hidden window on did-fail-load without waiting for fallback load", async () => {
+ const remote = "https://remote.example.com";
+ const { host } = setup(
+ { serverUrl: remote },
+ { localServerResumable: async () => false },
+ );
+ await host.start();
+
+ const win = state.windows[0]!;
+ expect(win.show).not.toHaveBeenCalled();
+
+ const content = contentView().webContents;
+ content.emit(
+ "did-fail-load",
+ {},
+ -105,
+ "ERR_NAME_NOT_RESOLVED",
+ remote,
+ true,
+ );
+
+ expect(win.show).toHaveBeenCalledTimes(1);
+ expect(win.focus).toHaveBeenCalledTimes(1);
+
+ await flush();
+ content.emit("did-finish-load");
+ expect(win.show).toHaveBeenCalledTimes(1);
+ await host.stop("quit");
+ });
+
+ it("reveals the hidden window via timeout fallback when load stalls", async () => {
+ vi.useFakeTimers();
+ try {
+ const remote = "https://slow.example.com";
+ const { host } = setup({ serverUrl: remote });
+ await host.start();
+
+ const win = state.windows[0]!;
+ expect(win.show).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(1_499);
+ expect(win.show).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(1);
+ expect(win.show).toHaveBeenCalledTimes(1);
+ expect(win.focus).toHaveBeenCalledTimes(1);
+ await host.stop("quit");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/window-manager.ts b/apps/desktop/src/main/window-manager.ts
index 4b069585..a7c97550 100644
--- a/apps/desktop/src/main/window-manager.ts
+++ b/apps/desktop/src/main/window-manager.ts
@@ -3,6 +3,7 @@ import {
WebContentsView,
ipcMain,
nativeImage,
+ net,
protocol,
session,
shell,
@@ -27,12 +28,15 @@ import type { Module, ModuleContext } from "./modules.js";
import {
OFFLINE_ORIGIN,
SHELL_ORIGIN,
+ type WindowLoadReason,
+ type WindowLoadState,
framableHeaders,
navigationDecision,
parseServerUrl,
permissionAllowed,
sameOrigin,
serverSwitch,
+ windowLoadDecision,
} from "./navigation.js";
// Must run before app "ready".
@@ -46,9 +50,11 @@ export interface WindowManagerOptions {
readonly preload: string;
readonly shellPreload: string;
readonly background: boolean;
+ readonly localServerResumable?: (serverUrl: string) => Promise<boolean>;
}
const TITLEBAR_HEIGHT = 40;
+const REVEAL_FALLBACK_MS = 1_500;
const CANVAS = "#f6f6f6";
const COMMANDS = new Set<ShellCommand>([
"back",
@@ -91,6 +97,35 @@ const html = (body: string): Response =>
const drawsTitlebar = (platform: NodeJS.Platform): boolean =>
platform !== "darwin";
+// Strip query and hash so tokens or room fragments never reach logs.
+const sanitizeTargetUrl = (rawUrl: string): string => {
+ try {
+ const parsed = new URL(rawUrl);
+ return `${parsed.origin}${parsed.pathname}`;
+ } catch {
+ return "";
+ }
+};
+
+const ASSET_SCRIPT_RE = /<script\b[^>]*\bsrc=["'](\/assets\/[^"']+)["']/gi;
+const ASSET_LINK_RE = /<link\b[^>]*>/gi;
+const LINK_REL_RE = /\brel=["'](?:modulepreload|stylesheet)["']/i;
+const LINK_HREF_RE = /\bhref=["'](\/assets\/[^"']+)["']/i;
+
+const extractAssetPaths = (documentHtml: string): string[] => {
+ const paths = new Set<string>();
+ for (const match of documentHtml.matchAll(ASSET_SCRIPT_RE)) {
+ if (match[1]) paths.add(match[1]);
+ }
+ for (const match of documentHtml.matchAll(ASSET_LINK_RE)) {
+ const tag = match[0];
+ if (!LINK_REL_RE.test(tag)) continue;
+ const href = LINK_HREF_RE.exec(tag)?.[1];
+ if (href) paths.add(href);
+ }
+ return [...paths];
+};
+
// The main window. Native window controls stay native (macOS
// traffic lights, the Windows caption overlay); Linux gets drawn controls.
// Closing hides the window; the tray keeps the app running.
@@ -103,6 +138,14 @@ export class WindowManagerModule implements Module {
#titlebar: WebContentsView | undefined;
#content: WebContentsView | undefined;
#quitting = false;
+ #openFromSetupAt: number | undefined;
+ #pendingTargetOrigin: string | undefined;
+ #showingShellPage: WindowLoadState["showingShellPage"] = "none";
+ #loadFailed = false;
+ #loadStartedAt: number | undefined;
+ #lastLoadReason: WindowLoadReason | undefined;
+ #pendingShow = false;
+ #revealTimer: NodeJS.Timeout | undefined;
readonly #unsubscribe: (() => void)[] = [];
constructor(options: WindowManagerOptions) {
@@ -132,6 +175,7 @@ export class WindowManagerModule implements Module {
async stop(): Promise<void> {
this.#quitting = true;
+ this.#clearRevealTimer();
for (const off of this.#unsubscribe.splice(0)) off();
protocol.unhandle("app");
this.#window?.destroy();
@@ -151,18 +195,94 @@ export class WindowManagerModule implements Module {
return this.#content?.webContents;
}
+ markOpenFromSetup(): void {
+ const contents = this.#content?.webContents;
+ const target = this.#serverUrl();
+ if (
+ target &&
+ contents &&
+ !contents.isDestroyed() &&
+ !contents.isLoading() &&
+ sameOrigin(contents.getURL(), target)
+ ) {
+ this.#openFromSetupAt = undefined;
+ this.#ctx?.log.info("local_server.timing", {
+ step: "open_linger_to_load",
+ ms: 0,
+ });
+ return;
+ }
+ this.#openFromSetupAt = Date.now();
+ }
+
show(): void {
if (this.#window) {
+ this.#pendingShow = false;
+ this.#clearRevealTimer();
if (this.#window.isMinimized()) this.#window.restore();
this.#window.show();
this.#window.focus();
return;
}
+ this.#pendingShow = true;
+ this.#ensureWindow();
+ this.#scheduleRevealFallback();
+ this.#loadConfiguredServer("boot");
+ this.#content?.webContents.focus();
+ }
+
+ // Warms the default session HTTP cache with `/` HTML and `/assets/*` bundles
+ // without mutating cookies or mounting a DOM.
+ async prewarmAssets(origin: string): Promise<void> {
+ const base = parseServerUrl(origin);
+ if (!base) return;
+ try {
+ const response = await net.fetch(`${base}/`, {
+ credentials: "omit",
+ });
+ if (!response.ok) return;
+ const assets = extractAssetPaths(await response.text());
+ await Promise.allSettled(
+ assets.map(async (assetPath) => {
+ const assetResponse = await net.fetch(
+ new URL(assetPath, base).toString(),
+ {
+ credentials: "omit",
+ },
+ );
+ await assetResponse.arrayBuffer();
+ }),
+ );
+ } catch {
+ // Best-effort cache warming; failures do not affect window loading.
+ }
+ }
+
+ // Creates the hidden window and loads the enrolled server in the background
+ // so opening the main window reveals an already-rendered SPA immediately.
+ preloadAuthenticated(origin: string): void {
+ const serverUrl = this.#serverUrl();
+ if (
+ !serverUrl ||
+ !sameOrigin(serverUrl, origin) ||
+ !this.#ctx?.config.get().computerId
+ )
+ return;
+ if (!this.#window) {
+ this.#pendingShow = false;
+ this.#ensureWindow();
+ }
+ this.#navigateToServer(origin, { reason: "prewarm" });
+ }
+
+ #ensureWindow(): void {
+ if (this.#window) return;
const bounds = this.#ctx!.config.get().window;
const window = new BaseWindow({
...(bounds ?? { width: 1280, height: 820 }),
minWidth: 800,
minHeight: 560,
+ show: false,
title: "Linger",
backgroundColor: CANVAS,
icon: nativeImage.createFromBuffer(Buffer.from(iconPng)),
@@ -218,6 +338,8 @@ export class WindowManagerModule implements Module {
if (titlebar) this.#guardTitlebar(titlebar.webContents);
this.#guardContent(content.webContents);
window.on("close", (event) => {
+ this.#pendingShow = false;
+ this.#clearRevealTimer();
const { x, y, width, height } = window.getNormalBounds();
this.#ctx!.config.update({ window: { x, y, width, height } });
if (this.#quitting) return;
@@ -228,17 +350,46 @@ export class WindowManagerModule implements Module {
titlebar?.webContents.close();
content.webContents.close();
if (this.#window === window) {
+ this.#clearRevealTimer();
this.#window = undefined;
this.#titlebar = undefined;
this.#content = undefined;
+ this.#pendingTargetOrigin = undefined;
+ this.#showingShellPage = "none";
+ this.#loadFailed = false;
+ this.#pendingShow = false;
}
});
void titlebar?.webContents
.loadURL(`${SHELL_ORIGIN}/titlebar`)
.catch(() => undefined);
- this.loadServer();
- content.webContents.focus();
+ }
+
+ #scheduleRevealFallback(): void {
+ this.#clearRevealTimer();
+ const timer = setTimeout(() => {
+ this.#revealTimer = undefined;
+ this.#revealIfPending();
+ }, REVEAL_FALLBACK_MS);
+ timer.unref?.();
+ this.#revealTimer = timer;
+ }
+
+ #clearRevealTimer(): void {
+ if (!this.#revealTimer) return;
+ clearTimeout(this.#revealTimer);
+ this.#revealTimer = undefined;
+ }
+
+ #revealIfPending(): void {
+ this.#clearRevealTimer();
+ if (!this.#pendingShow || !this.#window || this.#window.isDestroyed())
+ return;
+ this.#pendingShow = false;
+ if (this.#window.isMinimized()) this.#window.restore();
+ this.#window.show();
+ this.#window.focus();
}
// Points the app at another server; false when the address is invalid.
@@ -246,26 +397,92 @@ export class WindowManagerModule implements Module {
// installer moved this computer's server off a taken port): the window
// follows it as `server.moved`, which keeps this computer's enrollment,
// instead of `server.changed`, which drops it.
- setServer(value: string, movedFrom?: string): boolean {
+ setServer(
+ value: string,
+ movedFrom?: string,
+ options?: { reason?: WindowLoadReason },
+ ): boolean {
const serverUrl = parseServerUrl(value);
if (!serverUrl) return false;
const ctx = this.#ctx!;
const previous = ctx.config.get().serverUrl;
const { moved, changed } = serverSwitch(previous, serverUrl, movedFrom);
+ const reason: WindowLoadReason =
+ options?.reason ?? (moved ? "port_moved" : "server_changed");
+ const decision = windowLoadDecision(
+ this.#loadState(),
+ previous,
+ serverUrl,
+ { ...(movedFrom !== undefined ? { movedFrom } : {}), reason },
+ );
+ if (
+ decision.action === "noop" &&
+ previous !== undefined &&
+ !sameOrigin(previous, serverUrl)
+ ) {
+ return true;
+ }
if (serverUrl !== previous) ctx.config.update({ serverUrl });
if (moved) ctx.bus.emit("server.moved", movedFrom!, serverUrl);
if (changed) ctx.bus.emit("server.changed", serverUrl);
setImmediate(() => {
- this.loadServer();
+ this.#navigateToServer(serverUrl, {
+ ...(movedFrom !== undefined ? { movedFrom } : {}),
+ reason,
+ });
this.#pushState();
});
return true;
}
- loadServer(): void {
+ loadServer(reason: WindowLoadReason = "retry"): void {
+ this.#loadConfiguredServer(reason);
+ }
+
+ #loadConfiguredServer(reason: WindowLoadReason): void {
const serverUrl = this.#serverUrl();
- if (!serverUrl) this.#loadOffline();
- else void this.#content?.webContents.loadURL(serverUrl).catch(() => {});
+ if (!serverUrl) {
+ this.#loadOffline();
+ return;
+ }
+ this.#navigateToServer(serverUrl, { reason });
+ }
+
+ #loadState(): WindowLoadState {
+ const contents = this.#content?.webContents;
+ const currentUrl =
+ contents && !contents.isDestroyed()
+ ? contents.getURL() || undefined
+ : undefined;
+ return {
+ ...(currentUrl ? { currentUrl } : {}),
+ ...(this.#pendingTargetOrigin
+ ? { pendingTargetOrigin: this.#pendingTargetOrigin }
+ : {}),
+ showingShellPage: this.#showingShellPage,
+ loadFailed: this.#loadFailed,
+ };
+ }
+
+ #navigateToServer(
+ targetOrigin: string,
+ options?: { movedFrom?: string; reason?: WindowLoadReason },
+ ): void {
+ const contents = this.#content?.webContents;
+ if (!contents || contents.isDestroyed()) return;
+ const decision = windowLoadDecision(
+ this.#loadState(),
+ this.#serverUrl(),
+ targetOrigin,
+ options,
+ );
+ if (decision.action === "noop" || !decision.targetUrl) return;
+ this.#pendingTargetOrigin = new URL(decision.targetUrl).origin;
+ this.#showingShellPage = "none";
+ this.#loadFailed = false;
+ this.#loadStartedAt = Date.now();
+ this.#lastLoadReason = decision.reason;
+ void contents.loadURL(decision.targetUrl).catch(() => undefined);
}
// While the services on this computer restart on a new version; the
@@ -286,6 +503,9 @@ export class WindowManagerModule implements Module {
}
#loadLocal(mode: "updating" | "starting" | "failed", value: string): void {
+ this.#pendingTargetOrigin = undefined;
+ this.#showingShellPage = mode === "failed" ? "start-failed" : "starting";
+ this.#loadFailed = mode === "failed";
const url = new URL(`${OFFLINE_ORIGIN}/`);
url.searchParams.set(mode, value);
// Send Diagnostics shows only while a diagnostics server is set up.
@@ -304,6 +524,9 @@ export class WindowManagerModule implements Module {
}
#loadOffline(error?: string): void {
+ this.#pendingTargetOrigin = undefined;
+ this.#showingShellPage = "offline";
+ this.#loadFailed = Boolean(error);
const url = new URL(`${OFFLINE_ORIGIN}/`);
const serverUrl = this.#serverUrl();
if (serverUrl) url.searchParams.set("server", serverUrl);
@@ -354,7 +577,7 @@ export class WindowManagerModule implements Module {
break;
case "reload":
if (this.#content?.webContents.getURL().startsWith(OFFLINE_ORIGIN))
- this.loadServer();
+ this.loadServer("retry");
else this.#content?.webContents.reload();
break;
case "minimize":
@@ -395,8 +618,57 @@ export class WindowManagerModule implements Module {
contents.on("did-fail-load", (_event, code, description, url, isMain) => {
// -3 is an aborted load, usually a navigation replacing another.
if (!isMain || code === -3 || url.startsWith(OFFLINE_ORIGIN)) return;
- this.#ctx!.log.warn("window.load_failed", { code, description });
- this.#loadOffline(description);
+ this.#revealIfPending();
+ this.#loadFailed = true;
+ this.#pendingTargetOrigin = undefined;
+ this.#ctx!.log.warn("window.load_failed", {
+ code,
+ description,
+ ...(this.#lastLoadReason ? { reason: this.#lastLoadReason } : {}),
+ });
+ const serverUrl = this.#serverUrl();
+ const check =
+ serverUrl && this.#options.localServerResumable
+ ? this.#options.localServerResumable(serverUrl).catch(() => false)
+ : Promise.resolve(false);
+ void check.then((resumable) => {
+ if (this.#showingShellPage !== "none" || !this.#loadFailed) return;
+ if (resumable) this.showStarting();
+ else this.#loadOffline(description);
+ });
+ });
+ contents.on("did-finish-load", () => {
+ this.#revealIfPending();
+ const loadedUrl = contents.getURL();
+ const isOffline = loadedUrl.startsWith(OFFLINE_ORIGIN);
+ if (!isOffline) {
+ this.#pendingTargetOrigin = undefined;
+ this.#showingShellPage = "none";
+ this.#loadFailed = false;
+ if (this.#lastLoadReason !== undefined) {
+ const durationMs =
+ this.#loadStartedAt !== undefined
+ ? Date.now() - this.#loadStartedAt
+ : 0;
+ const reason = this.#lastLoadReason;
+ this.#loadStartedAt = undefined;
+ this.#lastLoadReason = undefined;
+ this.#ctx?.log.info("window.did_finish_load", {
+ reason,
+ duration_ms: durationMs,
+ target: sanitizeTargetUrl(loadedUrl),
+ });
+ }
+ }
+ if (this.#openFromSetupAt === undefined) return;
+ const target = this.#serverUrl();
+ if (!target || !sameOrigin(loadedUrl, target)) return;
+ const startedAt = this.#openFromSetupAt;
+ this.#openFromSetupAt = undefined;
+ this.#ctx?.log.info("local_server.timing", {
+ step: "open_linger_to_load",
+ ms: Date.now() - startedAt,
+ });
});
for (const event of [
"did-navigate",
diff --git a/apps/desktop/src/main/workspace-grants.test.ts b/apps/desktop/src/main/workspace-grants.test.ts
index 675984a3..524e9234 100644
--- a/apps/desktop/src/main/workspace-grants.test.ts
+++ b/apps/desktop/src/main/workspace-grants.test.ts
@@ -81,4 +81,24 @@ describe("WorkspaceGrantsModule", () => {
expect(grants.list().map((g) => g.grantId)).toEqual(["grant_1"]);
await host.stop("quit");
});
+
+ it("serializes concurrent ensureDefault calls without creating duplicates", async () => {
+ const directory = path.join(tempDirectory(), "Linger");
+ const grants = new WorkspaceGrantsModule({
+ pickDirectory: pickNothing,
+ defaultDirectory: directory,
+ });
+ const host = testHost([stubModule("Config"), grants], {});
+ await host.start();
+
+ await Promise.all([
+ grants.ensureDefault(),
+ grants.ensureDefault(),
+ grants.ensureDefault(),
+ ]);
+
+ expect(grants.list()).toHaveLength(1);
+ expect(grants.list()[0]?.path).toBe(realpathSync(directory));
+ await host.stop("quit");
+ });
});
diff --git a/apps/desktop/src/main/workspace-grants.ts b/apps/desktop/src/main/workspace-grants.ts
index 92d66891..5765c5da 100644
--- a/apps/desktop/src/main/workspace-grants.ts
+++ b/apps/desktop/src/main/workspace-grants.ts
@@ -19,6 +19,7 @@ export class WorkspaceGrantsModule implements Module {
readonly #options: WorkspaceGrantsOptions;
#ctx: ModuleContext | undefined;
#offComputerChanged: (() => void) | undefined;
+ #ensuringDefault: Promise<void> | undefined;
constructor(options: WorkspaceGrantsOptions) {
this.#options = options;
@@ -27,9 +28,9 @@ export class WorkspaceGrantsModule implements Module {
async start(ctx: ModuleContext): Promise<void> {
this.#ctx = ctx;
this.#offComputerChanged = ctx.bus.on("computer.changed", (computerId) => {
- if (computerId) void this.#ensureDefault();
+ if (computerId) void this.ensureDefault();
});
- if (ctx.config.get().computerId) await this.#ensureDefault();
+ if (ctx.config.get().computerId) await this.ensureDefault();
}
async stop(): Promise<void> {
@@ -66,6 +67,16 @@ export class WorkspaceGrantsModule implements Module {
return grant;
}
+ // Ensures the default workspace grant exists before the daemon connects.
+ // Concurrent callers share one in-flight call so duplicate grants are never
+ // added.
+ ensureDefault(): Promise<void> {
+ this.#ensuringDefault ??= this.#ensureDefault().finally(() => {
+ this.#ensuringDefault = undefined;
+ });
+ return this.#ensuringDefault;
+ }
+
async #ensureDefault(): Promise<void> {
const directory = this.#options.defaultDirectory;
if (!directory || this.list().length > 0) return;