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(local-installation): move Linger's web origin off a port another program holds
Dongdong Chenf8399f142d27
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex c3378c6b..9284ac1f 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -180,7 +180,15 @@ Gateway and runs Agents. The daemon exits with the app.file and renamed, so a power loss leaves the old record or none) and, whilethe window still uses that origin and the computer is enrolled, restarts theservices on launch with `installer.js --resume`, which also restarts them- when the instance's `user.env` changed. A source folder removed since, or+ when the instance's `user.env` changed. When another program took the web+ port, the installer moves the services to a free one and reports the new+ origin (`details.origin`, or the setup job's `origin`). The record, the+ window's `serverUrl` and the `savedEnrollments` entry follow it together+ (`setServer` with the previous origin emits `server.moved`, not+ `server.changed`), so the Computer stays enrolled: it reaches TeamHub+ through the gateway URL TeamHub gave it, and the session cookies are not+ port-scoped. The record and `serverUrl` change only together, so a later+ launch still resumes. A source folder removed since, orone the installer no longer accepts as a Linger checkout (such as one theearlier Simplex app unpacked, or this package's own folder with filesmissing since), is unpacked again from the app's package first anddiff --git a/apps/desktop/src/main/enrollment.test.ts b/apps/desktop/src/main/enrollment.test.tsindex d56ce368..fde34508 100644--- a/apps/desktop/src/main/enrollment.test.ts+++ b/apps/desktop/src/main/enrollment.test.ts@@ -546,6 +546,46 @@ describe("EnrollmentModule", () => {await host.stop("quit");});+ it("keeps the enrollment when the same server moves to another origin", async () => {+ const { enrollment, host, bus, credentials, server } = setupModule(+ {},+ "http://localhost:3000",+ {+ savedEnrollments: { "https://other.example.com": { computerId: "c" } },+ },+ );+ await host.start();+ await enrollment.enroll();+ const credential = credentials.read();++ host.ctx.config.update({ serverUrl: "http://localhost:3001" });+ bus.emit("server.moved", "http://localhost:3000", "http://localhost:3001");++ const config = host.ctx.config.get();+ expect(config.computerId).toBe("computer_1");+ expect(credentials.read()).toEqual(credential);+ expect(config.savedEnrollments).toEqual({+ "https://other.example.com": { computerId: "c" },+ "http://localhost:3001": {+ computerId: "computer_1",+ tenantId: "tenant_acme",+ ownerActorId: "actor_ann",+ },+ });+ // Unenrolling later saves the enrollment under the new origin.+ await enrollment.unenroll();+ expect(+ Object.keys(host.ctx.config.get().savedEnrollments ?? {}),+ ).not.toContain("http://localhost:3000");+ // Enrolling again at the new origin renews the same Computer.+ await enrollment.enroll();+ const creates = server.calls.filter((call) =>+ call.url.endsWith("/local-computer-enrollments"),+ );+ expect(creates.at(-1)?.body?.computer_id).toBe("computer_1");+ await host.stop("quit");+ });+it("saves the previous server origin on server.changed without polluting the new origin", async () => {const { enrollment, host, bus } = setupModule();await host.start();diff --git a/apps/desktop/src/main/enrollment.ts b/apps/desktop/src/main/enrollment.tsindex a529b675..398282fb 100644--- a/apps/desktop/src/main/enrollment.ts+++ b/apps/desktop/src/main/enrollment.ts@@ -350,6 +350,7 @@ export class EnrollmentModule implements Module {#ctx: ModuleContext | undefined;#pending: Promise<{ computerId: string }> | undefined;#offServerChanged: (() => void) | undefined;+ #offServerMoved: (() => void) | undefined;#activeServerUrl: string | undefined;constructor(options: EnrollmentOptions) {@@ -377,6 +378,11 @@ export class EnrollmentModule implements Module {ctx.log.warn("enrollment.clear_failed", { error: String(error) }),);});+ // The same server at another origin keeps its enrollments: the Computer+ // reaches it through the gateway TeamHub named, not through the origin.+ this.#offServerMoved = ctx.bus.on("server.moved", (from, to) => {+ this.#moveEnrollment(from, to);+ });// Enrollments made before the owner was kept, or whose credential did// not carry over from the bridge, are renewed for the same Computer.const config = ctx.config.get();@@ -400,6 +406,27 @@ export class EnrollmentModule implements Module {async stop(): Promise<void> {this.#offServerChanged?.();+ this.#offServerMoved?.();+ }++ #moveEnrollment(from: string, to: string): void {+ const fromOrigin = enrollmentOrigin(from);+ const toOrigin = enrollmentOrigin(to);+ if (!fromOrigin || !toOrigin) return;+ if (+ this.#activeServerUrl &&+ enrollmentOrigin(this.#activeServerUrl) === fromOrigin+ )+ this.#activeServerUrl = to;+ const saved = this.#ctx!.config.get().savedEnrollments;+ const entry = saved?.[fromOrigin];+ if (!saved || !entry) return;+ this.#ctx!.config.update({+ savedEnrollments: Object.fromEntries([+ ...Object.entries(saved).filter(([origin]) => origin !== fromOrigin),+ [toOrigin, entry],+ ]),+ });}// Whether the window holds a valid session for the configured server.diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.tsindex c2a6ecb8..71421952 100644--- a/apps/desktop/src/main/local-server.test.ts+++ b/apps/desktop/src/main/local-server.test.ts@@ -145,7 +145,10 @@ if (args.includes("--resume")) {const source = fs.existsSync(servingFile) ? fs.readFileSync(servingFile, "utf8") : fs.existsSync(repo) ? fs.realpathSync(repo) : repo;// resume-fails may hold the failed outcome's message and details.const failure = code ? fs.readFileSync(path.join(home, "resume-fails"), "utf8").trim() : "";- const outcome = failure ? JSON.parse(failure) : { message: code ? "Native teamhub stopped" : "ok", details: { source } };+ // resume-origin names the origin the installer moved the services to.+ const originFile = path.join(home, "resume-origin");+ const origin = fs.existsSync(originFile) ? fs.readFileSync(originFile, "utf8") : "http://localhost:3000";+ const outcome = failure ? JSON.parse(failure) : { message: code ? "Native teamhub stopped" : "ok", details: { source, origin } };process.stdout.write("noise\n" + JSON.stringify({ code, ...outcome, ...(runtime ? { runtime } : {}) }) + "\n");process.exit(code);}@@ -2080,6 +2083,30 @@ describe("LocalServerModule", () => {await f.host.stop("quit");});+ it("follows an installation that moved to another origin as the same server", async () => {+ const f = fixture(withCheckout, {}, (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:2999",+ }),+ );+ });+ await f.host.start();+ await f.module.begin();+ expect(f.module.status().phase).toBe("ready");+ expect(f.setServer).toHaveBeenCalledWith(+ "http://localhost:3000",+ "http://localhost:2999",+ );+ expect(f.unenroll).not.toHaveBeenCalled();+ await f.host.stop("quit");+ });+it("saves provider keys in user.env before the installation runs again with them", async () => {const finishedJob = {id: "old",@@ -2330,6 +2357,31 @@ describe("LocalServerModule after a restart", () => {await f.host.stop("quit");});+ it("follows the origin the installer moved the services to", async () => {+ const f = fixture({}, enrolled, (home) => {+ record(home);+ writeFileSync(path.join(home, "resume-origin"), "http://localhost:3001");+ });+ await f.host.start();+ await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ // The same server at a new origin: the window follows it as a move,+ // which keeps this computer's enrollment.+ expect(f.setServer).toHaveBeenCalledWith(+ "http://localhost:3001",+ "http://localhost:3000",+ );+ expect(f.unenroll).not.toHaveBeenCalled();+ expect(+ JSON.parse(+ readFileSync(path.join(f.home, "desktop", "local-server.json"), "utf8"),+ ),+ ).toMatchObject({ repo: "/source", origin: "http://localhost:3001" });+ expect(f.module.status()).toMatchObject({+ origin: "http://localhost:3001",+ });+ await f.host.stop("quit");+ });+it("stops the local models when the person quits, without waiting for them", async () => {const stopped = (home: string) => path.join(home, "stop-local-models.json");const f = fixture({}, enrolled, record);diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.tsindex 72188a19..4fba3eba 100644--- a/apps/desktop/src/main/local-server.ts+++ b/apps/desktop/src/main/local-server.ts@@ -66,7 +66,7 @@ import {} from "../../../../scripts/local-computer-node-distributions.mjs";import type { Logger } from "./log.js";import type { Module, ModuleContext, StopReason } from "./modules.js";-import { sameOrigin } from "./navigation.js";+import { 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";@@ -1079,6 +1079,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);+ // 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();await this.#writeRecord({home,repo,@@ -1088,7 +1091,10 @@ export class LocalServerModule implements Module {await this.#pruneSources(home, [repo]);this.#home = home;this.#location = undefined;- this.#ready(job.origin);+ this.#ready(+ job.origin,+ previous?.home === home ? previous.origin : undefined,+ );this.#daemonConnection = undefined;await this.#ctx!.get<EnrollmentModule>("Enrollment").enroll();this.#advance("agents", 0, "Preparing your agents…");@@ -2162,9 +2168,12 @@ export class LocalServerModule implements Module {);}- #ready(origin: string): void {+ // `previous` is the origin this installation answered at before.+ #ready(origin: string, previous?: string): void {this.#origin = origin;- this.#ctx?.get<WindowManagerModule>("WindowManager").setServer(origin);+ const windows = this.#ctx?.get<WindowManagerModule>("WindowManager");+ if (previous && previous !== origin) windows?.setServer(origin, previous);+ else windows?.setServer(origin);}// The server sets up the Another Me once this computer offers a signed-in@@ -2317,25 +2326,36 @@ export class LocalServerModule implements Module {? await this.#ensureSource(record.home, signal): record.repo;const serving = await this.#runResume(record, repo, signal);+ // 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+ // is the same server.+ const origin = serving.origin ?? record.origin;if (repo !== record.repo) {// The record moves, and the older folder goes, only once the// services run from the new one and answer; until then the older// services keep running from their folder, and Retry moves them.if (- serving !== (await realpath(repo).catch(() => repo)) ||- !(await this.#reachable(record.origin))+ serving.source !== (await realpath(repo).catch(() => repo)) ||+ !(await this.#reachable(origin)))throw new Error("Linger could not restart on this version. The earlier version is still installed; try again.",);- await this.#moved(record, repo);- }+ await this.#moved({ ...record, origin }, repo);+ } else if (origin !== record.origin)+ await this.#writeRecord({ ...record, origin });+ if (origin !== record.origin)+ this.#ctx?.log.info("local_server.origin_moved", {+ from: record.origin,+ to: origin,+ });if (update)this.#ctx?.log.info("local_server.source_updated", {source: path.basename(repo),from: record.version,});- this.#ready(record.origin);+ this.#ready(origin, record.origin);this.#set("ready", "Linger is running on this computer.");} catch (error) {if (signal.aborted) return;@@ -2407,20 +2427,15 @@ export class LocalServerModule implements Module {}// Resolves with the source folder the installer reports the services- // serving from.+ // serving from, and the origin they serve at.async #runResume(record: LocalRecord,repo: string,signal: AbortSignal,- ): Promise<string | undefined> {+ ): Promise<{ source?: string; origin?: string }> {await this.#adoptSourceKeys(record.home);const node = await this.#ensureNode(signal);- const outcome = await new Promise<{- code: number;- message: string;- details?: { source?: unknown; code?: unknown; reasons?: unknown };- runtime?: InstanceRuntime;- }>((resolve, reject) => {+ const outcome = await new Promise<ResumeOutcome>((resolve, reject) => {const child = spawn(node,[@@ -2451,14 +2466,7 @@ export class LocalServerModule implements Module {child.once("close", (code) => {try {const last = output.trim().split("\n").at(-1) ?? "";- resolve(- JSON.parse(last) as {- code: number;- message: string;- details?: { source?: unknown; code?: unknown; reasons?: unknown };- runtime?: InstanceRuntime;- },- );+ resolve(JSON.parse(last) as ResumeOutcome);} catch {reject(new Error(`The installer exited with code ${code}`));}@@ -2488,8 +2496,13 @@ export class LocalServerModule implements Module {);}this.#adoptRuntime(outcome.runtime);- const source = outcome.details?.source;- return typeof source === "string" ? source : undefined;+ const { source, origin } = outcome.details ?? {};+ return {+ ...(typeof source === "string" ? { source } : {}),+ ...(typeof origin === "string" && parseServerUrl(origin) === origin+ ? { origin }+ : {}),+ };}// Every resume reports the runtime and localmodels tool paths, so an@@ -2597,6 +2610,19 @@ const atLeast = (version: string, minimum: string): boolean => {return major !== wantMajor ? major > wantMajor : minor >= wantMinor;};+// The single JSON line `installer.js --resume` prints.+interface ResumeOutcome {+ code: number;+ message: string;+ details?: {+ source?: unknown;+ origin?: unknown;+ code?: unknown;+ reasons?: unknown;+ };+ runtime?: InstanceRuntime;+}+interface LocalRecord {// The installer home.readonly home: string;diff --git a/apps/desktop/src/main/modules.ts b/apps/desktop/src/main/modules.tsindex 068053ef..6a45fec3 100644--- a/apps/desktop/src/main/modules.ts+++ b/apps/desktop/src/main/modules.ts@@ -31,6 +31,8 @@ export interface BusEvents {"runtime.activity": [running: number];"runtime.state": [state: string];"server.changed": [serverUrl: string];+ // The same server answers at another origin; enrollments follow it.+ "server.moved": [from: string, to: string];"setup.open": [];"status.changed": [status: { tone: string; label: string }];"update.changed": [state: string];diff --git a/apps/desktop/src/main/navigation.test.ts b/apps/desktop/src/main/navigation.test.tsindex 7ca07078..8ffc65d4 100644--- a/apps/desktop/src/main/navigation.test.ts+++ b/apps/desktop/src/main/navigation.test.ts@@ -5,10 +5,50 @@ import {navigationDecision,parseServerUrl,permissionAllowed,+ serverSwitch,} from "./navigation.js";const server = "https://linger.example.com";+describe("serverSwitch", () => {+ const local = "http://localhost:3000";+ const moved = "http://localhost:3001";++ it("follows the same server to its new origin without changing servers", () => {+ expect(serverSwitch(local, moved, local)).toEqual({+ moved: true,+ changed: false,+ });+ });++ it("changes servers when the app pointed at another one", () => {+ expect(serverSwitch(server, moved, local)).toEqual({+ moved: true,+ changed: true,+ });+ expect(serverSwitch(local, server)).toEqual({+ moved: false,+ changed: true,+ });+ });++ it("changes no server when the origin stays", () => {+ expect(serverSwitch(local, local)).toEqual({+ moved: false,+ changed: false,+ });+ expect(serverSwitch(local, local, local)).toEqual({+ moved: false,+ changed: false,+ });+ // A retry after the move already followed it.+ expect(serverSwitch(moved, moved, local)).toEqual({+ moved: true,+ changed: false,+ });+ });+});+describe("window policy", () => {it("keeps navigation on the server origin", () => {expect(navigationDecision(`${server}/rooms/1`, server)).toBe("allow");diff --git a/apps/desktop/src/main/navigation.ts b/apps/desktop/src/main/navigation.tsindex 17b34b5b..74601cab 100644--- a/apps/desktop/src/main/navigation.ts+++ b/apps/desktop/src/main/navigation.ts@@ -15,6 +15,28 @@ export const sameOrigin = (url: string, serverUrl: string): boolean => {}};+export interface ServerSwitch {+ // The same server answers at another origin; its enrollments follow it.+ readonly moved: boolean;+ // The app leaves the server it used for another one, which drops this+ // computer's enrollment.+ readonly changed: boolean;+}++// What pointing the app from `previous` at `serverUrl` means. `movedFrom` is+// the origin the server at `serverUrl` answered at before it moved.+export function serverSwitch(+ previous: string | undefined,+ serverUrl: string,+ movedFrom?: string,+): ServerSwitch {+ const moved = movedFrom !== undefined && movedFrom !== serverUrl;+ return {+ moved,+ changed: serverUrl !== previous && !(moved && previous === movedFrom),+ };+}+export type NavigationDecision = "allow" | "external" | "deny";// App pages are reachable only from app pages: the server's pages must notdiff --git a/apps/desktop/src/main/setup-window.ts b/apps/desktop/src/main/setup-window.tsindex c271160a..d7eb778e 100644--- a/apps/desktop/src/main/setup-window.ts+++ b/apps/desktop/src/main/setup-window.ts@@ -138,6 +138,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("server.moved", onCookie),ctx.bus.on("setup.open", () => this.show()),);if (this.#options.show) this.show();diff --git a/apps/desktop/src/main/window-manager.ts b/apps/desktop/src/main/window-manager.tsindex b4d1665d..4b069585 100644--- a/apps/desktop/src/main/window-manager.ts+++ b/apps/desktop/src/main/window-manager.ts@@ -32,6 +32,7 @@ import {parseServerUrl,permissionAllowed,sameOrigin,+ serverSwitch,} from "./navigation.js";// Must run before app "ready".@@ -241,14 +242,19 @@ export class WindowManagerModule implements Module {}// Points the app at another server; false when the address is invalid.- setServer(value: string): boolean {+ // `movedFrom` names the origin the same server answered at before (the+ // 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 {const serverUrl = parseServerUrl(value);if (!serverUrl) return false;const ctx = this.#ctx!;- if (serverUrl !== ctx.config.get().serverUrl) {- ctx.config.update({ serverUrl });- ctx.bus.emit("server.changed", serverUrl);- }+ const previous = ctx.config.get().serverUrl;+ const { moved, changed } = serverSwitch(previous, serverUrl, movedFrom);+ 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.#pushState();diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.mdindex 4be37c4f..881cd306 100644--- a/apps/linger-installer/AGENTS.md+++ b/apps/linger-installer/AGENTS.md@@ -28,7 +28,9 @@ once its services are ready on it: until then `instance.json` keeps naming thecheckout they run from, the new checkout's migrations run only after theruntime (the local model, for one) is ready, and a run that stops earlierleaves the running services and their schema as they were. A successful-outcome's `details.source` names the checkout the services serve from. A+outcome's `details.source` names the checkout the services serve from, and+`details.origin` the origin they serve at, which the run moves when another+program took the web port. Alocal model stack whose saved binding is no longer ready (any setup bindingreason, `pi-extensions-unavailable` from a Pi an earlier localmodelsinstalled without extension support included) gets its approved plan applieddiff --git a/apps/linger-installer/src/server/resume.test.ts b/apps/linger-installer/src/server/resume.test.tsindex f79bec41..f4c201f6 100644--- a/apps/linger-installer/src/server/resume.test.ts+++ b/apps/linger-installer/src/server/resume.test.ts@@ -115,6 +115,26 @@ test("reports the source the services serve from", async () => {).toMatchObject({ code: 0, details: { source: "/old-source" } });});+test("reports the origin the services moved to", async () => {+ const moved = { ...instance, origin: "http://localhost:3001" } as Instance;+ const load = vi+ .fn<() => Promise<Instance>>()+ .mockResolvedValueOnce(instance)+ .mockResolvedValue(moved);+ const run = vi.fn<ResumeEngine["run"]>(async () => ({+ code: 0,+ state: "ready",+ message: "ok",+ details: { origin: moved.origin },+ }));+ expect(+ await resumeSourceInstance(options, {+ load,+ engines: native(run, false),+ }),+ ).toMatchObject({ code: 0, details: { origin: "http://localhost:3001" } });+});+test("needs an installed source instance", async () => {expect(await resumeSourceInstance(options, {diff --git a/apps/linger-installer/src/server/resume.ts b/apps/linger-installer/src/server/resume.tsindex b205bbc7..e3edfae1 100644--- a/apps/linger-installer/src/server/resume.ts+++ b/apps/linger-installer/src/server/resume.ts@@ -93,7 +93,9 @@ export async function resumeSourceInstance(},});if (outcome.code !== 0) return outcome;- // The instance names a checkout only once its services serve from it.+ // The instance names a checkout only once its services serve from it, and+ // the origin they serve at: the run moves the web port off one another+ // program took.const serving = await load({name: options.instanceName,home: options.home,@@ -102,7 +104,7 @@ export async function resumeSourceInstance(...outcome,details: {...(outcome.details as object | undefined),- origin: instance.origin,+ origin: serving?.origin,source: serving?.source?.repo,},};diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.mdindex f16a9588..5ed08ffa 100644--- a/packages/local-installation/AGENTS.md+++ b/packages/local-installation/AGENTS.md@@ -41,10 +41,16 @@ first on macOS, and a program on ::1 alone would answer for a service thatbound 127.0.0.1 without an error. The web static host listens on both. Eachstart re-checks a stopped service's ports and moves one another program tookto a free port, persisted in `instance.json` or `livekit.env`, so the service-restarts with the new environment. The web port is the product origin, which-the browser session, the desktop app and the Computer keep once the owner-account exists (or a database set aside from an older install marks it to be-made again); it moves only before that. The account step sends a password only+restarts with the new environment. The web port is the product origin+(`instance.origin`, `WEB_PUBLIC_ORIGIN`). For the desktop's instance+(`externalComputer`) it moves like the others: the desktop follows the origin+the installer reports and keeps its Computer and session. A Computer this+installer enrolled keeps the origin once the owner account exists (or a+database set aside from an older install marks it to be made again), because+its self-update source and a pending enrollment credential name it; there it+moves only before that. A moved port is saved without the checkout an+update rebinds to, which `instance.json` names only once the services serve+from it. The account step sends a password onlyafter the origin's `/v0/local/identity` proof, and a service that stops on ataken port names the port, instead of a foreign server's answer or a barefailure.diff --git a/packages/local-installation/src/native-source.test.ts b/packages/local-installation/src/native-source.test.tsindex 52d22553..65214c5f 100644--- a/packages/local-installation/src/native-source.test.ts+++ b/packages/local-installation/src/native-source.test.ts@@ -247,8 +247,8 @@ test("a resumed instance moves off ports another program took", async () => {);expect(second.warnings).toHaveLength(5);- // Once the owner account exists, the browser session and the desktop app- // keep the origin: the web port stays and its service reports the program.+ // Once the owner account exists, a Computer this installer enrolled keeps+ // the origin: the web port stays and its service reports the program.await writeFile(path.join(first.instance.root, "local-account.json"),JSON.stringify({ provisioned: true }),@@ -261,7 +261,7 @@ test("a resumed instance moves off ports another program took", async () => {expect(third.warnings).toEqual([]);// A database set aside from an older install marks the account to be made- // again, but that install's desktop still keeps the origin.+ // again, but that install's Computer still keeps the origin.await writeFile(path.join(first.instance.root, "local-account.json"),JSON.stringify({ provisioned: false }),@@ -272,3 +272,46 @@ test("a resumed instance moves off ports another program took", async () => {expect(fourth.instance.port).toBe(after.web);expect(fourth.warnings).toEqual([]);});+test("the desktop's web origin moves off a taken port after the account exists", async () => {+ const f = await fixture();+ const options = { home: f.home, name: "desktop", externalComputer: true };+ const first = await prepareNativeConfiguration(f.repo, options);+ const before = first.instance.source!.ports;+ await writeFile(+ path.join(first.instance.root, "local-account.json"),+ JSON.stringify({ provisioned: true }),+ { mode: 0o600 },+ );+ // A database set aside from an older install does not hold it either.+ await mkdir(path.join(first.instance.root, "simplex-backup-earlier"));+ await occupy(before.web);+ // The desktop update that finds the port taken also brings a new checkout.+ const next = path.join(f.home, "next");+ await mkdir(path.join(next, "scripts"), { recursive: true });+ for (const file of ["package.json", "scripts/source-native.mjs"])+ await writeFile(+ path.join(next, file),+ await readFile(path.join(f.repo, file)),+ );++ const second = await prepareNativeConfiguration(next, {+ ...options,+ rebindSource: true,+ });+ const after = second.instance.source!.ports;+ expect(after.web).not.toBe(before.web);+ expect(second.instance.port).toBe(after.web);+ expect(second.instance.origin).toBe(`http://localhost:${after.web}`);+ expect(second.env.WEB_PUBLIC_ORIGIN).toBe(second.instance.origin);+ expect(second.env.WEB_HTTP_PORT).toBe(String(after.web));+ expect(second.warnings.join("")).toContain(+ `Port ${before.web} is in use by another program; Linger's web uses port ${after.web} instead.`,+ );+ // The moved origin is saved at once; the checkout only once the services+ // serve from it.+ const stored = await loadInstance(options);+ expect(stored?.origin).toBe(second.instance.origin);+ expect(stored?.source?.ports).toEqual(after);+ expect(stored?.releaseDir).toBe(f.repo);+ expect(stored?.source?.repo).toBe(f.repo);+});diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.tsindex 7f5b440e..39100c63 100644--- a/packages/local-installation/src/native-source.ts+++ b/packages/local-installation/src/native-source.ts@@ -89,6 +89,7 @@ export async function prepareNativeConfiguration(home?: string;port?: number;computerName?: string;+ externalComputer?: boolean;rebindSource?: boolean;} = {},) {diff --git a/packages/local-installation/src/source-checkout.ts b/packages/local-installation/src/source-checkout.tsindex 6f3f7081..a9d76034 100644--- a/packages/local-installation/src/source-checkout.ts+++ b/packages/local-installation/src/source-checkout.ts@@ -209,14 +209,17 @@ export async function prepareSourceConfiguration(// A port another program took since it was chosen moves to a free one// while the service that listens there is stopped; the services then// restart because their environment names the new port. The web port is- // the product origin, which the browser session, the desktop app and the- // Computer keep once the account exists, so it moves only before that;- // after it, the web service reports the program on its port. A database- // set aside from an older install marks the account to be made again, but- // that install's desktop still keeps the origin.+ // the product origin. The desktop app follows it to a new port and keeps+ // its Computer and session, so for the desktop it moves like the others.+ // A Computer this installer enrolled keeps it once the owner account+ // exists (or a database set aside from an older install marks the+ // account to be made again): its self-update source and a pending+ // enrollment credential name the origin. There the web service reports+ // the program on its port instead.const keepsOrigin =- (await localAccountProvisioned(instance.root)) ||- (await latestLegacyBackup(instance.root)) !== undefined;+ !options.externalComputer &&+ ((await localAccountProvisioned(instance.root)) ||+ (await latestLegacyBackup(instance.root)) !== undefined);const movable = Object.entries(portOwners).filter(([name]) => !keepsOrigin || name !== "web",) as [keyof typeof portOwners, NativeService][];@@ -241,9 +244,24 @@ export async function prepareSourceConfiguration(instance.port = next;instance.origin = `http://localhost:${next}`;}+ // Only the ports change on disk: a checkout this run rebinds to is+ // saved once the services serve from it (saveSourceBinding).+ const stored = (await loadInstance({+ name: instance.name,+ home: path.resolve(instance.root, "../.."),+ }))!;await atomicPrivate(path.join(instance.root, "instance.json"),- JSON.stringify(instance, null, 2) + "\n",+ JSON.stringify(+ {+ ...stored,+ port: instance.port,+ origin: instance.origin,+ source: { ...stored.source!, ports: { ...instance.source.ports } },+ },+ null,+ 2,+ ) + "\n",);warnings.push(`Port ${port} is in use by another program; Linger's ${owner} uses port ${next} instead.\n`,