Skip to content

feat: environment cluster behind one main host - #1

Draft
andrebrait wants to merge 389 commits into
mainfrom
feat/environment-cluster
Draft

andrebrait wants to merge 389 commits into
mainfrom
feat/environment-cluster

Conversation

@andrebrait

@andrebrait andrebrait commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

Proposal tracked in Ideas discussion pingdotgg#38571. This draft PR lives on the fork to hold review rounds; it is not aimed at upstream.

Problem

T3 Code can link environments one to one, but there is no way to group several machines behind one main host so that every client that connects to that host reaches all of them, and agents on any machine can reach the others.

What this adds

  • Cluster role. A main host plus members (Settings → Labs, then Settings → Environments → Cluster on web, desktop and mobile; t3 cluster join|add|remove|leave on the CLI).
  • Proxy. The main host proxies HTTP and WebSocket at /cluster/<memberId>/*, so clients connected only to the main host see every member as an environment, including Settings, threads and the Device panel.
  • Joining, dial-in only.
    • HTTPS join string <url>#<code>[.<sha256 pin>]; the main host accepts a pin match or a CA-valid chain.
    • SSH: the main host signs in once (ssh config/agent, password, or key file + passphrase), installs a dedicated cluster key in the member's authorized_keys, and removes it on Remove.
    • Host keys are verified like ssh: an unknown or changed key needs explicit trust of its fingerprint.
  • HTTPS by default. Self-signed HTTPS on the same port via first-byte sniff. A "plain HTTP on the network" setting allows or redirects plain HTTP; loopback and Tailscale are exempt.
  • Member to main link. An SSE doorbell plus take-once request/reply, so concurrent calls never share one sequential socket.
  • Agents. Calls to other members go through the existing MCP forwarding seam via the main host.
  • Isolation. Clusters are separate from peer links: members refuse peer links and non-loopback sessions other than the cluster link.
  • Load balancing per cluster. The machine picker offers " (load balanced)" for each cluster, next to each of its machines, with a cluster icon. Machines are weighted per client (Prefer, Normal, Less often, Manual only); cluster machines default to Normal. A separate "Balance across all machines" switch balances across clusters and standalone machines too.
  • Fewer machines. When some machines lack the project, the balanced entry shows a warning naming them, and the first send asks before balancing across fewer machines (with "Don't ask again" per project, reset in the load-balancing settings).
  • Start on a machine without the project. Choosing a machine marked "clones the project" clones it from its remote to the same path under that machine's home. "Add to another machine" defaults to the source path too.
  • Mobile. Cluster management in Settings → Environments, members lit by this device's connection to them, and pull request routing that follows the main host.

Also changed outside clusters

These reach users who never set up a cluster:

  • Load balancing on mobile. Mobile had no load balancing before (upstream discussion Mobile load balancing controls pingdotgg/t3code#40014). It now has the balanced entries in the new-thread machine picker, per-machine weights in Settings → Environments, the fewer-machines warning and confirmation, and drafts that keep their balanced choice or hand-picked machine across reloads. Tested on Android; iOS shares the code but is not built or tested yet.
  • Machine picker order. Machines are grouped: the connected host's cluster first (main host, then members), other clusters by name, then standalone machines. Machines that have the project come before ones that would clone it.
  • Load-balancing settings grouped. One group per cluster, then "Other machines" with the "Balance across all machines" switch (hidden when one cluster holds every machine).
  • A pool with one candidate goes straight to it, without a resource check, as sends did before load balancing.
  • Add to another machine keeps the path. It defaults to the project's path relative to the home folder (for example ~/git/project) instead of the target's default folder; a project outside the home folder falls back to the default folder. The server config now reports its home directory for this.
  • Network HTTPS. Servers answer HTTPS (self-signed) and HTTP on the same port. A Redirect network HTTP to HTTPS setting (web and mobile) sends browsers to HTTPS and refuses other plain HTTP; loopback and Tailscale peers are exempt.
  • t3 pair --url <address> puts the address you give in the printed pairing link.

Screenshots

Taken from a live three-machine cluster (ai-dev main host, ai-worker-2 and ai-worker-3 members).

Web

Picker in a project every machine has Picker in a project only the main host has
Cluster members and per-cluster load balancing
Add a member by join code Add a member over SSH

Desktop

Picker with a cluster and a standalone machine Load balancing: cluster and other machines

Mobile (Android)

Cluster in Environments Load balancing Picker Fewer machines

Verified

  • Web: two servers joined over pinned HTTPS; member online/offline; Remove; member Settings → Devices and Device panel streaming an Android emulator through the proxy.
  • Android emulator: Cluster section, add/join sheets, PR routing for members.
  • Docker SSH end to end: unknown host trust plus password, changed key replace, passphrase key, key revoked on Remove.
  • Live three-machine cluster on Linux, desktop (macOS) and Android: per-cluster balancing, the fewer-machines warning and confirmation with "Don't ask again", clone to a machine without the project, and reopened drafts keeping their machine.

@andrebrait

andrebrait commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner Author

Review round 1: Simplification

Scope: 8cf97b5f06..9e9dc7a337 (whole PR). Tool: code-simplification (report only).

# Severity Location Finding Verdict
1 Low apps/server/src/cli/cluster.ts:39, apps/server/src/server.ts The ClusterService layer stack (upstream, SSH manager, password prompt, cluster key) is assembled twice. One exported live layer would serve both. Rejected: two call sites with different extras (the CLI adds FetchHttpClient and settings); a shared export would save a few lines and add an indirection.
2 Low apps/server/src/cluster/ClusterSshKey.ts:351 resolveSshCliRunner copies the desktop's resolveDesktopSshCliRunner, but honours T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH in any build, while the desktop does so only in development. Rejected: setting T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH is an explicit operator choice that the dev runner and ssh end-to-end tests rely on; merging with the desktop helper is a cross-app refactor outside this PR.
3 Low packages/client-runtime/src/connection/registry.ts:575 The same "platform or cluster member" check repeats at four sites. Rejected: four one-line checks; no behaviour risk, not worth the churn here.
4 Low apps/server/src/cluster/ClusterUpstream.ts:89 SSH target parsing, its invalid_target text, and the SSH error fallback are copied in ClusterUpstream (twice) and ClusterSshKey. Rejected: short copies with no behaviour difference; not worth the churn here.
5 Low apps/server/src/mcp/McpHttpServer.ts:337 /mcp reads the cluster role (up to two SQL selects) twice per request for linked clients. Fixed in d28a998
6 Low apps/server/src/cluster/ClusterService.ts:628 addMember is ~120 lines: nested ternary for target resolution, formatClusterSshTarget computed three times. Rejected: the race and cleanup tests cover it and this round already changed its error path (89e297c); a restructure now adds risk without a behaviour gain.
7 Low apps/server/src/peer/PeerForwarding.ts:391 "Current members" is read with the same Stream.runHead pattern at three sites. Rejected: three reads of an existing stream; the CLI site now uses storedMembers (b347b8b), leaving two.
8 Low apps/server/src/peer/PeerForwarding.ts:140 ClusterService, ClusterRole and ClusterHosts are optional services only so tests can omit them, which costs double guards and Option handling. Rejected: ClusterRole is optional so in-process MCP hosts without a database work (comment at McpHttpServer.ts:290); the others follow the same pattern.
9 Low apps/server/src/cluster/ClusterService.ts:150 Pin-mismatch to "certificate changed" mapping exists three times. Rejected: three short mappings with different fallbacks per call site; no behaviour difference.
10 Low apps/server/src/tls/ServerTls.ts:56 Re-implements normalizeCertificateFingerprint; isLoopbackClient strips ::ffff: that normalizeIpAddress already strips; plainHttpPolicy casts for the socket where NodeHttpServerRequest.toIncomingMessage exists. Fixed in d28a998 (normalizeCertificateFingerprint). The ::ffff: strip and the socket cast are kept: removing them changes no behaviour.
11 Low apps/web/src/state/cluster.ts:14 Cluster-host predicate copied in web, mobile and client-runtime; host-key error predicate copied in CLI and web; mobile filters cluster members at four call sites. Rejected: cross-surface consolidation of small predicates; no behaviour risk, not worth the churn here.
12 Low apps/server/src/cluster/ClusterService.ts:376 The same is_main_host refusal text is written twice. Fixed in d28a998
13 Low apps/server/src/peer/PeerMcpClient.ts:330 Two identical error handlers. Fixed in d28a998
14 Low packages/ssh/src/tunnel.ts:1226 identityFile spreads extend an existing four-way copy of the auth-option spreads. Rejected: extends an existing pattern in tunnel.ts; consolidating it is a refactor of pre-existing code.
15 Low apps/server/src/cli/cluster.ts:80 CLI invite JSON renames code to credential through a bespoke schema. Rejected: a cosmetic JSON field name; no behaviour risk.
16 Low packages/contracts/src/cluster.ts:43 ClusterStatus.fingerprint and the joinedAt fields are read by no client, only CLI list --json. Rejected: kept on purpose for t3 cluster list --json.
17 Low apps/server/src/cluster/ClusterHostKey.test.ts:89 Tests that break the repo's test rules: constant-table mirror, 3-line Option.filter, presentation and copy-text cases, a one-liner URL helper. Rejected for this round: deleting cheap tests carries no behaviour risk either way; revisit if a maintainer asks.
18 Low packages/client-runtime/src/connection/layer.ts:96 watchClusterMembers computes the cluster host twice per emission. Rejected: cheap per emission; changing it risks the publish ordering the comment protects.
19 Low packages/client-runtime/src/connection/routes.ts Small dead or duplicated paths: unreachable label branch, duplicated loginOptions branches, hand-rolled uint32/concat, status reads the membership row twice. Rejected: each is a few lines with no behaviour difference.

Not checked: full render bodies of ClusterSettings.tsx and ClusterSection.tsx; case-by-case overlap inside the large test files; ClusterService.testkit.ts; diffs to McpOAuth, PeerLinks, RemoteDelegation, desktop, devProxy and preview; i18n, docs, evals and dependency choices. No suggestion was compiled or tested.

@andrebrait

andrebrait commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner Author

Review round 1: Adversarial

Scope: 8cf97b5f06..9e9dc7a337 (whole PR). Tool: adversarial-review.

# Severity Location Finding Verdict
1 High apps/server/src/proxyHeaders.ts:35 The shared response-header filter drops content-security-policy. Members serve agent-written HTML and SVG with a sandbox CSP; through /cluster/<id>/… that HTML would run same-origin on the main host with the user's session. The same filter now also strips CSP from DeviceHubProxy responses. Fixed in 631baa2 (test: DeviceHubProxy "sends requests a host routes itself to its upstream" asserts the CSP survives the shared filter)
2 Medium apps/server/src/cluster/ClusterProxy.ts:108 No test pins the percent-decoding in the main-host-only path guard: removing decodeURIComponent survives the suite, while the member's router decodes /%61pi/cluster/events to /api/cluster/events. Fixed in 04f759a (rows /%61pi/cluster/events, /%61pi/cluster/leave, /%6dcp)
3 Medium apps/server/src/cluster/ClusterService.ts:687 A join the member commits but the main host then fails (10 s timeout, lost response, secret or insert failure) is never undone. The member keeps a membership to a host with no row, and remote pairing is refused there until someone runs t3 cluster leave locally. Fixed in 89e297c for every failure after the member answers (test: removal test, insert refused by a trigger). A lost join response leaves no token to undo with; re-adding from the same host or t3 cluster leave on the member recovers it.
4 Low apps/server/src/mcp/ClusterHostRequests.ts:44 The main host serves a member's agent calls with full access; the member supplies its own limits. Matches the symmetric-trust design; recorded so the boundary is explicit. Rejected: intended. Trust inside a cluster is symmetric, as agreed in the design and documented.
5 Low apps/server/src/cluster/ClusterProxy.ts:122 An unauthenticated descriptor request can make the main host spawn ssh for an SSH member with no cached origin. Fixed in 92b4189 (test: "answers 502 for a member that stopped answering")
6 Low apps/server/src/cluster/ClusterService.ts:424 The member's session sweep runs only at join and at startup; a session created later via the startup pairing link survives until restart. Rejected: the startup pairing link is printed only on the member's own console; whoever holds it already has local access, which a member trusts.
7 Low apps/server/src/cluster/ClusterSshKey.ts:34 The authorize script rewrites authorized_keys in place (cat "$t" > "$f"), so a failed write leaves it truncated; a custom AuthorizedKeysFile is ignored. Rejected: the temp file is fully written in the same directory first, so a full disk fails that write and the && chain stops before authorized_keys is touched. Using ~/.ssh/authorized_keys matches ssh-copy-id's default.
8 Low apps/server/src/peer/PeerForwarding.ts On a member, routeLabel reports every environment as reachable, so RemoteDelegation's unreachable check never fires there. Rejected: on a member every call goes to the main host, which refuses an unknown environment with capability_denied, so the agent still gets a clear answer.
9 Low apps/server/src/cluster/ClusterProxy.ts:230 Any upstream 401 is reported as cluster_member_revoked, including a route that legitimately answers 401. Rejected: the proxy authenticates the client itself and sends only the cluster-host bearer upstream, so a member's 401 means that bearer was refused.

Mutations: 10 run, 9 caught; the decode guard (finding 2) survived.

Not checked: client-runtime registry races; web and mobile UI behaviour; whether T3 Connect sets X-Forwarded-For (affects which sessions count as loopback); a live SSH run of the authorized_keys write path; hostnames with shell metacharacters reaching a user ProxyCommand %h; a live run of the orphan-join scenario.

@andrebrait

andrebrait commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner Author

Review round 1: Code review

Scope: 8cf97b5f06..9e9dc7a337 (whole PR). Tool: /code-review (high).

# Severity Location Finding Verdict
1 Medium apps/server/scripts/migrate-dev-db.ts:213 cluster_members and cluster_membership are not in CLEARED_TABLES, so a dev database seeded from a real install keeps its cluster state: a member-seeded dev server revokes sessions and refuses pairing; a main-seeded one with copied secrets dials real members. Fixed in 95b9d2e (test: migrate-dev-db "keeps stopped and settled thread families and clears pending work")
2 Medium apps/server/src/cluster/ClusterService.ts:1123 The startup repair runs whenever the layer is built, and every t3 cluster CLI command builds it. On a member, t3 cluster list revokes the invite just minted and the server's startup pairing link. Fixed in 7d44e9b (test: "a member that stopped between joining and revoking finishes on start" now asserts building the service revokes nothing)
3 Medium apps/server/src/cli/cluster.ts:403 With the Labs flag off, t3 cluster list on a main host prints "Standalone… no members", hiding the ids t3 cluster remove needs. Fixed in b347b8b (test: cluster flag-off case asserts storedMembers)
4 Medium apps/server/src/cluster/ClusterProxy.ts:122 Unauthenticated descriptor requests can start SSH work against a member with no cached origin (same as adversarial 5); 404 vs 502 also reveals which member ids exist. Fixed in 92b4189. The id oracle is rejected: member ids are environment UUIDs, not secrets.
5 Low apps/server/src/cluster/ClusterService.ts:716 Re-adding a member ignores a new label (ON CONFLICT does not set label). Fixed in 6ac13e6 (test: "re-adding a member at a new address…")
6 Low apps/server/src/cluster/ClusterService.ts:731 Re-adding a member at a different SSH target revokes the old key but leaves the old tunnel open. Fixed in 6ac13e6 (test: ssh member test asserts the old tunnel is closed)
7 Low apps/server/src/cluster/ClusterProxy.ts:158 A session with no scopes makes encodeOAuthScope throw: 500 instead of 403. Rejected: a session cannot have no scopes. Issuing a pairing credential with scopes: [] fails with ServerAuthScopeNotGrantedError (tried in the proxy test).
8 Low apps/server/src/mcp/McpHttpServer.ts:339 /mcp reads the cluster role twice per linked request (same as simplification 5). Fixed in d28a998
9 Low apps/server/src/cluster/ClusterService.ts:1065 Effect.fnUntraced without the reason AGENTS.md asks for (also client-runtime/connection/layer.ts:93). Fixed in d28a998

Not checked: web and mobile UI code paths in depth; i18n; docs.

@andrebrait

Copy link
Copy Markdown
Owner Author

Review round 1 closed. It reviewed head 9e9dc7a, and the fixes landed at d28a998. The stop rule does not hold yet. This round found correctness and security defects (one High, five Medium), and the fixes change production logic. Round 2 is therefore due: the code-review pass only, scoped to 9e9dc7a337..d28a998abc.

@andrebrait

Copy link
Copy Markdown
Owner Author

Three-server run (head d28a998)

Server A is the main host on 127.0.0.1:13901. Members B (:13902) and C (:13903) joined over HTTPS with t3 cluster invite / t3 cluster add. Only A has the Labs flag on.

$ t3 cluster list   # on A
Box B	5c9e68ff-…	https	https://127.0.0.1:13902	online
Box C	8e6776ca-…	https	https://127.0.0.1:13903	online

A real agent on B (t3 thread start --provider claudeAgent --model claude-haiku-5-5) was told to reach C through T3 MCP tools only:

  1. t3_environment_links on B lists A (main-host, online) and C (member, online), and leaves out B itself.
  2. t3_project_list with C's environmentId returns C's project.
  3. delegate_task to C ran a child agent on C, which answered with C's working directory (…/c3/c/work). The child thread lives on C.

The first delegate_task call returned target_required. B's project is a git repository with no remote, so nothing on C matched it. Passing target.projectId fixed it. Linked environments behave the same way, so this is not specific to clusters.

Automated coverage of the same route already exists in PeerForwarding.test.ts ("a member reaches another member through the main host, which never loops"), with the control link mocked. This run adds the real control link, TLS pinning and provider sessions.

@andrebrait

Copy link
Copy Markdown
Owner Author

Review round 2: code review (/code-review high, 9e9dc7a337..d28a998abc)

# Finding Severity Verdict
1 ClusterProxy.test.ts:312: the anonymous-descriptor 502 is said to race with the control link coming up important Rejected. serveMain never calls cluster.start, so no link runs in that test and the member stays offline. The assertion is deterministic.
2 ClusterService.ts: a failed re-add tells the member to leave but keeps the main host's old row, whose token the new join had already revoked important Fixed in f0d106b. The undo now also drops the stored row, its secret and its old ssh key. The removal test failed first (member count stayed 1).
3 ClusterService.ts: startup repair in start could run after the HTTP server starts serving important Rejected. start runs inside layerMakeRoutes, which HttpRouter.serve builds before it listens. The repair is awaited, and only the link supervision is forked.
4 ClusterProxy.ts: the descriptor gate also answers 502 for https members until their link is up nit Rejected. After a restart the 502 lasts only until the link reconnects, and the client retries. A gate that depends on the transport is extra code with no safety gain.
5 ClusterService.ts: a lost join answer leaves no token to undo with, so the comment overclaims pre_existing Comment narrowed. This is the known gap from round 1. Recovery: re-add the member, or run t3 cluster leave on it.
6 ClusterProxy.ts: each anonymous descriptor request opens a settings subscription nit Rejected. That cost is negligible next to the upstream HTTP hop the same request makes, and the stream keeps the 403 for a disabled cluster.
7 ClusterProxy.ts: the status can lag a dropped tunnel, so "never starts ssh" overclaims nit Comment softened ("cannot keep starting ssh").

Checks: typecheck, lint, format and knip pass. The cluster tests pass (52). check:changed shows only the same 5 environment-only failures as round 1.

Round 2 closed at f0d106b. It found one correctness defect (pingdotgg#2), and the fix changes production logic, so the stop rule does not hold: a code-review-only round 3 (the last allowed) is due on d28a998abc..f0d106b115.

@andrebrait

Copy link
Copy Markdown
Owner Author

Review round 3: code review (/code-review high, d28a998abc..f0d106b115, the round-2 fix only)

# Finding Severity Verdict
1 The stored row was looked up after the id-mismatch check and role.current, so a failure in either one, which comes after the member already rotated its token, still left the dead row important Fixed in 4f96020. The lookup now runs right after the join answer. No new test: making role.current fail, or making a member answer under two ids, would need a fake built only for this. The change only moves the lookup earlier.
2 Dropping the row on a failed re-add loses a custom label nit Rejected. The row's token is dead and the member has left, so a row kept only for its label is the inconsistent state this fix removes. A re-add needs a new invite anyway, and --label sets the label again.
3 The old target's key was revoked even when deleting the row failed nit Fixed. The revoke runs only after the row is gone, so a row that survives keeps a working key for t3 cluster remove.
4 The branch that revokes the old ssh target's key on a failed move is untested nit Fixed. The ssh member test now covers a failed move from me@box9 to me@box3: both keys are revoked and no member remains. Removing that revoke makes the test fail (checked).
5 Effect.suspend(() => reload) is redundant nit Fixed. reload is defined above dropRow.
6 A lost join answer on a re-add leaves the stored row with a dead token pre_existing Rejected for this PR. This is the known gap from rounds 1 and 2. Recovery is the same: re-add, or run t3 cluster leave on the member.

Checks: typecheck, lint, format and knip pass. The cluster tests pass (52). check:changed shows only the same 5 environment-only failures as before.

Round 3 closed at 4f96020. This is the last round the policy allows (3 of 3), so no further review round runs on this PR.

@andrebrait
andrebrait force-pushed the feat/environment-cluster branch 2 times, most recently from 198747f to 0461ec8 Compare November 20, 2026 15:40
@andrebrait

Copy link
Copy Markdown
Owner Author

Review round 2 (full): adversarial

Scope: e24f0c7154..adfd185908 (whole change; the base is upstream main, which the branch is rebased on, because this PR's base branch lags it). Tool: adversarial-review.

# Severity Location Finding Verdict
1 High apps/server/src/auth/EnvironmentAuth.ts (capClusterHostScopes), apps/server/src/cluster/ClusterProxy.ts:39 A proxied request kept the cluster-host session's access:write, so any paired client of the host could, on a member, mint a join code and re-join the member to itself, create pairing links, manage sessions, or approve MCP clients via /cluster/<id>/oauth/mcp/*, gaining access that outlives revocation on the host. Fixed in 45c5dfc: capped requests never carry access:write, and /oauth/mcp is main-host-only (tests: "caps a cluster-host request to the forwarded scopes, failing closed", "forwards HTTP to the member under the client's scopes…")
2 High packages/client-runtime/src/connection/registry.ts (removeClusterMemberLocked) Drafts and the mobile outbox of every member were deleted whenever the host's member list went empty, including the reversible cases (cluster flag off, host disabled). Fixed in 56c10e7: de-listing keeps owned data (test: "drops a host's members when it stops listing them, is disabled, or is removed")
3 Medium apps/server/src/cluster/http.ts:51 The leave endpoint's subject check had no test. Fixed in dff4975 (test: "over HTTP, only its cluster host or a session that manages access makes a member leave"; red when the guard is mutated)
4 Medium apps/server/src/cluster/ClusterService.ts (keepOnlyHostAndLoopback) Revoking T3 Connect sessions on join had no test. Fixed in 1e62819 (test: "a member keeps only its cluster host and loopback sessions after joining"; red when mutated)
5 Medium apps/server/src/proxyHeaders.ts:25 Dropping the client's cookie and dpop before forwarding had no test. Fixed in 7dc3cf4 (test: "forwards bodies sent chunked or after 100-continue, never the client's credentials"; red when mutated)
6 Low apps/server/src/cluster/ClusterService.ts:416-421 The re-join host-id check compares a caller-supplied id. Rejected: after #1 only the member itself can mint a join code, so a code holder is legitimate and the check is a UX guard only.
7 Low apps/server/src/auth/PairingGrantStore.ts:538,554 The exactSubject guards on the desktop token and seeded grants had no test; without them a join attempt would spend those credentials. Fixed in e88b190 (tests: "matches a seeded desktop bootstrap credential exactly", "accepts rotating desktop bootstrap tokens…")
8 Low apps/server/src/cluster/ClusterUpstream.ts:112-117 A stale ssh loopback port could receive the member's bearer if a local process binds it. Rejected: it needs code running on the main host, which can already read the stored member secrets.
9 Low mcp/ClusterHostRequests.ts, peer/PeerForwarding.ts A compromised member reaches the whole cluster through the main host. Rejected: documented design ("a cluster member trusts only its main host"), not a defect.

Not checked: a full two-server WebSocket RPC run of #1 (proven at the service layer and by the permission map); peer/PeerForwarding.ts, PeerMcpClient.ts, packages/ssh/src/tunnel.ts, the web and mobile cluster UI, mobile new-task-flow-provider.tsx, DeviceHubProxy.ts, i18n and most docs.

@andrebrait

Copy link
Copy Markdown
Owner Author

Review round 2 (full): code review

Scope: e24f0c7154..adfd185908 (whole change, against upstream main). Tool: /code-review.

# Severity Location Finding Verdict
1 Medium apps/server/src/cli/cluster.ts:395 t3 cluster leave ran in the CLI process; the running member's control link waits on an in-process PubSub, so the host kept the member online and open proxied sockets kept the old token. Fixed in dff4975: leave goes through the running server like t3 auth writes, and the endpoint accepts an access:write session (test: "over HTTP, only its cluster host or a session that manages access makes a member leave")
2 Medium apps/server/src/cluster/ClusterService.ts:438 Joining keeps sessions whose client address is loopback, such as an ssh-tunnelled desktop. Rejected: behind a reverse proxy the session records the forwarded client address (resolveClientIpAddress trusts X-Forwarded-For from a loopback peer), so those clients are signed out. Only ssh-tunnel clients stay, and they already hold shell access to the member; revoking them would also break T3's SSH connection mode.
3 Medium apps/server/src/cluster/http.ts:97 Any failure to authenticate the control link, including a transient database error, answered 401, which the main host records as revoked and which cuts every proxied connection. Fixed in d466e64: 401 only for credential errors, 503 otherwise (test: "the control link answers 503, not 401, when a member cannot check the credential")
4 Low apps/server/src/cluster/ClusterProxy.ts:172 A session read error ends a proxied connection at once, and proxied sockets skip markConnected. Rejected: ws.ts also ends the socket on that error (only with an error status), and the client's own /ws to the host is what the connected-clients list tracks.
5 Low apps/web/src/components/chat/useDraftEnvironmentRouting.ts:425 A confirmed clone stays on the machine if the user then switches machines; triage is prepared before the clone confirm. Rejected: the user explicitly confirmed that clone, so keeping it is correct; the triage work is wasted only, with no visible effect.
6 Low apps/server/src/peer/PeerForwarding.ts:213 A member's 403 on /mcp told agents the member has clusters turned off, which members never check. Fixed in 6225dcb (wording; no eval covers this text)
7 Low apps/server/src/mcp/McpHttpServer.ts:297 Each /mcp request reads the cluster role from SQLite. Rejected: two small indexed reads beside the session lookup every request already makes; an in-memory cache would go stale when t3 cluster writes from another process.

Not checked: the web ClusterSettings.tsx and mobile ClusterSection.tsx UI; test files in depth; tlsSniff across Node versions.

@andrebrait

Copy link
Copy Markdown
Owner Author

Review round 2 (full): simplification

Scope: e24f0c7154..adfd185908 (whole change, production code, against upstream main). Tool: code-simplification.

# Severity Location Finding Verdict
M1 Medium contracts cluster.ts, rpc.ts; ClusterService.ts; client-runtime state/cluster.ts; CLI The invite→join-code rename stopped at the UI, so "join" meant both minting and spending a code, and joinString (now a URL) reached the CLI JSON. Fixed in 5277657: cluster.createJoinCode, ClusterJoinCode, joinUrl, canJoin, defaultClusterJoinAddress; CLI --json prints code and joinUrl
M2 Medium packages/client-runtime/src/connection/resolver.ts:289 The resolver silently tolerated a missing ClusterHosts service, which would leave members waiting forever. Fixed in 2d227fb
M3 Medium packages/client-runtime/src/connection/pullRequestRoutingPermissions.ts:50-97 A cluster member had two routing keys, so a future set on a member would store a key get never matches. Fixed in 899ef74: the member's key is the main host's
L1–L4 Low web/mobile state/cluster.ts, ClusterSettings.tsx, ClusterSection.tsx, new-task-flow-provider.tsx, cli/cluster.ts Logic duplicated between web and mobile (cluster host hook, join URL paste split, clone question, host-key error check). Deferred: cleanups with no bug behind them; they move to client-runtime in a follow-up.
L5 Low apps/web/src/components/chat/composerSend.logic.ts:53 loadBalancingCandidateIds outlived the clone-at-send design. Rejected: it is the unit the "picks only machines that already have the project" test covers.
L6, L7, L9, L10, L11, L12, L14, L16, L17 Low see the commit One-caller return shape, duplicated checks, dead branches, a repeated ssh ensureEnvironment, a repeated format call, a duplicate SHA-256 regex, a repeated computation, unreachable fallbacks, stale comments. Fixed in 96ec52e (L10 extends "starts an ssh member's server once…"; connectRow's fallback kept, as removing it would not stay simple)
L8 Low apps/web/src/lib/addProjectToMachine.ts:221 One-caller wrapper. Rejected: it names the cluster case at the call site; inlining saves nothing.
L13 Low apps/server/src/cluster/ClusterService.ts:364 status reads the membership row twice. Deferred with L1–L4.
L15 Low ClusterService.ts:364,514 Effect.gen with a span instead of Effect.fn. Rejected: both are zero-argument effects, which the convention allows.

Not checked: ClusterService.ts reconcile/link code past line 1000, ClusterSshKey.ts, ClusterHostKey.ts, pinnedTransport.ts, ClusterProxy.ts past line 110, the peer/MCP forwarding files, the TLS files, packages/ssh/*, the migration, tests, translations and docs.

Round 2 head: adfd185908cf02732f63909db4f758cbcf8fb35a; fixes pushed up to 96ec52e68c. Rounds used: 1 of 3 after the first full review (the one extra full round for a major change is now spent). A light round is due on the fix push, since it changes production logic.

@andrebrait
andrebrait force-pushed the feat/environment-cluster branch from 96ec52e to 5387173 Compare November 20, 2026 19:37
@andrebrait

Copy link
Copy Markdown
Owner Author

Review round 3 (light): code review

Scope: adfd185908..5387173569 (since the last reviewed head). After the rebase onto 6cbda0cd0a, git range-diff shows the PR's earlier commits unchanged except the reconcile commit (its agentContextBudget.json conflict only), so the reviewed change is the round-2 fix push plus the budget commit: 420a4fdbf0..5387173569. Tool: /code-review.

# Severity Location Finding Verdict
1 Medium packages/client-runtime/src/connection/registry.ts:910 Keeping a de-listed member's drafts and outbox meant they were never cleared at all, since a member can't be removed on its own, not even when its main host is removed. Fixed in 93f9810: removing a main host clears its members' drafts and outbox; de-listing and disabling still keep them (test: "drops a host's members when it stops listing them, is disabled, or is removed"). A member a main host drops with t3 cluster remove keeps its data until its host is removed: the client can't tell that from a reversible de-listing.
2 Medium apps/server/src/auth/EnvironmentAuth.ts:751 Dropping access:write for proxied requests also stops guest-sharing a member's thread through the main host. Rejected: a guest share mints a credential on the member that reaches the thread without the main host, which is exactly what round 2's takeover fix closes. Guest-sharing still works on the member itself.
3 Low apps/server/src/cluster/http.ts:53 A proxied client authenticates as the cluster host, so only the proxy's path block kept it from /api/cluster/leave; the comment claimed the scope check did. Fixed in f0ba0e5: the endpoint refuses any request carrying the forwarded scopes header (test: "over HTTP, only its cluster host or a session that manages access makes a member leave")
4 Low packages/client-runtime/src/connection/pullRequestRoutingPermissions.ts:157 A permission set on a member was stored under the member's id with the host's key, so it could shadow the host's own setting. Fixed in bffa587: a member's permission is stored as its main host's, in the shared service and in web storage (test: "persists explicit GitHub trust and forgets it when a connection is removed")
5 Low docs/internals/environment-auth.md:147 The doc still said the scopes header only narrows and that the proxy refuses only /api/cluster. Fixed in 6c476ea

Not checked: whether ensureEnvironment with issuePairingToken returns the same tunnel that ClusterUpstream now caches in sshOrigins; t3 cluster leave through a server bound only to a LAN address (a limit shared by every changeState command).

Round 3 head: 53871735691c5f11e503f8b76248c6e16e5f1c89; fixes pushed up to 6c476ea7f5. Rounds used: 2 of 3 after the first full review. The fix push changes production logic, so one light round remains available for it; after that only a High finding or your request opens another.

@andrebrait

Copy link
Copy Markdown
Owner Author

Review round 4 (light): code review

Scope: 5387173569..6c476ea7f5 (since the last reviewed head: the round-3 fix push). Tool: /code-review.

# Severity Location Finding Verdict
1 Medium packages/client-runtime/src/connection/registry.ts:1010 Removing a main host that was disabled, or offline since the app started, does not clear its members' drafts, because the member list is in memory. Rejected: covering it needs a new persisted host-to-member map. What is left behind is inert local data that only resurfaces if a host lists that member again, where it is useful; nothing is lost or exposed.
2 Medium packages/client-runtime/src/connection/pullRequestRoutingPermissions.ts:169 A permission saved on a member by an earlier build could keep routing on after the host is turned off. Rejected: earlier builds stored a member under the key ["ClusterConnectionTarget", hostKey, memberId], and lookups match on the key, so those records match nothing now.
3 Medium packages/client-runtime/src/connection/pullRequestRoutingPermissions.ts:167 Setting a member's routing wrote the member's cached host key, which goes stale when the host's address changes, and could overwrite the host's own setting. Fixed in 381d130, more simply than proposed: setting a cluster member is refused, since members only follow their host and no UI offers it (tests: "persists explicit GitHub trust and forgets it when a connection is removed", "revokes across runtimes before storage events and resists stale catalog writes")
4 Medium packages/client-runtime/src/connection/registry.ts:1038 A member's drafts can be written again right after the host-removal clear, before the member is torn down. Rejected: the same inert leftover as #1, and only in a narrow window while the user is removing the host.
5 Low apps/web/src/connection/storage.ts:711 The web storage version of the member rule had no test. Fixed in 381d130 (test: "revokes across runtimes before storage events and resists stale catalog writes")

Not checked: the rest of the branch beyond this range.

Round 4 head: 6c476ea7f5dcceeba029ef8dbd849ab4af55240b; fixes pushed up to 381d130498. Rounds used: 3 of 3 after the first full review, so the limit is reached: only a High finding or the user's request opens another round.

@andrebrait

Copy link
Copy Markdown
Owner Author

Review round 5 (light): code review

Scope: 381d130498..c16b104a3a (since the last reviewed head: mobile load balancing). The review limit was already reached; this round was run at the user's request. Tool: /code-review.

# Severity Location Finding Verdict
1 Medium apps/mobile/src/features/threads/new-task-flow-provider.tsx:1069 Moving a draft under Auto carried the branch auto-filled from the source machine's checkout, so the target could switch its checkout to, or fail on, a branch it doesn't have. Fixed in 64ab0af: the move carries only the draft content and a pull request checkout; the target resolves its own workspace defaults.
2 Medium apps/mobile/src/features/threads/new-task-flow-provider.tsx:1024 Choosing a branch didn't keep the draft on its machine, unlike web and the user docs. Fixed in 64ab0af: choosing a branch, or arriving with a checked-out branch, pins the machine; changing workspace mode doesn't, matching web.
3 Medium apps/mobile/src/features/threads/new-task-flow-provider.tsx:1014 Auto counted machines whose project only shared a folder name or title, so it could start the thread in an unrelated repository. Fixed in 64ab0af: Auto counts only isSameRepository matches; weak matches stay available for manual selection.
4 Medium apps/mobile/src/features/threads/NewTaskDraftScreen.tsx:741 Auto moved the draft before send validation, so a rejected send left the draft moved and stripped. Fixed in 64ab0af, by a different design: mobile resolves the machine when the draft opens or a balanced choice is made, as web does, so a send always validates on an already-resolved machine.
5 Medium apps/mobile/src/features/threads/NewTaskDraftScreen.tsx:757 The send waited for a render on the target with no exit, so it could hang and leave the composer stuck. Fixed in 64ab0af: the wait, its ref and the layout effect are gone (same design as pingdotgg#4).
6 Low apps/mobile/src/features/threads/NewTaskDraftScreen.tsx:745 Every failed pick said "no eligible machine has available resources", whatever the cause. Fixed in 70970bb and 64ab0af: loadBalancingSendWarning moved to client-runtime and is shared. Attached threads on linked machines stay strict on both web and mobile, as before.
7 Low apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx:217 Choosing Auto while a worktree pinned the draft did nothing. Fixed in 64ab0af: a balanced choice clears the pin and resolves again.
8 Low docs/user/remote-access.md:206 The user docs still said mobile has no load balancing. Fixed in 64ab0af.

Not checked: the follow-up commits' new features (per-cluster balancing in 64ab0af, clone path in adbd3db) beyond the fixes listed here; no device or browser run.

Round 5 head: c16b104a3a8a72416c2f25861e4e72fe4857b602; fixes pushed up to 64ab0af110. The limit is passed; any further round needs a High finding or the user's request.

juliusmarminge and others added 13 commits November 20, 2026 20:26
…tgg#24888)

Co-authored-by: Julius Marminge <julius0216@outlook.com>
…s current (pingdotgg#36868)

Co-authored-by: Julius Marminge <julius0216@outlook.com>
…checkout (pingdotgg#37191)

Co-authored-by: Julius Marminge <julius0216@outlook.com>
… errors (pingdotgg#40042)

Co-authored-by: Julius Marminge <julius0216@outlook.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Marve10s and others added 29 commits November 22, 2026 04:28
…h the agent (pingdotgg#40777)

Co-authored-by: Julius Marminge <julius0216@outlook.com>
…0816)

Co-authored-by: Julius Marminge <julius0216@outlook.com>
…ingdotgg#29438)

Co-authored-by: maria-rcks <maria@kuuro.net>
Co-authored-by: Julius Marminge <julius0216@outlook.com>
…usage frames (pingdotgg#40804)

Co-authored-by: lvning.liu <lvning.liu@weimob.com>
Co-authored-by: Julius Marminge <julius0216@outlook.com>
…pingdotgg#40830)

Co-authored-by: lvning.liu <lvning.liu@weimob.com>
Co-authored-by: Julius Marminge <julius0216@outlook.com>
…ad of stepping through stale states (pingdotgg#27401)

Co-authored-by: maria-rcks <maria@kuuro.net>
Co-authored-by: Julius Marminge <julius0216@outlook.com>
pingdotgg#40841)

Co-authored-by: Julius Marminge <julius0216@outlook.com>
pingdotgg#27391)

Co-authored-by: Enmani <43571965+Enmani@users.noreply.github.com>
Co-authored-by: Julius Marminge <julius0216@outlook.com>
…on (pingdotgg#21667)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Co-authored-by: Julius Marminge <julius0216@outlook.com>
…gg#40874)

Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com>
Co-authored-by: Julius Marminge <julius0216@outlook.com>
…nder its full name (pingdotgg#40877)

Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com>
Co-authored-by: Julius Marminge <julius0216@outlook.com>
…l finds no match (pingdotgg#40886)

Co-authored-by: Julius Marminge <julius0216@outlook.com>
Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com>
Co-authored-by: Julius Marminge <julius0216@outlook.com>
…pers

Adds the cluster contracts (membership, join codes, host requests, the
cluster connection target), the cluster.* RPCs and their permission
scopes, ServerConfig.homeDirectory, and the client load-balancing
settings. packages/ssh and packages/shared gain what the main host needs
to add a member over SSH.
A main host accepts members by join code over HTTPS or by SSH, proxies
/cluster/<memberId>/ to them, and routes agents' cross-environment calls
through itself. Members accept only their main host and local apps. The
Cluster migration, CLI (t3 cluster join/add/remove/leave), TLS pinning
and the Cluster lab setting come with it.
… and cloning

Members appear in the connection catalog behind their main host. New
threads can balance across a cluster's machines or across all machines,
weighted per client, and a thread can start on a machine that lacks the
project by cloning it to the same path under that machine's home.
…gets

Settings -> Environments -> Cluster manages membership. The machine
picker offers "<main host> (load balanced)" per cluster, groups machines
by cluster, warns and asks when some machines lack the project, and
offers Don't ask again per project. Add to another machine keeps the
source path.
Mobile manages a cluster, shows members behind their main host, and
balances new threads per cluster or across machines with the same
weights, warnings and confirmation as web.
…e main host

Signed file links load in <img> and native image views, which send no
sign-in, so the cluster proxy answered them 401 before reaching the
member. The proxy now forwards GET and HEAD under /api/assets/ without
a client session, with an empty scope cap; the member checks the link's
signature as it does for direct clients, and only while its control
link is up.
@andrebrait
andrebrait force-pushed the feat/environment-cluster branch from fadbe4f to 591dfda Compare November 22, 2026 16:18
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.