fix(server): make remote updates rollback-safe (#5181)

This commit is contained in:
Theo Browne authored and GitHub committed 2026-08-01 05:48:03 -07:00
1 parent 0ad91b6e7f
commit d3037064e6
40 files changed
+2856 -2270

No files matched your search

+60 -112
View File
@@ -2,139 +2,87 @@
> For maintainers. Using T3 Code? See [docs/user](../user/).
T3 Code can update a connected server to the exact version of the client that detected version
drift. This path exists primarily for remote environments, where the user may not have a terminal
open on the server machine.
Remote server updates use one stable systemd launcher. Foreground CLI processes do not self-update,
and a running server never edits its systemd unit or durable service state.
The feature has three boundaries:
## Ownership
- the server advertises whether and how it can be replaced;
- the client chooses the matching user action;
- the server installs and verifies the replacement before handing off the process.
The service files under `<baseDir>/runtime` are:
## Detection and Presentation
- `service-launcher.mjs`, the stable process selected by systemd;
- `service-state.json`, the launcher's durable selection state;
- `versions/<version>`, immutable exact-version npm installs.
`ExecutionEnvironmentDescriptor` includes the server version and an optional
`capabilities.serverSelfUpdate` value. Progress-capable servers also advertise
`capabilities.serverSelfUpdateProgress`. The client compares the server version with `APP_VERSION`
after loading server config.
The launcher is the only runtime writer of `service-state.json`. `t3 service install` and
`t3 service update` may replace the launcher and state while the unit is stopped. Server children
only communicate with the launcher over their inherited IPC channel.
The optional capability is intentionally backward compatible. An older server does not know about
the field, so a missing value means the client must offer a manual relaunch instead of sending an
unknown RPC.
The state contains one active version and, at most, one update record:
The shared `ServerUpdateAction` is rendered in both user-facing version-drift surfaces:
- `pending A → B` selects B as a retryable trial;
- `committed A → B` selects B for ordinary restarts;
- `rolled-back A → B` or `failed A → B` selects A;
- invalid state fails closed so systemd cannot guess at a runtime.
- the conversation banner in `ChatView`;
- primary and saved environment rows in **Settings** → **Connections**.
Every write uses same-directory replacement plus file and directory fsync.
Both surfaces target the client's exact version. When the reconnected server reports that version,
the mismatch and action disappear.
## Remote Update
The operation state lives in `packages/client-runtime`, keyed by environment. Both web surfaces read
the same `downloading`, `installing`, or `resuming` state, so route changes do not own or cancel the
operation.
1. The active server installs `t3@<target>` into a unique staging directory.
2. The target runs `__service-preflight` against the active database in read-only mode.
3. The staging directory is renamed to its immutable version path only after preflight succeeds.
4. The active child sends `request-update`. The launcher validates the child and target, writes
pending state, generates the update ID, then replies `update-accepted`.
5. After a short response-flush grace period, the launcher stops the active child.
6. The launcher starts the target as a trial and gives it the pending update over IPC.
7. The trial acquires dependencies, binds HTTP, starts every long-running root fiber, and verifies
that each root is parked at the activation gate. It does not run migrations.
8. The trial sends `prepared`. The launcher durably commits B before replying `committed`.
9. The child opens the existing activation gate, accepts commands, and publishes lifecycle ready
with the terminal update outcome.
## Capability Selection
Post-commit startup does not call service `start`, `initialize`, `connect`, `load`, or `acquire`
operations. It only opens prepared gates and publishes prepared lifecycle state.
The server resolves its capability once at startup and publishes it in the environment descriptor.
The launcher serializes child exits, IPC messages, and timers. A trial must report prepared within
120 seconds. If the trial exits or times out before prepared, the launcher records rollback and
starts A. After commit, B is active and normal systemd restart policy applies.
| Advertised value | Process shape | Client behavior |
| ----------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `boot-service` | Linux server running under the T3-managed systemd user service | Call the update RPC; the service unit is replaced and restarted. |
| `respawn` | Published npm CLI running in the foreground on macOS or Linux | Call the update RPC; the process hands off to a detached replacement. |
| `desktop-managed` | Backend supervised by the desktop app | Tell the user to update the desktop app on the server machine. |
| absent | Older server, development checkout, Windows foreground process, or an unrecognized supervisor | Offer the exact manual relaunch command. |
## Migration Boundary
Desktop ownership takes precedence over process-shape detection. A desktop-managed backend must
never spawn a second CLI server beside the app-owned process. Likewise, a process launched by an
unrecognized systemd unit does not claim the foreground respawn path because its supervisor could
bring the old version back.
Remote update preflight requires exact equality between the database's applied `(id, name)` rows
and the target release's migration manifest. A target with a missing, additional, renamed, or
unknown migration is blocked. Remote updates never migrate or downgrade a database.
## Update Flow
This deliberately means any release containing a migration requires a local service update:
```mermaid
flowchart TD
A[Client detects different versions] --> B{Advertised update path}
B -->|desktop-managed| C[Update desktop app on server machine]
B -->|missing| D[Copy exact manual relaunch command]
B -->|boot-service or respawn| E{Progress capability}
E -->|present| F[server.updateServerWithProgress]
E -->|missing| G[server.updateServer fallback]
F --> H[Install exact t3 version in pinned runtime]
G --> H
H --> I[Run version preflight]
I -->|bad code or version| J[Remove candidate runtime and keep current server]
I -->|cannot run preflight| J2[Keep candidate and current server]
I -->|passes| K{Handoff method}
K -->|boot-service| L[Rewrite and restart T3 systemd unit]
K -->|respawn| M[Start delayed replacement and exit current process]
L --> N[Reconnect with fresh backoff]
M --> N
N --> O[Replacement publishes ready at target version]
```sh
npx t3@<version> service update
```
Both update RPCs require the environment's `orchestration:operate` authorization scope. Their
payload accepts only an exact npm version, including an exact prerelease version; dist-tags such as
`latest` and `nightly` are rejected. The unary `server.updateServer` method remains available so a
new client can still repair skew with an older server.
The local command stops the unit, selects the new launcher and exact runtime, then restarts the
service. Its normal server startup may run migrations.
The update service permits one update at a time. It installs `t3@<version>` under
`<baseDir>/runtime/versions/<version>` and writes an install-complete sentinel only after npm exits
successfully. Boot-service setup and self-update share the same process-wide installation lock, so
they cannot mutate a pinned runtime concurrently.
## Client Correlation
Before any restart, the current Node executable runs the replacement with `--version`. A failed
install, failed preflight, or wrong reported version leaves the current server running.
The update acknowledgement includes the launcher-generated update ID. After reconnecting, clients
wait for a lifecycle ready event carrying that same ID. `committed` completes the operation only
when the ready server is the target version. `rolled-back` and `failed` end it immediately with the
recorded reason. Older servers without an ID retain version-only reconnect behavior.
Candidate cleanup is narrower than "any failed preflight". The candidate runtime is removed only when
the preflight process actually completes and reports a bad exit code or the wrong version: that is
the case where a completed npm install produced an unusable tree, so retrying the same version must
perform a clean install rather than reuse it. If the preflight cannot run at all, for example a spawn
error or the `PREFLIGHT_TIMEOUT` elapsing, the update fails before reaching cleanup and the candidate
directory is left in place.
## Capability and Compatibility
## Host Service Lifecycle
The systemd user service is a host lifecycle concern, not a T3 Connect resource. The standalone
`t3 service install`, `uninstall`, `update`, and `status` commands own it. Install and update both
reconcile the unit through `BootService`; running `npx t3@latest service update` therefore pins and
activates the latest CLI release without requiring a connected client.
The `t3 connect` onboarding flow may offer service installation, but it calls the same reconciliation
operation as `t3 service install`. Connect logout only disables cloud access and clears its
authorization; it does not uninstall the host service.
## Process Handoff
For `boot-service`, the server atomically rewrites the T3-managed user unit to point at the verified
runtime and reloads systemd. It acknowledges the handoff, then restarts the unit after the same
short grace period used by foreground respawn. A rejected deferred restart restores the previous
unit and is logged by the still-running process.
For `respawn`, the server starts a detached, delayed replacement that replays the original CLI
arguments. It then acknowledges the request and schedules the current process to exit. The delays
give the acknowledgement time to cross direct or relayed connections before the socket closes.
Progress-capable servers emit `downloading` before installing the pinned runtime and `installing`
before preflight and handoff. A terminal stream event acknowledges that restart is scheduled. The
client then enters `resuming`, waits for the replacement lifecycle stream to publish `ready` with
the target version, and only then completes the operation. It watches for the intentional
disconnect's first backoff state and requests one fresh retry, which clears historical backoff debt
without adding a separate reconnect loop.
## Release Invariant
The exact client version must exist as the `t3` npm package before a client carrying that version is
published. The release workflow therefore makes the GitHub release depend on CLI publication, and
the hosted web deployment depends on that release. See [Release Checklist](../operations/release.md#server-self-update-release-invariant).
The existing additive RPC and lifecycle schemas remain compatible with older clients. New servers
advertise remote self-update only when they have valid launcher context and a live IPC channel.
Desktop-managed servers direct the user to update the desktop app. Other process shapes provide a
manual command; the old detached foreground respawn path no longer exists.
## Source Map
- Capability contract: `packages/contracts/src/environment.ts`
- Update RPC contract: `packages/contracts/src/server.ts` and `packages/contracts/src/rpc.ts`
- Capability detection and handoff: `apps/server/src/cloud/selfUpdate.ts`
- Host service commands: `apps/server/src/cli/service.ts`
- Pinned runtime installation: `apps/server/src/cloud/pinnedRuntime.ts`
- Client version comparison: `apps/web/src/versionSkew.ts`
- Shared update action: `apps/web/src/components/ServerUpdateAction.tsx`
- Launcher and state machine: `apps/server/src/serviceLauncher.ts`
- IPC and durable state types: `apps/server/src/cloud/serviceProtocol.ts`
- Child IPC adapter: `apps/server/src/cloud/serviceLauncherClient.ts`
- Staging and preflight: `apps/server/src/cloud/pinnedRuntime.ts` and `servicePreflight.ts`
- Service installation: `apps/server/src/cloud/bootService.ts`
- Activation boundary: `apps/server/src/serverRuntimeStartup.ts` and `serverActivation.ts`
- Client outcome correlation: `packages/client-runtime/src/state/server.ts`
+4 -2
View File
@@ -187,8 +187,10 @@ the **Update server** action targeting a package version that does not exist yet
For a release smoke test, confirm `npm view t3@<version> version` returns the expected version, then
connect the new client to a server on the previous version and verify that the update action
reconnects to the matching server. Test one automatic path and the manual or desktop-managed
guidance when those environments are available.
reconnects to the matching server. Use releases with identical migration manifests for the
automatic path. When the manifest changed, verify that the remote action stops before restart and
shows the exact local `npx t3@<version> service update` command. Also test the manual or
desktop-managed guidance when those environments are available.
## Desktop auto-update notes
+4
View File
@@ -31,6 +31,10 @@ npx t3@latest service uninstall
Updating restarts T3 Code briefly. Let active agent work and terminal commands finish first.
The systemd unit runs a small stable launcher. Exact T3 Code versions are installed separately, so
a failed remote candidate can return to the previous version without rewriting the unit. Releases
that change the database must be installed with the local `service update` command above.
## Using It with T3 Connect
T3 Connect may offer to install the service during setup so the host stays reachable after you log
+7 -3
View File
@@ -24,13 +24,17 @@ The update does not remove saved threads, settings, or project files.
| Action | What to do |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Update server** | Select the button and leave T3 Code open. It prepares the matching version, restarts the server, and reconnects automatically. This can take several minutes. |
| **Update server** | Available for the T3 Code Linux background service. Select the button and leave T3 Code open while it prepares, tests, restarts, and reconnects. |
| **Update the desktop app** | Open the T3 Code desktop app on the machine that runs the server and install the app update there. Reopen it if needed. |
| **Copy update command** | Copy the command, open a terminal on the server machine, stop the current T3 Code server, and relaunch it with the copied command and any startup options you normally use. |
The available action depends on how that server was started. T3 Code does not update connected
servers silently in the background.
If the requested version includes a database update, remote installation stops before restart and
asks you to run the exact `npx t3@<version> service update` command on the server machine. This is
an intentional rollback-safety boundary.
After selecting **Update server**, the warning becomes a three-step progress rail:
**Download**, **Install**, and **Resume**. The same progress appears in the conversation and in
Connections, so navigating between them does not lose the update. A failed step remains visible
@@ -56,8 +60,8 @@ commands.
## After the Update
Keep the web or desktop app open while the server restarts. The update completes only after the
replacement server reports the requested version and is ready to accept commands. The warning and
progress rail then disappear.
service launcher reports that exact update committed and the replacement server is ready to accept
commands. A rollback is reported immediately instead of waiting for a generic reconnect timeout.
If a step fails: