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): renew existing Computer across reset and surface Daemon Identity conflicts
Dongdong Chenf3f6c19e4db6
diff --git a/apps/computer/local-daemon/internal/computercli/cli.go b/apps/computer/local-daemon/internal/computercli/cli.goindex 587da448..701bc133 100644--- a/apps/computer/local-daemon/internal/computercli/cli.go+++ b/apps/computer/local-daemon/internal/computercli/cli.go@@ -742,6 +742,8 @@ func (c *cli) connectionFailure(state string) (string, bool) {switch state {case "authentication-failed":return "Rejected by the server. Run " + c.command + " login to authorize again.", true+ case "identity-conflict":+ return "This computer's identity is already bound to another Computer registration. Run " + c.command + " login to reconnect it.", truecase "upgrade-required":return "The server requires a newer Linger Computer. Rerun the installer.", true}@@ -770,7 +772,7 @@ func (c *cli) reportConnection(ctx context.Context, configPath string) (int, errreport := c.waitForConnection(ctx, configPath)c.out(c.formatStatus(report))switch state, _ := report.Daemon.string("gateway_state"); state {- case "authentication-failed":+ case "authentication-failed", "identity-conflict":return exitCodes[categoryCredential], nilcase "upgrade-required":return exitCodes[categoryConfiguration], nildiff --git a/apps/computer/local-daemon/internal/computercli/cli_test.go b/apps/computer/local-daemon/internal/computercli/cli_test.goindex e7d1f125..c92f2455 100644--- a/apps/computer/local-daemon/internal/computercli/cli_test.go+++ b/apps/computer/local-daemon/internal/computercli/cli_test.go@@ -284,6 +284,12 @@ func TestDaemonStartShowsProcessConnectionAndRuntimes(t *testing.T) {t.Fatalf("exit=%d", code)}contains(t, f.stdout.String(), "Connection Rejected by the server. Run linger-computer login to authorize again.\n")+ f.clear()+ f.gatewayState = "identity-conflict"+ if code := f.run("daemon", "start", "--config", f.configPath); code != 11 {+ t.Fatalf("exit=%d", code)+ }+ contains(t, f.stdout.String(), "Connection This computer's identity is already bound to another Computer registration. Run linger-computer login to reconnect it.\n")}func TestDefaultConfigLocations(t *testing.T) {@@ -676,6 +682,16 @@ func TestDoctorFailures(t *testing.T) {}contains(t, f.stdout.String(), "{\n \"name\": \"runtime:codex\",\n \"category\": \"capabilityProbe\",\n \"status\": \"fail\",\n \"detail\": \"Codex authentication is required\"\n }")contains(t, f.stdout.String(), "{\n \"name\": \"credential\",\n \"category\": \"credential\",\n \"status\": \"pass\",")++ f = newFixture(t)+ f.gatewayState = "identity-conflict"+ f.deps.inspectDaemon = func(ctx context.Context, _ string) doctorCheck {+ return inspectDaemonHealth(ctx, fakeClient{f: f}, "linger-computer")+ }+ if code := f.run("doctor", "--json", "--config", f.configPath); code != 11 {+ t.Fatalf("identity-conflict doctor exit=%d", code)+ }+ contains(t, f.stdout.String(), "already bound to another Computer registration")}func TestDoctorPrune(t *testing.T) {diff --git a/apps/computer/local-daemon/internal/computercli/doctor.go b/apps/computer/local-daemon/internal/computercli/doctor.goindex 1bb14afe..10710623 100644--- a/apps/computer/local-daemon/internal/computercli/doctor.go+++ b/apps/computer/local-daemon/internal/computercli/doctor.go@@ -177,6 +177,11 @@ func inspectDaemonHealth(ctx context.Context, client controlClient, commandNameName: "daemon", Category: categoryCredential, Status: "fail",Detail: fmt.Sprintf("Gateway rejected this enrollment. If the server-side Computer was deleted, run %s doctor --prune, then %s login", commandName, commandName),}+ case "identity-conflict":+ return doctorCheck{+ Name: "daemon", Category: categoryCredential, Status: "fail",+ Detail: fmt.Sprintf("This computer's Daemon Identity is already bound to another Computer registration. Run %s login to reconnect, or %s doctor --prune to reset local state", commandName, commandName),+ }case "upgrade-required":return doctorCheck{Name: "daemon", Category: categoryConfiguration, Status: "fail",diff --git a/apps/computer/local-daemon/internal/daemon/daemon.go b/apps/computer/local-daemon/internal/daemon/daemon.goindex 04141f55..adac90e0 100644--- a/apps/computer/local-daemon/internal/daemon/daemon.go+++ b/apps/computer/local-daemon/internal/daemon/daemon.go@@ -270,6 +270,8 @@ func New(options Options) (*Daemon, error) {}, nil}+// Run loads or creates the Daemon Identity and keeps the Gateway stream+// connected until ctx ends or a terminal configuration error stops redials.func (d *Daemon) Run(ctx context.Context) error {defer func() {_, _ = native.StopAllParkedResidents()@@ -316,6 +318,12 @@ func (d *Daemon) Run(ctx context.Context) error {<-ctx.Done()return ctx.Err()}+ var daemonIdentityInUse *transport.DaemonIdentityInUseError+ if errors.As(err, &daemonIdentityInUse) {+ d.setGatewayState("identity-conflict")+ <-ctx.Done()+ return ctx.Err()+ }if transport.IsGatewayRestart(err) {if !d.now().Before(quickRedialUntil) {slog.Info("Runner Gateway is restarting; redialing at the shortest delay", "window", gatewayRestartRedialWindow)diff --git a/apps/computer/local-daemon/internal/daemon/daemon_test.go b/apps/computer/local-daemon/internal/daemon/daemon_test.goindex 5aeeacc6..81081999 100644--- a/apps/computer/local-daemon/internal/daemon/daemon_test.go+++ b/apps/computer/local-daemon/internal/daemon/daemon_test.go@@ -1690,6 +1690,37 @@ func TestDaemonRetainsUpgradeRequiredStatus(t *testing.T) {}}+func TestDaemonRetainsIdentityConflictStatusWithoutRedialing(t *testing.T) {+ device, err := transport.GenerateIdentity()+ if err != nil {+ t.Fatal(err)+ }+ stream := &fakeStream{receiveErr: &transport.DaemonIdentityInUseError{Reason: "daemon_identity_in_use: reconnect this Computer"}}+ controlPlane := &sequenceControlPlane{streams: []*fakeStream{stream}}+ daemon, err := newTestDaemon(t, Options{+ ComputerID: "computer-1", ControlPlane: controlPlane,+ IdentityStore: fakeStore{value: device}, OperationResolver: fakeOperationResolver{},+ RetryDelay: func(int) time.Duration { return 0 },+ })+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() { done <- daemon.Run(ctx) }()+ waitForGatewayState(t, daemon, "identity-conflict")+ controlPlane.mu.Lock()+ calls := controlPlane.calls+ controlPlane.mu.Unlock()+ if calls != 1 {+ t.Fatalf("identity-conflict connect attempts = %d, want 1", calls)+ }+ cancel()+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("Run() error = %v, want context cancellation", err)+ }+}+func TestDaemonDisconnectDoesNotCancelRunningOperation(t *testing.T) {device, err := transport.GenerateIdentity()if err != nil {diff --git a/apps/computer/local-daemon/internal/linger/transport/gateway.go b/apps/computer/local-daemon/internal/linger/transport/gateway.goindex e0b2906c..bf4afb83 100644--- a/apps/computer/local-daemon/internal/linger/transport/gateway.go+++ b/apps/computer/local-daemon/internal/linger/transport/gateway.go@@ -113,9 +113,13 @@ func (s *gatewayStream) Receive(ctx context.Context) (protocol.Command, error) {_, encoded, err := s.socket.ReadMessage()if err != nil {var closeError *websocket.CloseError- if errors.As(err, &closeError) && closeError.Code == websocket.ClosePolicyViolation &&- strings.HasPrefix(closeError.Text, "upgrade_required:") {- return protocol.Command{}, &UpgradeRequiredError{Reason: closeError.Text}+ if errors.As(err, &closeError) && closeError.Code == websocket.ClosePolicyViolation {+ if strings.HasPrefix(closeError.Text, "upgrade_required:") {+ return protocol.Command{}, &UpgradeRequiredError{Reason: closeError.Text}+ }+ if strings.HasPrefix(closeError.Text, "daemon_identity_in_use:") {+ return protocol.Command{}, &DaemonIdentityInUseError{Reason: closeError.Text}+ }}return protocol.Command{}, err}@@ -310,11 +314,18 @@ func IsGatewayRestart(err error) bool {return closeError.Code == websocket.CloseGoingAway || closeError.Code == websocket.CloseServiceRestart}+// ClassifyConnectionFailure separates release incompatibilities from transient or+// account-level connection errors so self-update never blames a bad release for an+// external state conflict.func ClassifyConnectionFailure(err error) ConnectionFailure {var upgradeRequired *UpgradeRequiredErrorif errors.As(err, &upgradeRequired) {return FailureIncompatible}+ var daemonIdentityInUse *DaemonIdentityInUseError+ if errors.As(err, &daemonIdentityInUse) {+ return FailureUnavailable+ }var closeError *websocket.CloseErrorif errors.As(err, &closeError) {switch closeError.Code {@@ -367,6 +378,16 @@ func (e *UpgradeRequiredError) Error() string {return "Runner Gateway requires a Local Computer upgrade"}+// DaemonIdentityInUseError reports that the Runner Gateway closed the session+// because another live Computer already holds this Daemon Identity.+type DaemonIdentityInUseError struct {+ Reason string+}++func (e *DaemonIdentityInUseError) Error() string {+ return "Runner Gateway rejected a Daemon Identity already bound to another Local Computer"+}+func (s *gatewayStream) Send(ctx context.Context, event protocol.Event) error {if err := ctx.Err(); err != nil {return errdiff --git a/apps/computer/local-daemon/internal/linger/transport/gateway_test.go b/apps/computer/local-daemon/internal/linger/transport/gateway_test.goindex efc25818..04b893e4 100644--- a/apps/computer/local-daemon/internal/linger/transport/gateway_test.go+++ b/apps/computer/local-daemon/internal/linger/transport/gateway_test.go@@ -241,6 +241,35 @@ func TestGatewayStreamClassifiesUpgradeRequiredClose(t *testing.T) {}}+func TestGatewayStreamClassifiesDaemonIdentityInUseClose(t *testing.T) {+ upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {+ socket, err := upgrader.Upgrade(writer, request, nil)+ if err != nil {+ t.Error(err)+ return+ }+ defer socket.Close()+ _ = socket.WriteControl(+ websocket.CloseMessage,+ websocket.FormatCloseMessage(websocket.ClosePolicyViolation, "daemon_identity_in_use: reconnect this Computer"),+ time.Now().Add(time.Second),+ )+ }))+ defer server.Close()+ url := "ws" + strings.TrimPrefix(server.URL, "http")+ stream, err := (GatewayControlPlane{URL: url, BearerToken: "test-token"}).Connect(context.Background(), Hello{})+ if err != nil {+ t.Fatal(err)+ }+ defer stream.Close()+ _, err = stream.Receive(context.Background())+ var conflict *DaemonIdentityInUseError+ if !errors.As(err, &conflict) || conflict.Reason != "daemon_identity_in_use: reconnect this Computer" {+ t.Fatalf("daemon-identity-in-use close error = %v", err)+ }+}+func TestGatewayStreamDecodesRuntimeRegistrationSnapshot(t *testing.T) {upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {@@ -502,6 +531,7 @@ func TestClassifyConnectionFailure(t *testing.T) {want ConnectionFailure}{{"upgrade required", &UpgradeRequiredError{Reason: "upgrade_required: protocol"}, FailureIncompatible},+ {"daemon identity in use", &DaemonIdentityInUseError{Reason: "daemon_identity_in_use: reconnect this Computer"}, FailureUnavailable},{"schema rejected", &websocket.CloseError{Code: websocket.CloseProtocolError, Text: "Runner protocol violation"}, FailureIncompatible},{"credential revoked", fmt.Errorf("receive: %w", &websocket.CloseError{Code: websocket.ClosePolicyViolation, Text: "Runner credential revoked"}), FailureUnavailable},{"Gateway restarting", &websocket.CloseError{Code: websocket.CloseServiceRestart}, FailureUnavailable},diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 953bef0f..b82fc3cf 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -189,17 +189,30 @@ Gateway and runs Agents. The daemon exits with the app.before the computer enrolled is not resumed: setup shows again and Installfinishes it, reusing a finished job only while its origin answers (a stoppedserver 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+ page's Set Up Again forgets the record (`local-server.json`), clears the+ active enrollment while keeping per-origin `savedEnrollments` in+ `config.json` (`legacy_data_set_aside` clears `savedEnrollments` as well),+ clears the server address, and shows setup; the instance and its data stay.+ `Enrollment` (`src/main/enrollment.ts`) sends the local `daemon_id` derived+ from `<userData>/computer/state/daemon-identity.json`'s public key along+ with any remembered `computerId` for that origin and owner so re-enrolling or+ recovering an interrupted exchange renews the existing Computer ID and+ surfaces `DAEMON_IDENTITY_IN_USE` / `DAEMON_IDENTITY_MISMATCH` conflicts.+ 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 anddeletes that `.env` (never a `LINGER_CHECKOUT`'s), logging only the namesof other values it drops; the installer reads only `user.env` for the- desktop. Setup then waits up to five minutes for the- server to create the Another Me; on timeout it reads `local-computers` and- says what is missing (offline computer, no writable folder, or no signed-in- runtime with each runtime's reported state) and logs- `local_server.another_me_missing`. Customize → API keys takes the+ desktop. Setup fails immediately on `identity_conflict`, `auth_failed`, or+ `upgrade_required` daemon connection states (`computer-daemon.ts` maps+ `identity-conflict` to `identity_conflict`, and `status.ts` summarizes it as+ an error asking to reconnect), then waits up to five minutes for the+ server to create the Another Me and for the enrolled Computer to report+ `online` when `local-computers` is served; on timeout it reads+ `local-computers` and says what is missing (offline computer, no writable+ folder, or no signed-in runtime with each runtime's reported state) and logs+ `local_server.another_me_missing` or+ `local_server.computer_offline_after_agents`. Customize → API keys takes theComposio key only (`provider-keys.ts`); voice keys are saved in the app,and a `SONIOX_API_KEY` or `XAI_API_KEY` written into `user.env` by handstill reaches the services and overrides the app's. Install saves the editsdiff --git a/apps/desktop/src/main/computer-daemon.test.ts b/apps/desktop/src/main/computer-daemon.test.tsindex fd7958eb..b7c7ff27 100644--- a/apps/desktop/src/main/computer-daemon.test.ts+++ b/apps/desktop/src/main/computer-daemon.test.ts@@ -313,6 +313,8 @@ describe("ComputerDaemonModule", () => {expect(daemon.running()).toBe(2);children[0]!.status("upgrade-required");expect(daemon.connection()).toBe("upgrade_required");+ children[0]!.status("identity-conflict");+ expect(daemon.connection()).toBe("identity_conflict");expect(activity).toEqual([2, 0]);});@@ -598,6 +600,7 @@ describe("connectionState", () => {expect(connectionState("connecting")).toBe("connecting");expect(connectionState("authentication-failed")).toBe("auth_failed");expect(connectionState("upgrade-required")).toBe("upgrade_required");+ expect(connectionState("identity-conflict")).toBe("identity_conflict");});});diff --git a/apps/desktop/src/main/computer-daemon.ts b/apps/desktop/src/main/computer-daemon.tsindex 0af2c876..5fd584d8 100644--- a/apps/desktop/src/main/computer-daemon.ts+++ b/apps/desktop/src/main/computer-daemon.ts@@ -108,6 +108,8 @@ export const connectionState = (gatewayState: string): string => {return "online";case "authentication-failed":return "auth_failed";+ case "identity-conflict":+ return "identity_conflict";case "upgrade-required":return "upgrade_required";default:diff --git a/apps/desktop/src/main/config.ts b/apps/desktop/src/main/config.tsindex c1084f37..c3876491 100644--- a/apps/desktop/src/main/config.ts+++ b/apps/desktop/src/main/config.ts@@ -15,6 +15,13 @@ const workspaceGrant = z.object({});export type WorkspaceGrant = z.infer<typeof workspaceGrant>;+const savedEnrollment = z.object({+ computerId: z.string().min(1),+ tenantId: z.string().min(1).optional(),+ ownerActorId: z.string().min(1).optional(),+});+export type SavedEnrollment = z.infer<typeof savedEnrollment>;+// Non-secret desktop settings. The Gateway credential is kept apart// (computer-credential.ts). Keys of older versions, such as sandboxMode,// are dropped on read.@@ -24,6 +31,9 @@ const desktopConfig = z.object({computerId: z.string().optional(),tenantId: z.string().optional(),ownerActorId: 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(),workspaceGrants: z.array(workspaceGrant).default([]),// Always-on mode: keep the system awake even when idle.preventSleep: z.boolean().default(false),diff --git a/apps/desktop/src/main/enrollment.test.ts b/apps/desktop/src/main/enrollment.test.tsindex 2c022635..3cef0110 100644--- a/apps/desktop/src/main/enrollment.test.ts+++ b/apps/desktop/src/main/enrollment.test.ts@@ -1,8 +1,18 @@import { createHash } from "node:crypto";+import { mkdirSync, writeFileSync } from "node:fs";+import path from "node:path";-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";-import { EnrollmentError, enrollComputer } from "./enrollment.js";+import { CredentialStore } from "./computer-credential.js";+import {+ EnrollmentError,+ EnrollmentModule,+ enrollComputer,+ readDaemonId,+} from "./enrollment.js";+import { EventBus } from "./modules.js";+import { stubModule, tempDirectory, testHost } from "./test-support.js";const claims = (value: object): string =>Buffer.from(JSON.stringify(value)).toString("base64url");@@ -18,8 +28,18 @@ interface Call {readonly body: Record<string, unknown> | undefined;}+interface ServerOverrides {+ readonly exchangeStatus?: number;+ readonly bundle?: Record<string, unknown>;+ readonly meActorId?: string;+ readonly onCreate?: (+ body: Record<string, unknown> | undefined,+ ) => Response | undefined;+ readonly onExchange?: () => Response | undefined;+}+const fakeServer = (- overrides: { exchangeStatus?: number; bundle?: Record<string, unknown> } = {},+ overrides: ServerOverrides = {},): { fetch: typeof fetch; calls: Call[] } => {const calls: Call[] = [];let challenge = "";@@ -37,16 +57,31 @@ const fakeServer = (const json = (value: unknown, status = 200): Response =>new Response(JSON.stringify(value), { status });if (input.pathname === "/v0/me")- return json({ actors: [{ kind: "human", tenant_id: "tenant_acme" }] });+ return json({+ actors: [+ {+ kind: "human",+ tenant_id: "tenant_acme",+ ...(overrides.meActorId ? { id: overrides.meActorId } : {}),+ },+ ],+ });if (input.pathname.endsWith("/local-computer-enrollments")) {+ const custom = overrides.onCreate?.(body);+ if (custom) return custom;challenge = String(body?.code_challenge);return json({enrollment_id: "enr_1",- computer_id: "computer_1",+ computer_id:+ typeof body?.computer_id === "string"+ ? body.computer_id+ : "computer_1",authorization_code: "code_1",expires_at: "2026-10-16T08:00:00Z",});}+ const exchangeCustom = overrides.onExchange?.();+ if (exchangeCustom) return exchangeCustom;if (overrides.exchangeStatus) return json({}, overrides.exchangeStatus);const verifier = String(body?.code_verifier);if (createHash("sha256").update(verifier).digest("base64url") !== challenge)@@ -64,6 +99,20 @@ const fakeServer = (return { fetch: fetchImpl, calls };};+const writeDaemonIdentity = (+ file: string,+ publicKey = Buffer.alloc(32, 7),+): string => {+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(+ file,+ JSON.stringify({+ public_key: publicKey.toString("base64").replace(/=+$/, ""),+ }),+ );+ return createHash("sha256").update(publicKey).digest("base64url");+};+const input = {serverUrl: "https://linger.example.com",cookie: "teamhub_session=abc",@@ -157,4 +206,255 @@ describe("enrollComputer", () => {enrollComputer({ ...input, fetch: server.fetch }),).rejects.toMatchObject({ code: "INVALID_RESPONSE" });});++ it("includes daemon_id when provided", async () => {+ const server = fakeServer();+ await enrollComputer({+ ...input,+ daemonId: "A".repeat(43),+ fetch: server.fetch,+ });+ expect(server.calls[1]?.body?.daemon_id).toBe("A".repeat(43));+ });++ it("omits saved computer_id only when another owner signed in", async () => {+ const otherOwner = fakeServer({ meActorId: "actor_bob" });+ await enrollComputer({+ ...input,+ computerId: "computer_1",+ expectedOwnerActorId: "actor_ann",+ daemonId: "A".repeat(43),+ fetch: otherOwner.fetch,+ });+ expect(otherOwner.calls[1]?.body).not.toHaveProperty("computer_id");+ expect(otherOwner.calls[1]?.body?.daemon_id).toBe("A".repeat(43));++ const sameOwner = fakeServer({ meActorId: "actor_ann" });+ await enrollComputer({+ ...input,+ computerId: "computer_1",+ expectedOwnerActorId: "actor_ann",+ daemonId: "A".repeat(43),+ fetch: sameOwner.fetch,+ });+ expect(sameOwner.calls[1]?.body?.computer_id).toBe("computer_1");+ });++ it.each([404, 410])(+ "retries once without computer_id when create returns %i for a saved Computer",+ async (status) => {+ let createCalls = 0;+ const server = fakeServer({+ onCreate: () => {+ createCalls += 1;+ if (createCalls === 1) return new Response("{}", { status });+ return undefined;+ },+ });+ const enrolled = await enrollComputer({+ ...input,+ computerId: "computer_stale",+ daemonId: "D".repeat(43),+ fetch: server.fetch,+ });+ expect(enrolled.computerId).toBe("computer_1");+ const creates = server.calls.filter((call) =>+ call.url.endsWith("/local-computer-enrollments"),+ );+ expect(creates).toHaveLength(2);+ expect(creates[0]?.body?.computer_id).toBe("computer_stale");+ expect(creates[0]?.body?.daemon_id).toBe("D".repeat(43));+ expect(creates[1]?.body).not.toHaveProperty("computer_id");+ expect(creates[1]?.body?.daemon_id).toBe("D".repeat(43));+ },+ );++ it.each([+ ["DAEMON_IDENTITY_IN_USE", "DAEMON_IDENTITY_IN_USE"],+ ["LOCAL_COMPUTER_IDENTITY_MISMATCH", "DAEMON_IDENTITY_MISMATCH"],+ ] as const)(+ "maps 409 %s to EnrollmentError %s",+ async (serverCode, expectedCode) => {+ const server = fakeServer({+ onCreate: () =>+ Response.json(+ { error: { code: serverCode, message: "conflict" } },+ { status: 409 },+ ),+ });+ await expect(+ enrollComputer({+ ...input,+ daemonId: "D".repeat(43),+ fetch: server.fetch,+ }),+ ).rejects.toMatchObject({ code: expectedCode });+ },+ );++ it("invokes onAuthorized before exchange runs", async () => {+ const seen: unknown[] = [];+ const server = fakeServer({+ meActorId: "actor_ann",+ exchangeStatus: 500,+ });+ await expect(+ enrollComputer({+ ...input,+ onAuthorized: (authorized) => seen.push(authorized),+ fetch: server.fetch,+ }),+ ).rejects.toMatchObject({ code: "REJECTED" });+ expect(seen).toEqual([+ {+ computerId: "computer_1",+ tenantId: "tenant_acme",+ ownerActorId: "actor_ann",+ },+ ]);+ });+});++describe("readDaemonId", () => {+ it("computes the 43-char base64url SHA-256 of the daemon public key", () => {+ const dir = tempDirectory();+ const file = path.join(dir, "state", "daemon-identity.json");+ const expected = writeDaemonIdentity(file);+ expect(readDaemonId(file)).toBe(expected);+ expect(expected).toMatch(/^[A-Za-z0-9_-]{43}$/);++ // Padded base64 is accepted identically.+ const key = Buffer.alloc(32, 9);+ const paddedFile = path.join(dir, "state", "padded.json");+ writeFileSync(+ paddedFile,+ JSON.stringify({ public_key: key.toString("base64") }),+ );+ expect(readDaemonId(paddedFile)).toBe(+ createHash("sha256").update(key).digest("base64url"),+ );+ });++ it("returns undefined for missing, malformed, or wrong-length files", () => {+ const dir = tempDirectory();+ expect(readDaemonId(path.join(dir, "missing.json"))).toBeUndefined();++ const invalidJson = path.join(dir, "invalid.json");+ writeFileSync(invalidJson, "{");+ expect(readDaemonId(invalidJson)).toBeUndefined();++ const shortKey = path.join(dir, "short.json");+ writeFileSync(+ shortKey,+ JSON.stringify({ public_key: Buffer.alloc(16, 1).toString("base64") }),+ );+ expect(readDaemonId(shortKey)).toBeUndefined();+ });+});++describe("EnrollmentModule", () => {+ const setupModule = (+ serverOverrides: ServerOverrides = {},+ initialServerUrl = "https://linger.example.com",+ ) => {+ const dir = tempDirectory();+ const daemonIdentityFile = path.join(dir, "daemon-identity.json");+ const daemonId = writeDaemonIdentity(daemonIdentityFile);+ const server = fakeServer({ meActorId: "actor_ann", ...serverOverrides });+ const credentials = new CredentialStore(path.join(dir, "credential.json"));+ const bus = new EventBus();+ const enrollment = new EnrollmentModule({+ sessionCookie: async () => "teamhub_session=abc",+ defaultDisplayName: "Laptop",+ credentials,+ daemonIdentityFile,+ fetch: server.fetch,+ });+ const host = testHost(+ [stubModule("Config"), enrollment],+ { serverUrl: initialServerUrl },+ bus,+ );+ return { enrollment, host, bus, server, credentials, daemonId };+ };++ it("renews the same Computer ID after unenroll using savedEnrollments and daemonId", async () => {+ const { enrollment, host, server, daemonId } = setupModule();+ await host.start();+ const first = await enrollment.enroll();+ expect(first.computerId).toBe("computer_1");++ await enrollment.unenroll();+ expect(host.ctx.config.get().computerId).toBeUndefined();+ expect(host.ctx.config.get().savedEnrollments).toEqual({+ "https://linger.example.com": {+ computerId: "computer_1",+ tenantId: "tenant_acme",+ ownerActorId: "actor_ann",+ },+ });++ const second = await enrollment.enroll();+ expect(second.computerId).toBe("computer_1");+ const creates = server.calls.filter((call) =>+ call.url.endsWith("/local-computer-enrollments"),+ );+ expect(creates[1]?.body?.computer_id).toBe("computer_1");+ expect(creates[1]?.body?.daemon_id).toBe(daemonId);+ await host.stop("quit");+ });++ it("remembers an authorized Computer ID across an interrupted exchange", async () => {+ let failExchange = true;+ const { enrollment, host, server, daemonId } = setupModule({+ onExchange: () =>+ failExchange ? new Response("{}", { status: 500 }) : undefined,+ });+ await host.start();+ await expect(enrollment.enroll()).rejects.toMatchObject({+ code: "REJECTED",+ });+ expect(host.ctx.config.get().computerId).toBeUndefined();+ expect(host.ctx.config.get().savedEnrollments).toEqual({+ "https://linger.example.com": {+ computerId: "computer_1",+ tenantId: "tenant_acme",+ ownerActorId: "actor_ann",+ },+ });++ failExchange = false;+ const recovered = await enrollment.enroll();+ expect(recovered.computerId).toBe("computer_1");+ const creates = server.calls.filter((call) =>+ call.url.endsWith("/local-computer-enrollments"),+ );+ expect(creates[1]?.body?.computer_id).toBe("computer_1");+ expect(creates[1]?.body?.daemon_id).toBe(daemonId);+ 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();+ await enrollment.enroll();++ host.ctx.config.update({ serverUrl: "https://other.example.com" });+ bus.emit("server.changed", "https://other.example.com");+ await vi.waitFor(() =>+ expect(host.ctx.config.get().computerId).toBeUndefined(),+ );++ expect(host.ctx.config.get().savedEnrollments).toEqual({+ "https://linger.example.com": {+ computerId: "computer_1",+ tenantId: "tenant_acme",+ ownerActorId: "actor_ann",+ },+ });+ expect(+ host.ctx.config.get().savedEnrollments?.["https://other.example.com"],+ ).toBeUndefined();+ await host.stop("quit");+ });});diff --git a/apps/desktop/src/main/enrollment.ts b/apps/desktop/src/main/enrollment.tsindex b8e5dbaa..a1f99e0e 100644--- a/apps/desktop/src/main/enrollment.ts+++ b/apps/desktop/src/main/enrollment.ts@@ -1,8 +1,10 @@import { createHash, randomBytes } from "node:crypto";+import { readFileSync } from "node:fs";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";type Schemas = components["schemas"];@@ -23,6 +25,8 @@ export class EnrollmentError extends Error {| "NO_TENANT"| "REJECTED"| "ENROLLMENT_REMOVED"+ | "DAEMON_IDENTITY_IN_USE"+ | "DAEMON_IDENTITY_MISMATCH"| "INVALID_RESPONSE",message: string,) {@@ -38,6 +42,16 @@ 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.+ readonly daemonId?: string;+ // When re-enrolling after a reset, omit computerId if another account signed in.+ readonly expectedOwnerActorId?: string;+ // Persists the authorized Computer ID before exchange completes.+ readonly onAuthorized?: (authorized: {+ readonly computerId: string;+ readonly tenantId: string;+ readonly ownerActorId?: string;+ }) => void;readonly fetch?: typeof fetch;}@@ -77,27 +91,73 @@ 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 tenantId = humanTenant(await me.json());- if (!tenantId)+ const actor = humanActor(await me.json());+ if (!actor)throw new EnrollmentError("NO_TENANT", "The account has no workspace");+ const { tenantId, actorId } = actor;- const verifier = randomBytes(32).toString("base64url");- const createBody: CreateRequest = {- display_name: input.displayName,- redirect_uri: REDIRECT_URI,- code_challenge: createHash("sha256").update(verifier).digest("base64url"),- ...(input.computerId ? { computer_id: input.computerId } : {}),+ const candidateComputerId =+ input.expectedOwnerActorId &&+ actorId &&+ actorId !== input.expectedOwnerActorId+ ? undefined+ : input.computerId;++ const createEnrollment = async (+ computerId?: string,+ ): Promise<{ verifier: string; response: Response }> => {+ const verifier = randomBytes(32).toString("base64url");+ const createBody: CreateRequest = {+ display_name: input.displayName,+ redirect_uri: REDIRECT_URI,+ code_challenge: createHash("sha256").update(verifier).digest("base64url"),+ ...(computerId ? { computer_id: computerId } : {}),+ ...(input.daemonId ? { daemon_id: input.daemonId } : {}),+ };+ const response = await call(+ `/v0/tenants/${encodeURIComponent(tenantId)}/local-computer-enrollments`,+ { method: "POST", body: createBody, cookie: input.cookie },+ );+ return { verifier, response };};- const created = await call(- `/v0/tenants/${encodeURIComponent(tenantId)}/local-computer-enrollments`,- { method: "POST", body: createBody, cookie: input.cookie },- );++ let { verifier, response: created } =+ await createEnrollment(candidateComputerId);+ if (+ (created.status === 404 || created.status === 410) &&+ candidateComputerId+ ) {+ ({ verifier, response: created } = await createEnrollment(undefined));+ }if (created.status === 401)throw new EnrollmentError("NOT_SIGNED_IN", "Sign in before enrolling");+ if (created.status === 409) {+ const code = await readErrorCode(created);+ if (code === "DAEMON_IDENTITY_IN_USE")+ throw new EnrollmentError(+ "DAEMON_IDENTITY_IN_USE",+ "This computer is already connected to another Linger account. Sign in to that account to reconnect it, or remove this Computer from that account first.",+ );+ if (code === "LOCAL_COMPUTER_IDENTITY_MISMATCH")+ throw new EnrollmentError(+ "DAEMON_IDENTITY_MISMATCH",+ "This Computer registration belongs to another local identity. Remove the old Computer in Linger first, then reconnect.",+ );+ throw rejected("Creating the enrollment", created.status);+ }if (!created.ok) throw rejected("Creating the enrollment", created.status);const authorization = (await created.json()) as Authorization;- if (!authorization.enrollment_id || !authorization.authorization_code)+ if (+ !authorization.enrollment_id ||+ !authorization.authorization_code ||+ !authorization.computer_id+ )throw invalid();+ input.onAuthorized?.({+ computerId: authorization.computer_id,+ tenantId,+ ...(actorId ? { ownerActorId: actorId } : {}),+ });const exchangeBody: ExchangeRequest = {authorization_code: authorization.authorization_code,@@ -177,18 +237,68 @@ export const credentialOwner = (}};-export const humanTenant = (value: unknown): string | undefined => {+function humanActor(+ value: unknown,+): { readonly tenantId: string; readonly actorId?: string } | undefined {const actors = (value as { actors?: unknown }).actors;if (!Array.isArray(actors)) return undefined;const human = actors.find(- (a): a is { tenant_id: string } =>+ (a): a is { tenant_id: string; id?: unknown } =>!!a &&typeof a === "object" &&(a as { kind?: unknown }).kind === "human" &&typeof (a as { tenant_id?: unknown }).tenant_id === "string",);- return human?.tenant_id;-};+ if (!human) return undefined;+ const actorId =+ typeof human.id === "string" && human.id ? human.id : undefined;+ return { tenantId: human.tenant_id, ...(actorId ? { actorId } : {}) };+}++export function humanTenant(value: unknown): string | undefined {+ return humanActor(value)?.tenantId;+}++// Reads the Daemon public key file and computes the same base64url SHA-256+// Daemon ID the Go daemon computes; never reads or retains the private key.+export function readDaemonId(file: string): string | undefined {+ let raw: string;+ try {+ raw = readFileSync(file, "utf8");+ } catch {+ return undefined;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return undefined;+ }+ if (!parsed || typeof parsed !== "object") return undefined;+ const encoded = (parsed as { public_key?: unknown }).public_key;+ if (typeof encoded !== "string" || !/^[A-Za-z0-9+/]{43}=?$/.test(encoded))+ return undefined;+ const publicKey = Buffer.from(encoded, "base64");+ if (publicKey.length !== 32) return undefined;+ return createHash("sha256").update(publicKey).digest("base64url");+}++export function enrollmentOrigin(serverUrl: string): string | undefined {+ try {+ return new URL(serverUrl).origin;+ } catch {+ return undefined;+ }+}++async function readErrorCode(response: Response): Promise<string | undefined> {+ try {+ const body = (await response.json()) as { error?: { code?: unknown } };+ return typeof body?.error?.code === "string" ? body.error.code : undefined;+ } catch {+ return undefined;+ }+}const rejected = (step: string, status: number): EnrollmentError =>new EnrollmentError("REJECTED", `${step} failed (${String(status)})`);@@ -204,6 +314,8 @@ export interface EnrollmentOptions {readonly defaultDisplayName: string;// Where the Gateway credential is kept for the daemon.readonly credentials: CredentialStore;+ // Path to the Go daemon's daemon-identity.json file.+ readonly daemonIdentityFile?: string;readonly fetch?: typeof fetch;}@@ -216,6 +328,7 @@ export class EnrollmentModule implements Module {#ctx: ModuleContext | undefined;#pending: Promise<{ computerId: string }> | undefined;#offServerChanged: (() => void) | undefined;+ #activeServerUrl: string | undefined;constructor(options: EnrollmentOptions) {this.#options = options;@@ -223,10 +336,22 @@ export class EnrollmentModule implements Module {async start(ctx: ModuleContext): Promise<void> {this.#ctx = ctx;+ const initial = ctx.config.get();+ if (initial.serverUrl && initial.computerId) {+ this.#activeServerUrl = initial.serverUrl;+ this.#remember(initial.serverUrl, {+ computerId: initial.computerId,+ ...(initial.tenantId ? { tenantId: initial.tenantId } : {}),+ ...(initial.ownerActorId ? { ownerActorId: initial.ownerActorId } : {}),+ });+ }// An enrollment belongs to one server; switching servers drops it.this.#offServerChanged = ctx.bus.on("server.changed", () => {- if (!ctx.config.get().computerId) return;- void this.unenroll().catch((error: unknown) =>+ if (!ctx.config.get().computerId) {+ this.#activeServerUrl = undefined;+ return;+ }+ void this.#unenrollForServerChange().catch((error: unknown) =>ctx.log.warn("enrollment.clear_failed", { error: String(error) }),);});@@ -278,12 +403,35 @@ export class EnrollmentModule implements Module {}async unenroll(): Promise<void> {+ await this.#clearEnrollment(+ this.#activeServerUrl ?? this.#ctx!.config.get().serverUrl,+ );+ }++ async #unenrollForServerChange(): Promise<void> {+ await this.#clearEnrollment(this.#activeServerUrl);+ }++ async #clearEnrollment(serverUrl: string | undefined): Promise<void> {const ctx = this.#ctx!;+ const config = ctx.config.get();+ const saved =+ serverUrl && config.computerId+ ? this.#withSaved(serverUrl, {+ computerId: config.computerId,+ ...(config.tenantId ? { tenantId: config.tenantId } : {}),+ ...(config.ownerActorId+ ? { ownerActorId: config.ownerActorId }+ : {}),+ })+ : undefined;+ this.#activeServerUrl = undefined;this.#options.credentials.clear();ctx.config.update({computerId: undefined,tenantId: undefined,ownerActorId: undefined,+ ...(saved ? { savedEnrollments: saved } : {}),});ctx.bus.emit("computer.changed", undefined);ctx.log.info("enrollment.cleared");@@ -296,11 +444,26 @@ export class EnrollmentModule implements Module {const cookie = await this.#options.sessionCookie(config.serverUrl);if (!cookie)throw new EnrollmentError("NOT_SIGNED_IN", "Sign in before enrolling");+ const origin = enrollmentOrigin(config.serverUrl);+ const saved = origin ? config.savedEnrollments?.[origin] : undefined;+ const computerId = config.computerId ?? saved?.computerId;+ const expectedOwnerActorId = config.computerId+ ? undefined+ : saved?.ownerActorId;+ const daemonId = this.#options.daemonIdentityFile+ ? readDaemonId(this.#options.daemonIdentityFile)+ : undefined;+ const serverUrl = config.serverUrl;const enrolled = await enrollComputer({- serverUrl: config.serverUrl,+ serverUrl,cookie,displayName: config.displayName ?? this.#options.defaultDisplayName,- ...(config.computerId ? { computerId: config.computerId } : {}),+ ...(computerId ? { computerId } : {}),+ ...(expectedOwnerActorId ? { expectedOwnerActorId } : {}),+ ...(daemonId ? { daemonId } : {}),+ onAuthorized: (authorized) => {+ this.#remember(serverUrl, authorized);+ },...(this.#options.fetch ? { fetch: this.#options.fetch } : {}),});this.#options.credentials.write({@@ -308,13 +471,37 @@ export class EnrollmentModule implements Module {gatewayUrl: enrolled.gatewayUrl,token: enrolled.credential,});+ const nextSaved = this.#withSaved(serverUrl, {+ computerId: enrolled.computerId,+ tenantId: enrolled.tenantId,+ ownerActorId: enrolled.ownerActorId,+ });+ this.#activeServerUrl = serverUrl;ctx.config.update({computerId: enrolled.computerId,tenantId: enrolled.tenantId,ownerActorId: enrolled.ownerActorId,+ ...(nextSaved ? { savedEnrollments: nextSaved } : {}),});ctx.bus.emit("computer.changed", enrolled.computerId);ctx.log.info("enrollment.completed", { computer_id: enrolled.computerId });return { computerId: enrolled.computerId };}++ #remember(serverUrl: string, entry: SavedEnrollment): void {+ const next = this.#withSaved(serverUrl, entry);+ if (next) this.#ctx?.config.update({ savedEnrollments: next });+ }++ #withSaved(+ serverUrl: string,+ entry: SavedEnrollment,+ ): Record<string, SavedEnrollment> | undefined {+ const origin = enrollmentOrigin(serverUrl);+ if (!origin) return undefined;+ return {+ ...this.#ctx?.config.get().savedEnrollments,+ [origin]: entry,+ };+ }}diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 2c822a8f..837acaf8 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -268,6 +268,11 @@ async function main(): Promise<void> {new EnrollmentModule({defaultDisplayName,credentials,+ daemonIdentityFile: path.join(+ daemonDirectory,+ "state",+ "daemon-identity.json",+ ),sessionCookie: webSessionCookie,}),new WorkspaceGrantsModule({diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.tsindex 1725f9e4..65b421c0 100644--- a/apps/desktop/src/main/local-server.test.ts+++ b/apps/desktop/src/main/local-server.test.ts@@ -20,6 +20,8 @@ import { describe, expect, it, vi } from "vitest";import { NODE_RUNTIME_VERSION } from "../../../../scripts/local-computer-node-distributions.mjs";import { rename } from "node:fs/promises";+import { CredentialStore } from "./computer-credential.js";+import { EnrollmentModule } from "./enrollment.js";import {LOCAL_INSTANCE,LOCAL_STEPS,@@ -27,6 +29,7 @@ import {MIN_MACOS,anotherMeMissing,checkLocation,+ computerNotOnline,followHttps,hasNativePostgres,InstallerApi,@@ -1098,6 +1101,116 @@ describe("LocalServerModule", () => {await f.host.stop("quit");});+ it("stops waiting immediately when the Computer daemon reports an identity conflict", async () => {+ const polls = { anotherMe: 0 };+ const server = (async (input: string | URL | Request) => {+ const url = new URL(String(input));+ if (url.pathname === "/v0/me")+ return Response.json({ actors: [{ kind: "human", tenant_id: "t1" }] });+ if (url.pathname === "/v0/tenants/t1/another-me") {+ polls.anotherMe += 1;+ return Response.json({});+ }+ return new Response(null, { status: 404 });+ }) as typeof fetch;+ const f = fixture(+ (home) => ({+ ...withCheckout(home),+ fetch: server,+ sessionCookie: async () => "session=s",+ pollMs: 1,+ }),+ { computerId: "cmp_1" },+ checkout,+ );+ await f.host.start();+ const setup = f.module.begin();+ await vi.waitFor(() => expect(polls.anotherMe).toBeGreaterThan(0));+ f.host.ctx.bus.emit("computer.connection", "identity_conflict");+ await expect(setup).rejects.toThrow(+ /already connected to another Computer registration/,+ );+ expect(f.module.status().phase).toBe("failed");+ await f.host.stop("quit");+ });++ it("waits for the enrolled Computer to report online before finishing setup", async () => {+ let computerPolls = 0;+ const server = (async (input: string | URL | Request) => {+ const url = new URL(String(input));+ if (url.pathname === "/v0/me")+ return Response.json({ actors: [{ kind: "human", tenant_id: "t1" }] });+ if (url.pathname === "/v0/tenants/t1/another-me")+ return Response.json({ agent_actor_id: "actor_anotherme_1" });+ if (url.pathname === "/v0/tenants/t1/rooms")+ return Response.json({ items: [{ name: "Getting Started" }] });+ if (url.pathname === "/v0/tenants/t1/local-computers") {+ computerPolls += 1;+ return Response.json({+ items: [+ {+ computer_id: "cmp_1",+ status: computerPolls < 3 ? "offline" : "online",+ },+ ],+ });+ }+ return new Response(null, { status: 404 });+ }) as typeof fetch;+ const f = fixture(+ (home) => ({+ ...withCheckout(home),+ fetch: server,+ sessionCookie: async () => "session=s",+ pollMs: 1,+ }),+ { computerId: "cmp_1" },+ checkout,+ );+ await f.host.start();+ const messages: string[] = [];+ f.host.ctx.bus.on("local-server.changed", () => {+ messages.push(f.module.status().message);+ });+ await f.module.begin();+ expect(computerPolls).toBe(3);+ expect(messages).toContain("Connecting this computer…");+ expect(f.module.status().phase).toBe("ready");+ await f.host.stop("quit");++ // On timeout while offline, it reports the Computer is offline instead+ // of claiming Another Me is missing.+ const offlineServer = (async (input: string | URL | Request) => {+ const url = new URL(String(input));+ if (url.pathname === "/v0/me")+ return Response.json({ actors: [{ kind: "human", tenant_id: "t1" }] });+ if (url.pathname === "/v0/tenants/t1/another-me")+ return Response.json({ agent_actor_id: "actor_anotherme_1" });+ if (url.pathname === "/v0/tenants/t1/rooms")+ return Response.json({ items: [{ name: "Getting Started" }] });+ if (url.pathname === "/v0/tenants/t1/local-computers")+ return Response.json({+ items: [{ computer_id: "cmp_1", status: "offline" }],+ });+ return new Response(null, { status: 404 });+ }) as typeof fetch;+ const offline = fixture(+ (home) => ({+ ...withCheckout(home),+ fetch: offlineServer,+ sessionCookie: async () => "session=s",+ agentsTimeoutMs: 0,+ }),+ { computerId: "cmp_1" },+ checkout,+ );+ await offline.host.start();+ await expect(offline.module.begin()).rejects.toThrow(+ computerNotOnline({ status: "offline" }),+ );+ await offline.host.stop("quit");+ });+it("rejects a source package with the wrong digest", async () => {const root = tempDirectory();const archive = sourceArchive(root);@@ -2809,6 +2922,228 @@ describe("LocalServerModule after a restart", () => {await f.host.stop("quit");});+ it("renews the same Computer ID across local-server reset and re-enrollment with retained daemon identity", async () => {+ 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"),+ FAKE_INSTALLER,+ );+ writeFileSync(+ path.join(installerDirectory, "package.json"),+ '{"type":"commonjs"}',+ );+ writeFileSync(+ path.join(installerDirectory, "distribution.json"),+ JSON.stringify({+ platform: "linux",+ arch: "x64",+ nativeSources: [{ target: "linux-x64" }],+ }),+ );+ 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"));+ checkout(home);++ const daemonIdentityFile = path.join(root, "state", "daemon-identity.json");+ mkdirSync(path.dirname(daemonIdentityFile), { recursive: true });+ const pubkey = Buffer.alloc(32, 5);+ writeFileSync(+ daemonIdentityFile,+ JSON.stringify({+ public_key: pubkey.toString("base64").replace(/=+$/, ""),+ }),+ );+ const expectedDaemonId = createHash("sha256")+ .update(pubkey)+ .digest("base64url");++ const computers: {+ readonly computer_id: string;+ readonly daemon_id: string | undefined;+ readonly owner_actor_id: string;+ }[] = [];+ const enrollmentBodies: Record<string, unknown>[] = [];+ let resetOccurred = false;+ let postResetPolls = 0;+ const api = installerApi();+ const teamhubToken = (computerId: string) =>+ `sr1.${Buffer.from(+ JSON.stringify({+ runner_id: computerId,+ tenant_owners: [{ tenant_id: "t1", owner_actor_id: "actor_ann" }],+ }),+ ).toString("base64url")}.${"s".repeat(43)}`;++ const fetcher = (async (+ input: string | URL | Request,+ init?: RequestInit,+ ) => {+ const url = new URL(input instanceof Request ? input.url : String(input));+ if (url.origin === "http://127.0.0.1:4321") return api.handle(url, init);+ if (url.pathname === "/v0/me")+ return Response.json({+ actors: [{ id: "actor_ann", kind: "human", tenant_id: "t1" }],+ });+ if (url.pathname === "/v0/tenants/t1/local-computer-enrollments") {+ const body = JSON.parse(String(init?.body)) as Record<string, unknown>;+ enrollmentBodies.push(body);+ const requestedId =+ typeof body.computer_id === "string" ? body.computer_id : undefined;+ const daemonId =+ typeof body.daemon_id === "string" ? body.daemon_id : undefined;+ const existing =+ computers.find((c) => c.computer_id === requestedId) ??+ (daemonId+ ? computers.find(+ (c) =>+ c.daemon_id === daemonId && c.owner_actor_id === "actor_ann",+ )+ : undefined);+ const resolvedId =+ existing?.computer_id ?? `cmp_${String(computers.length + 1)}`;+ if (!existing) {+ computers.push({+ computer_id: resolvedId,+ daemon_id: daemonId,+ owner_actor_id: "actor_ann",+ });+ }+ return Response.json({+ enrollment_id: `enr_${resolvedId}`,+ computer_id: resolvedId,+ authorization_code: `code_${resolvedId}`,+ expires_at: "2026-11-18T00:00:00Z",+ });+ }+ if (url.pathname.startsWith("/v0/local-computer-enrollments/")) {+ const id = url.pathname.split("/")[3]!.replace(/^enr_/, "");+ return Response.json({+ computer_id: id,+ tenant_id: "t1",+ gateway_url: "wss://localhost:4319/v1/runner",+ gateway_token: teamhubToken(id),+ credential_expires_at: "2026-12-18T00:00:00Z",+ });+ }+ if (url.pathname === "/v0/tenants/t1/another-me")+ return Response.json({ agent_actor_id: "actor_anotherme_1" });+ if (url.pathname === "/v0/tenants/t1/rooms")+ return Response.json({ items: [{ name: "Getting Started" }] });+ if (url.pathname === "/v0/tenants/t1/local-computers") {+ const online = !resetOccurred || ++postResetPolls >= 2;+ return Response.json({+ items: computers.map((c) => ({+ computer_id: c.computer_id,+ status: online ? "online" : "offline",+ })),+ });+ }+ return new Response(null, { status: 404 });+ }) as typeof fetch;++ const bus = new EventBus();+ const initialGrant = {+ grantId: "grant_1",+ path: path.join(root, "workspace"),+ label: "Workspace",+ access: "read_write" as const,+ createdAt: "2026-11-01T00:00:00Z",+ };+ const enrollment = new EnrollmentModule({+ sessionCookie: async () => "session=s",+ defaultDisplayName: "Studio Mac",+ credentials: new CredentialStore(path.join(root, "credential.json")),+ daemonIdentityFile,+ fetch: fetcher,+ });+ const module = new LocalServerModule({+ home,+ version: APP_VERSION,+ installerDirectory,+ checkout: path.join(home, "src"),+ platform: "linux",+ arch: "x64",+ pollMs: 1,+ freeBytes: 1,+ signIn: async () => {},+ serverIdentity: async (_h, origin) => ({+ origin,+ teamhub: TEAMHUB,+ key: KEY,+ }),+ proveServer: async () => {},+ sessionCookie: async () => "session=s",+ fetch: fetcher,+ });+ let hostContext: ModuleContext | undefined;+ const host = testHost(+ [+ {+ ...stubModule("Config"),+ start: async (ctx: ModuleContext) => {+ hostContext = ctx;+ },+ },+ {+ ...stubModule("WindowManager"),+ setServer: (origin: string) => {+ if (origin !== hostContext!.config.get().serverUrl) {+ hostContext!.config.update({ serverUrl: origin });+ bus.emit("server.changed", origin);+ }+ return true;+ },+ showUpdating: vi.fn(),+ showStarting: vi.fn(),+ showStartFailed: vi.fn(),+ loadServer: vi.fn(),+ } as never,+ enrollment,+ module,+ ],+ { workspaceGrants: [initialGrant] },+ bus,+ );++ const opened = vi.fn();+ bus.on("setup.open", opened);+ await host.start();++ await module.begin();+ expect(module.status().phase).toBe("ready");+ expect(host.ctx.config.get().computerId).toBe("cmp_1");+ expect(enrollmentBodies[0]?.daemon_id).toBe(expectedDaemonId);++ resetOccurred = true;+ bus.emit("local-server.reset");+ await vi.waitFor(() => expect(opened).toHaveBeenCalledOnce());+ expect(host.ctx.config.get().computerId).toBeUndefined();+ expect(host.ctx.config.get().serverUrl).toBeUndefined();+ expect(host.ctx.config.get().savedEnrollments).toEqual({+ "http://localhost:3000": {+ computerId: "cmp_1",+ tenantId: "t1",+ ownerActorId: "actor_ann",+ },+ });+ expect(host.ctx.config.get().workspaceGrants).toEqual([initialGrant]);++ await module.begin();+ expect(module.status().phase).toBe("ready");+ expect(host.ctx.config.get().computerId).toBe("cmp_1");+ expect(host.ctx.config.get().workspaceGrants).toEqual([initialGrant]);+ expect(computers).toHaveLength(1);+ expect(enrollmentBodies).toHaveLength(2);+ expect(enrollmentBodies[1]?.computer_id).toBe("cmp_1");+ expect(enrollmentBodies[1]?.daemon_id).toBe(expectedDaemonId);+ expect(postResetPolls).toBe(2);+ await host.stop("quit");+ });+it("writes its record in one piece", async () => {const f = fixture(withCheckout, {}, checkout);await f.host.start();diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.tsindex b2e9a48a..d69e59d1 100644--- a/apps/desktop/src/main/local-server.ts+++ b/apps/desktop/src/main/local-server.ts@@ -428,7 +428,10 @@ export class LocalServerModule implements Module {#offRetry: (() => void) | undefined;#offReset: (() => void) | undefined;#offDaemon: (() => void) | undefined;+ #offDaemonConnection: (() => void) | undefined;+ #offComputerChanged: (() => void) | undefined;#daemonFailure: string | undefined;+ #daemonConnection: string | undefined;#signIn: RuntimeSignIn | undefined;#byokCheck: SetupByokCheck | undefined;#legacyBackup: string | undefined;@@ -482,6 +485,12 @@ export class LocalServerModule implements Module {this.#offDaemon = ctx.bus.on("computer.failed", (reason) => {this.#daemonFailure = reason;});+ this.#offDaemonConnection = ctx.bus.on("computer.connection", (state) => {+ this.#daemonConnection = state;+ });+ this.#offComputerChanged = ctx.bus.on("computer.changed", () => {+ this.#daemonConnection = undefined;+ });this.#offRetry = ctx.bus.on("local-server.retry", () => {if (this.#phase === "failed" && record) {void this.#resume(record, this.#abort.signal);@@ -497,6 +506,8 @@ export class LocalServerModule implements Module {this.#offRetry?.();this.#offReset?.();this.#offDaemon?.();+ this.#offDaemonConnection?.();+ this.#offComputerChanged?.();// The installer manager keeps running a started installation; it exits// by itself once idle.this.#abort.abort();@@ -987,7 +998,7 @@ export class LocalServerModule implements Module {backup: legacyBackup,});await this.#ctx?.get<EnrollmentModule>("Enrollment").unenroll();- this.#ctx?.config.update({ legacyBackup });+ this.#ctx?.config.update({ legacyBackup, savedEnrollments: undefined });this.#legacyBackup = legacyBackup;}this.#advance("connect", 0, "Connecting this computer…");@@ -1003,6 +1014,7 @@ export class LocalServerModule implements Module {this.#home = home;this.#location = undefined;this.#ready(job.origin);+ this.#daemonConnection = undefined;await this.#ctx!.get<EnrollmentModule>("Enrollment").enroll();this.#advance("agents", 0, "Preparing your agents…");await this.#awaitAgents(job.origin, signal);@@ -2098,6 +2110,24 @@ export class LocalServerModule implements Module {});throw new Error(computerServiceFailed(this.#daemonFailure));}+ if (this.#daemonConnection === "identity_conflict") {+ this.#ctx?.log.warn("local_server.computer_identity_conflict");+ throw new Error(+ "This computer's local identity is already connected to another Computer registration. Choose Reconnect This Computer in the Linger menu, or remove the duplicate Computer and try again.",+ );+ }+ if (this.#daemonConnection === "auth_failed") {+ this.#ctx?.log.warn("local_server.computer_auth_failed");+ throw new Error(+ "This computer's sign-in expired before it could connect. Choose Reconnect This Computer in the Linger menu, then try again.",+ );+ }+ if (this.#daemonConnection === "upgrade_required") {+ this.#ctx?.log.warn("local_server.computer_upgrade_required");+ throw new Error(+ "This computer's Linger app is too old for the server. Update Linger, then try again.",+ );+ }// The Another Me has an Agent once the server created it; there is no// status to wait for.const anotherMe = (await get(`${base}/another-me`)) as@@ -2108,10 +2138,32 @@ export class LocalServerModule implements Module {const rooms = (await get(`${base}/rooms`)) as| { items?: { name?: string }[] }| undefined;- if (rooms?.items?.some((room) => room.name === STARTER_ROOM)) return;- // An owner who removed the starter Room is not kept waiting.- if (Date.now() >= deadline) return;- this.#advance("agents", 0.6, "Adding your starter agents…");+ const starterReady = rooms?.items?.some(+ (room) => room.name === STARTER_ROOM,+ );+ if (starterReady || Date.now() >= deadline) {+ const computerId = this.#ctx?.config.get().computerId;+ if (!computerId) return;+ const computers = (await get(`${base}/local-computers`).catch(+ () => undefined,+ )) as { items?: ReportedComputer[] } | undefined;+ if (!computers) return;+ const computer = computers.items?.find(+ (item) => item.computer_id === computerId,+ );+ if (computer?.status === "online" && !computer.upgrade_required)+ return;+ if (Date.now() >= deadline) {+ this.#ctx?.log.warn("local_server.computer_offline_after_agents", {+ computer_id: computerId,+ computer_status: computer?.status,+ });+ throw new Error(computerNotOnline(computer));+ }+ this.#advance("agents", 0.8, "Connecting this computer…");+ } else {+ this.#advance("agents", 0.6, "Adding your starter agents…");+ }} else {if (Date.now() >= deadline) {// Say what the server is missing, as this computer last reported it.@@ -2478,6 +2530,18 @@ const RUNTIME_STATES: Record<string, string> = {export const computerServiceFailed = (reason: string): string =>`The Computer service on this computer cannot start: ${reason.replace(/[.\s]+$/, "")}. computer-daemon.log in the logs has details.`;+export function computerNotOnline(+ computer: ReportedComputer | undefined,+): string {+ if (!computer)+ return "This computer did not come online on Linger: the server does not list this computer. Choose Reconnect This Computer in the Linger tray menu, then try again.";+ if (computer.status !== "online")+ return "This computer did not come online on Linger: its Computer service is not connected. computer-daemon.log in the logs says why.";+ if (computer.upgrade_required)+ return "This computer's Computer service is too old for the server. Update Linger, then try again.";+ return "This computer did not come online on Linger.";+}+export const anotherMeMissing = (computer: ReportedComputer | undefined | null,timeoutMs: number,diff --git a/apps/desktop/src/main/status.test.ts b/apps/desktop/src/main/status.test.tsindex 7dab71b5..4b05a7b9 100644--- a/apps/desktop/src/main/status.test.ts+++ b/apps/desktop/src/main/status.test.ts@@ -45,4 +45,16 @@ describe("summarizeStatus", () => {label: "Sign-in Expired · Reconnect This Computer",});});++ it("asks to reconnect on a Daemon Identity conflict", () => {+ expect(+ summarizeStatus({+ ...base,+ connection: "identity_conflict",+ }),+ ).toEqual({+ tone: "error",+ label: "Computer Identity Conflict · Reconnect This Computer",+ });+ });});diff --git a/apps/desktop/src/main/status.ts b/apps/desktop/src/main/status.tsindex d51f9370..d718dfb5 100644--- a/apps/desktop/src/main/status.ts+++ b/apps/desktop/src/main/status.ts@@ -26,6 +26,11 @@ export const summarizeStatus = (input: StatusInput): StatusSummary => {tone: "error",label: "Sign-in Expired · Reconnect This Computer",};+ case "identity_conflict":+ return {+ tone: "error",+ label: "Computer Identity Conflict · Reconnect This Computer",+ };case "upgrade_required":return { tone: "error", label: "Update Required" };}diff --git a/apps/node-services/src/agent/runner-gateway/local-computer-registry.ts b/apps/node-services/src/agent/runner-gateway/local-computer-registry.tsindex c67f3b00..35503687 100644--- a/apps/node-services/src/agent/runner-gateway/local-computer-registry.ts+++ b/apps/node-services/src/agent/runner-gateway/local-computer-registry.ts@@ -15,6 +15,7 @@ import {type RuntimeStateSchemas,type TeamHubRuntimeStateClient,} from "../executor/teamhub-runtime-state-client.js";+import { RunnerDaemonIdentityInUseError } from "./runner-operation.js";export interface LocalComputerOwner {readonly ownerActorId: string;@@ -117,26 +118,40 @@ export const createTeamHubLocalComputerRegistry = (status,recommendedVersion,}) {- const result = await client.connectLocalComputer({- computer_id: computerId,- owner: { tenant_id: owner.tenantId, owner_actor_id: owner.ownerActorId },- credential_generation: String(credentialGeneration),- daemon_id: hello.daemon_identity.daemon_id,- daemon_public_key: hello.daemon_identity.public_key,- identity_version: String(hello.daemon_identity.identity_version),- status,- seen_at: new Date().toISOString(),- display_name: hello.display_name ?? computerId,- platform: hello.platform,- ...(hello.capacity === undefined ? {} : { capacity: hello.capacity }),- runtimes: [...hello.runtimes],- runtime_diagnostics: jsonObjects(hello.runtime_diagnostics),- workspace_grants: jsonObjects(hello.workspace_grants),- daemon_version: hello.daemon_version,- ...(recommendedVersion === undefined- ? {}- : { recommended_version: recommendedVersion }),- });+ let result: RuntimeStateSchemas["ConnectAgentRuntimeLocalComputerResult"];+ try {+ result = await client.connectLocalComputer({+ computer_id: computerId,+ owner: {+ tenant_id: owner.tenantId,+ owner_actor_id: owner.ownerActorId,+ },+ credential_generation: String(credentialGeneration),+ daemon_id: hello.daemon_identity.daemon_id,+ daemon_public_key: hello.daemon_identity.public_key,+ identity_version: String(hello.daemon_identity.identity_version),+ status,+ seen_at: new Date().toISOString(),+ display_name: hello.display_name ?? computerId,+ platform: hello.platform,+ ...(hello.capacity === undefined ? {} : { capacity: hello.capacity }),+ runtimes: [...hello.runtimes],+ runtime_diagnostics: jsonObjects(hello.runtime_diagnostics),+ workspace_grants: jsonObjects(hello.workspace_grants),+ daemon_version: hello.daemon_version,+ ...(recommendedVersion === undefined+ ? {}+ : { recommended_version: recommendedVersion }),+ });+ } catch (error) {+ if (+ error instanceof TeamHubRuntimeStateError &&+ error.code === "DAEMON_IDENTITY_IN_USE"+ ) {+ throw new RunnerDaemonIdentityInUseError(error.message);+ }+ throw error;+ }return result.placements.map((placement) => ({agentId: placement.agent_id,tenantId: placement.tenant_id,diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.tsindex 156c42df..95e32055 100644--- a/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.ts@@ -24,6 +24,7 @@ import {import type { OperationEnvelope } from "./runner-operation.js";import {+ RunnerDaemonIdentityInUseError,RunnerGatewayProtocolError,RunnerUpgradeRequiredError,type InvalidOperationFrame,@@ -68,6 +69,8 @@ const MAX_QUEUED_BYTES = 16 * 1024 * 1024;const MAX_TIMER_DELAY_MS = 2_147_000_000;export const RUNNER_UPGRADE_REQUIRED_CLOSE_REASON ="upgrade_required: rerun the Linger Computer installer";+export const RUNNER_DAEMON_IDENTITY_IN_USE_CLOSE_REASON =+ "daemon_identity_in_use: reconnect this Computer";// Every Computer release that can update itself declares this in its hello.const SELF_UPDATE_CAPABILITY = "self_update_v2";@@ -653,6 +656,10 @@ export class RunnerSocketSession {this.#closeProtocol(1008, RUNNER_UPGRADE_REQUIRED_CLOSE_REASON);return;}+ if (error instanceof RunnerDaemonIdentityInUseError) {+ this.#closeProtocol(1008, RUNNER_DAEMON_IDENTITY_IN_USE_CLOSE_REASON);+ return;+ }this.#closeProtocol(error instanceof RunnerCredentialScopeError? 1008diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway.tsindex 09f55731..0a38f14a 100644--- a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts@@ -115,6 +115,7 @@ export type {RunnerModelInvokeRequest,} from "./runner-model-invocation.js";export {+ RunnerDaemonIdentityInUseError,RunnerGatewayError,RunnerGatewayProtocolError,RunnerOperationError,diff --git a/apps/node-services/src/agent/runner-gateway/runner-operation.ts b/apps/node-services/src/agent/runner-gateway/runner-operation.tsindex 26bf91d5..6558861f 100644--- a/apps/node-services/src/agent/runner-gateway/runner-operation.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-operation.ts@@ -181,6 +181,17 @@ export class RunnerUpgradeRequiredError extends RunnerGatewayError {}}+export class RunnerDaemonIdentityInUseError extends RunnerGatewayError {+ readonly code = "daemon_identity_in_use";++ constructor(+ message = "Daemon Identity is already bound to another Local Computer",+ ) {+ super(message);+ this.name = "RunnerDaemonIdentityInUseError";+ }+}+export class RunnerOperationError extends RunnerGatewayError {constructor(readonly code: string,diff --git a/apps/node-services/tests/agent/runner-gateway/runner-connections-public.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-connections-public.test.tsindex cb8f7885..119f406a 100644--- a/apps/node-services/tests/agent/runner-gateway/runner-connections-public.test.ts+++ b/apps/node-services/tests/agent/runner-gateway/runner-connections-public.test.ts@@ -10,10 +10,12 @@ import {MINIMUM_CURRENT_COMPUTER_VERSION,} from "../../../src/agent/runner-gateway/local-computer-management.js";import {+ RunnerDaemonIdentityInUseError,RunnerGateway,RunnerUpgradeRequiredError,type RunnerGatewayConnection,} from "../../../src/agent/runner-gateway/runner-gateway.js";+import { createTeamHubLocalComputerRegistry } from "../../../src/agent/runner-gateway/local-computer-registry.js";import {createTestRunnerGateway,testRegistrationId,@@ -838,4 +840,45 @@ describe("RunnerGateway local Computer reconnect wait", () => {await acceptReadyConnection(gateway, new RecordingPeer());await waiting;});++ it("maps DAEMON_IDENTITY_IN_USE from TeamHub connect to RunnerDaemonIdentityInUseError", async () => {+ const connectLocalComputer = vi+ .fn()+ .mockRejectedValueOnce(+ new TeamHubRuntimeStateError(+ 409,+ "Daemon Identity is already bound to another Local Computer",+ "DAEMON_IDENTITY_IN_USE",+ false,+ ),+ )+ .mockRejectedValueOnce(+ new TeamHubRuntimeStateError(+ 409,+ "Agent Runtime State conflicts with the request",+ "AGENT_RUNTIME_CONFLICT",+ false,+ ),+ );+ const registry = createTeamHubLocalComputerRegistry({+ getLocalComputer: vi.fn(),+ connectLocalComputer,+ touchLocalComputer: vi.fn(),+ removeLocalComputer: vi.fn(),+ recordLocalModels: vi.fn(),+ });+ const connection = {+ computerId: "computer-local",+ owner: { tenantId: "tenant-acme", ownerActorId: "actor-alice" },+ credentialGeneration: 0,+ hello: hello(),+ status: "offline" as const,+ };+ await expect(registry.connect(connection)).rejects.toBeInstanceOf(+ RunnerDaemonIdentityInUseError,+ );+ await expect(registry.connect(connection)).rejects.toMatchObject({+ code: "AGENT_RUNTIME_CONFLICT",+ });+ });});diff --git a/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.tsindex d0b124b6..f0d88181 100644--- a/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.ts+++ b/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.ts@@ -40,10 +40,12 @@ import type {import { type RunnerCredentialAuthenticator } from "../../../src/agent/runner-gateway/runner-credential-authority.js";import {attachRunnerGatewayWebSocket,+ RUNNER_DAEMON_IDENTITY_IN_USE_CLOSE_REASON,RUNNER_UPGRADE_REQUIRED_CLOSE_REASON,type AttachRunnerGatewayWebSocketOptions,} from "../../../src/agent/runner-gateway/runner-gateway-websocket.js";import {+ RunnerDaemonIdentityInUseError,RunnerGatewayProtocolError,RunnerUpgradeRequiredError,type RunnerOperation,@@ -181,6 +183,29 @@ describe("Runner Gateway WebSocket", () => {},);+ it("closes with policy violation and identity conflict reason on RunnerDaemonIdentityInUseError", async () => {+ const onSessionError = vi.fn();+ const fixture = await startFixture({ onSessionError });+ const accept = vi+ .spyOn(fixture.gateway, "acceptConnection")+ .mockRejectedValueOnce(new RunnerDaemonIdentityInUseError());+ const socket = new WebSocket(fixture.url, {+ headers: { Authorization: "Bearer runner-secret" },+ });+ await opened(socket);+ const closed = onceClosed(socket);+ socket.send(JSON.stringify(hello()));+ await expect(closed).resolves.toEqual({+ code: 1008,+ reason: RUNNER_DAEMON_IDENTITY_IN_USE_CLOSE_REASON,+ });+ expect(accept).toHaveBeenCalledOnce();+ expect(onSessionError).toHaveBeenCalledWith(+ expect.any(RunnerDaemonIdentityInUseError),+ expect.objectContaining({ phase: "runner.hello" }),+ );+ });+it.each(["close", "invalid frame"])("cleans up pending admission after %s",async (ending) => {diff --git a/apps/teamhub/internal/agentruntimestate/runner.go b/apps/teamhub/internal/agentruntimestate/runner.goindex c15aa190..0e42e364 100644--- a/apps/teamhub/internal/agentruntimestate/runner.go+++ b/apps/teamhub/internal/agentruntimestate/runner.go@@ -262,58 +262,85 @@ func (s *Service) RemoveLocalComputer(ctx context.Context, input LocalComputerCr})}-func (s *Service) CreateLocalComputerEnrollment(ctx context.Context, input CreateLocalComputerEnrollmentInput) error {+// CreateLocalComputerEnrollment records a pending PKCE enrollment and returns+// the resolved Computer ID. When DaemonID matches a live Computer owned by the+// same owner, that Computer is renewed so existing Agent placements stay intact;+// claiming another owner's bound DaemonID returns ErrDaemonIdentityInUse.+func (s *Service) CreateLocalComputerEnrollment(ctx context.Context, input CreateLocalComputerEnrollmentInput) (string, error) {if !validText(input.EnrollmentID, 8, 128) || !validComputerID(input.ComputerID) ||+ (input.DaemonID != "" && !daemonIDPattern.MatchString(input.DaemonID)) ||!validDisplayName(input.DisplayName) || !validOwner(input.Owner) || !validText(input.RedirectURI, 1, 2000) ||!validText(input.CodeChallenge, 43, 128) || len(input.AuthorizationCodeHash) != sha256.Size || input.ExpiresAt.IsZero() {- return ErrInvalid+ return "", ErrInvalid}- _, err := executeLocalComputerTx(ctx, s, func(ctx context.Context, _ pgx.Tx, queries *store.Queries) (bool, *LocalComputerOwner, error) {+ return executeLocalComputerTx(ctx, s, func(ctx context.Context, _ pgx.Tx, queries *store.Queries) (string, *LocalComputerOwner, error) {now, err := queries.AgentRuntimeDatabaseNow(ctx)if err != nil {- return false, nil, err+ return "", nil, err}if !now.Valid || !input.ExpiresAt.After(now.Time) {- return false, nil, ErrInvalid+ return "", nil, ErrInvalid}if err := requireOwnerActor(ctx, queries, input.Owner); err != nil {- return false, nil, err+ return "", nil, err}- computer, lockComputerErr := queries.LockAgentRuntimeLocalComputer(ctx, input.ComputerID)- if input.RenewsExistingComputer {+ computerID := input.ComputerID+ renews := input.RenewsExistingComputer+ if input.DaemonID != "" {+ bound, boundErr := queries.LockAgentRuntimeLocalComputerByDaemonID(ctx, input.DaemonID)+ if boundErr != nil && !isNoRows(boundErr) {+ return "", nil, boundErr+ }+ if boundErr == nil {+ if bound.OwnerTenantID != input.Owner.TenantID || bound.OwnerActorID != input.Owner.OwnerActorID {+ return "", nil, ErrDaemonIdentityInUse+ }+ // Renew the owner's Computer already bound to this Daemon Identity+ // instead of creating a duplicate Computer that would fail connect.+ computerID = bound.ComputerID+ renews = true+ }+ }+ computer, lockComputerErr := queries.LockAgentRuntimeLocalComputer(ctx, computerID)+ if renews {if isNoRows(lockComputerErr) {- return false, nil, ErrNotFound+ return "", nil, ErrNotFound}if lockComputerErr != nil {- return false, nil, lockComputerErr+ return "", nil, lockComputerErr}if computer.OwnerTenantID != input.Owner.TenantID || computer.OwnerActorID != input.Owner.OwnerActorID {- return false, nil, ErrNotFound+ return "", nil, ErrNotFound}if computer.Status == "removed" {- return false, nil, ErrRemoved+ return "", nil, ErrRemoved+ }+ if input.DaemonID != "" && computer.DaemonID.Valid && computer.DaemonID.String != input.DaemonID {+ return "", nil, ErrComputerDaemonMismatch}} else if lockComputerErr == nil || !isNoRows(lockComputerErr) {if lockComputerErr != nil {- return false, nil, lockComputerErr+ return "", nil, lockComputerErr}- return false, nil, ErrConflict+ return "", nil, ErrConflict}if err := queries.DeletePendingAgentRuntimeLocalComputerEnrollments(ctx, store.DeletePendingAgentRuntimeLocalComputerEnrollmentsParams{TenantID: input.Owner.TenantID, OwnerActorID: input.Owner.OwnerActorID,}); err != nil {- return false, nil, err+ return "", nil, err}_, err = queries.InsertAgentRuntimeLocalComputerEnrollment(ctx, store.InsertAgentRuntimeLocalComputerEnrollmentParams{EnrollmentID: input.EnrollmentID, TenantID: input.Owner.TenantID, OwnerActorID: input.Owner.OwnerActorID,- ComputerID: input.ComputerID, RenewsExistingComputer: input.RenewsExistingComputer,+ ComputerID: computerID, RenewsExistingComputer: renews,DisplayName: strings.TrimSpace(input.DisplayName), RedirectUri: input.RedirectURI,CodeChallenge: input.CodeChallenge, AuthorizationCodeHash: append([]byte(nil), input.AuthorizationCodeHash...),ExpiresAt: timestamptz(input.ExpiresAt),})- return true, nil, err+ if err != nil {+ return "", nil, err+ }+ return computerID, nil, nil})- return err}func (s *Service) ConsumeLocalComputerEnrollment(ctx context.Context, input ConsumeLocalComputerEnrollmentInput) (ConsumeLocalComputerEnrollmentResult, error) {diff --git a/apps/teamhub/internal/agentruntimestate/runner_types.go b/apps/teamhub/internal/agentruntimestate/runner_types.goindex 92c91b8f..18d6ebd1 100644--- a/apps/teamhub/internal/agentruntimestate/runner_types.go+++ b/apps/teamhub/internal/agentruntimestate/runner_types.go@@ -89,9 +89,12 @@ type TouchLocalComputerInput struct {RecommendedVersion string `json:"recommended_version,omitempty"`}+// CreateLocalComputerEnrollmentInput describes one PKCE Local Computer+// enrollment request.type CreateLocalComputerEnrollmentInput struct {EnrollmentID string `json:"enrollment_id"`ComputerID string `json:"computer_id"`+ DaemonID string `json:"daemon_id,omitempty"`DisplayName string `json:"display_name"`Owner LocalComputerOwner `json:"owner"`RedirectURI string `json:"redirect_uri"`diff --git a/apps/teamhub/internal/agentruntimestate/types.go b/apps/teamhub/internal/agentruntimestate/types.goindex d379d636..0759e181 100644--- a/apps/teamhub/internal/agentruntimestate/types.go+++ b/apps/teamhub/internal/agentruntimestate/types.go@@ -22,6 +22,10 @@ var (// holds the Daemon Identity a Computer connected with.var ErrDaemonIdentityInUse = fmt.Errorf("Daemon Identity is held by another Local Computer: %w", ErrConflict)+// ErrComputerDaemonMismatch means the requested Local Computer is already bound+// to a different Daemon Identity than the one presented.+var ErrComputerDaemonMismatch = fmt.Errorf("Local Computer is bound to another Daemon Identity: %w", ErrConflict)+// ErrRemoved means the Local Computer was removed and cannot be renewed.var ErrRemoved = errors.New("Local Computer was removed")diff --git a/apps/teamhub/internal/app/contract_server_agent_runtime_error_test.go b/apps/teamhub/internal/app/contract_server_agent_runtime_error_test.goindex bf9846e9..0bf07bda 100644--- a/apps/teamhub/internal/app/contract_server_agent_runtime_error_test.go+++ b/apps/teamhub/internal/app/contract_server_agent_runtime_error_test.go@@ -27,6 +27,7 @@ func TestAgentRuntimeInboxAuthorizationDoesNotFenceContext(t *testing.T) {{"Inbox authorization", agentruntimestate.ErrInboxNotAuthorized, 403, "INBOX_NOT_AUTHORIZED"},{"Context lease or identity", agentruntimestate.ErrFenced, 409, "CONTEXT_FENCED"},{"real fence wins", errors.Join(agentruntimestate.ErrInboxNotAuthorized, agentruntimestate.ErrFenced), 409, "CONTEXT_FENCED"},+ {"Daemon Identity in use", agentruntimestate.ErrDaemonIdentityInUse, 409, "DAEMON_IDENTITY_IN_USE"},{"selection race", agentruntimestate.ErrConflict, 409, "AGENT_RUNTIME_CONFLICT"},} {t.Run(tc.name, func(t *testing.T) {diff --git a/apps/teamhub/internal/app/contract_server_agent_runtime_state.go b/apps/teamhub/internal/app/contract_server_agent_runtime_state.goindex edcb5837..acb1c1f1 100644--- a/apps/teamhub/internal/app/contract_server_agent_runtime_state.go+++ b/apps/teamhub/internal/app/contract_server_agent_runtime_state.go@@ -583,6 +583,8 @@ func (a *App) writeAgentRuntimeStateError(c *gin.Context, operation string, errstatus, code, message = http.StatusConflict, "CONTEXT_FENCED", "Agent Runtime Context identity or Agent Service epoch is no longer authoritative"case errors.Is(err, agentruntimestate.ErrInboxNotAuthorized):status, code, message = http.StatusForbidden, "INBOX_NOT_AUTHORIZED", "Agent Runtime Context cannot receive this Inbox"+ case errors.Is(err, agentruntimestate.ErrDaemonIdentityInUse):+ status, code, message = http.StatusConflict, "DAEMON_IDENTITY_IN_USE", "Daemon Identity is already bound to another Local Computer"case errors.Is(err, agentruntimestate.ErrConflict):status, code, message = http.StatusConflict, "AGENT_RUNTIME_CONFLICT", "Agent Runtime State conflicts with the request"case errors.Is(err, agentruntimestate.ErrDependency):diff --git a/apps/teamhub/internal/app/handlers_local_computer_enrollment.go b/apps/teamhub/internal/app/handlers_local_computer_enrollment.goindex 05220de7..f7b5eac0 100644--- a/apps/teamhub/internal/app/handlers_local_computer_enrollment.go+++ b/apps/teamhub/internal/app/handlers_local_computer_enrollment.go@@ -49,8 +49,8 @@ func (a *App) createLocalComputerEnrollment(c *gin.Context) {enrollmentID, authorizationCode := ids.New("enrollment"), newLocalComputerAuthorizationCode()codeHash := sha256.Sum256([]byte(authorizationCode))expiresAt := time.Now().UTC().Add(localComputerEnrollmentLifetime)- err := a.agentRuntimeState.CreateLocalComputerEnrollment(c.Request.Context(), agentruntimestate.CreateLocalComputerEnrollmentInput{- EnrollmentID: enrollmentID, ComputerID: computerID, DisplayName: request.DisplayName,+ resolvedComputerID, err := a.agentRuntimeState.CreateLocalComputerEnrollment(c.Request.Context(), agentruntimestate.CreateLocalComputerEnrollmentInput{+ EnrollmentID: enrollmentID, ComputerID: computerID, DaemonID: optionalStringValue(request.DaemonId), DisplayName: request.DisplayName,Owner: agentruntimestate.LocalComputerOwner{TenantID: tenantID, OwnerActorID: ownerID},RedirectURI: request.RedirectUri, CodeChallenge: request.CodeChallenge,AuthorizationCodeHash: codeHash[:], ExpiresAt: expiresAt, RenewsExistingComputer: renews,@@ -60,6 +60,12 @@ func (a *App) createLocalComputerEnrollment(c *gin.Context) {case errors.Is(err, agentruntimestate.ErrRemoved):a.writeError(c, http.StatusGone, "LOCAL_COMPUTER_REMOVED", "Local Computer was removed")return+ case errors.Is(err, agentruntimestate.ErrDaemonIdentityInUse):+ a.writeError(c, http.StatusConflict, "DAEMON_IDENTITY_IN_USE", "Daemon Identity is already bound to another Local Computer")+ return+ case errors.Is(err, agentruntimestate.ErrComputerDaemonMismatch):+ a.writeError(c, http.StatusConflict, "LOCAL_COMPUTER_IDENTITY_MISMATCH", "Local Computer is already bound to another Daemon Identity")+ returncase errors.Is(err, agentruntimestate.ErrNotFound), errors.Is(err, agentruntimestate.ErrConflict):a.writeError(c, http.StatusNotFound, "INVALID_ENROLLMENT", "Local Computer enrollment is invalid or expired")return@@ -71,7 +77,7 @@ func (a *App) createLocalComputerEnrollment(c *gin.Context) {return}c.JSON(http.StatusCreated, httpapi.LocalComputerEnrollmentAuthorization{- EnrollmentId: enrollmentID, ComputerId: computerID,+ EnrollmentId: enrollmentID, ComputerId: resolvedComputerID,AuthorizationCode: &authorizationCode, ExpiresAt: expiresAt,})}@@ -175,6 +181,7 @@ func (a *App) exchangeLocalComputerEnrollment(c *gin.Context) {func validLocalComputerEnrollmentCreate(request httpapi.LocalComputerEnrollmentCreateRequest) bool {return strings.TrimSpace(request.DisplayName) != "" && len(request.DisplayName) <= 120 &&(request.ComputerId == nil || localComputerIDPattern.MatchString(*request.ComputerId)) &&+ (request.DaemonId == nil || localComputerPKCEPattern.MatchString(*request.DaemonId)) &&localComputerPKCEPattern.MatchString(request.CodeChallenge) && validLocalComputerRedirect(request.RedirectUri)}diff --git a/apps/teamhub/internal/store/agent_runtime_state.sql.go b/apps/teamhub/internal/store/agent_runtime_state.sql.goindex d34935d7..0a2a23d3 100644--- a/apps/teamhub/internal/store/agent_runtime_state.sql.go+++ b/apps/teamhub/internal/store/agent_runtime_state.sql.go@@ -3289,6 +3289,43 @@ func (q *Queries) LockAgentRuntimeLocalComputer(ctx context.Context, computerIDreturn i, err}+const lockAgentRuntimeLocalComputerByDaemonID = `-- name: LockAgentRuntimeLocalComputerByDaemonID :one+SELECT computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id+FROM local_computers+WHERE daemon_id=$1::text+ AND status<>'removed'+FOR UPDATE+`++func (q *Queries) LockAgentRuntimeLocalComputerByDaemonID(ctx context.Context, daemonID string) (LocalComputer, error) {+ row := q.db.QueryRow(ctx, lockAgentRuntimeLocalComputerByDaemonID, daemonID)+ var i LocalComputer+ err := row.Scan(+ &i.ComputerID,+ &i.DisplayName,+ &i.Status,+ &i.CredentialGeneration,+ &i.Capacity,+ &i.ActiveOperations,+ &i.RuntimeInventory,+ &i.WorkspaceGrants,+ &i.RuntimeDiagnostics,+ &i.LastSeenAt,+ &i.RemovedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.DaemonID,+ &i.DaemonPublicKey,+ &i.DaemonIdentityVersion,+ &i.Platform,+ &i.DaemonVersion,+ &i.RecommendedVersion,+ &i.OwnerTenantID,+ &i.OwnerActorID,+ )+ return i, err+}+const lockAgentRuntimeLocalComputerEnrollment = `-- name: LockAgentRuntimeLocalComputerEnrollment :oneSELECT enrollment_id, tenant_id, owner_actor_id, requested_computer_id, renews_existing_computer, display_name, redirect_uri, code_challenge, authorization_code_hash, expires_at, exchanged_at, exchanged_generation, created_atFROM local_computer_enrollmentsdiff --git a/apps/teamhub/internal/store/queries/agent_runtime_state.sql b/apps/teamhub/internal/store/queries/agent_runtime_state.sqlindex 773127b6..644109f0 100644--- a/apps/teamhub/internal/store/queries/agent_runtime_state.sql+++ b/apps/teamhub/internal/store/queries/agent_runtime_state.sql@@ -1033,6 +1033,13 @@ WHERE computer_id=sqlc.arg(computer_id)::text)RETURNING *;+-- name: LockAgentRuntimeLocalComputerByDaemonID :one+SELECT *+FROM local_computers+WHERE daemon_id=sqlc.arg(daemon_id)::text+ AND status<>'removed'+FOR UPDATE;+-- name: DeletePendingAgentRuntimeLocalComputerEnrollments :execDELETE FROM local_computer_enrollmentsWHERE tenant_id=sqlc.arg(tenant_id)::textdiff --git a/apps/teamhub/tests/integration/agent_runtime_runner_state_test.go b/apps/teamhub/tests/integration/agent_runtime_runner_state_test.goindex d3b76fe9..ca6981fa 100644--- a/apps/teamhub/tests/integration/agent_runtime_runner_state_test.go+++ b/apps/teamhub/tests/integration/agent_runtime_runner_state_test.go@@ -27,7 +27,7 @@ func TestAgentRuntimeLocalComputerEnrollmentExchangeIsReplaySafe(t *testing.T) {DisplayName: "Runtime enrollment", Owner: owner, RedirectURI: "http://127.0.0.1:53100/callback",CodeChallenge: strings.Repeat("a", 43), AuthorizationCodeHash: firstHash[:], ExpiresAt: expiresAt,}- if err := env.service.CreateLocalComputerEnrollment(t.Context(), first); err != nil {+ if _, err := env.service.CreateLocalComputerEnrollment(t.Context(), first); err != nil {t.Fatalf("create Local Computer enrollment: %v", err)}consumeFirst := agentruntimestate.ConsumeLocalComputerEnrollmentInput{@@ -46,7 +46,7 @@ func TestAgentRuntimeLocalComputerEnrollmentExchangeIsReplaySafe(t *testing.T) {CodeChallenge: strings.Repeat("b", 43), AuthorizationCodeHash: secondHash[:], ExpiresAt: expiresAt,RenewsExistingComputer: true,}- if err := env.service.CreateLocalComputerEnrollment(t.Context(), renewal); err != nil {+ if _, err := env.service.CreateLocalComputerEnrollment(t.Context(), renewal); err != nil {t.Fatalf("create Local Computer renewal: %v", err)}consumeRenewal := agentruntimestate.ConsumeLocalComputerEnrollmentInput{@@ -77,7 +77,7 @@ func TestAgentRuntimeLocalComputerEnrollmentExchangeIsReplaySafe(t *testing.T) {pending := firstpending.EnrollmentID = "enrollment_rejected_" + rejectionpending.ComputerID = "computer_rejected_" + rejection- if err := env.service.CreateLocalComputerEnrollment(t.Context(), pending); err != nil {+ if _, err := env.service.CreateLocalComputerEnrollment(t.Context(), pending); err != nil {t.Fatal(err)}exchange := consumeFirst@@ -191,6 +191,91 @@ func TestAgentRuntimeLocalComputerRepairsWithSameDaemonAfterRemoval(t *testing.T}}+func TestAgentRuntimeLocalComputerRenewsByDaemonIdentityWithActiveAgents(t *testing.T) {+ allowParallelIntegrationTest(t)+ env := newRuntimeStateTestEnv(t)+ owner := runtimeComputerOwner()+ enrollRuntimeComputer(t, env, "computer_runtime_reset_a")+ setRuntimeAgentPlacementFields(t, env, "computer_runtime_reset_a", "codex")+ first := runtimeConnectInput("computer_runtime_reset_a", 0, time.Now())+ if _, err := env.service.ConnectLocalComputer(t.Context(), first); err != nil {+ t.Fatalf("connect Computer A: %v", err)+ }+ if status, err := env.service.RemoveLocalComputer(t.Context(), agentruntimestate.LocalComputerCredentialInput{+ ComputerID: "computer_runtime_reset_a", Owner: owner,+ }); err != nil || status != "has_agents" {+ t.Fatalf("Computer with active Agent removal status=%q err=%v, want has_agents", status, err)+ }++ expiresAt := time.Now().UTC().Truncate(time.Microsecond).Add(time.Hour)+ firstHash := sha256.Sum256([]byte("interrupted-reset-code"))+ resolved, err := env.service.CreateLocalComputerEnrollment(t.Context(), agentruntimestate.CreateLocalComputerEnrollmentInput{+ EnrollmentID: "enrollment-reset-1", ComputerID: "computer_runtime_reset_b1", DaemonID: first.DaemonID,+ DisplayName: "Reset A", Owner: owner, RedirectURI: "http://127.0.0.1:53100/callback",+ CodeChallenge: strings.Repeat("a", 43), AuthorizationCodeHash: firstHash[:], ExpiresAt: expiresAt,+ })+ if err != nil || resolved != "computer_runtime_reset_a" {+ t.Fatalf("create enrollment by Daemon Identity: resolved=%q err=%v", resolved, err)+ }++ secondHash := sha256.Sum256([]byte("completed-reset-code"))+ resolved, err = env.service.CreateLocalComputerEnrollment(t.Context(), agentruntimestate.CreateLocalComputerEnrollmentInput{+ EnrollmentID: "enrollment-reset-2", ComputerID: "computer_runtime_reset_b2", DaemonID: first.DaemonID,+ DisplayName: "Reset A", Owner: owner, RedirectURI: "http://127.0.0.1:53100/callback",+ CodeChallenge: strings.Repeat("b", 43), AuthorizationCodeHash: secondHash[:], ExpiresAt: expiresAt,+ })+ if err != nil || resolved != "computer_runtime_reset_a" {+ t.Fatalf("create second enrollment by Daemon Identity: resolved=%q err=%v", resolved, err)+ }+ renewed, err := env.service.ConsumeLocalComputerEnrollment(t.Context(), agentruntimestate.ConsumeLocalComputerEnrollmentInput{+ EnrollmentID: "enrollment-reset-2", RedirectURI: "http://127.0.0.1:53100/callback",+ CodeChallenge: strings.Repeat("b", 43), AuthorizationCodeHash: secondHash[:],+ })+ assertConsumedEnrollment(t, renewed, err, "computer_runtime_reset_a", 1)++ reconnected := runtimeConnectInput("computer_runtime_reset_a", 1, time.Now().Add(time.Second))+ connected, err := env.service.ConnectLocalComputer(t.Context(), reconnected)+ if err != nil || len(connected.Placements) != 1 || connected.Placements[0].AgentID != testRuntimeAgentID {+ t.Fatalf("reconnect renewed Computer A: placements=%+v err=%v", connected.Placements, err)+ }++ thirdHash := sha256.Sum256([]byte("explicit-reset-code"))+ resolved, err = env.service.CreateLocalComputerEnrollment(t.Context(), agentruntimestate.CreateLocalComputerEnrollmentInput{+ EnrollmentID: "enrollment-reset-3", ComputerID: "computer_runtime_reset_a", DaemonID: first.DaemonID,+ DisplayName: "Reset A", Owner: owner, RedirectURI: "http://127.0.0.1:53100/callback",+ CodeChallenge: strings.Repeat("c", 43), AuthorizationCodeHash: thirdHash[:], ExpiresAt: expiresAt,+ RenewsExistingComputer: true,+ })+ if err != nil || resolved != "computer_runtime_reset_a" {+ t.Fatalf("explicit renewal with Daemon Identity: resolved=%q err=%v", resolved, err)+ }+ var computerCount int+ if err := env.pool.QueryRow(t.Context(), `SELECT count(*) FROM local_computers WHERE owner_tenant_id=$1 AND owner_actor_id=$2`, owner.TenantID, owner.OwnerActorID).Scan(&computerCount); err != nil || computerCount != 1 {+ t.Fatalf("owner Computer count=%d err=%v, want 1", computerCount, err)+ }++ mismatchHash := sha256.Sum256([]byte("mismatch-reset-code"))+ if _, err := env.service.CreateLocalComputerEnrollment(t.Context(), agentruntimestate.CreateLocalComputerEnrollmentInput{+ EnrollmentID: "enrollment-reset-mismatch", ComputerID: "computer_runtime_reset_a", DaemonID: strings.Repeat("Z", 43),+ DisplayName: "Reset A", Owner: owner, RedirectURI: "http://127.0.0.1:53100/callback",+ CodeChallenge: strings.Repeat("d", 43), AuthorizationCodeHash: mismatchHash[:], ExpiresAt: expiresAt,+ RenewsExistingComputer: true,+ }); !errors.Is(err, agentruntimestate.ErrComputerDaemonMismatch) {+ t.Fatalf("explicit renewal with wrong Daemon Identity: err=%v, want ErrComputerDaemonMismatch", err)+ }++ seedPeerHumanActor(t, env.pool)+ otherHash := sha256.Sum256([]byte("other-owner-code"))+ if _, err := env.service.CreateLocalComputerEnrollment(t.Context(), agentruntimestate.CreateLocalComputerEnrollmentInput{+ EnrollmentID: "enrollment-reset-foreign", ComputerID: "computer_runtime_foreign", DaemonID: first.DaemonID,+ DisplayName: "Foreign", Owner: agentruntimestate.LocalComputerOwner{TenantID: "tenant_acme", OwnerActorID: "actor_acme_bob"},+ RedirectURI: "http://127.0.0.1:53100/callback", CodeChallenge: strings.Repeat("e", 43),+ AuthorizationCodeHash: otherHash[:], ExpiresAt: expiresAt,+ }); !errors.Is(err, agentruntimestate.ErrDaemonIdentityInUse) {+ t.Fatalf("foreign owner claim by Daemon Identity: err=%v, want ErrDaemonIdentityInUse", err)+ }+}+// A move only changes the registration row. The Computer the Agent left no// longer lists it when it connects, so its Runner there is removed and its// late results have no placement; the new Computer lists it at the next@@ -417,7 +502,7 @@ func enrollRuntimeComputerFor(t *testing.T, env runtimeStateTestEnv, computerIDOwner: owner, RedirectURI: "http://127.0.0.1:53100/callback", CodeChallenge: strings.Repeat("a", 43),AuthorizationCodeHash: codeHash[:], ExpiresAt: time.Now().UTC().Truncate(time.Microsecond).Add(time.Hour),}- if err := env.service.CreateLocalComputerEnrollment(t.Context(), enrollment); err != nil {+ if _, err := env.service.CreateLocalComputerEnrollment(t.Context(), enrollment); err != nil {return err}result, err := env.service.ConsumeLocalComputerEnrollment(t.Context(), agentruntimestate.ConsumeLocalComputerEnrollmentInput{diff --git a/apps/teamhub/tests/integration/local_computer_test.go b/apps/teamhub/tests/integration/local_computer_test.goindex 3c32deff..162a09b2 100644--- a/apps/teamhub/tests/integration/local_computer_test.go+++ b/apps/teamhub/tests/integration/local_computer_test.go@@ -337,3 +337,136 @@ func enrollLocalComputerOverHTTP(t *testing.T, env *testEnv, owner *http.Client,}return authorization.ComputerID}++func TestLocalComputerEnrollmentDaemonIdentityHTTP(t *testing.T) {+ allowParallelIntegrationTest(t)+ databaseURL := newIntegrationDatabase(t)+ pool, err := pgxpool.New(context.Background(), databaseURL)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(pool.Close)+ application, err := newTestApp(context.Background(), localComputerEnrollmentConfig(config.ForTest(func(c *config.Config) {+ c.DatabaseURL = databaseURL+ c.SessionTTL = time.Hour+ c.CookieName = "teamhub_session"+ c.TeamHubInternalToken = teamHubInternalToken+ c.NodeServicesInternalToken = nodeServicesInternalToken+ c.AgentRunTokenSecret = agentRunTokenSecret+ c.ArtifactStorageRoot = t.TempDir()+ })), withLocalComputers(&recordingLocalComputers{}))+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(application.Close)+ server := httptest.NewServer(application.Handler())+ registerIntegrationServerCleanup(t, server)+ env := &testEnv{t: t, databaseURL: databaseURL, pool: pool, server: server}+ alice := env.login("alice", alicePassword)+ bob := seedPeerHuman(t, env)++ computerA := enrollLocalComputerOverHTTP(t, env, alice, "Alice's Mac", "")+ if _, err := pool.Exec(t.Context(), `+ INSERT INTO actors(id,tenant_id,kind,display_name,handle)+ VALUES ('actor_local_reset','tenant_acme','agent','Local Reset','local_reset')+ `); err != nil {+ t.Fatal(err)+ }+ if _, err := pool.Exec(t.Context(), `+ INSERT INTO agent_registrations(+ actor_id,tenant_id,agent_management_id,status,instructions,runtime_model,+ computer_id,local_runtime_type,workspace_grant_id,created_by_actor_id+ ) VALUES (+ 'actor_local_reset','tenant_acme','agent-management-local-reset','active','Run locally','model-local',+ $1,'codex','grant_linger','actor_acme_alice'+ )+ `, computerA); err != nil {+ t.Fatal(err)+ }++ key := sha256.Sum256([]byte("http-daemon-key"))+ daemonHash := sha256.Sum256(key[:])+ daemonID := base64.RawURLEncoding.EncodeToString(daemonHash[:])+ daemonPubKey := base64.StdEncoding.EncodeToString(key[:])+ connectBody := func(computerID, ownerActorID string, generation string) map[string]any {+ return map[string]any{+ "computer_id": computerID,+ "owner": map[string]any{"tenant_id": acmeTenant, "owner_actor_id": ownerActorID},+ "credential_generation": generation,+ "daemon_id": daemonID,+ "daemon_public_key": daemonPubKey,+ "identity_version": "1",+ "status": "offline",+ "seen_at": time.Now().UTC().Format(time.RFC3339Nano),+ "display_name": "Alice's Mac",+ "runtimes": []string{"codex"},+ "runtime_diagnostics": []any{},+ "workspace_grants": []any{},+ "daemon_version": "0.51.0",+ }+ }+ status, body := agentRuntimeStateRequest(t, application.Handler(), http.MethodPost, "/v0/agent-runtime/local-computers/connect", teamHubInternalToken, connectBody(computerA, "actor_acme_alice", "0"))+ if status != http.StatusOK {+ t.Fatalf("connect Computer A status=%d body=%s", status, body)+ }++ status, _, removeBody := env.request(alice, http.MethodDelete, "/v0/tenants/"+acmeTenant+"/local-computers/"+computerA, nil, "")+ if status != http.StatusConflict || !containsJSONText(removeBody, "LOCAL_COMPUTER_HAS_AGENTS") {+ t.Fatalf("delete assigned Computer A status=%d body=%s", status, removeBody)+ }++ verifier := strings.Repeat("v", 43)+ challenge := sha256.Sum256([]byte(verifier))+ challengeB64 := base64.RawURLEncoding.EncodeToString(challenge[:])+ status, _, enrollBody := env.request(alice, http.MethodPost, "/v0/tenants/"+acmeTenant+"/local-computer-enrollments", map[string]any{+ "display_name": "Alice's Mac",+ "redirect_uri": "http://127.0.0.1:45123/callback",+ "code_challenge": challengeB64,+ "daemon_id": daemonID,+ }, "")+ if status != http.StatusCreated {+ t.Fatalf("re-enroll by daemon_id status=%d body=%s", status, enrollBody)+ }+ var authorization struct {+ EnrollmentID string `json:"enrollment_id"`+ ComputerID string `json:"computer_id"`+ AuthorizationCode string `json:"authorization_code"`+ }+ decode(t, enrollBody, &authorization)+ if authorization.ComputerID != computerA {+ t.Fatalf("re-enroll computer_id=%q, want %q", authorization.ComputerID, computerA)+ }+ status, _, exchangeBody := env.request(newClient(t), http.MethodPost, "/v0/local-computer-enrollments/"+authorization.EnrollmentID+"/exchange", map[string]any{+ "authorization_code": authorization.AuthorizationCode,+ "code_verifier": verifier,+ "redirect_uri": "http://127.0.0.1:45123/callback",+ }, "")+ if status != http.StatusOK {+ t.Fatalf("exchange renewed enrollment status=%d body=%s", status, exchangeBody)+ }+ status, body = agentRuntimeStateRequest(t, application.Handler(), http.MethodPost, "/v0/agent-runtime/local-computers/connect", teamHubInternalToken, connectBody(computerA, "actor_acme_alice", "1"))+ if status != http.StatusOK || !containsJSONText(body, "agent-management-local-reset") {+ t.Fatalf("reconnect renewed Computer A status=%d body=%s", status, body)+ }++ 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),+ "display_name": "Alice's Mac",+ "redirect_uri": "http://127.0.0.1:45123/callback",+ "code_challenge": challengeB64,+ }, "")+ assertAgentRuntimeHTTPError(t, status, mismatchBody, http.StatusConflict, "LOCAL_COMPUTER_IDENTITY_MISMATCH")++ status, _, bobEnrollBody := env.request(bob, http.MethodPost, "/v0/tenants/"+acmeTenant+"/local-computer-enrollments", map[string]any{+ "display_name": "Bob's Mac",+ "redirect_uri": "http://127.0.0.1:45123/callback",+ "code_challenge": challengeB64,+ "daemon_id": daemonID,+ }, "")+ assertAgentRuntimeHTTPError(t, status, bobEnrollBody, http.StatusConflict, "DAEMON_IDENTITY_IN_USE")++ computerB := enrollLocalComputerOverHTTP(t, env, bob, "Bob's Mac", "")+ status, bobConnectBody := agentRuntimeStateRequest(t, application.Handler(), http.MethodPost, "/v0/agent-runtime/local-computers/connect", teamHubInternalToken, connectBody(computerB, "actor_acme_bob", "0"))+ assertAgentRuntimeHTTPError(t, status, bobConnectBody, http.StatusConflict, "DAEMON_IDENTITY_IN_USE")+}diff --git a/apps/web/src/features/local-computer/desktop-computer-setup.tsx b/apps/web/src/features/local-computer/desktop-computer-setup.tsxindex 0ec3b7d1..d0ac7b24 100644--- a/apps/web/src/features/local-computer/desktop-computer-setup.tsx+++ b/apps/web/src/features/local-computer/desktop-computer-setup.tsx@@ -62,6 +62,8 @@ function desktopSetupProblem(status: DesktopComputerStatus) {switch (status.bridge) {case "auth_failed":return "This computer's sign-in expired. Choose Reconnect This Computer in the Linger menu bar menu.";+ case "identity_conflict":+ return "This computer is already registered under another Computer entry. Choose Reconnect This Computer in the Linger menu bar menu.";case "upgrade_required":return "Update the Linger app to connect this computer.";case "disconnected":diff --git a/apps/web/src/features/rooms/quick-create-general-agent-page.test.tsx b/apps/web/src/features/rooms/quick-create-general-agent-page.test.tsxindex 20d2f3f3..153e6ef6 100644--- a/apps/web/src/features/rooms/quick-create-general-agent-page.test.tsx+++ b/apps/web/src/features/rooms/quick-create-general-agent-page.test.tsx@@ -910,6 +910,10 @@ describe("quick Local Agent creation", () => {it.each([[{ bridge: "auth_failed", runtime: "stopped" }, /sign-in expired/],+ [+ { bridge: "identity_conflict", runtime: "ready" },+ /already registered under another Computer/,+ ],[{ bridge: "online", runtime: "crashed" }, /local runtime stopped/],])("says why it cannot find runtimes instead of searching forever (%o)",diff --git a/contracts/generated/go/teamhubpublic/openapi.gen.go b/contracts/generated/go/teamhubpublic/openapi.gen.goindex 4d1b333b..89eca03a 100644--- a/contracts/generated/go/teamhubpublic/openapi.gen.go+++ b/contracts/generated/go/teamhubpublic/openapi.gen.go@@ -6379,9 +6379,12 @@ type LocalComputerEnrollmentCreateRequest struct {CodeChallenge string `json:"code_challenge"`// ComputerId Opaque, case-sensitive identifier. Clients must not infer type or time from it.- ComputerId *Id `json:"computer_id,omitempty"`- DisplayName string `json:"display_name"`- RedirectUri string `json:"redirect_uri"`+ ComputerId *Id `json:"computer_id,omitempty"`++ // DaemonId SHA-256 of the local Daemon Ed25519 public key in base64url. When supplied, TeamHub renews a live Computer already bound to this Daemon Identity for the same owner and rejects claims by another owner with 409 DAEMON_IDENTITY_IN_USE.+ DaemonId *string `json:"daemon_id,omitempty"`+ DisplayName string `json:"display_name"`+ RedirectUri string `json:"redirect_uri"`}// LocalComputerEnrollmentExchangeRequest defines model for LocalComputerEnrollmentExchangeRequest.diff --git a/contracts/generated/typescript/src/generated/teamhub-public/types.ts b/contracts/generated/typescript/src/generated/teamhub-public/types.tsindex 0cdaf996..d7e714c2 100644--- a/contracts/generated/typescript/src/generated/teamhub-public/types.ts+++ b/contracts/generated/typescript/src/generated/teamhub-public/types.ts@@ -5011,6 +5011,8 @@ export interface components {};LocalComputerEnrollmentCreateRequest: {computer_id?: components["schemas"]["Id"];+ /** @description SHA-256 of the local Daemon Ed25519 public key in base64url. When supplied, TeamHub renews a live Computer already bound to this Daemon Identity for the same owner and rejects claims by another owner with 409 DAEMON_IDENTITY_IN_USE. */+ daemon_id?: string;display_name: string;/** Format: uri */redirect_uri: string;@@ -9364,6 +9366,7 @@ export interface operations {400: components["responses"]["BadRequest"];401: components["responses"]["Unauthenticated"];404: components["responses"]["NotFound"];+ 409: components["responses"]["Conflict"];410: components["responses"]["Gone"];503: components["responses"]["ServiceUnavailable"];};diff --git a/contracts/openapi/components/domain.yaml b/contracts/openapi/components/domain.yamlindex caec2fdd..641abe4b 100644--- a/contracts/openapi/components/domain.yaml+++ b/contracts/openapi/components/domain.yaml@@ -334,6 +334,14 @@ components:properties:computer_id:$ref: "./common.yaml#/components/schemas/Id"+ daemon_id:+ type: string+ pattern: "^[A-Za-z0-9_-]{43}$"+ description: >-+ SHA-256 of the local Daemon Ed25519 public key in base64url. When+ supplied, TeamHub renews a live Computer already bound to this+ Daemon Identity for the same owner and rejects claims by another+ owner with 409 DAEMON_IDENTITY_IN_USE.display_name:type: stringminLength: 1diff --git a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml b/contracts/openapi/teamhub-public/teamhub-api.openapi.yamlindex 030e882b..a12c6ffe 100644--- a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml+++ b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml@@ -1027,6 +1027,8 @@ paths:$ref: '../components/common.yaml#/components/responses/Unauthenticated''404':$ref: '../components/common.yaml#/components/responses/NotFound'+ '409':+ $ref: '../components/common.yaml#/components/responses/Conflict''410':$ref: '../components/common.yaml#/components/responses/Gone''503':