Repository navigation
fix(computer): keep the same Computer when Linger is set up again - #229
oldwinter53 wants to merge 2 commits into
Conversation
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>
There was a problem hiding this comment.
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_keyasRawStdEncoding(local-daemon/internal/linger/transport/identity_store.go:81) and derives the ID asRawURLEncoding(sha256(pub))(transport/identity.go:39-41).readDaemonIddecodes 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.jsonmatchesmain.go:320and the desktop'sdaemonStateDirectory. Only the public key is read. - Lookup by daemon ID is unambiguous.
local_computers_daemon_id_idxis a partial UNIQUE index, so the:onelookup can't return an arbitrary row.RemoveAgentRuntimeLocalComputersetsdaemon_idto 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
ErrDaemonIdentityInUseand 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 oneexecuteLocalComputerTx. - Error mapping order.
ErrDaemonIdentityInUseis matched beforeErrConflictin bothwriteAgentRuntimeStateErrorand the enrollment handler. A unit case was added incontract_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 asFailureUnavailable(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 !== daemonIdruns at most one renewal per mismatch, because#enrollthen recordsdaemonId. It reuses the existingvoid this.enroll()renewal path, andunenrollclearsdaemonId. 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 :=redeclarescomputerIDwith the Computer actually renewed, and the response returns it. The desktop already storescomputer_idfrom the response. - Contracts and docs.
daemon_idand the 409 response are added incontracts/openapi, and the generated diffs match.apps/desktop/AGENTS.mddocuments 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>
There was a problem hiding this comment.
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
renewComputerHoldingDaemonduplicatesRemoveLocalComputer's removal steps. Not resolved.apps/teamhub/internal/agentruntimestate/runner.godid 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_capabilitiesis optional and additive. It is defined incontracts/openapi/components/domain.yaml, and the generated Go and TypeScript match the source. TeamHub fills it from a single package-level list inmodels.go. I found no runtime schema validation of the/v0/me/Sessionresponse 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 nodaemon_idto an older server, never retries after an error, and does no message matching.Enrolled.daemonIdis set only when the field was actually sent, soconfig.daemonIdstays 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#nameDaemonsees the capability, so an older server never gets its credential rotated on every launch. A signed-out or unreachable session (#identityreturns undefined) does nothing. Against an older server the cost is one/v0/meread per launch, off the user message →provider_readypath. - Tests cover both sides of the gate:
enrollComputerandEnrollmentModulewith and without the capability, plus the start path against an older server. The HTTP integration test asserts that/v0/melists the capability. The registry test now uses the sharedruntimeDiagnostics()fixture, which fixes the type error from the first round. apps/desktop/AGENTS.mdis 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), andmainrequires up-to-date branches, so it needs a rebase before merge. 3cfa970also fixeslocal-computer-registry.test.ts, which56f02d9broke.maintakes rebase merges, so56f02d9would 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.
|
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 |
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()callsEnrollmentModule.unenroll(), which dropscomputerId. The next Quick Install then enrolls a new Computer.<userData>/computer/state/daemon-identity.json), and TeamHub keeps it bound to the old Computer. Every connect of the new Computer failed inConnectLocalComputerwithErrDaemonIdentityInUse, which wrapsErrConflictand was answered as a generic 409AGENT_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
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 asdaemon_idonly when the server's/v0/melists thelocal_computer_enrollment_daemon_idserver capability (acceptsDaemonId,enrollment.ts:171). TeamHub decodes request bodies strictly, so a team server older than the desktop gets the old request withoutdaemon_idand the enrollment still works there.CurrentIdentity(served by/v0/meand insideSession) gets an optionalserver_capabilitieslist, an additive change. This TeamHub listslocal_computer_enrollment_daemon_id(apps/teamhub/internal/app/models.go,serverCapabilities). An older TeamHub omits the list. The desktop already reads/v0/mebefore 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.CreateLocalComputerEnrollment(apps/teamhub/internal/agentruntimestate/runner.go:271) callsrenewComputerHoldingDaemon(runner.go:342):DAEMON_IDENTITY_IN_USE. One owner's Computer is never handed to another owner.computer_idfrom the response.LockAgentRuntimeLocalComputerByDaemonID(internal/store/queries/agent_runtime_state.sql:950).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;#nameDaemonreads/v0/mefirst; 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.DAEMON_IDENTITY_IN_USE(handlers_local_computer_enrollment.go:63). The desktop turns that code intoEnrollmentError("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.writeAgentRuntimeStateErrormapsErrDaemonIdentityInUseto 409DAEMON_IDENTITY_IN_USE(contract_server_agent_runtime_state.go:587). The Agent Service turns it intoRunnerDaemonIdentityInUseError(local-computer-registry.ts:150), logsrunner.hello.daemon_identity_in_useand closes the socket with 1008daemon_identity_in_use: …(runner-gateway-websocket.ts:662). The daemon needs no change: it classifies a 1008 close withoutupgrade_requiredas 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.daemon_idis added toLocalComputerEnrollmentCreateRequest, the create endpoint gets a 409 response, and the connect operation's description namesDAEMON_IDENTITY_IN_USE. The generated code is regenerated.apps/desktop/AGENTS.mddescribes 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:
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.tests/integration/local_computer_test.go):TestLocalComputerEnrollmentByDaemonIDOverHTTPchecks that the owner gets 201 with the heldcomputer_idand that another account gets 409DAEMON_IDENTITY_IN_USE.contract_server_agent_runtime_error_test.go.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.tschecks the 1008 close with the new reason.src/main/enrollment.test.ts):readDaemonId./v0/mehas no capability: the create body has nodaemon_idand the enrollment succeeds (bothenrollComputerand the module); at start the desktop reads only/v0/meand does not renew. Against a server with the capability,daemon_idis sent.daemon_id.DAEMON_IDENTITY_IN_USE.Checks run:
make check BASE=origin/main: every planned check passes except one Go test incheck-computer.TestManagedToolsUpdateKeepsResidentDaemonPIDfails with "Managed tools require Node 26.5.0" and fails the same way on a cleanorigin/maincheckout on this host. This PR does not touchapps/computer.check-packages(native-process.test.ts) once timed out under parallel load and passed on its own;scripts/install.test.tsneeded mise shims off PATH. Both are host issues, not this change.make checkstopped 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, andmake check-node-servicespasses.make check-repository-gate BASE=origin/main: passes.make -C apps/teamhub fmt-checkandgo test ./tests/integration/layout: pass.Critical path, overlaps, limits
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.apps/desktop/src/main/index.tsis also touched by feat(desktop): reach the update feed from mainland China through npm #224; this PR only addsdaemonIdentityFileto theEnrollmentModuleoptions. This PR does not touchlocal-server.tsorrunner-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.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.linger-computer setup) do not senddaemon_idyet.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.
<userData>/config.jsonbefore and after), with no second Computer row in TeamHub (querylocal_computersfor the owner).enrollment.completedwith the oldcomputer_id.AGENT_RUNTIME_CONFLICT.enrollment.completedwith the oldcomputer_id. The orphan named in the 0.1.3 config isremovedinlocal_computers. The Computer comes online and the Agents answer.config.jsonhasdaemonId).daemon_id. On relaunch, the desktop log shows noenrollment.renew_failedand no repeated renewal.runner.hello.daemon_identity_in_use, and the daemon log shows close 1008daemon_identity_in_use:rather than 1011.🤖 Generated with Claude Code