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(computer): name the daemon only to a TeamHub that accepts it
Dongdong Chen6bc19cffc48a
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 0fb07a66..87a7f754 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -211,6 +211,13 @@ Gateway and runs Agents. The daemon exits with the app.with any remembered `computerId` for that origin and owner so re-enrolling orrecovering an interrupted exchange renews the existing Computer ID andsurfaces `DAEMON_IDENTITY_IN_USE` / `DAEMON_IDENTITY_MISMATCH` conflicts.+ It sends `daemon_id` only when the server's `/v0/me` lists the+ `local_computer_enrollment_daemon_id` server capability; a TeamHub older+ than the desktop omits it and would reject the field. `config.json` keeps+ the `daemonId` the active enrollment named, and at start an enrollment that+ named none or another one is renewed once the server lists the capability,+ so a computer an earlier Set Up Again paired anew gets back the Computer+ that holds its Daemon Identity, with its Agents.Before installing or resuming it moves the`COMPOSIO_API_KEY`, `SONIOX_API_KEY`, `XAI_API_KEY` and `TZ` of an unpackedsource package's `.env` into `<home>/instances/desktop/user.env` once anddiff --git a/apps/desktop/src/main/config.ts b/apps/desktop/src/main/config.tsindex c3876491..5671c9e6 100644--- a/apps/desktop/src/main/config.ts+++ b/apps/desktop/src/main/config.ts@@ -31,6 +31,9 @@ const desktopConfig = z.object({computerId: z.string().optional(),tenantId: z.string().optional(),ownerActorId: z.string().optional(),+ // The Daemon ID the active enrollment named; an enrollment that named none+ // or another one is renewed once at start.+ daemonId: z.string().optional(),// Previous enrollments by server origin so re-enrolling after a local reset// or server switch renews the same Computer ID for the same account.savedEnrollments: z.record(z.string(), savedEnrollment).optional(),diff --git a/apps/desktop/src/main/enrollment.test.ts b/apps/desktop/src/main/enrollment.test.tsindex 3cef0110..d56ce368 100644--- a/apps/desktop/src/main/enrollment.test.ts+++ b/apps/desktop/src/main/enrollment.test.ts@@ -5,6 +5,7 @@ import path from "node:path";import { describe, expect, it, vi } from "vitest";import { CredentialStore } from "./computer-credential.js";+import type { DesktopConfig } from "./config.js";import {EnrollmentError,EnrollmentModule,@@ -28,10 +29,20 @@ interface Call {readonly body: Record<string, unknown> | undefined;}+// The /v0/me server capability of a TeamHub whose enrollment accepts+// daemon_id; an older TeamHub lists none and rejects the field.+const DAEMON_CAPABLE = ["local_computer_enrollment_daemon_id"];+interface ServerOverrides {+ // The server_capabilities /v0/me lists; null omits the list, as a TeamHub+ // that predates it does.+ readonly capabilities?: readonly string[] | null;readonly exchangeStatus?: number;readonly bundle?: Record<string, unknown>;readonly meActorId?: string;+ // The Computer that holds the daemon's identity, which TeamHub renews when+ // an enrollment names the daemon.+ readonly daemonHeldBy?: string;readonly onCreate?: (body: Record<string, unknown> | undefined,) => Response | undefined;@@ -65,6 +76,9 @@ const fakeServer = (...(overrides.meActorId ? { id: overrides.meActorId } : {}),},],+ ...(overrides.capabilities === null+ ? {}+ : { server_capabilities: overrides.capabilities ?? DAEMON_CAPABLE }),});if (input.pathname.endsWith("/local-computer-enrollments")) {const custom = overrides.onCreate?.(body);@@ -73,9 +87,11 @@ const fakeServer = (return json({enrollment_id: "enr_1",computer_id:- typeof body?.computer_id === "string"- ? body.computer_id- : "computer_1",+ overrides.daemonHeldBy && body?.daemon_id+ ? overrides.daemonHeldBy+ : typeof body?.computer_id === "string"+ ? body.computer_id+ : "computer_1",authorization_code: "code_1",expires_at: "2026-10-16T08:00:00Z",});@@ -209,14 +225,34 @@ describe("enrollComputer", () => {it("includes daemon_id when provided", async () => {const server = fakeServer();- await enrollComputer({+ const enrolled = await enrollComputer({...input,daemonId: "A".repeat(43),fetch: server.fetch,});expect(server.calls[1]?.body?.daemon_id).toBe("A".repeat(43));+ expect(enrolled.daemonId).toBe("A".repeat(43));});+ it.each([+ ["predates the capability list", null],+ ["does not list the capability", []],+ ] as const)(+ "omits daemon_id for a server that %s",+ async (_name, capabilities) => {+ // TeamHub decodes request bodies strictly, so an older one rejects it.+ const server = fakeServer({ capabilities });+ const enrolled = await enrollComputer({+ ...input,+ daemonId: "A".repeat(43),+ fetch: server.fetch,+ });+ expect(server.calls[1]?.body).not.toHaveProperty("daemon_id");+ expect(enrolled.computerId).toBe("computer_1");+ expect(enrolled).not.toHaveProperty("daemonId");+ },+ );+it("omits saved computer_id only when another owner signed in", async () => {const otherOwner = fakeServer({ meActorId: "actor_bob" });await enrollComputer({@@ -356,6 +392,7 @@ describe("EnrollmentModule", () => {const setupModule = (serverOverrides: ServerOverrides = {},initialServerUrl = "https://linger.example.com",+ initialConfig: Partial<DesktopConfig> = {},) => {const dir = tempDirectory();const daemonIdentityFile = path.join(dir, "daemon-identity.json");@@ -372,12 +409,87 @@ describe("EnrollmentModule", () => {});const host = testHost([stubModule("Config"), enrollment],- { serverUrl: initialServerUrl },+ { serverUrl: initialServerUrl, ...initialConfig },bus,);return { enrollment, host, bus, server, credentials, daemonId };};+ // A computer enrolled by a release that did not name its daemon: Set Up+ // Again there paired computer_orphan while the daemon's identity stayed+ // bound to the Computer it had before.+ const enrolledWithoutDaemon = (+ serverOverrides: ServerOverrides = {},+ initialConfig: Partial<DesktopConfig> = {},+ ) => {+ const setup = setupModule(serverOverrides, "https://linger.example.com", {+ computerId: "computer_orphan",+ tenantId: "tenant_acme",+ ownerActorId: "actor_ann",+ ...initialConfig,+ });+ setup.credentials.write({+ computerId: "computer_orphan",+ gatewayUrl: "wss://linger.example.com/v1/runner",+ token: TOKEN,+ });+ return setup;+ };+ const enrollmentCalls = (calls: readonly Call[]): Call[] =>+ calls.filter((call) => call.url.endsWith("/local-computer-enrollments"));++ it("renews once at start an enrollment that did not name the daemon", async () => {+ const { host, server, daemonId } = enrolledWithoutDaemon({+ daemonHeldBy: "computer_1",+ });+ await host.start();+ await vi.waitFor(() =>+ expect(host.ctx.config.get().computerId).toBe("computer_1"),+ );+ const creates = enrollmentCalls(server.calls);+ expect(creates).toHaveLength(1);+ expect(creates[0]?.body).toMatchObject({+ computer_id: "computer_orphan",+ daemon_id: daemonId,+ });+ expect(host.ctx.config.get().daemonId).toBe(daemonId);+ await host.stop("quit");+ });++ it("does not renew at start an enrollment that named the daemon", async () => {+ const { host, server, daemonId } = enrolledWithoutDaemon();+ host.ctx.config.update({ daemonId });+ await host.start();+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(server.calls).toEqual([]);+ expect(host.ctx.config.get().computerId).toBe("computer_orphan");+ await host.stop("quit");+ });++ it("does not renew at start only to name the daemon to a server that cannot take it", async () => {+ const { host, server } = enrolledWithoutDaemon({ capabilities: null });+ await host.start();+ await vi.waitFor(() =>+ expect(server.calls.map((call) => call.url)).toEqual(["/v0/me"]),+ );+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(server.calls.map((call) => call.url)).toEqual(["/v0/me"]);+ expect(host.ctx.config.get().computerId).toBe("computer_orphan");+ await host.stop("quit");+ });++ it("enrolls without the daemon's identity on a server that does not accept it", async () => {+ const { enrollment, host, server } = setupModule({ capabilities: null });+ await host.start();+ await enrollment.enroll();+ expect(enrollmentCalls(server.calls)[0]?.body).not.toHaveProperty(+ "daemon_id",+ );+ expect(host.ctx.config.get().computerId).toBe("computer_1");+ expect(host.ctx.config.get().daemonId).toBeUndefined();+ await host.stop("quit");+ });+it("renews the same Computer ID after unenroll using savedEnrollments and daemonId", async () => {const { enrollment, host, server, daemonId } = setupModule();await host.start();diff --git a/apps/desktop/src/main/enrollment.ts b/apps/desktop/src/main/enrollment.tsindex a1f99e0e..a529b675 100644--- a/apps/desktop/src/main/enrollment.ts+++ b/apps/desktop/src/main/enrollment.ts@@ -12,6 +12,11 @@ type CreateRequest = Schemas["LocalComputerEnrollmentCreateRequest"];type Authorization = Schemas["LocalComputerEnrollmentAuthorization"];type ExchangeRequest = Schemas["LocalComputerEnrollmentExchangeRequest"];type CredentialBundle = Schemas["LocalComputerCredentialBundle"];+type ServerCapability = NonNullable<+ Schemas["CurrentIdentity"]["server_capabilities"]+>[number];+const DAEMON_ID_CAPABILITY: ServerCapability =+ "local_computer_enrollment_daemon_id";// The main process both creates and exchanges the enrollment, so nothing is// ever redirected here. TeamHub still requires a loopback redirect URI.@@ -42,7 +47,8 @@ export interface EnrollInput {readonly displayName: string;// Keeps the same Computer identity when enrolling again.readonly computerId?: string;- // SHA-256 of the local Daemon public key in base64url.+ // SHA-256 of the local Daemon public key in base64url. Sent only to a+ // server whose /v0/me lists the capability, since an older one rejects it.readonly daemonId?: string;// When re-enrolling after a reset, omit computerId if another account signed in.readonly expectedOwnerActorId?: string;@@ -63,6 +69,8 @@ export interface Enrolled {// The Runner Gateway the daemon connects to (ws or wss).readonly gatewayUrl: string;readonly credential: string;+ // The Daemon ID the enrollment named, when the server accepted one.+ readonly daemonId?: string;}// PKCE enrollment for this computer with the current web session:@@ -91,10 +99,13 @@ export const enrollComputer = async (input: EnrollInput): Promise<Enrolled> => {if (me.status === 401)throw new EnrollmentError("NOT_SIGNED_IN", "Sign in before enrolling");if (!me.ok) throw rejected("Reading the signed-in account", me.status);- const actor = humanActor(await me.json());+ const identity: unknown = await me.json();+ const actor = humanActor(identity);if (!actor)throw new EnrollmentError("NO_TENANT", "The account has no workspace");const { tenantId, actorId } = actor;+ const daemonId =+ input.daemonId && acceptsDaemonId(identity) ? input.daemonId : undefined;const candidateComputerId =input.expectedOwnerActorId &&@@ -112,7 +123,7 @@ export const enrollComputer = async (input: EnrollInput): Promise<Enrolled> => {redirect_uri: REDIRECT_URI,code_challenge: createHash("sha256").update(verifier).digest("base64url"),...(computerId ? { computer_id: computerId } : {}),- ...(input.daemonId ? { daemon_id: input.daemonId } : {}),+ ...(daemonId ? { daemon_id: daemonId } : {}),};const response = await call(`/v0/tenants/${encodeURIComponent(tenantId)}/local-computer-enrollments`,@@ -197,9 +208,20 @@ export const enrollComputer = async (input: EnrollInput): Promise<Enrolled> => {ownerActorId,gatewayUrl: bundle.gateway_url,credential: bundle.gateway_token,+ ...(daemonId ? { daemonId } : {}),};};+// Whether the server's /v0/me lists that its enrollment accepts daemon_id.+// A TeamHub older than the desktop omits the list and rejects the field.+function acceptsDaemonId(identity: unknown): boolean {+ const capabilities = (identity as { server_capabilities?: unknown } | null)+ ?.server_capabilities;+ return (+ Array.isArray(capabilities) && capabilities.includes(DAEMON_ID_CAPABILITY)+ );+}+const isGatewayUrl = (value: unknown): value is string => {if (typeof value !== "string") return false;try {@@ -358,15 +380,22 @@ export class EnrollmentModule implements Module {// 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();+ if (!config.computerId) return;+ const renewFailed = (error: unknown): void =>+ ctx.log.warn("enrollment.renew_failed", { error: String(error) });if (- config.computerId &&- (!config.ownerActorId ||- this.#options.credentials.read()?.computerId !== config.computerId)+ !config.ownerActorId ||+ this.#options.credentials.read()?.computerId !== config.computerId) {- void this.enroll().catch((error: unknown) =>- ctx.log.warn("enrollment.renew_failed", { error: String(error) }),- );+ void this.enroll().catch(renewFailed);+ return;}+ // So, once, is an enrollment that did not name the daemon's identity:+ // Set Up Again in an earlier release paired a new Computer while the+ // identity stayed bound to the old one, and naming it renews the old one.+ const daemonId = this.#readDaemonId();+ if (daemonId !== undefined && config.daemonId !== daemonId)+ void this.#nameDaemon().catch(renewFailed);}async stop(): Promise<void> {@@ -375,10 +404,16 @@ export class EnrollmentModule implements Module {// Whether the window holds a valid session for the configured server.async signedIn(): Promise<boolean> {+ return (await this.#identity()) !== undefined;+ }++ // The signed-in identity (/v0/me) on the configured server, or undefined+ // when signed out or unreachable.+ async #identity(): Promise<unknown> {const serverUrl = this.#ctx!.config.get().serverUrl;- if (!serverUrl) return false;+ if (!serverUrl) return undefined;const cookie = await this.#options.sessionCookie(serverUrl);- if (!cookie) return false;+ if (!cookie) return undefined;try {const response = await (this.#options.fetch ?? fetch)(new URL("/v0/me", serverUrl),@@ -388,12 +423,24 @@ export class EnrollmentModule implements Module {signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),},);- return response.ok;+ return response.ok ? ((await response.json()) as unknown) : undefined;} catch {- return false;+ return undefined;}}+ // Renews the enrollment so it names the daemon's identity, only on a+ // server that accepts it, so an older one sees no credential rotation.+ async #nameDaemon(): Promise<void> {+ if (acceptsDaemonId(await this.#identity())) await this.enroll();+ }++ #readDaemonId(): string | undefined {+ return this.#options.daemonIdentityFile+ ? readDaemonId(this.#options.daemonIdentityFile)+ : undefined;+ }+enroll(): Promise<{ computerId: string }> {// Concurrent clicks share one enrollment instead of creating two.this.#pending ??= this.#enroll().finally(() => {@@ -431,6 +478,7 @@ export class EnrollmentModule implements Module {computerId: undefined,tenantId: undefined,ownerActorId: undefined,+ daemonId: undefined,...(saved ? { savedEnrollments: saved } : {}),});ctx.bus.emit("computer.changed", undefined);@@ -450,9 +498,7 @@ export class EnrollmentModule implements Module {const expectedOwnerActorId = config.computerId? undefined: saved?.ownerActorId;- const daemonId = this.#options.daemonIdentityFile- ? readDaemonId(this.#options.daemonIdentityFile)- : undefined;+ const daemonId = this.#readDaemonId();const serverUrl = config.serverUrl;const enrolled = await enrollComputer({serverUrl,@@ -481,6 +527,7 @@ export class EnrollmentModule implements Module {computerId: enrolled.computerId,tenantId: enrolled.tenantId,ownerActorId: enrolled.ownerActorId,+ daemonId: enrolled.daemonId,...(nextSaved ? { savedEnrollments: nextSaved } : {}),});ctx.bus.emit("computer.changed", enrolled.computerId);diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.tsindex 3c525fad..c2a6ecb8 100644--- a/apps/desktop/src/main/local-server.test.ts+++ b/apps/desktop/src/main/local-server.test.ts@@ -3126,6 +3126,7 @@ describe("LocalServerModule after a restart", () => {if (url.pathname === "/v0/me")return Response.json({actors: [{ id: "actor_ann", kind: "human", tenant_id: "t1" }],+ server_capabilities: ["local_computer_enrollment_daemon_id"],});if (url.pathname === "/v0/tenants/t1/local-computer-enrollments") {const body = JSON.parse(String(init?.body)) as Record<string, unknown>;diff --git a/apps/teamhub/internal/app/models.go b/apps/teamhub/internal/app/models.goindex 68154f53..6df8b664 100644--- a/apps/teamhub/internal/app/models.go+++ b/apps/teamhub/internal/app/models.go@@ -33,11 +33,19 @@ func (a *App) identity(ctx context.Context, session store.GetActiveSessionRow) (models = append(models, collaboration.ActorModel(actor))}return httpapi.CurrentIdentity{- Account: accountModel(session.AccountID, session.Email, session.AccountCreatedAt),- Actors: models,+ Account: accountModel(session.AccountID, session.Email, session.AccountCreatedAt),+ Actors: models,+ ServerCapabilities: &serverCapabilities,}, nil}+// serverCapabilities lists the request fields this TeamHub accepts that an+// earlier release rejected, so a client newer than its server sends one only+// when it is listed here.+var serverCapabilities = []httpapi.CurrentIdentityServerCapabilities{+ httpapi.LocalComputerEnrollmentDaemonId,+}+func (a *App) sessionModel(ctx context.Context, session store.GetActiveSessionRow) (httpapi.Session, error) {identity, err := a.identity(ctx, session)if err != nil {diff --git a/apps/teamhub/tests/integration/local_computer_test.go b/apps/teamhub/tests/integration/local_computer_test.goindex 162a09b2..74d5d934 100644--- a/apps/teamhub/tests/integration/local_computer_test.go+++ b/apps/teamhub/tests/integration/local_computer_test.go@@ -365,6 +365,13 @@ func TestLocalComputerEnrollmentDaemonIdentityHTTP(t *testing.T) {alice := env.login("alice", alicePassword)bob := seedPeerHuman(t, env)+ // A desktop newer than its server names its Daemon only when /v0/me lists+ // the capability, because an older TeamHub rejects the unknown field.+ if status, _, meBody := env.request(alice, http.MethodGet, "/v0/me", nil, ""); status != http.StatusOK ||+ !strings.Contains(string(meBody), `"server_capabilities":["local_computer_enrollment_daemon_id"]`) {+ t.Fatalf("read the enrollment capability status=%d body=%s", status, meBody)+ }+computerA := enrollLocalComputerOverHTTP(t, env, alice, "Alice's Mac", "")if _, err := pool.Exec(t.Context(), `INSERT INTO actors(id,tenant_id,kind,display_name,handle)@@ -449,6 +456,28 @@ func TestLocalComputerEnrollmentDaemonIdentityHTTP(t *testing.T) {t.Fatalf("reconnect renewed Computer A status=%d body=%s", status, body)}+ // A desktop whose earlier release paired a new Computer without naming its+ // Daemon renews at start naming both; the owner's Computer holding the+ // Daemon Identity is renewed instead of the never-connected one.+ orphan := enrollLocalComputerOverHTTP(t, env, alice, "Alice's Mac", "")+ status, _, healBody := env.request(alice, http.MethodPost, "/v0/tenants/"+acmeTenant+"/local-computer-enrollments", map[string]any{+ "computer_id": orphan,+ "daemon_id": daemonID,+ "display_name": "Alice's Mac",+ "redirect_uri": "http://127.0.0.1:45123/callback",+ "code_challenge": challengeB64,+ }, "")+ var healed struct {+ ComputerID string `json:"computer_id"`+ }+ if status != http.StatusCreated {+ t.Fatalf("renew the orphan naming the Daemon status=%d body=%s", status, healBody)+ }+ decode(t, healBody, &healed)+ if healed.ComputerID != computerA {+ t.Fatalf("renew the orphan naming the Daemon computer_id=%q, want %q", healed.ComputerID, computerA)+ }+status, _, mismatchBody := env.request(alice, http.MethodPost, "/v0/tenants/"+acmeTenant+"/local-computer-enrollments", map[string]any{"computer_id": computerA,"daemon_id": strings.Repeat("Z", 43),diff --git a/contracts/generated/go/teamhubpublic/openapi.gen.go b/contracts/generated/go/teamhubpublic/openapi.gen.goindex 61c5dca7..da95f972 100644--- a/contracts/generated/go/teamhubpublic/openapi.gen.go+++ b/contracts/generated/go/teamhubpublic/openapi.gen.go@@ -839,6 +839,21 @@ func (e CreatableAgentType) Valid() bool {}}+// Defines values for CurrentIdentityServerCapabilities.+const (+ LocalComputerEnrollmentDaemonId CurrentIdentityServerCapabilities = "local_computer_enrollment_daemon_id"+)++// Valid indicates whether the value is a known member of the CurrentIdentityServerCapabilities enum.+func (e CurrentIdentityServerCapabilities) Valid() bool {+ switch e {+ case LocalComputerEnrollmentDaemonId:+ return true+ default:+ return false+ }+}+// Defines values for DecisionAnswerDecision.const (DecisionAnswerApprove DecisionAnswerDecision = "approve"@@ -5040,8 +5055,14 @@ type CurrentIdentity struct {// Actors Active Human Actor identities available to this Account, one per Tenant in V0.Actors []Actor `json:"actors"`++ // ServerCapabilities Request fields this TeamHub accepts that earlier releases rejected, so a client newer than its server sends one only when the server lists it. A TeamHub that predates this list omits it. local_computer_enrollment_daemon_id: Local Computer enrollment accepts daemon_id.+ ServerCapabilities *[]CurrentIdentityServerCapabilities `json:"server_capabilities,omitempty"`}+// CurrentIdentityServerCapabilities defines model for CurrentIdentity.ServerCapabilities.+type CurrentIdentityServerCapabilities string+// Cursor Opaque pagination cursor. Clients must not parse or modify it.type Cursor = stringdiff --git a/contracts/generated/typescript/src/generated/teamhub-public/types.ts b/contracts/generated/typescript/src/generated/teamhub-public/types.tsindex ced85053..71ec6b2d 100644--- a/contracts/generated/typescript/src/generated/teamhub-public/types.ts+++ b/contracts/generated/typescript/src/generated/teamhub-public/types.ts@@ -4179,6 +4179,8 @@ export interface components {account: components["schemas"]["Account"];/** @description Active Human Actor identities available to this Account, one per Tenant in V0. */actors: components["schemas"]["Actor"][];+ /** @description Request fields this TeamHub accepts that earlier releases rejected, so a client newer than its server sends one only when the server lists it. A TeamHub that predates this list omits it. local_computer_enrollment_daemon_id: Local Computer enrollment accepts daemon_id. */+ server_capabilities?: "local_computer_enrollment_daemon_id"[];};Session: {id: components["schemas"]["Id"];diff --git a/contracts/openapi/components/domain.yaml b/contracts/openapi/components/domain.yamlindex 641abe4b..c55df4a4 100644--- a/contracts/openapi/components/domain.yaml+++ b/contracts/openapi/components/domain.yaml@@ -677,6 +677,16 @@ components:description: Active Human Actor identities available to this Account, one per Tenant in V0.items:$ref: "#/components/schemas/Actor"+ server_capabilities:+ type: array+ description: >-+ Request fields this TeamHub accepts that earlier releases rejected, so a client+ newer than its server sends one only when the server lists it. A TeamHub that+ predates this list omits it. local_computer_enrollment_daemon_id: Local Computer+ enrollment accepts daemon_id.+ items:+ type: string+ enum: [local_computer_enrollment_daemon_id]Session:type: objectadditionalProperties: false