Skip to content

fix(computer): keep the same Computer when Linger is set up again - #229

Closed
oldwinter53 wants to merge 2 commits into
mainfrom
oldwinter/014-c1
Closed

oldwinter53 wants to merge 2 commits into
mainfrom
oldwinter/014-c1

Conversation

@oldwinter53

@oldwinter53 oldwinter53 commented Nov 18, 2026 •

Copy link
Copy Markdown

Summary

Set Up Again (the start-failure page's recovery) now reconnects the same Computer, so its Agents keep working. A desktop already stuck after an earlier Set Up Again heals the next time the app starts. A Daemon Identity held by another Computer now has its own error code, DAEMON_IDENTITY_IN_USE, instead of a generic 409 loop. Fixes P0-3 (#97).

Root cause

  • apps/desktop/src/main/local-server.ts #reset() calls EnrollmentModule.unenroll(), which drops computerId. The next Quick Install then enrolls a new Computer.
  • The daemon keeps its identity key (<userData>/computer/state/daemon-identity.json), and TeamHub keeps it bound to the old Computer. Every connect of the new Computer failed in ConnectLocalComputer with ErrDaemonIdentityInUse, which wraps ErrConflict and was answered as a generic 409 AGENT_RUNTIME_CONFLICT. The gateway closed the connection with 1011 and the daemon redialed forever. The Agents placed on the old Computer never ran again, and no product path could recover.

Fix

  • The desktop names its Daemon ID when it enrolls. readDaemonId (apps/desktop/src/main/enrollment.ts:241) derives it the way the daemon does: the SHA-256 of the raw public key. It reads only the public key. An enrollment sends it as daemon_id only when the server's /v0/me lists the local_computer_enrollment_daemon_id server capability (acceptsDaemonId, enrollment.ts:171). TeamHub decodes request bodies strictly, so a team server older than the desktop gets the old request without daemon_id and the enrollment still works there.
  • Server capability. CurrentIdentity (served by /v0/me and inside Session) gets an optional server_capabilities list, an additive change. This TeamHub lists local_computer_enrollment_daemon_id (apps/teamhub/internal/app/models.go, serverCapabilities). An older TeamHub omits the list. The desktop already reads /v0/me before every enrollment, so the gate adds no request; it decides on the structured field alone, with no retry after an error and no message matching.
  • TeamHub renews the Computer that holds that Daemon ID. CreateLocalComputerEnrollment (apps/teamhub/internal/agentruntimestate/runner.go:271) calls renewComputerHoldingDaemon (runner.go:342):
    • If the holder belongs to the same owner (tenant and actor), the enrollment renews the holder instead of the requested Computer or a new one. The holder's credential generation goes up, and its Agents stay placed on it.
    • If the request named another Computer of that owner that never bound a Daemon Identity and has no Agents, that Computer is the orphan an earlier Set Up Again left, so it is removed in the same transaction.
    • If another owner's Computer holds the Daemon ID, the enrollment is refused with DAEMON_IDENTITY_IN_USE. One owner's Computer is never handed to another owner.
    • The response returns the Computer that was actually renewed. The desktop already stores the computer_id from the response.
    • New sqlc query LockAgentRuntimeLocalComputerByDaemonID (internal/store/queries/agent_runtime_state.sql:950).
  • Heal at start. The desktop config now records the Daemon ID its enrollment named (daemonId). At start, an enrollment that named no Daemon ID, or a different one, is renewed once the server lists the capability (enrollment.ts:317; #nameDaemon reads /v0/me first; on an older server nothing is renewed, so the credential is not rotated on every launch), using the same mechanism as the existing renewal of enrollments without an owner. A machine stuck on 0.1.3 therefore renews its orphan, and TeamHub moves it back to the Computer its daemon holds.
  • Its own code and UI.
    • Enrollment: TeamHub answers 409 DAEMON_IDENTITY_IN_USE (handlers_local_computer_enrollment.go:63). The desktop turns that code into EnrollmentError("DAEMON_IDENTITY_IN_USE") with the message "This computer is connected to another Linger account. Remove it from that account's Computers, then connect it again." Quick Install, the tray and the SPA's connect action already show that message.
    • Connect: writeAgentRuntimeStateError maps ErrDaemonIdentityInUse to 409 DAEMON_IDENTITY_IN_USE (contract_server_agent_runtime_state.go:587). The Agent Service turns it into RunnerDaemonIdentityInUseError (local-computer-registry.ts:150), logs runner.hello.daemon_identity_in_use and closes the socket with 1008 daemon_identity_in_use: … (runner-gateway-websocket.ts:662). The daemon needs no change: it classifies a 1008 close without upgrade_required as unavailable and redials on backoff. A self-update no longer counts this close as a fault of the release; the earlier 1011 counted as one.
  • Contracts: daemon_id is added to LocalComputerEnrollmentCreateRequest, the create endpoint gets a 409 response, and the connect operation's description names DAEMON_IDENTITY_IN_USE. The generated code is regenerated.
  • Docs: apps/desktop/AGENTS.md describes Set Up Again and the enrollment rules.

The web needs no change: the orphan Computer had no workspace grants, so the Computers page never listed it.

Tests

Each new test failed before the fix:

  • TeamHub integration tests (real PostgreSQL), tests/integration/agent_runtime_runner_state_test.go:
    • TestAgentRuntimeLocalComputerEnrollmentRenewsTheComputerItsDaemonHolds: Set Up Again renews the held Computer, and its Agent is listed again on reconnect.
    • TestAgentRuntimeLocalComputerRenewalHealsAComputerStuckBehindItsDaemonIdentity: reproduces the 409 state first, then heals it: the orphan is removed and the holder reconnects.
    • TestAgentRuntimeLocalComputerEnrollmentByDaemonIDKeepsOwnersApart: a Computer that has its own Daemon, or that has Agents, is kept. Another owner is refused, and the held Computer is unchanged.
  • TeamHub HTTP test (tests/integration/local_computer_test.go): TestLocalComputerEnrollmentByDaemonIDOverHTTP checks that the owner gets 201 with the held computer_id and that another account gets 409 DAEMON_IDENTITY_IN_USE.
  • TeamHub unit test: a new error-mapping case in contract_server_agent_runtime_error_test.go.
  • Agent Service:
    • tests/agent/runner-gateway/local-computer-registry.test.ts (new) checks the mapping from the TeamHub code to the gateway error.
    • runner-gateway-websocket.test.ts checks the 1008 close with the new reason.
  • Desktop (src/main/enrollment.test.ts):
    • readDaemonId.
    • Against a server whose /v0/me has no capability: the create body has no daemon_id and the enrollment succeeds (both enrollComputer and the module); at start the desktop reads only /v0/me and does not renew. Against a server with the capability, daemon_id is sent.
    • The create body carries daemon_id.
    • The 409 code becomes DAEMON_IDENTITY_IN_USE.
    • After Set Up Again, enrolling pairs the held Computer.
    • At start, an enrollment without the Daemon ID is renewed once, and one that has it is not renewed.

Checks run:

  • make check BASE=origin/main: every planned check passes except one Go test in check-computer. TestManagedToolsUpdateKeepsResidentDaemonPID fails with "Managed tools require Node 26.5.0" and fails the same way on a clean origin/main checkout on this host. This PR does not touch apps/computer. check-packages (native-process.test.ts) once timed out under parallel load and passed on its own; scripts/install.test.ts needed mise shims off PATH. Both are host issues, not this change.
  • Correction to the first round: that make check stopped its heavy lane after the script failure, so node-services never ran then. It would have caught a type error in the new registry test, which is now fixed, and make check-node-services passes.
  • make check-repository-gate BASE=origin/main: passes.
  • make -C apps/teamhub fmt-check and go test ./tests/integration/layout: pass.
  • The focused TeamHub integration tests above were run again after rebasing onto the newest main.

Critical path, overlaps, limits

  • User message → provider_ready: this PR adds no network round trip and no file walk there. Enrollment reads one small file, and the start-time renewal runs only for an enrollment without a matching Daemon ID.
  • Overlaps with other open PRs: apps/desktop/src/main/index.ts is also touched by feat(desktop): reach the update feed from mainland China through npm #224; this PR only adds daemonIdentityFile to the EnrollmentModule options. This PR does not touch local-server.ts or runner-connections.ts, which feat: switch a Computer's model source, with bring-your-own-key endpoints #222, feat(local-installation): resolve one download region and order every download by it #213 and feat(desktop): reach the update feed from mainland China through npm #224 change.
  • One-time renewal: on the first start of 0.1.4 against a server that lists the capability, every already-enrolled desktop renews once, because no stored Daemon ID exists yet. So does a fresh install on its second start: its daemon had not run yet when it enrolled. Each such renewal rotates the credential once and restarts the daemon.
  • Version skew: a 0.1.4 desktop against a TeamHub older than this change enrolls exactly as before, without daemon_id. There, Set Up Again still pairs a new Computer; the fix and the heal take effect once that server is updated, at the desktop's next start or enrollment.
  • Not covered:
    • Earlier orphans other than the one the desktop config names (for example the second and third of ae17…/e2ad…/38e8… on the Mac) stay as inert, unlisted, agent-less rows.
    • CLI enrollments (linger-computer setup) do not send daemon_id yet.

Real-machine checks for the 0.1.4 RC round (FIXLIST section 6, P0-3)

Run on macOS (macmini) and Windows (homewin); Linux is optional.

  1. Fix path:
    1. On a 0.1.4 RC with a working Quick Install and at least one Agent, force the start-failure page (for example, stop the services and break the record), then choose Set Up Again → Quick Install.
    2. Expected: the Computers page shows the same Computer (same id in <userData>/config.json before and after), with no second Computer row in TeamHub (query local_computers for the owner).
    3. Expected: the Computer comes online and the existing Agents answer a chat message. The desktop log shows enrollment.completed with the old computer_id.
  2. Heal path:
    1. On official 0.1.3, reproduce the stuck state: Set Up Again → Quick Install. Confirm the Agents are dead and the Agent Service log shows connects rejected with AGENT_RUNTIME_CONFLICT.
    2. Upgrade to the 0.1.4 RC and launch.
    3. Expected: one enrollment.completed with the old computer_id. The orphan named in the 0.1.3 config is removed in local_computers. The Computer comes online and the Agents answer.
    4. Expected: on later launches there is no further renewal (config.json has daemonId).
  3. Another account:
    1. Sign the desktop into a second account on the same server without removing the first account's Computer, then choose Connect This Computer.
    2. Expected: the dialog says "This computer is connected to another Linger account…". No new Computer row is created. The first account's Computer and Agents are untouched.
  4. Older team server: point the 0.1.4 RC desktop at a TeamHub without this change (for example the 0.1.3 server) and connect the computer. Expected: the enrollment succeeds and the create request has no daemon_id. On relaunch, the desktop log shows no enrollment.renew_failed and no repeated renewal.
  5. Gateway code: with an orphan connecting (for example a 0.1.3 desktop against the 0.1.4 server), the Agent Service log shows runner.hello.daemon_identity_in_use, and the daemon log shows close 1008 daemon_identity_in_use: rather than 1011.

🤖 Generated with Claude Code

Set Up Again unenrolled the desktop, so the next enrollment paired a new
Computer while the machine's Daemon Identity stayed bound to the old one.
Every connect then failed with a generic 409 and the Agents on the old
Computer never ran again.

The desktop now names its Daemon ID when it enrolls. TeamHub renews the
owner's Computer that holds that identity instead of pairing a new one,
removes the never-connected orphan the request named, and refuses another
account's Computer with DAEMON_IDENTITY_IN_USE. An enrollment made without
the Daemon ID is renewed once at start, which heals computers already
stuck. The Runner Gateway closes such a connection with its own 1008
reason instead of a service failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve with nits (1 P2)

Scope: base main, merge base fb2e1537, 1 commit, 26 files reviewed at 56f02d9f. Helper skills loaded: coderbook, ponytail-review, karpathy-guidelines. Ran in a separate session.

Findings

P2

Orphan removal copies RemoveLocalComputer's removal steps (apps/teamhub/internal/agentruntimestate/runner.go:372-387)
renewComputerHoldingDaemon repeats the body of RemoveLocalComputer (runner.go:243-258) step for step: CountLocalAgentRegistrationsByComputer → skip if > 0 → PurgeAgentRuntimeLocalComputerEnrollmentsByComputer → DeleteLocalComputerModelSnapshot → RemoveAgentRuntimeLocalComputer. So "removing a Computer" is now written in two places. If one gains a step later (for example cleaning up another per-Computer table, or emitting a change), the orphan path will silently stop doing it and leave dangling rows for the removed orphan.
Fix: move the shared part into one in-transaction helper, e.g. removeUnplacedLocalComputer(ctx, queries, owner, computerID) (removed bool, err error), that does the agent count and the three deletes. Call it from both RemoveLocalComputer and renewComputerHoldingDaemon. Each caller keeps its own lock, owner checks and status checks.

Verified as fine

  • Daemon ID derivation matches the daemon. The daemon stores public_key as RawStdEncoding (local-daemon/internal/linger/transport/identity_store.go:81) and derives the ID as RawURLEncoding(sha256(pub)) (transport/identity.go:39-41). readDaemonId decodes with Node's lenient base64, checks for 32 bytes and hashes to base64url without padding, which is the same. The path <userData>/computer/state/daemon-identity.json matches main.go:320 and the desktop's daemonStateDirectory. Only the public key is read.
  • Lookup by daemon ID is unambiguous. local_computers_daemon_id_idx is a partial UNIQUE index, so the :one lookup can't return an arbitrary row. RemoveAgentRuntimeLocalComputer sets daemon_id to NULL, so a removed Computer never counts as a holder. That matches the new query's comment.
  • Owner boundary. A holder that belongs to another tenant or actor returns ErrDaemonIdentityInUse and is never renewed. The orphan is removed only if it belongs to the same owner, is not removed, never bound a daemon, and has no Agents. Holder lock, orphan removal and enrollment insert all happen in one executeLocalComputerTx.
  • Error mapping order. ErrDaemonIdentityInUse is matched before ErrConflict in both writeAgentRuntimeStateError and the enrollment handler. A unit case was added in contract_server_agent_runtime_error_test.go.
  • Daemon handling of the new close. The daemon classifies a 1008 close without upgrade_required: and without the scope-violation reason as FailureUnavailable (transport/gateway.go:321-327). So the PR's claims hold: no daemon change is needed, and the close no longer counts against a self-update release the way 1011 did.
  • Startup heal. The condition daemonId !== undefined && config.daemonId !== daemonId runs at most one renewal per mismatch, because #enroll then records daemonId. It reuses the existing void this.enroll() renewal path, and unenroll clears daemonId. Existing installs, and fresh installs whose daemon had not yet created its identity at enrollment, renew once on the next start. This is a one-time credential rotation, as the PR describes.
  • Handler. computerID, err := redeclares computerID with the Computer actually renewed, and the response returns it. The desktop already stores computer_id from the response.
  • Contracts and docs. daemon_id and the 409 response are added in contracts/openapi, and the generated diffs match. apps/desktop/AGENTS.md documents Set Up Again and the enrollment rules. No CJK, no new env vars, no cross-app imports.
  • Tests. Integration tests cover renewing the holder, healing a stuck Computer, and keeping owners apart. Desktop tests cover the code mapping and the one-time renewal. A Node test covers the 1008 close mapping.

Process notes

  • One commit, no merge or fixup commits. The branch is up to date with main.

CI

Passing: changes, check (contracts), check (desktop), check (installer), check (teamhub-cli), repository-gate, web-static, web tests (2/3), CodeQL/Analyze. Still pending when this review ran: check (teamhub) (runs the new integration tests), check (packages), web tests (1/3), web tests (3/3). check (computer-go) was skipped because no daemon code changed. I ran no tests myself; the integration tests need PostgreSQL, so I relied on CI and the code for them.

Automated review by Claude Code


Automated review of 56f02d9 by Claude Code.

TeamHub decodes request bodies strictly, so a desktop newer than its team
server could not enroll once it sent daemon_id. /v0/me now lists
server_capabilities, and the desktop sends daemon_id only when the list
holds local_computer_enrollment_daemon_id. The start-time renewal that
names the daemon waits until the server lists it, so an older server sees
no repeated credential rotation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve with nits (0 new findings; 1 previous P2 still open)

Scope: follow-up on 56f02d9, reviewing head 3cfa970 against main (merge base fb2e1537). 2 commits; 9 files changed since the previous review (27 in the whole PR). Loaded coderbook, ponytail-review and karpathy-guidelines. Ran alone in a separate session.

Previous findings

  • P2: the orphan removal in renewComputerHoldingDaemon duplicates RemoveLocalComputer's removal steps. Not resolved. apps/teamhub/internal/agentruntimestate/runner.go did not change in this push, and lines 375-386 still repeat the purge enrollments, delete model snapshot and remove computer sequence from lines 248-258. One helper that runs inside the transaction, called from both places, would keep the two from drifting apart.

Findings

No new findings in the changes since 56f02d9.

Verified as fine

  • Version skew. CurrentIdentity.server_capabilities is optional and additive. It is defined in contracts/openapi/components/domain.yaml, and the generated Go and TypeScript match the source. TeamHub fills it from a single package-level list in models.go. I found no runtime schema validation of the /v0/me / Session response in Web or the CLI, so the extra field cannot break old clients during a rolling deploy.
  • The desktop gate (acceptsDaemonId) uses only the structured field. It sends no daemon_id to an older server, never retries after an error, and does no message matching. Enrolled.daemonId is set only when the field was actually sent, so config.daemonId stays undefined against an older server.
  • Start-time heal (EnrollmentModule.start). A missing owner or a mismatched credential still triggers an unconditional renewal. A Daemon ID mismatch triggers a renewal only after #nameDaemon sees the capability, so an older server never gets its credential rotated on every launch. A signed-out or unreachable session (#identity returns undefined) does nothing. Against an older server the cost is one /v0/me read per launch, off the user message → provider_ready path.
  • Tests cover both sides of the gate: enrollComputer and EnrollmentModule with and without the capability, plus the start path against an older server. The HTTP integration test asserts that /v0/me lists the capability. The registry test now uses the shared runtimeDiagnostics() fixture, which fixes the type error from the first round.
  • apps/desktop/AGENTS.md is updated to describe the capability gate.
  • PR description: the claims about the capability, the older-server behaviour and the start-time renewal match the diff.

Process notes

  • The branch is behind main (ff092f21), and main requires up-to-date branches, so it needs a rebase before merge.
  • 3cfa970 also fixes local-computer-registry.test.ts, which 56f02d9 broke. main takes rebase merges, so 56f02d9 would land on its own with a node-services type error. Consider squashing that fix (or the whole second commit) into the first commit.
  • No merge commits. Both commits have the same author.

CI

At review time most checks were still pending: contracts, desktop, packages, teamhub, teamhub-cli, repository-gate, web tests and web-static. installer, CodeQL and Analyze passed, and computer-go was skipped (the PR doesn't touch apps/computer). I didn't run any tests locally: this worktree has no node_modules installed, so I left the desktop enrollment tests to check (desktop).

Automated review by Claude Code


Automated review of 3cfa970 by Claude Code.

@oldwinter53

Copy link
Copy Markdown
Author

Closing: main already has #234, which fixes the same problem (#97) with a different implementation, so this branch no longer applies. The parts of this PR that #234 does not cover (server capability gate for daemon_id, healing a desktop already stuck at start, removing the orphan Computer) are tracked in #243.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants