diff --git a/AGENTS.md b/AGENTS.md index b7786ba84b5..5c99a4628a0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,7 +72,7 @@ The most common defect in this repo is a change that works on the path you teste - **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow. - **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug. - **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real. -- **Docs.** `docs/` mirrors this structure. Behavior changes that a user would notice belong in `docs/user/`; architecture changes in `docs/architecture/`; new vocabulary in `docs/reference/encyclopedia.md`. +- **Docs.** `docs/` splits by audience. Behavior changes that a user would notice belong in `docs/user/` (shipped-product voice, no repo tooling or source paths); architecture and contributor changes in `docs/internals/`; runbooks in `docs/operations/`; new vocabulary in `docs/internals/glossary.md`. ## Dev servers @@ -114,13 +114,13 @@ An empty database is a bad test. Seed your worktree's `.t3` instead of pointing Clients send typed WebSocket requests. The server turns them into _commands_, a pure _decider_ turns commands into persisted _events_, and a _projector_ derives the read model the UI renders. Provider CLIs run as subprocesses; per-provider _adapters_ translate their native protocols into orchestration events. Side effects run in queue-backed _reactors_ that emit _receipts_ when milestones land. Each turn ends with a _checkpoint_, a hidden git ref, so the app can diff and restore. -Full glossary with file links: `docs/reference/encyclopedia.md` +Full glossary with file links: `docs/internals/glossary.md` ## Where code lives -- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` and `docs/operations/effect-fn-checklist.md` before writing Effect code. +- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` before writing Effect code. - `apps/web` - React/Vite UI. `apps/desktop` wraps it, `apps/mobile` is React Native, `apps/marketing` is the site. -- `packages/contracts` - Effect/Schema contracts. Schema only, no runtime logic. +- `packages/contracts` - Effect/Schema contracts plus small derived helpers. No heavy runtime logic. - `packages/shared` - shared runtime utils, subpath exports, no barrel. - `packages/client-runtime` - client code shared by web and mobile. - `.repos/` - vendored read-only references. Prefer their patterns over invented ones. Never edit or import from them. Sync with `vpr sync:repos` when bumping the matching dependency. diff --git a/README.md b/README.md index 9b63f4ac75d..08b07b995f7 100644 --- a/README.md +++ b/README.md @@ -17,13 +17,13 @@ We wanted something performant, remote-ready, and truly open. If we ever go the > > - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login` > - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login` -> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login` +> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `agent login` > - Grok Build: install [Grok Build CLI](https://x.ai/cli) and run `grok login` > - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login` ### Try it out (install-free) -The easiest way to test T3 Code is to run the server in your terminal: +The easiest way to test T3 Code is to run the server in your terminal (requires Node.js 22.16+, 23.11+, or 24.10+): ```bash npx t3@latest @@ -61,17 +61,20 @@ We are very very early in this project. Expect bugs. We are (mostly) not accepting contributions yet. Small fixes may be considered. Big features will not be. -There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs). - ## Documentation -- [Getting started](./docs/getting-started/quick-start.md) -- [Remote access](./docs/user/remote-access.md) -- [Keeping T3 Code in sync](./docs/user/server-updates.md) -- [Architecture overview](./docs/architecture/overview.md) -- [Provider guides](./docs/providers/codex.md) -- [Operations](./docs/operations/ci.md) -- [Reference](./docs/reference/encyclopedia.md) +Full docs live in [docs/](./docs). There's no docs site yet. + +- [Install and first run](./docs/user/install.md) +- [Permission modes](./docs/user/permission-modes.md) +- [Keyboard shortcuts](./docs/user/keybindings.md) +- [Remote access from a phone or another machine](./docs/user/remote-access.md) +- [Keeping app and server in sync](./docs/user/updating.md) +- [Source control integrations](./docs/user/source-control.md) +- Multiple accounts: [Codex](./docs/user/providers-codex.md) · [Claude](./docs/user/providers-claude.md) +- Linux: [run T3 Code as a background service](./docs/user/background-service.md) + +Building from source? Start at [docs/internals/overview.md](./docs/internals/overview.md). ## If you REALLY want to contribute still.... read this first diff --git a/docs/README.md b/docs/README.md index fe473094bbc..e8494059713 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,19 +1,40 @@ -# Documentation - -- [Getting started](./getting-started/quick-start.md) -- Architecture - - [Overview](./architecture/overview.md) - - [Connection runtime](./architecture/connection-runtime.md) - - [Remote environments](./architecture/remote.md) - - [Server updates](./architecture/server-updates.md) -- User guides - - [Background service](./user/background-service.md) - - [Remote access](./user/remote-access.md) - - [Keeping T3 Code in sync](./user/server-updates.md) - - [Keybindings](./user/keybindings.md) -- [T3 Connect](./cloud/t3-connect-clerk.md) -- [Integrations](./integrations/source-control-providers.md) -- [Mobile](./mobile/app.md) -- [Operations](./operations/ci.md) -- [Providers](./providers/codex.md) -- [Reference](./reference/encyclopedia.md) +# T3 Code docs + +## Using T3 Code + +- [Install and first run](./user/install.md) +- [Permission modes](./user/permission-modes.md) +- [Keyboard shortcuts](./user/keybindings.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) + +Mobile app: [apps/mobile/README.md](../apps/mobile/README.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). + +- [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) +- [Providers](./internals/providers.md) +- [Remote environments](./internals/remote.md) +- [Server updates](./internals/server-updates.md) +- [Environment auth](./internals/environment-auth.md) +- [T3 Connect](./internals/t3-connect.md) +- [CI gates](./internals/ci.md) + +### Runbooks + +- [Release](./operations/release.md) +- [Observability](./operations/observability.md) +- [Relay observability](./operations/relay-observability.md) +- [Mobile app store screenshots](./operations/mobile-app-store-screenshots.md) diff --git a/docs/architecture/connection-runtime.md b/docs/architecture/connection-runtime.md deleted file mode 100644 index 06f7e6338ca..00000000000 --- a/docs/architecture/connection-runtime.md +++ /dev/null @@ -1,137 +0,0 @@ -# Connection Runtime - -The connection runtime is shared by web and mobile. It owns connectivity, -authentication, retries, transport lifetime, cached environment data, and -environment-scoped operations. - -Web and mobile mount this runtime once at the application root. There is no -legacy connection owner or supported mixed mode. - -## Ownership - -Each registered environment has one scoped Effect `Context` containing focused -services: - -- `EnvironmentSupervisor` owns desired state, retry scheduling, and the active - session scope. -- `ConnectionBroker` prepares credentials and endpoints for primary, bearer, - relay, and SSH targets. -- `RpcSessionFactory` performs one transport attempt. It does not retry. -- `EnvironmentRpc` exposes the active session without leaking the transport. -- `EnvironmentProjectCommands` and `EnvironmentThreadCommands` construct - orchestration commands, IDs, and timestamps. -- `EnvironmentShell` and `EnvironmentThreads` own live subscriptions and cached - snapshots. - -`EnvironmentServicesFactory` assembles that context, and `EnvironmentRegistry` -owns its scope. There is no aggregate environment runtime facade. React -components do not create connections, transports, retry loops, or RPC clients. - -## Connection State - -The supervisor is the only retry owner. - -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 without consuming retry attempts. -3. When online, the supervisor asks the broker for one prepared connection and - asks the session factory for one RPC session. -4. Transient failures retry forever with exponential backoff capped at 16 - seconds. -5. Connectivity changes, application activation, credential changes, and - explicit user retry interrupt the current wait and trigger a fresh attempt. -6. Authentication or configuration failures remain blocked until an external - wakeup changes the relevant input. -7. An involuntary session close keeps the registration and cache, then retries. -8. Explicit removal closes the session and deletes the registration, - credentials, shell cache, and thread cache. - -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. -- Expected subscription failures update domain sync state and wait for a - replacement session; they do not take down a healthy transport. -- Mutations resolve the current environment runtime at execution time. -- Shell and thread snapshots are available while offline. -- A connected transport may have `empty`, `cached`, `synchronizing`, `live`, or - failed shell and thread data independently. -- 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. -- 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. - -## Source Boundaries - -The public package subpaths mirror the runtime layers: - -- `connection/core` contains state, catalog, retry policy, and connectivity. -- `connection/transport` contains brokerage, authorization, attempts, and RPC - sessions. -- `connection/platform` declares capabilities and persistence contracts. -- `connection/services` contains environment-scoped data services. -- `connection/application` assembles registries, discovery, and startup. -- `connection/atoms` adapts shared services to application-owned Atom runtimes. -- `connection/presentation` contains pure UI projections. - -Other reusable state lives in domain subpaths such as `shell`, `threads`, -`terminal`, and `vcs`. Applications must import explicit package subpaths; the -package intentionally has no root export. - -## Application Boundary - -The application root mounts the shared connection application 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 `WsTransport`, 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. diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md deleted file mode 100644 index 7983bef377e..00000000000 --- a/docs/architecture/overview.md +++ /dev/null @@ -1,137 +0,0 @@ -# Architecture - -T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app. - -``` -┌─────────────────────────────────┐ -│ Browser (React + Vite) │ -│ wsTransport (state machine) │ -│ Typed push decode at boundary │ -└──────────┬──────────────────────┘ - │ ws://localhost:3773 -┌──────────▼──────────────────────┐ -│ apps/server (Node.js) │ -│ WebSocket + HTTP static server │ -│ ServerPushBus (ordered pushes) │ -│ ServerReadiness (startup gate) │ -│ OrchestrationEngine │ -│ ProviderService │ -│ CheckpointReactor │ -│ RuntimeReceiptBus │ -└──────────┬──────────────────────┘ - │ JSON-RPC over stdio -┌──────────▼──────────────────────┐ -│ codex app-server │ -└─────────────────────────────────┘ -``` - -## Components - -- **Browser app**: The React app renders session state, owns the client-side WebSocket transport, and treats typed push events as the boundary between server runtime details and UI state. - -- **Server**: `apps/server` is the main coordinator. It serves the web app, accepts WebSocket requests, waits for startup readiness before welcoming clients, and sends all outbound pushes through a single ordered push path. - -- **Provider runtime**: `codex app-server` does the actual provider/session work. The server talks to it over JSON-RPC on stdio and translates those runtime events into the app's orchestration model. - -- **Background workers**: Long-running async flows such as runtime ingestion, command reaction, and checkpoint processing run as queue-backed workers. This keeps work ordered, reduces timing races, and gives tests a deterministic way to wait for the system to go idle. - -- **Runtime signals**: The server emits lightweight typed receipts when important async milestones finish, such as checkpoint capture, diff finalization, or a turn becoming fully quiescent. Tests and orchestration code wait on these signals instead of polling internal state. - -- **Server updates**: A connected environment advertises whether its server can replace itself. When client and server versions differ, the browser selects an automatic, desktop-managed, or manual update path without changing connection ownership. See [Server Update Architecture](./server-updates.md). - -## Event Lifecycle - -### Startup and client connect - -```mermaid -sequenceDiagram - participant Browser - participant Transport as WsTransport - participant Server as wsServer - participant Layers as serverLayers - participant Ready as ServerReadiness - participant Push as ServerPushBus - - Browser->>Transport: Load app and open WebSocket - Transport->>Server: Connect - Server->>Layers: Start runtime services - Server->>Ready: Wait for startup barriers - Ready-->>Server: Ready - Server->>Push: Publish server.welcome - Push-->>Transport: Ordered welcome push - Transport-->>Browser: Hydrate initial state -``` - -1. The browser boots `WsTransport` and registers typed listeners in `wsNativeApi`. -2. The server accepts the connection in `wsServer` and brings up the runtime graph defined in `serverLayers`. -3. `ServerReadiness` waits until the key startup barriers are complete. -4. Once the server is ready, `wsServer` sends `server.welcome` from the contracts in `ws.ts` through `ServerPushBus`. -5. The browser receives that ordered push through `WsTransport`, and `wsNativeApi` uses it to seed local client state. - -### User turn flow - -```mermaid -sequenceDiagram - participant Browser - participant Transport as WsTransport - participant Server as wsServer - participant Provider as ProviderService - participant Codex as codex app-server - participant Ingest as ProviderRuntimeIngestion - participant Engine as OrchestrationEngine - participant Push as ServerPushBus - - Browser->>Transport: Send user action - Transport->>Server: Typed WebSocket request - Server->>Provider: Route request - Provider->>Codex: JSON-RPC over stdio - Codex-->>Ingest: Provider runtime events - Ingest->>Engine: Normalize into orchestration events - Engine-->>Server: Domain events - Server->>Push: Publish orchestration.domainEvent - Push-->>Browser: Typed push -``` - -1. A user action in the browser becomes a typed request through `WsTransport` and the browser API layer in `nativeApi`. -2. `wsServer` decodes that request using the shared WebSocket contracts in `ws.ts` and routes it to the right service. -3. [`ProviderService`][8] starts or resumes a session and talks to `codex app-server` over JSON-RPC on stdio. -4. Provider-native events are pulled back into the server by [`ProviderRuntimeIngestion`][9], which converts them into orchestration events. -5. [`OrchestrationEngine`][10] persists those events, updates the read model, and exposes them as domain events. -6. `wsServer` pushes those updates to the browser through `ServerPushBus` on channels defined in [`orchestration.ts`][11]. - -### Async completion flow - -```mermaid -sequenceDiagram - participant Server as wsServer - participant Worker as Queue-backed workers - participant Cmd as ProviderCommandReactor - participant Checkpoint as CheckpointReactor - participant Receipt as RuntimeReceiptBus - participant Push as ServerPushBus - participant Browser - - Server->>Worker: Enqueue follow-up work - Worker->>Cmd: Process provider commands - Worker->>Checkpoint: Process checkpoint tasks - Checkpoint->>Receipt: Publish completion receipt - Cmd-->>Server: Produce orchestration changes - Checkpoint-->>Server: Produce orchestration changes - Server->>Push: Publish resulting state updates - Push-->>Browser: User-visible push -``` - -1. Some work continues after the initial request returns, especially in [`ProviderRuntimeIngestion`][9], [`ProviderCommandReactor`][13], and [`CheckpointReactor`][14]. -2. These flows run as queue-backed workers using [`DrainableWorker`][16], which helps keep side effects ordered and test synchronization deterministic. -3. When a milestone completes, the server emits a typed receipt on [`RuntimeReceiptBus`][15], such as checkpoint completion or turn quiescence. -4. Tests and orchestration code wait on those receipts instead of polling git state, projections, or timers. -5. Any user-visible state changes produced by that async work still go back through `wsServer` and `ServerPushBus`. - -[8]: ../../apps/server/src/provider/Layers/ProviderService.ts -[9]: ../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts -[10]: ../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts -[11]: ../../packages/contracts/src/orchestration.ts -[13]: ../../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts -[14]: ../../apps/server/src/orchestration/Layers/CheckpointReactor.ts -[15]: ../../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts -[16]: ../../packages/shared/src/DrainableWorker.ts diff --git a/docs/architecture/providers.md b/docs/architecture/providers.md deleted file mode 100644 index 794b6aa5d5e..00000000000 --- a/docs/architecture/providers.md +++ /dev/null @@ -1,30 +0,0 @@ -# Provider architecture - -The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol: - -- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }` -- **Push events**: typed envelopes with `channel`, `sequence` (monotonic per connection), and channel-specific `data` - -Push channels: `server.welcome`, `server.configUpdated`, `terminal.event`, `orchestration.domainEvent`. Payloads are schema-validated at the transport boundary (`wsTransport.ts`). Decode failures produce structured `WsDecodeDiagnostic` with `code`, `reason`, and path info. - -Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`: - -- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn` -- `providers.respondToRequest`, `providers.stopSession` -- `shell.openInEditor`, `server.getConfig` - -Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI. - -## Client transport - -`wsTransport.ts` manages connection state: `connecting` → `open` → `reconnecting` → `closed` → `disposed`. Outbound requests are queued while disconnected and flushed on reconnect. Inbound pushes are decoded and validated at the boundary, then cached per channel. Subscribers can opt into `replayLatest` to receive the last push on subscribe. - -## Server-side orchestration layers - -Provider runtime events flow through queue-based workers: - -1. **ProviderRuntimeIngestion** — consumes provider runtime streams, emits orchestration commands -2. **ProviderCommandReactor** — reacts to orchestration intent events, dispatches provider calls -3. **CheckpointReactor** — captures git checkpoints on turn start/complete, publishes runtime receipts - -All three use `DrainableWorker` internally and expose `drain()` for deterministic test synchronization. diff --git a/docs/architecture/remote.md b/docs/architecture/remote.md deleted file mode 100644 index fc4fc0b4065..00000000000 --- a/docs/architecture/remote.md +++ /dev/null @@ -1,397 +0,0 @@ -# Remote Architecture - -This document describes the target architecture for first-class remote environments in T3 Code. - -It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite. - -## Goals - -- Treat remote environments as first-class product primitives, not special cases. -- Support multiple ways to reach the same environment. -- Keep the T3 server as the execution boundary. -- Let desktop, mobile, and web all share the same conceptual model. -- Avoid introducing a local control plane unless product pressure proves it is necessary. - -## Non-goals - -- Replacing the existing WebSocket server boundary with a custom transport protocol. -- Making SSH the only remote story. -- Syncing provider auth across machines. -- Shipping every access method in the first iteration. - -## High-level architecture - -T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations. - -Remote support should preserve that boundary. - -```text -┌──────────────────────────────────────────────┐ -│ Client (desktop / mobile / web) │ -│ │ -│ - known environments │ -│ - connection manager │ -│ - environment-aware routing │ -└───────────────┬──────────────────────────────┘ - │ - │ resolves one access endpoint - │ -┌───────────────▼──────────────────────────────┐ -│ Access method │ -│ │ -│ - direct ws / wss │ -│ - tunneled ws / wss │ -│ - desktop-managed ssh bootstrap + forward │ -└───────────────┬──────────────────────────────┘ - │ - │ connects to one T3 server - │ -┌───────────────▼──────────────────────────────┐ -│ Execution environment = one T3 server │ -│ │ -│ - environment identity │ -│ - provider state │ -│ - projects / threads / terminals │ -│ - git / filesystem / process runtime │ -└──────────────────────────────────────────────┘ -``` - -The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself. - -## Domain model - -### ExecutionEnvironment - -An `ExecutionEnvironment` is one running T3 server instance. - -It is the unit that owns: - -- provider availability and auth state -- model availability -- projects and threads -- terminal processes -- filesystem access -- git operations -- server settings - -It is identified by a stable `environmentId`. - -This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here. - -### KnownEnvironment - -A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach. - -It is not server-authored. It is local to a device or client profile. - -Examples: - -- a saved LAN URL -- a saved public `wss://` endpoint -- a desktop-managed SSH host entry -- a saved tunneled environment - -A known environment may or may not know the target `environmentId` before first successful connect. - -In the hosted web app, known environments are browser-local. A hosted pairing URL can create the saved entry, but it does not give the hosted app a server-side control plane or a copy of the session state. - -### AccessEndpoint - -An `AccessEndpoint` is one concrete way to reach a known environment. - -This is the key abstraction that keeps SSH from taking over the model. - -A single environment may have many endpoints: - -- `wss://t3.example.com` -- `ws://10.0.0.25:3773` -- a tunneled relay URL -- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL - -The environment stays the same. Only the access path changes. - -### AdvertisedEndpoint - -An `AdvertisedEndpoint` is a server or desktop-authored candidate endpoint for an environment. It is how the backend tells the client which URLs may be useful for pairing and reconnecting. - -`AdvertisedEndpoint` is deliberately narrower than the full access model: - -- it describes a concrete HTTP and WebSocket base URL pair -- it can mark the endpoint as default, available, or unavailable -- it includes reachability hints such as loopback, LAN, private, public, or tunnel -- it includes compatibility hints such as whether the endpoint can be used from the hosted HTTPS app - -Clients should treat advertised endpoints as hints, not as proof that a route works from the current device. The final connection attempt still decides whether the endpoint is reachable. - -The UI presents one default advertised endpoint in the network-access summary and keeps the rest behind an expandable advanced list. The default controls pairing QR codes and primary copy actions. Users can override it, but that override is a UI preference, not backend configuration. - -Persist the override by stable endpoint kind rather than raw URL whenever possible. For example, a LAN endpoint should be stored as the desktop LAN endpoint preference, not as `192.168.x.y`, because the address can change when the user switches networks. Provider endpoints should use provider-specific stable keys such as Tailscale IP or Tailscale MagicDNS HTTPS. Custom endpoints may fall back to their concrete identity. - -When no user default is saved, endpoint selection should prefer: - -1. endpoints compatible with the hosted HTTPS app -2. explicitly default endpoints -3. non-loopback endpoints -4. loopback endpoints only for same-machine clients - -This keeps endpoint discovery centralized without making any one provider, such as Tailscale or a future tunnel service, part of the core environment model. - -### Endpoint providers - -Endpoint providers are add-ons that contribute advertised endpoints for the current environment. - -The provider boundary is intentionally outside the core environment model: - -- core owns `ExecutionEnvironment`, saved environments, pairing, and connection lifecycle -- providers discover or synthesize endpoints -- providers return normalized `AdvertisedEndpoint` records -- the UI and pairing logic select from those records without knowing provider-specific commands - -The first provider is Tailscale. It can discover Tailnet IP and MagicDNS addresses from the local machine and publish them as additional endpoint candidates. Future providers, such as a hosted tunnel service, should plug into the same shape rather than adding a separate remote environment path. - -Provider-specific confidence should remain a hint. A Tailscale endpoint still needs a successful browser or desktop connection before the client treats it as connected. - -### Hosted pairing request - -A hosted pairing request is a bootstrap URL for the static web app, not a transport. - -Example: - -```text -https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE -``` - -The hosted app reads the `host` parameter and pairing token, exchanges the token directly with that backend, then saves the resulting environment record in browser local storage. - -Important constraints: - -- the hosted app does not proxy HTTP or WebSocket traffic -- the backend must still be reachable directly from the browser -- HTTPS pages can only connect to HTTPS/WSS backends -- HTTP LAN endpoints should keep using direct desktop or CLI pairing URLs -- the token belongs in the URL hash so it is not sent to the hosted app origin - -### RepositoryIdentity - -`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments. - -It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository. - -### Workspace / Project - -The current `Project` model remains environment-local. - -That means: - -- a local clone and a remote clone are different projects -- they may share a `RepositoryIdentity` -- threads still bind to one project in one environment - -## Access methods - -Access methods answer one question: - -How does the client speak WebSocket to a T3 server? - -They do not answer: - -- how the server got started -- who manages the server process -- whether the environment is local or remote - -### 1. Direct WebSocket access - -Examples: - -- `ws://10.0.0.15:3773` -- `wss://t3.example.com` - -This is the base model and should be the first-class default. - -Benefits: - -- works for desktop, mobile, and web -- no client-specific process management required -- best fit for hosted or self-managed remote T3 deployments - -Browser security rules are part of this access method. A hosted HTTPS web client can connect to `wss://` backends, but it cannot connect to plain `ws://` or `http://` LAN backends because that would be mixed content. - -### 2. Tunneled WebSocket access - -Examples: - -- public relay URLs -- private network relay URLs -- local tunnel products such as pipenet - -This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay. - -For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment. - -This is especially useful when: - -- the host is behind NAT -- inbound ports are unavailable -- mobile must reach a desktop-hosted environment -- a machine should be reachable without exposing raw LAN or public ports - -Tailscale-backed access sits here architecturally even though the current implementation is endpoint discovery rather than a T3-managed tunnel. It contributes private-network endpoints and lets the existing HTTP/WebSocket client path do the actual connection. - -### 3. Desktop-managed SSH access - -SSH is an access and launch helper, not a separate environment type. - -The desktop main process can use SSH to: - -- reach a machine -- probe it -- launch or reuse a remote T3 server -- establish a local port forward - -After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port. - -This keeps the renderer transport model consistent with every other access method. - -The desktop main process owns the SSH bridge because it can spawn local SSH processes, manage askpass prompts, write temporary launch scripts, and clean up forwards. The renderer receives a saved environment record and connects through the forwarded URL; it should not need SSH-specific RPC paths for normal environment traffic. - -## Launch methods - -Launch methods answer a different question: - -How does a T3 server come to exist on the target machine? - -Launch and access should stay separate in the design. - -### 1. Pre-existing server - -The simplest launch method is no launch at all. - -The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint. - -This should be the first remote mode shipped because it validates the environment model with minimal extra machinery. - -### 2. Desktop-managed remote launch over SSH - -This is the main place where Zed is a useful reference. - -Useful ideas to borrow from Zed: - -- remote probing -- platform detection -- session directories with pid/log metadata -- reconnect-friendly launcher behavior -- desktop-owned connection UX - -What should be different in T3: - -- no custom stdio/socket proxy protocol between renderer and remote runtime -- no attempt to make the remote runtime look like an editor transport -- keep the final client-to-server connection as WebSocket - -The recommended T3 flow is: - -1. Desktop connects over SSH. -2. Desktop probes the remote machine and verifies T3 availability. -3. Desktop launches or reuses a remote T3 server. -4. Desktop establishes local port forwarding. -5. Renderer connects to the forwarded WebSocket endpoint as a normal environment. - -The saved environment should remember that it was created by desktop SSH launch only for reconnect and lifecycle UX. That metadata should not change the server protocol or the environment identity model. - -Failure handling should be explicit: - -- SSH authentication failure should surface before any environment is saved -- remote launch failure should include remote logs or the launcher command output when available -- forwarded-port failure should leave the saved environment disconnected rather than falling back to an unrelated endpoint -- reconnect should attempt to restore the SSH bridge before reconnecting the normal WebSocket client - -### 3. Client-managed local publish - -This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel. - -This is useful for: - -- exposing a desktop-hosted environment to mobile -- temporary remote access without changing router or firewall settings - -This is still a launch concern, not a new environment kind. - -## Why access and launch must stay separate - -These concerns are easy to conflate, but separating them prevents architectural drift. - -Examples: - -- A manually hosted T3 server might be reached through direct `wss`. -- The same server might also be reachable through a tunnel. -- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket. -- A local desktop server might be published through a tunnel for mobile. - -In all of those cases, the `ExecutionEnvironment` is the same kind of thing. - -Only the launch and access paths differ. - -## Version Coordination - -Remote environments may stay online while web, desktop, or mobile clients move to a newer release. -The environment descriptor therefore carries the running server version and may advertise a safe -replacement path. The web and desktop UI use that information to show the appropriate action -without making the connection transport responsible for process management. - -Published CLI servers on supported hosts can install and hand off to the client's exact version. A -desktop-managed backend instead points the user to the desktop app on that machine, while older or -unsupported servers fall back to a manual relaunch. The existing connection supervisor owns the -disconnect and reconnect just as it would for any other involuntary socket close. - -See [Server Update Architecture](./server-updates.md) for capability detection, installation safety, -and restart sequencing. - -## Security model - -Remote support must assume that some environments will be reachable over untrusted networks. - -That means: - -- remote-capable environments should require explicit authentication -- tunnel exposure should not rely on obscurity -- client-saved endpoints should carry enough auth metadata to reconnect safely - -T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention. - -For publicly reachable environments, authenticated access should be treated as required. - -Hosted pairing should be treated as 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 safe or reachable from an HTTPS browser context. - -## Relationship to Zed - -Zed is a useful reference implementation for managed remote launch and reconnect behavior. - -The relevant lessons are: - -- remote bootstrap should be explicit -- reconnect should be first-class -- connection UX belongs in the client shell -- runtime ownership should stay clearly on the remote host - -The important mismatch is transport shape. - -Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime. - -T3 should not copy that part. - -T3 already has the right runtime boundary: - -- one T3 server per environment -- ordinary HTTP/WebSocket between client and environment - -So T3 should borrow Zed's launch discipline, not its transport protocol. - -## Recommended rollout - -1. First-class known environments and access endpoints. -2. Direct `ws` / `wss` remote environments. -3. Authenticated tunnel-backed environments. -4. Desktop-managed SSH launch and forwarding. -5. Multi-environment UI improvements after the base runtime path is proven. - -This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows. diff --git a/docs/architecture/runtime-modes.md b/docs/architecture/runtime-modes.md deleted file mode 100644 index 956b242e1c1..00000000000 --- a/docs/architecture/runtime-modes.md +++ /dev/null @@ -1,6 +0,0 @@ -# Runtime modes - -T3 Code has a global runtime mode switch in the chat toolbar: - -- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`. -- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals. diff --git a/docs/getting-started/codex-prerequisites.md b/docs/getting-started/codex-prerequisites.md deleted file mode 100644 index 608374d5db9..00000000000 --- a/docs/getting-started/codex-prerequisites.md +++ /dev/null @@ -1,5 +0,0 @@ -# Codex prerequisites - -- Install Codex CLI so `codex` is on your PATH. -- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex). -- T3 Code starts the server via `codex app-server` per session. diff --git a/docs/getting-started/quick-start.md b/docs/getting-started/quick-start.md deleted file mode 100644 index 2206d53ee58..00000000000 --- a/docs/getting-started/quick-start.md +++ /dev/null @@ -1,22 +0,0 @@ -# Quick start - -```bash -# Development (with hot reload) -bun run dev - -# Desktop development -bun run dev:desktop - -# Desktop development on an isolated port set -T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop - -# Production -bun run build -bun run start - -# Build a shareable macOS .dmg (arm64 by default) -bun run dist:desktop:dmg - -# Or from any project directory after publishing: -npx t3 -``` diff --git a/docs/internals/ci.md b/docs/internals/ci.md new file mode 100644 index 00000000000..e88b9a9e4b5 --- /dev/null +++ b/docs/internals/ci.md @@ -0,0 +1,24 @@ +# CI quality gates + +> For maintainers. Using T3 Code? See [docs/user](../user/). + +[`.github/workflows/ci.yml`](../../.github/workflows/ci.yml) runs four jobs 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 + still exports its expected symbols. +- **Test**: `vp run test` across the workspace. +- **Mobile Native Static Analysis**: `vp run lint:mobile` on macOS, wrapping + `scripts/mobile-native-static-check.ts`. +- **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. diff --git a/docs/internals/connection-runtime.md b/docs/internals/connection-runtime.md new file mode 100644 index 00000000000..d9c849104cf --- /dev/null +++ b/docs/internals/connection-runtime.md @@ -0,0 +1,174 @@ +# Connection Runtime + +> For maintainers. Using T3 Code? See [docs/user](../user/). + +The connection runtime is shared by web and mobile. It owns connectivity, +authentication, retries, transport lifetime, cached environment data, and +environment-scoped operations. + +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. + +## Composition + +[`connection/layer.ts`][layer] assembles the runtime: + +- `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`. + +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. + +`EnvironmentSupervisor` owns desired state, retry scheduling, and the active +session scope. React components do not create connections, transports, retry +loops, or RPC clients. + +## Connection State + +The supervisor is the only retry owner. + +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. + +### Wakeups + +Wakeup handling differs by phase, in [supervisor.ts][supervisor]: + +- During establishment, `waitForEstablishmentInterrupt` consumes and **ignores** + application activation. Restarting an in-flight attempt because the app came + to the foreground would only delay it. +- 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. +- Once connected, `monitorConnectedLease` handles application activation by + probing the existing session (`lease.session.probe`, bounded by a 15-second + timeout) rather than reconnecting. A healthy session survives foregrounding. + +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. + +## 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 diff --git a/docs/cloud/environment-auth.md b/docs/internals/environment-auth.md similarity index 71% rename from docs/cloud/environment-auth.md rename to docs/internals/environment-auth.md index af92bcb474d..78190856458 100644 --- a/docs/cloud/environment-auth.md +++ b/docs/internals/environment-auth.md @@ -1,5 +1,7 @@ # Environment Authentication Profile +> For maintainers. Using T3 Code? See [docs/user](../user/). + 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. @@ -61,26 +63,52 @@ The response has the token-exchange shape: "access_token": "", "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", "token_type": "Bearer", - "expires_in": 3600, + "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. + +`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. This keeps bearer tokens and -browser cookies out of WebSocket URLs while allowing the socket handshake to -authenticate. The ticket carries its session's scopes; each RPC method then -enforces `orchestration:read`, `orchestration:operate`, `terminal:operate`, -`review:write`, or `access:read` as appropriate. 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. +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_SCOPE` in `ws.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 diff --git a/docs/reference/encyclopedia.md b/docs/internals/glossary.md similarity index 60% rename from docs/reference/encyclopedia.md rename to docs/internals/glossary.md index 82a58fd959c..da16f74d339 100644 --- a/docs/reference/encyclopedia.md +++ b/docs/internals/glossary.md @@ -1,4 +1,6 @@ -# Encyclopedia +# 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. @@ -16,7 +18,7 @@ This is a living glossary for T3 Code. It explains what common terms mean in thi #### Project -The top-level workspace record in the app. In [the orchestration contracts][1], a project has a `workspaceRoot`, a title, and one or more threads. See [workspace-layout.md][2]. +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 @@ -24,7 +26,7 @@ The root filesystem path for a project. In [the orchestration model][1], it is t #### 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 in [GitCore.ts][3]. +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 @@ -34,7 +36,7 @@ The main durable unit of conversation and workspace history. In [the orchestrati #### Turn -A single user-to-assistant work cycle inside a thread. It starts with user input and ends when follow-up work like checkpointing settles. See [the contracts][1], [ProviderRuntimeIngestion.ts][5], and [CheckpointReactor.ts][6]. +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 @@ -80,20 +82,19 @@ A side-effecting service that handles follow-up work after events or runtime sig #### Receipt -A lightweight typed runtime signal emitted when an async milestone completes. See [RuntimeReceiptBus.ts][13]. -Examples include `checkpoint.baseline.captured`, `checkpoint.diff.finalized`, and `turn.processing.quiesced`, which are emitted by flows such as [CheckpointReactor.ts][6]. +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. In [the receipt schema][13], it means the follow-up work has settled, including work in [CheckpointReactor.ts][6]. +"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 [provider-architecture.md][16]. +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. See [ProviderService.ts][14], [ProviderAdapter.ts][15], and [CodexAdapter.ts][17]. +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 @@ -101,15 +102,15 @@ The live provider-backed runtime attached to a thread. Session shape is in [the #### Runtime mode -The safety/access mode for a thread or session. In [the contracts][1], the main values are `approval-required` and `full-access`. See [runtime-modes.md][18]. +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 main values are `default` and `plan`. See [runtime-modes.md][18]. +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` delivers a completed result. See [ProviderService.ts][14]. +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 @@ -143,38 +144,38 @@ The file patch and changed-file summary for one turn. It is usually computed in - If you see `requested`, think "intent recorded". - If you see `completed`, think "result applied". -- If you see `receipt`, think "async milestone signal". +- 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.md][24] -- [provider-architecture.md][16] -- [runtime-modes.md][18] -- [workspace-layout.md][2] +- [Architecture overview][24] +- [Provider architecture][16] +- [Permission modes][18] +- [Workspace layout][2] -[1]: ../packages/contracts/src/orchestration.ts +[1]: ../../packages/contracts/src/orchestration.ts [2]: ./workspace-layout.md -[3]: ../apps/server/src/git/Layers/GitCore.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]: ./provider-architecture.md -[17]: ../apps/server/src/provider/Layers/CodexAdapter.ts -[18]: ./runtime-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]: ./architecture.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 diff --git a/docs/internals/overview.md b/docs/internals/overview.md new file mode 100644 index 00000000000..a08079dd55f --- /dev/null +++ b/docs/internals/overview.md @@ -0,0 +1,150 @@ +# Architecture + +> For maintainers. Using T3 Code? See [docs/user](../user/). + +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. + +``` +┌────────────────────────────────────────────────┐ +│ 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 │ +└────────────────────────────────────────────────┘ +``` + +## The RPC boundary + +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. + +[`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). + +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. + +## Shared client runtime + +`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 identically (`apps/web/src/connection/runtime.ts` and +`apps/mobile/src/connection/runtime.ts` are byte-identical) and differ 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). + +## Orchestration is event-sourced + +The server does not mutate app state directly. Clients dispatch typed commands; the engine turns them +into persisted events; projections derive the read model. + +[`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`: + +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 and publishes committed events to subscribers. + +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. + +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`). + +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. + +## 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, and +[`CheckpointReactor`][checkpoint] captures and reverts workspace checkpoints. + +`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 the three 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) +- [Remote environments](./remote.md), [Server updates](./server-updates.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 +[receipts]: ../../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts +[drivers]: ../../apps/server/src/provider/builtInDrivers.ts diff --git a/docs/internals/providers.md b/docs/internals/providers.md new file mode 100644 index 00000000000..a309d70f03d --- /dev/null +++ b/docs/internals/providers.md @@ -0,0 +1,92 @@ +# Provider architecture + +> For maintainers. Using T3 Code? See [docs/user](../user/). + +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. + +## Built-in drivers + +[`builtInDrivers.ts`][drivers] exports `BUILT_IN_DRIVERS` with five entries: + +| 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] | + +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. + +## Registry and routing + +Two registries separate configuration from live processes: + +- [`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`. + +[`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. + +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. + +## 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 +[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 diff --git a/docs/internals/remote.md b/docs/internals/remote.md new file mode 100644 index 00000000000..afce95f725b --- /dev/null +++ b/docs/internals/remote.md @@ -0,0 +1,235 @@ +# Remote Architecture + +> For maintainers. Using T3 Code? See [docs/user](../user/). + +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). + +## The model + +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. + +```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 │ +└──────────────────────────────────────────────┘ +``` + +### ExecutionEnvironment + +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. + +It is identified by a stable `environmentId`, persisted by the server at `/environment-id` +and generated on first start (`apps/server/src/environment/ServerEnvironment.ts`). Desktop, mobile, +and web all reason about the same concept. + +### Known environments and connection targets + +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. + +[`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 diff --git a/docs/internals/scripts.md b/docs/internals/scripts.md new file mode 100644 index 00000000000..2a020701064 --- /dev/null +++ b/docs/internals/scripts.md @@ -0,0 +1,119 @@ +# 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. +- `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 `/.t3/userdata`. Pass `--home-dir ` 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 ` stores state under + `/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 --base-dir ...`: Inspects or seeds + an isolated T3 SQLite database; writes create a private backup first. + +## Desktop artifacts + +- `vp run dist:desktop:artifact --platform --target --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 `, 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. +- 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. diff --git a/docs/architecture/server-updates.md b/docs/internals/server-updates.md similarity index 89% rename from docs/architecture/server-updates.md rename to docs/internals/server-updates.md index 2e8c9d6ef61..a6a39e5b576 100644 --- a/docs/architecture/server-updates.md +++ b/docs/internals/server-updates.md @@ -1,5 +1,7 @@ # Server Update Architecture +> For maintainers. Using T3 Code? See [docs/user](../user/). + T3 Code can update a connected server to the exact version of the client that detected version drift. This path exists primarily for remote environments, where the user may not have a terminal open on the server machine. @@ -54,7 +56,8 @@ flowchart TD B -->|boot-service or respawn| E[server.updateServer] E --> F[Install exact t3 version in pinned runtime] F --> G[Run version preflight] - G -->|fails| H[Remove failed runtime and keep current server] + G -->|bad code or version| H[Remove candidate runtime and keep current server] + G -->|cannot run preflight| H2[Keep candidate and current server] G -->|passes| I{Handoff method} I -->|boot-service| J[Rewrite and restart T3 systemd unit] I -->|respawn| K[Start delayed replacement and exit current process] @@ -72,8 +75,14 @@ successfully. Boot-service setup and self-update share the same process-wide ins they cannot mutate a pinned runtime concurrently. Before any restart, the current Node executable runs the replacement with `--version`. A failed -install, failed preflight, or wrong reported version leaves the current server running. A failed -preflight also removes the candidate runtime so retrying the same version performs a clean install. +install, failed preflight, or wrong reported version leaves the current server running. + +Candidate cleanup is narrower than "any failed preflight". The candidate runtime is removed only when +the preflight process actually completes and reports a bad exit code or the wrong version: that is +the case where a completed npm install produced an unusable tree, so retrying the same version must +perform a clean install rather than reuse it. If the preflight cannot run at all, for example a spawn +error or the `PREFLIGHT_TIMEOUT` elapsing, the update fails before reaching cleanup and the candidate +directory is left in place. ## Host Service Lifecycle diff --git a/docs/cloud/t3-code-connect-auth-flow.html b/docs/internals/t3-code-connect-auth-flow.html similarity index 100% rename from docs/cloud/t3-code-connect-auth-flow.html rename to docs/internals/t3-code-connect-auth-flow.html diff --git a/docs/cloud/t3-connect-clerk.md b/docs/internals/t3-connect.md similarity index 75% rename from docs/cloud/t3-connect-clerk.md rename to docs/internals/t3-connect.md index 2fe48243a59..c8a0217919f 100644 --- a/docs/cloud/t3-connect-clerk.md +++ b/docs/internals/t3-connect.md @@ -1,8 +1,16 @@ -# T3 Connect Clerk Setup +# T3 Connect -T3 Connect uses one Clerk application for web, desktop, and mobile authentication. The relay accepts -Clerk JWTs only when they are generated from the `t3-relay` template with the shared -`t3-code-relay` audience. +> For maintainers. Using T3 Code? See [docs/user](../user/). + +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. + +For the wider system diagram, see +[t3-code-connect-auth-flow.html](./t3-code-connect-auth-flow.html). ## Application Keys @@ -35,10 +43,11 @@ should set `T3CODE_CLERK_PUBLISHABLE_KEY`, `T3CODE_CLERK_JWT_TEMPLATE`, production builds only need the Clerk publishable key, JWT template name, and relay URL in their EAS environment. -When any client-facing public value is absent, cloud UI is omitted. When the CLI public values are -absent, the `t3 connect` CLI command group is omitted. The bundled server still accepts runtime -overrides for self-hosted or operator-managed -deployments. +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. 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`, @@ -63,7 +72,12 @@ 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 `http://127.0.0.1:34338/callback` as an allowed redirect URI. +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. @@ -72,17 +86,20 @@ The CLI derives Clerk's frontend API URL from the publishable key and calls Cler `/oauth/authorize` and `/oauth/token` endpoints 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 CLI supports these headless operations: +The connect command group is: ```sh +t3 connect # default: onboarding t3 connect login -t3 connect link -t3 connect status +t3 connect link # --publish-only +t3 connect status # --json +t3 connect publish # --disable t3 connect unlink t3 connect logout -t3 serve ``` +`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 @@ -95,16 +112,21 @@ 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`. -The current OAuth callback listener binds to loopback port `34338`. When running the CLI over SSH, -forward that port before running `t3 connect login` or `t3 connect link`: +### 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 ``` -A relay-hosted callback broker can remove this port-forward requirement later without changing the -stored PKCE token model. - ## JWT Template In **Clerk Dashboard > JWT templates**, create a template with: @@ -207,34 +229,26 @@ 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. -## Enable Waitlist Access - -For a private beta where people should request access, use **Clerk Dashboard > Waitlist**: - -1. Toggle on **Enable waitlist** and save. -2. Review requests on the same page and select **Invite** or **Deny**. - -Approved signed-in users manage T3 Connect under **Connections**. The web and desktop sidebars do -not expose a dedicated account or waitlist control. Signed-out users reach Clerk's waitlist and -sign-in flow contextually from the T3 Connect controls on the Connections page. - -On mobile, signed-out users open **Settings > T3 Account** to reach `/settings/waitlist` within the -Settings form sheet. It submits enrollment through Clerk's `useWaitlist()` flow because the prebuilt -`` component is web-only in the Expo SDK. Approved users can use **Sign in** from that -screen. +## Sign-in Surfaces -## Alternative: Known-User Allowlist +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. -For a closed beta where all permitted users are known in advance, use an allowlist instead of a -request-and-approval waitlist: +## Restricting Sign-ups: Known-User Allowlist -To restrict the beta to permitted email addresses or domains: +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 without a waitlist request flow. + manually created. Do not enable an empty allowlist: it blocks all new sign-ups. diff --git a/docs/internals/workspace-layout.md b/docs/internals/workspace-layout.md new file mode 100644 index 00000000000..e933e452891 --- /dev/null +++ b/docs/internals/workspace-layout.md @@ -0,0 +1,63 @@ +# 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`. diff --git a/docs/operations/ci.md b/docs/operations/ci.md deleted file mode 100644 index 7a0447ec070..00000000000 --- a/docs/operations/ci.md +++ /dev/null @@ -1,6 +0,0 @@ -# CI quality gates - -- `.github/workflows/ci.yml` runs `vp check` (lint + typecheck), `vpr typecheck`, and `vp run test` on pull requests and pushes to `main`. -- `.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. -- The release workflow 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](./release.md) for the full release/signing setup checklist. diff --git a/docs/operations/effect-fn-checklist.md b/docs/operations/effect-fn-checklist.md deleted file mode 100644 index 938dea8d681..00000000000 --- a/docs/operations/effect-fn-checklist.md +++ /dev/null @@ -1,198 +0,0 @@ -# Effect.fn Refactor Checklist - -Generated from a repo scan for non-test wrapper-style candidates matching either `=> Effect.gen(function* ...)` or `return Effect.gen(function* ...)`. - -Refactor Method: - -```ts -// Old -function old () { - return Effect.gen(function* () { - ... - }); -} - -const old2 = () => Effect.gen(function* () { - ... -}); -``` - -```ts -// New -const new = Effect.fn('functionName')(function* () { - ... -}) -``` - -- Use `Effect.fn('name')(function* (input: Input): Effect.fn.Return {})` to annotate the return type of the function if needed. - -- The 2nd argument works as a pipe, and it gets the effect and input as arguments: - -```ts -Effect.fn("name")( - function* (input: Input): Effect.fn.Return {}, - (effect, input) => Effect.catch(effect, (reason) => Effect.logWarning("Err", { input, reason })), -); -``` - -## Summary - -- Total non-test candidates: `322` - -## Suggested Order - -- [ ] `apps/server/src/provider/Layers/ProviderService.ts` -- [x] `apps/server/src/provider/Layers/ClaudeAdapter.ts` -- [x] `apps/server/src/provider/Layers/CodexAdapter.ts` -- [x] `apps/server/src/git/Layers/GitCore.ts` -- [x] `apps/server/src/git/Layers/GitManager.ts` -- [x] `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` -- [x] `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` -- [ ] `apps/server/src/orchestration/Layers/OrchestrationEngine.ts` -- [ ] `apps/server/src/provider/Layers/EventNdjsonLogger.ts` -- [ ] `Everything else` - -## Checklist - -### `apps/server/src/provider/Layers/ClaudeAdapter.ts` (`62`) - -- [x] [buildUserMessageEffect](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L554) -- [x] [makeClaudeAdapter](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L913) -- [x] [startSession](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L2414) -- [x] [sendTurn](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L2887) -- [x] [interruptTurn](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L2975) -- [x] [readThread](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L2984) -- [x] [rollbackThread](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L2990) -- [x] [stopSession](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L3039) -- [x] Internal helpers and callback wrappers in this file - -### `apps/server/src/git/Layers/GitCore.ts` (`58`) - -- [x] [makeGitCore](../../apps/server/src/git/Layers/GitCore.ts#L513) -- [x] [handleTraceLine](../../apps/server/src/git/Layers/GitCore.ts#L324) -- [x] [emitCompleteLines](../../apps/server/src/git/Layers/GitCore.ts#L455) -- [x] [commit](../../apps/server/src/git/Layers/GitCore.ts#L1190) -- [x] [pushCurrentBranch](../../apps/server/src/git/Layers/GitCore.ts#L1223) -- [x] [pullCurrentBranch](../../apps/server/src/git/Layers/GitCore.ts#L1323) -- [x] [checkoutBranch](../../apps/server/src/git/Layers/GitCore.ts#L1727) -- [x] Service methods and callback wrappers in this file - -### `apps/server/src/git/Layers/GitManager.ts` (`28`) - -- [x] [configurePullRequestHeadUpstream](../../apps/server/src/git/Layers/GitManager.ts#L387) -- [x] [materializePullRequestHeadBranch](../../apps/server/src/git/Layers/GitManager.ts#L428) -- [x] [findOpenPr](../../apps/server/src/git/Layers/GitManager.ts#L576) -- [x] [findLatestPr](../../apps/server/src/git/Layers/GitManager.ts#L602) -- [x] [runCommitStep](../../apps/server/src/git/Layers/GitManager.ts#L728) -- [x] [runPrStep](../../apps/server/src/git/Layers/GitManager.ts#L842) -- [x] [runFeatureBranchStep](../../apps/server/src/git/Layers/GitManager.ts#L1106) -- [x] Remaining helpers and nested callback wrappers in this file - -### `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` (`25`) - -- [x] [runProjectorForEvent](../../apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L1161) -- [x] [applyProjectsProjection](../../apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L357) -- [x] [applyThreadsProjection](../../apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L415) -- [x] `Effect.forEach(..., threadId => Effect.gen(...))` callbacks around `L250` -- [x] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L264` -- [x] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L305` -- [x] Remaining apply helpers in this file - -### `apps/server/src/provider/Layers/ProviderService.ts` (`24`) - -- [ ] [makeProviderService](../../apps/server/src/provider/Layers/ProviderService.ts#L134) -- [ ] [recoverSessionForThread](../../apps/server/src/provider/Layers/ProviderService.ts#L196) -- [ ] [resolveRoutableSession](../../apps/server/src/provider/Layers/ProviderService.ts#L255) -- [ ] [startSession](../../apps/server/src/provider/Layers/ProviderService.ts#L284) -- [ ] [sendTurn](../../apps/server/src/provider/Layers/ProviderService.ts#L347) -- [ ] [interruptTurn](../../apps/server/src/provider/Layers/ProviderService.ts#L393) -- [ ] [respondToRequest](../../apps/server/src/provider/Layers/ProviderService.ts#L411) -- [ ] [respondToUserInput](../../apps/server/src/provider/Layers/ProviderService.ts#L430) -- [ ] [stopSession](../../apps/server/src/provider/Layers/ProviderService.ts#L445) -- [ ] [listSessions](../../apps/server/src/provider/Layers/ProviderService.ts#L466) -- [ ] [rollbackConversation](../../apps/server/src/provider/Layers/ProviderService.ts#L516) -- [ ] [runStopAll](../../apps/server/src/provider/Layers/ProviderService.ts#L538) - -### `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` (`14`) - -- [x] [finalizeAssistantMessage](../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L680) -- [x] [upsertProposedPlan](../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L722) -- [x] [finalizeBufferedProposedPlan](../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L761) -- [x] [clearTurnStateForSession](../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L800) -- [x] [processRuntimeEvent](../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L908) -- [x] Nested callback wrappers in this file - -### `apps/server/src/provider/Layers/CodexAdapter.ts` (`12`) - -- [x] [makeCodexAdapter](../../apps/server/src/provider/Layers/CodexAdapter.ts#L1317) -- [x] [sendTurn](../../apps/server/src/provider/Layers/CodexAdapter.ts#L1399) -- [x] [writeNativeEvent](../../apps/server/src/provider/Layers/CodexAdapter.ts#L1546) -- [x] [listener](../../apps/server/src/provider/Layers/CodexAdapter.ts#L1555) -- [x] Remaining nested callback wrappers in this file - -### `apps/server/src/checkpointing/CheckpointStore.ts` (`10`) - -- [ ] [captureCheckpoint](../../apps/server/src/checkpointing/CheckpointStore.ts#L123) -- [ ] [restoreCheckpoint](../../apps/server/src/checkpointing/CheckpointStore.ts#L137) -- [ ] [diffCheckpoints](../../apps/server/src/checkpointing/CheckpointStore.ts#L144) -- [ ] [deleteCheckpointRefs](../../apps/server/src/checkpointing/CheckpointStore.ts#L151) -- [ ] Nested callback wrappers in this file - -### `apps/server/src/provider/Layers/EventNdjsonLogger.ts` (`9`) - -- [ ] [toLogMessage](../../apps/server/src/provider/Layers/EventNdjsonLogger.ts#L77) -- [ ] [makeThreadWriter](../../apps/server/src/provider/Layers/EventNdjsonLogger.ts#L102) -- [ ] [makeEventNdjsonLogger](../../apps/server/src/provider/Layers/EventNdjsonLogger.ts#L174) -- [ ] [write](../../apps/server/src/provider/Layers/EventNdjsonLogger.ts#L231) -- [ ] [close](../../apps/server/src/provider/Layers/EventNdjsonLogger.ts#L247) -- [ ] Flush and writer-resolution callback wrappers in this file - -### `apps/server/scripts/cli.ts` (`8`) - -- [ ] Command handlers around [cli.ts](../../apps/server/scripts/cli.ts#L125) -- [ ] Command handlers around [cli.ts](../../apps/server/scripts/cli.ts#L170) -- [ ] Resource callbacks around [cli.ts](../../apps/server/scripts/cli.ts#L221) -- [ ] Resource callbacks around [cli.ts](../../apps/server/scripts/cli.ts#L239) - -### `apps/server/src/orchestration/Layers/OrchestrationEngine.ts` (`7`) - -- [ ] [processEnvelope](../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L64) -- [ ] [dispatch](../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L218) -- [ ] Catch/stream callback wrappers around [OrchestrationEngine.ts](../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L162) -- [ ] Catch/stream callback wrappers around [OrchestrationEngine.ts](../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L200) - -### `apps/server/src/orchestration/projector.ts` (`5`) - -- [ ] `switch` branch wrapper at [projector.ts](../../apps/server/src/orchestration/projector.ts#L242) -- [ ] `switch` branch wrapper at [projector.ts](../../apps/server/src/orchestration/projector.ts#L336) -- [ ] `switch` branch wrapper at [projector.ts](../../apps/server/src/orchestration/projector.ts#L397) -- [ ] `switch` branch wrapper at [projector.ts](../../apps/server/src/orchestration/projector.ts#L446) -- [ ] `switch` branch wrapper at [projector.ts](../../apps/server/src/orchestration/projector.ts#L478) - -### Smaller clusters - -- [ ] [packages/shared/src/DrainableWorker.ts](../../packages/shared/src/DrainableWorker.ts) (`4`) -- [ ] [apps/server/src/wsServer/pushBus.ts](../../apps/server/src/wsServer/pushBus.ts) (`4`) -- [ ] [apps/server/src/wsServer.ts](../../apps/server/src/wsServer.ts) (`4`) -- [ ] [apps/server/src/provider/Layers/ProviderRegistry.ts](../../apps/server/src/provider/Layers/ProviderRegistry.ts) (`4`) -- [ ] [apps/server/src/persistence/Layers/Sqlite.ts](../../apps/server/src/persistence/Layers/Sqlite.ts) (`4`) -- [ ] [apps/server/src/orchestration/Layers/ProviderCommandReactor.ts](../../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts) (`4`) -- [ ] [apps/server/src/main.ts](../../apps/server/src/main.ts) (`4`) -- [ ] [apps/server/src/keybindings.ts](../../apps/server/src/keybindings.ts) (`4`) -- [ ] [apps/server/src/git/Layers/CodexTextGeneration.ts](../../apps/server/src/git/Layers/CodexTextGeneration.ts) (`4`) -- [ ] [apps/server/src/serverLayers.ts](../../apps/server/src/serverLayers.ts) (`3`) -- [ ] [apps/server/src/telemetry/Layers/AnalyticsService.ts](../../apps/server/src/telemetry/Layers/AnalyticsService.ts) (`2`) -- [ ] [apps/server/src/telemetry/Identify.ts](../../apps/server/src/telemetry/Identify.ts) (`2`) -- [ ] [apps/server/src/provider/Layers/ProviderAdapterRegistry.ts](../../apps/server/src/provider/Layers/ProviderAdapterRegistry.ts) (`2`) -- [ ] [apps/server/src/provider/Layers/CodexProvider.ts](../../apps/server/src/provider/Layers/CodexProvider.ts) (`2`) -- [ ] [apps/server/src/provider/Layers/ClaudeProvider.ts](../../apps/server/src/provider/Layers/ClaudeProvider.ts) (`2`) -- [ ] [apps/server/src/persistence/NodeSqliteClient.ts](../../apps/server/src/persistence/NodeSqliteClient.ts) (`2`) -- [ ] [apps/server/src/persistence/Migrations.ts](../../apps/server/src/persistence/Migrations.ts) (`2`) -- [ ] [apps/server/src/open.ts](../../apps/server/src/open.ts) (`2`) -- [ ] [apps/server/src/git/Layers/ClaudeTextGeneration.ts](../../apps/server/src/git/Layers/ClaudeTextGeneration.ts) (`2`) -- [ ] [apps/server/src/checkpointing/CheckpointDiffQuery.ts](../../apps/server/src/checkpointing/CheckpointDiffQuery.ts) (`2`) -- [ ] [apps/server/src/provider/makeManagedServerProvider.ts](../../apps/server/src/provider/makeManagedServerProvider.ts) (`1`) - -``` - -``` diff --git a/docs/operations/mobile-app-store-screenshots.md b/docs/operations/mobile-app-store-screenshots.md index 2c36ab9d008..27891cb5d63 100644 --- a/docs/operations/mobile-app-store-screenshots.md +++ b/docs/operations/mobile-app-store-screenshots.md @@ -1,5 +1,7 @@ # Mobile app-store screenshot harness +> For maintainers. Using T3 Code? See [docs/user](../user/). + The screenshot harness runs the real mobile application against three disposable local T3 environments. It creates an isolated base directory and server for each environment, real Git projects with deterministic content, seeded orchestration projections, and persisted terminal @@ -44,35 +46,44 @@ delay allows native terminal and Git review data to finish rendering. A full capture regenerates the selected native project with Expo's clean development prebuild before building it. Use --skip-build for repeated captures after the first build. -The harness uses its own Metro port (8199 by default), so an ordinary mobile server or another -worktree cannot accidentally provide the bundle being photographed. +The harness uses fixed Metro port `8199`, which separates it from Expo's normal default port but is +shared across every checkout. The readiness check only verifies that the port is open; it does not +verify process ownership. Concurrent screenshot harnesses in different worktrees can therefore +collide or attach to the wrong Metro process. + +Every configured device defaults to dark appearance, so plain `pnpm screenshots:mobile` produces +30 dark PNGs. Pass `--appearance light`, `--appearance dark`, or `--appearance both` to override the +configured appearance; `both` produces 60 PNGs. The default matrix is: -| Output folder | Capture target | Upload dimensions | Store slot | -| ------------------------------------- | ------------------------- | ----------------- | ----------------------------------------- | -| `apple/iphone-6.9/{light,dark}/` | iPhone 17 Pro Max | 1320×2868 | App Store Connect iPhone 6.9-inch | -| `apple/iphone-6.5/{light,dark}/` | disposable iPhone 14 Plus | 1284×2778 | App Store Connect iPhone 6.5-inch | -| `apple/ipad-13/{light,dark}/` | iPad Pro 13-inch (M5) | 2064×2752 | App Store Connect iPad 13-inch | -| `google-play/phone/{light,dark}/` | Pixel AVD at 420 dpi | 1080×1920 | Google Play phone, portrait 9:16 | -| `google-play/tablet-7/{light,dark}/` | Pixel AVD at 600dp width | 1080×1920 | Google Play 7-inch tablet, portrait 9:16 | -| `google-play/tablet-10/{light,dark}/` | Pixel AVD at 800dp width | 1440×2560 | Google Play 10-inch tablet, portrait 9:16 | - -Each target captures thread, terminal, review, thread list, and environments, producing 30 PNG -files for one appearance or 60 for both. Each appearance folder's five screenshots satisfy the configured Apple limit of 1–10, Google +| Output folder | Capture target | Upload dimensions | Store slot | +| ----------------------------- | ------------------------- | ----------------- | ----------------------------------------- | +| `apple/iphone-6.9/dark/` | iPhone 17 Pro Max | 1320×2868 | App Store Connect iPhone 6.9-inch | +| `apple/iphone-6.5/dark/` | disposable iPhone 14 Plus | 1284×2778 | App Store Connect iPhone 6.5-inch | +| `apple/ipad-13/dark/` | iPad Pro 13-inch (M5) | 2064×2752 | App Store Connect iPad 13-inch | +| `google-play/phone/dark/` | Pixel AVD at 420 dpi | 1080×1920 | Google Play phone, portrait 9:16 | +| `google-play/tablet-7/dark/` | Pixel AVD at 600dp width | 1080×1920 | Google Play 7-inch tablet, portrait 9:16 | +| `google-play/tablet-10/dark/` | Pixel AVD at 800dp width | 1440×2560 | Google Play 10-inch tablet, portrait 9:16 | + +Each target captures thread, terminal, review, thread list, and environments. Each appearance +folder's five screenshots satisfy the configured Apple limit of 1–10, Google phone requirement of 2–8, and Google tablet recommendation/slot minimum of 4 with a maximum of 8. The generated tree is deliberately aligned with the store upload fields: artifacts/app-store/screenshots/ ├── apple/ - │ ├── iphone-6.9/{light,dark}/{thread,terminal,review,threads,environments}.png - │ ├── iphone-6.5/{light,dark}/{thread,terminal,review,threads,environments}.png - │ └── ipad-13/{light,dark}/{thread,terminal,review,threads,environments}.png + │ ├── iphone-6.9/dark/{thread,terminal,review,threads,environments}.png + │ ├── iphone-6.5/dark/{thread,terminal,review,threads,environments}.png + │ └── ipad-13/dark/{thread,terminal,review,threads,environments}.png └── google-play/ - ├── phone/{light,dark}/{thread,terminal,review,threads,environments}.png - ├── tablet-7/{light,dark}/{thread,terminal,review,threads,environments}.png - └── tablet-10/{light,dark}/{thread,terminal,review,threads,environments}.png + ├── phone/dark/{thread,terminal,review,threads,environments}.png + ├── tablet-7/dark/{thread,terminal,review,threads,environments}.png + └── tablet-10/dark/{thread,terminal,review,threads,environments}.png + +A light-only run writes the same tree under `light/`; `--appearance both` writes both appearance +folders. Edit [mobile-showcase.config.ts](../../scripts/mobile-showcase.config.ts) to change simulator or AVD names, light/dark appearance, scenes, output directory, capture delay, Android ABI, or viewport. @@ -85,10 +96,11 @@ runs iOS and Android concurrently: iPhone and iPad capture on a 12-vCPU Blacksmith macOS runner, while Android phone, 7-inch tablet, and 10-inch tablet capture on a 16-vCPU Blacksmith Linux runner with a KVM-accelerated x86_64 emulator. -Every job uploads its PNGs even when a later capture fails, which makes partial runs useful for -diagnosis. Download `app-store-connect-screenshots` and `google-play-screenshots` from the workflow -run's Artifacts section. Each job runs validation again immediately before upload. Artifacts are -retained for 14 days. +Every job uploads its PNGs even when capture fails, which makes partial runs useful for diagnosis. +The separate validation step is success-gated: it runs before upload only when capture succeeds. If +capture fails, the `always()` upload still publishes partial PNGs without re-validating them. +Download `app-store-connect-screenshots` and `google-play-screenshots` from the workflow run's +Artifacts section. Artifacts are retained for 14 days. The workflow uses the same checked-in device and scene matrix as local capture. Android remains ARM64 by default for local Apple Silicon development; CI sets `T3_SHOWCASE_ANDROID_ABI=x86_64` so the @@ -111,11 +123,19 @@ Reuse the native build and retain the disposable environment: pnpm screenshots:mobile --device ipad-13 --skip-build --keep-running -Run Metro separately: +By default, let the screenshot runner start Metro on port `8199`. To keep Metro in a separate +terminal, start it with the same showcase environment and explicit harness port: + + cd apps/mobile + APP_VARIANT=development EXPO_PUBLIC_SHOWCASE=1 pnpm exec expo start --dev-client --port 8199 + +Then run the capture from the repository root: - pnpm --filter @t3tools/mobile showcase pnpm screenshots:mobile --skip-build --skip-metro --device iphone-6.9 +`pnpm --filter @t3tools/mobile showcase` starts Expo on its normal port, so it is not compatible with +the harness's `--skip-metro` mode. + List the matrix and flags: pnpm screenshots:mobile --list @@ -151,7 +171,9 @@ remote-first while the harness retains reliable loopback connections to its ephe ## Local prerequisites - iOS: Xcode command-line tools, the configured simulator runtimes, and installed CocoaPods. -- Android: ANDROID_HOME (or the default macOS SDK path), adb, emulator, and the configured AVD. +- Android: SDK resolution checks `ANDROID_HOME`, then `ANDROID_SDK_ROOT`, then defaults to + `$HOME/Library/Android/sdk` on macOS or `$HOME/Android/Sdk` on other platforms. The resolved SDK + must provide `adb` and `emulator`, and the configured AVD must exist. The harness is the source of truth for upload dimensions; do not resize its output. If store rules change, update the target's `storeAsset` specification. Capture fails when a PNG is the wrong size, diff --git a/docs/operations/observability.md b/docs/operations/observability.md index 1d55894b182..7341bfb5eda 100644 --- a/docs/operations/observability.md +++ b/docs/operations/observability.md @@ -1,39 +1,53 @@ # Observability +> For maintainers. Using T3 Code? See [docs/user](../user/). + T3 Code has one server-side observability model: - pretty logs go to stdout for humans - completed spans go to a local NDJSON trace file - traces and metrics can also be exported over OTLP to a real backend like Grafana LGTM -The local trace file is the persisted source of truth. There is no separate persisted server log file anymore. +The local trace file is the persisted source of truth for normal local launches. Those launches do not +write a separate server log file, but SSH-managed launches also persist the remote process's +stdout/stderr at `~/.t3/ssh-launch//server.log`. ## Where To Find Things ### Logs -Logs are human-facing only: +Logs are human-facing: - destination: stdout - format: `Logger.consolePretty()` -- persistence: none +- normal local persistence: none +- SSH-managed launch persistence: `~/.t3/ssh-launch//server.log` If you want a log message to show up in the trace file, emit it inside an active span with `Effect.log...`. `Logger.tracerLogger` will attach it as a span event. ### Traces -Completed spans are written as NDJSON records to `serverTracePath` (by default, `~/.t3/userdata/logs/server.trace.ndjson`). +Completed spans are written as NDJSON records to `serverTracePath`. The default depends on how the +server starts: production and explicitly configured homes use +`/userdata/logs/server.trace.ndjson` (so `~/.t3/userdata/...` by default, or +`/custom/path/userdata/...` with `--home-dir /custom/path`), a linked worktree dev run uses +`/.t3/userdata/logs/server.trace.ndjson`, and an implicit dev run outside a linked +worktree uses `~/.t3/dev/logs/server.trace.ndjson`. -Important fields in each record: +Important fields common to both record types: +- `type`: `effect-span` or `otlp-span` - `name`: span name - `traceId`, `spanId`, `parentSpanId`: correlation - `durationMs`: elapsed time - `attributes`: structured context - `events`: embedded logs and custom events -- `exit`: `Success`, `Failure`, or `Interrupted` -The schema lives in `apps/server/src/observability/TraceRecord.ts`. +`effect-span` records also contain `exit` with `Success`, `Failure`, or `Interrupted`. `otlp-span` +records instead carry OTLP resource, scope, and optional status fields. + +The `TraceRecord`, `EffectTraceRecord`, and `OtlpTraceRecord` schemas live in +`packages/shared/src/observability.ts`. ### Metrics @@ -165,30 +179,35 @@ The backend reads observability config at process start. If you change OTLP env The trace file is the fastest way to inspect raw span data. -Resolve the production or explicitly configured trace file once. Runtime state lives under the -base directory's `userdata` folder: +Resolve the path for the launch mode once. Production and explicitly configured homes store runtime +state under the base directory's `userdata` folder: ```bash TRACE_FILE="${T3CODE_HOME:-$HOME/.t3}/userdata/logs/server.trace.ndjson" ``` -Tail it: +A dev server started from a linked worktree defaults to that worktree's local home: ```bash -tail -f "$TRACE_FILE" +TRACE_FILE="$WORKTREE/.t3/userdata/logs/server.trace.ndjson" ``` -For an implicit monorepo dev server, use: +Only an implicit dev run outside a linked worktree uses the shared dev directory: ```bash TRACE_FILE="$HOME/.t3/dev/logs/server.trace.ndjson" +``` + +Tail the selected file: + +```bash tail -f "$TRACE_FILE" ``` Show failed spans: ```bash -jq -c 'select(.exit._tag != "Success") | { +jq -c 'select(.type == "effect-span" and .exit._tag != "Success") | { name, durationMs, exit, @@ -281,10 +300,12 @@ Recommended flow in Grafana: Good first searches: - service name such as `t3-local`, `t3-dev`, or `t3-desktop` -- span names like `sql.execute`, `git.runCommand`, `provider.sendTurn` +- span names like `sendTurn` or a Git operation such as `GitVcsDriver.statusDetails.status` +- Git spans whose `git.operation` attribute identifies the operation - orchestration spans with attributes like `orchestration.command_type` -Once you know traces are arriving, narrower TraceQL queries like `name = "sql.execute"` become useful. +Once you know traces are arriving, narrower TraceQL queries for names such as `sendTurn` or Git +operation names become useful. ### Use Metrics To See Systemic Problems @@ -297,7 +318,6 @@ Good metric families to watch: - `t3_orchestration_command_ack_duration` - `t3_provider_turn_duration` - `t3_git_command_duration` -- `t3_db_query_duration` Counters tell you volume and failure rate: @@ -305,7 +325,6 @@ Counters tell you volume and failure rate: - `t3_orchestration_commands_total` - `t3_provider_turns_total` - `t3_git_commands_total` -- `t3_db_queries_total` Use metrics when the question is: @@ -339,7 +358,7 @@ If you need those later, add client-side instrumentation or a dedicated server f ### "Why did this request fail?" 1. Start with the local NDJSON file. -2. Find spans where `exit._tag != "Success"`. +2. Find `effect-span` records where `exit._tag != "Success"`. 3. Group by `traceId`. 4. Inspect sibling spans and span events. 5. If needed, move to Tempo for the full trace tree. @@ -522,6 +541,8 @@ Current high-value span and metric boundaries include: ### Current Constraints -- logs outside spans are not persisted +- logs outside spans are not persisted in the trace file; SSH-managed launch stdout/stderr is still + captured in its launcher log - metrics are not snapshotted locally -- the old `serverLogPath` still exists in config for compatibility, but the trace file is the persisted artifact that matters +- the old `serverLogPath` still exists in config for compatibility, but the trace file is the primary + structured persisted artifact diff --git a/docs/operations/relay-observability.md b/docs/operations/relay-observability.md index dafad2155af..2bc697b2ef1 100644 --- a/docs/operations/relay-observability.md +++ b/docs/operations/relay-observability.md @@ -1,9 +1,14 @@ # Relay observability -The relay Alchemy stack owns a focused Axiom trace setup: +> For maintainers. Using T3 Code? See [docs/user](../user/). -- `t3-code-relay-traces-prod`, an OpenTelemetry trace dataset for Worker requests -- `t3-code-relay-otel-ingest-prod`, a dataset-scoped ingest token bound to the Worker +The relay Alchemy stack owns a shared Axiom trace setup: + +- `t3-code-relay-traces-prod`, the OpenTelemetry trace dataset shared by the Worker, mobile app, and + first-party relay clients +- `t3-code-relay-otel-ingest-prod`, the dataset-scoped Worker ingest token +- `t3-code-mobile-otel-ingest-prod`, the dataset-scoped mobile ingest token +- `t3-code-relay-client-otel-ingest-prod`, the dataset-scoped first-party relay-client ingest token - `t3-code-relay-recent-spans-prod`, a view of recent request and endpoint spans Alchemy stages append their sanitized stage name to isolate resources, for example @@ -15,8 +20,9 @@ Deploy from `infra/relay` with the normal Alchemy workflow: vp run deploy ``` -Alchemy resolves Axiom deployment credentials through its provider. At runtime, the Worker -receives only the scoped ingest token; it does not receive the diagnostics query token. +Alchemy resolves account-level Axiom deployment credentials through its provider. At runtime, the +Worker receives only its scoped ingest token. Mobile and relay clients use their own separately +provisioned scoped ingest tokens. The Worker emits Effect's built-in HTTP server spans plus endpoint and database child spans. Effect's OpenTelemetry exporter stores semantic HTTP attributes below the `attributes.` prefix. @@ -25,18 +31,23 @@ For example: ```apl ['t3-code-relay-traces-prod'] | where name startswith 'http.server' +| extend endpoint = column_ifexists('attributes.http.route', ''), + customAttributes = column_ifexists('attributes.custom', dynamic({})) | project _time, name, trace_id, duration, ['attributes.http.request.method'], ['attributes.url.path'], - ['attributes.http.response.status_code'] + ['attributes.http.response.status_code'], + endpoint, + relayOperation = customAttributes['relay']['operation'] | order by _time desc | limit 200 ``` -Endpoint failure annotations and other relay-specific attributes are also emitted in the -`attributes.custom` map when present on a span, for example -`['attributes.custom']['relay.endpoint']`. +The provisioned view also reads the endpoint from `attributes.http.route`. Relay-specific span +annotations are stored under `attributes.custom`; `relay.operation` is one of the emitted custom +attributes. Agents should prefer the provisioned view or APL queries for completed incidents instead of -tailing the Cloudflare Worker. Use the read-only query token when scripted access is needed; -keep the ingest token reserved for the Worker. +tailing the Cloudflare Worker. The stack does not provision a separate query token. Responders who +need scripted query access use the authorized account-level `AXIOM_TOKEN` together with +`AXIOM_ORG_ID`; scoped ingest tokens remain write-only credentials for their producers. diff --git a/docs/operations/release.md b/docs/operations/release.md index 9e908550054..9b33e94cc60 100644 --- a/docs/operations/release.md +++ b/docs/operations/release.md @@ -1,5 +1,7 @@ # Release Checklist +> For maintainers. Using T3 Code? See [docs/user](../user/). + This document covers the unified release workflow for stable and nightly desktop releases. ## What the workflow does @@ -30,6 +32,17 @@ This document covers the unified release workflow for stable and nightly desktop - nightly releases are aliased to the `nightly` hosted app channel - Signing is optional and auto-detected per platform from secrets. +## Required release credentials + +The release workflow requires these GitHub Actions secrets in addition to the platform and deployment +credentials documented below: + +- `RELEASE_APP_ID` +- `RELEASE_APP_PRIVATE_KEY` + +The GitHub Release job uses them to mint the token that publishes release assets. Stable releases use +them again in the finalize job, which can commit and push aligned package versions to `main`. + ## T3 Connect relay deployment The relay is a shared control plane versioned separately from client releases. Stable and nightly @@ -148,7 +161,8 @@ One-time Vercel dashboard setup: - manual `workflow_dispatch` with `channel=nightly` - Runs the same desktop quality gates and artifact matrix as the tagged release flow. - Publishes a GitHub prerelease only: - - tag format: `nightly-vX.Y.Z-nightly.YYYYMMDD.` + - current tag format: `vX.Y.Z-nightly.YYYYMMDD.` + - `nightly-v...` is accepted only as a legacy previous-nightly tag - release name includes the short commit SHA - `make_latest` is always `false` - Uses the next stable patch version as the nightly base. For example, `0.0.17` produces nightlies on `0.0.18-nightly.*`. @@ -178,7 +192,9 @@ guidance when those environments are available. ## Desktop auto-update notes -- Runtime updater: `electron-updater` in `apps/desktop/src/main.ts`. +- Updater runtime: `apps/desktop/src/updates/DesktopUpdates.ts`. +- `electron-updater` adapter: `apps/desktop/src/electron/ElectronUpdater.ts`. +- `apps/desktop/src/main.ts` only wires the updater layers into the desktop runtime. - Update UX: - Background checks run on startup delay + interval. - No automatic download or install. @@ -187,9 +203,6 @@ guidance when those environments are available. - Repository slug source: - `T3CODE_DESKTOP_UPDATE_REPOSITORY` (format `owner/repo`), if set. - otherwise `GITHUB_REPOSITORY` from GitHub Actions. -- Temporary private-repo auth workaround: - - set `T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN` (or `GH_TOKEN`) in the desktop app runtime environment. - - the app forwards it as an `Authorization: Bearer ` request header for updater HTTP calls. - Required release assets for updater: - platform installers (`.exe`, `.dmg`, `.AppImage`, plus macOS `.zip` for Squirrel.Mac update payloads) - channel metadata: `latest*.yml` for stable releases, `nightly*.yml` for nightly releases @@ -200,8 +213,9 @@ guidance when those environments are available. ## 0) npm OIDC trusted publishing setup (CLI) -The workflow publishes the CLI with `npm publish` from `apps/server` after bumping -the package version to the release tag version. +The workflow invokes `node apps/server/scripts/cli.ts publish` after aligning package versions. That +script temporarily prepares the `t3` package, then runs `vp pm publish --filter t3 ...` from the +repository root so workspace publish configuration is applied correctly. Checklist: @@ -213,22 +227,27 @@ Checklist: - Environment (if used): match your npm trusted publishing config 3. Ensure npm account and org policies allow trusted publishing for the package. 4. Create release tag `vX.Y.Z` and push; workflow will: - - set `apps/server/package.json` version to `X.Y.Z` + - align the release package versions to `X.Y.Z` - build web + server - - run `npm publish --access public --tag latest` -5. Nightly runs from the same workflow file publish with `npm publish --access public --tag nightly`. + - invoke the CLI publish script with npm dist-tag `latest` +5. Nightly runs invoke the same publish script with npm dist-tag `nightly`. + +## 1) Release validation and unsigned builds -## 1) Dry-run release without signing +There is no dry-run tag path. Pushing any accepted non-nightly tag, including +`v0.0.0-test.1`, classifies the run as the stable channel. It publishes `t3` with npm dist-tag +`latest`, creates a real GitHub Release, aliases the hosted app to `latest.app.t3.codes` and +`app.t3.codes`, and can commit a version bump to `main` in the finalize job. Do not push a test tag +to validate the workflow. -Use this first to validate the release pipeline. +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 +commit a version bump to `main`. Only run it when a real nightly release is acceptable. -1. Confirm no signing secrets are required for this test. -2. Create a test tag: - - `git tag v0.0.0-test.1` - - `git push origin v0.0.0-test.1` -3. Wait for `.github/workflows/release.yml` to finish. -4. Verify the GitHub Release contains all platform artifacts. -5. Download each artifact and sanity-check installation on each OS. +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. ## 2) Apple signing + notarization setup (macOS) @@ -267,7 +286,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](../cloud/t3-connect-clerk.md#desktop-passkeys). +10. Complete the Clerk Native API and AASA setup in [T3 Connect Clerk Setup](../internals/t3-connect.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. diff --git a/docs/project/todo.md b/docs/project/todo.md deleted file mode 100644 index 3d856996d8d..00000000000 --- a/docs/project/todo.md +++ /dev/null @@ -1,13 +0,0 @@ -# TODO - -## Small things - -- [ ] Submitting new messages should scroll to bottom -- [ ] Only show last 10 threads for a given project -- [ ] Thread archiving -- [ ] New projects should go on top -- [ ] Projects should be sorted by latest thread update - -## Bigger things - -- [ ] Queueing messages diff --git a/docs/reference/scripts.md b/docs/reference/scripts.md deleted file mode 100644 index 3927adcfe29..00000000000 --- a/docs/reference/scripts.md +++ /dev/null @@ -1,56 +0,0 @@ -# Scripts - -- `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. -- `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`. -- `vp run dev:web` — Starts just the Vite dev server for the web app. -- Dev commands run from a linked **git worktree** default to that worktree's gitignored `.t3`, even when `T3CODE_HOME` is set, storing state in `/.t3/userdata`. Pass `--home-dir ` 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 ` stores state under `/userdata`; the base directory remains available for caches, worktrees, and other shared data. -- Web dev commands do not auto-open a browser. Open the one-time pairing URL printed by the server so the first browser navigation is authenticated. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional. -- Pass dev-runner flags directly after the root task name, for example: - `vp run dev --home-dir /tmp/t3code-dev` -- `vp run start` — Runs the production server (serves built web app as static files). -- `vp run build` — Builds contracts, web app, and server. -- `vp run typecheck` — Strict TypeScript checks for all packages. -- `vp run test` — Runs workspace tests. -- `node apps/server/scripts/t3-sqlite-state.ts --base-dir ...` — Inspects or seeds an isolated T3 SQLite database; writes create a private backup first. -- `vp run dist:desktop:artifact -- --platform --target --arch ` — Builds a desktop artifact for a specific platform/target/arch. -- `vp run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`. -- `vp run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`. -- `vp run dist:desktop:linux` — Builds a Linux AppImage into `./release`. -- `vp run dist:desktop:win` — Builds a Windows NSIS installer into `./release`. - -## 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. -- Desktop production windows load the bundled UI from `t3code://app/index.html` (not a `127.0.0.1` document URL). - -- 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. - -Worktrees derive a preferred port offset from their path. The runner shifts both ports together when either is occupied or the web port is blocked by browsers, so treat the `[dev-runner]` output as authoritative. - -## Running multiple dev instances - -Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together. - -- Default ports: server `13773`, web `5733` -- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`) -- Example: `T3CODE_DEV_INSTANCE=branch-a vp run dev:desktop` - -If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset. diff --git a/docs/reference/workspace-layout.md b/docs/reference/workspace-layout.md deleted file mode 100644 index be88f2b603b..00000000000 --- a/docs/reference/workspace-layout.md +++ /dev/null @@ -1,7 +0,0 @@ -# Workspace layout - -- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start. -- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket. -- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app. -- `/packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. -- `/packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`, `@t3tools/shared/DrainableWorker`) — no barrel index. diff --git a/docs/user/install.md b/docs/user/install.md new file mode 100644 index 00000000000..fe0b418ca1e --- /dev/null +++ b/docs/user/install.md @@ -0,0 +1,84 @@ +# Install T3 Code + +T3 Code is a web and desktop GUI for running coding agents on your machine. + +## Requirements + +Node.js `^22.16 || ^23.11 || >=24.10` on the machine that runs the T3 Code server. + +At least one provider CLI, installed and authenticated. See [Providers](#providers) below. + +## 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. + +## 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: + +```bash +yay -S t3code-bin +``` + +## Providers + +T3 Code drives provider CLIs; it does not ship them. Install the CLI for each provider you want +to use, then authenticate it. + +| 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` | +| OpenCode | [OpenCode](https://opencode.ai) | `opencode` | `opencode auth login` | + +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`. + +Run the login command on the machine running the T3 Code server, not on the device you browse +from. + +### Binary Discovery + +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 diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index 254aa92c6a0..0e5c7246fd2 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -1,10 +1,14 @@ # Keybindings -T3 Code reads keybindings from: +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. -- `~/.t3/keybindings.json` +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. -The file must be a JSON array of rules: +The file is a JSON array of rules. ```json [ @@ -13,105 +17,54 @@ The file must be a JSON array of rules: ] ``` -See the full schema for more details: [`packages/contracts/src/keybindings.ts`](../../packages/contracts/src/keybindings.ts) +Invalid rules are ignored. An invalid file is ignored entirely, and the server logs a warning. -## Defaults - -```json -[ - { "key": "mod+j", "command": "terminal.toggle" }, - { "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" }, - { "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" }, - { "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" }, - { "key": "mod+shift+j", "command": "preview.toggle" }, - { "key": "mod+r", "command": "preview.refresh", "when": "previewFocus" }, - { "key": "mod+l", "command": "preview.focusUrl", "when": "previewFocus" }, - { "key": "mod+=", "command": "preview.zoomIn", "when": "previewFocus" }, - { "key": "mod+-", "command": "preview.zoomOut", "when": "previewFocus" }, - { "key": "mod+0", "command": "preview.resetZoom", "when": "previewFocus" }, - { "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" }, - { "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" }, - { "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" }, - { "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" }, - { "key": "mod+o", "command": "editor.openFavorite" } -] -``` - -For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](../../apps/server/src/keybindings.ts) - -## Configuration - -### Rule Shape - -Each entry supports: +## Rule Shape - `key` (required): shortcut string, like `mod+j`, `ctrl+k`, `cmd+shift+d` -- `command` (required): action ID +- `command` (required): the command ID to run - `when` (optional): boolean expression controlling when the shortcut is active -Invalid rules are ignored. Invalid config files are ignored. Warnings are logged by the server. +## Key Syntax -### Available Commands +Modifiers: `mod` (`cmd` on macOS, `ctrl` elsewhere), `cmd` / `meta`, `ctrl` / `control`, `shift`, +`alt` / `option`. -- `terminal.toggle`: open/close terminal drawer -- `terminal.split`: split terminal (in focused terminal context by default) -- `terminal.new`: create new terminal (in focused terminal context by default) -- `terminal.close`: close/kill the focused terminal (in focused terminal context by default) -- `preview.toggle`: open/close the in-app browser preview panel (desktop app only) -- `preview.refresh`: reload the active preview tab (in focused preview context by default) -- `preview.focusUrl`: focus the URL input of the preview panel (in focused preview context by default) -- `preview.zoomIn`: zoom the preview viewport in one step (in focused preview context by default) -- `preview.zoomOut`: zoom the preview viewport out one step (in focused preview context by default) -- `preview.resetZoom`: reset the preview zoom to 100% (in focused preview context by default) -- `commandPalette.toggle`: open or close the global command palette -- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state -- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`)) -- `editor.openFavorite`: open current project/worktree in the last-used editor -- `script.{id}.run`: run a project script by id (for example `script.test.run`) +Examples: `mod+j`, `mod+shift+d`, `ctrl+l`, `cmd+k`. -### Key Syntax +## Commands -Supported modifiers: +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`. -- `mod` (`cmd` on macOS, `ctrl` on non-macOS) -- `cmd` / `meta` -- `ctrl` / `control` -- `shift` -- `alt` / `option` - -Examples: +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. -- `mod+j` -- `mod+shift+d` -- `ctrl+l` -- `cmd+k` +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. -### `when` Conditions +## `when` Conditions -Currently available context keys: +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`. -- `terminalFocus` -- `terminalOpen` -- `previewFocus` -- `previewOpen` - -Supported operators: - -- `!` (not) -- `&&` (and) -- `||` (or) -- parentheses: `(` `)` +Operators: `!` (not), `&&` (and), `||` (or), and parentheses. Examples: - `"when": "terminalFocus"` - `"when": "terminalOpen && !terminalFocus"` -- `"when": "terminalFocus || terminalOpen"` - -Unknown condition keys evaluate to `false`. +- `"when": "!terminalFocus"` -### Precedence +## Precedence - Rules are evaluated in array order. - For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins. -- That means precedence is across commands, not only within the same command. +- 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. diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md new file mode 100644 index 00000000000..0ec55a2f6fe --- /dev/null +++ b/docs/user/permission-modes.md @@ -0,0 +1,47 @@ +# Permission Modes + +A permission mode controls how much the agent does on its own and when it stops to ask you. + +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. New threads start in **Full access** unless you pick +something else before sending. + +## The Modes + +**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. + +**Auto-accept edits**: auto-approve edits, ask before other actions. File changes go through +without prompting; commands and anything else still stop for approval. + +**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. + +## Choosing a Mode + +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. The +labels above describe what you get; the exact per-provider translation is internal and may +change. + +Mobile offers the same four modes. It labels the first one **Approve actions** rather than +**Supervised**. diff --git a/docs/providers/claude.md b/docs/user/providers-claude.md similarity index 72% rename from docs/providers/claude.md rename to docs/user/providers-claude.md index bbf72722cf1..79f1211cf40 100644 --- a/docs/providers/claude.md +++ b/docs/user/providers-claude.md @@ -1,6 +1,7 @@ # Claude -This guide is for people who want to use more than one Claude setup in T3 Code. +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). Common reasons: @@ -24,20 +25,24 @@ In T3 Code Settings, your Claude provider can stay like this: ```text Display name: Claude Binary path: claude -Claude HOME path: empty +CLAUDE_CONFIG_DIR path: empty ``` -An empty `Claude HOME path` means T3 Code uses your normal home directory. +An empty `CLAUDE_CONFIG_DIR path` means T3 Code uses Claude Code's normal config directory. + +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. ## I Want Work And Personal Claude Accounts -Use a different Claude home for each account. +Use a different Claude config directory for each account. Example: ```text -default home work account -~/.claude_personal_home personal account +default config dir work account +~/.claude_personal_home personal account ``` ### Set Up The First Account @@ -53,24 +58,27 @@ In T3 Code Settings: ```text Display name: Claude Work Binary path: claude -Claude HOME path: empty +CLAUDE_CONFIG_DIR path: empty ``` ### Set Up The Second Account -Log in with a separate home: +Log in with a separate config directory: ```bash mkdir -p ~/.claude_personal_home -HOME=~/.claude_personal_home claude auth login +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 HOME path: ~/.claude_personal_home +CLAUDE_CONFIG_DIR path: ~/.claude_personal_home ``` Use the email shown in Settings to confirm each provider is using the intended account. Emails are @@ -80,12 +88,12 @@ blurred by default; click the blurred email to reveal it. Usually, no. -T3 Code only offers Claude providers that use the same Claude home for an existing thread. A -different Claude home is treated as a different Claude environment. +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 home directory, so T3 Code keeps separate Claude homes isolated instead of -trying to share part of the state. +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 @@ -102,7 +110,7 @@ Add or edit a Claude provider in T3 Code Settings: ```text Display name: Claude OpenRouter Binary path: claude -Claude HOME path: ~/.claude_openrouter_home +CLAUDE_CONFIG_DIR path: ~/.claude_openrouter_home ``` In that provider's Environment variables section, add: @@ -173,40 +181,18 @@ Claude Code Router is useful when you want a local routing layer with more contr OpenRouter setup. T3 Code does not need a special Claude Code Router provider. Treat the router as a Claude -environment. - -Use this when you want Claude Code Router to decide which upstream model or provider handles Claude -requests. - -High-level flow: - -1. Start Claude Code Router. -2. Add or configure a Claude provider in T3 Code. -3. Put the router's required variables on that provider instance. - -Configure a Claude provider: +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 HOME path: ~/.claude_router_home -``` - -Then copy the variables that `ccr activate` would export into the provider's Environment variables -section. Mark tokens and API keys as sensitive. - -If you want the router-backed setup to stay separate from your normal Claude account, create and log -in with a dedicated home first: - -```bash -mkdir -p ~/.claude_router_home -ccr start -ccr activate -HOME=~/.claude_router_home claude auth login +CLAUDE_CONFIG_DIR path: ~/.claude_router_home ``` -Claude Code Router's setup can change over time. Use its upstream README for the current install and -configuration steps: . +Follow the upstream project's README for the router's own install, startup, and configuration +steps: . ## I Want Different Claude Settings, Not A Different Account @@ -218,7 +204,7 @@ Examples: - "Claude Router" - "Claude Experimental" -If the preset needs different Claude files, give it a different `Claude HOME path`. If it needs +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`. diff --git a/docs/providers/codex.md b/docs/user/providers-codex.md similarity index 96% rename from docs/providers/codex.md rename to docs/user/providers-codex.md index cc9e84e484a..7c5ea91f043 100644 --- a/docs/providers/codex.md +++ b/docs/user/providers-codex.md @@ -1,6 +1,7 @@ # Codex -This guide is for people who want to use more than one Codex account in T3 Code. +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). Common reasons: diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index d6ff00bee1f..3881c5be3a4 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -14,14 +14,15 @@ That gives you: ## Enabling Network Access -There are two ways to expose your server for remote connections: from the desktop app or from the CLI. +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 **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces. +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. @@ -48,10 +49,10 @@ Depending on your Tailscale setup, this may include: - 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 disabled until the app verifies that the URL reaches this -backend. Use **Setup** on the Tailscale HTTPS row to opt in. 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. +`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. @@ -96,10 +97,8 @@ By default this configures Tailscale Serve on HTTPS port 443 and advertises npx t3 serve --tailscale-serve --tailscale-serve-port 8443 ``` -> Note -> The GUIs do not currently support adding projects on remote environments. -> For now, use `t3 project ...` on the server machine instead. -> Full GUI support for remote project management is coming soon. +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. ### Option 3: Desktop-Managed SSH Launch @@ -125,16 +124,10 @@ The remote host must have a compatible Node.js runtime. T3 Code uses the server ^22.16 || ^23.11 || >=24.10 ``` -During SSH launch, T3 Code first checks whether `node` is already available on `PATH`. If it is missing, the launcher tries common non-interactive shell locations and version-manager shims/activation hooks: - -- `~/.local/bin`, `~/bin`, `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/bin` -- Volta via `~/.volta/bin` -- asdf via `~/.asdf/shims`, `~/.asdf/bin`, or `~/.asdf/asdf.sh` -- mise via `~/.local/share/mise/shims`, `~/.mise/shims`, or `mise activate sh` -- fnm via `fnm env --use-on-cd --shell sh` or `fnm env --shell sh` -- nodenv via `~/.nodenv/bin`, `~/.nodenv/shims`, or `nodenv init -` -- nvm via `$NVM_DIR/nvm.sh`, then `nvm use default`, `nvm use node`, or `nvm use --lts` -- installed nvm versions under `$NVM_DIR/versions/node/*/bin` +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 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: @@ -148,7 +141,7 @@ If that does not print a compatible Node version, configure your version manager nvm alias default 24 ``` -With mise/asdf/fnm/nodenv, make sure the tool's shim directory is installed and points at a Node version satisfying the range above. +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. 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. @@ -160,7 +153,7 @@ be able to update and reconnect the server for you, or it may ask you to update run a copied command on the server machine. Finish active work before updating because the server restarts briefly. For step-by-step guidance, -see [Keeping T3 Code in Sync](./server-updates.md). +see [Keeping T3 Code in Sync](./updating.md). 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). diff --git a/docs/integrations/source-control-providers.md b/docs/user/source-control.md similarity index 74% rename from docs/integrations/source-control-providers.md rename to docs/user/source-control.md index c496d5516a6..6d81d2b33ab 100644 --- a/docs/integrations/source-control-providers.md +++ b/docs/user/source-control.md @@ -1,6 +1,6 @@ # Source Control Integrations -T3 Code connects directly to your Git hosting provider so you can create pull requests, review code, and manage repositories without leaving your editor. Work stays in flow—no more jumping between browser tabs and terminal windows. +T3 Code connects to your Git hosting provider so you can create pull requests, review code, and manage repositories without leaving the app. ## Supported Providers @@ -24,16 +24,16 @@ T3 Code works with the platforms your team already uses: **Publish local projects to the cloud** - 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—all in one flow -- Perfect for turning a weekend prototype into a real project +- 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. ### Manage Code Reviews Without Context Switching **Create pull requests while you work** -- Push a branch and create a pull request from the Git panel +- 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 -- Supports GitHub Pull Requests, GitLab Merge Requests, and Bitbucket Pull Requests +- Supports GitHub Pull Requests, GitLab Merge Requests, Bitbucket Pull Requests, and Azure DevOps Pull Requests **Stay on top of open reviews** @@ -65,7 +65,7 @@ Run a quick **Rescan** after setting up a new machine or changing credentials. ``` 3. Open **Settings → Source Control** in T3 Code and verify GitHub shows as authenticated -That's it—you can now clone, publish, and create pull requests. +You can now clone, publish, and create pull requests. ### For GitLab @@ -81,15 +81,25 @@ That's it—you can now clone, publish, and create pull requests. ### For Bitbucket -Bitbucket uses API tokens instead of a CLI tool: +Bitbucket uses tokens instead of a CLI tool. Two options, both set as environment variables on the +machine running T3 Code. -1. Create an API token in your Atlassian account with read/write access to pull requests and repositories -2. Add these environment variables to the environment running T3 Code: - ```bash - export T3CODE_BITBUCKET_EMAIL="you@example.com" - export T3CODE_BITBUCKET_API_TOKEN="your-token" - ``` -3. Restart T3 Code and verify the connection in **Source Control settings** +Recommended, a Bitbucket access token: + +```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: + +```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**. ### For Azure DevOps @@ -124,4 +134,4 @@ Bitbucket uses API tokens instead of a CLI tool: - [GitHub CLI](https://cli.github.com/) - [GitLab CLI](https://gitlab.com/gitlab-org/cli) -- [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/) +- [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/) diff --git a/docs/user/server-updates.md b/docs/user/updating.md similarity index 83% rename from docs/user/server-updates.md rename to docs/user/updating.md index 6a8e33977b7..37ae362fb0e 100644 --- a/docs/user/server-updates.md +++ b/docs/user/updating.md @@ -31,12 +31,20 @@ The update does not remove saved threads, settings, or project files. The available action depends on how that server was started. T3 Code does not update connected servers silently in the background. -If the server uses the T3 Code background service, you can also update it directly on the host: +**Copy update command** gives you `npx t3@`, 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: ```sh -npx t3@latest service update +npx t3@ 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. + See [Running T3 Code in the Background](./background-service.md) for install, status, and removal commands. diff --git a/infra/relay/README.md b/infra/relay/README.md index 114d5e9b07f..0085c9c5b6b 100644 --- a/infra/relay/README.md +++ b/infra/relay/README.md @@ -1,7 +1,7 @@ # T3 Connect Relay -> [!WARNING] -> T3 Connect is currently in private beta. Join the waitlist in the app under Settings > T3 Connect. +> [!NOTE] +> Sign in to T3 Connect from the app under Settings > Connections. The relay is the hosted control plane for T3 Connect. It helps clients discover and connect to remote environments, manages the cloud-side records needed for those connections, and delivers @@ -9,7 +9,7 @@ optional mobile notifications and Live Activities. The relay is intentionally not in the hot path for normal T3 Code traffic. After a client connects, regular API and WebSocket traffic goes directly between that client and the selected environment. -See the [T3 Connect architecture overview](../../docs/cloud/t3-code-connect-auth-flow.html) for the larger system +See the [T3 Connect architecture overview](../../docs/internals/t3-code-connect-auth-flow.html) for the larger system design. ## Responsibilities @@ -25,7 +25,7 @@ The relay currently owns: - Persisting relay state and exposing relay-specific traces for diagnostics. The environment server and relay have separate credentials and trust boundaries. Read -[Environment Authentication Profile](../../docs/environment-auth.md) before changing token, +[Environment Authentication Profile](../../docs/internals/environment-auth.md) before changing token, credential, or authorization behavior. ## Code Map @@ -159,8 +159,8 @@ and hosted web builds. See: -- [T3 Connect Clerk Setup](../../docs/cloud/t3-connect-clerk.md) for Clerk keys, JWT templates, and waitlist +- [T3 Connect Clerk Setup](../../docs/internals/t3-connect.md) for Clerk keys, JWT templates, and sign-up restrictions setup. -- [Relay Observability](../../docs/relay-observability.md) for deployment tracing and diagnostics. -- [T3 Connect Architecture Overview](../../docs/cloud/t3-code-connect-auth-flow.html) for the full link, +- [Relay Observability](../../docs/operations/relay-observability.md) for deployment tracing and diagnostics. +- [T3 Connect Architecture Overview](../../docs/internals/t3-code-connect-auth-flow.html) for the full link, connect, endpoint, and notification flows.