Merge remote-tracking branch 'origin/main' into pr-server-only

* origin/main: (675 commits)
  fix(web): tolerate servers that predate git identity in project import (#10547)
  chore(mobile): bump app version to 1.1.0
  fix(mobile): wait for native thread scroll before reveal (#10486)
  fix(mobile): match Working status color to desktop
  fix(web): remove inserted citations on cancel (#10518)
  feat(web): group onboarding project import by repository (#10493)
  fix(mobile): preserve chat rows when toggling commands (#10492)
  fix(mobile): restore assistant message bottom padding (#10491)
  fix(mobile): animate thread lifecycle transitions consistently (#10487)
  fix(mobile): release initial scroll target after dragging (#10483)
  fix(mobile): smooth composer status pill resizing (#10484)
  fix(mobile): prevent chat from disappearing when scrolling (#10479)
  fix(web): resize the floating preview from any edge (#10467)
  fix(web): keep composer toolbar controls anchored during transitions (#10478)
  fix(mobile): improve font-size slider performance and prevent maximum update depth errors (#7138)
  feat(mobile): start a new thread on an existing branch (#10359)
  fix(ios): scroll short source files from blank space (#10178)
  fix(mobile): hide changed-files navigator and restore refresh in raw diff fallback (#9828)
  fix(projects): prevent invalid script IDs from crashing threads (#10019)
  fix(devcontainer): make repository setup work (#7875)
  ...

# Conflicts:
#	apps/server/src/provider/builtInDrivers.ts
#	docs/README.md
#	docs/user/install.md
#	packages/contracts/src/settings.test.ts
#	packages/contracts/src/settings.ts
This commit is contained in:
raman325 committed 2026-09-07 15:47:47 -04:00
commit f9b4ceb463
1802 files changed
+186443 -43978

No files matched your search

+27 -19
View File
@@ -2,47 +2,55 @@
## Using T3 Code
- [Install and first run](./user/install.md)
- [Install T3 Code](./user/install.md)
- [Messages and context](./user/composer.md)
- [Working with threads](./user/thread-sidebar.md)
- [Permission modes](./user/permission-modes.md)
- [Terminal history](./user/terminal.md)
- [Source control](./user/source-control.md)
- [Project settings](./user/project-settings.md)
- [Appearance and themes](./user/appearance.md)
- [Keyboard shortcuts](./user/keybindings.md)
- [Organizing threads](./user/thread-sidebar.md)
- [Review usage](./user/usage.md)
- [Customize a project icon](./user/project-settings.md)
- [Mobile appearance](./user/mobile-appearance.md)
- [Environment themes](./user/environment-theme.md)
- [Import browser sessions](./user/browser-import.md)
- [Usage and limits](./user/usage.md)
- [Product usage data](./user/telemetry.md)
- [Remote access](./user/remote-access.md)
- [Keeping app and server in sync](./user/updating.md)
- [Source control integrations](./user/source-control.md)
- [Background service (Linux)](./user/background-service.md)
- Providers: [Codex](./user/providers-codex.md) · [Claude](./user/providers-claude.md) · [Hermes](./user/providers-hermes.md) · [OpenCode](./user/providers-opencode.md)
Mobile app: [apps/mobile/README.md](../apps/mobile/README.md)
- [Running in the background](./user/background-service.md)
- [Updating T3 Code](./user/updating.md)
- Provider guides: [Codex](./user/providers-codex.md) · [Claude](./user/providers-claude.md) · [Hermes](./user/providers-hermes.md) · [OpenCode](./user/providers-opencode.md) · [Antigravity](./user/providers-antigravity.md)
---
## Working on T3 Code
Everything below is for maintainers. Setup lives in the [root README](../README.md);
policy in [CONTRIBUTING.md](../CONTRIBUTING.md); agent rules in [AGENTS.md](../AGENTS.md).
Start with the [development runbook](./operations/development.md) and
[contribution policy](../CONTRIBUTING.md).
Internal notes preserve architectural decisions, constraints, and implementation traps that the
source alone does not explain. Most code changes do not need an internal documentation update. Follow the
[documentation rules](../AGENTS.md#documentation) before adding one.
- [Architecture overview](./internals/overview.md)
- [Workspace layout](./internals/workspace-layout.md)
- [Glossary](./internals/glossary.md)
- [Scripts](./internals/scripts.md)
- [Connection runtime](./internals/connection-runtime.md)
- [Voice input](./internals/voice-input.md)
- [Providers](./internals/providers.md)
- [Model classification](./internals/model-manifest.md)
- [Remote environments](./internals/remote.md)
- [Server updates](./internals/server-updates.md)
- [Resource telemetry](./internals/resource-telemetry.md)
- [Product analytics](./internals/product-analytics.md)
- [Environment auth](./internals/environment-auth.md)
- [T3 Connect](./internals/t3-connect.md)
- [CI gates](./internals/ci.md)
- [Engineering work artifacts](./internals/work-artifacts.md)
- [Assistant citations](./internals/assistant-citations.md)
- [Mobile navigation](./internals/mobile-navigation.md)
- [Mobile development lifecycle](./internals/mobile-development.md)
- [Terminal runtime](./internals/terminal-runtime.md)
- [Voice input](./internals/voice-input.md)
### Runbooks
- [Development and local builds](./operations/development.md)
- [T3 Connect setup](./operations/connect-setup.md)
- [Release](./operations/release.md)
- [Observability](./operations/observability.md)
- [Relay observability](./operations/relay-observability.md)
-42
View File
@@ -1,42 +0,0 @@
# Terminal renderers
Terminal sessions remain server-owned PTYs. Clients receive the existing raw byte stream and send
input and resize events over the existing terminal contracts; renderer choices never cross the
wire.
## Ghostty alignment
Android and web use the official `libghostty-vt` C ABI for parsing, terminal state, grapheme
boundaries, keyboard encoding, selection, and scrollback:
- Android links the native shared library and converts render state into a compact JNI snapshot.
- Web loads a separately cached WebAssembly build and reads render state into a Canvas 2D surface.
- Both artifacts are built from the revision in
`native/libghostty-vt/VERSION`.
The platform adapters deliberately own only platform behavior. Android owns its Kotlin Canvas and
touch integration. Web owns browser font shaping, the hidden IME textarea, clipboard and DOM input,
and its Canvas renderer. The web adapter also delegates application mouse encoding, word and line
selection, and OSC 8 hyperlink metadata to the official ABI. Browser conventions remain available:
holding Shift bypasses application mouse capture, and the platform link modifier opens hyperlinks.
React does not participate in terminal frames.
The web runtime is singleton-scoped per browser tab so split terminals share one compiled module
and memory. Each visible terminal owns and frees its own terminal, render state, row iterator, cell
iterator, key and mouse encoder, and input event handles. Restoring captured scrollback temporarily
detaches the PTY callback so historical device queries cannot emit replies into the current shell.
## Updating Ghostty
Update and rebuild Android first, because mobile's `VERSION` file is the single source of truth for
the upstream pin (the upstream `LICENSE` lives beside it). Then run:
```sh
pnpm --dir apps/web build:ghostty-wasm
```
Commit the regenerated web `wasm` artifacts. The build embeds the pinned revision into the binary as
semver build metadata, and the focused web ABI test reads it back through `ghostty_build_info` and
compares it against mobile's `VERSION` — so the web vendor directory holds only the artifacts, drift
cannot hide, and there is no second pin to keep in sync. The same test enforces the artifact budget
and exercises repeated create/write/free cycles with multi-codepoint graphemes.
+29
View File
@@ -0,0 +1,29 @@
# Assistant citations
Citations carry the selected excerpt and source identity in ordinary message text.
Drafts, clipboard copies, stashes, and sent messages keep that representation
without a separate citation store. The saved quote remains usable when its source
disappears or changes. The [shared format](../../packages/shared/src/assistantCitations.ts) uses
stable environment IDs without a browser origin, so moving between local, remote,
and tunnel connections does not change a citation's identity.
Source navigation is best effort. [Text selectors](../../apps/web/src/lib/assistantTextSelection.ts)
refer to rendered text after whitespace normalization, measured in UTF-16 units.
They cannot be applied to raw Markdown. The original excerpt keeps its whitespace;
normalization is only for locating it. Repeated text needs an unambiguous context
match, even if one occurrence still sits at the saved offsets. Guessing could
highlight the wrong claim.
Navigation owns the highlight's lifetime across virtual-row remounts. The source
row must be fetched, unfolded, mounted, and measured before quote positioning
takes over from normal timeline scrolling. Remounting must not revive a dismissed
highlight. The [navigation hash](../../apps/web/src/lib/assistantCitationNavigation.ts)
uses base64url because router normalization otherwise decodes whitespace and
source IDs inside the citation URI.
[ProviderService](../../apps/server/src/provider/Layers/ProviderService.ts) expands
citations before dispatch to any provider adapter. It sends the saved excerpt
without looking up the source, distinguishes quoted reference material from the
user's comment, and leaves persisted messages in their original form. Input
limits apply after expansion as well as before it. A draft that fits as encoded
links can exceed the provider limit once expanded.
-31
View File
@@ -1,31 +0,0 @@
# CI quality gates
> For maintainers. Using T3 Code? See [docs/user](../user/).
[`.github/workflows/ci.yml`](../../.github/workflows/ci.yml) runs these quality gates on pull requests
and pushes to `main`:
- **Check**: `vp check` (format and lint; this repo sets `typeCheck: false` in its lint options),
then `vpr typecheck` for the workspace type check. The same job
builds the desktop pipeline (`vp run build:desktop`) and verifies the preload bundle exists and
uses only imports that Electron's sandbox can load. The verifier parses imports, then executes the
trusted artifact with controlled bridge stubs to confirm that its required APIs are callable.
- **Test**: `vp run test` across the workspace.
- **Mobile Native Static Analysis**: `vp run lint:mobile` on macOS, wrapping
`scripts/mobile-native-static-check.ts`. A cheap Linux **Mobile Native Changes** job gates it:
the macOS runner only boots when the diff touches `apps/mobile` Swift/Kotlin sources, the
SwiftLint/detekt/ktlint configuration, the `Brewfile`, the check script, the root `package.json`
that defines `lint:mobile`, or `ci.yml`. Otherwise the job is skipped, which GitHub reports as
success for the required check. Renames are matched on both their old and new path. The gate fails
open in every other case: if the changed-file list cannot be resolved, GitHub truncates it, or the
gate job itself fails, the lint runs.
- **Release Smoke**: exercises release-only workflow steps through `scripts/release-smoke.ts`, so
release breakage surfaces on PRs rather than at tag time.
`.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`)
desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release. It auto-enables
signing only when platform credentials are present. macOS passkey builds additionally require
`APPLE_TEAM_ID` and the `MACOS_PROVISIONING_PROFILE` secret; Windows uses Azure Trusted Signing.
Without the core signing credentials, it still releases unsigned artifacts.
See [Release Checklist](../operations/release.md) for the full release/signing setup checklist.
+60 -182
View File
@@ -1,196 +1,74 @@
# Connection Runtime
# Connection runtime
> For maintainers. Using T3 Code? See [docs/user](../user/).
Web, the desktop renderer, and mobile share one connection owner per environment
in `packages/client-runtime`. Platform code supplies storage, credentials, network
signals, and application lifecycle events. React views consume the runtime.
Keeping retries and session lifetime here prevents competing reconnect loops when
several views need the same environment.
The connection runtime is shared by web and mobile. It owns connectivity,
authentication, retries, transport lifetime, cached environment data, and
environment-scoped operations.
## One transport retry owner
Web and mobile mount this runtime once at the application root and compose it
identically: `apps/web/src/connection/runtime.ts` and
`apps/mobile/src/connection/runtime.ts` differ only in the platform layer they
supply. There is no legacy connection owner or supported mixed mode.
The [supervisor](../../packages/client-runtime/src/connection/supervisor.ts) owns
transport retry policy; resolving an endpoint and opening an RPC session are single
attempts. Transient failures retry with capped backoff. Offline states and
authentication failures wait for a wakeup instead of spending attempts on
unchanged conditions.
## Composition
Foregrounding needs different treatment depending on the connection's state.
It wakes a retry immediately, leaves an ordinary in-flight attempt alone, and
probes an established session before replacing it. A long mobile background
suspension forces replacement because the OS can kill a socket without reporting
closure. Treating every foreground event as a reconnect delays healthy attempts;
treating every resume as harmless leaves suspended sockets stuck.
[`connection/layer.ts`][layer] assembles the runtime:
The [registry](../../packages/client-runtime/src/connection/registry.ts) scopes
connections by environment. An involuntary disconnect retains the registration
and cached data. Explicit removal closes the scope and clears credentials,
projections, and platform-owned state such as drafts. Cloud-account changes apply
to relay registrations; they must not discard directly paired environments.
- `ConnectionResolver` ([resolver.ts][resolver]) resolves a catalog entry into a
prepared, authenticated endpoint for primary, bearer, relay, or SSH targets.
- `ConnectionDriver` ([driver.ts][driver]) prepares through the resolver, opens
one RPC session, and reports `preparing`, `opening`, and `synchronizing`.
- `RpcSessionFactory` ([rpc/session.ts][session]) performs one transport
attempt. It does not retry. `RpcSession` is the interface it returns,
exposing `client`, `initialConfig`, `ready`, `probe`, and `closed`.
- `EnvironmentRegistry` ([registry.ts][registry]) owns the catalog and the
per-environment scopes.
- `ConnectionOnboarding` and `RelayEnvironmentDiscovery` sit alongside the
registry. Startup calls `EnvironmentRegistry.start` and streams platform
registrations into `reconcilePlatform`.
## HTTP authorization
The registry creates one environment-scoped supervisor per environment.
`acquireSupervisor` serializes access per environment, reuses an existing
supervisor when the catalog entry is unchanged, and closes and recreates the
scope when it changed. `createServiceScope` builds an `EnvironmentSupervisor`
bound to a closeable scope and connects it; `run` and `runStream` execute caller
effects with that supervisor provided.
RPC sessions authenticate at socket upgrade, while HTTP requests need current
credentials from the
[authorization service](../../packages/client-runtime/src/authorization/service.ts).
Replacing a healthy socket for HTTP renewal would interrupt conversations and
change the transport generation without a transport failure. Credential expiry
does not close the socket, and refresh failure belongs to the HTTP operation.
`EnvironmentSupervisor` owns desired state, retry scheduling, and the active
session scope. React components do not create connections, transports, retry
loops, or RPC clients.
Session listings must retain unrevoked connected sessions after credential expiry
so an open connection does not disappear from connection management. This does
not extend the credential's lifetime. New HTTP requests and socket upgrades still
require valid credentials.
## Connection State
## Transport health and data freshness are separate
The supervisor is the only retry owner.
A socket opening is insufficient evidence that the environment is usable. The
[RPC session](../../packages/client-runtime/src/rpc/session.ts) waits for the
initial server configuration before becoming ready. Shell and thread data then
have their own synchronization state. A failed shell subscription can coexist
with a healthy connection; labeling that state "reconnecting" promises a
transport retry that will never happen.
1. A persisted or platform registration marks an environment as desired.
2. If the device is offline, the supervisor releases the active session and
waits for a signal without consuming retry attempts or running a timer.
3. When online, it asks the driver for one prepared connection and one RPC
session.
4. Transient failures retry forever with exponential backoff capped at 16
seconds (`RETRY_DELAYS_MS`). A connection stable for 30 seconds resets
accumulated backoff.
5. Authentication or configuration failures remain blocked until an external
wakeup changes the relevant input.
6. An involuntary session close keeps the registration and cache, then retries.
7. Explicit removal closes the session and deletes the registration,
credentials, shell cache, and thread cache.
Cached projections remain readable offline. They must neither imply a live
connection nor overwrite newer live data during a reconnect. Loading and
resuming snapshots belongs to the shared state services, so every view agrees
on which data is current.
### Wakeups
[Thread detail](../../packages/client-runtime/src/state/threads.ts) separates
subscription lifetime from cache lifetime. Mounted consumers share one live
stream, which stops when the last consumer unmounts; hidden mounted routes still
count. A registry-local cache retains state and its replay cursor for five idle
minutes so back navigation can resume without another snapshot download.
Wakeup handling differs by phase, in [supervisor.ts][supervisor]:
Retain state and cursor together only after an update finishes. Cancellation must
not advance the cached cursor beyond the applied data, and an old scope must not
overwrite its successor's cache. Preserve pagination data on reuse, but clear
canceled loading state.
- During establishment, `waitForEstablishmentInterrupt` consumes and **ignores**
plain application activation. Restarting an in-flight attempt because the app
came to the foreground would only delay it. The exception is
`application-active-reconnect`, which mobile emits after a meaningful
background suspension; it interrupts establishment and resets the retry
ladder, because the OS may have silently killed the socket underneath the
attempt.
- Credential changes interrupt establishment only for relay targets, where a new
credential changes what is being established.
- Explicit disconnect, explicit retry, and going offline interrupt establishment
in every case.
- While waiting out backoff, application activation resets the retry ladder so a
foregrounded app reconnects immediately instead of serving the remaining
delay.
- Once connected, `monitorConnectedLease` handles plain activation by probing
the existing session (`lease.session.probe`, with a shorter timeout for
mobile's `application-active-probe`) rather than reconnecting; a healthy
session survives foregrounding. `application-active-reconnect` skips the probe
and replaces the lease outright.
The UI derives `available`, `offline`, `connecting`, `reconnecting`,
`connected`, and `error` from supervisor state plus explicit data-sync state.
It does not infer connection health from cached data or the existence of a
transport object. An environment becomes `connected` after the socket opens and
the initial config RPC succeeds, proving that the server is responsive. Shell
and thread synchronization are independent data states. A healthy RPC transport
with a failed shell subscription is shown as connected with a synchronization
error, not as a reconnect that is not actually scheduled.
## Data Boundary
Finite requests, durable subscriptions, and commands are separate APIs:
- Query atoms revalidate when the RPC generation changes.
- Subscription atoms switch to replacement sessions.
- Subscription failure handling in [rpc/client.ts][client] distinguishes two
cases. A transport failure (`isTransportFailure`: every failure is an RPC
client error) ends the inner subscription without resubscribing, so the outer
stream waits for the supervisor to supply a replacement session. A handled
domain failure runs `onExpectedFailure` and, when
`retryExpectedFailureAfter` is set, sleeps and resubscribes on the **same**
session. A healthy transport is never torn down for a domain failure.
- Mutations resolve the current environment runtime at execution time.
- Shell and thread snapshots are available while offline.
- Sync status is explicit and independent per domain. Shell status is `empty`,
`cached`, `synchronizing`, or `live`, with a separate `error` field; there is
no `failed` status. Thread status adds `deleted`.
- Cached shell and thread projections are never allowed to overwrite newer live
data during a fast reconnect.
- Domain atom factories route effects through the environment registry and
resolve the current scoped service at execution time. Project and thread
commands are Atom factories under `src/state`
(`createProjectEnvironmentAtoms`, `createThreadEnvironmentAtoms`), as are the
shell and thread state factories (`createEnvironmentShellAtoms`,
`createEnvironmentThreadStateAtoms`).
- Web and mobile own their Atom runtimes, React hooks, and feature composition.
The Promise bridge exists only at the React/Atom boundary. Runtime and business
logic remain Effect-native.
## Platform Layers
Web and mobile provide:
- network status and network-change streams;
- application lifecycle wakeups;
- cloud session credentials;
- device identity;
- platform registrations;
- persistent catalog, credential, shell, and thread stores;
- HTTP, crypto, and telemetry layers.
Platform layers adapt operating-system capabilities. They do not implement
connection policy. `EnvironmentOwnedDataCleanup` is part of this contract: on
removal the registry clears its cache and calls the platform implementation, so
web clears composer drafts and mobile clears drafts plus the thread outbox.
Mobile cloud sign-out first saves relay drafts and queued messages in the local
composer store under the owning account. These saved copies retain attachment
files during cleanup and remain outside the active composer and upload queue.
Signing back into that account restores them before relay credentials activate.
Directly paired environments keep their drafts and outbox when cloud sign-out runs.
Mobile composer attachments upload over HTTP while their environment is connected,
with at most three concurrent transfers. Drafts retain local image data or an owned
file URI alongside the pending upload ID. Sending verifies and reuses that ID, or
uploads the local bytes again if it expired. Disconnecting cancels active transfers
without discarding drafts; reconnecting resumes preparation. Older servers without
attachment-upload support continue to receive inline images.
## Source Boundaries
Applications must import explicit package subpaths; the package intentionally
has no root export. The subpaths are documented in
[packages/client-runtime/README.md](../../packages/client-runtime/README.md),
with the `exports` map in that package's `package.json` as the authoritative
list. Files that are not exported are implementation details.
## Application Boundary
The application root mounts the shared connection layer, creates its own Atom
runtime, and selects the domain atom factories required by that platform. Web
and mobile may expose different hooks and features without changing connection
ownership.
Application code must not construct RPC clients, retry loops, or raw
orchestration commands. Persistence paths belong to the platform registration
and cache stores, with explicit migration or invalidation policy.
## Verification
Core state-machine tests use `@effect/vitest` and deterministic service layers.
Required coverage includes:
- offline startup and online wakeup;
- forever retry with the 16-second cap;
- explicit retry interrupting backoff;
- authentication wakeups;
- involuntary close and reconnect;
- explicit removal clearing all owned state;
- relay token reuse and refresh;
- progressive relay discovery;
- shell and thread cache hydration;
- durable subscriptions switching sessions;
- command metadata and idempotent queued-command metadata.
[layer]: ../../packages/client-runtime/src/connection/layer.ts
[resolver]: ../../packages/client-runtime/src/connection/resolver.ts
[driver]: ../../packages/client-runtime/src/connection/driver.ts
[registry]: ../../packages/client-runtime/src/connection/registry.ts
[supervisor]: ../../packages/client-runtime/src/connection/supervisor.ts
[session]: ../../packages/client-runtime/src/rpc/session.ts
[client]: ../../packages/client-runtime/src/rpc/client.ts
The [RPC boundary](../../packages/client-runtime/src/rpc/client.ts) resolves
requests against the current session at execution time. Durable subscriptions
follow replacement sessions. After a transport failure they wait for the
supervisor; an expected domain failure may resubscribe on the same healthy
session. Reconnection does not automatically replay mutations, whose retry and
idempotency rules belong to the operation.
+32
View File
@@ -0,0 +1,32 @@
# Dev container
> For maintainers. Using T3 Code? See [docs/user](../user/).
`.devcontainer/` gives you a ready-to-code Linux environment matching CI: Ubuntu 24.04, Node 24, pnpm, Rust stable, the global `vp` CLI, and the GitHub CLI. Open the repo in VS Code and "Reopen in Container", or create a GitHub Codespace. Dependency install (`vp i`), the Electron exec-bit repair, and the Vite dep-cache warmup all run automatically before you attach.
## What works in the container
- The full dev stack: `vp run dev`, then open the pairing URL it prints through the forwarded web port (5733). The bare origin is useless without the pairing token. In VS Code the forwarded port is a true localhost, so the printed URL works as-is; in browser Codespaces the forwarded origin differs, and if the server rejects it, pass the forwarded origin via `T3CODE_DEV_ALLOWED_ORIGINS`.
- Everything the Linux CI jobs run: focused `vp test run <files>`, `vp lint <files>`, package typechecks, `vp run build:desktop`, and the resource-monitor cargo build and tests. (`vpr` is not on PATH here; the curl installer only shims `vp`. Use `vp run <script>` or `node_modules/.bin/vpr` after install.)
## State and safety
`T3CODE_HOME` points at the workspace's gitignored `.t3`, so all runtime state stays inside the container workspace, mirroring the worktree default. There is no live install to damage inside a container, but the test-data rule from AGENTS.md still holds: copy data in, never point at shared state.
## Caching
Two named volumes keep rebuilds fast and installs off the slow macOS/Windows bind mount: the pnpm store (shared across checkouts, mounted where `vp i` keeps it) and root `node_modules` (per-container, which covers the whole `.pnpm` virtual store since workspace packages just symlink into it). Deleting a container and recreating it reuses both, so a rebuild's `vp i` is seconds, not minutes. The host sees an empty `node_modules`; run host-side tooling inside the container.
## Out of scope
- Windowed Electron development is host-only. Building and verifying the desktop bundle works fine in the container (CI does exactly that, headless); launching the app needs a display.
- Mobile native builds are host-only (Xcode for iOS, Android SDK for Android). Typecheck, lint, and the mobile static checks run fine.
- `vp run dev --share` needs a tailscale binary and a tailnet; not provisioned here.
## Prebuilds
Container creation from scratch does a full `vp i` plus toolchain installs, which is worth prebuilding. Codespaces prebuilds are configured in repo settings, not files, and pick this config up as-is: the heavy steps live in `onCreateCommand` and `updateContentCommand`, which prebuilds bake in. Restrict prebuilds to one region and one retained version; storage bills per region per version. Note that prebuild snapshots exclude the caching volumes, so a prebuild-first workflow may prefer dropping the mounts. Outside Codespaces, the Dev Container CLI can push a prebuilt image:
```bash
devcontainer build --workspace-folder . --push true --image-name <registry>/t3code-devcontainer:latest
```
+49 -175
View File
@@ -1,186 +1,60 @@
# Environment Authentication Profile
# Environment authentication
> For maintainers. Using T3 Code? See [docs/user](../user/).
The environment issues its own sessions and enforces their capabilities. Cloud
identity and relay credentials belong to a separate trust boundary, described in
[T3 Connect](./t3-connect.md). A relay token is never an environment login.
The environment server and the relay use separate credentials, issuers, and trust
boundaries. They intentionally use a similar OAuth-shaped model so that permission
checks and token exchange behavior can be audited against established concepts.
## Authority survives transport changes
## Authorization Model
Pairing delegates a set of scopes. Exchanging a bootstrap credential can narrow
that grant but cannot widen it. Ordinary pairing does not grant access-management
or relay-management authority. Creating another pairing link requires both
`access:write` and every scope being delegated. The
[auth handlers](../../apps/server/src/auth/http.ts) enforce this at issuance;
client labels and device metadata have no authorization role.
Environment authorization is capability-based. A session carries zero or more
OAuth-style scope strings:
The access read model contains pairing metadata, never recoverable pairing
secrets. Only the creation response returns the raw credential. Otherwise read
access to the connections list would become a way to acquire another client's
authority.
| Scope | Permission |
| ----------------------- | ------------------------------------------------------------------------ |
| `orchestration:read` | Read snapshots, status, events, configuration, and filesystem/VCS state. |
| `orchestration:operate` | Dispatch user operations and mutate environment-side workspace state. |
| `terminal:operate` | Create, attach, input, resize, clear, restart, and terminate terminals. |
| `review:write` | Read review diff previews used to compose review feedback. |
| `access:read` | Inspect pairing links and client sessions. |
| `access:write` | Create or revoke pairing links and client sessions. |
| `relay:read` | Inspect managed relay connectivity. |
| `relay:write` | Link, configure, or unlink managed relay connectivity. |
Browser cookies, bearer tokens, and DPoP tokens adapt the same scoped session
model. DPoP binds a token to a client's proof key; an invalid proof must fail
rather than fall back to bearer authentication. The OAuth token-exchange
vocabulary gives these grants a familiar meaning, but the environment does not
implement a general-purpose OAuth authorization server.
Ordinary pairing links grant the four client-operation scopes and read access to
managed relay connectivity:
`orchestration:read orchestration:operate terminal:operate review:write relay:read`.
The desktop bootstrap credential and command-line administrative bootstrap
credentials additionally grant `access:read access:write relay:write`.
Bearer and DPoP clients obtain short-lived WebSocket tickets through authenticated
HTTP so long-lived tokens stay out of socket URLs. Browser sessions can
authenticate the upgrade with their cookie. A successful handshake grants no
extra authority: [every RPC declares a required
scope](../../apps/server/src/auth/RpcAuthorization.ts).
## Host file access
Desktop restarts forget the previous local bearer token, so its reusable
bootstrap grant replaces earlier sessions for the same subject and method.
Revocation and insertion share a [database
transaction](../../apps/server/src/persistence/AuthSessions.ts); a failed
replacement must leave the old credential usable. Pairing and browser sessions
do not follow this replacement rule.
Clients with `orchestration:read` can read files anywhere the environment's server account can
read, following the environment-wide authorization model rather than introducing per-project
filesystem permissions. `projects.readFile` accepts an absolute path and returns the text of that
host file; only workspace-relative paths pass its root check, and `projects.writeFile` never
accepts an absolute path. Clients use this to show files an agent wrote outside the workspace, such
as a report in a temp directory, read-only.
## The environment is the filesystem boundary
## Media preview access
Projects are organizational boundaries, not filesystem sandboxes.
`orchestration:read` permits reading files the server account can read, including
absolute paths outside a project. This lets clients display artifacts that an
agent writes in a temporary directory. Relative paths and writes still follow
the [workspace path rules](../../apps/server/src/workspace/WorkspaceFileSystem.ts).
Clients with `orchestration:read` can request a `media-file` URL through `assets.createUrl` for
supported images, videos, HTML, and PDF files anywhere the environment's server account can read.
A thread ID supplies the workspace for relative paths; absolute paths refer to the environment
host, not the client.
Signed asset URLs are bearer credentials. A URL for media on the host grants
access to one canonical file and its device/inode identity, not its containing directory.
[Asset access](../../apps/server/src/assets/AssetAccess.ts) rechecks the opened
file's identity when serving it, so atomic replacement requires a new URL while
editing the same file in place does not. An HTML file authorized this way cannot
load sibling assets; directory-scoped workspace previews are a separate grant.
Clients should share the authored file reference so they do not disclose the
temporary URL's credential.
[`AssetAccess.ts`](../../apps/server/src/assets/AssetAccess.ts) resolves symlinks, requires a regular
file, and validates the resolved file's literal extension. It opens the file and signs its canonical
path and device/inode identity for one hour. The token grants access to that exact file, not adjacent
files or its containing directory. Serving rechecks the canonical path, media type, and opened
descriptor's identity, then streams full or partial responses from that descriptor. Replacing a
file atomically requires a freshly signed URL; editing it in place does not. Because the token names
one file, an HTML document served this way cannot load sibling assets; the directory-scoped
`workspace-file` resource remains the route for HTML inside the workspace. Uploaded attachments keep
their separate asset resource.
Signed asset URLs are bearer credentials. Anyone who obtains a URL and can reach the environment
can fetch that file until it expires. Clients should copy the authored reference, not the temporary
URL. Responses use `nosniff`; SVG responses retain their restrictive sandbox policy. Video reads
support byte ranges so playback does not require a complete download first.
Host videos can change in place, so their responses use `private, no-store` and omit `ETag`
and `Last-Modified`. File metadata cannot prove byte-for-byte identity for `If-Range`; advertising
those validators would encourage native players to send conditional seeks that require a full
response. Ordinary range requests receive partial responses. An explicitly supplied `If-Range`
still falls back to a full response because no strong validator is available. Host image previews
keep their private cache policy and weak metadata validators.
The server serves media in place without importing it into attachment storage. Deletion makes
future server reads fail, though an already loaded client or its cache can retain bytes. Native
viewers may use temporary client-side files for display or explicit sharing; those are not durable
environment copies.
## Authentication Flows
### Browser Session
`POST /api/auth/browser-session` consumes a one-time bootstrap credential and creates a
browser session cookie. The cookie is an HTTP transport adapter for the same
scoped session model; the response never exposes the session secret to browser
JavaScript.
### Bearer Access Token
Non-browser clients use `POST /oauth/token` with an
`application/x-www-form-urlencoded` body:
```text
grant_type=urn:ietf:params:oauth:grant-type:token-exchange
subject_token=<bootstrap credential>
subject_token_type=urn:t3:params:oauth:token-type:environment-bootstrap
requested_token_type=urn:ietf:params:oauth:token-type:access_token
scope=orchestration:read orchestration:operate terminal:operate review:write relay:read
```
Clients may additionally submit `client_label`, `client_device_type`, and
`client_os` extension parameters so the authorized-clients UI can identify the
device that established the session. These are presentation hints only; the
environment derives transport metadata such as IP address and user agent from
the request and does not use these fields for authorization.
The response has the token-exchange shape:
```json
{
"access_token": "<opaque session token>",
"issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
"token_type": "Bearer",
"expires_in": 2592000,
"scope": "orchestration:read orchestration:operate terminal:operate review:write relay:read"
}
```
Sessions issued from a plain bearer exchange use the store's
`DEFAULT_SESSION_TTL` of 30 days. The shorter one-hour `expires_in: 3600` applies
only to DPoP-bound exchanges, where the token is additionally constrained by a
proof key. See `SessionStore.ts` and `EnvironmentAuth.ts`.
Requested scopes must be a subset of the one-time bootstrap credential grant.
An ordinary paired client therefore cannot exchange its grant for
`access:read`, `access:write`, or `relay:write`.
### DPoP-Bound Access Token
The same `/oauth/token` exchange supports proof-of-possession tokens. A client
that sends a `DPoP` header has its proof verified by `verifyRequestDpopProof`;
the resulting JWK thumbprint is stored on the session, which is then issued with
method `dpop-access-token` and a one-hour TTL instead of the bearer default. An
invalid proof gets a DPoP challenge header and a credential error rather than a
bearer token. Newer servers include a safe `dpopFailureReason` category in that
error. When an older server omits the category, clients mention clock skew as
one possible cause rather than presenting it as confirmed.
`dpop-access-token` is advertised alongside `browser-session-cookie` and
`bearer-access-token` in the descriptor's `sessionMethods`
(`EnvironmentAuthPolicy.ts`), so clients can discover support rather than
assume it. Relay-brokered clients use this mode so that a leaked token cannot be
replayed without the corresponding key.
### WebSocket Ticket
`POST /api/auth/websocket-ticket` accepts any authenticated session and returns
a short-lived, single-purpose WebSocket ticket, issued through
`EnvironmentAuth.issueWebSocketTicket` with a five-minute default TTL. The
client presents its bearer or DPoP credential in headers to get the ticket, then
appends only that ticket to the socket URL as `wsTicket`. This keeps long-lived
tokens and browser cookies out of WebSocket URLs while letting the handshake
authenticate.
The ticket carries its session's scopes; each RPC method then enforces
`orchestration:read`, `orchestration:operate`, `terminal:operate`,
`review:write`, `relay:write`, or `access:read` as appropriate, through
`RPC_REQUIRED_SCOPES` in `apps/server/src/auth/RpcAuthorization.ts`. Review feedback submission currently dispatches
an orchestration operation, so clients performing it also need
`orchestration:operate`. Creating a ticket is not authorization to call every
RPC method.
## Standards Alignment
- Bearer access tokens are used through the `Authorization: Bearer` scheme from
RFC 6750.
- The token endpoint profiles the request and response vocabulary from OAuth 2.0
Token Exchange (RFC 8693), including `subject_token`, `requested_token_type`,
`access_token`, `issued_token_type`, and `token_type`.
- Scope values follow the OAuth 2.0 scope model from RFC 6749: space-delimited,
unordered capabilities with subset checking during exchange.
This is intentionally not a general-purpose OAuth authorization server. The
environment bootstrap token type is private, the bootstrap cookie and WebSocket
connection-token routes are product-specific adapters, and the API returns its
typed `HttpApi` errors rather than implementing every OAuth error response
surface.
## Upgrade Behavior
Migration `031_AuthAuthorizationScopes` is a hard cutover from role-bearing auth
records to scoped records. It deletes existing pairing links and sessions while
leaving non-authentication environment state unchanged. Upgraded clients must
pair again; old `owner` or `client` credentials are never silently mapped to new
capabilities.
## Relay Boundary
Relay-managed tunnels use their own tokens and keys. The relay can reuse scope
parsing and token-exchange conventions, but an environment access token is not a
relay token and cannot be presented to the relay.
Host videos can change in place. Their [HTTP
responses](../../apps/server/src/http.ts) omit cache validators because file
metadata cannot prove byte-for-byte identity for `If-Range`. Adding weak
validators would turn native-player seeks into full downloads.
+45 -201
View File
@@ -1,203 +1,47 @@
# Glossary
> For maintainers. Using T3 Code? See [docs/user](../user/).
This is a living glossary for T3 Code. It explains what common terms mean in this codebase.
## Table of contents
- [Project and workspace](#project-and-workspace)
- [Thread timeline](#thread-timeline)
- [Orchestration](#orchestration)
- [Provider runtime](#provider-runtime)
- [Checkpointing](#checkpointing)
- [Appearance](#appearance)
## Concepts
### Project and workspace
#### Project
The top-level workspace record in the app. In [the orchestration contracts][1], a project has a `workspaceRoot` and a title. It does not contain threads: `OrchestrationProject` and `OrchestrationThread` are separate arrays on the read model, and a project can have zero threads. See [workspace-layout.md][2].
#### Workspace root
The root filesystem path for a project. In [the orchestration model][1], it is the base directory for branches and optional worktrees. See [workspace-layout.md][2].
#### Worktree
A Git worktree used as an isolated workspace for a thread. If a thread has a `worktreePath` in [the contracts][1], it runs there instead of in the main working tree. Git operations live behind the VCS driver contract in `apps/server/src/vcs/VcsDriver.ts`, implemented by [GitVcsDriverCore.ts][3].
### Thread timeline
#### Thread
The main durable unit of conversation and workspace history. In [the orchestration contracts][1], a thread holds messages, activities, checkpoints, and session-related state. See [projector.ts][4].
#### Turn
A single user-to-assistant work cycle inside a thread. It starts with user input and ends when the session leaves `running` status, which [projector.ts][4] treats as the authoritative completion signal (`settledTurnStateForSessionStatus`). Checkpoint and diff work may settle afterward without changing when the turn ended. See [the contracts][1] and [ProviderRuntimeIngestion.ts][5].
#### Activity
A user-visible log item attached to a thread. In [the contracts][1], activities cover important non-message events like approvals, tool actions, and failures. They are projected into thread state in [projector.ts][4].
### Orchestration
Orchestration is the server-side domain layer that turns runtime activity into stable app state. The main entry point is [OrchestrationEngine.ts][7], with core logic in [decider.ts][8] and [projector.ts][4].
#### Aggregate
The domain object a command or event belongs to. In [the contracts][1], that is usually `project` or `thread`. See [decider.ts][8].
#### Command
A typed request to change domain state. In [the contracts][1], commands are validated in [commandInvariants.ts][9] and turned into events by [decider.ts][8].
Examples include `thread.create`, `thread.turn.start`, and `thread.checkpoint.revert`.
#### Domain Event
A persisted fact that something already happened. In [the contracts][1], events are the source of truth, and [projector.ts][4] shows how they are applied.
Examples include `thread.created`, `thread.message-sent`, and `thread.turn-diff-completed`.
#### Decider
The pure orchestration logic that turns commands plus current state into events. The core implementation is in [decider.ts][8], with preconditions in [commandInvariants.ts][9].
#### Projection
A read-optimized view derived from events. See [projector.ts][4], [ProjectionPipeline.ts][11], and [ProjectionSnapshotQuery.ts][10].
#### Projector
The logic that applies domain events to the read model or projection tables. See [projector.ts][4] and [ProjectionPipeline.ts][11].
#### Read model
The current materialized view of orchestration state. In [the contracts][1], it holds projects, threads, messages, activities, checkpoints, and session state. See [ProjectionSnapshotQuery.ts][10] and [OrchestrationEngine.ts][7].
#### Reactor
A side-effecting service that handles follow-up work after events or runtime signals. Examples include [CheckpointReactor.ts][6], [ProviderCommandReactor.ts][12], and [ProviderRuntimeIngestion.ts][5].
#### Receipt
A typed signal emitted when an async milestone completes, such as `checkpoint.baseline.captured`, `checkpoint.diff.finalized`, or `turn.processing.quiesced`. Receipts are a test-only mechanism: the production `RuntimeReceiptBusLive` publish is a no-op and only the test layer is PubSub-backed. Do not build production behavior on them. See [RuntimeReceiptBus.ts][13] and [CheckpointReactor.ts][6].
#### Quiesced
"Quiesced" means a turn has gone quiet and stable: follow-up work such as [CheckpointReactor.ts][6] has settled. It appears in [the receipt schema][13], so in practice it is something tests wait on rather than a production signal.
### Provider runtime
The live backend agent implementation and its event stream. The main service is [ProviderService.ts][14], the adapter contract is [ProviderAdapter.ts][15], and the overview is in [providers.md][16].
#### Provider
The backend agent runtime that actually performs work. Five drivers ship built in: Codex, Claude, Cursor, Grok, and OpenCode. See [ProviderService.ts][14], [ProviderAdapter.ts][15], and [CodexAdapter.ts][17] as a representative adapter.
#### Session
The live provider-backed runtime attached to a thread. Session shape is in [the orchestration contracts][1], and lifecycle is managed in [ProviderService.ts][14].
#### Runtime mode
The safety/access mode for a thread or session. [The contracts][1] define four values: `approval-required`, `auto-accept-edits`, `auto`, and `full-access`. See [permission modes][18].
#### Interaction mode
The agent interaction style for a thread. In [the contracts][1], the values are `default` and `plan`.
#### Assistant delivery mode
Controls how assistant text reaches the thread timeline. In [the contracts][1], `streaming` updates incrementally and `buffered` accumulates text. Buffered delivery is not held until the turn completes: it spills once accumulated text would exceed 24,000 characters, and flushes at approval and user-input boundaries. See [ProviderRuntimeIngestion.ts][5].
#### Snapshot
A point-in-time view of state. The word is used in multiple layers, including orchestration, provider, and checkpointing. See [ProjectionSnapshotQuery.ts][10], [ProviderAdapter.ts][15], and [CheckpointStore.ts][19].
#### Model manifest
The per-driver list of current model slugs that decides which models land in the model picker's legacy section. Bundled at `apps/server/src/provider/model-manifest.json` and refreshed at runtime from the same file on `main`, so classification updates ship as commits instead of releases. See the [provider architecture][16] model manifest section.
### Checkpointing
Checkpointing captures workspace state over time so the app can diff turns and restore earlier points. The main pieces are [CheckpointStore.ts][19], [CheckpointDiffQuery.ts][20], and [CheckpointReactor.ts][6].
#### Checkpoint
A saved snapshot of a thread workspace at a particular turn. In practice it is a hidden Git ref in [CheckpointStore.ts][19] plus a projected summary from [ProjectionCheckpoints.ts][21]. Capture and lifecycle work happen in [CheckpointReactor.ts][6].
#### Checkpoint ref
The durable identifier for a filesystem checkpoint, stored as a Git ref. It is typed in [the contracts][1], constructed in [Utils.ts][22], and used by [CheckpointStore.ts][19].
#### Checkpoint baseline
The starting checkpoint for diffing a thread timeline. This flow is surfaced through [RuntimeReceiptBus.ts][13], coordinated in [CheckpointReactor.ts][6], and supported by [Utils.ts][22].
#### Checkpoint diff
The patch difference between two checkpoints. Query logic lives in [CheckpointDiffQuery.ts][20], diff parsing lives in [Diffs.ts][23], and finalization is coordinated by [CheckpointReactor.ts][6].
#### Turn diff
The file patch and changed-file summary for one turn. It is usually computed in [CheckpointDiffQuery.ts][20], represented in [the contracts][1], and recorded into thread state by [projector.ts][4].
### Appearance
#### Environment theme
A theme an environment's machine publishes for clients to follow, one file per theme under `themes/` in that environment's state directory; the filename is the theme id. [environmentTheme.ts][25] watches the directory and streams the set over `subscribeServerConfig`; clients render each as a library card, generating a full palette when the file carries seed colors and using the palette directly when it is a standard exported theme file. A desktop that retints its apps when the system theme changes rewrites its file, so T3 Code follows along without a restart. See [environment-theme.md][26].
#### Default theme
The environment's theme, held in its `settings.json` as `defaultTheme` (with `defaultThemeSetAt`
as the set-generation) and set with `t3 theme set <id>`. Web and desktop clients apply each set
once — live when connected, on the next connect otherwise — so setting it switches them, while a
theme a user picks in Settings afterwards sticks until the next set; mobile keeps its own
appearance settings. Naming a published [environment theme](#environment-theme) is how a desktop
ships T3 Code already matching it.
## Practical Shortcuts
- If you see `requested`, think "intent recorded".
- If you see `completed`, think "result applied".
- If you see `receipt`, think "async milestone signal, for tests".
- If you see `checkpoint`, think "workspace snapshot for diff/restore".
- If you see `quiesced`, think "all relevant follow-up work has gone idle".
## Related Docs
- [Architecture overview][24]
- [Provider architecture][16]
- [Permission modes][18]
- [Workspace layout][2]
[1]: ../../packages/contracts/src/orchestration.ts
[2]: ./workspace-layout.md
[3]: ../../apps/server/src/vcs/GitVcsDriverCore.ts
[4]: ../../apps/server/src/orchestration/projector.ts
[5]: ../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
[6]: ../../apps/server/src/orchestration/Layers/CheckpointReactor.ts
[7]: ../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
[8]: ../../apps/server/src/orchestration/decider.ts
[9]: ../../apps/server/src/orchestration/commandInvariants.ts
[10]: ../../apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
[11]: ../../apps/server/src/orchestration/Layers/ProjectionPipeline.ts
[12]: ../../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
[13]: ../../apps/server/src/orchestration/Services/RuntimeReceiptBus.ts
[14]: ../../apps/server/src/provider/Layers/ProviderService.ts
[15]: ../../apps/server/src/provider/Services/ProviderAdapter.ts
[16]: ./providers.md
[17]: ../../apps/server/src/provider/Layers/CodexAdapter.ts
[18]: ../user/permission-modes.md
[19]: ../../apps/server/src/checkpointing/CheckpointStore.ts
[20]: ../../apps/server/src/checkpointing/CheckpointDiffQuery.ts
[21]: ../../apps/server/src/persistence/Services/ProjectionCheckpoints.ts
[22]: ../../apps/server/src/checkpointing/Utils.ts
[23]: ../../apps/server/src/checkpointing/Diffs.ts
[24]: ./overview.md
[25]: ../../apps/server/src/environmentTheme.ts
[26]: ../user/environment-theme.md
Terms whose meaning matters across T3 Code. Architecture and lifecycle constraints belong in the
[overview](./overview.md), not in these definitions.
## Workspace and conversation
| Term | Meaning |
| -------------- | ------------------------------------------------------------------------------------------------- |
| Environment | One running server and the machine, credentials, workspace access, and state it owns. |
| Client | A web, desktop, or mobile UI connected to an environment. The desktop app can also host a server. |
| Project | An environment-local workspace record rooted at a directory. |
| Workspace root | The project's base filesystem directory on the environment. |
| Worktree | A separate Git checkout a thread can use instead of the project's main checkout. |
| Thread | The durable conversation and work history for a project. It survives provider process exits. |
| Turn | One user-to-agent work cycle. Provider work can finish before checkpoint and diff work settles. |
| Activity | A non-message timeline item, such as a tool action, approval, or failure. |
| T3 home | The base data directory. Runtime state normally lives under its `userdata` directory. |
## Orchestration
| Term | Meaning |
| ----------------------- | -------------------------------------------------------------------------------------------- |
| Command | A request to change domain state. Accepting it does not mean its side effects have finished. |
| Event | A persisted fact produced by a command. |
| Decider | The pure logic that turns a command and current state into events. |
| Projection / read model | A view of current state derived from persisted events. |
| Projector | The logic that applies events to a read model. |
| Reactor | A worker that performs follow-up work in response to recorded intent or runtime signals. |
| Command receipt | A durable record of a command's result, used to make retries idempotent. |
| Runtime receipt | A test-only signal that an asynchronous milestone completed. |
| Quiesced | The relevant follow-up workers have finished, beyond the provider turn merely ending. |
## Providers and checkpoints
| Term | Meaning |
| ------------------- | ------------------------------------------------------------------------------------------------------------ |
| Provider | The agent runtime T3 Code controls, such as Codex or Claude Code. |
| Driver | The integration for a provider kind. |
| Provider instance | One configured provider, with its own settings and lifecycle. Multiple instances can use the same driver. |
| Adapter | The boundary translating a provider's native protocol into T3 Code operations and events. |
| Session | The provider runtime attached to a thread. A session can be stopped and resumed without deleting the thread. |
| Runtime mode | The thread's permission policy. See [permission modes](../user/permission-modes.md). |
| Interaction mode | How the agent approaches the task, such as planning. Separate from permission policy. |
| Checkpoint | A saved workspace state used for diffs and restore, stored as a hidden Git ref. |
| Checkpoint baseline | The workspace state captured before the work being compared. |
| Turn diff | The workspace changes attributed to one turn. |
+20 -45
View File
@@ -1,50 +1,25 @@
# Mobile development lifecycle
Ordinary component changes use Metro Fast Refresh. The connection runtime uses
a stable development-only atom runtime whose writable layer atom receives the
newly evaluated Effect layer. Its module accepts the update only after installing
that layer. Existing subscribers observe the new context, and Effect releases the
previous runtime scope without restarting React Navigation. Production uses an
ordinary `Atom.runtime` without this hot-update boundary.
The [connection runtime's HMR boundary](../../apps/mobile/src/lib/hot-swappable-atom-runtime.ts)
keeps a stable atom runtime and replaces its Effect layer through a writable atom.
It accepts the update only after installing the new layer. Otherwise importers
retain the old behavior even though Metro reports a successful refresh.
Replacing the atom registry itself disposes its old nodes; replacing the managed
runtime starts its asynchronous disposal. These modules use normal Metro update
propagation. The app does not call `DevSettings.reload` during their replacement.
React can still reset state when its normal Fast Refresh rules require it.
Do not reset the shared atom registry to refresh a connection-runtime edit. Reset
removes listeners from mounted consumers that Metro has no reason to rerender.
When the registry or managed-runtime module itself changes, normal Metro propagation
disposes its old resources. This boundary does not make arbitrary module-level atom
families safe to hot-swap. Production uses an ordinary atom runtime.
Do not reset the shared registry to clean up a connection-runtime edit: registry
reset removes listeners from unedited mounted consumers. Do not self-accept a
runtime module while leaving importers attached to its old implementation. A
hot-update boundary must install fresh behavior through the existing reactive
dependencies. These boundaries do not make every module-level atom family in the
app hot-swappable; new runtime singletons still need explicit ownership. Editing
the registry or managed runtime can still rebuild a much larger dependency graph
than an ordinary component or connection-runtime edit.
[Environment supervisor scopes](../../packages/client-runtime/src/connection/registry.ts)
are children of the registry scope. The per-environment map supports targeted
shutdown, but a supervisor created after its cleanup runs would escape it. A closed
parent scope also closes late arrivals, preventing interrupted startup or runtime
replacement from leaving a WebSocket alive outside the new registry.
Environment supervisor scopes are children of the connection registry scope.
The registry's per-environment map supports targeted shutdown, but it cannot be
the sole owner: a supervisor created after that map's finalizer has run must
still inherit the closed parent scope. Otherwise interrupted startup or runtime
replacement can leave a session and WebSocket alive outside the current registry.
The compact Home list owns its minute-based presentation clock in a focus effect.
Blur clears the interval without a render-driving focus subscription; focus
refreshes the clock immediately. Other prop or state changes can still render
the hidden list. Exact snooze-expiry timers remain active, and the visible iPad
sidebar keeps its own minute updates.
Connection and runtime projections are shared per environment. Thread selection
consumers should read those atoms instead of repeatedly parsing the same socket
URL or constructing new connection objects during each render.
The Uniwind dependency patch still recompiles CSS on Metro updates so newly used
classes are discovered. It fingerprints the generated native stylesheet and
theme list, then skips development-only global invalidation when that output is
unchanged. A changed stylesheet or theme list still resets the style caches and
notifies subscribers. The digest is committed only after initialization succeeds.
Web and production retain their existing initialization behavior.
After installing or changing the Uniwind patch, restart Metro once with
`vp run dev:client:reset` from `apps/mobile`. pnpm gives patched packages new
filesystem paths, and cached transforms can otherwise retain references to the
previous package. Ordinary development starts should retain the transform cache.
The [Uniwind patch](../../patches/[email protected]) still compiles CSS on Metro
updates so newly used classes are discovered. It skips global style invalidation
only when the generated stylesheet and theme list are unchanged. Skipping compilation
would lose new classes; invalidating every consumer for unchanged output makes an
ordinary component edit refresh the whole app. The fingerprint is recorded only
after initialization succeeds.
+44 -111
View File
@@ -1,123 +1,56 @@
# Mobile navigation
The iOS Home and thread routes share the root native stack in
[`Stack.tsx`](../../apps/mobile/src/Stack.tsx). Keeping them in one navigation
controller lets UIKit animate the header between routes. The iPad sidebar owns
a separate, single-screen stack; Android uses its own in-flow headers.
Home and thread routes share the [root native stack](../../apps/mobile/src/Stack.tsx)
so UIKit can animate the header within one navigation controller. The iPad sidebar
has its own stack. Splitting Home and threads between controllers loses that
continuous transition.
Home and the iPad sidebar render their brand and connection status through
`headerTitle`, with `Threads` retained as the route title. The editor-style native
bar aligns that title on the leading side. Do not model the brand as a toolbar
button: on iOS 26.5 UIKit morphs a background-free custom leading item's rectangle
into the next screen's glass back button, even with distinct item identifiers.
Using the title slot lets the brand and native back button animate separately.
## UIKit constraints
The connection-status title has a maximum width based on its header's width and
trailing actions. A long environment name or larger text must not push Settings
into UIKit's overflow menu. Keep the full status as the accessibility label
while visually truncating it. The iPad sidebar uses its pane width, not the full
window width.
The [react-native-screens patch](../../patches/[email protected])
preserves behavior that is easy to break when changing native headers:
On iOS 26, UIKit does not recognize Fabric's custom text views when shaping the
native scroll-edge fade. The screens patch gives custom title subviews an empty,
non-interactive native label matching their bounds. This supplies the fade's
geometry without drawing anything or turning the title back into a toolbar item.
Check the top scroll fade as well as push/pop when changing these title views.
- The brand belongs in `headerTitle`. On iOS 26.5, UIKit morphs a background-free
leading toolbar item's rectangle into the next screen's glass back button,
even when the items have different identifiers.
- UIKit's scroll-edge fade does not recognize Fabric text views. An empty native
label supplies the custom title's geometry. Removing that apparently unused
view changes the fade.
- Leading, trailing, and center item groups need independent caches. A button can
belong to only one group; rebuilding an unchanged group can pull its buttons
out of a group UIKit is still animating. Cache ownership also includes the
header config, whose event emitter changes on remount.
- A horizontal ScrollView at its leading edge must yield to the full-screen back
gesture. Upstream gives every horizontal ScrollView priority, so swiping back
on a code block or table can only bounce its content.
The react-native-screens patch caches leading, trailing, and center item groups
independently. A button can belong to only one group: constructing another group
with the same button removes it from the previous one. Unrelated menu updates
must therefore preserve the other groups while UIKit may be animating them.
Each cache includes the owning header config, its item values, and custom native
item identities, so changed content or remounted event emitters still rebuild.
Custom header identifiers require native code generation and a new mobile build;
an over-the-air JavaScript update alone is insufficient. The Android view manager
implements the generated identifier setter as a no-op because this behavior is
specific to iOS 26 and later.
After changing a dependency patch, refresh CocoaPods before rebuilding an
existing iOS project. pnpm installs each patch hash in a different directory;
an old Pods project can keep compiling the previous directory even though Metro
and `apps/mobile/node_modules` resolve to the new patch.
`ControlPillMenu` resolves semantic icon colors through `withUniwind` and supplies them to every
iOS `MenuView` action, including nested actions. The menu library's Fabric bridge converts a missing
`imageColor` to transparent, so callers should use this wrapper instead of
rendering `MenuView` directly. Explicit colors are preserved, and destructive
actions default to the theme's danger foreground color. Native stack header menus
use a separate implementation and do not need this workaround.
The patch adds native header props that require code generation and a new binary.
Patch rebuild guidance lives in the
[mobile development README](../../apps/mobile/README.md#development).
## Native media presentations
`PresentationSource` in `NativePresentation` registers a thumbnail for AVKit,
image zoom transitions, and UIKit's share sheet. Wrap the thumbnail as its single child
and pass the stable identifier to the presentation. The registry keeps weak
references to source views; recycled or compact composer thumbnails can register
the same identifier. Identifiers must distinguish simultaneously visible attachments.
The source registration does not own the preview. Android uses a regular view.
iOS delegates full-screen video to [AVKit](../../apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift)
and images and documents to [Quick Look](../../apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift).
Each framework owns its controls and transition. A separate UIKit zoom transition
prevents AVKit's native Close action from exiting full screen and interferes with
Quick Look's interactive return to its thumbnail. The AVKit entry selector is
guarded, with standard modal presentation as the fallback.
On iOS, video previews mount `AVPlayerViewController` temporarily inside the
registered source and enter full screen through AVKit. AVKit
owns that zoom, its playback controls, Close button, and interactive dismissal.
Do not replace AVKit's transition with `preferredTransition`: in the iOS 27
simulator, that leaves native Close unable to exit full screen. When the source is unavailable,
the player uses a standard modal presentation. Programmatic entry uses the same
guarded `enterFullScreenAnimated:completionHandler:` selector as Expo Video;
if that selector is unavailable, the player also falls back to a standard modal.
[Thumbnail registration](../../apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift)
holds weak view references for transition and share-sheet anchors. It does not own
the preview; a source row can disappear while a native presentation is open.
Identifiers must distinguish attachments that are visible at the same time.
Native promises complete after dismissal so callers keep local file leases until
the preview or share flow has finished.
`FilePreviewModal` resolves image and PDF sources from a URI, a signed environment asset,
or a retained composer file. On iOS, Quick Look owns image and document layout, controls,
zooming, sharing, and interactive dismissal. Its delegate supplies the registered thumbnail
and its bounds for Quick Look's source-view zoom. Do not layer `preferredTransition` or
another image scroll view over that presentation: Quick Look coordinates its image gestures
with the return to the thumbnail. Missing sources use the standard transition, and Reduce
Motion disables animation. A pending programmatic Close waits until the current presentation
or cancelled dismissal has settled before starting another transition.
Treat a dismissal request as pending until UIKit finishes its current transition.
Starting another dismissal while presentation or an interactive dismissal is
settling can strand the controller. Video cleanup restores the previous audio
configuration only if it still matches the preview's configuration. It must not
deactivate the shared audio session, which may belong to another player or recorder.
The shared native presenter copies original bytes into its own temporary directory and
removes that copy after dismissal. Network downloads write to disk, and sharing never edits
the source attachment. Draft images use their stored upload data rather than a potentially
expired picker URI. No React Navigation route or custom transition animator is needed.
The same viewer handles message images, markdown images, PDF attachments and links,
composer thumbnails, and workspace image previews. The workspace PDF web preview has an
Open PDF action for the native viewer. Android retains its image viewer and uses the
system chooser for PDFs. Saving images on iOS uses the add-only photo-library permission.
Received videos open directly from their signed asset URL. AVKit handles buffering;
the client does not download the entire file or show a separate opening overlay before
presentation. The URL is captured once per preview so credential refresh does not
restart playback. Saving or sharing still downloads the original file.
The native presentation promise completes after dismissal. Local draft previews
hold their file lease until that promise settles. The iOS preview component requests
native dismissal when its source screen unmounts. Playback pauses in the background.
AVPlayer activates audio as playback starts. The presenter pauses and releases
its own player on close, then restores the previous audio-session configuration
if no other component changed it during playback. It does not deactivate the
shared session, which may still serve another player or recorder. Android retains
its React Native modal and Expo Video player.
`shareFileFromSource` uses the same source registration to anchor UIKit's activity
controller. Its promise completes when the native share flow finishes, keeping
the existing attachment lease and foreground handoff active for that duration.
Android uses Expo Sharing. On iOS, received and draft video attachments expose
Save or share through `VideoAttachmentMenu`. The attachment supplies the source
identifier, and the native share presentation inherits its appearance. AVKit's
iOS playback controls do not expose a public custom-share-action API.
Video attachment thumbnails use Expo Video's native frame extraction and Expo Image.
Received attachments use their signed asset URL; drafts retain and resolve their local file
until extraction ends. Extraction is serial; temporary players never play or change audio settings. Leaving the screen cancels
pending work; a 15-second limit prevents an unreachable source from holding up the queue.
The client keeps at most 32 native images, each bounded to 480 pixels per side, keyed by
environment and attachment identity rather than expiring URLs. Images still displayed keep
their own references when evicted from that cache.
The asset HTTP route supports single byte ranges for videos so iOS can read metadata and
frames without first downloading the whole file. Normal downloads keep their full response;
unsupported ranges and conditional `If-Range` requests also fall back to the full file.
An older environment without range support may still show the play-card fallback. Thumbnail
failure never disables playback or sharing.
Video playback holds the first signed asset URL for the lifetime of the preview.
Following credential refreshes reactively would restart playback. Quick Look copies
original bytes into its own temporary directory so preview and sharing cannot
mutate a draft or workspace file.
+19 -34
View File
@@ -1,40 +1,25 @@
# Model manifest
`apps/server/src/provider/model-manifest.json` is bundled for offline startup and fetched from
`main` at runtime. A remote fetch replaces the in-memory and on-disk cache only after generic
catalog references and provider-owned adapter data validate. A failed or invalid fetch keeps the
last successful remote manifest. The bundle is used only when no valid remote cache exists.
The [bundled manifest](../../apps/server/src/provider/model-manifest.json) allows
offline startup; fetching it from `main` lets model metadata change between
releases. Failed fetches or invalid data preserve the last usable manifest.
Remote data must pass both catalog-reference validation and the owning provider's
adapter validation before replacing the cache.
The top-level provider catalog is generic: models contain presentation metadata, aliases, status,
an optional badge, and a reusable capability profile. The profile and model `adapter` fields are
opaque until the owning provider validates them with its own allowlisted schema.
A newer bundle outranks the cached remote manifest by `updatedAt`, so a release can
correct model data before the next successful fetch. Bump `updatedAt` whenever the
file changes. Fetch time cannot establish which copy contains the newer edit.
Claude Code uses the manifest as its complete built-in model catalog. To add a Claude model that
uses an existing profile, add one object to `providers.claudeAgent.models`. Do not add a test or
change application code. Add or change a profile in the same JSON file only when the model exposes
a capability combination that does not already exist.
Generic catalog data describes presentation and capabilities. Each provider owns
its adapter schema and dispatch mappings. Claude uses the manifest for its entire
built-in catalog. Adding a model with an existing capability profile is a JSON
edit; a new profile is needed only for a new capability combination. Codex still
gets its model list from its app server.
`currentModels.claudeAgent` is retained as a frozen compatibility field for releases that predate
catalog discovery. New Claude models do not need to be added there. Codex still discovers models
from its app server and uses `currentModels.codex` only as a legacy-classification overlay.
`currentModels.claudeAgent` is frozen for releases that predate catalog discovery.
Do not extend it when adding Claude models. Codex uses `currentModels.codex` as a
legacy-classification overlay for discovered models.
Claude model entries support:
- `aliases`, `status`, `badge`, and `profile` for client presentation and selection.
- `adapter.claudeCode.minVersion` and `maxVersionExclusive` for installed-runtime compatibility.
- Profile-level effort mappings, model suffixes, and context-window metadata for dispatch.
## Test policy
Changing model data does not require tests. Do not add or update tests for a model slug, display
name, alias, legacy status, version boundary, badge, or profile assignment. The bundled manifest is
configuration and is validated by its schema when imported.
Add tests only when implementation behavior changes:
- Fetching, caching, fallback, or schema-version handling changes in the manifest service.
- Provider-neutral profile resolution gains new semantics.
- A provider adapter gains a new compatibility or dispatch mapping type.
Resolver tests must use synthetic providers and model names so normal JSON edits never create test
churn.
Model data is schema-validated configuration. Tests should cover resolver, cache,
and adapter semantics with synthetic model names, so adding a model never requires
tests that repeat the configuration.
+50 -153
View File
@@ -1,170 +1,67 @@
# Architecture
> For maintainers. Using T3 Code? See [docs/user](../user/).
T3 Code keeps execution in the environment that owns the workspace. Web, desktop, and mobile
clients control it over authenticated RPC. A remote client must never substitute its own filesystem,
provider credentials, or machine state for the environment's. The desktop app bundles a server,
but its renderer follows the same boundary.
T3 Code is a server runtime that owns agent sessions, workspaces, and version control, plus clients
(web, desktop, mobile) that talk to it over one authenticated Effect RPC WebSocket. The server is the
execution boundary: every provider process, terminal, git operation, and filesystem read happens
there, never in the client.
## Ownership boundaries
```
┌────────────────────────────────────────────────┐
│ Clients: apps/web, apps/desktop, apps/mobile │
│ shared runtime: packages/client-runtime │
│ connection supervisor, RPC session, Atom state│
└──────────────────┬─────────────────────────────┘
│ Effect RPC over WebSocket (/ws)
│ contract: packages/contracts
┌──────────────────▼─────────────────────────────┐
│ apps/server │
│ orchestration engine (event-sourced) │
│ provider driver registry (5 built-in drivers) │
│ checkpointing, VCS, terminals, filesystem │
└──────────────────┬─────────────────────────────┘
│ per-driver transport
┌──────────────────▼─────────────────────────────┐
│ Agent CLIs: Codex, Claude, Cursor, Grok, │
│ OpenCode │
└────────────────────────────────────────────────┘
```
Provider processes, terminals, Git, and project files belong to the server. Shared connection and
domain state belongs in `packages/client-runtime`; clients supply platform services and UI.
Keeping that logic shared prevents reconnect and multi-environment behavior from diverging between
web and mobile. See [connection runtime](./connection-runtime.md) and
[remote environments](./remote.md).
## The RPC boundary
The [RPC contract](../../packages/contracts/src/rpc.ts) is the boundary between independently
versioned clients and servers. Subscriptions send the state a client needs, so a client viewing one
thread does not pay for every thread's history. Authentication of a socket does not authorize every
method on it. See [environment auth](./environment-auth.md).
The client/server contract is an Effect RPC group, not a hand-rolled push protocol. [`rpc.ts`][rpc]
declares `WS_METHODS` and assembles `WsRpcGroup`; each member is either unary or a server stream
(`stream: true`). Streaming members such as `orchestration.subscribeShell`,
`orchestration.subscribeThread`, `subscribeServerConfig`, and `terminal.attach` replace what used to
be a broadcast push bus: a client subscribes to what it needs and the server pushes only on that
subscription.
Provider-specific behavior belongs behind an adapter. Orchestration works with normalized commands
and events, so adding a provider should not require branches throughout the domain or clients.
See [provider constraints](./providers.md).
[`ws.ts`][ws] serves the group. `websocketRpcRouteLayer` mounts `GET /ws`, authenticates the upgrade
through `EnvironmentAuth.authenticateWebSocketUpgrade`, then hands the socket to
`RpcServer.toHttpEffectWebsocket`. Authorization is per method: `RPC_REQUIRED_SCOPE` maps each method
to a scope, and `authorizeEffect`/`authorizeStream` enforce it. Holding a valid socket is not
authorization to call everything on it. See [environment-auth.md](./environment-auth.md).
## Durable intent and side effects
On the client, [`session.ts`][session] opens the socket and builds the typed client.
`RpcSessionFactory` is the service; a session exposes `client`, `initialConfig`, `ready`, `probe`,
and `closed`. It performs one attempt and does not retry. Retry, backoff, and offline policy belong
to the connection supervisor.
The event log is the source of truth for orchestration state. The
[engine](../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts) serializes commands;
the [decider](../../apps/server/src/orchestration/decider.ts) produces events without performing
provider or filesystem work. Events, persisted projections, and the accepted command receipt commit
in one database transaction. The in-memory state changes and subscribers receive events after that
commit. This keeps command retries idempotent and prevents a persisted projection from getting
ahead of the event log.
## Shared client runtime
Reactors perform side effects after intent has been recorded, then feed results back through
commands. A command acknowledgement therefore means the intent committed, not that the provider,
checkpoint, or other follow-up work finished. Keep external I/O out of the decider and the database
transaction.
`packages/client-runtime` holds every non-visual client concern: connection lifecycle,
authentication, RPC, cached environment data, and domain state as Atom factories. Web and mobile
compose it the same way (`apps/web/src/connection/runtime.ts` and
`apps/mobile/src/connection/runtime.ts` mirror each other, differing only in platform-specific
background-activity layers) and differ beyond that only in the platform layer they supply and the
UI they build on top. React components never construct transports, retry loops,
or RPC clients. See [connection-runtime.md](./connection-runtime.md).
Persisted events must remain decodable on replay. Changing a schema affects old environments at
startup as well as live RPC traffic. Compatibility work must account for stored history, not just
what the newest client sends.
## Orchestration is event-sourced
## Turn completion and checkpoints
The server does not mutate app state directly. Clients dispatch typed commands; the engine turns them
into persisted events; projections derive the read model.
A turn ending and its follow-up work settling are separate milestones. The
[projector](../../apps/server/src/orchestration/projector.ts) settles the turn from its session
status. A late checkpoint or diff must not extend the recorded turn duration or keep the client
showing provider work as active.
[`OrchestrationEngine.ts`][engine] serializes this. `dispatch` offers a `CommandEnvelope` onto
`commandQueue` and awaits its result; a single worker fiber takes envelopes one at a time, so command
processing is totally ordered. For each envelope `processEnvelope`:
[Checkpoints](../../apps/server/src/checkpointing/CheckpointStore.ts) use hidden Git refs to
capture workspace state without adding commits to the user's branch. A revert must coordinate
workspace state with the provider conversation. A provider that cannot roll back its conversation
must reject that operation before changing the filesystem.
1. checks the durable command receipt, making retries idempotent;
2. runs `decideOrchestrationCommand` ([`decider.ts`][decider]) to produce events from command plus
current state, pure and side-effect free;
3. inside one SQL transaction, appends events to the event store, applies them to the in-memory read
model via [`projector.ts`][projector], projects them into persisted tables, and writes the
accepted receipt;
4. after commit, swaps in the new read model, cleans up attachments, and publishes committed events
to subscribers. Attachment cleanup failures are logged and do not reject committed commands.
## Waiting for asynchronous work
Because persistence and projection share a transaction, the read model cannot durably disagree with
the event log. On dispatch failure the engine rereads persisted events past the starting sequence and
reconciles.
Tests use [drainable workers](../../packages/shared/src/DrainableWorker.ts) to wait until both the
queue and its current item have finished. An empty queue alone does not prove the worker is idle.
Command and event names live in [`orchestration.ts`][contracts]. Some commands are client
dispatchable (`thread.create`, `thread.turn.start`, `thread.approval.respond`); others are internal
and produced only by server-side reactors (`thread.message.assistant.delta`,
`thread.turn.diff.complete`).
Runtime receipts mark specific test milestones. Their
[production layer](../../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts) is a no-op;
production behavior must use persisted state and events. These test signals are separate from the
durable command receipts that make dispatch idempotent.
A turn is complete when its session leaves `running` status, projected by
`settledTurnStateForSessionStatus` in [`projector.ts`][projector]. Checkpoint work settling later
does not define turn end.
Thread settlement is server-owned. Each server's own settings control PR and inactivity
settlement. Those keys are user preferences, so clients write them to every connected environment
(`SHARED_SERVER_SETTING_KEYS` in `packages/client-runtime/src/state/sharedSettings.ts`) and warn
when a connected environment drifts.
[`ThreadSettlementReactor`][settlement] checks threads at startup, when those settings change, and
once per minute, including when no client is connected. It dispatches the guarded internal
`thread.auto-settle` command, which uses the existing settlement event lifecycle. Automatic
settlement excludes live background work and requires a comparable PR timestamp for immediate PR
settlement. The command also rejects any later event for its thread after the reactor's snapshot.
Clients render the persisted settlement state and do not derive settlement from PR or inactivity
state. A committed `thread.settled` event also lets `ProviderCommandReactor` stop an idle provider
session.
## Drainable workers
Follow-up work runs asynchronously in queue-backed workers built on [`DrainableWorker`][worker]:
[`ProviderRuntimeIngestion`][ingest] normalizes provider runtime streams into orchestration commands,
[`ProviderCommandReactor`][cmd] dispatches provider calls in response to intent events,
[`CheckpointReactor`][checkpoint] captures and reverts workspace checkpoints, and
[`ThreadSettlementReactor`][settlement] evaluates server-owned automatic settlement rules.
`DrainableWorker` pairs a transactional queue with a transactional count of outstanding items.
`enqueue` atomically offers and increments; processing always decrements. `drain` retries until the
count reaches zero, so a test can await "queue empty and current item finished" instead of sleeping.
Each of these four services exposes `drain` for exactly this.
Runtime receipts are a test-only mechanism. `RuntimeReceiptBusLive` in
[`RuntimeReceiptBus.ts`][receipts] publishes nothing; only the test layer is PubSub-backed. Do not
build production behavior on receipts.
## Provider drivers
Five drivers ship built in, registered in [`builtInDrivers.ts`][drivers] as `BUILT_IN_DRIVERS`:
Codex, Claude, Cursor, Grok, and OpenCode. A driver declares its kind and config schema and creates a
scoped adapter; `ProviderInstanceRegistry` owns live instances and `ProviderAdapterRegistry` resolves
an instance to its adapter, so `ProviderService` routes session and turn operations without knowing
which agent is behind them. See [providers.md](./providers.md).
## Checkpointing
Each turn is bracketed by workspace checkpoints so diffs and reverts are exact. `CheckpointStore`
captures state as hidden Git refs through the VCS driver's checkpoint operations;
`CheckpointDiffQuery` answers turn and full-thread diff requests; `CheckpointReactor` coordinates
baseline capture, completed-turn capture, diff projection, and reverting both the workspace and the
provider conversation. The storage contract is `VcsCheckpointOps` in
[`VcsDriver.ts`](../../apps/server/src/vcs/VcsDriver.ts), implemented for Git in the same directory.
## Startup
[`serverRuntimeStartup.ts`][startup] runs a fixed lifecycle: start keybindings, settings, and
reactors; publish welcome; signal command readiness (logged as `Accepting commands`); wait for the
HTTP listener via `markHttpListening`; publish ready; fork the heartbeat; then either print headless
output or open the browser. Command readiness precedes the listener, so a socket that opens can
already dispatch.
## Related
- [Workspace layout](./workspace-layout.md), [Glossary](./glossary.md)
- [Mobile navigation headers](./mobile-navigation.md)
- [Remote environments](./remote.md), [Server updates](./server-updates.md)
- [Resource telemetry](./resource-telemetry.md)
- [Product analytics](./product-analytics.md)
- [Scripts](./scripts.md), [CI gates](./ci.md)
[rpc]: ../../packages/contracts/src/rpc.ts
[contracts]: ../../packages/contracts/src/orchestration.ts
[ws]: ../../apps/server/src/ws.ts
[session]: ../../packages/client-runtime/src/rpc/session.ts
[startup]: ../../apps/server/src/serverRuntimeStartup.ts
[engine]: ../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
[decider]: ../../apps/server/src/orchestration/decider.ts
[projector]: ../../apps/server/src/orchestration/projector.ts
[worker]: ../../packages/shared/src/DrainableWorker.ts
[ingest]: ../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
[cmd]: ../../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
[checkpoint]: ../../apps/server/src/orchestration/Layers/CheckpointReactor.ts
[settlement]: ../../apps/server/src/orchestration/ThreadSettlementReactor.ts
[receipts]: ../../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts
[drivers]: ../../apps/server/src/provider/builtInDrivers.ts
See the [glossary](./glossary.md) for shared terms and the
[development runbook](../operations/development.md) for setup and checks.
+37 -100
View File
@@ -1,112 +1,49 @@
# Product analytics
T3 Code sends anonymous product events from the server to PostHog. The server
uses the first available hashed Codex account ID, hashed Claude user ID, or
installation-scoped anonymous ID as the distinct ID. It also keeps the
telemetry opt-out, event buffer, and batch delivery. Clients do not load the
PostHog browser SDK.
The server owns PostHog delivery, opt-out, and identity for every connected client.
[Identity selection](../../apps/server/src/telemetry/Identify.ts) hashes an available
provider account ID, falling back to an installation-scoped ID. This identity can
span several clients; it does not identify a browser session. Clients do not load
the PostHog browser SDK. Client-use events require an authenticated connection, so
visiting the hosted app without connecting does not count as product use.
## Client events
## Attribution boundaries
These events use the metadata from the WebSocket connection that caused them.
The metadata is not a person property or server-global current-client value.
Two clients connected to one server can report different values at the same
time.
Client dimensions belong to the event's WebSocket connection. A server-global
"current client" would misattribute simultaneous web, desktop, and mobile use.
Provider execution has its own events because a turn can outlive the requesting
connection.
| Event | Description |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `client.connected` | The server accepted an authenticated WebSocket connection. Reconnects count again. Use this event for connection diagnostics, not active-use counts. |
| `client.thread.started` | The server accepted a command that created a thread. |
| `client.turn.requested` | The server accepted a turn request. This is the standard active-use event. |
Keep client and server dimensions separate. A desktop host can serve a phone or a
remote browser, and a direct connection can cross a network. Older clients omit
metadata. Missing client values must stay unknown rather than being backfilled
from server properties. The legacy `clientType` property describes how the server
runs; use `surface` for the connected client.
`provider.turn.sent` stays a provider execution event. It does not receive
client metadata because a provider turn can continue after the requesting
client disconnects.
## Interpreting events
## Recommended properties
Use `client.turn.requested` for active-use reports. `client.connected` counts
reconnects, so network behavior can inflate it. One identity can appear in several
client groups during a period; adding those groups double-counts users.
Client properties appear on the three client events when the connected client
reports them. Older clients can omit every client property.
Provider send and completion counts need not match. Providers can emit synthetic
turns without a send request. Collection is best effort, with no scan or backfill
of provider history.
| Property | Values and meaning |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `surface` | Product client: `web`, `desktop`, or `mobile`. |
| `webDeployment` | Web delivery: `hosted` for the hosted app or `server` for web files served by a T3 server. Web only. This does not describe connection distance. |
| `clientOs` | `macOS`, `Windows`, `Linux`, `iOS`, `Android`, `ChromeOS`, `other`, or `unknown`. |
| `clientDeviceType` | `desktop`, `phone`, `tablet`, or `unknown`. This is separate from `surface`. |
| `clientBrowser` | Normalized browser family. Web only. Browser detection is best effort. |
| `clientAppVersion` | Version of the connected client. |
| `clientOsMajorVersion` | Client OS major version when the native client reports it. Initially mobile only. |
| `clientDeviceModel` | Hardware model when the native client reports it. Initially mobile only. This is not a user-assigned device name. |
| `connectionMethod` | `direct`, `ssh`, `relay`, or `unknown`. `direct` means that the client connected to the server endpoint without an SSH or relay connection. It does not mean both processes run on one machine. |
Token totals cover the main agent. Child agents and model rerouting prevent a turn
from representing one provider/model combination's full cost. For provider
comparisons, require complete usage, no observed subagents, and no mixed models;
compare matching model, effort, interaction mode, and terminal status. Aggregate
output/input ratios should divide the summed totals. Averaging per-turn ratios
lets small-input turns dominate.
Server properties appear on all events, including server boot and background
events.
Unknown counts stay absent. Partial usage contains valid observed counts but
cannot establish a whole-turn total. Keep these distinctions when changing token
normalization or building reports.
| Property | Values and meaning |
| ------------------ | -------------------------------------------------------------- |
| `serverOs` | Server process OS, normalized to the same names as `clientOs`. |
| `serverArch` | Server process architecture. |
| `serverWslDistro` | WSL distribution from `WSL_DISTRO_NAME`, when present. |
| `serverAppVersion` | T3 server version. |
| `serverMode` | Server runtime mode: `desktop` or `web`. |
## Collection boundary
## Legacy properties
Existing property meanings do not change:
- `clientType` describes how the server runs. It is `desktop-app` for a desktop
server and `cli-web-client` for a CLI web server. It does not describe the
connected client. Use `surface` and `webDeployment` for new reports.
- `platform`, `arch`, `wsl`, and `t3CodeVersion` describe the server. Use the
new `server*` names for new reports.
- `appVersion` describes the connected client. Use `clientAppVersion` for new
reports.
- Mobile connection events keep `os`, `osMajorVersion`, and `deviceModel`.
Use the new `client*` names for new reports.
## PostHog dashboard
Create one saved dashboard named `Client and platform usage`. Set
`client.turn.requested` as the event for active-use reports. A user can appear
in several client groups during one period, so do not add breakdown values to
calculate a total.
Save these insights:
| Insight | Configuration |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Active users, daily | Trends, `client.turn.requested`, unique users, daily interval. |
| Active users, weekly | Trends, `client.turn.requested`, unique users, weekly interval. |
| Active users, monthly | Trends, `client.turn.requested`, unique users, monthly interval. |
| Client usage | Trends, `client.turn.requested`, unique users. Save four filtered series: `surface = desktop`, `surface = mobile`, `surface = web` and `webDeployment = hosted`, and `surface = web` and `webDeployment = server`. Name them Desktop, Native mobile, Hosted web, and Server-served web. |
| Client OS, active users | Trends, `client.turn.requested`, unique users, breakdown by `clientOs`. |
| Client OS, turns | Trends, `client.turn.requested`, total events, breakdown by `clientOs`. |
| Client versus server OS | Table, `client.turn.requested`, breakdown by `clientOs` and `serverOs`. |
| Connection method, active users | Trends, `client.turn.requested`, unique users, breakdown by `connectionMethod`. |
| Connection method, turns | Trends, `client.turn.requested`, total events, breakdown by `connectionMethod`. |
| Mobile devices | Table, `client.turn.requested`, filter `surface = mobile`, breakdown by `clientOs`, `clientOsMajorVersion`, and `clientDeviceType`. |
| Client version adoption | Trends, `client.turn.requested`, unique users, breakdown by `clientAppVersion`. |
| Server version adoption | Trends, `client.turn.requested`, unique users, breakdown by `serverAppVersion`. |
| Missing metadata | Table or SQL insight that shows the percentage of `client.turn.requested` events where each of `surface`, `clientOs`, `clientDeviceType`, `clientAppVersion`, and `connectionMethod` is absent. Track `webDeployment` and `clientBrowser` only within `surface = web`. |
In PostHog Data management, use the event and property descriptions from this
document. Mark the recommended properties as verified. Keep `clientType`
visible with its legacy description so old reports remain understandable.
## Collection and release boundary
Client values are best effort. Invalid values are ignored and never reject a
connection. Browser clients use user-agent data for broad OS, browser, phone,
and tablet groups. They do not infer CPU architecture or an exact OS version
from `navigator.platform`.
This change does not collect URLs, tokens, prompts, IP addresses, or
user-assigned device names. It measures authenticated product use. It does not
measure a person who visits the hosted app without connecting to a server.
The new fields start with the first client and server release that contains
this metadata path. Historical events cannot reliably identify the client OS,
hosted web use, device type, or connection method when the old client did not
send those fields. Reports must treat missing values as pre-release or older
client data instead of backfilling them from server fields.
Keep analytics payloads to product metadata and normalized measurements. Do not
send prompts, authentication material, raw provider payloads, user-assigned device
names, or conversation identifiers. Client metadata is best effort; invalid values
must not reject a connection. PostHog person profiles remain disabled.
+86 -165
View File
@@ -1,188 +1,109 @@
# Provider architecture
# Provider constraints
> For maintainers. Using T3 Code? See [docs/user](../user/).
Orchestration records intent and state without knowing which provider runs a thread. Provider
protocols, account ownership, permissions, and capabilities belong at the
[adapter boundary](../../apps/server/src/provider/Services/ProviderAdapter.ts). Normalize there
instead of spreading provider checks through reactors and clients.
A provider is the agent runtime that does the actual work. T3 Code supports several, and the
orchestration layer does not know which one is behind a thread.
A driver kind identifies an integration; an instance identifies one configuration and account
lifecycle. Route work by instance, so two accounts using the same driver do not share mutable
session or catalog state.
## Built-in drivers
## Process and account isolation
[`builtInDrivers.ts`][drivers] exports `BUILT_IN_DRIVERS` with five entries:
T3-managed OpenCode chat uses one server per thread. Its MCP registrations are directory-scoped, while
T3's MCP connection is thread-scoped. Sharing a chat server between threads in one directory would
let them replace each other's connection. Catalog and text-generation work can share the
[instance-owned helper](../../apps/server/src/provider/OpenCodeServerOwner.ts), which closes
after an idle period. External OpenCode servers remain externally owned and can require an
external restart to pick up configuration changes.
| Driver kind | Driver source |
| ------------- | --------------------------------------- |
| `codex` | [`Drivers/CodexDriver.ts`][codex] |
| `claudeAgent` | [`Drivers/ClaudeDriver.ts`][claude] |
| `cursor` | [`Drivers/CursorDriver.ts`][cursor] |
| `grok` | [`Drivers/GrokDriver.ts`][grok] |
| `opencode` | [`Drivers/OpenCodeDriver.ts`][opencode] |
OpenCode also stores persistent approval grants per directory. Automatic full-access replies use
`once` so they cannot widen a supervised thread's permissions on a shared external server.
See the [adapter](../../apps/server/src/provider/Layers/OpenCodeAdapter.ts).
Each driver declares its `driverKind`, a `configSchema`, and a `create` function that builds an
adapter in a child scope. Adapter implementations live beside them in
`apps/server/src/provider/Layers/` (`CodexAdapter.ts`, `ClaudeAdapter.ts`, and so on) and conform to
[`ProviderAdapter.ts`][adapter]. Read the driver plus its adapter to see how a specific agent's
transport, config, and event shapes are mapped.
Antigravity separates account profiles per instance while sharing installed executables across the
environment. It forces file-based credential storage because the native macOS keychain entry would
otherwise be shared across instances. The launch environment removes ambient Google credentials,
so an instance cannot silently use another account or billing project. The agent also resolves
its user-global skill directories under that profile, so the profile links those two directories
back to the user's real `~/.gemini`; MCP servers, hooks, and rules there stay out of the profile.
See [profile isolation](../../apps/server/src/provider/antigravityAuthSupport.ts).
## Registry and routing
The [Antigravity installer](../../apps/server/src/provider/AntigravityInstallation.ts) outlives
client connections and provider-instance rebuilds. Releases are immutable, with an atomic pointer
selecting the version for new processes. Running processes hold leases on their version. Updates
and removal must respect those leases instead of replacing executables under a running agent.
Two registries separate configuration from live processes:
## Setup must not happen as a health-check side effect
- [`ProviderInstanceRegistry`][instances] keys configured instances by `ProviderInstanceId`. Creating
one looks up the driver by `driverKind`, decodes `entry.config` with that driver's schema, opens a
child scope, and calls `driver.create`.
- [`ProviderAdapterRegistry`][registry] resolves an instance ID to its live adapter via
`getByInstance`.
Opening a provider session can start MCP servers, run hooks, or launch a login browser.
[Grok probes](../../apps/server/src/provider/Layers/GrokProvider.ts) avoid authentication and
session creation for this reason. Antigravity likewise reserves authenticated catalog sessions for
explicit setup or model refresh; background checks use initialization only.
[`ProviderService`][service] sits on top. It combines the adapter registry with the provider session
directory to route session and turn operations for a thread, so callers name a thread, not an agent.
[Antigravity sign-in](../../apps/server/src/provider/AntigravityAuth.ts) belongs to the initiating
T3 auth session. The client carries the return URL back to the environment because the provider's
loopback listener may be on another machine. Forward only the callback for the owned pending flow;
a successful callback HTTP request is not proof that provider authentication finished. The native
process owns token exchange and storage.
Adding a driver means writing the driver plus adapter and adding it to `BUILT_IN_DRIVERS`. No
orchestration, contract, or client change is required for the common case.
Antigravity sign-out closes admission to new processes and stops existing processes before clearing account
metadata. Otherwise a helper or resumed session could retain the old account. Cached model lists
do not establish current access, and an authoritative empty catalog must clear the old list.
### Grok health check
Antigravity text-generation helpers deny tool requests, but native hooks and MCP configuration can
run before the prompt. They reject profiles with such configuration before launch. Prompt
instructions and tool denial do not create a native sandbox.
See [helper constraints](../../apps/server/src/textGeneration/AntigravityTextGeneration.ts).
`checkGrokProviderStatus` never opens an ACP session. It runs `grok --version`, then `grok models`
for login state and model slugs, then a single ACP `initialize` and reads models from
`_meta.modelState`. `authenticate` and `session/new` are skipped on purpose: `authenticate` can open
a browser login and `session/new` boots every configured MCP server, both of which made background
probes hang or surprise the user. A failed `initialize` degrades to `warning` with the CLI's model
list instead of persisting `error` over a working install. The built-in `grok-build` slug is the
CLI's product name, not an ACP model id. `applyGrokAcpModelSelection` treats it as "keep the
session's current model" and never sends it in `session/set_model`.
## Provider updates run only through the owning installer
## OpenCode server ownership and catalog
A one-click update is offered only when the resolved executable's path proves which installer owns
it. Homebrew and npm are proven by the real path (symlinks followed): a versioned keg or cask under
`brew --prefix`, or `<prefix>/lib/node_modules/<pkg>/` (Windows: the shim beside `node_modules`).
Native installer layouts and the global bin directories of pnpm, Bun, and Vite+ may match on either
the resolved path or its real target, since those installers place real files or their own symlinks
there. Anything unproven stays manual-only but still reports the version gap. npm updates pin
`--prefix` because the `npm` on `PATH` can belong to a different Node than the one that owns the
provider. Homebrew
compares against `brew info` since casks trail npm by hours; native installs share npm's version
train, so the registry stays authoritative for them.
See the [resolver](../../apps/server/src/provider/providerMaintenance.ts).
Each OpenCode provider instance owns one lazy local server for catalog discovery and
text-generation helpers through [`OpenCodeServerOwner.ts`][opencode-server-owner]. Concurrent
borrowers share startup. The server closes 30 seconds after the last borrower releases it, or
when the provider instance closes. A failed or exited process can be started again on the next
use. An externally configured OpenCode server remains externally owned.
Ownership is cached per instance and re-read immediately before an update runs. The
[runner](../../apps/server/src/provider/providerMaintenanceRunner.ts) refuses when the lock key
changed since the advisory, and reports success only when the refreshed provider is still installed
with a readable, current version.
The local server and its SDK clients use one resolved password. An explicit provider password
overrides `OPENCODE_SERVER_PASSWORD` in the spawned environment. Without an explicit password,
the client uses the password from the environment that the process inherits. External servers use
only their explicit provider password and never inherit the host's local password.
## Protocol traps
Every server connection must pass the authenticated `/global/health` check before inventory or
session operations start. The response must contain a valid version at or above 1.14.19. Local
owners cache this result for the lifetime of the spawned process. External actions check once when
they create their server connection, not for each model or SDK request.
Codex async questions arrive as notifications and are answered with a new user message. There is
no pending RPC response to send. Blocking questions still use the request/response path. The
[adapter](../../apps/server/src/provider/Layers/CodexAdapter.ts) distinguishes them; the
[decider](../../apps/server/src/orchestration/decider.ts) records an async answer and its user
message together.
Chat adapters keep their own server per thread. They register a thread-specific `t3-code` MCP
connection, while OpenCode stores MCP connections by directory. Sharing these chat servers
without changing MCP routing would let two threads in one directory replace each other's
connection.
An async question can outlive the turn or a server restart. The engine reads that request's
durable activity before resolving it because the in-memory command snapshot omits old activities.
Do not infer that a request has disappeared merely because it is outside the recent window.
OpenCode loads its catalog through the HTTP API when an enabled provider instance starts. The
provider registry keeps the snapshot in memory and persists it in the existing per-instance cache.
Each `subscribeServerConfig` connection refreshes all providers, so a client reconnect reloads the
OpenCode catalog from the current helper. The `serverRefreshProviders` request also refreshes it.
Periodic OpenCode probes remain disabled. OpenCode reads credentials for each inventory request,
but its native configuration files can remain cached for the lifetime of the helper process. The
helper closes 30 seconds after its last inventory or text-generation borrower releases it. A
refresh after that idle period starts a new helper and reads file changes. Repeated refreshes and
active text-generation work can extend process reuse. Changes to the provider configuration or
environment replace the instance and start a new discovery. Changes to unrelated settings only
update snapshot enrichment. Other providers retain their existing refresh policy.
Capabilities must describe what the provider can actually do. Antigravity can capture workspace
checkpoints but cannot roll back its conversation. The [checkpoint boundary](./overview.md#turn-completion-and-checkpoints)
therefore rejects revert before touching files. Native permission and question option IDs must
also survive normalization; a display label is not necessarily a valid reply.
T3 Code does not own an external OpenCode process. Native configuration changes there can require
an external reload or restart before T3 Code's next refresh sees them.
## Attachments and stored history
The shared server's idle shutdown does not clear the catalog. Failed discovery keeps the last
known models, slash commands, and skills through the registry's existing merge rules. A successful
empty inventory is authoritative. Existing threads keep their explicit model identifier and
options when catalog metadata is missing; the catalog is not permission to choose a different
model for a thread.
Attachments live outside the project workspace. [ProviderService](../../apps/server/src/provider/Layers/ProviderService.ts)
puts their environment-local paths in turn input and lets adapters choose native input formats.
A path in the prompt does not grant filesystem access. Keep provider sandbox and approval rules
in force; copying uploads into the project to bypass them changes that boundary.
## Model manifest
File attachments introduced a replay compatibility limit. Image-only clients cannot decode
file-bearing messages, and an image-only server can fail the entire environment's startup when
replaying one such event. Rollouts and downgrades must account for persisted history as well as
current client support.
The model picker's legacy section is driven by `apps/server/src/provider/model-manifest.json`, which
lists the current (non-legacy) model slugs per driver kind. The `ModelManifest` service
(`apps/server/src/provider/ModelManifest.ts`) refreshes that data from the same file on `main` via
raw.githubusercontent.com, so moving a model in or out of the legacy section is a commit, not a
release. Preference order is remote fetch, then the on-disk copy of the last successful fetch (in
the state directory), then the bundled copy. Fetches are TTL-gated, run concurrently with provider
probes, respect the `enableProviderUpdateChecks` setting, and never fail a provider check. The
Codex and Claude drivers apply the classification to every snapshot with `applyModelManifest`;
driver kinds absent from the manifest have no legacy concept.
## Attachment access
The server stores uploaded attachments in its attachment directory, outside the project workspace.
`ProviderService` adds the absolute path of each attachment to the turn text, then passes every
attachment to the provider adapter. Each adapter decides what its provider ingests natively:
- Codex, Claude, Cursor, and Grok send images as native image inputs and skip generic files. For
these providers, generic files reach the agent only as file paths in the turn text.
- OpenCode sends PNG/JPEG/GIF/WebP images, text files, and PDFs up to 20 MB as native file parts
with their real mime type. Everything else (ZIP and other binaries, image formats model APIs
reject, oversized files) falls back to the file path in the turn text, like the other providers.
Claude receives the attachment directory as an allowed additional directory. Codex keeps its
configured sandbox policy, so access depends on that policy and the selected runtime mode. OpenCode
allows all paths in full-access mode and requests approval for directories outside the workspace in
restricted modes. Cursor and Grok use their own provider permission rules.
The server does not copy attachments into a project or bypass provider approval rules. If an agent
cannot read an attachment, the user must approve the access or select a runtime mode that permits it.
Updated attachment schemas tolerate unknown attachment members, but old image-only clients still
cannot decode messages that contain file attachments. Client file-picking rollouts must account for
this limit.
Do not run an old image-only server against state that contains file attachments. Replay decodes
each persisted event before projection. A file-bearing event can make `ProjectionPipeline` bootstrap
and `OrchestrationEngine` startup fail for the entire environment, not only the affected thread.
## How provider work is requested
Clients never call a provider directly. They dispatch orchestration commands over the RPC method
`orchestration.dispatchCommand`, defined with the rest of the orchestration surface in
[`orchestration.ts`][contracts]. The client-dispatchable provider-facing commands are
`thread.turn.start`, `thread.turn.interrupt`, `thread.approval.respond`,
`thread.user-input.respond`, `thread.checkpoint.revert`, and `thread.session.stop`, plus the mode
setters `thread.runtime-mode.set` and `thread.interaction-mode.set`.
The engine persists an event for the command, and a server-side reactor performs the provider call.
Provider output comes back as internal commands such as `thread.message.assistant.delta` and
`thread.session.set`, which clients observe through `orchestration.subscribeThread`. See
[overview.md](./overview.md) for the command/event loop.
## Server-side workers
Provider work flows through three queue-backed workers. All three are built with
`makeDrainableWorker` from [`DrainableWorker.ts`][worker] and expose `drain` for deterministic test
synchronization.
1. [`ProviderRuntimeIngestion`][ingest] consumes provider runtime streams and emits orchestration
commands.
2. [`ProviderCommandReactor`][cmd] reacts to orchestration intent events and dispatches provider
calls.
3. [`CheckpointReactor`][checkpoint] captures workspace checkpoints on turn start and completion, and
performs reverts.
### Buffered assistant delivery
A thread in `buffered` assistant delivery mode accumulates assistant text instead of streaming each
delta. The buffer is not held until turn completion. In [`ProviderRuntimeIngestion`][ingest],
`MAX_BUFFERED_ASSISTANT_CHARS` is 24,000: the append that would exceed it invalidates the buffer and
spills the whole accumulated text as one delta. The buffer also flushes at interaction boundaries,
when a request opens (approval) or user input is requested, via
`flushBufferedAssistantMessagesForTurn`.
[drivers]: ../../apps/server/src/provider/builtInDrivers.ts
[codex]: ../../apps/server/src/provider/Drivers/CodexDriver.ts
[claude]: ../../apps/server/src/provider/Drivers/ClaudeDriver.ts
[cursor]: ../../apps/server/src/provider/Drivers/CursorDriver.ts
[grok]: ../../apps/server/src/provider/Drivers/GrokDriver.ts
[opencode]: ../../apps/server/src/provider/Drivers/OpenCodeDriver.ts
[opencode-server-owner]: ../../apps/server/src/provider/OpenCodeServerOwner.ts
[adapter]: ../../apps/server/src/provider/Services/ProviderAdapter.ts
[instances]: ../../apps/server/src/provider/Services/ProviderInstanceRegistry.ts
[registry]: ../../apps/server/src/provider/Services/ProviderAdapterRegistry.ts
[service]: ../../apps/server/src/provider/Layers/ProviderService.ts
[contracts]: ../../packages/contracts/src/orchestration.ts
[worker]: ../../packages/shared/src/DrainableWorker.ts
[ingest]: ../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
[cmd]: ../../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
[checkpoint]: ../../apps/server/src/orchestration/Layers/CheckpointReactor.ts
Model classification has its own [manifest constraints](./model-manifest.md). Assistant-reference
handling is documented under [citations](./assistant-citations.md).
+47 -227
View File
@@ -1,239 +1,59 @@
# Remote Architecture
# Remote architecture
> For maintainers. Using T3 Code? See [docs/user](../user/).
Each connection joins a client to one environment over HTTP and WebSocket. The
environment owns providers, execution, files, and durable state. Direct access,
Tailscale, SSH, and T3 Connect change how the client reaches that server; they do
not introduce another execution model. See
[remote access](../user/remote-access.md) for setup.
Remote environments are shipped, not planned. Direct, bearer-paired, relay-tunneled, Tailscale, and
desktop-managed SSH access all exist today. This document describes the model they share and where
each piece lives. For the user-facing setup guide see
[remote access](../user/remote-access.md).
## Identity is independent of the route
## The model
An environment keeps its ID across server restarts and endpoint changes. Saved
connections are local to a client profile; the server's identity and state are
not. A repository identity can correlate clones across environments, but never
routes work between them. A project and its threads belong to one environment.
T3 has one runtime boundary: a client talks to a T3 server over HTTP and WebSocket, and the server
owns orchestration, providers, terminals, git, and filesystem operations. Remoteness is expressed at
the connection layer, never by splitting the runtime.
[Environment ID initialization](../../apps/server/src/environment/ServerEnvironment.ts)
must publish a complete ID atomically. Repair of an empty ID file retains a
recovery file so concurrent or delayed initializers choose the same winner.
Removing that recovery state as ordinary temporary-file cleanup can change the
identity underneath an already-running server.
```text
┌──────────────────────────────────────────────┐
│ Client (desktop / mobile / web) │
│ known environments, connection supervisor │
└───────────────┬──────────────────────────────┘
│ resolves one access endpoint
┌───────────────▼──────────────────────────────┐
│ Access method │
│ direct ws/wss, relay tunnel, │
│ Tailscale serve, desktop-managed ssh │
└───────────────┬──────────────────────────────┘
│ connects to one T3 server
┌───────────────▼──────────────────────────────┐
│ Execution environment = one T3 server │
│ identity, providers, projects/threads, │
│ terminals, git, filesystem │
└──────────────────────────────────────────────┘
```
Advertised endpoints are reachability hints. Only the connecting device can
prove that a route works. In particular, a host's loopback address refers to a
different machine when another device opens it. Endpoint selection must not
silently fall back to loopback when a shareable endpoint is unavailable.
### ExecutionEnvironment
## Hosted web is a client
One running T3 server instance. It owns provider availability and auth, model availability, projects
and threads, terminal processes, filesystem access, git operations, and server settings.
The hosted web app stores its connection catalog in the browser and connects
directly to each environment. It does not proxy traffic or hold server-side
pairing state. Hosting the UI over HTTPS therefore cannot make a plain HTTP LAN
backend accessible from that browser context.
It is identified by a stable `environmentId`, persisted by the server at `<stateDir>/environment-id`
and generated on first start (`apps/server/src/environment/ServerEnvironment.ts`). Desktop, mobile,
and web all reason about the same concept.
A [hosted pairing URL](../../apps/web/src/hostedPairing.ts) identifies the backend
in its query and carries the pairing secret in its fragment. Fragments stay out
of requests to the hosted origin. The browser exchanges the secret with the
environment and strips it from its history. Moving the token into a query
parameter would disclose it to the wrong origin.
Initialization publishes a complete ID atomically. Empty or whitespace-only ID files are repaired
using a retained `<stateDir>/environment-id.recovery` file so concurrent and delayed repairs choose
the same ID. Existing nonempty ID files remain authoritative.
## Access and process ownership are different
### Known environments and connection targets
Tailscale supplies an endpoint for ordinary pairing, so it needs no separate
environment type. Authentication remains the environment's responsibility for
every route. See [environment authentication](./environment-auth.md) and the
[T3 Connect trust boundary](./t3-connect.md).
A saved client-side entry for an environment the client knows how to reach. It is not
server-authored; it is local to a device or client profile. In the hosted web app these entries are
browser-local. A hosted pairing URL can create one, but it does not give the hosted app a server-side
control plane or a copy of session state.
SSH can launch a server as well as forward a port. Desktop main owns that
lifecycle because it can spawn SSH and handle authentication prompts. The
renderer uses the forwarded endpoint through the shared connection runtime.
[SSH cleanup](../../packages/ssh/src/tunnel.ts) stops a remote server only if the
launcher owns it; a server it discovered already running must survive a client
disconnect. Reconnection restores the forward before opening the application
transport.
[`connection/model.ts`][model] defines four target tags, which are the real access taxonomy:
| Target | Used for |
| ------------------------- | ------------------------------------------------------------------------ |
| `PrimaryConnectionTarget` | The platform-managed local server (desktop backend, CLI-served web app). |
| `BearerConnectionTarget` | Any manually paired endpoint reached over direct HTTP/WebSocket. |
| `RelayConnectionTarget` | Managed T3 Connect relay tunnels. |
| `SshConnectionTarget` | Desktop-managed SSH environments. |
Bearer, relay, and SSH are persisted; primary is platform-managed. Note that Tailscale is not a
separate target kind. A Tailscale URL is paired through the ordinary bearer path in
[`onboarding.ts`][onboarding] (`preparePairingRegistration`), which accepts either a pairing URL or a
host plus pairing code. Tailscale is an endpoint provider and transport, not a distinct runtime
concept.
### AdvertisedEndpoint
A server- or desktop-authored candidate endpoint for an environment: a concrete HTTP and WebSocket
base URL pair, a default/available/unavailable marker, reachability hints (loopback, LAN, private,
public, tunnel), and compatibility hints such as whether the hosted HTTPS app can use it.
Clients treat advertised endpoints as hints, not proof that a route works from the current device.
The connection attempt decides.
The UI shows one default endpoint in the network-access summary and keeps the rest behind an advanced
list. `selectPairingEndpoint` in
[`ConnectionsSettings.tsx`](../../apps/web/src/components/settings/ConnectionsSettings.tsx) excludes
unavailable endpoints and then picks, in order:
1. the saved `defaultEndpointKey` override;
2. the first endpoint marked `isDefault`;
3. the first endpoint whose reachability is not `loopback`;
4. the first endpoint compatible with the hosted HTTPS app;
5. otherwise nothing.
There is no unconditional loopback fallback. A loopback endpoint only wins through an explicit saved
override or `isDefault`. Persist the override by stable endpoint kind rather than raw URL where
possible, since LAN addresses change with networks; Tailscale endpoints use provider-specific stable
keys (`tailscale-ip:`, `tailscale-magicdns:`).
### Endpoint providers
Endpoint providers contribute advertised endpoints without becoming part of the core environment
model: core owns environments, pairing, and connection lifecycle, and providers return normalized
`AdvertisedEndpoint` records.
Tailscale is the first provider, and T3 manages more than discovery. When `tailscaleServeEnabled` is
set, the server acquires a Tailscale serve mapping for its actual listening port at startup with
`ensureTailscaleServe` and releases it with `disableTailscaleServe` on scope close
(`apps/server/src/server.ts`, using [`@t3tools/tailscale`](../../packages/tailscale/src/tailscale.ts)).
Endpoint identifiers are synthesized in `apps/desktop/src/backend/tailscaleEndpointProvider.ts` with
`private-network` reachability.
### Hosted pairing request
A hosted pairing request is a bootstrap URL for the static web app, not a transport:
```text
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
```
The hosted app reads `host`, takes the token from the URL hash, exchanges it directly with that
backend, strips the token from browser history, and saves the environment record locally. Helpers
live in [`shared/remote.ts`](../../packages/shared/src/remote.ts) (`setPairingTokenOnUrl`,
`getPairingTokenFromUrl`, `stripPairingTokenFromUrl`) and `apps/web/src/hostedPairing.ts`.
Constraints:
- the hosted app does not proxy HTTP or WebSocket traffic;
- the backend must be directly reachable from the browser;
- HTTPS pages can only reach HTTPS/WSS backends;
- HTTP LAN endpoints keep using direct desktop or CLI pairing URLs;
- the token belongs in the hash so it is never sent to the hosted app origin.
### RepositoryIdentity and Project
`RepositoryIdentity` is a best-effort logical repo grouping across environments, used for UI grouping
and correlation only, never for routing. `Project` remains environment-local: a local clone and a
remote clone are different projects that may share a `RepositoryIdentity`, and threads bind to one
project in one environment.
## Access methods
Access answers one question: how does the client speak WebSocket to a T3 server? It does not answer
how the server got started or who manages the process.
### Direct WebSocket access
`wss://t3.example.com` or `ws://10.0.0.15:3773`, paired as a bearer target. This is the base model.
It works for desktop, mobile, and web with no client-side process management. Browser security rules
are part of it: a hosted HTTPS client cannot connect to plain `ws://` or `http://` LAN backends.
### Relay-tunneled access
Managed T3 Connect relay tunnels use `RelayConnectionTarget` and are the answer when the host is
behind NAT, inbound ports are unavailable, or mobile must reach a desktop-hosted environment. From
the client's perspective this is still an ordinary WebSocket connection; the route is mediated. The
relay Worker only brokers credentials and a managed endpoint; application traffic then flows over
the provisioned Cloudflare tunnel hostname for the life of the connection, not through the relay
Worker itself. See [t3-connect.md](./t3-connect.md).
### Tailscale access
A T3-managed `tailscale serve` mapping exposes the server on the tailnet over HTTPS, and the
resulting private-network endpoints are advertised for pairing. Connection then follows the ordinary
bearer path.
### Desktop-managed SSH access
SSH is an access and launch helper, not a separate environment type. `DesktopSshEnvironment`
([apps/desktop/src/ssh/DesktopSshEnvironment.ts][sshenv]) exposes `discoverHosts`,
`ensureEnvironment`, and `disconnectEnvironment`. It discovers targets from SSH config and known
hosts, owns password/askpass prompts, and delegates lifecycle to `SshEnvironmentManager` in
[packages/ssh/src/tunnel.ts][sshtunnel], which resolves the target, launches or reuses the remote T3
server, opens a local tunnel, checks HTTP readiness, optionally issues a remote pairing token, and
returns local HTTP/WS endpoints. Disconnect closes the tunnel and stops the remote server if the
launcher started it; a server that was already running (marked `external`) is left running.
The desktop main process owns this because it can spawn SSH, manage prompts, write launch scripts,
and clean up forwards. The renderer connects through the forwarded URL like any other environment and
needs no SSH-specific RPC path.
Failure handling is explicit: SSH auth failure surfaces before an environment is saved, remote launch
failure includes launcher output where available, forwarded-port failure leaves the environment
disconnected rather than falling back to an unrelated endpoint, and reconnect restores the SSH bridge
before reconnecting the WebSocket client.
## Launch methods
Launch answers a different question: how does a T3 server come to exist on the target machine? Keep
it separate from access.
- **Pre-existing server.** The operator already runs T3 and the client connects directly or through a
tunnel.
- **Desktop-managed remote launch over SSH.** Desktop probes the machine, launches or reuses a remote
server, forwards a port, and the renderer connects normally. The saved environment records that it
came from SSH launch for reconnect and lifecycle UX only; that metadata never changes the protocol
or the identity model.
- **Client-managed local publish.** A local server is published through the relay with
`t3 connect link`, exposing a desktop-hosted environment to mobile without router or firewall
changes.
The same `ExecutionEnvironment` can be reached several of these ways. Only the launch and access
paths differ.
## Security model
Some environments are reachable over untrusted networks, so remote-capable environments require
explicit authentication, tunnel exposure never relies on obscurity, and saved endpoints carry enough
auth metadata to reconnect safely.
WebSocket authentication is a dedicated short-lived ticket, not a token in a query string. The client
presents its long-lived bearer or DPoP credential in HTTP headers to
`POST /api/auth/websocket-ticket` ([authorization/remote.ts][authremote]), and appends only the
returned ticket as `wsTicket` on the socket URL. The server issues it through
`EnvironmentAuth.issueWebSocketTicket`; tickets are tagged `kind: "websocket"` and default to a
five-minute TTL (`DEFAULT_WEBSOCKET_TOKEN_TTL` in `apps/server/src/auth/SessionStore.ts`). The
handshake verifies the ticket, and each RPC method still enforces its own scope. See
[environment-auth.md](./environment-auth.md).
Hosted pairing is a client-side convenience only. The hosted app must not receive pairing tokens
through query parameters, must not store pairing state server-side, and must not imply that an HTTP
backend is reachable from an HTTPS browser context.
## Version coordination
Remote environments stay online while clients move to newer releases. The environment descriptor
carries the running server version and may advertise a safe replacement path, so the UI can show the
right action without making the transport responsible for process management. The connection
supervisor owns the resulting disconnect and reconnect like any other involuntary close. See
[server-updates.md](./server-updates.md).
## Future work
These remain unbuilt and are listed to keep the model honest:
- third-party tunnel products as additional endpoint providers;
- a relay-hosted OAuth callback broker (see [t3-connect.md](./t3-connect.md));
- richer multi-environment UI beyond the current connections list.
[model]: ../../packages/client-runtime/src/connection/model.ts
[onboarding]: ../../packages/client-runtime/src/connection/onboarding.ts
[authremote]: ../../packages/client-runtime/src/authorization/remote.ts
[sshenv]: ../../apps/desktop/src/ssh/DesktopSshEnvironment.ts
[sshtunnel]: ../../packages/ssh/src/tunnel.ts
Remote servers can outlive several client releases. Clients must use advertised
capabilities and handle their absence, rather than assume their own version
describes the server. Process replacement belongs to the launcher's
[update protocol](./server-updates.md); the connection runtime handles the
resulting disconnect.
+50 -394
View File
@@ -1,394 +1,50 @@
# Resource telemetry architecture
> For maintainers. Using T3 Code? See [docs/user](../user/).
Status: implemented
## Purpose
Resource telemetry replaces recurring `ps`, PowerShell, `ioreg`, and `pmset`
subprocess probes with two persistent, direct data sources:
1. a standalone Rust resource-monitor executable that reads process counters
through operating-system APIs via `sysinfo`;
2. Electron main-process APIs for Electron process metrics and host power state.
The native monitor owns bounded in-memory history. The server only merges and
summarizes that history when diagnostics requests it. Telemetry history is not
persisted to disk or continuously copied into Node.
## Why a standalone executable
The monitor is intentionally not a Node native addon.
- No N-API, `ffi-rs`, or dynamic-library ABI is loaded into the server process.
- A monitor crash cannot corrupt the Node runtime.
- The server can supervise, restart, version-check, and measure the monitor as a
normal child process.
- The same protocol works for the desktop app and the published CLI.
- Packaging is a single platform executable instead of an addon toolchain plus
Node/Electron ABI matrix.
The cost is one persistent child process and NDJSON serialization. That is a
better failure boundary than repeatedly spawning shell utilities or loading
native code into Node.
## Runtime topology
### Desktop
```text
Electron main
├─ powerMonitor
├─ app.getAppMetrics() while diagnostics is open
├─ inherited fd 4, telemetry NDJSON ─────────────┐
└─ inherited fd 5, demand-control NDJSON ◀──────┤
▼
Node server ── stdin/stdout NDJSON ── Rust resource monitor
│
├─ ResourceTelemetry Effect service
├─ background power policy projection
└─ WebSocket RPC/subscription ── diagnostics UI
```
### Web, headless, and remote server
Electron telemetry is unavailable. The native monitor still runs beside the
server and tracks the server process tree. Power fields degrade to `unknown`
instead of invoking platform shell commands.
### WSL backend limitation
Windows desktop packages currently ship the Windows resource-monitor executable.
That executable cannot run inside the Linux WSL backend, so a WSL-only backend
does not receive `resourceMonitorPath` and reports native process telemetry as
unavailable. Electron host-power telemetry remains available over the inherited
desktop pipe. Supporting native WSL process telemetry requires publishing a
Linux sidecar for each supported architecture in the Windows artifact and
converting its packaged path into the selected distro; the configuration
deliberately does not pass the Windows `.exe` into WSL as a false fallback.
## Native monitor
The executable lives in `native/resource-monitor`.
It receives schema-compatible commands on stdin and emits one JSON object per
line on stdout:
- `configure`
- `setExternalProcesses`
- `setSampleInterval`
- `setStreaming`
- `sampleNow`
- `readHistory`
- `shutdown`
- `hello`
- `snapshot`
- `historyChunk`
- `error`
The protocol version is defined by
`RESOURCE_MONITOR_PROTOCOL_VERSION` in
`packages/contracts/src/resourceTelemetry.ts`.
### Collection
The monitor keeps one `sysinfo::System` instance and refreshes it at the
power-adaptive interval selected by the server. It collects:
- PID and parent PID;
- process start time and run time;
- process name and command line;
- current and cumulative CPU usage;
- resident and virtual memory;
- cumulative process I/O counters.
On Linux, task/thread enumeration is disabled. Command lines are refreshed with
each sample so process replacements remain visible. Disabling task enumeration
avoids walking every `/proc/<pid>/task/<tid>` directory on each refresh.
### Process-tree selection
Each sample scans the accessible process table, builds the PID/PPID graph, and
retains:
- the server process;
- every descendant of the server, including provider-spawned grandchildren such
as shells, `node`, `tsgo`, language servers, and other tools;
- Electron processes supplied as explicit external roots;
- descendants of those Electron roots;
- the resource monitor itself, because it is a server child.
Process identity is `(pid, startTimeMs)`, not PID alone. Electron and native
start times are matched with a two-second tolerance because native start times
can have coarser platform resolution.
The process list is emitted in depth-first tree order so renderer collapse and
expansion preserves complete subtrees.
### Native history and streaming
Every native sample is appended to a one-hour in-memory ring bounded to 3,600
snapshots, 20,000 retained process rows, and 64 MiB of retained history bytes.
History stays in the sidecar until a `readHistory` request and is returned in
bounded chunks. The first bound reached wins, so high process counts or large
process names and command lines shorten the effective history window.
Periodic snapshot streaming is disabled by default. The server enables it only
while at least one diagnostics subscription is retained. `sampleNow` remains
available for explicit refreshes and identity validation.
The server adjusts native sampling without restarting the sidecar:
- suspended, locked, low-power, or serious/critical thermal state: 15 seconds;
- battery: 5 seconds;
- normal AC: 5 seconds in the background and 1 second while live diagnostics is
open;
- unknown or stale power: 5 seconds in the background and 1 second while live
diagnostics is open.
### Sampling limits
This is counter sampling, not syscall tracing.
- A process that starts and exits entirely between samples may not be observed.
- Cumulative CPU and I/O counters still provide accurate deltas for processes
that survive across samples.
- Exact file paths, individual write syscalls, ETW events, eBPF events, and
Endpoint Security events are outside this implementation.
Those deeper tracing systems can be added later as opt-in diagnostic modes
without changing the public `ResourceTelemetry` model.
## I/O semantics
The monitor preserves platform semantics instead of presenting all counters as
equivalent:
- Unix-like platforms report storage I/O counters exposed by `sysinfo`.
- Windows reports all process I/O bytes, not only disk bytes.
- Operating-system caches can prevent logical application reads or writes from
appearing as physical storage bytes.
The UI therefore labels these values as I/O reads and writes and exposes the
per-process `ioSemantics` value.
Group totals are observed deltas since telemetry startup. Per-process total
columns are the operating system's cumulative counters for that process.
## Electron telemetry
Electron main owns `DesktopTelemetryPublisher`.
Power events trigger an immediate snapshot. While diagnostics is closed, the
server sends the configured active and idle host-power intervals to Electron
(30 seconds and 2 minutes in the balanced profile). During those heartbeats
Electron reads:
- `powerMonitor.isOnBatteryPower()`;
- `powerMonitor.getSystemIdleTime()`;
- `powerMonitor.getSystemIdleState()`;
- `powerMonitor.getCurrentThermalState()`.
`app.getAppMetrics()` is only called while diagnostics demand is active. Its
live cadence is 1 second on AC, 5 seconds on battery, and 15 seconds while
locked, suspended, or thermally constrained.
It also listens for:
- lock and unlock;
- suspend and resume;
- AC and battery transitions;
- thermal-state changes;
- CPU speed-limit changes.
Suspension stays latched across event-driven snapshots. An explicit resume
clears it immediately; a periodic heartbeat also clears a stale latch so a
missed resume event cannot leave telemetry permanently constrained.
Electron does not expose a cross-platform low-power-mode getter, so that field
remains `unknown`.
The desktop backend is spawned with:
- fd 3 for the existing bootstrap payload;
- fd 4 for Electron-to-server telemetry NDJSON;
- fd 5 for server-to-Electron diagnostics-demand NDJSON.
These are private Electron-main/server pipes. They do not use the renderer
WebSocket and are recreated for every backend restart.
## Server Effect services
The implementation is under `apps/server/src/resourceTelemetry`.
### `ResourceMonitorBinary`
Resolves an executable from:
1. `T3CODE_RESOURCE_MONITOR_PATH`;
2. desktop bootstrap configuration;
3. bundled CLI resources;
4. local Cargo build outputs.
Unsupported platforms, missing binaries, and non-executable binaries use
schema-backed tagged errors with descriptive messages.
### `NativeTelemetryClient`
Owns the resource-monitor process and protocol.
- validates the hello/version handshake;
- sends configuration and external process roots;
- adapts the native interval from host power state;
- enables streaming only for scoped live subscribers;
- reads chunked native history on demand;
- exposes `sampleNow`;
- serializes commands;
- supervises process exit and protocol failure;
- restarts with bounded exponential backoff;
- opens a circuit after repeated failures;
- supports explicit retry;
- publishes health changes immediately.
Snapshot sequence numbers are scoped to a monitor generation. Server ingestion
uses the monitor restart count as the generation key, so sequence reset after a
restart cannot freeze telemetry.
### `DesktopTelemetryReceiver`
Reads fd 4, decodes schema-validated messages, stores the latest Electron
snapshot, and publishes desktop health. It writes diagnostics demand to fd 5
and gives the first sample a 90-second startup deadline. Once samples arrive,
the stale deadline stays beyond the slower configured host-power interval with
30 seconds of scheduling grace, so intentional 2–10 minute idle polling does
not oscillate the policy between constrained and unconstrained states. Decode
errors, protocol mismatch, control-write failure, stream failure, stale input,
and normal stream closure are represented explicitly.
### `ResourceTelemetry`
Merges native and Electron data and owns public telemetry semantics.
- calculates CPU and I/O rates from cumulative native counters;
- preserves the last native rates during desktop-only updates;
- classifies backend, Electron, and monitor processes;
- computes process depth and child relationships;
- tracks starts, exits, CPU time, and observed I/O;
- projects power data;
- acquires native streaming and Electron process metrics only for scoped live
subscribers;
- queries and replays native history only when requested;
- validates `(pid, startTimeMs)` before process signaling;
- updates history health even when no further native sample arrives.
Electron and monitor processes are visible but are not valid targets for the
existing process-signal RPC.
### History projection
`ResourceTelemetryHistory` is a pure on-demand projection. It replays raw native
snapshots to derive rates, lifecycle counters, buckets, and process summaries.
Current Electron process metrics are intentionally excluded from historical
replay so they cannot overwrite older native CPU or memory samples.
### `ResourceAttribution`
Tracks known logical application I/O separately from OS counters. Current
integration points record successful writes for:
- provider native and canonical event logs;
- the local server trace sink.
Entries contain component, operation, logical bytes, count, and elapsed time.
Future persistence paths should call `ResourceAttribution.record` rather than
adding diagnostics-specific counters.
## Background policy integration
`HostPowerMonitor` consumes `DesktopTelemetryReceiver` directly; observing host
power does not retain live resource diagnostics or invoke shell probes.
The monitor updates its latest timestamp on every Electron sample but only
publishes semantic state changes. Increasing idle seconds alone does not cause a
background-policy broadcast every second.
## Public API and UI
The WebSocket RPC surface provides:
- current snapshot;
- bounded history;
- explicit monitor retry;
- a live snapshot subscription.
The diagnostics page displays:
- aggregate CPU, memory, I/O, and process counts;
- backend, Electron, and monitor overhead groups;
- power and thermal state;
- collector health and restart information;
- CPU and I/O history;
- a collapsible live process tree;
- safe process signaling for backend descendants;
- instrumented logical application I/O.
Legacy process diagnostics RPCs are projected from the same service so they no
longer start recurring process-table commands.
## Packaging
Desktop artifact builds compile the Rust target, stage it as
`resources/resource-monitor/t3-resource-monitor[.exe]`, and pass its path to the
backend bootstrap.
CLI release jobs upload each active platform monitor artifact and copy it into:
```text
apps/server/dist/resource-monitor/<platform>-<arch>/
```
The published server package already includes `dist`, so those executables ship
with the CLI. Missing platform artifacts degrade native telemetry to
`unavailable`; the server continues running.
## Resource and failure behavior
Steady state uses:
- one native process;
- power-adaptive native counter sampling with no periodic Node snapshot stream;
- event-driven Electron power updates plus profile-driven heartbeats (30–60
seconds while active and 2–10 minutes while idle);
- no `app.getAppMetrics()` calls while diagnostics is closed;
- no telemetry database;
- no recurring shell probes;
- bounded PubSub queues and native ring history.
The diagnostics page exposes the monitor's own process resource usage and
collection duration so the observer's cost is measurable.
Failures are isolated:
- native failure does not stop the server;
- Electron telemetry loss does not stop native telemetry;
- schema/version errors are visible in health;
- repeated native failures stop automatic restart churn until explicit retry;
- server and desktop shutdown close their respective streams and child process
scopes.
## Future integration points
High-value follow-up work can use the existing service boundaries:
- opt-in file-path attribution through platform-specific tracing;
- process lifecycle events to reduce the chance of missing very short-lived
children;
- additional `ResourceAttribution` instrumentation for databases, checkpoints,
caches, and file synchronization;
- exported diagnostic bundles;
- adaptive sample intervals based on diagnostics visibility and active work.
These additions should preserve the current rules: direct platform APIs,
schema-validated boundaries, explicit metric semantics, bounded retention, and
no mandatory telemetry persistence.
# Resource telemetry
Process counters come from a [standalone Rust monitor](../../native/resource-monitor/src/main.rs)
using `sysinfo`. Electron main supplies host power and Electron process metrics.
Keeping native collection outside Node isolates collector crashes and avoids a
Node/Electron addon ABI matrix. Desktop and CLI servers use the same child-process
protocol. A missing or failed collector leaves the server running.
## Collection cost
The native child owns sampling and bounded in-memory history. The server requests
continuous snapshots only while diagnostics has live subscribers and fetches
history on demand. Consuming host power for background scheduling must not retain
live diagnostics. There is no telemetry database or recurring shell-probe fallback.
History has independent bounds for age, snapshot count, process rows, and retained
bytes. A count limit alone cannot bound memory when command lines vary in size.
Large process trees therefore shorten the available history window. Linux task
enumeration is disabled because walking every `/proc/<pid>/task/<tid>` directory
makes sampling itself expensive.
Electron power updates travel over private inherited pipes, independent of the
renderer connection. Power events and slow heartbeats continue with diagnostics
closed; `app.getAppMetrics()` runs only on live demand. The receiver's stale deadline
must exceed the slowest configured heartbeat plus scheduling grace, or intentional
idle polling makes background policy oscillate between constrained and
unconstrained states. Headless servers leave unavailable power data unknown.
## Measurement traps
- Process identity includes start time because operating systems reuse PIDs.
Electron and native start times have different precision, so merging allows a
small tolerance. Process signaling rechecks the native identity with a fresh
sample.
- Snapshot sequence numbers belong to a monitor generation. Comparing them across
restarts would discard the new monitor's samples until its sequence caught up.
- Sampling can miss a process that starts and exits between samples. Cumulative
counters still yield deltas for processes observed across samples.
- Windows process I/O includes more than disk traffic. Unix counters report storage
I/O, which can differ from logical application reads and writes because of OS
caching. Keep instrumented logical I/O separate from these counters.
- Group totals accumulate observed deltas since telemetry started. Per-process
cumulative counters cover the operating system's lifetime for that process.
- Historical replay uses native samples without current Electron CPU or memory
metrics. Merging the latest Electron values would overwrite the past.
A WSL backend needs a Linux monitor even though Electron runs on Windows. Windows
desktop packages currently supply only the Windows executable, so native process
telemetry for the WSL backend is unavailable. The inherited Electron power feed
still works.
-127
View File
@@ -1,127 +0,0 @@
# Scripts
> For maintainers. Using T3 Code? See [docs/user](../user/).
## First checkout
T3 Code uses [Vite+](https://viteplus.dev/guide/). Install the global `vp` command, install
dependencies, then start the dev stack:
```bash
curl -fsSL https://vite.plus | bash # Windows: irm https://vite.plus/ps1 | iex
vp i
vp run dev
```
Node 24 is required. Bun is not: the server picks Bun adapters when it detects Bun and falls back to
Node otherwise, and nothing in contributor setup needs it.
`vp run dev` prints a one-time pairing URL. Open it so the first browser navigation is
authenticated.
## Dev
- `vp run dev`: Starts contracts, server, and web in watch mode.
- `vp run dev --share`: Also publishes the web port over HTTPS on this machine's tailnet. The
startup pairing URL is built against the shared origin, and the mapping is removed on exit.
Shared runs default to Vite's bundled dev mode (`T3CODE_BUNDLED_DEV=1`): a remote browser pays a
network round trip per import level in unbundled dev, which turns a cold module graph into
minutes of waterfall. Set `T3CODE_BUNDLED_DEV=0` to opt a shared run back out.
- `vp run dev --browser`: Auto-opens a browser. Off by default. The dev runner writes
`T3CODE_NO_BROWSER` itself from this flag, so setting `T3CODE_NO_BROWSER=0` in your environment has
no effect; use `--browser`.
- `vp run dev:server`: Starts just the server. It runs on Node (`node --watch src/bin.ts`), so
without Bun present it selects `NodePtyAdapter` and `NodeHttpServer`.
- `vp run dev:web`: Starts just the Vite dev server for the web app.
- `vp run dev:desktop`: Starts the Electron shell against the dev server.
- `vp run dev:marketing`: Starts the Astro marketing site.
- Pass dev-runner flags directly after the root task name, for example:
`vp run dev --home-dir /tmp/t3code-dev`
### Dev state directories
- Dev commands run from a linked **git worktree** default to that worktree's gitignored `.t3`, even
when `T3CODE_HOME` is set, storing state in `<worktree>/.t3/userdata`. Pass `--home-dir <path>` to
choose another isolated directory explicitly. Submodules are not worktrees and keep the normal
precedence.
- From the **main checkout**, dev commands implicitly use `~/.t3/dev`, keeping development state
separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under
`<path>/userdata`; the base directory remains available for caches, worktrees, and other shared
data.
## Build, check, test
- `vp run build`: Fans out over `apps/*`, `packages/*`, `oxlint-plugin-t3code`, and `scripts`.
Workspaces that define a build task run one: desktop, marketing, server (which depends on web), and
web. Shared packages are consumed and bundled transitively rather than built separately.
- `vp run build:desktop`: Builds the desktop pipeline (desktop plus server).
- `vp run start`: Runs the production server (serves the built web app as static files).
- `vp check`: Vite+ format, lint, and type checks. This repo sets `typeCheck: false` in its lint
options, so workspace type checking runs separately.
- `vp run typecheck`: Strict TypeScript checks for all packages.
- `vp run test`: Runs workspace tests.
- `vp run lint:mobile`: Mobile native static analysis (`scripts/mobile-native-static-check.ts`).
- `node apps/server/scripts/t3-sqlite-state.ts <query|exec> --base-dir <path> ...`: Inspects or seeds
an isolated T3 SQLite database; writes create a private backup first.
## Desktop artifacts
- `vp run dist:desktop:artifact --platform <mac|linux|win> --target <target> --arch <arch>`: Builds a desktop artifact for a specific platform/target/arch.
- `vp run dist:desktop:dmg`: Builds a shareable macOS `.dmg` into `./release`. Architecture defaults
to the host, so this produces an arm64 DMG on Apple Silicon. Use `dist:desktop:dmg:arm64` or
`dist:desktop:dmg:x64`, or pass `--arch <arm64|x64|universal>`, to force one.
- `vp run dist:desktop:linux`: Builds a Linux AppImage into `./release`.
- `vp run dist:desktop:win`: Builds a Windows NSIS installer into `./release`. `:arm64` and `:x64`
variants exist.
### Desktop `.dmg` packaging notes
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/prod/black-macos-1024.png` as the production app icon source.
- The DMG chrome follows the release channel: neutral for Latest and the Nightly sky artwork for
Nightly. Blueprint artwork remains exclusive to Dev builds. Packaging rasterizes the selected
SVG into standard and Retina PNGs inside the disposable staging directory.
- The Finder window is 540×412 while its background is 540×380; the extra 32px accounts for the
title bar included in Finder's window bounds.
- Desktop production windows load the bundled UI from the `t3code://app/` root URL (not a
`127.0.0.1` document URL, and not an explicit `index.html` path).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an
auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first
launch.
- To keep staging files for debugging package contents, run: `vp run dist:desktop:dmg --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Signed macOS builds also require `T3CODE_APPLE_TEAM_ID` and
`T3CODE_MACOS_PROVISIONING_PROFILE`. The passkey RP domain is derived from
`T3CODE_CLERK_PUBLISHABLE_KEY` unless `T3CODE_CLERK_PASSKEY_RP_DOMAINS` overrides it.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
## Browser development
`dev` and `dev:web` leave `VITE_HTTP_URL` and `VITE_WS_URL` unset so the browser resolves the backend
from `window.location.origin`. Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the
server, allowing the same bundle to work from localhost or a tailnet hostname.
## Running multiple dev instances
Worktrees derive a preferred port offset from their path.
- Default ports: server `13773`, web `5733`
- Shifted ports: `base + offset`
- Example: `T3CODE_DEV_INSTANCE=branch-a vp run dev:desktop`
Offset resolution, in order:
1. `T3CODE_PORT_OFFSET`, which must be a non-negative integer. Negative values are rejected.
2. `T3CODE_DEV_INSTANCE`. An all-digit value is used directly as the offset; any other non-empty
value is hashed into one.
3. The worktree path hash.
Collision scanning depends on the mode. `dev:web` scans only the web port and shifts only the web
offset. `dev:server` scans only the server port. `dev` and `dev:desktop` scan both and shift them
together as one shared offset. Explicit server or dev-URL overrides remove the corresponding port
from the availability check. Treat the `[dev-runner]` output as authoritative.
+45 -95
View File
@@ -1,107 +1,57 @@
# Server Update Architecture
# Server updates
> For maintainers. Using T3 Code? See [docs/user](../user/).
A [stable launcher](../../apps/server/src/serviceLauncher.ts) owns the runtime
selected by systemd or launchd. It is the only runtime writer of durable service
state. Server children request updates over inherited IPC; they never rewrite
their service definition or select their own replacement. Local service commands
may replace the launcher and state while the service is stopped. Foreground CLI
processes do not self-update.
Remote server updates use one stable launcher selected by the platform service manager (systemd on
Linux, launchd on macOS). Foreground CLI processes do not self-update, and a running server never
edits its service definition or durable service state.
Exact-version installs keep restarts independent of npm cache eviction or a moving
release tag. Installation and preflight happen in staging before publishing an
immutable runtime. Preflight checks the launcher protocol because a target that
needs new rollback guarantees cannot safely run under an older launcher. Upgrading
that launcher requires a local service update.
## Ownership
## Commit boundary
The service files under `<baseDir>/runtime` are:
The launcher durably records the pending update before acknowledging it, then
stops the old child and starts the target as a trial. Service-state writes use
same-directory replacement with file and directory fsync. Invalid state stops
startup rather than guessing which runtime to boot.
- `service-launcher.mjs`, the stable process selected by the service manager;
- `service-state.json`, the launcher's durable selection state;
- `versions/<version>`, immutable exact-version npm installs.
The trial must finish migrations, acquire dependencies, bind HTTP, and park every
long-running root at the activation gate before reporting `prepared`. The launcher
then commits the target version durably and replies `committed`. Only then may the
child release its gates, accept commands, and publish ready. Keep fallible startup
acquisitions before this boundary. A listener alone does not prove the runtime is
ready to commit.
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.
A failed or timed-out trial returns to the old version. After commit, the target
is authoritative and the service manager's ordinary restart policy applies.
The state contains one active version and, at most, one update record:
## Database rollback
- `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 the service manager cannot guess at a runtime.
After the old child exits, the launcher snapshots SQLite's main file, WAL, and
shared-memory file. This makes trial migrations reversible without down
migrations. The snapshot is made once per update and survives launcher restarts;
replacing it during a retry could capture changes from the failed trial.
Every write uses same-directory replacement plus file and directory fsync.
Rollback stops the trial before restoring. A durable restore marker makes an
interrupted restore finish before either version boots. Keep the snapshot until
commit, or until both restoration and the terminal rollback state are durable.
Attachments and other files outside SQLite are outside this rollback boundary.
## Remote Update
## Client acknowledgement
1. The active server installs `t3@<target>` into a unique staging directory.
2. The target runs `__service-preflight` and verifies that the stable launcher supports its update
protocol.
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. With SQLite quiescent, the launcher snapshots the database, WAL, and shared-memory files.
7. The launcher starts the target as a trial and gives it the pending update over IPC.
8. The trial runs migrations, acquires dependencies, binds HTTP, starts every long-running root
fiber, and verifies that each root is parked at the activation gate.
9. The trial sends `prepared`. The launcher durably commits B, deletes the snapshot, then replies
`committed`.
10. The child opens the existing activation gate, accepts commands, and publishes lifecycle ready
with the terminal update outcome.
An accepted update is still pending. Clients correlate the launcher's update ID
with the ready event after reconnecting, then check the outcome and target version.
A reconnect alone cannot distinguish successful replacement from rollback. Older
servers without an update ID retain version-only correlation.
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 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 stops it, restores the
snapshot, records rollback, and starts A. A durable restore marker makes an interrupted restore
resume before either version can boot. After commit, B is active and the service manager's normal
restart policy applies.
## Database Rollback
The launcher snapshots `state.sqlite`, `state.sqlite-wal`, and `state.sqlite-shm` after the old
server stops and before the trial starts. This makes trial migrations and writes reversible without
requiring down migrations. The snapshot is retained across launcher restarts and is removed only
after commit or after both restore and the terminal rollback state are durable.
The protocol version is part of the safety boundary. A target that requires database snapshots is
blocked when the installed launcher is too old. Upgrade the launcher once with:
```sh
npx t3@<version> service update
```
The local command stops the unit, selects the new launcher and exact runtime, then restarts the
service. Later releases, including releases with migrations, can use the remote trial path.
Snapshots briefly require enough free disk for another copy of the SQLite files. Attachments and
other files under the state directory are outside this rollback boundary.
## Client Correlation
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.
## Capability and Compatibility
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 advertise `desktopAppUpdate` when the desktop telemetry control fd is
attached. The progress RPC asks the desktop app to check and download, then returns a preparation
token while the backend is still connected. Only after the client receives that result does it send
`server.commitDesktopUpdate`. A successful commit closes the connection and must reconnect at the
prepared version. The desktop app and bundled server versions stay equal because
`scripts/update-release-package-versions.ts` bumps them together. If install fails, the desktop keeps its windows, restarts stopped backends, and
replays the failure for the same token. This two-phase handoff prevents backend shutdown from
dropping the only successful RPC result. Desktop servers without the capability direct the user to
update the desktop app locally. Other process shapes provide a manual command; the old detached
foreground respawn path no longer exists.
## Source Map
- 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`
Desktop updates have a separate two-phase handoff because installing the app stops
its bundled backend. Preparation returns a token while the connection is alive;
the client commits that token only after receiving it. Otherwise backend shutdown
could lose the only successful RPC result. The client must then observe the
prepared version after reconnecting. If installation fails, desktop restarts the
stopped backends and replays the failure for the same token.
File diff suppressed because it is too large. Load diff
+65 -257
View File
@@ -1,273 +1,81 @@
# T3 Connect
> For maintainers. Using T3 Code? See [docs/user](../user/).
T3 Connect uses Clerk for cloud identity. The relay manages environment links,
credentials for reaching environments, and managed tunnel allocations. After
bootstrap, clients send application traffic through the environment's tunnel
hostname; the relay Worker does not proxy their HTTP or WebSocket sessions.
T3 Connect uses one Clerk application for web, desktop, and mobile authentication. The relay verifies
two kinds of bearer credential: template JWTs generated from the `t3-relay` template with the shared
`t3-code-relay` audience, and Clerk OAuth tokens issued to the CLI. `verifyRelayClientBearerToken` in
`infra/relay/src/http/Api.ts` tries the template/session path first and falls back to OAuth
verification (`acceptsToken: "oauth_token"`), so the CLI's OAuth credential works without a JWT
template.
Clerk, deployment, and native authentication setup live in the
[Connect setup runbook](../operations/connect-setup.md).
For the wider system diagram, see
[t3-code-connect-auth-flow.html](./t3-code-connect-auth-flow.html).
## The relay is a trusted broker
## Application Keys
An authenticated cloud user still needs an active environment link. The relay
asks that environment to mint a one-time bootstrap credential bound to the
client's DPoP key. The client exchanges it directly with the environment for an
[environment session](./environment-auth.md). The relay never receives that
session token, and possessing the bootstrap credential alone does not permit
redeeming it without the client's private key.
T3 Connect is disabled in a fresh clone. To enable it for source builds against the production
deployment, copy the repository-root example file:
Both sides authenticate this exchange. The environment accepts only bounded,
replay-guarded relay proofs for its own identity, linked user, and requested
operation. Signed environment responses bind the result to the request nonce;
mint responses also bind the credential to the client proof key. The relay
verifies those bindings before returning a credential. This prevents a different
process behind the tunnel from impersonating the linked environment. The checks
meet in the
[environment cloud handlers](../../apps/server/src/cloud/http.ts) and
[relay connector](../../infra/relay/src/environments/EnvironmentConnector.ts).
```sh
cp .env.example .env
```
The relay holds the signing authority for mint requests. DPoP protects an honest
exchange from credential reuse; it does not make a compromised relay signing
key harmless. Keep that trust assumption explicit when changing the protocol.
`.env.example` carries the production public identifiers (the same values baked into official
release builds). To target a different Clerk application or relay, set the values yourself in a
repository-root `.env` or `.env.local` file:
Managed tunnels expose only a validated loopback HTTP origin. Link proof checks
reject forwarded authority headers, and the relay resolves endpoints from its
own managed allocations rather than a caller-supplied URL. Health and mint
requests must not follow redirects. These restrictions keep endpoint discovery
from turning into arbitrary relay egress or exposing another service on the
environment host.
```dotenv
T3CODE_CLERK_PUBLISHABLE_KEY=<publishable key>
T3CODE_CLERK_JWT_TEMPLATE=<JWT template name>
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=<public OAuth application client ID>
T3CODE_RELAY_URL=https://relay.example.com
```
## A link outlives a connector process
The shared client loader projects these canonical values into framework-specific `VITE_*` and
`EXPO_PUBLIC_*` aliases. Existing aliases remain accepted as overrides for compatibility, but new
client configuration should use the canonical names.
CLI authorization, desired exposure, and a running connector have different
lifetimes. Linking can record intent while the server is stopped. Startup
reconciles that intent. CLI logout removes the stored cloud credential and
disables exposure without uninstalling the environment's background service.
Configuration precedence is:
Managed allocations belong to a user/environment pair. Provisioning checkpoints
external tunnel and DNS resources so retries can reconcile partial work. A
normal shutdown of a CLI-managed link releases its tunnel to avoid paying for
an idle resource, retaining the hostname reservation for the next startup.
It also retains the allocation record so the environment remains "offline"
rather than becoming "not authorized".
1. Process or CI environment variables.
2. Repository-root `.env.local`.
3. Repository-root `.env`.
Two cases must retain the tunnel across shutdown. A link installed through a
client has no startup provisioning path and depends on its stored connector
token. An update handoff immediately starts a replacement server, and replacing
the tunnel would add routing propagation delay to every update. These exceptions
belong to [shutdown handling](../../apps/server/src/cloud/http.ts).
The Clerk publishable key, JWT template name, CLI OAuth client ID, and relay URL are public
identifiers, not secrets.
Web, desktop, mobile, and bundled server builds statically inject the values they consume during
their build step. A built artifact does not need an environment file at runtime. CI release builds
should set `T3CODE_CLERK_PUBLISHABLE_KEY`, `T3CODE_CLERK_JWT_TEMPLATE`,
`T3CODE_CLERK_CLI_OAUTH_CLIENT_ID`, and `T3CODE_RELAY_URL` before building. EAS preview and
production builds only need the Clerk publishable key, JWT template name, and relay URL in their EAS
environment.
Release and unlink claim the allocation generation before deleting external
resources. A delayed cleanup must not delete a tunnel reused by a concurrent
restart or relink. Unlink commits authorization revocation before external
teardown, because a database failure must leave the active link usable. Failed
teardown retains enough state to retry. See the
[managed endpoint lifecycle](../../infra/relay/src/environments/ManagedEndpointProvider.ts).
When any client-facing public value is absent, cloud UI is omitted. The `t3 connect` command group is
always registered: when the CLI public values are absent, `makeCli` in `apps/server/src/bin.ts`
registers a hidden fallback `connect` command that reports the missing configuration instead of
silently vanishing from help. The bundled server still accepts runtime overrides for self-hosted or
operator-managed deployments.
## OAuth traps
For a hosted relay deployment, copy `infra/relay/.env.example` to `infra/relay/.env`. The relay
deployment reads `RELAY_DOMAIN`, `RELAY_API_ZONE_NAME`, `RELAY_TUNNEL_ZONE_NAME`,
`CLERK_PUBLISHABLE_KEY`, and `CLERK_JWT_AUDIENCE` through Effect `Config`. There are no checked-in
deployment defaults.
`vp run --filter t3code-relay deploy` invokes Alchemy from the relay directory, so Alchemy loads
`infra/relay/.env`. After a successful deployment, the wrapper updates the repository-root `.env`
with the deployed HTTPS relay URL. The relay still requires
`CLERK_SECRET_KEY` as an Alchemy secret. Never put `CLERK_SECRET_KEY` in a client application
environment or commit it to the repository.
Interactive clients and the headless CLI use the same Clerk application but
different credentials. The relay accepts both session-template JWTs and CLI
OAuth tokens; requiring a JWT template for the CLI would reject valid logins.
The CLI is a public OAuth client using PKCE and stores no client secret.
The `prod` Alchemy stage owns the retained PlanetScale database. Non-production stages reference
that database and provision isolated PlanetScale branches, so deploy `prod` before creating a
personal developer stage.
## Headless CLI OAuth Application
The `t3 connect` commands authorize a headless environment with a separate Clerk OAuth application.
This uses an OAuth public client with PKCE, so the CLI stores no client secret.
In **Clerk Dashboard > OAuth applications**:
1. Create an OAuth application for the T3 CLI.
2. Enable the **Public** option so authorization-code exchange uses PKCE.
3. Add **both** allowed redirect URIs:
- `http://127.0.0.1:34338/callback` for the loopback listener;
- `https://app.t3.codes/connect/callback` for the hosted out-of-band flow. This is
`connectCallbackUrl(DEFAULT_HOSTED_APP_URL)` from `packages/shared/src/connectAuth.ts`, so a
custom `T3CODE_HOSTED_APP_URL` means `$T3CODE_HOSTED_APP_URL/connect/callback` instead.
Omitting it breaks headless and SSH authorization.
4. Enable the `openid`, `profile`, and `email` scopes.
5. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` in the repository-root `.env` file and release build
environment to the generated public client ID.
Both CLI flows start at the hosted `/connect` page (`buildConnectAuthorizeRequestUrl` in
`packages/shared/src/connectAuth.ts`), which waits for a Clerk session and then forwards the request
to Clerk's `/oauth/authorize`. The CLI never opens `/oauth/authorize` directly: a signed-out browser
sent there goes through Clerk's sign-in redirect, which drops the authorize query parameters and
fails the flow with `unsupported_response_type` or an empty `state` (#5051). The loopback flow marks
the request with a `port` fragment parameter so the hosted page asks Clerk to redirect the
authorization code straight to `http://127.0.0.1:<port>/callback`; the out-of-band flow omits it and
uses the hosted `/connect/callback` page instead. The CLI derives Clerk's frontend API URL from the
publishable key and calls only the `/oauth/token` endpoint directly. The relay is not involved in
the OAuth handshake; it only validates the issued Clerk bearer token when the CLI manages an
environment link.
The connect command group is:
```sh
t3 connect # default: onboarding
t3 connect login
t3 connect link # --publish-only
t3 connect status # --json
t3 connect publish # --disable
t3 connect unlink
t3 connect logout
```
`t3 serve` is a separate top-level command, not a connect subcommand.
`t3 connect login` opens the Clerk authorization flow and stores the CLI credential without enabling
cloud exposure. `t3 connect link` installs the pinned managed `cloudflared` binary when needed,
authorizes when needed, and records durable intent to expose the environment. It works without a
running T3 server. The next `t3 serve` or `t3 start` reconciles the relay link and launches the
managed tunnel. `t3 connect unlink` records disabled intent immediately, stops a reachable running
connector, and attempts to revoke the relay-side environment record. It retains the stored CLI
authorization so `t3 connect link` can re-enable exposure without another browser flow. `t3 connect
logout` performs the same cleanup and removes the stored CLI authorization.
The background service has an independent lifecycle. Connect setup may offer to install it, but
logout leaves it running; manage it with `t3 service status`, `install`, `update`, and `uninstall`.
### Headless and SSH authorization
The loopback OAuth callback listener binds to port `34338`. That path only works when a browser on
the same machine can reach it, so `authorizeCli` in `apps/server/src/cli/connect.ts` automatically
selects the out-of-band flow when `--headless` is passed or when it detects SSH through
`SSH_CONNECTION` or `SSH_TTY`. The out-of-band flow prints the hosted `/connect` authorization URL
and accepts a pasted authorization code, so no port is involved.
Port forwarding is therefore optional, not required. Forward the port only if you specifically want
the loopback flow over SSH:
```sh
ssh -L 34338:127.0.0.1:34338 <host>
```
## JWT Template
In **Clerk Dashboard > JWT templates**, create a template with:
| Setting | Value |
| ------- | ---------------------------- |
| Name | `t3-relay` |
| Claims | `{ "aud": "t3-code-relay" }` |
Set `T3CODE_CLERK_JWT_TEMPLATE=t3-relay` in the repository-root `.env`, and set
`CLERK_JWT_AUDIENCE=t3-code-relay` in `infra/relay/.env`. Define `CLERK_JWT_TEMPLATE` and
`CLERK_JWT_AUDIENCE` in the production relay deployment environment as well. The stable `aud` value
is shared by production and non-production relay stages. The client-facing `T3CODE_RELAY_URL` still
selects the concrete relay deployment, but changing that URL does not require a JWT template change.
## Desktop OAuth Redirect Allowlist
The desktop app opens OAuth in the system browser and returns to the app with a custom URL scheme.
In **Clerk Dashboard > Native applications**, enable the Native API and add these entries under the
mobile SSO redirect allowlist:
```text
t3code-dev://app/
t3code://app/
```
Local desktop development uses `t3code-dev://app`, while packaged builds use `t3code://app`. Add the
matching origin to each Clerk instance's Backend API `allowed_origins` array as well. The development
Clerk instance should only need `t3code-dev://app`; the production Clerk instance should only need
`t3code://app`. `@clerk/electron` owns the native request adapter, encrypted Clerk token persistence,
external-browser OAuth transport, and callback delivery for initial sign-in and linked-account flows.
There is currently no Dashboard UI for `allowed_origins`. Preserve any existing entries and update
the instance through the Backend API:
```sh
curl -X PATCH https://api.clerk.com/v1/instance \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $CLERK_SECRET_KEY" \
-d '{"allowed_origins":["t3code://app"]}'
```
Never put `CLERK_SECRET_KEY` in the desktop app, a client-facing environment file, or a build
artifact.
## Desktop Passkeys
The production macOS bundle ID is `com.t3tools.t3code`. To enable native passkeys:
1. Create an explicit macOS App ID for `com.t3tools.t3code` in the Apple Developer portal and enable
**Associated Domains**.
2. Create a compatible macOS provisioning profile for that App ID and the certificate used to sign
the distributed app.
3. In Clerk's Native API settings, add an iOS app with the same Apple Team ID and bundle ID. This is
also the configuration point for Electron/macOS passkeys.
4. Confirm Clerk serves `https://<frontend-api>/.well-known/apple-app-site-association` and that
`webcredentials.apps` contains `<TEAM_ID>.com.t3tools.t3code`.
5. Set the local or CI signing configuration described below.
For a local signed build, add these values to `.env.local` or export them before invoking the
desktop artifact command:
```dotenv
T3CODE_APPLE_TEAM_ID=ABC1234567
T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# Optional: comma-separated override when Clerk's RP ID differs from the Frontend API hostname.
T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
```
When `T3CODE_CLERK_PASSKEY_RP_DOMAINS` is absent, the build derives the RP domain from
`T3CODE_CLERK_PUBLISHABLE_KEY`. Signed macOS builds fail early if the Team ID, provisioning profile,
or RP-domain configuration is missing. The generated main-app entitlements include every configured
`webcredentials:<domain>` entry; helper apps keep Electron's minimal default entitlements.
The normal `dev:desktop` launcher is unsigned and cannot complete macOS passkey ceremonies. For
renderer HMR, build and install a signed app first, run the renderer dev server, then launch the
installed app executable with `VITE_DEV_SERVER_URL` and `T3CODE_PORT` set. Rebuild the signed app
after native dependency, main-process, preload, entitlement, provisioning, or signing changes;
renderer-only changes can reuse the installed app.
For the default development ports, run `pnpm dev:web` in one terminal and launch the installed
binary from another:
```sh
VITE_DEV_SERVER_URL=http://127.0.0.1:5733 \
T3CODE_PORT=13773 \
"/Applications/T3 Code (Alpha).app/Contents/MacOS/T3 Code (Alpha)"
```
After changing Associated Domains, bump the build version before rebuilding; macOS may otherwise
reuse stale Shared Web Credentials metadata for the same app/version pair.
Verify the installed bundle before testing:
```sh
codesign --verify --deep --strict "/Applications/T3 Code (Alpha).app"
codesign -d --entitlements :- "/Applications/T3 Code (Alpha).app"
```
The current mobile UI uses Clerk's native authentication view. If a future mobile browser OAuth
flow uses a custom redirect URI, add that exact URI to the same allowlist.
## Sign-in Surfaces
Signed-in users manage T3 Connect under **Connections**. The settings sidebar also has dedicated
controls, rendered by `SettingsSidebarNav.tsx`: `T3ConnectSidebarSignIn` in the footer shows a
**Sign in to T3 Connect** button while signed out, and `T3ConnectSidebarAvatar` shows a Clerk
`UserButton` account control while signed in. Both are gated on cloud public configuration.
Desktop renders the same web bundle, so it has them too. The waitlist enrollment flow from the
private beta was removed when Connect went GA; sign-up is open unless a Clerk restriction below is
enabled.
## Restricting Sign-ups: Known-User Allowlist
For a closed deployment where all permitted users are known in advance, restrict sign-up to
permitted email addresses or domains:
1. In **Clerk Dashboard > Restrictions > Allowlist**, add each permitted email address or email
domain.
2. Enable the allowlist and save.
3. Alternatively, enable **Restricted mode** when all new users must be explicitly invited or
manually created.
Do not enable an empty allowlist: it blocks all new sign-ups.
Clerk allowlists control who can sign up. They do not revoke an existing user's active cloud
access. To remove an already-created user's access, ban that user in Clerk so their active
sessions are ended and future sign-ins are rejected.
CLI authorization starts on the hosted `/connect` page so sign-in completes
before entering Clerk's authorize endpoint. Sending a signed-out browser
straight to that endpoint loses the authorize parameters during the sign-in
redirect. The [shared flow](../../packages/shared/src/connectAuth.ts) preserves
PKCE and state for both loopback and pasted-code callbacks. SSH and headless
sessions use the pasted-code flow because the browser cannot ordinarily reach a
listener on the remote machine.
+44
View File
@@ -0,0 +1,44 @@
# Terminal runtime
The environment server owns PTYs, session lifetime, and retained output. Every
client, including the desktop renderer, attaches through the environment connection.
This lets clients reconnect or share a running session. Renderer choices stay local
to each client and do not change terminal contracts.
## Output and retention
[Terminal history](../../apps/server/src/terminal/Manager.ts) is incremental.
PTY callbacks append new chunks; live events carry only those chunks. Materializing
or copying full scrollback on every callback makes output cost grow with retained
history, so snapshots and coalesced persistence are the materialization boundaries.
Persistence queues the mutable history buffer and reads its latest value when the
write runs. Clear, restart, and close must drain writes before completing their
lifecycle boundary.
Server history is capped at 5,000 lines and 8 MiB of UTF-8 text per terminal, so a
long unterminated line cannot bypass retention. Eviction removes the oldest output
without splitting Unicode code points; live output is not truncated. Release
discarded chunk references immediately, even if array compaction happens later.
Client buffers have a separate 512 KiB cap. Measure throughput with full scrollback
when changing this path.
Restoration must read only the bounded tail of current or legacy history files,
skip any incomplete UTF-8 prefix, and apply the line limit. Close the read handle
before rewriting the capped file. Reading whole old logs would defeat the memory
bound during startup.
## Renderer ownership
Android and web use the same `libghostty-vt` C ABI for terminal behavior. Platform
adapters own drawing and input integration, and React stays out of terminal frames.
The web adapter shares one WebAssembly instance per browser tab while each terminal
owns and frees its own handles. The canonical upstream pin is
[`native/libghostty-vt/VERSION`](../../native/libghostty-vt/VERSION); both native and
web artifacts must be rebuilt when it changes. Web embeds the revision in its build
info so the ABI check can detect drift without a second pin.
Restoring scrollback must not send terminal replies to the current shell. Historical
device queries can otherwise provoke fresh replies that appear as junk at the
prompt. The server strips query/response traffic from retained history, and the
[web renderer](../../apps/web/src/terminal/ghostty/core.ts) detaches its PTY writer
during replay. Preserve both protections when changing retention or renderer code.
+16 -98
View File
@@ -1,102 +1,20 @@
# Voice input
> For maintainers. Using T3 Code? See [voice input on iPhone](../user/composer.md#voice-input-on-iphone).
Transcription edits a composer draft. It does not submit an agent turn. Audio is
temporary client input, and only normal message submission sends the resulting
text. The current implementation transcribes locally on supported iOS devices;
environment-backed transcription is not implemented.
Voice input produces editable composer text. The current implementation records on the client and
transcribes locally with Apple's `SpeechAnalyzer` and `SpeechTranscriber` on supported iOS 26+
devices. Environment-provided transcription and transcription on web and desktop are not implemented.
The [shared controller](../../packages/client-runtime/src/voice-input/controller.ts)
owns the operation while the client supplies capture and transcription. Preparation
binds the transcriber and resolved locale for the whole recording. Draft ownership,
text, and revision are captured before recording and checked before insertion, so
a late transcript cannot overwrite a draft that was edited or replaced.
## Current boundaries
The shared [`VoiceInputController`][controller] in `packages/client-runtime` owns preparation,
recording, transcription, cancellation, temporary-file cleanup, and insertion into the captured
draft selection. Applications import it through the [voice-input entry point][voice-input] as
`@t3tools/client-runtime/voice-input`. Its dependencies separate capture from transcription; the
controller imports neither React Native nor an Apple transcription API.
The shared [transcription contract][transcription] defines `VoiceTranscriber`,
`PreparedVoiceTranscription`, and transcription errors. The controller calls `getTranscriber()` once
at the start of an operation, before asking for microphone permission. Preparation returns a resolved
locale and a bound `transcribe` function. The controller retains that result for the recording, so a
selection change cannot prepare with one implementation and transcribe with another.
[`useVoiceInputController`][hook] supplies Expo audio capture, microphone permissions, audio-session
management, waveform samples, and app and navigation lifecycle handling. It normalizes Expo's
`mediaServicesDidReset` into a generic recorder error. [`voiceTranscription.ios.ts`][ios] adapts
`@react-native-ai/apple` through `getLocalVoiceTranscriber()`, capturing the requested device locale
and binding the prepared transcriber to Apple's resolved locale. The other-platform binding returns
no local transcriber. That result describes the local implementation, not whether a client could use
an environment's transcription service.
Mobile's [`voiceInputPresentation.ts`][presentation] maps shared state to toolbar labels and actions.
Waveform and toolbar rendering stay in mobile. The composer edits draft text without selecting a
speech vendor.
Recording captures the draft owner, revision, text, and selection. A late transcript cannot overwrite
a different or edited draft. Only normal message submission sends the resulting text to an agent.
Each operation passes one `AbortSignal` through preparation and transcription. Cancellation
invalidates the operation and aborts that signal immediately. Implementations settle their promises
only after their underlying work stops. The Apple binding checks cancellation between asynchronous
steps but cannot interrupt an in-flight native request. The controller retains its session until
that work settles, ignores its result, and cleans up the recording.
## Ownership decisions
The extension boundary distinguishes transcription on the client device from transcription through
the composer's environment. These constraints apply when adding selectable transcription services:
- Local means the client device, regardless of which machine hosts the environment. A device's lack
of local recognition does not prevent it from recording audio for an environment service.
- Remote service configuration and API keys belong to the environment. The environment calls the
external service. Clients receive service identifiers, labels, and availability information, never
credential values. Transcription services are independent of coding-agent `providerInstances`;
selecting OpenAI for transcription does not select Codex for the thread.
- The client owns its transcription preference, scoped by stable `environmentId`. Its choices are
supported local recognition and the services exposed by the composer's environment. A service ID
is meaningful only within that environment. Different clients can make different choices.
- Resolve and capture the environment, selected service, and locale when an operation starts.
Preparation and transcription use the same selection; preference changes affect the next
recording. Capture environment identity explicitly rather than recovering it from a draft key.
Keep the existing draft-owner and revision checks before inserting text.
- If the selected option is unavailable, report that state and let the user choose another option.
A local failure must not silently upload audio, and a disconnected environment must not redirect
a recording to another environment or service.
- Transcription audio is temporary input, separate from durable chat attachments and messages.
Remote adapters need cancellation of upload and transcription where supported, cleanup after
success, failure, or cancellation, and the same protection against late results as local transcription.
## Existing integration points
[`ServerSettingsService`][settings] and [`ServerSecretStore`][secrets] provide environment-owned
configuration and secret persistence. Existing settings redaction handles coding-provider environment
variables only. Any transcription credential fields need their own explicit separation and redaction
before settings responses or subscriptions reach client caches.
[`ExecutionEnvironmentCapabilities`][capabilities] handles version skew. Remote transcription must be
opt-in: a missing transcription capability means unsupported. The authenticated server-config
subscription and [shared environment state][server-state] already distribute configuration per
environment. A transcription service catalog belongs behind that capability and authenticated
boundary. Older servers expose no remote transcription choices.
The [attachment upload contracts][uploads] and [shared upload operations][attachment-state] provide a
pattern for authorized binary uploads through an environment, including remote connections. Their
existing chat-attachment retention is not a transcription cleanup policy.
Future service selection and environment requests belong alongside the controller in
`packages/client-runtime`, with wire contracts in `packages/contracts`. Capture and native local
recognition remain client-specific. An environment-backed transcriber implements the same shared
contract, with its environment and service bound when selected. The controller does not own service
credentials, provider SDKs, or transport selection.
[controller]: ../../packages/client-runtime/src/voice-input/controller.ts
[voice-input]: ../../packages/client-runtime/src/voice-input/index.ts
[transcription]: ../../packages/client-runtime/src/voice-input/transcription.ts
[hook]: ../../apps/mobile/src/features/voice-input/useVoiceInputController.ts
[presentation]: ../../apps/mobile/src/features/voice-input/voiceInputPresentation.ts
[ios]: ../../apps/mobile/src/native/voiceTranscription.ios.ts
[settings]: ../../apps/server/src/serverSettings.ts
[secrets]: ../../apps/server/src/auth/ServerSecretStore.ts
[capabilities]: ../../packages/contracts/src/environment.ts
[server-state]: ../../packages/client-runtime/src/state/server.ts
[uploads]: ../../packages/contracts/src/assets.ts
[attachment-state]: ../../packages/client-runtime/src/state/attachments.ts
Cancellation invalidates a result immediately, but resources stay owned until the
underlying work settles. Apple's native transcription call cannot be interrupted
once started. Releasing the session or deleting its recording when the abort signal
fires would race that work. The [transcription contract](../../packages/client-runtime/src/voice-input/transcription.ts)
therefore requires implementations to settle only after their work has stopped;
the [Apple binding](../../apps/mobile/src/native/voiceTranscription.ios.ts) checks
cancellation between native calls and discards late results.
-25
View File
@@ -1,25 +0,0 @@
# Engineering work artifacts
> For maintainers. Using T3 Code? See [docs/user](../user/).
Keep planned work out of the source tree. Code search should return the product as it exists, not a mix of current behavior and abandoned intentions.
## Current facts belong in the docs
Put durable architecture, constraints, and operational knowledge in `docs/internals/` or `docs/operations/`. Write these documents in the present tense and update them with the code they describe.
When the reason for a decision will matter after implementation, record it in the relevant internal document. Use a separate decision record under `docs/internals/` only when the rationale does not fit cleanly beside the current architecture.
## Planned work belongs in GitHub
Track active maintainer work in its GitHub issue or project item. The tracking item should state the outcome, constraints, and acceptance criteria, then link the pull requests that implement it. Split large efforts into one durable specification and small work items that can each close independently.
Close completed items. Update or delete invalidated work before starting the next implementation session. External proposals follow [CONTRIBUTING.md](../../CONTRIBUTING.md) and belong in Ideas discussions rather than issues.
## Temporary work stays temporary
Keep agent scratch files, exploratory research, transcripts, and session handoff notes outside the worktree. They are inputs to the work, not project documentation.
`.plans/` is gitignored as a safety net for legacy tools. Its presence does not make it an accepted project artifact. Pull requests must not add implementation plans or temporary research under another name.
A pull request records what changed and why. If a fact must survive after the pull request merges, update the relevant documentation. Otherwise, the tracking item and pull request are the record.
-63
View File
@@ -1,63 +0,0 @@
# Workspace layout
> For maintainers. Using T3 Code? See [docs/user](../user/).
A pnpm workspace driven by [vite-plus](https://vite.plus) (`vp`). See [scripts.md](./scripts.md) for
the task commands.
## apps
- `apps/server` (`t3`): the execution runtime and the published CLI. Owns orchestration, provider
drivers, checkpointing, VCS, terminals, filesystem access, auth, and the HTTP + WebSocket surface.
Also serves the built web app.
- `apps/web` (`@t3tools/web`): React + Vite UI. Consumes the shared client runtime and adds routing,
components, and web-specific platform layers.
- `apps/desktop` (`@t3tools/desktop`): Electron shell. Supervises a desktop-scoped `t3` backend,
loads the web bundle over the `t3code://` protocol, and owns SSH-managed remote environments.
- `apps/mobile` (`@t3tools/mobile`): Expo/React Native client. Same client runtime composition as
web, different platform layer and UI.
- `apps/marketing` (`@t3tools/marketing`): Astro marketing site.
## packages
- `packages/contracts` (`@t3tools/contracts`): shared Effect Schema definitions. RPC group,
orchestration commands/events/read model, auth scopes, environment descriptors, settings.
- `packages/shared` (`@t3tools/shared`): framework-agnostic utilities used by server and clients
(`DrainableWorker`, git and source-control helpers, relay auth and signing, DPoP, semver, logging,
observability, and more).
- `packages/client-runtime` (`@t3tools/client-runtime`): connection lifecycle, authorization, RPC
session, environment registry, and Atom-based domain state shared by web and mobile. See its
[README](../../packages/client-runtime/README.md).
- `packages/ssh` (`@t3tools/ssh`): SSH config parsing, auth prompts, command execution, and the
tunnel/environment manager behind desktop-managed SSH environments.
- `packages/tailscale` (`@t3tools/tailscale`): Tailscale CLI wrapper, including the
`ensureTailscaleServe` / `disableTailscaleServe` serve lifecycle the server drives.
- `packages/effect-acp` (`effect-acp`): Effect client and agent implementation of the Agent Client
Protocol, used by ACP-speaking provider drivers.
- `packages/effect-codex-app-server` (`effect-codex-app-server`): Effect client for the
`codex app-server` JSON-RPC protocol.
## infra
- `infra/relay` (`t3code-relay`): the hosted T3 Connect relay, deployed with Alchemy. Handles
environment discovery, cloud-side records, and mobile notifications. It is not in the hot path;
after connect, client traffic goes directly to the environment. See
[t3-connect.md](./t3-connect.md).
## Other top-level directories
- `scripts/`: workspace tooling run through `vp run`. Dev runner, desktop artifact builds, release
helpers, mobile static checks and showcase capture, update-manifest merging.
- `assets/`: brand and app icon sources per channel (`dev`, `nightly`, `prod`).
- `patches/`: pnpm patches for pinned upstream dependencies.
- `oxlint-plugin-t3code/`: repo-specific lint rules.
- `experiments/`: throwaway prototypes. Not part of the shipped build.
- `docs/`: this documentation tree.
## Import conventions
`@t3tools/shared` and `@t3tools/client-runtime` use explicit subpath exports with no barrel index and
no root export. Import the narrow path (`@t3tools/shared/DrainableWorker`,
`@t3tools/client-runtime/state/threads`) rather than the package root. Files that are not exported
are implementation details. `@t3tools/contracts` does export a root alongside `./settings` and
`./relay`.
+126
View File
@@ -0,0 +1,126 @@
# T3 Connect setup
Deployment and client configuration for T3 Connect. The [architecture note](../internals/t3-connect.md)
explains the trust boundaries; the [relay README](../../infra/relay/README.md#deployment) owns relay
provisioning instructions.
## Public application configuration
T3 Connect is disabled in a fresh clone. To build against the production deployment, copy the
repository-root example:
```sh
cp .env.example .env
```
For another deployment, set these values in the repository-root `.env` or `.env.local`:
```dotenv
T3CODE_CLERK_PUBLISHABLE_KEY=<publishable key>
T3CODE_CLERK_JWT_TEMPLATE=<JWT template name>
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=<public OAuth application client ID>
T3CODE_RELAY_URL=https://relay.example.com
```
Process variables take precedence over `.env.local`, then `.env`. Use these canonical names;
the build loader supplies framework-specific aliases. These values are public identifiers.
`CLERK_SECRET_KEY` belongs only in the relay's secrets, never in client configuration.
Client and bundled-server builds embed the public values, so set them before building.
EAS preview and production environments need the publishable key, JWT template name, and relay URL.
Bundled servers also accept runtime overrides for operator-managed deployments.
Copy `infra/relay/.env.example` to `infra/relay/.env` for relay deployment settings.
Deploy `prod` before personal stages because it owns the retained database that their branches
depend on. The deploy wrapper writes the resulting relay URL back to the root `.env`.
## CLI OAuth application
In Clerk's OAuth applications settings:
1. Create a public OAuth application for the T3 CLI, using authorization-code exchange with PKCE.
2. Allow both redirect URIs: `http://127.0.0.1:34338/callback` and
`https://app.t3.codes/connect/callback`. A custom `T3CODE_HOSTED_APP_URL` needs its own
`/connect/callback` URL. Headless and SSH authorization depend on the hosted redirect.
3. Enable the `openid`, `profile`, and `email` scopes.
4. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` to the generated public client ID in local and release
build environments.
## JWT template
Create a Clerk JWT template named `t3-relay` with claims:
```json
{ "aud": "t3-code-relay" }
```
Set `T3CODE_CLERK_JWT_TEMPLATE=t3-relay` for clients and
`CLERK_JWT_AUDIENCE=t3-code-relay` for the relay. The production relay deployment environment
also defines `CLERK_JWT_TEMPLATE`. The audience stays the same across relay stages; the relay
URL selects the deployment.
## Desktop OAuth redirects
Enable Clerk's Native API and add the desktop redirects to its SSO redirect allowlist:
```text
t3code-dev://app/
t3code://app/
```
Add the corresponding origin to the Clerk instance's Backend API `allowed_origins` array.
Development uses `t3code-dev://app`; production uses `t3code://app`. Update the array with
`PATCH https://api.clerk.com/v1/instance` using the Clerk secret key, preserving existing entries.
The Clerk Electron integration handles token
persistence and system-browser callback delivery.
## Desktop passkeys
For a production macOS app with bundle ID `com.t3tools.t3code`:
1. Create an explicit macOS App ID in the Apple Developer portal with **Associated Domains**.
2. Create a provisioning profile for that App ID and the distribution signing certificate.
3. In Clerk's Native API settings, add an iOS app with the same Apple Team ID and bundle ID.
This setting also configures Electron/macOS passkeys.
4. Check `https://<frontend-api>/.well-known/apple-app-site-association`. Its
`webcredentials.apps` must include `<TEAM_ID>.com.t3tools.t3code`.
5. Configure signing as described in the [release runbook](./release.md#2-apple-signing--notarization-setup-macos).
Local signed builds additionally use:
```dotenv
T3CODE_APPLE_TEAM_ID=ABC1234567
T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# Override only when the RP domain differs from the Clerk Frontend API hostname.
T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
```
Without the override, the build derives the RP domain from the Clerk publishable key.
After changing Associated Domains, bump the build version before rebuilding. macOS can otherwise
reuse stale Shared Web Credentials metadata for the same app/version pair.
The ordinary `dev:desktop` launcher is unsigned and cannot exercise macOS passkeys. For renderer
HMR, install a signed build, start `vp run dev:web`, and launch the installed executable with the
actual web and server ports. For example, with the default ports:
```sh
VITE_DEV_SERVER_URL=http://127.0.0.1:5733 \
T3CODE_PORT=13773 \
"/Applications/T3 Code (Alpha).app/Contents/MacOS/T3 Code (Alpha)"
```
Rebuild the signed app after native dependency, main-process, preload, entitlement, provisioning,
or signing changes. Renderer edits can reuse it. Verify the installed bundle before testing:
```sh
codesign --verify --deep --strict "/Applications/T3 Code (Alpha).app"
codesign -d --entitlements :- "/Applications/T3 Code (Alpha).app"
```
## Restricting sign-ups
Use Clerk's allowlist for permitted email addresses or domains, or Restricted mode for invitation-only
sign-up. An enabled empty allowlist blocks all new sign-ups.
Sign-up restrictions do not revoke an existing account's access. Ban the account in Clerk when
its active sessions and future sign-ins must be disabled.
+159
View File
@@ -0,0 +1,159 @@
# Development
## First checkout
Install `vp` using the [root README](../../README.md#install-vp). The checkout requires Node 24;
Bun is optional. From the repository root:
```sh
vp i
vp run dev
```
Open the one-time pairing URL printed by the dev runner. The bare origin does not authenticate
a new browser.
Prefer a container? See [Dev container](../internals/devcontainer.md) for VS Code and Codespaces setup.
## Choosing a dev process
Use `vp run dev` for server and web, or `vp run dev:desktop` for the Electron client.
`dev:server` and `dev:web` start those processes separately.
See the [mobile README](../../apps/mobile/README.md) for native builds and Metro.
Flags go directly after the task name, for example `vp run dev --home-dir /tmp/t3code-dev`.
Add `--browser` to open a browser automatically.
### State and ports
Linked worktrees default to their own `.t3/userdata`, even when `T3CODE_HOME` is set.
The main checkout defaults to `~/.t3/dev/userdata`. An explicit `--home-dir` wins in both cases.
Never run a development server against the live `~/.t3/userdata`.
See [test data](../../AGENTS.md#test-data) for copying a consistent database snapshot.
Read ports from the `[dev-runner]` output. Worktrees derive stable preferences from their paths,
but occupied ports can shift them. `T3CODE_PORT_OFFSET` or `T3CODE_DEV_INSTANCE` can select a
different preference when needed.
### Sharing and remote debugging
`vp run dev --share` publishes the web port over the machine's tailnet and prints a pairing URL
for that origin. Give the tester the complete URL, including its token. The dev runner removes
its mapping on exit.
Leave `VITE_HTTP_URL` and `VITE_WS_URL` unset. Vite proxies the backend through the browser's
origin so the same build works over localhost and remote connections.
Shared runs enable bundled dev to avoid a network round trip for each import level.
`T3CODE_BUNDLED_DEV=0` opts out when debugging bundler differences. Two reload traps matter
when changing this setup:
- The web entry must dynamically import the app so React refresh initializes before application
chunks. Static imports can work on first load and fail after a route split.
- Bundled dev rebuilds Tailwind through watched files. Its ordinary Vite hot-update hook expects
a server/module graph that Rolldown does not provide.
The workarounds live in the [web entry](../../apps/web/src/bootstrap.ts) and
[Tailwind plugin](../../apps/web/vite/tailwind.ts).
## Checks
Run checks for the files and packages you changed:
```sh
vp test run <files>
vp lint <files>
vp run --filter <package> typecheck
```
Use `vp run lint:mobile` for native mobile changes. CI owns the full suite; see
[ci.yml](../../.github/workflows/ci.yml) for its current jobs.
The [manual Windows lane](../../.github/workflows/windows-tests.yml) is available for focused
Windows investigation while that suite is not a required gate.
### Unused code
`vp run knip:check` checks unused files and dependencies across the repo, then
unused runtime exports in `apps/web` and every internal package under `packages/`.
CI enforces both checks.
Exported types and Effect schemas are allowed without consumers. The schema preprocessor
recognizes schema types, including aliases and schema classes; functions that create or decode
schemas remain checked. Completely unused files remain checked too.
Named exports in web UI component modules are kept as complete component sets. Knip ignores
unused exports in `apps/web/src/components/ui/*.tsx`, while still reporting an entire unused file.
Use `vp run knip --workspace apps/web` to audit one workspace, including exports,
or `vp run knip:production --workspace apps/web` to find code kept alive only by tests.
The full export audit still has findings and is not a repo-wide CI gate. Extend the
export check's workspace selectors as more workspaces become clean. Review callers before
deleting code; production mode can also report development scripts and test fixtures.
Runtime-discovered entrypoints and dependency exceptions belong in [knip.jsonc](../../knip.jsonc).
## Desktop artifacts
Local artifact builds are unsigned by default and write to `release/`:
```sh
vp run dist:desktop:dmg
vp run dist:desktop:linux
vp run dist:desktop:win
```
DMGs default to the host architecture. Use `--arch` to choose another target and `--keep-stage`
to retain packaging files for inspection. Run `vp run dist:desktop:artifact --help` for other
options.
### Linux AppImage prerequisites
Build on Linux because the browser-secret helper links against the host's libsecret. Install
Rust, C/C++ build tools, libsecret development headers, pkg-config, and ImageMagick.
Ubuntu and Debian:
```sh
sudo apt-get update
sudo apt-get install cargo rustc build-essential libsecret-1-dev pkg-config imagemagick
```
Fedora:
```sh
sudo dnf install rust cargo gcc gcc-c++ make libsecret-devel pkgconf-pkg-config ImageMagick
```
Arch Linux:
```sh
sudo pacman -S rust base-devel libsecret pkgconf imagemagick
```
The C toolchain, pkg-config, and libsecret headers are also needed for Linux desktop development.
### macOS DMG prerequisites
Install the Xcode Command Line Tools with `xcode-select --install` and install Rust.
For a cross-architecture or universal build, add the requested Rust targets:
```sh
rustup target add aarch64-apple-darwin x86_64-apple-darwin
```
### Windows installer prerequisites
Install Rust, Python 3, and Visual Studio Build Tools with **Desktop development with C++**.
Include the Windows SDK and the MSVC build tools and Spectre-mitigated libraries for the target
architecture. Add its Rust target:
```powershell
rustup target add x86_64-pc-windows-msvc
# For an ARM64 installer:
rustup target add aarch64-pc-windows-msvc
```
NSIS is downloaded by electron-builder. WSL support additionally needs a Linux node-pty prebuild;
see the [release runbook](./release.md#windows-payload-topology-and-update-validation).
### Signing and passkeys
Add `--signed` after configuring the platform credentials in the
[release runbook](./release.md). macOS passkeys need a signed, provisioned app; follow the
[Connect setup](./connect-setup.md#desktop-passkeys) for local signing and renderer HMR.
+38 -14
View File
@@ -8,9 +8,18 @@ This document covers the unified release workflow for stable and nightly desktop
- Workflow: `.github/workflows/release.yml`
- Triggers:
- push tag matching `v*.*.*` for stable releases
- scheduled nightly check every three hours
- manual `workflow_dispatch` for either channel
- manual `workflow_dispatch` with `channel=stable`, the normal way to ship stable
- push tag matching `v*.*.*` for a stable release of an explicit commit
- scheduled nightly check every 30 minutes
- manual `workflow_dispatch` with `channel=nightly`
- A manual stable release builds the commit of the latest published nightly, not `main` HEAD.
Nightly is the release candidate: verify the nightly, then promote it. Merges to `main` keep
landing while you verify and never leak into the stable build.
- The version defaults to the one the nightly previewed (`0.0.39-nightly.*` ships as `0.0.39`).
Pass the `version` input to override it, for example for a minor bump.
- The stable tag is created on the nightly's commit when the GitHub Release is published.
- Pushing a `vX.Y.Z` tag by hand still works and builds exactly the tagged commit. Use it when
the commit to ship is not the latest nightly, such as a cherry-picked fix on a release branch.
- Runs lint, typecheck, and tests alongside artifact builds. Publishing waits for every check.
- Reads the shared production T3 Connect relay URL and Clerk client configuration before packaging clients.
- Builds four artifacts in parallel for both channels:
@@ -102,6 +111,17 @@ Developers deploy personal stages locally rather than through pull-request autom
vp run --filter t3code-relay deploy -- --stage "$USER" --env-file .env.local
```
## Marketing site deployment
After a nightly release is published, the release workflow deploys the same commit
to the marketing site's Vercel production project. Stable releases do not deploy
the marketing site because they can promote an older nightly commit.
The job looks up the `t3code-marketing` project using the existing `VERCEL_TOKEN`
and `VERCEL_ORG_ID` secrets. It also respects the optional `VERCEL_TEAM_SLUG`
variable. The Vercel project's root directory must be `apps/marketing`.
Git deployments remain disabled in `apps/marketing/vercel.ts`.
## Hosted web app release deployment
The hosted app is intentionally not deployed by Vercel's Git integration. The
@@ -158,8 +178,10 @@ One-time Vercel dashboard setup:
- Workflow: `.github/workflows/release.yml`
- Triggers:
- scheduled check every three hours
- scheduled check every 30 minutes
- manual `workflow_dispatch` with `channel=nightly`
- Automatic nightlies require new commits and at least six hours since the last nightly was published, including manual nightlies.
- Manual nightlies bypass the time and change checks. Nightly runs remain serialized. Scheduled runs wait for an active nightly to finish, then check the publication gap before building.
- Runs the same desktop quality gates and artifact matrix as the tagged release flow.
- Publishes a GitHub prerelease only:
- current tag format: `vX.Y.Z-nightly.YYYYMMDD.<run_number>`
@@ -286,11 +308,11 @@ to validate the workflow.
The workflow has no non-publishing `workflow_dispatch` mode. Use normal CI or local quality gates to
validate checks and builds without shipping. To exercise the complete release graph at lower stable
risk, manually dispatch `channel=nightly`; this still publishes a real nightly npm package, GitHub
prerelease, desktop updater release, and hosted nightly alias, but it does not update stable aliases or
prerelease, desktop updater release, hosted nightly alias, and marketing site, but it does not update stable app aliases or
commit a version bump to `main`. Only run it when a real nightly release is acceptable.
Manual `channel=stable` with a version input is also a real stable-channel release. Omitting signing
secrets only makes platform artifacts unsigned; it does not prevent publication.
Manual `channel=stable` is also a real stable-channel release. Omitting signing secrets only makes
platform artifacts unsigned; it does not prevent publication.
## 2) Apple signing + notarization setup (macOS)
@@ -329,7 +351,7 @@ Checklist:
- `APPLE_API_KEY`: contents of the downloaded `.p8`
- `APPLE_API_KEY_ID`: Key ID
- `APPLE_API_ISSUER`: Issuer ID
10. Complete the Clerk Native API and AASA setup in [T3 Connect Clerk Setup](../internals/t3-connect.md#desktop-passkeys).
10. Complete the Clerk Native API and AASA setup in [T3 Connect setup](./connect-setup.md#desktop-passkeys).
11. Re-run a tag release and confirm macOS artifacts are signed/notarized and contain the expected
`com.apple.developer.associated-domains` entitlement.
@@ -368,17 +390,19 @@ Checklist:
## 4) Ongoing release checklist
1. Ensure `main` is green in CI.
2. Bump app version as needed.
3. Create release tag: `vX.Y.Z`.
4. Push tag.
5. Verify workflow steps:
1. Pick the latest nightly and verify it: run the smoke test above against its artifacts and
check the nightly channel for regressions.
2. Dispatch the Release workflow with `channel=stable`. Leave `version` empty unless the version
should differ from the one the nightly previewed.
3. Confirm the `Resolve release commit` notice names the nightly tag and commit you verified. If a
newer nightly published in between, the run builds that one instead.
4. Verify workflow steps:
- preflight passes
- release quality checks pass
- all matrix builds pass
- `publish_cli` publishes the exact release version before the release job
- release job uploads expected files
6. Smoke test downloaded artifacts.
5. Smoke test downloaded artifacts.
## 5) Troubleshooting
+73
View File
@@ -0,0 +1,73 @@
# Appearance and themes
Open **Settings → Appearance** to choose a theme and follow the system appearance or stay in light
or dark mode. To use different themes for light and dark mode, select the corresponding preview
within each theme. Appearance preferences are saved separately on each device or browser.
Mobile has its own themes and text, code, and terminal preferences. It does not follow environment
themes or defaults.
## Motion
The main sidebar, right panel, and terminal drawer open and close immediately by default. Move the
**Panel animations** slider above 0 ms to add motion, up to 400 ms, unless reduced motion is enabled
in your operating system. Moving between threads always snaps to the selected thread's panel state
without replaying its transitions.
## Custom themes
On web and desktop, choose **Create theme** to adjust a palette, or import a T3 Code or VS Code
theme. The theme editor's color picker lets you select an area of the app to find the color to
change. Export your theme as JSON to share it.
## Environment themes
Environment themes and defaults come from the server serving your web app or the desktop app's
main local environment. app.t3.codes and additional connections do not use them.
Select a published theme in **Settings → Appearance** to follow its palette as the server updates
it. **Duplicate** makes an independent copy you can edit. A saved custom theme with the same ID
takes precedence. If the server stops publishing the selected theme, T3 Code falls back to its
standard theme.
Run this on the server to set a default and switch connected clients to it:
```bash
t3 theme set nightfall
```
Clients that are offline apply it when they reconnect. Each client applies the setting once;
choosing another theme afterward sticks until the next `t3 theme set`. Run the command again to
reapply it, even if the name is unchanged.
`t3 theme clear` removes the default without changing anyone's current theme. `t3 theme show` lists
the default and published themes.
### Publish a theme
Save a theme exported from T3 Code into `~/.t3/userdata/themes/` on the server, or the `themes`
directory under your custom state directory. The filename supplies the theme ID: `nightfall.json`
can be selected with `t3 theme set nightfall`. Keep the filename stable when updating its colors.
Do not use `system`, `light`, `dark`, or a built-in theme's ID.
For an integration that generates a palette, this shorter format also works:
```json
{
"name": "Nightfall",
"appearance": "dark",
"canvas": "#1a1b26",
"accent": "#7aa2f7",
"colors": {
"terminalSelection": "#292e42",
"error": "#f7768e"
}
}
```
Set `appearance` to `light` or `dark` and supply hex colors for `canvas` and `accent`. T3 Code
generates the rest. The optional `colors` overrides use the names in the theme editor's advanced
view.
Write updates to a temporary file and rename it into place so clients never read a partial theme.
Invalid files are not published.
+67 -75
View File
@@ -1,89 +1,81 @@
# Running T3 Code in the Background
# Running T3 Code in the background
On Linux and macOS, T3 Code can run as a background service for your user, so it is ready without
keeping a terminal open.
On Linux and macOS, T3 Code can run as a service for your user so you do not need
to keep a terminal open.
## Manage the Service
## Manage the service
Install it with the latest T3 Code release:
Run these commands on the machine that will host T3 Code:
| Task | Command |
| ------------------------------- | --------------------------------- |
| Install and start | `npx t3@latest service install` |
| Inspect status and log location | `npx t3@latest service status` |
| Update or repair | `npx t3@latest service update` |
| Stop and remove from startup | `npx t3@latest service uninstall` |
Uninstalling the service leaves your projects, threads, and settings intact.
Install and update use the version of the CLI you invoke. For nightly, use
`npx t3@nightly service update`; replace `nightly` with an exact version to pin
one. An older CLI refuses to replace a newer service unless you explicitly add
`--allow-downgrade`.
Updating restarts the server. Finish active work first, and wait for any remote
update already in progress. To match a remote client's version, follow
[Updating T3 Code](./updating.md).
## Platform support
Linux needs systemd user services. Setup enables lingering so T3 Code starts at
boot and keeps running after logout. If this needs administrator permission,
setup prints a recovery command before changing the service.
macOS starts the service when you log in and stops it when you log out. Keep the
Mac logged in and awake for unattended remote access. Installing over SSH while
nobody is logged in at the Mac's screen can fail at the final start step; the
service is still installed and will start at the next login.
Windows background services are not supported.
T3 Connect can offer service installation during setup, but the two are managed
separately. Signing out of T3 Connect does not stop or uninstall the service.
## Troubleshooting
Start with `t3 service status` on the host. It prints the log path and, on Linux,
checks whether the installed service is running, enabled, and allowed to survive
logout.
If it stops when your SSH session closes, check for `linger-disabled`. An
administrator can enable lingering with:
```sh
npx t3@latest service install
sudo loginctl enable-linger "$(id -un)"
```
Check whether it is installed:
Over SSH, allow sudo to prompt:
```sh
npx t3@latest service status
ssh -t your-server 'sudo loginctl enable-linger "$(id -un)"'
```
Update or repair it:
Then retry service setup as your normal user. Run only the `loginctl` command
with sudo; running T3 Code as root creates a separate installation and Connect
identity. Without administrator access, run `t3 serve` in a terminal and keep
that session open.
```sh
npx t3@latest service update
```
| Status problem | Next step |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `linger-unavailable` | Run `loginctl show-user "$(id -un)" --property=Linger` and check that systemd-logind is available. |
| `user-manager-unavailable` | Run `systemctl --user status` in a login session for the service user; check your distribution's systemd user-session support. |
| `service-disabled` or `service-stopped` | Read the log and `systemctl --user status t3code.service`, then use the repair command printed by T3 Code. |
The service uses the same T3 Code version as the CLI you run. To install a nightly or an exact
version, use that version of the CLI:
On macOS, check **System Settings → General → Login Items** if the service no
longer starts at login. If agent work cannot access Desktop, Documents, or
Downloads, it may need Full Disk Access for the Node executable listed in
`ProgramArguments` in
`~/Library/LaunchAgents/com.t3tools.t3code.service.plist`.
```sh
npx t3@nightly service update
npx t3@1.2.3 service update
```
The install and update commands refuse to replace a newer service with an older version. Setup
through T3 Connect leaves a newer service unchanged. To downgrade, select the exact older version
and pass `--allow-downgrade`:
```sh
npx t3@1.2.3 service update --allow-downgrade
```
Stop it and remove it from startup:
```sh
npx t3@latest service uninstall
```
Updating restarts T3 Code briefly. Let active agent work and terminal commands finish first.
If a remote update is already in progress, wait for it to finish before retrying a local update.
The service 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 service
definition. The launcher snapshots the database before a remote candidate starts, so database
updates roll back with the server version. An older launcher may require one local
`service update` before this is available.
## Platform Support
**Linux** uses a systemd user unit at `~/.config/systemd/user/t3code.service`. The service starts
when the machine boots and keeps running after you log out (lingering is enabled during install).
**macOS** uses a launch agent at `~/Library/LaunchAgents/com.t3tools.t3code.service.plist`. It
starts when you log in, not when the Mac boots, and it stops when you log out; macOS has no
equivalent of Linux lingering for user agents. For a Mac that should stay reachable unattended,
turn on automatic login (System Settings → Users & Groups; unavailable while FileVault is on) and
keep the Mac from sleeping.
A few more macOS notes:
- Installing over SSH needs someone logged in at the Mac's screen to start the agent right away.
Without that, the install command reports an error at the final start step, but the agent is
fully installed and starts at the next login.
- macOS may show privacy prompts for protected folders such as Desktop, Documents, or Downloads,
attributed to a bare `node` process, or deny access without a prompt. If agent work fails to
read those folders, grant Full Disk Access to the node binary listed in the launch agent's
`ProgramArguments`.
- The agent appears under System Settings → General → Login Items. If it was switched off there,
or disabled with `launchctl disable`, macOS will not start it at login until you switch it back
on.
**Windows** is not supported yet.
## Using It with T3 Connect
T3 Connect may offer to install the service during setup so the host stays reachable in the
background. This is only an onboarding shortcut: the service and T3 Connect are managed separately.
Signing out of T3 Connect does not remove the service. Use `t3 service uninstall` when you no longer
want T3 Code to start in the background.
For failures after signing in to T3 Connect, see
[connection troubleshooting](./remote-access.md#t3-connect-troubleshooting).
+21
View File
@@ -0,0 +1,21 @@
# Import browser sessions
The desktop app can import cookies from another browser so you can reuse its signed-in sessions
in the preview browser.
Open **Settings → Integrations → Browser profiles → Add profile**, then choose a browser under
**Import from**. Close the source browser before importing, and allow an operating-system keyring
unlock prompt if one appears.
This is a one-time copy. Later login changes stay separate between the two browsers, and some
sites may still require you to sign in again.
On macOS, Safari is also available. Safari protects its cookies with Full Disk Access rather than
a keychain, so the import wizard asks you to grant it: **Open System Settings** takes you to the
right pane, and macOS may ask you to quit and reopen T3 Code before the grant applies. You can
revoke Full Disk Access after the import is done. Only Safari's primary profile is imported; cookies
kept by additional Safari profiles are not.
On Windows, import supports Firefox and Helium profiles that use standard profile encryption.
Other Chromium-based browsers use app-bound encryption and cannot be imported. Partitioned cookies
are skipped on all platforms.
+102 -146
View File
@@ -1,182 +1,138 @@
# Message composer
# Messages and context
Messages can contain up to 120,000 characters. If a draft is longer, T3 Code keeps it in the
composer and shows how many characters need to be removed. Shorten the draft or split it into
multiple messages, then send again in the same thread.
Give the agent a task in the composer. Add files, quote a previous response, or
include a skill when the task needs more context.
On mobile, an empty composer shows an interrupt button while the agent is working. Adding text
or an attachment replaces it with the send button. This applies to both compact and expanded
composers.
Messages can contain up to 120,000 characters. Longer drafts stay in the composer
so you can shorten them or split them into several messages.
You can attach images up to 10 MB. On servers that support file uploads, you can also
attach videos, text files, PDFs, ZIP archives, and other files. Each file can be up to the limit advertised
by the server, capped at 50 MB. Each message can contain up to eight attachments in total. Files
upload directly to the environment, where your agent can read, copy, or edit them by their file path.
## Attach files
Attachments upload as soon as you add them while connected to a server that supports uploads.
The send button becomes available after every upload finishes. Failed uploads can be retried or
removed. On mobile, tap **+** to open
the photo library from either the compact or expanded composer. When the connected server supports
file uploads, **+** opens a menu beside the button with **Photo Library** and **Choose Files**.
Videos use the server's file upload limit. You can also share photos, videos, and files into
T3 Code from other apps through the system share sheet. Mobile keeps a local copy of each draft
attachment, so you can still preview it and queue messages while offline. Uploads resume when
you reconnect. Drafts and queued messages survive app restarts; signing out of T3 Connect keeps
them on your device until you sign back into the same account. Select a received file on mobile
to preview it or open the system share options.
Attach up to eight files per message. Images can be up to 10 MB; other files can
be up to 50 MB, subject to the environment's upload support and limit. The agent
receives them on the environment's machine.
Tap an image or PDF before or after sending to open it. On iOS, images zoom from their thumbnail
into the native viewer. Pinch or double-tap to zoom, and swipe down or tap Close to return.
Use Share to save a copy or send it to another app. PDFs support page navigation and search.
PDF links in assistant responses open the same preview. On Android, images open in the image
viewer and PDFs open the system chooser.
Uploads begin when you add an attachment. All uploads must finish before the
message can send. Retry or remove a failed upload. On web and desktop, reloading
before an upload finishes requires you to attach that file again.
Select a video attachment before or after sending to play it. Web and desktop use the browser's
built-in controls. On mobile, videos open in a full-screen player with native playback controls.
Supported videos show a thumbnail in the conversation and composer.
On web, desktop, and iOS, received videos stream from their environment as they play. Supported formats and codecs
depend on the browser or device; you can save an unsupported video to open it in another app.
You can drag or paste images into the web or desktop composer. HEIC and HEIF
photos are converted to JPEG there and when selected from the iOS photo library;
the image limit applies after conversion. On mobile, you can also send files to
T3 Code through another app's system share sheet.
On iOS, the system player zooms from the attachment. Swipe down or tap Close to return to the
conversation or draft. Touch and hold the attachment, then choose **Save or share video** to open
the system share options. On Android, use **Save or share video** inside the preview.
See [images and videos](#images-and-videos-in-messages) for previewing and saving media.
On web and desktop, if you reload before a file finishes uploading, the draft keeps the file's name
and shows **Attach again** next to it. Attach the file again or remove it, then send.
## Queue messages offline on mobile
On web and desktop, HEIC and HEIF photos are automatically converted to JPEG when you drag them into
the composer or paste them into a message. On iOS, selecting them from **Photo Library** also
converts them to JPEG. The 10 MB image limit applies to the converted photo.
Mobile keeps local copies of draft attachments, so you can preview them and queue
messages while disconnected. Uploads resume when you reconnect. Drafts and queued
messages survive app restarts. Signing out of T3 Connect keeps that work on your
device until you sign back into the same account.
On mobile, the model picker shows each OpenCode model's upstream provider, such as Anthropic,
GitHub Copilot, or OpenCode Zen, beneath its name. Search by that provider name to narrow the list
when starting a thread or changing an existing thread's model.
## Custom models
## Images and videos in messages
On web and desktop, use Settings → Providers → **Models** to add an unlisted model with a custom
name and options. Only options supported by the provider integration affect turns. Antigravity
uses its account catalog and does not support custom models.
On web, desktop, and mobile, select a link to an image or video to open it inside T3 Code.
Workspace image and video links open the file viewer. Links to media outside the workspace
open a media preview.
Videos opened from the file explorer or a file-viewer tab also play inside T3 Code. They
stream from the environment as needed, rather than downloading the entire video before playback.
Paths in inline code, such as `/tmp/recording.mp4`, work the same way. Image embeds stay inline;
video embeds show a player with controls and an option to expand. Visible video previews load
an initial frame when supported, but stay paused until you press Play. Video file references use
a filmstrip icon.
## Model defaults
On web and desktop, hover over a preview to see its full file path or original URL. Right-click
to copy that reference, save an image, or copy an image to the clipboard. Use the video player's
built-in controls to download videos. If the player cannot decode a video, its error message
offers a link to open the source in the browser. Workspace media also offers **Copy relative
path** and **Open in file viewer**. These actions are available in expanded previews too.
T3 Code remembers your provider, model, and model options for new threads. A
project's configured model takes precedence; resetting that project setting
returns to the remembered selection.
On mobile, touch and hold an inline image or use a preview's **Media actions** menu to see its
source, copy the path or URL, or choose **Save or share**. Workspace media can open in the file
viewer from the same menu. Saving downloads a copy only when you request it; it does not change
how the video buffers during playback.
Leaving reasoning level or service tier unset uses the provider's own configuration.
Use Markdown image syntax to embed either kind of media:
## Quote an assistant response
```markdown
![Screenshot](/tmp/screenshot.png)
![Recording](/tmp/recording.mp4)
[Open recording](/tmp/recording.mp4)
```
On web and desktop, select text within one assistant response and choose
**Cite in composer**. You can add a comment about the quote and write instructions
around it.
Relative paths resolve from the thread's workspace. Absolute paths and `file://` links refer to
the environment's machine, even when you connect remotely or use your phone. Supported media
can live outside the workspace, including in Downloads or `/tmp`.
Select the quote in a draft or sent message to return to its source. If the source
is unavailable or has changed, the saved quote remains readable.
T3 Code serves the original file without adding it to attachment storage. If that file is moved
or deleted, its preview can no longer load from the environment. A browser or device may still
have a cached copy. Supported video formats and codecs depend on the browser or device.
Mobile displays saved quotes and comments, but does not create citations or
navigate to their sources.
Bare paths in ordinary prose and paths inside code blocks stay text. Raw HTML `<video>` tags
are not supported; use the Markdown embed syntax above.
## Recall a sent prompt
## Files outside the workspace
Press `ArrowUp` in an empty composer to bring back the last prompt you sent in this thread. Press
`ArrowUp` again to go further back, and `ArrowDown` to come forward. Moving forward past the newest
prompt clears the composer. Recall walks the prompts loaded in the thread. Attachments, terminal
context, and other extras from the original message are not restored, only the text you typed. A
composer that holds an attachment or a picked element does not count as empty.
When an agent links to a file it wrote outside the workspace, such as a Markdown report in
`/tmp`, select the link to open it in the file viewer. The viewer shows the file read-only, with
rendered Markdown available as usual; it cannot edit files outside the workspace. HTML and PDF
files outside the workspace open the same way as ones inside it. Because such a file is served on
its own, an HTML page outside the workspace cannot load scripts, styles, or images from files beside
it.
## HTML and PDF files in the file viewer
On web and desktop, the file viewer shows HTML and PDF files as a rendered page. Use the
source toggle in the viewer's header to switch an HTML file between the page and its markup; the
choice persists like the rendered-Markdown toggle. A link to a line always opens the source. HTML
runs in an isolated frame with no access to your T3 Code session. On desktop, the integrated
browser remains available from the same header for a full browser view.
## Changing projects
On web and desktop, changing the project from a new thread keeps the current environment when that
project exists there. If it does not, T3 Code selects another environment that has the project.
## Notices above the composer
On web and desktop, loading and syncing statuses fill the available banner width beside the
stash tab. Task progress appears above the composer, while the timeline's working timer shows
only elapsed time.
On web and desktop, additional notices peek out above the attached banner. Hover over the peek
to reveal them, or focus **Show other notices** with `Tab` and press `Enter` or `Space`. Press
`Escape` to close the stack and return focus to that control. On a touchscreen, tap the peek to
open the stack. Interacting with the attached banner or composer does not open the stack.
When the composer has text, the arrow keys move the caret as usual. Recall takes over only while
the text is an unedited recalled prompt, with the caret on the first visual line for `ArrowUp` or
the last visual line for `ArrowDown`, counting wrapped lines. Editing a recalled prompt turns it
into a normal draft.
## Prompt stash
Use the default shortcut, `Cmd+S` on macOS or `Ctrl+S` on Windows and Linux, to stash the current
prompt and its attachments after all file uploads finish. Restore the entry later from the stash
menu. Stashes that contain files must be restored in the environment where those files were
uploaded. Stashed files stay uploaded on the server for 24 hours. If you restore an entry after
that, the file comes back with **Attach again** next to it. Attach the file again or remove it, then
send.
On web and desktop, press `Cmd+S` on macOS or `Ctrl+S` on Windows and Linux to save
the current prompt and its attachments for later. Wait for uploads to finish first.
With an empty composer, the same shortcut restores a single stash or opens the
stash menu when there are several.
Stashes containing uploaded files must be restored in their original environment.
Those files are retained for 24 hours. After an upload expires, restore the prompt
and use **Attach again** or remove the missing file before sending.
## Voice input on iPhone
On supported iPhones with iOS 26 or later, tap the microphone in the composer to record a message.
An expanded composer keeps your draft visible and flips its bottom toolbar into recording controls
with waves that respond to your voice. A collapsed composer flips into a compact recording strip
without changing height. Tap the checkmark to finish and transcribe on your device. The waves fade
into a transcription status, then the usual
controls return with the text inserted at the selection where recording started. If the keyboard
is open when you start, it stays open during voice input. You can review and edit the text before
you send it.
On supported iPhones with iOS 26 or later, use the composer's microphone to record,
then confirm to transcribe. Text is inserted where your selection was when
recording started, ready for you to review and edit before sending.
The first use can download Apple's speech model and needs a network connection. Later transcription
works offline for that language. A recording can be up to five minutes long. Canceling voice input,
leaving the screen, or an audio interruption discards the new recording and keeps the existing draft
and attachments. T3 Code deletes the local audio file after transcription or cancellation. It sends
only the normal message text when you submit the draft.
The first use may download Apple's speech model and needs a network connection.
Later transcription works offline for that language. Recordings can be up to five
minutes long. Canceling, leaving the screen, or an audio interruption discards the
recording and preserves your existing draft.
Transcription runs on your device. T3 Code deletes the temporary audio after
transcription or cancellation; only the message text is sent when you submit.
## Commands and skills
Type `/` to open the command menu. Type `$` to find and add a skill. Skill rows show their source,
such as System, Personal, Project, or App.
Type `/` for commands or `$` to add a skill from the selected environment and
provider. On mobile, both are also available before starting a thread on
**New task**.
On mobile, these menus are available on the **New task** screen before you start a thread. They
use the skills and commands from the selected environment and provider.
The slash menu also includes skills unless you turn off **Settings → General →
Show skills in slash menu**. Only skills enabled for the provider are listed.
By default, the `/` menu includes skills. To keep this menu command-only, turn off **Show skills in
slash menu** in **Settings → General**. Skill results use the `/skill:Skill Name` label and add the
same `$name` skill token to your message. The original skill name remains searchable. If the provider
also reports that skill as a native slash command, T3 Code hides the duplicate native entry and keeps
the `/skill:Skill Name` label.
Provider commands must start the message to run. T3 Code commands such as
`/model` and `/plan`, and skill mentions, work on any line.
A skill token runs the skill wherever it sits in your message. T3 Code sends it to each provider in
the form that provider runs, so the text before and after the token is kept. Skills that only you may
start, and never the agent on its own, work the same way. A skill you switched off in the provider's
settings does not appear in either menu.
Send `/compact` in an existing conversation to reduce context usage when the
provider supports it. Web and desktop also offer compaction from the context meter.
Provider commands such as `/compact` only run when they open the message, so the `/` menu offers
them only there. T3 Code's own commands, such as `/model` and `/plan`, and skills stay available on
any line.
## Images and videos in messages
On desktop, press `Cmd+Enter` on macOS or `Ctrl+Enter` on Windows and Linux from a new thread to
start it in the background. T3 Code opens another new thread and shows an **Open** action for the
thread that started. The new thread keeps the selected workspace mode and base branch. If **New
worktree** is selected, each background thread creates its own worktree.
Select an image or video attachment or link to preview it. Playback support depends
on your browser or device; save an unsupported video to open it in another app.
On web and desktop, right-click media to save it or copy its path or URL. On mobile,
touch and hold an image or video thumbnail and choose **Save or share**. On iOS,
return to the thumbnail to open this menu after watching a full-screen video.
File links refer to the environment's machine, including when you connect remotely.
Previews use the original file, even outside the workspace. Moving or deleting it
can break the preview, so save a copy if you need to keep it.
## Files outside the workspace
Follow an agent's file link to read a report or other file outside the workspace.
These files open read-only. An HTML file outside the workspace cannot load scripts,
styles, or images from neighboring files.
## HTML and PDF files in the file viewer
On web and desktop, HTML and PDF files open as rendered pages. Switch an HTML
file to source view to read its markup; a link to a specific line opens source
automatically. HTML previews cannot access your T3 Code session.
On mobile, select a PDF attachment or link to open it. iOS uses the native viewer;
Android opens the system chooser.
-92
View File
@@ -1,92 +0,0 @@
# Environment theme
Some desktops publish the palette they are currently wearing so that apps can match it. When the
machine running your T3 Code server does that, its themes appear in the theme library alongside
your own, and T3 Code follows them: change the desktop theme and T3 Code retints with it, without
a restart.
To use one:
1. Open **Settings**.
2. Select **Appearance**.
3. Choose the theme published by your environment.
Like every theme, this is a per-client choice: picking it on your desktop does not change what your
phone or another browser shows.
The machine can also set the environment's theme:
```bash
t3 theme set nightfall
```
Web and desktop clients switch to it — immediately when connected, on their next connect
otherwise — and a fresh client opens with it. Each client applies a set once, so picking a
different theme in Settings afterwards sticks until the next `t3 theme set`, and running the same
set again is how you bring clients back. `t3 theme clear` removes the setting without changing
what anyone currently has, and `t3 theme show` prints the current theme and everything the
machine publishes. Only the environment you are anchored to publishes themes, so a remote client
follows the machine it is connected to, not the device it runs on. T3 Code Mobile keeps its own
appearance settings and does not follow environment themes.
Select **Duplicate** on a published theme's card to keep a copy you can edit. The published theme
itself cannot be edited or removed, because the environment rewrites it whenever its own theme
changes. If the machine stops publishing it, the card disappears and clients using it fall back to
the standard T3 Code look. A theme you saved always wins over a published one with the same id.
When the theme editor is open, its draft stays visible while published themes change.
Close the editor to show the latest selected theme.
## Publishing themes
A machine publishes themes by writing files into the `themes` directory of the T3 Code state
directory (`~/.t3/userdata/themes/` by default). The filename is the theme id — `nightfall.json`
appears as `nightfall` — and stays stable while the machine rewrites the colors underneath, so
selections and defaults keep pointing at it.
The filename may not be an appearance keyword (`system`, `light`, `dark`) or a built-in theme's
id — those names already mean something on every client. Two formats are accepted. A theme
exported from T3 Code (the **Download** button's output) works as-is, so any theme someone shared
can be dropped in unchanged. Or, for a desktop that only knows
its own palette, a short seeded form:
```json
{
"name": "Nightfall",
"appearance": "dark",
"canvas": "#1a1b26",
"accent": "#7aa2f7"
}
```
`appearance` is `light` or `dark`, and `canvas` and `accent` are hex colors. T3 Code generates the
rest of the palette from those two, the same way the guided theme editor does, so the result reads
as a T3 Code theme wearing your desktop's colors rather than a transplant of another app's.
A machine that knows a role better than a derivation can guess — its terminal palette, its
semantic colors — can publish that role directly under `colors`, layered over the generated
palette:
```json
{
"name": "Nightfall",
"appearance": "dark",
"canvas": "#1a1b26",
"accent": "#7aa2f7",
"colors": {
"terminalSelection": "#292e42",
"error": "#f7768e"
}
}
```
Any of the roles shown in the theme editor's advanced view can be published this way; roles left
out keep their generated value. A role this version of T3 Code does not know is ignored rather
than rejected, so publishing a role added by a newer release is safe. An `id` inside the file is
ignored — the filename decides.
A theme with no usable colors is not listed on that client.
Write each file atomically — write a temporary file beside it and rename — so T3 Code never reads
a half-written theme. An unreadable or invalid file is simply not published; the machine's other
themes are unaffected.
+77 -100
View File
@@ -1,132 +1,109 @@
# Install T3 Code
T3 Code is a web and desktop GUI for running coding agents on your machine.
T3 Code runs coding agents on your computer and lets you control them from its
desktop, web, or mobile app. Set up the machine where the agents will work first.
## Requirements
Node.js `^22.16 || ^23.11 || >=24.10` on the machine that runs the T3 Code server.
Command-line use, SSH hosts, and WSL backends need Node.js 22.16+ (22.x), 23.11+
(23.x), or 24.10 and later. The native desktop app includes its server runtime.
At least one provider CLI, installed and authenticated. See [Providers](#providers) below.
You need an installed, authenticated provider before starting a thread. You can
launch T3 Code and configure providers afterwards.
## Run Without Installing
## Run without installing
```bash
npx t3@latest
```
This starts the T3 Code server on your machine and opens the local web app. Use
`npx t3@latest --help` for the full CLI reference.
This starts the server and opens the local web app. Run
`npx t3@latest --help` for command-line options.
## Open a project in the desktop app
## Desktop app
When the T3 Code desktop app is running on the same machine, open the current directory with:
Download a release from [GitHub Releases](https://github.com/pingdotgg/t3code/releases),
or use a package manager:
| Platform | Install |
| ------------------ | ------------------------------- |
| Windows | `winget install T3Tools.T3Code` |
| macOS | `brew install --cask t3-code` |
| Arch Linux | `yay -S t3code-bin` |
| Arch Linux nightly | `yay -S t3code-nightly-bin` |
### Windows Subsystem for Linux
Choose a WSL distro in **Settings → Connections** to run agents and projects
there. Install Node.js and provider CLIs inside that distro. T3 Code installs its
matching server runtime there automatically; the first launch after an app
update can take longer.
### Open a project from a terminal
With the desktop app already running on the same machine:
```bash
npx t3 app
```
Pass a path to open another directory:
This opens a new thread for the current directory, adding the project if needed.
Pass a path, such as `npx t3 app ../my-project`, to open another directory. It requires
the desktop app, so a standalone server or an SSH session is not enough. If the
command cannot reach the app, start or update the desktop app and try again.
```bash
npx t3 app ../my-project
```
## Mobile app
The command adds the directory as a project when needed, focuses the desktop app, and opens a new
thread. It does not launch the desktop app, open a browser, or start a T3 Code server. A background
server does not count as the desktop app. The command also rejects SSH sessions because a remote
shell cannot focus a local desktop window. The CLI package and the running desktop app must both
include `t3 app` support.
## Desktop App
Download the latest release from
[GitHub Releases](https://github.com/pingdotgg/t3code/releases), or install from a package
registry.
Windows:
```bash
winget install T3Tools.T3Code
```
macOS:
```bash
brew install --cask t3-code
```
Arch Linux:
Stable:
```bash
yay -S t3code-bin
```
Nightly:
```bash
yay -S t3code-nightly-bin
```
### Windows Subsystem for Linux
When the desktop app runs a WSL backend, it installs the matching server runtime into
`~/.t3/wsl-runtime` inside the selected distro. The first launch after installing or updating T3
Code may take a little longer while that release's runtime is extracted. Later launches reuse the
Linux-local copy so startup does not depend on reading application files through `/mnt/c`. After a
successful launch, T3 Code keeps the current runtime and one previous runtime for rollback and
removes older caches automatically. If a cached runtime stops working, T3 Code launches from the
application files under `/mnt/c` instead and reinstalls the runtime on the next launch.
Install T3 Code from the
[App Store](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824) or
[Google Play](https://play.google.com/store/apps/details?id=com.t3tools.t3code).
The phone connects to a server on another machine. Follow
[remote access](./remote-access.md) to link it through T3 Connect or a pairing URL.
## Providers
T3 Code drives provider CLIs; it does not ship them. Install the CLI for each provider you want
to use, then authenticate it.
Open **Settings → Providers** in the web or desktop app, select the environment,
and enable the provider you want. Installation, login, and configuration belong
to that environment's machine, even when you connect from a phone or another
computer.
| Provider | CLI | Default binary | Log in with |
| ---------- | ------------------------------------------------------------ | -------------- | --------------------- |
| Codex | [Codex CLI](https://developers.openai.com/codex/cli) | `codex` | `codex login` |
| Claude | [Claude Code](https://claude.com/product/claude-code) | `claude` | `claude auth login` |
| Cursor | [Cursor CLI](https://cursor.com/cli) | `cursor-agent` | `agent login` |
| Grok Build | [Grok Build CLI](https://x.ai/cli) | `grok` | `grok login` |
| Hermes | [Hermes Agent](https://github.com/NousResearch/hermes-agent) | `hermes` | `hermes setup` |
| OpenCode | [OpenCode](https://opencode.ai) | `opencode` | `opencode auth login` |
| Provider | Install and authenticate |
| ----------- | ---------------------------------------------------------------------------------------------- |
| Codex | Install [Codex CLI](https://developers.openai.com/codex/cli), then run `codex login`. |
| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. |
| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. |
| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. |
| Hermes | Install [Hermes Agent](https://github.com/NousResearch/hermes-agent), then run `hermes setup`. |
| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. |
| Antigravity | Install and sign in with Google from T3 Code's provider settings. |
Codex and Claude are on by default. Cursor, Grok Build, Hermes, and OpenCode are off by default;
turn them on in **Settings** → the provider's card when you want to use them. Hermes is
experimental — its provider card shows an **Experimental** badge; see
Provider CLIs must be on the server's `PATH`. If T3 Code cannot find one, set its
**Binary path** in provider settings, especially when using a version manager.
Cursor's executable is `cursor-agent`, although its login command is
`agent login`. Antigravity can use its managed runtime without a `PATH` entry.
Hermes is experimental — its provider card shows an **Experimental** badge; see
[Hermes](./providers-hermes.md) for details.
Cursor is the one to watch: install Cursor CLI, which provides the `cursor-agent` binary that
T3 Code looks for, but authenticate with `agent login`, not `cursor-agent login`.
When a provider CLI is behind its latest release, its provider card shows the
available version. **Update now** appears only when T3 Code can tell which
installer owns the CLI (its own update command, Homebrew, or a global npm, pnpm,
bun, or Vite+ install) and runs that installer. Otherwise update the CLI the same
way you installed it. Homebrew installs compare against the version Homebrew
offers, which can trail the npm release by a few hours.
Grok models that support adjustable reasoning show a **Reasoning** control beside the model picker.
The available levels and default come from the installed Grok Build CLI, so they can vary by model
and CLI version.
Add another provider instance for a separate account or configuration. Each
instance can have its own environment variables, such as API keys or a custom
base URL. Mark secret values as sensitive; after saving, T3 Code does not display
their original values.
Run the login command on the machine running the T3 Code server, not on the device you browse
from.
For provider-specific setup and accounts, see [Codex](./providers-codex.md),
[Claude](./providers-claude.md), [OpenCode](./providers-opencode.md), and
[Antigravity](./providers-antigravity.md).
### Binary Discovery
## Next steps
Each provider CLI must be on the server's `PATH`, or have an explicit binary path set in
**Settings** → the provider instance → **Binary path**. Use the explicit path when a version
manager or a non-standard install location keeps the CLI off the `PATH` of the shell that
started T3 Code.
### When Auth Is Needed
Provider auth is required before you start a session with that provider, not before you start
T3 Code. You can install T3 Code, open it, and add providers afterwards. A provider that is not
authenticated shows its status in **Settings** and fails at session start with the login command
to run.
For multi-account setups, see [Codex](./providers-codex.md) and [Claude](./providers-claude.md).
## Next Steps
- [Permission modes](./permission-modes.md): how much T3 Code asks before acting
- [Remote access](./remote-access.md): connect from a phone, tablet, or another desktop
- [Keeping T3 Code in sync](./updating.md): client and server version skew
- [Running in the background](./background-service.md): Linux background service
- [Working with threads](./thread-sidebar.md): start tasks and organize parallel work.
- [Permission modes](./permission-modes.md): choose when agents ask before acting.
- [Remote access](./remote-access.md): connect from another device.
- [Running in the background](./background-service.md): keep a Linux or macOS host available.
- [Updating T3 Code](./updating.md): update the app and connected servers.
+54 -82
View File
@@ -1,14 +1,13 @@
# Keybindings
Edit keybindings from **Settings** → **Keybindings**. That page lists every command, its current
shortcut, whether it is a default or your own, and warns about conflicts.
Customize shortcuts in **Settings → Keybindings** on web and desktop. That page
also lists the command IDs and defaults available in your version.
The same configuration lives in `~/.t3/userdata/keybindings.json` on the machine running the
server, if you prefer editing it directly. T3 Code writes the built-in defaults into that file on
first run, and adds any new defaults on later startups unless a rule of yours already claims the
command or the shortcut.
## Edit the configuration file
The file is a JSON array of rules.
Keybindings live on the environment's machine, in
`~/.t3/userdata/keybindings.json` by default. You can edit this file directly.
It is a JSON array of rules:
```json
[
@@ -17,90 +16,63 @@ The file is a JSON array of rules.
]
```
Invalid rules are ignored. An invalid file is ignored entirely, and the server logs a warning.
T3 Code creates the file with its defaults and adds new defaults on later startups.
New defaults do not replace commands you customized. If a new default overlaps one
of your shortcuts, [rule order](#precedence) decides which runs.
Invalid rules are ignored; if the file cannot be parsed, T3 Code uses defaults.
## Rule Shape
## Rule shape
- `key` (required): shortcut string, like `mod+j`, `ctrl+k`, `cmd+shift+d`
- `command` (required): the command ID to run
- `when` (optional): boolean expression controlling when the shortcut is active
Each rule requires a `key` shortcut and a `command` ID. An optional `when`
expression restricts when it runs.
## Key Syntax
Project scripts use `script.{id}.run`, such as `script.test.run`.
Modifiers: `mod` (`cmd` on macOS, `ctrl` elsewhere), `cmd` / `meta`, `ctrl` / `control`, `shift`,
`alt` / `option`.
## Key syntax
Examples: `mod+j`, `mod+shift+d`, `ctrl+l`, `cmd+k`.
Join modifiers and a key with `+`, such as `mod+shift+d` or `ctrl+l`.
`mod` means Command on macOS and Control elsewhere. Other modifiers are
`cmd` / `meta`, `ctrl` / `control`, `alt` / `option`, and `shift`.
## Commands
## When conditions
Commands are IDs like `terminal.toggle`, `commandPalette.toggle`, `preview.refresh`, and
`chat.new`. Project scripts are addressable as `script.{id}.run`, for example `script.test.run`.
Available context keys are `terminalFocus`, `terminalOpen`, `previewFocus`,
`previewOpen`, and `modelPickerOpen`. Unknown keys evaluate to `false`.
`filePicker.toggle` opens file search for the active project and defaults to `mod+p`.
`projectSearch.toggle` searches inside the active project's files and defaults to `mod+shift+f`.
Repeating either shortcut closes that search, and switching shortcuts replaces the open search.
`themeEditor.toggle` opens or closes the floating theme editor and defaults to
`mod+alt+shift+t`. Select a color label to spotlight the elements that use it; select the label
again to clear the spotlight. The swatch and hex field keep that color selected while you edit it.
Advanced mode groups related app tokens into a smaller set of color families. Changing a family
updates its paired text and interaction states while leaving every unrelated imported color intact.
Use **Inspect** to pick an element in the app and reveal its color token. Inspect disarms after one
successful pick; its hover glow and badge preview the element and color family that click will select.
**Cancel** or `Escape` exits Inspect and clears its selection and spotlight.
Combine keys with `!` for not, `&&` for and, `||` for or, and parentheses:
`rightPanel.toggleMaximized` maximizes or restores the open right panel. It has no default shortcut,
so add one in **Settings** → **Keybindings** if you want to use it.
`thread.copyReference` copies the active thread's pull request link, or its thread ID when no pull
request is available. Its default shortcut is `mod+shift+c`, and it does not replace terminal copy
while the terminal has focus.
`thread.settle` settles the active thread or restores it when it is already settled. Its default
shortcut is `mod+shift+s`, and it does not run while the terminal has focus.
`thread.pin` pins the active thread to the pinned section of the sidebar, or unpins it when it is
already pinned. Its default shortcut is `mod+shift+p`, and it does not run while the terminal has
focus. See [Organizing threads](./thread-sidebar.md) for how pinned threads are ordered.
The command palette searches settings, active thread titles, projects, branches, user messages, and
final agent responses across connected environments. A setting result opens its exact control or
section. Message matches show one labeled excerpt while keeping the thread's project, branch, and
machine context visible. Message search begins after two characters and uses SQLite's ASCII
case-insensitive matching.
The full command list and the current defaults are shown in **Settings** → **Keybindings**, which
always matches the build you are running. Use that rather than a copied list.
Note that `chat.new` and `chat.newLocal` both create a thread through the same path. A new thread
inherits the project you were in, along with model and mode selections. Branch, worktree, and
environment mode always come from your configured defaults, not from the thread you were looking
at. To keep a worktree, use the explicit "new thread in this worktree" action in the branch
toolbar. The only difference between the two commands: with the current sidebar and more than one
project, `chat.new` opens a project chooser first.
Background submission from a new thread is the exception. `mod+enter` starts that thread and opens
another new thread with the same workspace mode and base branch. **New worktree** remains selected,
but the new thread does not reuse the worktree created for the thread that just started.
## `when` Conditions
A `when` expression is evaluated against context keys describing the current UI state. The keys
the app supplies today are `terminalFocus`, `terminalOpen`, `previewFocus`, `previewOpen`, and
`modelPickerOpen`. The set is open and grows over time, so treat that as the current list rather
than a fixed one. Any key the running app does not supply evaluates to `false`.
Operators: `!` (not), `&&` (and), `||` (or), and parentheses.
Examples:
- `"when": "terminalFocus"`
- `"when": "terminalOpen && !terminalFocus"`
- `"when": "!terminalFocus"`
```json
{ "key": "mod+j", "command": "terminal.toggle", "when": "terminalOpen && !terminalFocus" }
```
## Precedence
- Rules are evaluated in array order.
- For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins.
- Precedence is across commands, not only within the same command. A later rule for a different
command can take a key away from an earlier one.
The last rule whose key and condition both match wins, even if it belongs to a
different command. Put a more specific rule after a general one when they share
a shortcut.
## Commands with special behavior
`chat.new` may ask you to choose a project when there is more than one.
`chat.newLocal` skips that chooser. Both use your
[new-thread defaults](./thread-sidebar.md#start-a-thread).
## Reserved shortcuts
In the desktop app, `mod+w` closes the focused terminal or the active right-panel
tab. When nothing remains to close, it closes the window. In a browser, `mod+w`
closes the browser tab; rebind `rightPanel.close` and `terminal.close` to an available
shortcut such as `alt+w`.
Many defaults include `!terminalFocus` so they do not intercept terminal input.
Keep that condition when remapping them if you want the same behavior.
## Desktop quit shortcut
Use `Cmd+Q` on macOS or `Ctrl+Q` on Windows and Linux. In the default **Hold** mode,
hold for 1.2 seconds or press twice within 500 milliseconds. Holding requires
keyboard repeat; if repeat is disabled, use two presses or the application menu.
Change **Settings → General → Confirmations → Quit shortcut** to **Direct** for a
single press or **Double press** for two presses only. Choosing **Quit** from the
application menu always quits immediately.
+9
View File
@@ -0,0 +1,9 @@
# Keyboard focus
The command palette keeps focus while open. Closing it returns focus to the composer.
While the palette or model picker is open, number shortcuts select its entries instead of
switching threads. Model shortcuts work in Settings as well as the composer.
See [Keybindings](./keybindings.md) to customize these shortcuts.
If you return to typing while a terminal is starting, the composer keeps focus when the terminal
becomes ready. Opening or switching to a terminal explicitly still focuses it.
-21
View File
@@ -1,21 +0,0 @@
# Mobile appearance
T3 Code Mobile includes the T3 Code, T3 Chat, Grove, Ocean, Ember, and Iris themes. Each theme has
light and dark colors that apply throughout the app, including code reviews, file previews, the
terminal, native headers, and sheets.
On supported iOS versions, the new-task and thread composers, working timer, and scroll-to-end
button use the system glass material. Other platforms use a themed background.
To change themes:
1. Open **Settings**.
2. Select **Appearance**.
3. Choose a theme.
4. Select **System**, **Light**, or **Dark**.
Tap a theme card to use it for both light and dark appearance. To mix themes, tap the light or dark
preview circle inside a card to change only that appearance.
**System** follows the device appearance automatically. Theme, text, code, and terminal appearance
preferences are stored on the device.
+21 -41
View File
@@ -1,51 +1,31 @@
# Permission Modes
# Permission modes
A permission mode controls how much the agent does on its own and when it stops to ask you.
Permission modes control when an agent needs your approval to act. Choose a mode in the message
composer; it applies to that thread.
The mode is set per thread, from the mode control in the message composer. Changing it in one
thread does not change any other thread. A thread created from inside another thread keeps that
thread's mode; otherwise new threads start in **Full access** unless you pick something else
before sending.
New threads start in **Full access** unless you choose another mode before sending. A thread
created from another thread inherits its mode.
## The Modes
| Mode | Behavior |
| --------------------- | ------------------------------------------------------------------------------------- |
| **Supervised** | Requests approval for commands and file changes. |
| **Auto-accept edits** | Approves file edits automatically; other actions can still require approval. |
| **Auto** | Uses the provider's automatic review to approve routine actions and ask about others. |
| **Full access** | Allows commands and edits without approval prompts. |
**Supervised**: ask before commands and file changes. The agent pauses and shows you what it
wants to run or edit, and waits for approval. Work outside the workspace is restricted.
Approve or reject requests in the conversation to let the agent continue. Permission modes do
not prevent the agent from asking questions about the task.
**Auto-accept edits**: auto-approve edits, ask before other actions. File changes go through
without prompting; commands and anything else still stop for approval.
## Provider differences
**Auto**: routine actions proceed without you; risky ones still ask. How this is enforced depends
on the provider: Codex delegates routine approvals to an AI reviewer, Claude uses its own auto
permission mode, and providers without an equivalent (such as OpenCode) fall back to asking, like
Supervised.
**Full access**: allow commands and edits without prompts. The default. The agent runs
unattended until it finishes or asks a question of its own.
Approvals appear inline in the conversation. Approve or reject one and the agent continues from
there.
Providers enforce permissions differently. Some read-only actions can proceed in **Supervised**.
**Auto** uses automatic review on Codex, Claude, and Cursor; providers without an equivalent,
including OpenCode and Antigravity, fall back to asking.
For Grok, **Always allow this session** remembers the matching command or tool input. Other
actions still ask for approval. It does not change the thread to **Full access**.
actions still require approval.
## Choosing a Mode
Antigravity can still send native approval requests in **Full access**. It only offers remembered
approvals for actions that support them.
Use **Full access** for work in a worktree or a sandbox you can throw away.
Use **Supervised** on a repository where an unwanted command is expensive, or the first time you
run an unfamiliar task.
**Auto-accept edits** suits refactors where the edits are the point and you only care about the
shell commands.
## Provider Behavior
Each provider maps these modes onto its own approval and sandbox settings. Codex, for example,
translates the mode into its approval policy and sandbox level, so **Supervised** runs the CLI
with prompting enabled and a restricted workspace while **Full access** disables both. Grok
threads do the same: **Supervised** starts Grok in ask mode even if your Grok CLI config is
set to always-approve, and **Full access** starts Grok with always-approve. The labels above
describe what you get; the exact per-provider translation is internal and may change.
Mobile offers the same four modes with the same labels and descriptions.
See the [provider guides](./install.md#providers) for setup and provider-specific limits.
+30 -11
View File
@@ -1,16 +1,35 @@
# Customize a project icon
# Project settings
T3 Code selects a project icon automatically. It checks `t3.json`, common favicon and app icon
paths, and icon links in project HTML files.
Open **Settings → Projects**. The project and machine pickers start at **All projects** and
**All machines**.
To choose a different icon:
Change the default model, workspace, automatic pull, agent browser access, or actions for projects that inherit those values.
Select an individual project to override a default. Reset its row to inherit again. Changing a
default preserves explicit project overrides. Workspace preferences in `t3.json` take precedence
over machine defaults when the project has no explicit workspace override.
1. Open **Settings** and select **Projects**.
2. Select the project.
3. Under **Appearance**, select **Choose a project file**.
4. Search for an image file and select it.
Select a machine to limit edits to it. **All machines** writes defaults to connected machines;
offline machines keep their previous values. Mixed values are indicated when selected machines
or checkouts disagree. Browser access changes apply when an agent session next starts.
T3 Code supports SVG, PNG, ICO, JPEG, GIF, AVIF, and WebP files. The selected path applies to
each checkout in the project group and appears on your connected clients.
Project grouping has a client-wide default across machines, with individual checkout overrides.
Shared actions apply to inheriting projects; editing a project's actions creates an independent list.
Reset that list to use shared actions again. Existing project actions are preserved.
To use automatic detection again, select **Automatic**.
Project names, icons, removal, and importing actions from a checkout remain project-specific.
When there are several checkouts, the checkout picker selects which actions and grouping to edit.
## Project icons
Choose an icon, emoji, or image from the project to make it easier to recognize. The choice applies
to selected checkouts in the project group and appears on connected clients. Choose **Automatic** to
let T3 Code detect an icon again.
## Keep the default branch current
Enable **Automatically pull** to keep the default-branch checkout up to date with its configured
upstream.
T3 Code only pulls when it can fast-forward and the checkout has no changed files, untracked files,
or local commits. It skips checkouts on another branch or without an upstream. If a checkout has
local work, resolve it yourself before automatic pulls can resume.
+142
View File
@@ -0,0 +1,142 @@
# Antigravity
T3 Code runs Google's official Antigravity ACP agent on your selected environment.
It has its own sign-in, separate from the Antigravity IDE or CLI. Google controls
which models and account access are available through this agent.
## Set up Antigravity
On web or desktop, open **Settings > Providers**, choose the environment that runs
your project, and enable Antigravity. Install its runtime there, then choose
**Sign in with Google** and complete the browser sign-in. Wait for T3 Code to confirm
account access and load models before starting a thread. Provider setup is not
available in the mobile app.
Installation continues if you leave settings or reconnect. Setup requires
permission to operate the environment; update an older server if it does not offer
Antigravity setup.
### Sign in from a remote device
Google returns to a `127.0.0.1` address. It can finish directly when your browser is
on the environment's machine. From another device, the final page will usually
fail to load because the sign-in listener is on the environment.
Copy the full return address, including everything after `?`, into the return URL
field in the web or desktop client where you started setup, then choose
**Continue**. Keep the original address; do not replace it with the server's
hostname. Only that T3 Code sign-in session can finish the attempt. If it expires,
retry sign-in and use the new link.
The return URL contains a temporary sign-in code. Paste it only into the setup
field. A successful callback page alone does not confirm account access; wait for
T3 Code's confirmation.
### Other sign-in methods
Choose **Sign-in method** in the Antigravity provider settings:
| Method | Credentials |
| -------------------------- | -------------------------------------------------------------------------------------------- |
| Google account | Personal Google sign-in in the browser |
| Gemini Enterprise | Browser sign-in, GCP project, and GCP location |
| Gemini API key | API key; choose Connect without a browser |
| Agent Platform / Vertex AI | API key, or GCP project and location with Application Default Credentials on the environment |
The Antigravity API key field is stored in plain text in settings on the
environment. The agent uses the method and credentials selected for this instance;
ambient `GEMINI_API_KEY` and Google credential variables do not override them.
Changing the method stops the instance's sessions. Sign out before replacing an
account.
## Runtime installation
Managed installation supports Apple Silicon macOS, Linux x64 or ARM64, and Windows
x64 or ARM64. Intel Macs can connect to a supported remote environment. Allow
several GB of free disk space, especially on Linux.
### Use a manual installation
Download the archive for your environment from the [official ACP Registry][registry].
Extract the ACP executable and its `localharness_external` helper into the same
directory, at the same version. Make both executable on macOS or Linux; Windows
uses `.exe` files.
Set **Binary path** to the ACP executable on the environment and update it yourself.
Leave the field blank to use the managed runtime, or a compatible executable on
`PATH` if no managed runtime is installed.
## Models and threads
The model list comes from your Antigravity account and can differ from other
Antigravity apps. A resumed thread keeps its selected model. If access to that
model ends, select another available model before continuing.
Use Antigravity's native `/plan` command for planning. T3 Code's separate Plan mode
is unavailable. Tool approvals follow [Permission modes](./permission-modes.md).
Questions with fixed choices still need one of the offered answers, even in
**Full access**.
T3 Code keeps conversation history and file diffs, but Antigravity cannot rewind
its conversation. Reverting a thread or editing and resubmitting an earlier turn
is unavailable. Continue with a follow-up message or start a new thread.
### Skills and attachments
Put project skills in `.agents/skills`. T3 Code also reads `.gemini/skills` and the
legacy `.agent/skills` directory. Among these project locations, the first copy
wins in this order: `.gemini/skills`, `.agents/skills`, `.agent/skills`. See
[commands and skills](./composer.md#commands-and-skills) for invoking them.
Skills for every project go in `~/.gemini/config/skills` or
`~/.gemini/antigravity-cli/skills`. Antigravity does not read `~/.agents/skills`,
so a skill there only appears when the project itself is your home directory.
Antigravity accepts images, PDFs, text files, and supported audio formats directly.
Its limits are 1 MiB per text file, 10 MiB per image, 20 MiB per audio clip, and
50 MiB total attachments per message. Unsupported formats are rejected. These
limits can be lower than the general upload limit; uploading a file does not
mean this provider can use it.
### Subagents
Antigravity groups subagent activity into batches. You cannot open or control
individual subagents, and an idle batch does not confirm that every child
succeeded. See [agent work](./thread-sidebar.md#inspect-agent-work) for where to
inspect activity.
## Accounts and removal
Add an Antigravity provider instance for each Google account in
**Settings > Providers** on web or desktop. Each has its own sign-in; downloaded
runtimes are shared on the environment.
| Action | Effect |
| ------------------------- | ----------------------------------------------------------------- |
| Disable | Stops the instance's sessions and keeps its Google sign-in. |
| Sign out of Google | Stops the instance's sessions and removes its saved Google login. |
| Remove downloaded runtime | Removes the shared installation and keeps Google credentials. |
All three keep thread history and workspace files. Sending `/logout` by itself in
a thread signs out its instance, including stopping that instance's other sessions.
Sign out, then sign in again to replace an account.
Before removing a managed runtime, disable its instances and cancel any active
installation. Clear any explicit binary path pointing into that runtime. Removal
is refused while the runtime is in use.
## Check access and troubleshoot
A server restart keeps your Google sign-in. The provider shows the saved account
until a session, a refresh, or a sign-out reports something new.
To check access and reload models, use **Refresh provider status** in web or desktop
provider settings, or **Refresh models** in mobile thread settings. If asked to
sign in again, use setup on web or desktop.
If Google reports `SUBSCRIPTION_REQUIRED`, an account restriction, or a usage limit,
follow the provider's message and any retry time. See [Google's account plans][plans]
for eligibility.
[registry]: https://github.com/agentclientprotocol/registry/blob/main/antigravity-acp/agent.json
[plans]: https://antigravity.google/docs/plans
+72 -207
View File
@@ -1,236 +1,101 @@
# Claude
This guide is for people who want to use more than one Claude setup in T3 Code. For Codex, see
[Codex](./providers-codex.md). For first-time setup, see [Install T3 Code](./install.md).
T3 Code uses Claude Code's login and configuration. Start with the default provider
for one account; [provider setup](./install.md#providers) covers installation and
shared provider settings.
Common reasons:
## Separate accounts or configurations
- use separate work and personal Claude accounts
- try a different Claude Code configuration without disturbing your main setup
- run Claude through a router such as Claude Code Router
- use external providers exposed through a Claude-compatible workflow
Use a separate Claude config directory for each account. This also works for named
presets that need different Claude settings or a router connection.
## I Only Use One Claude Account
Use the default provider.
Log in with Claude Code normally:
Keep your existing account in the default directory. On the environment's machine,
create the second login:
```bash
claude auth login
mkdir -p ~/.claude_personal
CLAUDE_CONFIG_DIR=~/.claude_personal claude auth login
```
In T3 Code Settings, your Claude provider can stay like this:
Add another Claude instance in **Settings > Providers**:
```text
Display name: Claude
Binary path: claude
CLAUDE_CONFIG_DIR path: empty
```
| Instance | Binary path | CLAUDE_CONFIG_DIR path |
| --------------- | ----------- | ---------------------- |
| Claude Work | `claude` | Leave empty |
| Claude Personal | `claude` | `~/.claude_personal` |
An empty `CLAUDE_CONFIG_DIR path` means T3 Code uses Claude Code's normal config directory.
An empty config-directory setting uses Claude Code's normal configuration. The
custom setting changes `CLAUDE_CONFIG_DIR`, leaving `HOME` and the system keychain
location intact. Use the same variable for the login command. Setting `HOME`
instead can put credentials where this provider will not find them.
When you set this field, T3 Code points Claude Code at that directory with the
`CLAUDE_CONFIG_DIR` environment variable. It does not change `HOME`, so your system keychain and
the rest of your environment stay as they are.
Check the account reported in provider settings after signing in. Existing
threads can switch only between Claude instances with the same config directory.
Separate account directories stay isolated, including their local conversation
state. Claude does not have Codex's shared-home and shadow-home arrangement.
## Reduce Context Usage
For presets that differ only in API keys or endpoints, use the instance's
**Environment variables**. Variable assignments do not belong in **Launch arguments**.
In Settings, open your Claude provider and set **Auto-compact after** to a token count between
`100000` and `1000000`. For example, `300000` compacts the conversation into a summary once it
reaches about 300,000 tokens, without changing the model's context window. Leave the field
empty to keep Claude Code's default behavior.
Claude Code's verbose mode can stay enabled when you use Claude for text generation, including
thread titles, branch names, commit messages, and pull request descriptions. On a remote connection,
T3 Code uses the Claude configuration on the connected server.
On web and desktop, when you return to an older Claude thread with a large context, T3 Code
offers to compact the conversation before you continue. You can also select **Compact context**
from the context meter. On every client, you can enter `/compact` in the message composer, and
Claude can show its own resume prompt when you continue an old session.
## Compact long conversations
## Where Claude Skills Are Loaded
Set **Auto-compact after** in the Claude provider settings to an integer between
`100000` and `1000000`. For example, `300000` asks Claude to summarize at about
300,000 tokens. This changes when compaction happens, not the model's context
window. Leave it empty for Claude Code's default.
T3 Code looks for Claude skills in the Claude config directory's `skills` folder and
`<workspace>/.claude/skills`, the two places Claude Code loads them from.
You can also send `/compact` in an existing conversation. Web and desktop offer
**Compact context** from the context meter and may suggest it when you return to
a large older thread. See [commands and skills](./composer.md#commands-and-skills)
for using composer commands.
If the same skill name exists in more than one folder, the one in the Claude config directory
wins, the same way Claude Code resolves it.
## Usage limits
A skill set to `off` in Claude Code's `skillOverrides` is left out of both composer menus. A skill
marked `disable-model-invocation` still appears, because you start it yourself when you pick it.
Claude Code runs one skill per message; when a message names several, the last one runs directly and
Claude starts the others through its Skill tool, which refuses skills marked
`disable-model-invocation`.
If your Claude subscription runs out of usage mid-turn, the thread shows which
limit was reached and the remaining wait when Claude provides a reset time.
Claude Code holds the turn until that window reopens, so it can keep showing as
working. Wait for the reset, or stop the turn and continue later. The warning's
timestamp shows when the displayed wait started.
## I Want Work And Personal Claude Accounts
## Skills
Use a different Claude config directory for each account.
Claude skills come from the config directory's `skills` folder and the project's
`.claude/skills` folder. If both define the same name, the config-directory copy
wins. Skills disabled in Claude's settings do not appear in the composer.
Example:
Use `$` in the composer to select a skill. Skills marked `disable-model-invocation`
can still be started by you. Invoke those one per message: Claude directly runs
only the last named skill and may try to start earlier ones through its Skill
tool, which refuses skills reserved for manual invocation.
```text
default config dir work account
~/.claude_personal_home personal account
```
## OpenRouter
### Set Up The First Account
Create a Claude instance with its own config directory, such as
`~/.claude_openrouter`, and keep **Binary path** set to `claude`. In that instance's
**Environment variables**, use:
Log in normally:
| Variable | Value |
| ---------------------- | ----------------------------------------- |
| `ANTHROPIC_BASE_URL` | `https://openrouter.ai/api` |
| `ANTHROPIC_AUTH_TOKEN` | Your OpenRouter API key, marked Sensitive |
| `ANTHROPIC_API_KEY` | An explicitly empty value |
```bash
claude auth login
```
If that Claude config directory has a cached Anthropic login, run `/logout` in a
Claude Code session using that directory before starting the router setup. Cached
login credentials can conflict with the router token.
In T3 Code Settings:
Verify requests in OpenRouter's activity dashboard. For model-role overrides and
current compatibility requirements, use the
[OpenRouter Claude Code guide](https://openrouter.ai/docs/cookbook/coding-agents/claude-code-integration).
```text
Display name: Claude Work
Binary path: claude
CLAUDE_CONFIG_DIR path: empty
```
## Other routers
### Set Up The Second Account
Log in with a separate config directory:
```bash
mkdir -p ~/.claude_personal_home
CLAUDE_CONFIG_DIR=~/.claude_personal_home claude auth login
```
Use `CLAUDE_CONFIG_DIR`, not `HOME`. Setting `HOME` writes the login to
`~/.claude_personal_home/.claude`, which is not where T3 Code looks.
Then add another Claude provider in T3 Code:
```text
Display name: Claude Personal
Binary path: claude
CLAUDE_CONFIG_DIR path: ~/.claude_personal_home
```
Use the email shown in Settings to confirm each provider is using the intended account. Emails are
blurred by default; click the blurred email to reveal it.
## Can I Switch Claude Accounts In An Existing Thread?
Usually, no.
T3 Code only offers Claude providers that use the same config directory for an existing thread. A
different config directory is treated as a different Claude environment.
This is different from the recommended Codex setup. Claude Code keeps account and local state across
multiple files under its config directory, so T3 Code keeps separate config directories isolated
instead of trying to share part of the state.
## I Want To Use OpenRouter
Use this when you want Claude Code to talk to OpenRouter directly, without running a local router.
This is the simplest external-provider setup.
OpenRouter provides a Claude Code integration through Claude's Anthropic-compatible environment
variables.
### Configure A Claude OpenRouter Provider
Add or edit a Claude provider in T3 Code Settings:
```text
Display name: Claude OpenRouter
Binary path: claude
CLAUDE_CONFIG_DIR path: ~/.claude_openrouter_home
```
In that provider's Environment variables section, add:
```text
ANTHROPIC_BASE_URL https://openrouter.ai/api
ANTHROPIC_AUTH_TOKEN sk-or-... Sensitive
ANTHROPIC_API_KEY Empty value
```
Mark `ANTHROPIC_AUTH_TOKEN` as sensitive. T3 Code stores the value as a server secret and does not
send it back to the app after saving.
If you want this setup isolated from your normal Claude account, create that home first:
```bash
mkdir -p ~/.claude_openrouter_home
```
If you previously used the same Claude home with a normal Anthropic login, run `/logout` in a Claude
Code session for that home before using OpenRouter. Otherwise Claude Code may keep using cached
Anthropic credentials instead of the OpenRouter token.
### Pick OpenRouter Models
OpenRouter can route Claude Code's default model roles to OpenRouter model IDs.
Example:
```text
ANTHROPIC_DEFAULT_OPUS_MODEL anthropic/claude-opus-4.6
ANTHROPIC_DEFAULT_SONNET_MODEL anthropic/claude-sonnet-4.6
ANTHROPIC_DEFAULT_HAIKU_MODEL anthropic/claude-haiku-4.5
CLAUDE_CODE_SUBAGENT_MODEL anthropic/claude-sonnet-4.6
```
Add those to the same provider's Environment variables section if you want stable model choices.
### Verify OpenRouter Is Being Used
Open a Claude session and run:
```text
/status
```
You should see the Anthropic base URL set to:
```text
https://openrouter.ai/api
```
You can also check the OpenRouter activity dashboard for requests from your API key.
### Common OpenRouter Mistakes
- Use `https://openrouter.ai/api`, not `https://openrouter.ai/api/v1`, for Claude Code.
- Set `ANTHROPIC_AUTH_TOKEN` to your OpenRouter API key.
- Set `ANTHROPIC_API_KEY` to an empty string so Claude Code does not try to use an Anthropic login.
- Put these variables on the Claude provider instance, not in global shell startup files.
OpenRouter's setup can change over time. Use its upstream Claude Code guide for the current details:
<https://openrouter.ai/docs/guides/guides/claude-code-integration>.
## I Want To Use Claude Code Router
Claude Code Router is useful when you want a local routing layer with more control than a direct
OpenRouter setup.
T3 Code does not need a special Claude Code Router provider. Treat the router as a Claude
environment: give a Claude provider its own `CLAUDE_CONFIG_DIR path`, and put whatever variables
the router tells you to export into that provider's Environment variables section. Mark tokens
and API keys as sensitive.
```text
Display name: Claude Router
Binary path: claude
CLAUDE_CONFIG_DIR path: ~/.claude_router_home
```
Follow the upstream project's README for the router's own install, startup, and configuration
steps: <https://github.com/musistudio/claude-code-router>.
## I Want Different Claude Settings, Not A Different Account
Create another Claude provider with the same account if you want a named preset.
Examples:
- "Claude Default"
- "Claude Router"
- "Claude Experimental"
If the preset needs different Claude files, give it a different `CLAUDE_CONFIG_DIR path`. If it needs
different API keys, base URLs, or router settings, use Environment variables.
Do not put environment variable assignments in `Launch arguments`.
A local router uses an ordinary Claude provider instance. Give it a separate
config directory and put the router's endpoint and credential variables in that
instance's **Environment variables**. The router must run where the environment
can reach it. Follow the [Claude Code Router instructions](https://github.com/musistudio/claude-code-router)
for its installation and routing configuration.
+62 -148
View File
@@ -1,159 +1,73 @@
# Codex
This guide is for people who want to use more than one Codex account in T3 Code. For Claude, see
[Claude](./providers-claude.md). For first-time setup, see [Install T3 Code](./install.md).
For one account, use the default Codex provider with your normal Codex login.
[Provider setup](./install.md#providers) covers installation, Settings > Providers,
and custom binaries or environment variables.
Common reasons:
## Use multiple accounts
- use a work account for work projects
- use a personal account for personal projects
- switch to another account when one account hits limits
- keep one shared Codex history instead of maintaining two separate Codex setups
A shared Codex home with a shadow home lets work and personal accounts continue
the same threads. The accounts share Codex sessions and configuration while keeping
their own login and available models.
## I Only Use One Codex Account
Use the default provider.
In Settings, your Codex provider can stay like this:
```text
Display name: Codex
CODEX_HOME path: ~/.codex
Shadow home path: empty
```
Log in with Codex normally:
Keep your first account in `~/.codex`. On the environment's machine, sign the
second account into a fresh directory:
```bash
codex login
mkdir -p ~/.codex_personal
CODEX_HOME=~/.codex_personal codex login
```
Then add a second Codex instance in **Settings > Providers**:
| Instance | CODEX_HOME path | Shadow home path |
| -------------- | --------------- | ------------------- |
| Codex Work | `~/.codex` | Leave empty |
| Codex Personal | `~/.codex` | `~/.codex_personal` |
Both instances must use the same **CODEX_HOME path**. T3 Code prepares the shared
state in the shadow directory; do not populate it by copying your whole Codex
home.
The shadow account needs its own `auth.json` file. If Codex uses an OS credential
store, configure file storage for this setup. See
[OpenAI's credential storage guide](https://learn.chatgpt.com/docs/auth#credential-storage).
Use a completely separate **CODEX_HOME path**, with no shadow home, when you want
separate Codex sessions and configuration. That instance cannot continue threads
from the other home.
## Switch accounts in an existing thread
Choose the other account from the thread's model picker. T3 Code offers compatible
Codex instances that share the thread's **CODEX_HOME path**. Changing accounts does
not move the conversation into a separate Codex home.
If the account is missing from the picker, compare the home paths in provider
settings. If two instances show the same unexpected account or models, check their
reported accounts, refresh provider status, and confirm the second instance has
its own shadow path and login. A shadow-home conflict usually means the directory
contains a copied Codex setup. Use a fresh shadow directory and sign in again.
## Answer questions while Codex works
Codex can ask a question and keep working. Answer it in the thread's question
panel. The answer becomes a new message: it reaches the active turn, or starts
another turn if Codex has finished. Unanswered questions survive reconnects.
If you do not want to answer, dismiss the question from its panel. Dismissing
closes it without sending anything to Codex. This requires a Codex version that
supports async questions.
## Approve app access
Codex tools can request access to another app. Respond to the named app's request
in the thread on web, desktop, or mobile. Some tools offer access for one request,
the current session, or permanently. See [Permission modes](./permission-modes.md)
for command and file approvals.
## Send feedback to OpenAI
In an existing Codex thread, send `/feedback` or `/feedback` followed by a description of the
issue. T3 Code uploads the thread and Codex logs to OpenAI and shows a thread ID that you can copy
and share with OpenAI employees.
## Sub-agent models
The web and desktop Agents panel shows each sub-agent's model and reasoning effort when Codex
reports them. If Codex does not report either value, T3 Code leaves it out instead of using the
parent agent's settings.
## Approve access to other apps
When a Codex tool needs access to an app such as Safari, T3 Code shows the app name and asks for
approval. You can approve, decline, or cancel the request from the desktop app, web app, or mobile
app. Some tools also offer approval for the current session or permanent approval.
## I Want Work And Personal Codex Accounts
Use one real Codex home and one shadow home.
Recommended setup:
```text
~/.codex shared Codex home
~/.codex_p second account auth
```
The idea is:
- both accounts can see the same T3/Codex sessions
- each account keeps its own login
- existing threads can continue with either account
### Set Up The First Account
Log in normally:
```bash
codex login
```
This is the account used by `~/.codex`.
In T3 Code Settings, name it something obvious:
```text
Display name: Codex Work
CODEX_HOME path: ~/.codex
Shadow home path: empty
```
### Set Up The Second Account
Log in with a separate Codex home:
```bash
mkdir -p ~/.codex_p
CODEX_HOME=~/.codex_p codex login
```
In T3 Code Settings, add another Codex provider:
```text
Display name: Codex Personal
CODEX_HOME path: ~/.codex
Shadow home path: ~/.codex_p
```
The important part is that both providers use the same `CODEX_HOME path`, but only the second one
has a `Shadow home path`.
## Which Account Am I Using?
Open Settings and look at the provider row.
T3 Code shows the authenticated email for providers that report one. Emails are blurred by default;
click the blurred email to reveal it.
Use display names and accent colors to make accounts easy to tell apart in the model picker.
## I Need A Different API Key Or Endpoint
Use the provider's Environment variables section in Settings.
This is useful when a Codex-compatible setup needs account-specific variables. Add the variables to
the provider instance that should receive them, and mark API keys or tokens as sensitive. Sensitive
values are stored as server secrets and are not sent back to the app after saving.
## Can I Switch Accounts In An Existing Thread?
Yes, when both Codex providers share the same `CODEX_HOME path`.
For example:
```text
Codex Work CODEX_HOME path: ~/.codex
Codex Personal CODEX_HOME path: ~/.codex, Shadow home path: ~/.codex_p
```
Those two providers are considered compatible for continuation, so the locked model picker can show
both.
If you add a third Codex provider with a completely different `CODEX_HOME path`, T3 Code treats it
as a different workspace. It will not be offered for existing threads created under `~/.codex`.
## If Both Accounts Look The Same
If two Codex providers show the same account or the same unexpected model list:
1. Check the email in Settings.
2. Refresh provider status.
3. Confirm the second provider has `Shadow home path` set.
4. Confirm the shadow directory has its own `auth.json`.
5. If you copied `~/.codex` into the shadow directory, remove everything except `auth.json`.
Example cleanup:
```bash
find ~/.codex_p -mindepth 1 ! -name auth.json -exec rm -rf {} +
```
## When To Use A Separate CODEX_HOME
Use a totally separate `CODEX_HOME path` only when you want a separate Codex workspace.
That means separate sessions and less account switching inside old threads. Most dual-account users
should use the shared-home plus shadow-home setup instead.
In an existing Codex thread, send `/feedback` with an optional description, for
example `/feedback The agent stopped before finishing the tests`. This uploads
the conversation and Codex logs to OpenAI. The returned thread ID can be shared
with OpenAI support.
+36 -49
View File
@@ -1,62 +1,49 @@
# OpenCode
T3 Code uses the OpenCode setup on the connected environment. With a remote environment, its
OpenCode login and configuration apply, not the setup on your desktop or phone.
Install and authenticate OpenCode on the machine running your environment, then
enable it in **Settings > Providers**. See [provider setup](./install.md#providers).
T3 Code requires OpenCode 1.14.19 or newer, including when you connect an existing
OpenCode server.
T3 Code requires OpenCode 1.14.19 or newer. It checks the server version before it loads models or
starts work. If the check fails, update OpenCode or fix the server URL and password, then refresh
the provider status. Reconnecting the client also runs the check again.
## Local or external server
## Server authentication
Leave **Server URL** empty to let T3 Code start OpenCode locally. A password in
provider settings applies to both that server and T3 Code's connection. With no
password setting, the local server uses `OPENCODE_SERVER_PASSWORD` from its
environment.
Without a server URL, T3 Code starts a local OpenCode server. The process inherits
`OPENCODE_SERVER_PASSWORD` from the environment. A password in the provider settings overrides
that environment value for both the local process and T3 Code.
To use an existing OpenCode server, set **Server URL** and its password in provider
settings. T3 Code uses only that configured password for an external server; it
does not forward a local `OPENCODE_SERVER_PASSWORD`. If connection or version checks
fail, check the URL, credentials, and OpenCode version, then refresh provider status.
With a server URL, T3 Code connects to that external server and uses only the password in the
provider settings. It does not send a local `OPENCODE_SERVER_PASSWORD` to an external server.
OpenCode uses this password for HTTP Basic authentication.
After a lost connection, send another prompt to reconnect to the same OpenCode
session.
## Stop a turn
## Approvals
When you select **Stop**, T3 Code stops the main OpenCode session and all nested child sessions.
T3 Code waits for this cleanup before it marks the turn as stopped or sends the next prompt. It
does not stop unrelated OpenCode sessions.
OpenCode follows the shared [permission modes](./permission-modes.md). **Auto** has
the same rules as **Supervised** because OpenCode has no AI approval reviewer.
Environment files such as `.env` and `.env.local` need approval in restricted
modes even though normal file reads do not; `.env.example` is allowed.
Stop reports an error if OpenCode cannot list or stop a child session. When T3 Code closes an
OpenCode session, it also tries to stop the child sessions, but this teardown is best effort.
**Allow for workspace** applies to matching requests in other OpenCode sessions
using the same workspace. It is broader than the current thread, especially on a
shared external server. Use **Allow once** for a single request. Denying an action
does not stop the whole turn.
## Refresh the model list
## Refresh models, commands, and skills
T3 Code loads the model list when an enabled OpenCode provider starts and keeps the list in its
cache. Reconnecting a client or using a refresh control asks OpenCode for the list again. The
periodic provider health setting does not refresh OpenCode's catalog.
After changing an OpenCode login or configuration, use **Refresh provider status**
in **Settings > Providers** for that environment. On mobile, use **Refresh models**
in the thread settings. Reconnecting also refreshes the catalog; periodic provider
health checks do not.
After changing an OpenCode login or configuration outside T3 Code, open **Settings > Providers**,
select the environment, and choose **Refresh provider status**. Changing the provider's
configuration in T3 Code also replaces that provider connection.
Credential changes are read on refresh. Native OpenCode configuration can remain
cached while the local helper is running. Let it sit for 30 seconds without model
refreshes or text-generation work, then refresh again to reload the files. Repeated
refreshes keep the helper alive. An external server may need its own reload or
restart before T3 Code can see configuration changes.
On mobile, open the thread settings and select **Refresh models**. The control stays disabled while
the refresh runs and shows an error if the refresh fails.
OpenCode reads credential changes on each model-list request. Native OpenCode configuration files
can stay cached while the local helper is running. The helper closes after 30 seconds with no
model-list or text-generation work. Refresh after that idle period to start a new helper and read
the file changes. Repeated refreshes or active helper work can extend this wait.
T3 Code does not own an external OpenCode server. Native configuration changes on that server can
require its own reload or restart before a refresh returns the new list.
If a refresh fails, T3 Code keeps the last known models, slash commands, and skills. Fix the
connection, then refresh again. A successful refresh can remove entries that OpenCode no longer
offers.
## Continue an existing thread
An existing thread keeps its selected model and options when that model is temporarily absent
from the catalog. The web picker shows an **Unavailable** row and keeps saved option values visible
until the model metadata returns. T3 Code does not switch the thread to the first model in the
list.
The stored selection does not guarantee that OpenCode can still run the model. If the provider
rejects it, select an available model before trying again.
Existing threads keep their selected model and options even when it disappears
from the catalog. If OpenCode rejects that model, select an available one and retry.
+142 -194
View File
@@ -1,240 +1,188 @@
# Remote Access
# Remote access
Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
Connect a phone, browser, or another desktop app to T3 Code running on a different
machine. That machine must stay running and reachable while you work.
## Quick Pairing for a Running Server
## T3 Connect
If a server is already running on this machine, mint a fresh pairing token and QR code without restarting anything:
T3 Connect makes an environment available to your other devices without setting
up router forwarding. In the desktop app on the host, open **Settings →
Connections**, sign in, and enable **T3 Connect** for that environment.
For a command-line host, run:
```bash
npx t3@latest connect
```
Follow the sign-in instructions. Setup offers a
[background service](./background-service.md); if you decline it, start the
server with `npx t3 serve`. Saving your sign-in alone does not make the machine
reachable.
On your other device, sign in to the same T3 Connect account and choose the
environment. Over SSH, the CLI prints a browser link and accepts the returned
authorization code, so you do not need to forward an OAuth callback port.
T3 Connect renews access credentials when needed without disconnecting a healthy
connection. Pull request diffs and provider settings keep working after the
previous credential expires. A failed renewal affects that request; it does not
disconnect an otherwise healthy conversation.
## Pair over a LAN or private network
Use direct pairing when the other device can reach the host's network address.
On a desktop host, open **Settings → Connections**, enable **Network access**,
then create a pairing link using an address the other device can reach. Changing
network access restarts the desktop app. You can turn it off in the same place.
For a command-line host, replace `<private-ip>` with the host's LAN or tailnet
address:
```bash
npx t3 serve --host <private-ip>
```
If a server is already running, generate a fresh link without restarting it:
```bash
npx t3 pair
```
`t3 pair` finds the running server (the shared `~/.t3` install, or the current worktree's dev server when run inside one), issues a one-time pairing token, and prints the pairing URL as a QR code you can scan from your phone.
Scan the QR code on your phone or paste the pairing URL into **Add environment**
in the receiving app. Connection settings are under **Settings → Connections**
on web and desktop and **Settings → Environments** on mobile. A loopback address
such as `127.0.0.1` reaches only the device opening the link.
If the server is only bound to loopback, the printed URL is not reachable from another device. Pair over your tailnet instead:
Pairing authorizes that device for future connections. Use a fresh one-time link
for each new device; you do not need the original token to reconnect. Links
created in Settings can only be copied from the client that created them while
its Connections page stays open. If you leave or reload that page, create
another link to share.
```bash
npx t3 pair --tailscale
```
### Balance new threads across machines
This publishes the server over Tailscale Serve HTTPS (configuring the mapping if needed — it persists until you run `tailscale serve --https=443 off`) and pairs through the `https://machine.tailnet.ts.net/` URL. Use `--tailscale-serve-port` for a different HTTPS port, `--ttl` to change the token lifetime, and `--base-dir` to target a specific data directory.
Auto balance is off by default. On web and desktop, enable it in
**Settings → Connections → Load balancing** to automatically choose a machine for
new threads in projects grouped across connected environments.
Each machine starts at **Normal**. Choose **Prefer** to favor it when it has CPU and
memory available, **Less often** to reduce its share, or **Manual only** to exclude
it from automatic selection. These are preferences, not fixed traffic percentages.
Preferences are saved separately in each client.
If no server is running, `t3 pair` says so and points you at `npx t3 serve` or `npx t3 connect`.
The composer checks eligible machines when choosing a draft's environment, then keeps
that choice stable. Choose **Auto balance** again to check current resources, or choose
a specific machine to override it. Choosing a branch or worktree also keeps the draft
on that machine. Existing threads stay where they started. If resource checks are
unavailable or all eligible machines are full, choose a machine manually to continue.
Mobile keeps its manual environment selection.
## Recommended Setup
### Tailscale HTTPS
Use a trusted private network that meshes your devices together, such as a tailnet.
Join both devices to the same tailnet. In the desktop app, enable **Tailscale
HTTPS** in **Settings → Connections**. Turn it off there to remove that route.
That gives you:
- a stable address to connect to
- transport security at the network layer
- less exposure than opening the server to the public internet
## Enabling Network Access
There are three ways to reach your server from another device: expose the desktop app's backend,
run a headless server from the CLI, or have the desktop app launch T3 Code over SSH.
### Option 1: Desktop App
If you are already running the desktop app and want to make it reachable from other devices:
1. Open **Settings** → **Connections**.
2. Under **This environment**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
3. The settings panel will show the default reachable endpoint, with a `+N` control when more endpoints are available. Expand it to inspect alternatives such as loopback, LAN, private-network, or HTTPS endpoints.
4. Use **Create Link** to generate a pairing link you can share with another device.
The default endpoint controls the QR code and primary copy action for pairing links. You can change it from the expanded endpoint list. The preference is stored by endpoint type, so choosing the local LAN endpoint survives normal IP address changes when you move between networks.
When no user default is saved, the app uses the built-in LAN endpoint for pairing links when
available. You can set another endpoint as the default from the expanded endpoint list.
- HTTPS/WSS-compatible endpoints work from `https://app.t3.codes`, but are not made the default
automatically.
- Non-loopback HTTP endpoints are useful for direct LAN pairing.
- Loopback-only endpoints are not useful for another device unless that device is the same machine.
If the copied link points directly at `http://192.168.x.y:3773`, open it from a client that can reach that LAN address. If it points at `https://app.t3.codes/pair?...`, the hosted web app will save the environment and connect directly to the backend URL in the link.
In the mobile app's **Add Environment** form, a numeric IP address without a scheme uses HTTP. Include `https://` explicitly when the backend is served over HTTPS.
### Tailscale Endpoints
When the desktop app can detect Tailscale, it adds Tailnet endpoints to the reachable endpoint list.
Depending on your Tailscale setup, this may include:
- the machine's `100.x.y.z` Tailnet IP
- a MagicDNS name
- an HTTPS MagicDNS endpoint when Tailscale Serve is configured for this backend
The Tailscale HTTPS endpoint uses the clean MagicDNS URL, such as
`https://machine.tailnet.ts.net/`, and is off until you opt in. Turn on **Enable Tailscale HTTPS**
on the **Tailscale HTTPS** row in **Settings** → **Connections**. The desktop app restarts the
backend with the same server-side behavior as `t3 serve --tailscale-serve`, then the server asks
Tailscale Serve to proxy HTTPS traffic to the local backend. Turn the same switch off to stop it.
The Tailscale support is an endpoint provider add-on. The core remote model still works without Tailscale: LAN HTTP endpoints, custom HTTPS endpoints, future tunnels, and SSH-launched environments all use the same saved environment and pairing flow.
For `https://app.t3.codes`, prefer an HTTPS Tailnet or other HTTPS endpoint. A plain `http://100.x.y.z:3773` endpoint can still work from a desktop client or another browser page served over HTTP, but it will not work from the hosted HTTPS app because of browser mixed-content rules.
### Option 2: Headless Server (CLI)
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
Run the server with `t3 serve`.
```bash
npx t3 serve --host "$(tailscale ip -4)"
```
`t3 serve` starts the server without opening a browser and prints:
- a connection string
- a pairing token
- a pairing URL
- a QR code for the pairing URL
From there, connect from another device in either of these ways:
- scan the QR code on your phone
- in the desktop app, enter the full pairing URL
- in the desktop app, enter the host and token separately
- in the hosted web app, open a hosted pairing URL when the backend is reachable over HTTPS
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
For hosted web pairing over Tailscale HTTPS, opt in to Tailscale Serve:
To start a command-line server with Tailscale HTTPS:
```bash
npx t3 serve --tailscale-serve
```
By default this configures Tailscale Serve on HTTPS port 443 and advertises
`https://machine.tailnet.ts.net/`. Advanced users can choose a different HTTPS port:
For an already-running server:
```bash
npx t3 serve --tailscale-serve --tailscale-serve-port 8443
npx t3 pair --tailscale
```
Once paired, add projects normally: open the Command Palette and choose **Add Project**, then pick
the environment the project lives on. Every saved environment is offered, not only the local one.
The pairing link uses an address such as `https://machine.tailnet.ts.net/`.
The mapping created by `pair --tailscale` persists across restarts. Remove its
default-port mapping with:
### Option 3: Desktop-Managed SSH Launch
Use this when you want the desktop app to start or reuse T3 Code on another machine over SSH.
1. Open **Settings** → **Connections**.
2. Under **Remote Environments**, choose **Add environment**.
3. Select the SSH launch flow.
4. Enter the SSH target, such as `[email protected]`.
5. Confirm the launch. The desktop app probes the host, starts or reuses a remote T3 server, opens a local port forward, and saves the environment.
After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint. The remote host still owns the actual T3 server, projects, files, git state, terminals, and provider sessions.
SSH launch is a desktop feature because it needs local process and SSH access. Once the environment is paired and saved, it uses the same environment list and connection model as direct LAN, Tailscale, HTTPS, or future tunnel-backed environments.
#### SSH Launch Troubleshooting
The desktop SSH launcher connects with a non-interactive `sh` session, writes a small launcher script under `~/.t3/ssh-launch/<host-key>/`, starts or reuses a remote T3 server, and forwards the remote loopback port back to your desktop.
The remote host must have a compatible Node.js runtime. T3 Code uses the server package's `engines.node` requirement:
```text
^22.16 || ^23.11 || >=24.10
```bash
tailscale serve --https=443 off
```
During SSH launch, T3 Code first checks whether `node` is on `PATH`. If it is missing, the launcher
looks in the usual install directories and tries to activate a version manager if it finds one
(Volta, asdf, mise, fnm, nodenv, nvm). That covers most setups, but a version manager that only
initializes from an interactive shell profile will not be picked up.
If that port is already in use, choose another with
`--tailscale-serve-port`. See `npx t3 pair --help` for other pairing options.
If launch fails with `node: command not found`, a port-scan failure, or a message that the remote Node version does not satisfy the required range, SSH into the host and check the same non-interactive shell path T3 Code uses:
### Hosted web app
[app.t3.codes](https://app.t3.codes) needs an HTTPS endpoint. It connects directly
to your server; a hosted pairing link does not make an unreachable backend
reachable or convert HTTP to HTTPS.
For a plain HTTP LAN endpoint, use the direct pairing URL in a browser that can
open it, or pair from the desktop app. On mobile, an IP address entered without a
scheme uses HTTP, so include `https://` when your server uses HTTPS.
## Desktop-managed SSH
In the desktop app, open **Settings → Connections → Add environment**, choose
**SSH**, and enter a host or SSH alias such as `[email protected]`. T3 Code starts
or reuses a server there and opens the port forward for you. Projects, provider
credentials, and agent work stay on the remote machine.
The remote host needs a compatible [Node.js installation](./install.md#requirements)
and [provider setup](./install.md#providers). If launch cannot find Node or reports
an incompatible version, check it through a non-interactive SSH session:
```bash
ssh user@example.com 'sh -lc "command -v node && node --version"'
```
If that does not print a compatible Node version, configure your version manager for non-interactive shells or install a compatible Node binary in one of the searched locations. For example, with nvm you may need a default alias:
Configure your version manager for non-interactive shells if this differs from
your normal terminal. With nvm, setting a compatible default, such as
`nvm alias default 24`, can resolve the problem.
```bash
nvm alias default 24
```
If SSH reconnecting fails after an app update, retry the launch once. Removing
the connection stops a server that T3 Code launched; a server that was already
running is left alone.
With mise, asdf, fnm, or nodenv, make sure the tool's shim directory is installed and resolves to a Node version satisfying the range above without an interactive shell.
For Antigravity's Google callback on a remote host, see
[remote sign-in](./providers-antigravity.md#sign-in-from-a-remote-device).
If reconnecting after an app update fails, retry the SSH launch once. The launcher now compares its generated runner script, stops stale launcher-managed remote servers, clears the SSH launch PID/port state, and starts a fresh remote server. You should not normally need to delete `~/.t3/ssh-launch` or kill `t3` processes manually.
## Manage or revoke access
## Updating a Remote Server
On the host, **Settings → Connections** lets authorized administrators create
pairing links and revoke client sessions. Revoking an unused link prevents new
pairings; revoke a device's session to remove its existing access. Command-line
management is available through `npx t3 auth --help`.
When the T3 Code web or desktop app and a remote server use different versions, a warning appears in
the conversation and in **Settings** → **Connections**. Follow the action shown there: T3 Code may
be able to update and reconnect the server for you, or it may ask you to update the desktop app or
run a copied command on the server machine.
A session with an open connection stays listed after its access credential
expires.
If T3 Connect cannot connect, check the date and time on both devices, then try again.
To remove an environment from T3 Connect, open your account menu's **T3 Connect**
page, or **Settings → T3 Connect** on mobile, and choose **Deregister**. This
revokes its cloud access and frees its host space even when the environment is
offline or has been wiped.
Finish active work before updating because the server restarts briefly. For step-by-step guidance,
see [Keeping T3 Code in Sync](./updating.md).
On a command-line host, `t3 connect unlink` disables exposure while retaining
your login; `t3 connect logout` also clears that login. Background-service
[removal](./background-service.md#manage-the-service) is separate.
On a Linux host, you can keep the server running after logout and manage it independently of the
connection method. See [Running T3 Code in the Background](./background-service.md).
Treat pairing URLs and authorization codes as passwords. Do not include them in
screenshots, logs, or bug reports.
## How Pairing Works
## T3 Connect troubleshooting
The remote device does not need a long-lived secret up front.
Run `t3 connect status` on the host to inspect saved authorization and link
configuration. It is not a live reachability check. If the environment appears
offline, run `t3 service status` and read the displayed log. If it disappears
when SSH closes, see [background-service troubleshooting](./background-service.md#troubleshooting).
Instead:
| Error | Recovery |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `environment_link_limit_exceeded` or managed tunnel limit | Deregister an unused environment, then restart T3 Code on the host. |
| `auth_invalid` or `invalid_bearer` | Run `t3 connect login`. If credentials were revoked, run `t3 connect logout`, then `t3 connect` again. Restart the server after signing in. |
| Expired or invalid link proof | Check the host's date and time, update T3 Code, then restart it. |
| HTTP 403 without a recognized error | Check relay access, proxies, and firewall rules. Keep any Cloudflare Ray ID for a bug report. |
| HTTP 408, 429, or 5xx | Check network and relay availability. Startup retries temporary failures for up to ten minutes. |
1. `t3 serve` issues a one-time owner pairing token.
2. The remote device exchanges that token with the server.
3. The server creates an authenticated session for that device.
After fixing a permanent rejection, restart the host's server. On Linux, use
`systemctl --user restart t3code.service` for the background service. For a
foreground server, stop it and run `t3 serve` again with your usual options.
Include the diagnostic message and trace ID when reporting a persistent failure.
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
## Hosted Web App Pairing
The hosted web app at `https://app.t3.codes` can save a remote backend in browser local storage from a URL like:
```text
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
```
Use hosted pairing when the backend is reachable from the browser over HTTPS/WSS. This includes a backend behind a trusted HTTPS tunnel or another HTTPS endpoint you operate.
Do not use hosted pairing for plain HTTP LAN URLs such as `http://192.168.x.y:3773`. Browsers block an HTTPS page from connecting to an insecure HTTP or WS backend. For those endpoints, use the direct pairing URL shown by the desktop app or CLI from a client that can open that HTTP URL directly.
Hosted pairing does not proxy traffic through T3 Code. The browser still connects directly to the backend URL in the pairing link.
## Managing Access Later
Use `t3 auth` to manage access after the initial pairing flow.
Typical uses:
- issue additional pairing credentials
- inspect active sessions
- revoke old pairing links or sessions
Use `t3 auth --help` and the nested subcommand help pages for the full reference.
### Deregister a T3 Connect Environment
Open your account menu and choose **T3 Connect** to see every environment registered to your
account. On mobile, open **Settings** → **T3 Connect**. Choose **Deregister** to revoke an
environment's T3 Connect access, remove any managed tunnel, and free its host space.
Deregistration is an account action and does not need a connection to the environment, so it also
works for a server that was wiped or is no longer reachable. Device-local connect and disconnect
controls remain in **Settings** → **Connections** on web and desktop or **Settings** →
**Environments** on mobile.
## Security Notes
- Treat pairing URLs and pairing tokens like passwords.
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
- Hosted pairing links keep the credential in the URL hash so it is not sent to the hosted app server, but it can still be exposed through browser history, screenshots, logs, or copy/paste.
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
For a connection that still fails after linking, check the date and time on both
devices. For server version warnings, follow [Updating T3 Code](./updating.md).
+61 -126
View File
@@ -1,158 +1,93 @@
# Source Control Integrations
# Source control
T3 Code connects to your Git hosting provider so you can create pull requests, review code, and manage repositories without leaving the app.
T3 Code integrates with GitHub, GitLab, Bitbucket, and Azure DevOps to clone and publish
repositories, create pull requests, and review changes.
## Supported Providers
## Connect an account
T3 Code works with the platforms your team already uses:
Install Git and configure authentication on the machine running your T3 Code server. For a remote
environment, do this on the remote machine. After signing in, open **Settings → Source Control**
and choose **Rescan**.
- **GitHub** – Pull requests, repository creation, and clone integration
- **GitLab** – Merge requests, repository publishing, and hosted clones
- **Bitbucket** – Pull request workflows (via API token authentication)
- **Azure DevOps** – Pull request support for Microsoft-hosted repositories
### GitHub
## What You Can Do
Install [GitHub CLI](https://cli.github.com/) 2.81.0 or newer, then sign in:
### Start Projects from Anywhere
```bash
gh auth login
```
**Clone repositories directly**
### GitLab
- Open the Command Palette (`Cmd/Ctrl + K`) → **Add Project**
- Choose **GitHub repository**, **GitLab repository**, **Bitbucket repository**, **Azure DevOps repository**, or paste any **Git URL**
- Enter the repository path (`owner/repo`, `group/project`, `workspace/repository`, or `project/repository`) or a full Git URL, pick a destination, and start coding
Install [GitLab CLI](https://gitlab.com/gitlab-org/cli), then sign in:
**Publish local projects to the cloud**
```bash
glab auth login
```
- Have a local Git repository without a remote?
- Use the **Publish Repository** action to create a new hosted repository (GitHub, GitLab, Bitbucket, or Azure DevOps), add it as your origin remote, and push, in one flow
- If the local repository has no commits yet, publishing creates the remote and wires it up but does not push. Make a commit, then push normally.
### Bitbucket
### Manage Code Reviews Without Context Switching
**Create pull requests while you work**
- Push a branch and create a pull request from the Git actions controls in the toolbar
- T3 Code can suggest titles and descriptions based on your commits
- With **Repository conventions** selected, generated source control text follows the project's
`AGENTS.md` along with recent commit subjects. Claude writers also follow `CLAUDE.md`
- Supports GitHub Pull Requests, GitLab Merge Requests, Bitbucket Pull Requests, and Azure DevOps Pull Requests
**Stay on top of open reviews**
- See if your current branch already has an open PR/MR
- Open several reviews from the **Pull requests** page as tabs in the right panel
- Filter the list by author or labels, rank authors by merges in the loaded results, see label and
change-size context on each row, and sort the results currently shown by update time, creation
time, or change size
- While working in a thread, open linked reviews in the same compact right-panel tabs without
leaving the conversation
- Open the review directly in your browser with one click
- If T3 Code cannot load a GitHub pull request, including when GitHub rate limits requests, use
**Open on GitHub** in the error view
- Command-click (Control-click on Windows and Linux) a pull request number in the sidebar to open it in your browser instead of in T3 Code
- Check out a teammate's branch to review code locally
**Fix what you wrote, in place**
- Rewrite a pull request's title and description from the review itself, in Markdown, with a
preview before you save
- Rewrite your own comments the same way, wherever they are shown
- Works on GitHub, GitLab, and Bitbucket. Azure DevOps takes a new title and description; its
comments stay read-only here, as they already were
### Know Your Setup at a Glance
The **Source Control settings** page shows you exactly what's connected:
- ✅ Which providers are authenticated and ready
- ⚠️ What's missing and how to fix it
- 👤 Which account is signed in (when available)
Run a quick **Rescan** after setting up a new machine or changing credentials.
## Getting Started
### For GitHub (Recommended for most users)
1. Install the GitHub CLI (version 2.81.0 or newer) on the machine running T3 Code:
```bash
brew install gh
```
2. Sign in:
```bash
gh auth login
```
3. Open **Settings → Source Control** in T3 Code and verify GitHub shows as authenticated
You can now clone, publish, and create pull requests.
### For GitLab
1. Install the GitLab CLI:
```bash
brew install glab
```
2. Authenticate:
```bash
glab auth login
```
3. Check **Settings → Source Control** to confirm the connection
### For Bitbucket
Bitbucket uses tokens instead of a CLI tool. Two options, both set as environment variables on the
machine running T3 Code.
Recommended, a Bitbucket access token:
Set an access token in the server's environment:
```bash
export T3CODE_BITBUCKET_ACCESS_TOKEN="your-access-token"
```
Or an Atlassian account email plus API token, with read/write access to pull requests and
repositories, plus read access to your user account (`read:user:bitbucket`, used to verify the
connection):
Or use an Atlassian account email and API token with read/write access to repositories and pull
requests, plus user read access (`read:user:bitbucket`):
```bash
export T3CODE_BITBUCKET_EMAIL="you@example.com"
export T3CODE_BITBUCKET_API_TOKEN="your-token"
```
If both are set, the access token wins. Restart T3 Code and verify the connection in **Source
Control settings**.
The access token takes precedence if both are configured. Restart the server after changing these
variables.
### For Azure DevOps
### Azure DevOps
1. Install Azure CLI:
```bash
brew install azure-cli
```
2. Add the DevOps extension:
```bash
az extension add --name azure-devops
```
3. Sign in:
```bash
az login
```
Install [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/), add the DevOps extension, and sign in:
---
```bash
az extension add --name azure-devops
az login
```
## Requirements & Troubleshooting
## Clone or publish a project
**Git is required** – T3 Code uses Git for all local operations. Ensure `git` is installed on your server.
Use **Add Project** in the command palette (`Cmd/Ctrl+K`) to clone a repository. Choose a hosting
provider or paste a Git URL, then choose where to save it.
**Server-side setup** – Authentication happens on the machine running T3 Code (the server), not your local browser. If you're using a hosted or team instance, your administrator may have already configured providers.
For a local Git repository without a remote, **Publish Repository** creates a hosted repository,
adds it as `origin`, and pushes your commits. If there are no commits yet, it creates the remote;
make your first commit before pushing.
**Common issues:**
## Create a pull request
- **Provider shows "Not authenticated"** – Run the login command for that provider (e.g., `gh auth login`) in a terminal on the server, then rescan in Settings
- **GitHub says it could not verify sign-in status** – T3 Code needs GitHub CLI 2.81.0 or newer to check sign-in status. Update `gh` (e.g., `brew upgrade gh`), then rescan
- **Bitbucket not connecting** – Double-check your environment variables are set in the correct shell profile and the server was restarted
- **Can't push to a remote** – Verify your Git remote URL matches the provider you've authenticated with (SSH vs HTTPS remotes may need different credentials)
Use a thread's Git actions to commit, push, and create a pull request. T3 Code can generate commit
messages, review titles, and descriptions from your changes.
**Need more help?** Check your provider's CLI documentation:
Choose the writing style and model in **Settings → Source Control**. **Repository conventions**
uses the project's instructions and recent commit subjects.
- [GitHub CLI](https://cli.github.com/)
- [GitLab CLI](https://gitlab.com/gitlab-org/cli)
- [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/)
## Review and merge
Open **Pull requests** to review changes and comments, request reviewers, check out a branch,
or merge. You can edit review titles and descriptions and your own comments where the host allows it.
GitLab calls these merge requests.
GitHub, GitLab, and Azure DevOps support auto-merge while checks are outstanding. GitHub also
supports approving waiting fork workflows and opening a revert pull request for a merged change.
For Azure DevOps, use the host website to view diffs or change comments. Bitbucket does not support
reopening a declined pull request.
## Troubleshooting
- **Not authenticated:** run the provider's login command on the server, then rescan. For Bitbucket,
confirm the running server received the environment variables.
- **GitHub sign-in cannot be verified:** update GitHub CLI to at least 2.81.0.
- **Push fails despite a connected account:** check the Git remote's credentials. SSH and HTTPS
remotes can require separate setup from the hosting provider's API access.
- **A review cannot load:** open it on the host website while resolving connectivity, permissions,
or rate limits.
+11
View File
@@ -0,0 +1,11 @@
# Product usage data
The T3 Code server sends product usage events to PostHog, associated with a hashed account or
installation identifier. Events include the provider, model, reasoning effort, permission mode,
turn result, duration, and main-agent token totals when available.
Events do not include prompts, responses, file contents, authentication tokens, conversation IDs,
raw provider events, or child-agent output. Child-agent token use is excluded from the totals.
To disable collection, set `T3CODE_TELEMETRY_ENABLED=false` in the server's environment before
starting it. This stops product events from being recorded or sent.
+8
View File
@@ -0,0 +1,8 @@
# Terminal history
Each terminal keeps up to 5,000 lines and 8 MiB of scrollback on its environment
server. T3 Code removes the oldest output when either limit is reached. A long
line can be shortened at the start. New terminal output is not truncated.
These limits apply when you reconnect and when T3 Code restores saved terminal
history. A client can show less scrollback than the server keeps.
+100 -41
View File
@@ -1,54 +1,113 @@
# Organizing threads
# Working with threads
Pin a thread from its context menu to keep it in the pinned section above your active work.
`mod+shift+p` pins or unpins the thread you have open. Pinned threads are shown independently of
their project, including when you connect to more than one environment.
Use a new thread for a separate task. Choose **New worktree** when its code changes
need a separate branch and working directory.
To require confirmation before unpinning, enable **Settings → General → Unpin confirmation**. The
confirmation applies to the sidebar controls, thread menus, and the `mod+shift+p` shortcut.
## Start a thread
Pinned threads still move to **Settled** when they become inactive. They also move when their pull
request merges if **Auto-settle merged threads** is enabled.
On web and desktop, a new thread keeps the current project and carries your model
and mode selections, unless the destination project has its own model default.
Its branch and workspace mode come from your configured defaults. To continue in
an existing worktree, use **New thread in this worktree** from the branch toolbar.
Each server stores its own copy of the automatic settlement settings and checks them even when no
web, desktop, or mobile client is connected. By default, it settles threads after three days without
activity and when their pull request merges. An eligible idle thread also settles when its pull
request closes. An open pull request blocks inactivity settlement. Active work, pending input, and
live background work keep the thread active. T3 Code settles from a closed or merged pull request
only when its timestamp is not older than the user's latest activity. If that timestamp is not
available, the inactivity rule still applies. A manual un-settle also keeps the thread active.
When you change a new thread's project, T3 Code stays in the current environment
if that project exists there. Otherwise it selects an environment that has it.
Change these rules in **Settings > General**. The change is written to every environment you are
connected to at that moment. An environment that is offline keeps its old value. When a connected
environment holds a different value, **Settings > General** shows a warning that names it. Choose
**Apply to all** to write your current values to every connected environment. The same applies to
the new-thread workspace mode and the source control writing style.
### Start in the background
A settings change affects future settlement and does not reopen a settled thread. Settings saved
by older clients on one device no longer control this behavior.
In a desktop browser or the desktop app, press `Cmd+Enter` on macOS or `Ctrl+Enter`
on Windows and Linux to start a new thread and immediately open another draft. The
next draft keeps the workspace mode and base branch you selected. With **New
worktree**, each background submission creates its own worktree.
When you un-settle a thread, it returns to the top of the active list so you can find it right
away. Its timestamps do not change. Other threads keep their positions.
## Pin and reorder threads
Right-click a pull request link in a thread and choose **Link to thread** to show that pull request
in the sidebar. The thread settles when the linked pull request merges if **Auto-settle merged
threads** is enabled. Right-click the same link and choose **Unlink from thread** to remove it.
Pin a thread from its menu to keep it above your active work.
On web and desktop, drag a pinned thread to change its position. On mobile, open the thread's menu
and choose **Move up** or **Move down**. The order is stored by the server and appears on your
other connected devices.
Pinning does not prevent automatic settlement. Settling a thread removes its pin.
If reordering is unavailable for one environment, update the T3 Code server running in that
environment. Older servers can still pin and unpin threads, but do not understand synced ordering;
their pinned threads keep the default newest-first order below the ones you have arranged.
On web and desktop, drag a thread between sections to change its state. Drag a thread up into
the pinned section to pin it at the spot you drop it; drag a pinned thread down into the active
list to unpin it. Dragging a thread onto the **Settled** header settles it, and dragging a settled
thread into the active list un-settles it. A snoozed thread can be dragged out of the snoozed
shelf, which wakes it, but threads cannot be dragged into the shelf because snoozing needs a wake
time. Dragging a pinned thread out of the pinned section does not ask for unpin confirmation.
Pinned and active boundary labels appear only while dragging, without moving the rows. The
other rows slide aside to show where the thread will land. When you cross into another section,
the dragged thread shows the action the drop performs, with its icon: **Pin**, **Unpin**,
**Settle**, **Un-settle**, or **Wake**. Its status and hover actions hide during the drag. A pinned
thread keeps its pin only while it stays in the pinned section; once it leaves, the badge takes
over. Reordering within the same section shows no badge. When there are no pins, drag to the top
edge to pin a thread. Section labels stay readable for the whole drag, and the section the
thread is over takes the accent color. Section labels also
identify empty sections and a collapsed settled shelf.
## Environment artwork
Drag within the pinned or active section to change its order. Other rows slide aside to show the
spot where the thread will land. Drops into either section keep the position you choose. On
mobile, open a pinned or active thread's menu and choose **Move up** or **Move down**. The server
saves the order, so it survives a refresh and appears on your other connected devices.
Dev and Nightly environments can identify themselves with artwork at the top of the sidebar and in
the send button. Choose **Artwork**, **Version pill**, or **None** in Settings under environment
identification. Artwork is recolored to match each built-in theme. Custom themes use the **Version
pill** fallback because their colors are not controlled by T3 Code.
On web and desktop, the list also animates section changes made with thread actions such as
**Pin**, **Settle**, and **Snooze**. These transitions respect your system's reduced-motion
preference. While dragging, rows follow the insertion gap without replaying a second transition
after the drop.
To generate a fresh title from the conversation, open a thread's context menu and choose
**Regenerate title**. While T3 Code is generating it, the action reads **Regenerating…** and cannot
be selected again. The option is hidden when the connected environment needs a server update.
New threads appear above the active threads you have arranged. Settling clears a thread's active
position, so using **Un-settle** returns it to the top. Pinning and snoozing preserve its active
position until you move it again. Thread activity does not change the order. The settled shelf
continues to use settlement time.
If dragging is unavailable for one environment, update the T3 Code server running in that
environment. Pinned and active reordering require server support. Threads from older servers keep
their default order until the server is updated.
## Settle finished work
Choose **Settle thread** from its menu to move finished work out of the active list
without deleting the conversation. **Un-settle thread** restores it to active work
and prevents automatic settlement until new activity resumes the usual rules.
Manually settling an idle thread dismisses unanswered async questions without
sending an answer or restarting the agent.
By default, environments settle inactive threads after three days and settle
threads whose pull request merged. A closed pull request can also settle an idle
thread. Work in progress, pending questions or approvals, and live background work
prevent automatic settlement. An open pull request does not prevent inactivity
settlement, but an old closed or merged pull request does not settle work you
resumed after it closed.
Change these rules in **Settings → General**. They continue to run when your apps
are closed. Changes apply to connected environments that support shared settings;
offline environments and older servers keep their previous values. If connected
environments disagree, **Apply to all** copies your current settings to those named
in the warning. Changing a rule does not reopen already settled threads.
## Link a pull request
The server finds the PR for each unsettled thread's saved branch, even when your
apps are closed. Settled threads keep their saved links. Update the server if
automatic branch links do not appear.
On web and desktop, right-click a pull request link in a thread and choose
**Link to thread** to select a different PR. Use **Unlink from thread** on the
same link to return to the branch PR, if one exists.
The linked pull request participates in automatic settlement.
## Find and reference work
On web and desktop, open the command palette with `Cmd/Ctrl+K` to search threads
across connected environments. Message search starts after two characters and
includes your messages and final agent responses.
Use **Settings → Keybindings** to find or customize shortcuts for searching files
and copying a thread reference. A copied reference uses the thread's pull request
link when available, otherwise its thread ID. See [keybindings](./keybindings.md)
for custom configuration.
## Inspect agent work
On web and desktop, use **Agents** to follow work delegated to subagents.
Expand a tool call in the conversation to see its full command and output.
Summaries shorten shell wrappers and can still describe the latest call after it
finishes; the call's own result shows its status.
+45 -71
View File
@@ -1,91 +1,65 @@
# Keeping T3 Code in Sync
# Updating T3 Code
The T3 Code web or desktop app and the server it connects to work best when they use the same
version. If they do not match, T3 Code shows a warning with the right update option for that server.
The app you use and the server running your agents can be on different machines.
When a server is behind your web or desktop app, an update notice appears in the
conversation and **Settings → Connections**. Update the machine named in that
notice.
## Where to Find the Update
## Before you update
You may see the warning in either of these places:
Server updates restart the connection and can interrupt active agents and
terminal commands. Saved threads, settings, and project files remain.
- above the message box in the current conversation
- **Settings** → **Connections**, beside the affected connection
**Settings → General → Continue threads after restarts** is off by default.
Enable it to resume supported active threads after an update, crash, or machine
restart. Changes are saved to connected environments that support this setting;
update older servers first. If a supported environment was offline or has a
different value, use **Apply to all** in Settings after it connects.
T3 Code must start again on that machine;
the setting does not enable automatic startup. Terminal commands may still be
interrupted, and threads without saved provider resume state need a new message.
If you previously enabled continuation for updates, enable this setting once
to allow recovery without a connected client.
Dismissing the conversation warning only hides that reminder for those two versions. It does not
update the server, and the version difference remains visible in Connections.
## Update a connected server
## Before You Update
The offered action depends on how the server runs:
Let active agent work and terminal commands finish first. Updating restarts the server, so the
connection will disappear briefly and work that is still running may be interrupted.
| Action | What to do |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Update server** | Keep the client open while it installs and reconnects. Supported background services update remotely. For a desktop-hosted server, this also closes and relaunches the desktop app on the host. |
| **Update the desktop app** | Update the desktop app on the machine running the server, then reopen it if needed. |
| **Copy update command** | Stop the command-line server on its host and relaunch with the copied command, keeping your usual startup options. |
The update does not remove saved threads, settings, or project files.
## Choose the Action You See
| Action | What to do |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Update server** | Available for the T3 Code Linux background service and for servers run by a current T3 Code desktop app. Select the button and leave T3 Code open while it downloads, installs, restarts, and reconnects. For desktop-app servers this closes and relaunches the desktop app on that machine. If installation fails, the desktop app stays open and reconnects to its server. |
| **Update the desktop app** | Shown for desktop apps that predate remote updates. 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.
An older background-service launcher may ask you to run the exact
`npx t3@<version> service update` command on the server machine. That one local update installs the
rollback support needed for later remote updates, including versions that change the database.
After selecting **Update**, the notice becomes a live status line: **Downloading…** while the new
version is fetched and verified, then **Restarting…** while the server restarts into it. The same
status appears in the conversation and in Connections, so navigating between them does not lose the
update. A failure remains visible with its error and an option to retry.
**Copy update command** gives you `npx t3@<client-version>`, which relaunches the server directly
at the matching version. Add whatever startup options you normally use.
If the server instead runs as the T3 Code background service, update the service on the host and
pin the same version:
For a background service, run the matching version's CLI on the host:
```sh
npx t3@<client-version> service update
```
`service update` installs the version of the CLI that invoked it, so `npx t3@latest service update`
only resolves the skew when your client happens to be on the latest release. The exact version from
the warning always works.
Replace `<client-version>` with the version shown in the notice. Using
`@latest` only resolves the mismatch if your client is on that release. An older
service launcher may require this local update before it supports remote updates
and rollback.
See [Running T3 Code in the Background](./background-service.md) for install, status, and removal
commands.
For a foreground server, the copied command is `npx t3@<client-version>`. Add
`serve` if you normally run without a browser, and preserve options such as
`--host` or `--tailscale-serve`. See
[background services](./background-service.md) for service management.
## Nightly desktop release notes
## If an update fails
The desktop app shows a compact release-notes preview when a nightly update is available. Changes
appear newest first within each release. Each release links to its exact page on GitHub, even when
all changes fit in the preview.
The preview shows up to eight changes from each of six releases. When it leaves out changes or older
releases, it shows the exact number and links to the rest. Contributor credits do not count as
changes.
## After the Update
Keep the web or desktop app open while the server restarts. The update completes only after the
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:
Keep the client open until it reconnects or reports a failure. A failed service
update can roll back to the previous version. If the update still fails:
1. Retry the offered action once.
2. Make sure you updated the machine named in the warning, not only the device you are using.
3. For a command-line server, relaunch it with `npx t3@<client-version>`, replacing
`<client-version>` with the client version shown in the warning.
2. Check that you updated the server's machine, not only the device you are using.
3. For a command-line server, stop it and relaunch the exact version shown in the notice.
## The Mobile App
## Mobile updates
The mobile app keeps itself current on its own. When it finds a new version, it downloads it in the
background and installs it automatically the next time you leave the app. Unsent drafts and queued
messages are saved before the restart. Only if the app stays open long enough that the update never
gets that chance does it ask whether to install right away; choosing **Later** is safe and keeps the
automatic install armed.
For remote connection setup and access troubleshooting, see [Remote Access](./remote-access.md).
Install App Store or Google Play releases as usual. The mobile app can also
download updates in the background and apply them when you next leave the app.
It saves drafts and queued messages before restarting. If you keep the app open
for a long time, it may ask to install immediately; choosing **Later** leaves the
update queued for the next suitable moment.
+72 -10
View File
@@ -1,13 +1,75 @@
# Review usage
# Usage and limits
The Usage page combines Codex, Claude Code, and Grok Build activity from your connected
environments. It reads the providers' local session history and shows API-equivalent token cost,
processed tokens, cache savings, provider shares, and model breakdowns. Subscription billing is
separate from the raw token cost shown here.
## Understand your usage
Grok Build totals come from persisted session updates. Interactive turns that never wrote a
completed-turn record will not appear.
**Usage** combines Codex, Claude Code, and Grok Build session history from your connected
environments. It shows token use, cache savings, model breakdowns, and estimated API-equivalent
cost. These estimates are not your subscription bill.
Use **Past 24h** for an hourly chart covering the exact rolling 24-hour period. The **7 days**,
**30 days**, and **90 days** ranges use daily resolution. Cost and token toggles update both the
headline and chart, and refreshing rescans every connected environment.
Totals depend on the history available on each server. Grok turns without a saved completed-turn
record are missing from the totals.
On web and desktop, use the environment dropdown to filter costs, tokens, and limits. All
environments are selected by default. The dropdown shows which environments are still scanning;
results appear as each one responds.
If recent work is missing or a new model shows no cost, refresh to rescan session history and
update model pricing.
## Set custom model prices
On web or desktop, open the environment dropdown on **Usage**, then choose **Model prices** to add,
edit, or reset a model's estimated price. **Apply to** starts with your current Usage filter;
choose all environments or select individual destinations. Enter the exact model ID and USD
rates per million input and output tokens. You can enter any model ID, including models
without public pricing.
Cache read and cache write rates are optional and use the input rate when blank. Enter `0` for
tokens that are free. Saved prices replace automatic pricing for all of that environment's
history and are shared with clients connected to it. When environments have different prices,
cells show **Mixed**. Edit rates directly in the table, then choose **Save changes** to apply all
edited rows. Untouched cells keep each environment's rate. Select one environment to inspect its
prices. **Reset to automatic** marks a model's override for removal when you save; you can undo
it before saving.
Each destination reports whether the change saved. Offline or unavailable environments are
marked **Not saved**. Reconnect them and choose **Retry failed saves** to finish the same change
without writing again to environments that already saved. Changes are not queued after you close
the dialog.
## Track subscription limits
**Usage → Limits** pools every subscription account it can see per provider, so with several Codex
or Claude accounts across your environments and hubs you read one number per window rather than a
list. Each window card shows how much of the pool is left and a bar with one segment per account,
ordered by which resets soonest; when the provider reports reset times, the card also says when
the next reset lands and how much it hands back. The hatched
part of a segment is what that reset restores. Tap a segment or account row for the account's plan,
where it is signed in, and its reset time. On web, you can hover too. Codex accounts with banked
reset credits show a ticket count and the **Use reset** action in the account details. On narrow screens, numbered rows below
the bar show each account's quota, countdown, and credits. Tap a row to open its details.
The same account signed in on more than one environment, or reported by a hub as well, counts once.
Filter with the environment dropdown to see what a single machine has.
If a window looks stale, refresh Limits to re-check every provider and hub.
Pick `/usage-limits` from the composer's command menu, or send it as a message, to check the
current model's limits without leaving the conversation. The result opens above the composer and
closes when you dismiss it or send your next message. It uses the same snapshot as **Usage → Limits**, so it does not run the agent or refresh
anything. The command is offered only for providers that appear under **Usage → Limits**.
API-key accounts may not report subscription limits. This also applies to Claude connections
using a proxy through `ANTHROPIC_AUTH_TOKEN`.
## Connect a CLIProxyAPI hub
To see pooled accounts, open **Settings → Providers → Usage providers → Add hub**. Choose the
environment that will connect to the hub and enter its URL and management key.
The accounts appear under **Usage → Limits**. Codex accounts show banked reset credits; select an
account and choose **Use reset** to redeem one. No hub plugin is required.
This connection supplies usage information; configure
the provider separately to send agent requests through the hub. Remove the hub from the same
settings section when you no longer need it.
+81
View File
@@ -0,0 +1,81 @@
# Welcome wizard
T3 Code shows a setup flow when you open a new installation or connect to the
hosted app for the first time. Existing workspaces skip this flow.
## Connect your computers
Select one or more computers to set up. If you opened T3 Code directly from a
server or the desktop app, that computer is already connected and selected.
It is identified by its name, which may differ from the device running your
browser.
You can add more computers before continuing:
- **T3 Connect** connects computers that are signed in to your account. Run
`npx t3 connect` on each computer you want to add, then start T3 Code or run
`npx t3 serve` so the computer stays available.
- **Add a computer** connects directly to a server on your network or tailnet.
Start the server with `npx t3 serve`, then run `npx t3 pair --tailscale` and
paste the pairing link. You can also run `npx t3 serve --host <address>` and
use `npx t3 pair` when the server is already reachable on your network.
Saved computers and computers discovered through T3 Connect are selected by
default. Uncheck any you do not want to set up; this does not disconnect them.
Continue when your selected computers are connected. Setup checks
agents across the selected computers, then offers project import grouped by computer.
If T3 Code cannot confirm the workspace during startup, the setup flow shows
**Still connecting** instead of opening the app. Select **Reload** to try again.
If T3 Code cannot read your saved settings, it shows **Could not read settings**.
Select **Retry** after storage becomes available. Setup does not replace
unreadable settings with defaults.
## Check your agents
T3 Code checks each selected computer for Claude Code and Codex. If an agent is
not installed or signed in, select its action to open a terminal with the
correct command ready to run. Install uses the vendor's standalone installer,
which does not need Node or npm and keeps **Update now** working in Settings.
Other providers can be enabled in Settings.
The setup terminal uses the home directory and environment configured for the
selected provider instance. Sensitive values remain redacted in Settings and
terminal metadata while the terminal process can use them.
## Import your projects
T3 Code finds directories that Claude Code or Codex has used. Git repositories
are listed first, newest activity on top. When the remote is on GitHub, the
group shows the repository as `owner/name`. Clones with the same remote share
one group. Directories that are not git repositories sit under "Other folders".
The default selection includes git repositories active within the last 30 days
with at least three conversations. Use the checkboxes, or "Select all" and
"Select none", to change the selection. Linked git worktrees, Codex scratch
directories under `Documents/Codex`, and anything under `Downloads` are not
offered.
A large or malformed history can reach the scan limit. T3 Code keeps the
projects it found and warns when projects or conversations may be missing.
Imported projects include Codex and Claude conversations active within the last
30 days. You can continue those conversations in T3 Code.
Conversation import is best effort. T3 Code keeps the first user prompt and the
newest remaining visible user and assistant messages, with 200 messages total.
It omits tool activity and attachments. For Codex, it omits generated setup
context only when a canonical user event and a valid shared turn ID identify the
same user turn. Ambiguous legacy or response-only context stays in the imported
conversation so T3 Code does not remove user text. It reads one conversation at
a time and skips files larger than 16 MiB. It ignores malformed records and skips
unreadable or unparseable conversations.
Each import attempt reads up to 100 conversation files and 64 MiB per project,
with up to 100,000 input records. Run import again to continue a large batch.
Completed conversations are not imported again. You can continue without the
remaining history.
You can continue without configuring agents or importing projects, or return to an earlier step
using the setup progress bar. Navigation pauses while an import is running.