Skip to content
Source
Sign inSign up
pingdotgg/t3code

Let the desktop app be a client of an existing T3 Code server #9376

Closedcolonelpanic8(GitHub profile, opens in a new tab)wants to merge 250+ commits intot3code/codex-turn-mapping fromrefs/pull/9376/headopened View on GitHub

Let the desktop app be a client of an existing T3 Code server

Fixes #6097. Supersedes #4444 and folds in #4496 and #4559.

Based on #2829's branch (t3code/codex-turn-mapping) rather than main: the new orchestrator rewrites the client state and settings surfaces this change touches, so a main-based version would only conflict with it. The same series against main is kept at colonelpanic8/t3code:t3code/client-environment-suite-main for reference.

The problem

Since t3 service (#4286, #6286) a T3 Code server can outlive the desktop app. But the desktop app still assumes it owns the machine's backend: on launch it sees port 3773 busy, picks 3774, and starts a second backend against the same ~/.t3/userdata/state.sqlite. Two servers then contend for one SQLite database and requests fail with database is locked (#6097). Users in that thread asked for the obvious alternative, a thin client, and explained why the browser PWA is not a substitute: browser hotkeys conflict and several settings are unavailable outside the app.

The mobile app already works this way. It owns no backend and pairs with whatever environments it is given. This PR gives the desktop app the same option.

What changes

The desktop app never starts a second backend against a state directory that already has one. On launch it reads the server-runtime.json a live server persists next to its database, exactly as t3 pair does, confirms the pid is alive and the process answers with the environment descriptor recorded next to it, and if so runs this launch as a client of that server instead of spawning its own. This is the same discovery t3 pair and t3 triage already rely on, so there is no new on-disk format and no new HTTP surface. Connections explains why the app is in this state and offers to pair with the running server.

Client-only mode. Users can also opt into this permanently (Settings → Connections → Backend mode) or per launch (--backend-mode client-only). In client-only mode the app serves its packaged renderer from static assets, opens the window when the renderer is ready rather than when a backend is, and does not stop any backend on quit. A client-only app with no saved connections lands on Connections instead of a dead primary-backend state.

Pairing with a server on this computer. Connections lists servers discovered through their runtime state. Pairing mints a one-time credential by running the bundled server's t3 pair --json against that state directory, which writes into the running server's own database. Same-user proof is filesystem access to the state directory, which is the trust model t3 pair already uses. Works on every platform.

Settings target an environment. A client with no backend of its own has nothing to call "primary", so settings that live on a server (environment general settings, providers, source control, keybindings, diagnostics) are addressed to an explicitly selected environment through one shared header that shows the same loading/offline/error state everywhere, and settings that belong to the client (general, appearance) are grouped separately in the navigation. Restore-to-defaults resets only the keys a page owns. Any connected client can manage pairing links and authorized clients for that environment, not only for a locally spawned one.

Commits

The series is squashed onto the orchestrator branch as one commit; the original seven-commit series is on the main-based reference branch and is meant to be read in that order.

  1. feat: client-only desktop mode and environment-scoped settings, the mode, IPC, static renderer serving, web routing, presence scope, and settings pages.
  2. shared: move server runtime state reading into packages/shared, so the desktop can read runtime state without depending on the server package.
  3. cli: add --json to t3 pair, following the existing t3 auth ... --json convention.
  4. desktop: discover local servers through runtime state and pair via t3 pair, replacing an earlier Linux-only advertisement scheme that needed a new unauthenticated endpoint.
  5. desktop: attach to a running server instead of spawning a second backend, the #6097 fix.
  6. web: unify environment-scoped settings selection and presentation.
  7. web: drop per-environment accent colors and display names, cosmetic client preferences split to a follow-up.

Prior art

Paseo, another local-first agent runner, settled on this shape: the daemon runs detached, the desktop app reuses a daemon that is already running rather than starting another, and a manageBuiltInDaemon setting turns the desktop into a pure client. Its desktop shells out to the bundled CLI for daemon status --json the way this PR shells out to t3 pair --json.

Not in this PR

Per-environment accent colors and custom display names, which were part of earlier revisions, are split out to keep this reviewable. Auto-pairing on attach is a one-line follow-up once the approach is agreed; this PR asks for one explicit Pair click.

Verification

  • vp run --filter @t3tools/desktop --filter t3 --filter @t3tools/web --filter @t3tools/contracts --filter @t3tools/client-runtime --filter @t3tools/shared typecheck: clean.
  • vp lint --report-unused-disable-directives and vp fmt --check over every changed file: clean.
  • Focused vp test run over apps/desktop (app, ipc, settings, electron, backend pool, exposure, updates, window), apps/server (cli, auth, startup access, server), apps/web (settings, environments, presence, grouping, hooks), packages/client-runtime (connection), packages/shared, packages/contracts: 132 files, 1307 tests, all passing.

Note

High Risk Changes desktop startup, shutdown, and custom-protocol serving (including static file handling and pairing subprocess trust), which are security- and data-integrity-sensitive paths.

Overview Adds a managed vs client-only desktop backend launch path so the app can run without spawning its own server and can reuse one that is already running.

Launch and lifecycle: Settings and --backend-mode resolve the effective mode; packaged managed launches auto-switch to client-only when a live userdata server is found via persisted runtime state (same discovery as t3 pair). Client-only bootstrap registers the custom protocol as a dev proxy or static packaged renderer, opens the window on renderer readiness, skips managed backend startup/shutdown, and surfaces fatal errors for invalid mode flags or missing packaged assets.

Local server UX: New IPC discovers running servers and pairs by shelling out to bundled t3 pair --json, with strict validation of pairing URLs. Changing backend mode persists settings and triggers a shutdown-then-relaunch sequence (with rollback if relaunch fails).

Web: Remote/local thread and sidebar grouping use an environment presence scope instead of comparing everything to the primary id; client-only desktop hides managed local bootstraps. Connections settings logic gains local-server pairing candidates and safer pairing base URLs per connection type.

Shared/server: Server runtime state read/write moves to @t3tools/shared; t3 pair gains --json for machine-readable output.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 5b21d4f9da0402f2a3ce9161aafde751dbe579d0. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Add desktop client-only backend mode to connect to an existing T3 Code server

  • Adds a DesktopBackendMode service with managed and client-only modes; a packaged managed launch with a live userdata server now falls back to client-only, and CLI arguments can override the persisted mode
  • Adds local T3 Code server discovery through persisted runtime-state files, process-liveness filtering, and pairing via a JSON pair --json CLI command; the desktop IPC exposes these to the renderer
  • Adds a FirstRunGate and WelcomeWizard onboarding flow that handles connection, agent setup, and project import, including direct pairing, relay connections, and agent-session scanning/import
  • Adds client-side load balancing: chooseLoadBalancedEnvironment scores connected environments by CPU/memory health and weights, and LoadBalancingSettings persists per-environment preferences
  • Refactors settings, telemetry, diagnostics, and project configuration to be environment-scoped rather than primary-environment-only; project scripts, browser access, and auto-pull now resolve per-project overrides against server defaults
  • Replaces the per-provider usage-limits UI with a pooled presentation (UsageLimitsPooled) that merges native and hub accounts, shows remaining quota, and exposes reset-credit actions through popovers
  • Risk: pair command now supports --json and existing callers relying on human-readable-only output are unaffected, but TerminalOpenInput/TerminalAttachInput/TerminalRestartInput schemas gained an optional providerInstanceId field that older servers will not send; readBrowserClientSettings now propagates LocalStorageOperationError instead of returning null, which may surface errors previously swallowed
Macroscope summarized d27c7a0.
    1. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Macroscope skipped reviewing this pull request. Per-review cost limit exceeded (workspace setting).

      This review would cost an estimated $58.10, which exceeds your per-review limit of $10.00.

      The top 3 files driving up this estimate:

      FileDiff SizeEstimate
      apps/web/src/components/onboarding/WelcomeWizard.tsx55.43KB$2.77
      apps/web/src/components/settings/ProjectSettingsPanel.tsx53.98KB$2.70
      apps/web/src/components/settings/SettingsPanels.tsx46.20KB$2.31

      Tip

      To get this pull request reviewed, you can:

      1. Comment @macroscope-app on this PR to request a manual review (monthly spend limits still apply).
      2. Exclude the file(s) above from review by adding a pattern to your .macroscope/ignore.md — note that creating this file replaces Macroscope's built-in default ignores rather than extending them.
      3. Raise your cost limit in your workspace billing settings.
      [Turn off this reminder going forward](https://app.macroscope.com/pingdotgg/settings#Personal)
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR introduces a broad desktop client-mode and existing-server pairing capability with substantial cross-cutting startup, lifecycle, authentication, protocol, and settings changes. Unresolved concerns include valid local pairing URLs being rejected and relaunches potentially being queued after shutdown failure, so the changes require human review.

      Not approved because:

      • Per-review cost limit exceeded (workspace setting). Approvability relies on correctness review in order to determine eligibility
      Review your spending limits in [Billing settings](https://app.macroscope.com/pingdotgg/settings/billing), or comment `@macroscope-app review this PR` to bypass the limit and review now. You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 82443106f8503bb8f3ad53fa8c2fcf9723ba6f45. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -0,0 +254,21 @@
      254+ const discoveredOrigin = parseUrlOrigin(server.httpBaseUrl);
      255+ if (outputOrigin === null || discoveredOrigin === null) {
      256+ return yield* new LocalServerPairingError({
      257+ reason: "request_failed",
      258+ detail: "The local T3 Code pairing command returned an invalid server origin.",
      259+ });
      260+ }
      261+ if (
      262+ output.environmentId !== server.environmentId ||
      263+ outputOrigin !== discoveredOrigin ||
      264+ !isValidLocalServerPairingUrl({
      265+ pairingUrl: output.pairingUrl,
      266+ httpBaseUrl: server.httpBaseUrl,
      267+ token: output.token,
      268+ })
      269+ ) {
      270+ return yield* new LocalServerPairingError({
      271+ reason: "request_failed",
      272+ detail: "The local T3 Code pairing command returned an invalid pairing link.",
      273+ });
      274+ }

      Pairing rejects valid local URLs

      High Severity

      Local pairing treats a t3 pair --json link as invalid unless its origin equals the discovered backend origin. t3 pair builds that link from devUrl or resolveHeadlessConnectionString, which is localhost or a LAN address when the server did not bind an explicit host, while persisted origin is 127.0.0.1. Pairing with the default local server therefore fails after the CLI succeeds.

      Additional Locations (2)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 82443106f8503bb8f3ad53fa8c2fcf9723ba6f45. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -173,15 +185,10 @@
      173185 yield* electronApp.exit(75);
      174186 return;
      175187 }
      176- yield* electronApp.relaunch({
      177- execPath: process.execPath,
      178- args: process.argv.slice(1),
      179- });
      180188 yield* electronApp.exit(0);
      181189 }).pipe(
      182190 Effect.catchCause((cause) => {
      183191 const error = new DesktopLifecycleRelaunchError({ reason, cause });
      184- return logLifecycleError(error.message, { error });
      192+ return Effect.fail(error);
      185193 }),
      186- Effect.forkDetach,
      187- Effect.asVoid,
      194+ Effect.tapError((error) => logLifecycleError(error.message, { error })),

      Relaunch queued before shutdown

      Medium Severity

      Packaged relaunch now calls electronApp.relaunch() before shutdown. setBackendMode rolls settings back if that later shutdown fails, but Electron has already queued a restart and there is no way to cancel it. The next quit then relaunches unexpectedly with the restored mode, after quitting has already been set.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 82443106f8503bb8f3ad53fa8c2fcf9723ba6f45. Configure [here](https://www.cursor.com/dashboard/bugbot).
    5. Note

      This comment is posted by Julius' dot

      This adds a client-only desktop lifecycle, automatically switches packaged launches to it when another server is running, and adds local server pairing. Theo declined the alternate desktop architecture in #4444, and the linked discussions contain no later approval for these startup and pairing changes. The contribution guide requires maintainer approval of the direction and scope for these workflow changes. Please agree that design with maintainers and link the approval when requesting reconsideration; the database-ownership problem reported in #6097 remains useful.

    6. juliusmarminge closed this

Sign in to join this conversation.