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.

fix(desktop): bring an unfinished local setup back to Quick Start

claude-opus-5-5-medium28d862a0c5a6
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index 66279f19..4a73cafd 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -128,10 +128,17 @@ Gateway and runs Agents. The daemon exits with the app.
engine); a counter of one file (`partial`) shows only that file. When
the check fails the installer picks, or Codex when it cannot inspect the
computer either. It records the install location, source, origin and engine in
- `desktop/local-server.json` under the default home and, while the window
- still uses that origin, restarts the services on launch with
- `installer.js --resume`, which also restarts them when the instance's
- `user.env` changed. Before installing or resuming it moves the
+ `desktop/local-server.json` under the default home (written to a temporary
+ file and renamed, so a power loss leaves the old record or none) and, while
+ the window still uses that origin and the computer is enrolled, restarts the
+ services on launch with `installer.js --resume`, which also restarts them
+ when the instance's `user.env` changed. A source folder removed since is
+ unpacked again from the app's package first. A Quick Install that stopped
+ before the computer enrolled is not resumed: setup shows again and Install
+ finishes it, reusing a finished job only while its origin answers (a stopped
+ server gets a new job, which starts the services again). The start failure
+ page's Set Up Again forgets the record, unenrolls the computer, clears the
+ server address and shows setup; the instance and its data stay. Before installing or resuming it moves the
`COMPOSIO_API_KEY`, `SONIOX_API_KEY`, `XAI_API_KEY` and `TZ` of an unpacked
source package's `.env` into `<home>/instances/desktop/user.env` once and
deletes that `.env` (never a `LINGER_CHECKOUT`'s), logging only the names
@@ -166,7 +173,11 @@ Gateway and runs Agents. The daemon exits with the app.
- `src/main/window-manager.ts`: one `BaseWindow` with two views, the title bar
(`app://shell/titlebar`) and the SPA. macOS keeps native traffic lights,
Windows uses `titleBarOverlay`, Linux draws its own controls. Closing hides
- the window to the tray.
+ the window to the tray. Closing the setup window does not quit either: an
+ installation keeps running, and opening Linger again (a second launch, the
+ 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.
- `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`.
diff --git a/apps/desktop/src/main/app-window.test.ts b/apps/desktop/src/main/app-window.test.ts
new file mode 100644
index 00000000..75d2f426
--- /dev/null
+++ b/apps/desktop/src/main/app-window.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+
+import { appWindow } from "./app-window.js";
+
+describe("appWindow", () => {
+ it("brings back setup that was closed before this computer connected", () => {
+ expect(appWindow({ enrolled: false, setupOpen: false })).toBe("setup");
+ });
+
+ it("keeps setup in front while it is open", () => {
+ expect(appWindow({ enrolled: true, setupOpen: true })).toBe("setup");
+ });
+
+ it("opens the main window once this computer is connected", () => {
+ expect(appWindow({ enrolled: true, setupOpen: false })).toBe("main");
+ });
+});
diff --git a/apps/desktop/src/main/app-window.ts b/apps/desktop/src/main/app-window.ts
new file mode 100644
index 00000000..b8e53121
--- /dev/null
+++ b/apps/desktop/src/main/app-window.ts
@@ -0,0 +1,11 @@
+// Which window opening Linger again shows (a second launch, the Dock, the
+// tray): setup while it is open or until this computer is connected, so a
+// setup closed part way, whose installation keeps running, comes back where
+// it was; the main window after. Without a server the main window could only
+// ask for a team's server address.
+export function appWindow(state: {
+ readonly enrolled: boolean;
+ readonly setupOpen: boolean;
+}): "setup" | "main" {
+ return state.setupOpen || !state.enrolled ? "setup" : "main";
+}
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 2dac6268..045c8944 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -311,7 +311,7 @@ async function main(): Promise<void> {
];
const host = new ModuleHost(modules, { config, log, bus: new EventBus() });
- const showApp = (): void => (setup.visible() ? setup.show() : windows.show());
+ const showApp = (): void => setup.showApp();
app.on("second-instance", showApp);
app.on("activate", showApp);
// Closing the window only hides it; the tray keeps the app running.
diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts
index 44f704c8..c137b26a 100644
--- a/apps/desktop/src/main/local-server.test.ts
+++ b/apps/desktop/src/main/local-server.test.ts
@@ -40,7 +40,7 @@ import {
type LocalServerOptions,
} from "./local-server.js";
import type { DesktopConfig } from "./config.js";
-import { EventBus } from "./modules.js";
+import { EventBus, type ModuleContext } from "./modules.js";
import {
silentLog,
stubModule,
@@ -291,6 +291,8 @@ const fixture = (
const showStartFailed = vi.fn();
const loadServer = vi.fn();
const enroll = vi.fn(async () => {});
+ const unenroll = vi.fn(async () => {});
+ let context: ModuleContext | undefined;
const signIn = vi.fn(async () => {});
// The installed server proves itself unless a test says otherwise.
const proveServer = vi.fn(async (_server: LocalServerIdentity) => {});
@@ -332,7 +334,14 @@ const fixture = (
showStartFailed,
loadServer,
} as never,
- { ...stubModule("Enrollment"), enroll } as never,
+ {
+ ...stubModule("Enrollment"),
+ enroll,
+ unenroll,
+ start: async (ctx: ModuleContext) => {
+ context = ctx;
+ },
+ } as never,
module,
],
config,
@@ -350,6 +359,8 @@ const fixture = (
loadServer,
bus,
enroll,
+ unenroll,
+ config: () => context!.config.get(),
signIn,
proveServer,
api,
@@ -1624,6 +1635,32 @@ describe("LocalServerModule", () => {
await f.host.stop("quit");
});
+ it("installs again when a finished installation's services are not running", async () => {
+ // The app or the computer stopped after the installation finished and
+ // before this computer connected; nothing answers at its origin.
+ const f = fixture(
+ withCheckout,
+ {},
+ checkout,
+ installerApi([
+ {
+ id: "old",
+ instance: LOCAL_INSTANCE,
+ state: "succeeded",
+ origin: "http://localhost:3000",
+ createdAt: "2026-11-03T00:00:00Z",
+ stages: [],
+ },
+ ]),
+ );
+ await f.host.start();
+ await f.module.begin();
+ expect(f.api.created).toHaveLength(1);
+ expect(f.enroll).toHaveBeenCalledOnce();
+ expect(f.module.status().phase).toBe("ready");
+ await f.host.stop("quit");
+ });
+
it("saves provider keys in user.env before the installation runs again with them", async () => {
const finishedJob = {
id: "old",
@@ -1701,8 +1738,12 @@ describe("LocalServerModule", () => {
),
).toBe("SONIOX_API_KEY=soniox-1\n");
await again.host.stop("quit");
+ // Its services still answer.
const plain = fixture(
- withCheckout,
+ (home) => ({
+ ...withCheckout(home),
+ fetch: (async () => new Response(null)) as typeof fetch,
+ }),
{},
checkout,
installerApi([finishedJob]),
@@ -1838,6 +1879,11 @@ describe("LocalServerModule install location", () => {
});
describe("LocalServerModule after a restart", () => {
+ // This computer connected to the installed server, so setup finished.
+ const enrolled = {
+ serverUrl: "http://localhost:3000",
+ computerId: "cmp_1",
+ };
const record = (home: string) => {
mkdirSync(path.join(home, "desktop"), { recursive: true });
writeFileSync(
@@ -1847,7 +1893,7 @@ describe("LocalServerModule after a restart", () => {
};
it("starts the installed services again for the local server", async () => {
- const f = fixture({}, { serverUrl: "http://localhost:3000" }, record);
+ const f = fixture({}, enrolled, record);
await f.host.start();
await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));
expect(f.setServer).toHaveBeenCalledWith("http://localhost:3000");
@@ -1866,7 +1912,7 @@ describe("LocalServerModule after a restart", () => {
});
it("moves the keys of the unpacked source's .env into the instance's user.env once", async () => {
- const f = fixture({}, { serverUrl: "http://localhost:3000" }, (home) => {
+ const f = fixture({}, enrolled, (home) => {
const source = path.join(home, "desktop", "source", "previous");
mkdirSync(source, { recursive: true });
writeFileSync(
@@ -1892,29 +1938,25 @@ describe("LocalServerModule after a restart", () => {
});
it("leaves a developer checkout's .env alone", async () => {
- const f = fixture(
- withCheckout,
- { serverUrl: "http://localhost:3000" },
- (home) => {
- checkout(home);
- writeFileSync(path.join(home, "src", ".env"), "XAI_API_KEY=xai\n");
- mkdirSync(path.join(home, "desktop", "source", "src"), {
- recursive: true,
- });
- writeFileSync(
- path.join(home, "desktop", "source", "src", ".env"),
- "XAI_API_KEY=xai\n",
- );
- writeFileSync(
- path.join(home, "desktop", "local-server.json"),
- JSON.stringify({
- home,
- repo: path.join(home, "src"),
- origin: "http://localhost:3000",
- }),
- );
- },
- );
+ const f = fixture(withCheckout, enrolled, (home) => {
+ checkout(home);
+ writeFileSync(path.join(home, "src", ".env"), "XAI_API_KEY=xai\n");
+ mkdirSync(path.join(home, "desktop", "source", "src"), {
+ recursive: true,
+ });
+ writeFileSync(
+ path.join(home, "desktop", "source", "src", ".env"),
+ "XAI_API_KEY=xai\n",
+ );
+ writeFileSync(
+ path.join(home, "desktop", "local-server.json"),
+ JSON.stringify({
+ home,
+ repo: path.join(home, "src"),
+ origin: "http://localhost:3000",
+ }),
+ );
+ });
await f.host.start();
await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));
expect(existsSync(path.join(f.home, "src", ".env"))).toBe(true);
@@ -1926,7 +1968,7 @@ describe("LocalServerModule after a restart", () => {
it("starts the services again in the folder they were installed in", async () => {
const elsewhere = path.join(tempDirectory(), "Linger");
- const f = fixture({}, { serverUrl: "http://localhost:3000" }, (home) => {
+ const f = fixture({}, enrolled, (home) => {
mkdirSync(path.join(home, "desktop"), { recursive: true });
writeFileSync(
path.join(home, "desktop", "local-server.json"),
@@ -1960,7 +2002,7 @@ describe("LocalServerModule after a restart", () => {
},
fetch: (async () => new Response(archive.bytes)) as typeof fetch,
},
- { serverUrl: "http://localhost:3000" },
+ enrolled,
(home) => {
const sources = path.join(home, "desktop", "source");
mkdirSync(path.join(sources, "previous"), { recursive: true });
@@ -1999,7 +2041,7 @@ describe("LocalServerModule after a restart", () => {
});
it("reports a failed restart", async () => {
- const f = fixture({}, { serverUrl: "http://localhost:3000" }, (home) => {
+ const f = fixture({}, enrolled, (home) => {
record(home);
writeFileSync(path.join(home, "resume-fails"), "");
});
@@ -2012,7 +2054,7 @@ describe("LocalServerModule after a restart", () => {
});
it("starts the services again when the person tries again", async () => {
- const f = fixture({}, { serverUrl: "http://localhost:3000" }, (home) => {
+ const f = fixture({}, enrolled, (home) => {
record(home);
writeFileSync(path.join(home, "resume-fails"), "");
});
@@ -2031,7 +2073,7 @@ describe("LocalServerModule after a restart", () => {
fetch: (async () =>
new Response(null, { status: 200 })) as typeof fetch,
},
- { serverUrl: "http://localhost:3000" },
+ enrolled,
record,
);
await f.host.start();
@@ -2040,6 +2082,130 @@ describe("LocalServerModule after a restart", () => {
await f.host.stop("quit");
});
+ it("shows setup instead of resuming a Quick Install that stopped before this computer connected", async () => {
+ // The record is written once the server runs, before this computer
+ // connects; the app quit or the computer went off in between.
+ const f = fixture(
+ withCheckout,
+ { serverUrl: "http://localhost:3000" },
+ (home) => {
+ checkout(home);
+ mkdirSync(path.join(home, "desktop"), { recursive: true });
+ writeFileSync(
+ path.join(home, "desktop", "local-server.json"),
+ JSON.stringify({
+ home,
+ repo: path.join(home, "src"),
+ origin: "http://localhost:3000",
+ }),
+ );
+ },
+ );
+ await f.host.start();
+ expect(f.module.status().phase).toBe("idle");
+ expect(existsSync(path.join(f.home, "installer", "args.json"))).toBe(false);
+ expect(f.showStarting).not.toHaveBeenCalled();
+ // Install on the setup page finishes it in the same place.
+ await f.module.begin();
+ expect(f.module.status().phase).toBe("ready");
+ expect(installerArgs(f.home)).not.toContain("--resume");
+ expect(f.signIn).toHaveBeenCalledOnce();
+ expect(f.enroll).toHaveBeenCalledOnce();
+ await f.host.stop("quit");
+ });
+
+ it("unpacks the source package again when its folder is gone", async () => {
+ const root = tempDirectory();
+ const archive = sourceArchive(root);
+ const repo = (home: string) =>
+ path.join(home, "desktop", "source", archive.sha256.slice(0, 16));
+ const f = fixture(
+ {
+ sourceArchive: {
+ url: "https://cdn.example/linger.tar.gz",
+ sha256: archive.sha256,
+ },
+ fetch: (async () => new Response(archive.bytes)) as typeof fetch,
+ },
+ enrolled,
+ (home) => {
+ mkdirSync(path.join(home, "desktop"), { recursive: true });
+ writeFileSync(
+ path.join(home, "desktop", "local-server.json"),
+ JSON.stringify({
+ home,
+ repo: repo(home),
+ origin: "http://localhost:3000",
+ }),
+ );
+ },
+ );
+ await f.host.start();
+ await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));
+ const args = installerArgs(f.home);
+ expect(args[args.indexOf("--source-repo") + 1]).toBe(repo(f.home));
+ expect(
+ existsSync(path.join(repo(f.home), "scripts/source-native.mjs")),
+ ).toBe(true);
+ expect(f.module.sourceUpdateAvailable()).toBe(false);
+ await f.host.stop("quit");
+ });
+
+ it("forgets the installation and its enrollment when the person sets up again", async () => {
+ const f = fixture({}, enrolled, (home) => {
+ record(home);
+ writeFileSync(path.join(home, "resume-fails"), "");
+ });
+ const opened = vi.fn();
+ f.bus.on("setup.open", opened);
+ await f.host.start();
+ await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));
+ f.bus.emit("local-server.reset");
+ await vi.waitFor(() => expect(opened).toHaveBeenCalledOnce());
+ expect(f.module.status().phase).toBe("idle");
+ expect(existsSync(path.join(f.home, "desktop", "local-server.json"))).toBe(
+ false,
+ );
+ expect(f.unenroll).toHaveBeenCalledOnce();
+ expect(f.config().serverUrl).toBeUndefined();
+ expect(f.loadServer).toHaveBeenCalledOnce();
+ // Try Again has nothing left to start.
+ rmSync(path.join(f.home, "installer", "args.json"));
+ f.bus.emit("local-server.retry");
+ await delay(50);
+ expect(existsSync(path.join(f.home, "installer", "args.json"))).toBe(false);
+ await f.host.stop("quit");
+ });
+
+ it("writes its record in one piece", async () => {
+ const f = fixture(withCheckout, {}, checkout);
+ await f.host.start();
+ await f.module.begin();
+ expect(readdirSync(path.join(f.home, "desktop")).sort()).toEqual(
+ expect.not.arrayContaining([expect.stringMatching(/\.tmp$/)]),
+ );
+ expect(
+ JSON.parse(
+ readFileSync(path.join(f.home, "desktop", "local-server.json"), "utf8"),
+ ),
+ ).toMatchObject({ origin: "http://localhost:3000" });
+ await f.host.stop("quit");
+ });
+
+ it("leaves no staged record behind when the record cannot be moved into place", async () => {
+ const f = fixture(withCheckout, {}, checkout);
+ // A folder where the record goes: the rename fails.
+ mkdirSync(path.join(f.home, "desktop", "local-server.json", "x"), {
+ recursive: true,
+ });
+ await f.host.start();
+ await f.module.begin().catch(() => {});
+ expect(readdirSync(path.join(f.home, "desktop"))).toEqual(
+ expect.not.arrayContaining([expect.stringMatching(/\.tmp$/)]),
+ );
+ await f.host.stop("quit");
+ });
+
it("leaves the services alone when the window uses another server", async () => {
const f = fixture({}, { serverUrl: "https://linger.example" }, record);
await f.host.start();
@@ -2437,6 +2603,7 @@ describe("LocalServerModule on Windows", () => {
describe("LocalServerModule owner account", () => {
const ORIGIN = "http://localhost:3000";
+ const enrolled = { serverUrl: ORIGIN, computerId: "cmp_1" };
const installed =
(account?: Record<string, unknown>, mode = 0o600) =>
(home: string) => {
@@ -2459,7 +2626,7 @@ describe("LocalServerModule owner account", () => {
};
it("signs the window in to the installed server with the account file", async () => {
- const f = fixture({}, { serverUrl: ORIGIN }, installed(OWNER));
+ const f = fixture({}, enrolled, installed(OWNER));
await f.host.start();
await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));
expect(await f.module.servesWindow()).toBe(true);
@@ -2483,7 +2650,7 @@ describe("LocalServerModule owner account", () => {
});
it("does not offer the account while the services are not running", async () => {
- const f = fixture({}, { serverUrl: ORIGIN }, (home) => {
+ const f = fixture({}, enrolled, (home) => {
installed(OWNER)(home);
writeFileSync(path.join(home, "resume-fails"), "");
});
@@ -2513,7 +2680,7 @@ describe("LocalServerModule owner account", () => {
"Linger on this computer is not responding.",
],
])("says what to do when signing in fails (%s)", async (error, message) => {
- const f = fixture({}, { serverUrl: ORIGIN }, installed(OWNER));
+ const f = fixture({}, enrolled, installed(OWNER));
f.signIn.mockRejectedValueOnce(error);
await f.host.start();
await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));
@@ -2525,7 +2692,7 @@ describe("LocalServerModule owner account", () => {
let now = Date.now();
const clock = vi.spyOn(Date, "now").mockImplementation(() => now);
try {
- const f = fixture({}, { serverUrl: ORIGIN }, installed(OWNER));
+ const f = fixture({}, enrolled, installed(OWNER));
await f.host.start();
await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));
expect(await f.module.servesWindow()).toBe(true);
@@ -2559,7 +2726,7 @@ describe("LocalServerModule owner account", () => {
);
},
},
- { serverUrl: ORIGIN },
+ enrolled,
installed(OWNER),
);
await f.host.start();
@@ -2588,7 +2755,7 @@ describe("LocalServerModule owner account", () => {
});
it("does not offer it before Linger is installed here", async () => {
- const f = fixture({}, { serverUrl: ORIGIN });
+ const f = fixture({}, enrolled);
await f.host.start();
expect(await f.module.servesWindow()).toBe(false);
await expect(f.module.account()).rejects.toThrow(
@@ -2616,7 +2783,7 @@ describe("LocalServerModule owner account", () => {
])(
"says why a %s account file cannot sign in",
async (_case, prepare, message) => {
- const f = fixture({}, { serverUrl: ORIGIN }, prepare);
+ const f = fixture({}, enrolled, prepare);
await f.host.start();
await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));
const failure = f.module.signInWithAccount();
diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts
index ba83c626..25575637 100644
--- a/apps/desktop/src/main/local-server.ts
+++ b/apps/desktop/src/main/local-server.ts
@@ -363,6 +363,7 @@ export class LocalServerModule implements Module {
#outdated: LocalRecord | undefined;
#updating: Promise<void> | undefined;
#offRetry: (() => void) | undefined;
+ #offReset: (() => void) | undefined;
#offDaemon: (() => void) | undefined;
#daemonFailure: string | undefined;
#signIn: RuntimeSignIn | undefined;
@@ -386,19 +387,24 @@ export class LocalServerModule implements Module {
this.#ctx = ctx;
const migrationFailure = await this.#migrateLegacyHome(ctx);
// After a reboot the local services are gone; start them again while the
- // window still points at them.
- const record = await this.#readRecord();
+ // window still points at them. A record of a Quick Install that stopped
+ // before this computer connected (the app quit or the computer went off
+ // during its last steps) is not resumed: setup shows instead, and its
+ // Install finishes that installation.
+ let record = await this.#readRecord();
if (record) this.#home = record.home;
+ const config = ctx.config.get();
+ const resumes =
+ !!record && config.serverUrl === record.origin && !!config.computerId;
if (migrationFailure) {
// Resume would fail on the legacy record with a less useful error;
// Retry resumes, and the installer migrates again first.
this.#set("failed", migrationFailure);
- if (record && ctx.config.get().serverUrl === record.origin)
+ if (resumes)
ctx
.get<WindowManagerModule>("WindowManager")
?.showStartFailed(migrationFailure);
- } else if (record && ctx.config.get().serverUrl === record.origin)
- void this.#resume(record, this.#abort.signal);
+ } else if (record && resumes) void this.#resume(record, this.#abort.signal);
this.#offDaemon = ctx.bus.on("computer.failed", (reason) => {
this.#daemonFailure = reason;
});
@@ -407,10 +413,15 @@ export class LocalServerModule implements Module {
void this.#resume(record, this.#abort.signal);
}
});
+ this.#offReset = ctx.bus.on("local-server.reset", () => {
+ record = undefined;
+ void this.#reset();
+ });
}
async stop(): Promise<void> {
this.#offRetry?.();
+ this.#offReset?.();
this.#offDaemon?.();
// The installer manager keeps running a started installation; it exits
// by itself once idle.
@@ -1884,8 +1895,12 @@ export class LocalServerModule implements Module {
// The window would show the server as unreachable until it is back.
if (!(await this.#reachable(record.origin))) windows?.showStarting();
const newer = this.#newerSource(record);
+ // A source folder removed since (by hand, or a cleanup that an uninstall
+ // left half done) is unpacked again from this app's package.
const repo =
- newer && !existsSync(record.repo)
+ this.#options.sourceArchive &&
+ !this.#options.checkout &&
+ !existsSync(record.repo)
? await this.#ensureSource(record.home, signal)
: record.repo;
await this.#runResume(record, repo, signal);
@@ -1902,18 +1917,31 @@ export class LocalServerModule implements Module {
}
}
- // Whether the services already answer, such as after only the app quit.
- async #reachable(origin: string): Promise<boolean> {
+ // The person gave up on the installation the window used, whose services
+ // do not start (it may have been removed or left broken by an uninstall):
+ // forget it and this computer's enrollment with it, and show setup. Its
+ // Install sets this computer up again in the same location, keeping what
+ // is left of that instance.
+ async #reset(): Promise<void> {
+ const ctx = this.#ctx!;
try {
- await (this.#options.fetch ?? fetch)(origin, {
- method: "HEAD",
- redirect: "manual",
- signal: AbortSignal.timeout(1_000),
- });
- return true;
- } catch {
- return false;
+ await rm(this.#recordFile(), { force: true });
+ this.#origin = undefined;
+ this.#outdated = undefined;
+ this.#set("idle", "");
+ ctx.log.info("local_server.reset");
+ await ctx.get<EnrollmentModule>("Enrollment").unenroll();
+ ctx.config.update({ serverUrl: undefined });
+ ctx.get<WindowManagerModule>("WindowManager").loadServer();
+ } catch (error) {
+ ctx.log.warn("local_server.reset_failed", { error: String(error) });
}
+ ctx.bus.emit("setup.open");
+ }
+
+ // Whether the services already answer, such as after only the app quit.
+ #reachable(origin: string): Promise<boolean> {
+ return answers(this.#options.fetch ?? fetch, origin);
}
// Whether the window's server is the one this app runs.
@@ -2059,9 +2087,17 @@ export class LocalServerModule implements Module {
async #writeRecord(record: LocalRecord): Promise<void> {
await mkdir(this.#desktopDirectory(), { recursive: true, mode: 0o700 });
- await writeFile(this.#recordFile(), JSON.stringify(record), {
- mode: 0o600,
- });
+ // Written aside and moved into place: a record cut short by a power loss
+ // would read as no installation while the window still points at it.
+ const staged = `${this.#recordFile()}.${randomBytes(4).toString("hex")}.tmp`;
+ try {
+ await writeFile(staged, JSON.stringify(record), { mode: 0o600 });
+ await renameRetrying(staged, this.#recordFile());
+ } catch (error) {
+ // Each failed write would otherwise leave one more staged file.
+ await rm(staged, { force: true });
+ throw error;
+ }
}
}
@@ -2214,6 +2250,23 @@ const STAGES: Record<string, readonly [LocalServerStep, number, number]> = {
computer: ["workspace", 1, 1],
};
+// Whether a server answers at an origin at all.
+async function answers(
+ fetcher: typeof fetch,
+ origin: string,
+): Promise<boolean> {
+ try {
+ await fetcher(origin, {
+ method: "HEAD",
+ redirect: "manual",
+ signal: AbortSignal.timeout(1_000),
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
// Done: services run and the owner exists. A runtime sign-in still missing
// is the setup page's own step.
const finished = (job: Job): boolean =>
@@ -2300,9 +2353,12 @@ export class InstallerApi {
latest &&
(["queued", "running"].includes(latest.state) ||
// A finished one only while its instance is still there; its data
- // may have been removed since.
+ // may have been removed since. Its services must still run too: after
+ // the app or the computer stopped part way through setup, a new job
+ // starts them again.
(finished(latest) &&
- (await this.#call(`/api/instances/${LOCAL_INSTANCE}/login`)).ok))
+ (await this.#call(`/api/instances/${LOCAL_INSTANCE}/login`)).ok &&
+ (await answers(this.#fetch, latest.origin!))))
)
job = latest;
else {
diff --git a/apps/desktop/src/main/modules.ts b/apps/desktop/src/main/modules.ts
index ddae5c6c..3cf78f6a 100644
--- a/apps/desktop/src/main/modules.ts
+++ b/apps/desktop/src/main/modules.ts
@@ -21,11 +21,14 @@ export interface BusEvents {
"computer.renamed": [];
"grants.changed": [];
"local-server.changed": [];
+ // Forget the installation the window used and set this computer up again.
+ "local-server.reset": [];
"local-server.retry": [];
"power.changed": [];
"runtime.activity": [running: number];
"runtime.state": [state: string];
"server.changed": [serverUrl: string];
+ "setup.open": [];
"status.changed": [status: { tone: string; label: string }];
"update.changed": [state: string];
}
diff --git a/apps/desktop/src/main/setup-window.ts b/apps/desktop/src/main/setup-window.ts
index ac2a919e..b2770546 100644
--- a/apps/desktop/src/main/setup-window.ts
+++ b/apps/desktop/src/main/setup-window.ts
@@ -27,6 +27,7 @@ import {
type SetupLocalAccount,
type SetupState,
} from "../shared/setup.js";
+import { appWindow } from "./app-window.js";
import type { DiagnosticsModule } from "./diagnostics.js";
import type { EnrollmentModule } from "./enrollment.js";
import type { LocalServerModule } from "./local-server.js";
@@ -136,6 +137,7 @@ export class SetupWindowModule implements Module {
ctx.bus.on("grants.changed", push),
ctx.bus.on("local-server.changed", onLocal),
ctx.bus.on("server.changed", onCookie),
+ ctx.bus.on("setup.open", () => this.show()),
);
if (this.#options.show) this.show();
}
@@ -150,6 +152,15 @@ export class SetupWindowModule implements Module {
return !!this.#window && !this.#window.isDestroyed();
}
+ // Opens Linger again: setup until this computer is connected, the main
+ // window after.
+ showApp(): void {
+ const enrolled = !!this.#ctx?.config.get().computerId;
+ if (appWindow({ enrolled, setupOpen: this.visible() }) === "setup")
+ this.show();
+ else this.#ctx?.get<WindowManagerModule>("WindowManager").show();
+ }
+
show(): void {
if (this.#window && !this.#window.isDestroyed()) {
this.#window.show();
diff --git a/apps/desktop/src/main/tray.ts b/apps/desktop/src/main/tray.ts
index 9c554a66..c92a8ffe 100644
--- a/apps/desktop/src/main/tray.ts
+++ b/apps/desktop/src/main/tray.ts
@@ -84,14 +84,14 @@ export class TrayModule implements Module {
async start(ctx: ModuleContext): Promise<void> {
this.#ctx = ctx;
- const windows = ctx.get<WindowManagerModule>("WindowManager");
+ const setup = ctx.get<SetupWindowModule>("SetupWindow");
try {
if (headless()) throw new Error("No display");
this.#tray = new Tray(this.#icon());
this.#tray.setToolTip("Linger");
// Windows and Linux open the window on click; macOS shows the menu.
if (process.platform !== "darwin")
- this.#tray.on("click", () => windows.show());
+ this.#tray.on("click", () => setup.showApp());
} catch (error) {
ctx.log.warn("tray.unavailable", { error: String(error) });
}
@@ -177,7 +177,7 @@ export class TrayModule implements Module {
else ctx.get<SetupWindowModule>("SetupWindow").show();
break;
case "open":
- ctx.get<WindowManagerModule>("WindowManager").show();
+ ctx.get<SetupWindowModule>("SetupWindow").showApp();
break;
case "toggle-prevent-sleep": {
const power = ctx.get<PowerGuardModule>("PowerGuard");
diff --git a/apps/desktop/src/main/window-manager.ts b/apps/desktop/src/main/window-manager.ts
index dbc96112..28f00771 100644
--- a/apps/desktop/src/main/window-manager.ts
+++ b/apps/desktop/src/main/window-manager.ts
@@ -473,6 +473,14 @@ export class WindowManagerModule implements Module {
this.#ctx!.bus.emit("local-server.retry");
return new Response(null, { status: 204 });
}
+ // Back to setup from the server address form, or, from the start failure
+ // page, setting this computer up again.
+ if (url.pathname === "/setup" || url.pathname === "/reset") {
+ this.#window?.hide();
+ if (url.pathname === "/reset") this.#ctx!.bus.emit("local-server.reset");
+ else this.#ctx!.bus.emit("setup.open");
+ return new Response(null, { status: 204 });
+ }
if (url.pathname === "/connect") {
if (!this.setServer(url.searchParams.get("server") ?? ""))
this.#loadOffline(INVALID_SERVER);
diff --git a/apps/desktop/src/shell/offline.html b/apps/desktop/src/shell/offline.html
index 8425c8b7..50399c3d 100644
--- a/apps/desktop/src/shell/offline.html
+++ b/apps/desktop/src/shell/offline.html
@@ -237,6 +237,9 @@
<button class="link failed-only" id="diagnostics" type="button">
Save Diagnostics
</button>
+ <button class="link failed-only" id="reset" type="button">
+ Set Up Again
+ </button>
<span class="countdown" id="countdown"></span>
</div>
<form action="app://offline/connect" method="get" id="form">
@@ -288,6 +291,8 @@
$("title").textContent = "Connect to Linger";
$("reason").textContent =
"Enter your team's server address, then sign in.";
+ // Setup, where Linger can also be installed on this computer.
+ $("cancel").textContent = "Back to Setup";
$("server").focus();
} else {
$("host").textContent = new URL(server).host;
@@ -313,9 +318,14 @@
document.body.classList.add("editing");
$("server").select();
});
- $("cancel").addEventListener("click", () =>
- document.body.classList.remove("editing"),
- );
+ $("reset").addEventListener("click", () => {
+ location.href = "app://offline/reset";
+ });
+ $("cancel").addEventListener("click", () => {
+ if (document.body.dataset.mode === "setup")
+ location.href = "app://offline/setup";
+ else document.body.classList.remove("editing");
+ });
// Retry on its own while the user is not editing.
if (server && !local) {
let left = 15;