- Canonicalize provider runtime tool data and usage snapshots
- Update work log extraction and user input contracts for the new schema
- Add coverage for the revised lifecycle and ingestion shapes
- Normalize provider token-usage events into thread activities
- Add a compact context window meter to chat
- Handle context compaction markers in the timeline
- ensure `chat.new` creates a fresh draft after a promoted draft thread
- enforce terminal cap per split group (4) while allowing additional terminal groups
- refine sidebar row selected/active styling via shared class-name logic and tests
* feat(web): add shift-click multi-select for sidebar threads
Add support for selecting multiple threads in the sidebar via
Cmd/Ctrl+Click (toggle) and Shift+Click (range select), with
bulk context menu actions for Delete and Mark Unread.
- New threadSelectionStore (Zustand) for ephemeral selection state
with anchor-based range selection and no-op guards
- Platform-aware modifier detection (Cmd on Mac, Ctrl elsewhere)
matching existing isMacPlatform pattern in terminal-links
- Extracted deleteThread helper from handleThreadContextMenu for
reuse by bulk delete, with deletedThreadIds set for correct
fallback navigation during batch operations
- Selected threads share the active thread highlight style
- Escape key clears selection; plain click clears and navigates
- Right-click on selected thread shows bulk menu; right-click on
unselected thread clears selection and shows single-thread menu
- 22 unit tests covering toggle, range select, clear, remove,
and edge cases (cross-project fallback, anchor stability)
* fix(web): filter deleted threads from worktree orphan check during bulk delete
When bulk-deleting threads that share a worktree, the stale threads
closure caused getOrphanedWorktreePathForThread to see the other
threads-being-deleted as still alive, suppressing the orphaned
worktree cleanup prompt. Filter out deletedThreadIds (keeping the
current thread) so the check correctly identifies worktrees that
will have no surviving references.
* fix(web): fix shift-click range selection, distinct selection styling, and deselect on click away
* Preserve thread multi-select on safe sidebar control clicks
- avoid clearing selection on mousedown for thread items and marked safe controls
- centralize the selection-safe selector and add logic tests for clear vs preserve behavior
- simplify thread selection store typing by merging state/actions interface
---------
Co-authored-by: Julius Marminge <[email protected]>
- Replace the inline composer PR menu with a dedicated `PullRequestThreadDialog`
- Remove `/checkout-pr` from composer slash-command parsing and tests
- Fix branch selector virtualization sizing for the checkout-PR row
- Change local PR worktree branch format from `pr/<number>-<head>` to `t3code/pr-<number>/<head>`
- Update GitManager tests to assert the new branch naming convention
- Treat remotes that only differ by trailing slash after `.git` as the same remote
- Add a GitCore regression test for trailing-slash remote reuse
- Refactor `GitHubCli` tests to `@effect/vitest` layer-based effect tests with reset cleanup
- create a unique local branch name for cross-repo PR worktrees (`pr/<number>-<head>`)
- fetch/set upstream against that local branch instead of overwriting local `main`
- add regression tests for fork PRs where head branch is `main`
- Restore/set upstream tracking when preparing local and reused PR worktrees
- Derive fork `owner/repo` from PR URL when GitHub omits `headRepositoryNameWithOwner`
- Expand GitManager tests to cover local mode, URL-derived fork identity, and reused worktree upstream recovery
- move branch filtering logic into `BranchToolbarBranchSelector`
- remove unused `filterBranchPickerItems` helper and related tests
- keep create-branch option pinned while filtering by query
- add GitCore helpers to ensure remotes, fetch remote branches, and set upstreams
- extend GitHub CLI parsing to include cross-repo PR metadata and repo clone URLs
- update GitManager flow and tests to materialize fork heads and keep tracking on fork remotes
- add `resolveBranchSelectionTarget` to unify checkout cwd/worktree decisions
- reuse existing worktrees when available, including switching back to main repo
- update branch selector to use shared logic and add targeted unit tests
- Add shared branch picker filtering logic and tests, including PR-reference-only results
- Improve branch selector UX/perf with deferred query filtering, conditional virtualization, and status-based current branch resolution
- Only expose and handle `/checkout-pr` for local draft threads in chat and toolbar UI
- Add git APIs to resolve PR refs and prepare PR thread workspaces
- Support fetching PR head refs into local branches and reusing existing worktrees
- Wire new websocket/contracts/web composer flows for PR-based thread creation
- Expand server/web/contracts tests for PR routing and branch/worktree behavior
- Replace manual UUID byte formatting fallback in `apps/web/src/lib/utils.ts`
- Use `Effect.runSync(Random.nextUUIDv4)` when `crypto.randomUUID` is unavailable
Replace direct crypto.randomUUID() calls with a randomUUID() helper in
utils.ts that falls back to crypto.getRandomValues() when the browser
is not in a secure context (e.g. plain HTTP on a non-localhost address).
Signed-off-by: Hiram Chirino <[email protected]>
Fixes: #769
* Updated wording for label from 'Commit, Create & Push PR' to 'Commit, Create & PR' to allow for it to fit within the current UI size constraints.
wording change
- Map Codex `error` notifications with `willRetry: true` to `runtime.warning`
- Keep active turns/sessions running during reconnect warnings
- Add adapter and ingestion tests for retry-warning behavior
- Keep long plan cards collapsed with lightweight preview text by default
- Render full plan markdown only after explicit expand to reduce thread open slowness
- Add tests for preview/strip helpers and browser coverage for expand behavior
- prevent accidental project toggles after drag operations
- switch project rows to Collapsible for stable expand/collapse animation
- add optional hidden scrollbar mode to ScrollArea and apply it in SidebarContent
- wire project list to dnd-kit sortable with vertical drag constraints
- prevent accidental expand/collapse clicks during drag gestures
- update store logic/tests and add dnd-kit dependencies
- Replace manual timeout debounce logic with `@tanstack/react-pacer`'s `Debouncer`
- Persist updates via `maybeExecute` to reduce localStorage write thrashing
- Flush pending persistence on `beforeunload` to avoid losing recent state
The ProviderHealth layer blocked server startup with two sequential CLI
spawns (codex --version + codex login status), each with a 4-second
timeout, delaying startup by up to 8 seconds.
Run health checks in the background via Effect.runPromise so the layer
resolves immediately with a placeholder status. Add an onReady callback
to ProviderHealthShape so wsServer can push the resolved statuses to
connected clients once checks complete, preventing early-connecting
clients from showing "Checking..." indefinitely.
During active sessions, every domain event triggered a full
syncSnapshot (IPC fetch + state rebuild + React re-render cascade) and
sometimes a provider query invalidation. Events fire in rapid bursts
during AI turns.
Replace per-event processing with a throttle-first pattern: schedule a
flush on the first event, absorb subsequent events within a 100ms
window, then sync once. Provider query invalidation is batched via a
flag. Since syncSnapshot fetches the complete snapshot, no events are
lost by skipping intermediate syncs.
The useStore subscriber called persistState on every state mutation,
triggering JSON.stringify + localStorage.setItem synchronously. It also
ran 8 localStorage.removeItem calls for legacy keys on every fire.
Wrap the subscriber with a 500ms debounce so rapid state changes batch
into a single write. Move legacy key cleanup behind a one-time flag so
it runs only once per page load. Add a beforeunload handler to flush
the final state.
Every keystroke triggered full JSON serialization of all composer drafts
(including base64 image attachments) and a synchronous localStorage
write. At normal typing speed this caused 5+ writes/sec, blocking the
main thread and creating noticeable input lag.
Wrap the Zustand persist storage with a 300ms debounce. In-memory state
updates remain immediate; only the serialization and storage write are
deferred. A beforeunload handler flushes pending writes to prevent data
loss. The removeItem method cancels any pending setItem to avoid
resurrecting cleared drafts.
Adds unit tests for the DebouncedStorage utility covering debounce
timing, rapid writes, removeItem cancellation, flush, and edge cases.
- Measure composer width from the form element in initial and resize paths
- Avoid relying on ResizeObserver contentRect width for compact footer layout decisions
- Replace `SIDEBAR_INSET_BASE_CLASSNAME` with an inline class string in `sidebar.tsx`
- Delete the now-unused `sidebar.logic.ts` helper and its focused unit test
- add shared footer layout breakpoint helper with tests
- switch chat composer footer to compact menu when width is constrained
- preserve plan sidebar toggle behavior while consolidating footer actions
- add `min-w-0` to chat/flex containers to prevent composer/sidebar overflow
- move `BranchToolbar` into the chat column so layout stays aligned with plan sidebar
- extract sidebar inset base classes to shared logic and add a regression test for `min-w-0`
- derive toast indices and Y offsets from the filtered visible toasts
- pass frontmost height and per-toast layout vars to the viewport/item styles
- add unit tests for visible toast layout calculations and height normalization
- delete `shouldShowFastTierIcon` and its test
- remove Zap icon badges from slash model commands and provider model picker
- simplify related ChatView props and memo dependencies
- Drop `serviceTier` from orchestration/provider contracts and server dispatch paths
- Remove service-tier app setting/UI and related resolver logic
- Keep fast badge behavior tied to explicit fast-mode boolean
- add "Plan Ready" sidebar status when a plan-mode turn is settled with a proposed plan
- update sidebar logic tests to cover the new status and expanded thread inputs
- add `Sidebar.logic.ts` to centralize thread status pill resolution
- show `Awaiting Input` when plan mode is blocked on user responses
- add unit tests for unseen completion and status-priority behavior
- prevent plan collapse/expand clicks from triggering chat scroll anchoring
- Use a toast error for add-project failures during immediate folder browse
- Keep inline add-project error state for non-immediate flows
- Include `shouldBrowseForProjectImmediately` in callback dependencies
- add `shouldOpenProjectFolderPickerImmediately` to centralize Sidebar behavior
- trigger folder browse directly when adding a project in desktop Electron
- keep manual path entry for mobile layouts and non-Electron, with tests for all cases
the rail's 16px hit area at z-20 sits right where the native os scrollbar
lives when the sidebar is in offcanvas mode and collapsed. this causes clicks
and drags on the scrollbar to toggle the sidebar instead on windows and linux.
scoping pointer-events-none to [data-collapsible=offcanvas][data-state=collapsed]
fixes the interception without affecting icon mode where the rail needs to stay
clickable.
Electron derives the userData path from productName in package.json,
which produces directories with spaces and parentheses on all platforms
(e.g. ~/.config/T3 Code (Alpha) on Linux). This is hostile to shell
usage and violates Linux XDG naming conventions.
Override the userData path via app.setPath() before the ready event to
use a clean lowercase name (t3code). If the legacy directory already
exists it is used as-is so existing users keep their Chromium profile
data (localStorage, cookies, sessions, cache).
This follows the same pattern VS Code uses — keeping productName for
display purposes while explicitly setting the data directory path.
Closes#578
`rawSearch` is already the output of `parseDiffRouteSearch` via the
`useSearch` select transform. The `useMemo` at line 760 re-parsed it
through the same function with an unsafe `as Record<string, unknown>`
cast, producing an identical result. Use `rawSearch` directly instead.
When the persisted state key was bumped from v7 to v8 in 689dda59,
the v7 key was not added to LEGACY_PERSISTED_STATE_KEYS. Users who
ran the app during the ~3-week v7 window retain a stale
`t3code:renderer-state:v7` entry in localStorage that is never
cleaned up.
The terminal RPC test used raw waitForMessage to receive the expected
terminal.event push, but a server.configUpdated push from the
keybindings file watcher can arrive first depending on OS timing.
Replace with the existing waitForPush helper that filters by channel.
* Add checkout and Node setup to release updater publish job
- Ensure the updater publish job checks out the target ref
- Initialize Node using the repository's package.json version file before downloading artifacts
* Fix release finalize lockfile refresh
- Ensure the updater publish job checks out the target ref
- Initialize Node using the repository's package.json version file before downloading artifacts
* fix(scripts): enable shell mode on Windows for .cmd shim resolution
On Windows, tools like `bun`, `npm`, `turbo`, and `bunx` are installed
as `.cmd` shims. Node's `child_process.spawn` cannot resolve these
without `shell: true`, causing `PlatformError: NotFound` on fresh
builds where there is no Turbo cache.
Add `shell: process.platform === "win32"` to all ChildProcess.make
calls in cli.ts, dev-runner.ts, and build-desktop-artifact.ts.
Closes#474
* docs: add comments explaining Windows shell spawn requirement
* docs: add shell spawn comments to remaining call sites
Adjust the Electron sidebar header to properly center the T3 wordmark
with the native window controls. The logo was sitting ~2px too low and
~8px too close to the traffic lights.
- Reduce wordmark container top margin from mt-2 (8px) to mt-1.5 (6px)
- Increase Electron header left padding from 82px to 90px for proper
traffic light clearance
- Match the desktop update button margin to stay aligned
Closes#564
Wire up Electron's context-menu event on webContents to surface
dictionary suggestions for misspelled words. Standard edit actions
(Cut, Copy, Paste, Select All) appear in all context menus.
Related to #473
The thread error banner had no way to be dismissed. Users hitting
unrecoverable errors (e.g. missing gh CLI during PR creation) were
stuck with a persistent error banner and no way to clear it.
Add a dismiss (X) button to ThreadErrorBanner using the existing
AlertAction component, wired to clear the thread error via
setThreadError(id, null).
Closes#496
* Add PR template with contribution notice and review checklist
- Add `.github/pull_request_template.md`
- Set expectations that external PRs may not be reviewed or merged
- Require clear change rationale plus UI before/after media when applicable
* Add contribution policy notice and link detailed guidelines
- add CONTRIBUTING.md with clear expectations for external PRs
- update README to direct would-be contributors to CONTRIBUTING.md first
When T3 Code web mode is accessed via HTTPS (e.g. through a reverse proxy
or Tailscale Serve), the WebSocket connection must use wss:// instead of
ws://. Browsers block mixed content — an insecure ws:// connection
initiated from an HTTPS page.
Fix: derive the WebSocket protocol from window.location.protocol.
Co-authored-by: PatrickBauer <[email protected]>
- Drop the redundant static bullet before the working status text in `MessagesTimeline`
- Keep the animated dots indicator as the sole working-state visual cue
* refactor(contracts): export ProviderStartOptions schema
* feat(contracts): add providerOptions to ThreadTurnStartCommand
* feat(web): send codex binary/home path settings to server
* feat(server): thread providerOptions through to session startup
* fix(contracts): define ProviderStartOptions inline to avoid circular dep
The import from provider.ts caused a ReferenceError at runtime because
of module initialization order in the bundled output.
* fix(server): preserve providerOptions across runtime mode changes and session recovery
Runtime mode toggles and server restarts silently dropped the custom
codex binary/home path, falling back to the default binary. Cache
providerOptions per thread in ProviderCommandReactor and persist it in
the session binding's runtimePayload so recovery can restore it.
Closes#486
Add a pre-flight version check that runs `codex --version` and blocks
session startup with a clear upgrade message when the installed CLI is
below v0.37.0. The check runs both synchronously at session start
(codexAppServerManager) and during provider health probes
(ProviderHealth), so users get fast feedback in the UI.
Introduces `codexCliVersion.ts` with semver parsing, comparison, and
formatting helpers shared by both call sites.
* Handle prerelease tags when publishing GitHub releases
- Derive `is_prerelease` and `make_latest` from the version format in preflight
- Mark suffixed versions (for example `1.2.3-alpha.1`) as prereleases
- Keep only plain `X.Y.Z` releases marked as latest
- Document prerelease/latest behavior in `docs/release.md`
* Force desktop auto-updates to stable latest channel
- set Electron updater channel to `latest`
- disable prerelease and downgrade updates regardless of app version
* fix: handle turbo shutdown in dev runner
* refactor: rely on effect child process shutdown
* refactor: inline turbo shutdown timeout
* add back sigint sigterm sighup handling
* refactor: tighten turbo signal forwarding
* refactor: inline dev runner errors
* fix: use detached false instead of manual signal forwarding
Effect defaults to detached: true on non-Windows, putting turbo in a
new process group where terminal signals (Ctrl+C) never reach it.
Setting detached: false keeps turbo in the same group, eliminating
the need for ~130 lines of manual signal forwarding.
* Update scripts/dev-runner.ts
Co-authored-by: Copilot <[email protected]>
---------
Co-authored-by: Copilot <[email protected]>
The app crashed when displaying code blocks with language identifiers
not bundled in Shiki (e.g. "env" from .env file edits). The language
string was cast to SupportedLanguages without validation, causing
resolveLanguage to throw an unhandled error that killed the thread.
Three layers of defense added:
- getHighlighterPromise falls back to "text" when Shiki rejects
- codeToHtml call wrapped in try/catch with "text" fallback
- CodeHighlightErrorBoundary prevents component tree crashes
Closes#266
Co-authored-by: Ahmed R <[email protected]>
* Guard non-git projects and improve send and diff UX
- Skip checkpoint capture/revert and turn diff ingestion for non-git workspaces
- Normalize project workspace roots and return clearer request/error messages
- Show "No Git" state in chat/diff UI and enrich work log with commands/files
- Track send start time so working status shows elapsed duration consistently
* Format active working timer in concise h/m/s units
- add `formatWorkingTimer` for human-friendly durations in ChatView
- show active "Working for" time as `0s`, `1m 5s`, or `2h 3m` instead of ms
* more cleanup
* Fix active work timing and use temp git workspaces in tests
- derive active work start from unsettled turn state instead of always latest turn
- update chat view to use shared deriveActiveWorkStartedAt helper
- make server/ws tests create temporary workspace roots with .git for project creation
- switch quickstart command from `npx t3@alpha` to `npx t3`
- fix wording in desktop app sentence
- replace "Discord link coming soon" with invite link
- add Shift+Tab keyboard handling in composer to switch chat/plan modes
- refactor mode toggle into shared callback used by hotkey and button
- add browser test to verify toggling only works when composer is focused
* marketing site
* redesign 1
* more
* Redesign marketing site: port to Astro, minimal dark homepage
Replace the React/Vite marketing site with a single static Astro page.
Dark theme matching the app aesthetic, featuring the production glossy
T3 icon, app screenshot, and a clean minimal layout.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* Fix GitHub link to pingdotgg/t3code
Co-Authored-By: Claude Opus 4.6 <[email protected]>
---------
Co-authored-by: Claude Opus 4.6 <[email protected]>
* Stage production icons for desktop builds and publish
- add shared brand asset paths and a Windows .ico asset
- stage Linux/Windows icons in desktop artifact builds
- override and restore publish favicon during server CLI publish
* 'blip'
* Fix PR review issues for publish icon staging
* Refactor brand assets and harden Windows desktop build setup
* Apply remaining server orchestration updates
* Fix production mac icon asset
Co-authored-by: Theo Browne <[email protected]>
---------
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
- Treat pending approvals as a dedicated composer state
- Disable prompt input and hide command menu/image chips while approval is active
- Move approval decision buttons into footer actions and simplify the header panel
- Pass resolved `openInCwd` from ChatView into OpenInPicker
- Fall back to project `cwd` when draft thread has no `worktreePath`
- Add browser test covering Open action for draft-only snapshot
- add `collectActiveTerminalThreadIds` to keep non-deleted server threads plus local draft threads
- use helper in root event router before orphan terminal state removal
- add unit tests for retained and deleted thread behavior
- Wrap test in `it.layer(NodeServices.layer)` for Node service provisioning
- Replace manual temp dir setup/cleanup with scoped `FileSystem.makeTempDirectoryScoped`
- Keep multi-batch flush assertions while simplifying test runtime wiring
- move `AnalyticsServiceLayerLive` from CLI runtime setup into `main` server layer
- persist telemetry `anonymous-id` under configured `stateDir` instead of home directory
- add `FetchHttpClient.layer` to `main.test.ts` test layer wiring
- introduce `AnalyticsService` with buffered PostHog batch flush
- add hashed telemetry identifier from Codex account id or anonymous local id
- record provider session/turn lifecycle events and flush on stop-all
- wire telemetry layer into server runtime and update tests with no-op analytics
- Send `collaborationMode` for both `default` and `plan` interactions
- Add default-mode developer instructions and preserve plan-mode behavior
- Update server/web tests for default collaboration mode and model constant usage
- Keep Claude Code and Cursor in provider list as disabled options
- Remove unused Claude agent SDK dependency from server
- Delete stale plan-mode deep-dive doc
- Replace ad-hoc `effort` handling with provider `modelOptions` across decider/reactor/adapters
- Map Codex `reasoningEffort` and `fastMode` to turn/session params (`effort`, `serviceTier`)
- Persist runtime/interaction/model selections from composer and sync them before sending turns
- Move model normalization/helpers into `@t3tools/shared/model` with updated contracts/tests
- Add `thread.proposed-plan-upserted` orchestration flow from ingestion through decider/projector
- Store proposed plans in a dedicated projection table and include them in snapshot queries
- Update provider runtime/web handling and tests to use proposed plans instead of assistant message wrappers
- Replace provider session-id centric plumbing with thread-id based runtime handling across server orchestration and provider layers
- Update persistence repositories/migrations and contracts for threadless runtime semantics
- Refresh integration/unit tests and web session/store types to match the new runtime model
- add structured lifecycle logs for Codex thread open/resume and provider session restarts
- introduce persistent server file logging layer and tighten WebSocket server startup/finalizer ordering
- preserve env-based boolean overrides in dev runner and stop forcing WS event logging in dev
- enrich provider session listing from persisted bindings and fix Claude rate-limit/task-id event mapping
- update orchestration and dev-runner tests for runtime-mode restart and env-flag behavior
- Add `thread.runtime-mode.set` -> `thread.runtime-mode-set` flow in decider/reactors/projectors
- Persist runtime mode on thread/session projections with new DB migrations
- Update provider and Codex integration tests to verify thread continuity across mode changes
Co-authored-by: codex <[email protected]>
- Define Cursor operating mode as binary `default | plan`
- Document mapping for `cursor/ask_question`, `cursor/create_plan`, and `cursor/update_todos`
- Update capability and fallback guidance based on docs plus probe evidence
- Reframe doc into a provider-agnostic implementation plan for Codex, Claude, and Cursor
- Define canonical mode, plan, and structured user-input models plus capability-driven UI behavior
- Add concrete orchestration, adapter, frontend, and test work items for rollout
- Map runtime session state transitions to orchestration session status
- Persist error reasons from `session.state.changed` error events
- Add coverage for waiting/error/stopped/ready transition handling
- add per-provider custom model settings/options in web settings and chat picker
- preserve Codex request type on `serverRequest/resolved` events
- validate empty Cursor prompts before turn start and keep tool-call item types consistent
- add tests for new adapter and model-settings behavior
- add PR event review checklist document
- map canonical approval request types to `requestKind` across ingestion and web pending approvals
- auto-approve Cursor permission requests when approval policy is `never`
- persist per-thread composer provider selection in draft store and use it in ChatView
- disable Cursor traits picker while model selection is locked
- Add provider capability plumbing for `sessionModelSwitch` and use it in session/turn routing
- Keep Cursor sessions stable when in-session model switching is unsupported
- Ingest canonical runtime events (`content.delta`, `item.*`, `request.*`) with legacy-shape compatibility
- Only include `effort` in start command when a value is selected
- Persist effort selection via composer draft state and hide picker when unavailable
- Add optional `provider` to `ClientThreadTurnStartCommand`
- Simplify thread model fallback selection in `ChatView`
- migrate Claude/Codex/registry adapters to canonical runtime event types and payload shapes
- add Cursor layer adapter plus tests and wire it through server layers
- update provider contracts/runtime schemas and related adapter tests
- Replace global reasoning constants with provider-scoped effort options/defaults
- Update ChatView to use Codex-specific reasoning effort types and default lookup
- Expand model contract tests for provider-specific reasoning effort behavior
- Restructure runtime events around a shared base plus typed payloads
- Add runtime-branded IDs and new event types (plan, item, request, user-input)
- Remove legacy canonical event names from docs and add schema decode/rejection tests
- Add Cursor ACP raw source types to `RuntimeEventRaw.source`
- Define canonical mappings for ACP lifecycle, updates, permissions, and errors
- Expand cross-provider equivalence table to include Cursor ACP and renumber sections
- Switch plan from `agent -p` stream-json to `agent acp` JSON-RPC transport
- Document ACP session, permission, event-mapping, and interrupt/recovery behavior
- Update implementation phases, tests, and delivery checklist for ACP-first design
- add `scripts/cursor-acp-probe.mjs` to run ACP protocol probing scenarios
- update `package.json` scripts for probe execution
- include generated probe summaries/transcripts under `.tmp/acp-probe/`
- Accept `cursor` as a first-class provider in orchestration, persistence, and session directory flows
- Update model/provider inference and normalization to handle Cursor model aliases
- Revamp chat provider/model picker with Cursor-specific trait controls and add coverage in tests
- add per-session `sessionSequence` on provider runtime events and persist activity `sequence`
- migrate `projection_thread_activities` with nullable `sequence` column + index
- sort server/web activity projections by sequence fallback to timestamp/id
- allow provider sessions/turns to start before a real threadId is emitted
- Default Claude sessions to bypass permissions when approval policy is `never`, while preserving explicit `permissionMode`
- Hide/send reasoning effort only for providers that support it in ChatView
- Add coverage for Claude permission-mode derivation and precedence, and update runtime event model docs
- Preserve active turn state when `session.started`/`thread.started` arrive mid-turn
- Emit `message.delta` from assistant text when stream deltas are missing, then complete the message
- Add Claude native SDK NDJSON observability logging and wire its log path in server layers
- Expand ingestion/adapter tests to cover mid-turn lifecycle and delta fallback behavior
- Do not pass `resumeCursor` when restarting a session after changing providers
- Treat synthetic Claude thread IDs (`claude-thread-*`) as unscoped during runtime ingestion
- Add tests covering provider-switch restart behavior and Claude turn lifecycle acceptance
- Stop synthesizing `resume` from generated thread IDs
- Persist resume session ID from query messages when available
- Validate resume/sessionId values as UUIDs before reuse
- Add tests for valid UUID resume passthrough and no synthesized resume
- Replace manual prompt async iterator with `Stream.fromQueue(...).toAsyncIterable`
- Use `Ref` for shared session context in tool approval callbacks
- Simplify timestamp/ID generation and close sessions via queue shutdown
- add `@anthropic-ai/claude-agent-sdk` dependency for `apps/server`
- replace placeholder Claude adapter with live session/query/event handling
- add comprehensive adapter tests for runtime events, approvals, resume, rollback, and model overrides
- introduce `ClaudeCodeAdapter` service and live layer wiring
- map runtime/session/request failures into provider adapter error types
- add coverage for validation, session-not-found mapping, lifecycle forwarding, and event passthrough
- Add per-provider model options, defaults, and slug aliases
- Add provider-aware model normalization/resolution helpers
- Preserve Codex-only constants/functions for backward compatibility
- Extend tests to cover Claude aliases and provider-specific fallback behavior
- Set `target_commitish` from preflight ref when creating GitHub releases
- Track whether package versions changed and expose it via step output
- Run format, lockfile refresh, and bump commit only when changes exist
Move the version bump commit and tag creation out of the preflight job
into a new finalize job that runs only after build, publish, and release
all succeed. This prevents orphaned version commits and tags on main
when downstream jobs fail.
- Preflight: validate version, lint/test only — no commit/tag/push
- Release: softprops/action-gh-release creates tag for workflow_dispatch
- Finalize: bump package.json versions, refresh lockfile, commit to main
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Replace flat changed-files chips in ChatView with a nested, expandable tree
- Extract diff tree/stat logic into turnDiffTree utilities
- Add unit tests for stat aggregation, nesting, and Windows path normalization
- Move "New thread" action to each project header with hover icon + shortcut tooltip
- Limit thread lists to 6 items by default with per-project Show more/Show less controls
- Remove the global sidebar-level new thread button
- Use the larger of shared stack height and per-toast height to avoid clipping
- Make toast content columns flexible with `min-w-0` and `break-words`
- Keep action buttons from shrinking so long text wraps instead of overflowing
- Add a `Copy Thread ID` item to the thread context menu in the sidebar
- Copy the selected thread ID via Clipboard API
- Show success/error toasts based on copy result
- replace Lexical-node cursor adjacency check with text/cursor helper
- prevent `@query` typing from being treated as mention-pill adjacent
- add regression test for non-pill `@pac` input
- Only intercept left/right arrow keys when cursor is directly next to a mention
- Prevent default arrow behavior only for those mention-boundary moves
- Add `isCollapsedCursorAdjacentToMention` logic with coverage for left/right adjacency cases
- Route `system` messages through assistant height estimation
- Keep user attachment height logic scoped to user messages
- Add regression test for system-message sizing behavior
- Add viewport matrix coverage for long text and attachment row-height parity
- Reuse a mount/measure test harness to validate resize behavior in one session
- Ensure production CSS and viewport sizing are applied before measurements
- recompute timeline width from the root element on ResizeObserver updates
- rerun width effect when message/working state changes
- reduce minimum user chars per line for narrow layouts and add regression test
- Replace manual timeout polling loops with `vi.waitFor` in test helpers
- Improve reliability of locating and measuring virtualized user rows in attachment-height tests
- replace manual `createRoot` mounting with `render`/`unmount` from vitest-browser-react
- add `vitest-browser-react` to web devDependencies and lockfile
- Run ChatView browser tests through the real app router/store stack
- Add MSW worker setup and mocked WS/attachment responses for full-app rendering
- Extract shared `getRouter` setup and add a timeline root data hook for reliable measurement
- Replace mocked router hooks with a memory router + RouterProvider
- Render ChatView through a test route to exercise attachment height layout in realistic routing context
- Replace Playwright e2e timeline-height test setup with Vitest browser config
- Add `ChatView.browser.tsx` parity tests for text wrapping and attachment height estimation
- Add row data attributes in `ChatView` to support in-browser measurement targeting
- add browser E2E tests validating timeline height estimator against rendered DOM
- configure Playwright test runner and scripts in `apps/web`
- run browser tests in CI with Playwright browser caching and install step
The publish_cli job was checking out the default ref instead of the
preflight commit, so it published with the pre-bump version. Add the
correct ref to checkout and a --app-version flag as a safety override.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- drop `electronmon` from desktop dependencies
- stop killing stale processes by matching electronmon hook paths
- keep cleanup scoped to `--t3code-dev-root` processes only
Use setFeedURL with private: true when a GitHub token is provided so
electron-updater queries the GitHub API instead of the public Atom feed
which rejects Bearer auth headers.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Extract desktop updater state transitions into `updateMachine` reducers with tests
- Extend update IPC/contracts to return `{accepted, completed, state}` for download/install actions
- Add web sidebar update-button logic for retryable download/install errors and clearer tooltips
- Add `updateState` helpers for auto-update eligibility reasons and progress throttling
- Show a user-facing dialog when manual update checks are unavailable
- Ensure manual update checks can open a window when none exist
- Add tests for disable-reason logic and 10% download progress bucketing
- track and clear startup + poll update timers through one cleanup path
- prevent update checks from starting while the app is quitting
- reset startup timer before scheduling to avoid duplicate checks
The guard for status === 'downloaded' logged 'skipping automatic install'
but the function only checks for updates, never installs. The guard was
also redundant since checkForUpdates() already returns early for
'downloaded', 'downloading', and 'available' statuses with correct
log messages.
Co-authored-by: Julius Marminge <[email protected]>
Applied via @cursor push command
- Prevent update install from running when shutdown is already in progress
- Ignore install IPC calls once `isQuitting` is set to avoid duplicate install attempts
- Skip redundant update checks while update is available/downloading/downloaded
- Wait for backend shutdown before `quitAndInstall` and improve updater error/progress handling
- Prevent sidebar update button clicks during download while preserving tooltip interactivity
- Skip desktop auto-update checks while an update is downloading or already downloaded
- Subscribe to update-state events before initial fetch in sidebar to avoid stale state races
- wire `electron-updater` into desktop main/preload IPC and shared contracts
- add sidebar update action for download/install state in Electron UI
- update release workflow/build script to include `latest*.yml` and `*.blockmap` assets
Add tree-kill via taskkill /T /F in processRunner and codexAppServerManager so timeout enforcement and session stop properly terminate the entire process tree instead of just the cmd.exe wrapper. Detect Windows command not found (exit 9009) in normalizeExitError. Pre-validate editor commands with isCommandAvailable in open.ts before spawning. Fix ProviderHealth test import and dev-runner test path assertion for Windows.
Made-with: Cursor
- Run Codex-related child processes with `shell` on Windows for reliable command execution
- Switch provider auth probe to `codex login status` and update health-check expectations
- Use Node PTY on Windows instead of Bun PTY in server runtime setup
- Parse nested/array JSON auth status output from `codex auth status --json`
- Return `unauthenticated` when JSON contains `authenticated: false`
- Return warning when JSON is parseable but lacks an auth marker
- add startup ProviderHealth service/layer to probe Codex install and auth state
- extend server contracts and WS payloads to include provider statuses
- show non-ready provider warnings in ChatView and cover with server/web tests
- add `vitest` to `apps/web` devDependencies and lockfile
- remove unused `envMode` prop from `BranchToolbar` usage and signature
- drop unused composer command input ref in `ChatView`
- Replace string-based env override plumbing with typed config/flag parsing
- Split server/web offset resolution from explicit port/dev-url overrides
- Refactor and expand dev-runner tests around offset/env behavior
- Add `vitest` as a contracts dev dependency for test execution
- Replace `scripts/dev-runner.mjs` with typed `scripts/dev-runner.ts` in a new `@t3tools/scripts` workspace
- Move networking helpers into `@t3tools/shared/Net` and reuse them in server and desktop
- Add shared NetService tests and align workspace deps to `catalog:` versions
- Pass command and args directly to `ChildProcess.make` in the publish CLI
- Remove fragile template-literal invocation to ensure command runs reliably
- Move branch combobox logic into `BranchToolbarBranchSelector` to simplify `BranchToolbar`
- Re-fetch git branches when opening the selector so options are current
- Preserve draft env mode correctly when switching between main and worktree branches
- Default new worktree branch selection to the current checked-out branch when unset
- Extract branch value resolution into shared logic with tests
- Stabilize virtualized branch list scroll/measurement to avoid loading glitches
- add `getSlashModelOptions` to centralize `/model` suggestion filtering
- include custom saved model slugs in slash-command suggestions
- update ChatView to consume shared helper and add focused tests
- Stop showing default-branch confirmation for `commit_push_pr`
- Keep confirmation only for direct `commit_push` actions
- Update logic test to match the new behavior
Deduplicate feature/ prefix logic in resolveAutoFeatureBranchName by
delegating to sanitizeFeatureBranchName. Skip the default-branch
confirmation dialog when there are no uncommitted changes (push-only),
since runFeatureBranchStep requires dirty worktree. Add merge-base
assertions to feature branch tests.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Consolidate the fragile 3-RPC flow (suggestCommitAndBranch → createBranch +
checkout → runStackedAction) into a single server-side operation triggered by
`runStackedAction({ featureBranch: true })`. The server now generates the
branch name via AI, deduplicates it, creates + checks out the branch, then
runs the normal commit/push/PR pipeline atomically.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Clarify that `packages/contracts` is schema-only with no runtime logic
- Add `packages/shared` as the home for shared runtime utilities and subpath exports
Create @t3tools/shared with explicit subpath exports (no barrel) for
shared utility logic. Move sanitizeBranchFragment and
sanitizeFeatureBranchName to @t3tools/shared/git, keeping contracts
focused on schemas.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Move sanitizeBranchFragment and sanitizeFeatureBranchName from three
duplicate definitions (CodexTextGeneration, GitManager, GitActionsControl)
into packages/contracts/src/git.ts. Remove the redundant double-sanitization
of branch names between the TextGeneration and GitManager layers —
CodexTextGeneration now owns sanitization of model output while GitManager
trusts the result and only sanitizes the custom commit message path.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace date-based auto feature branch names (feature/stacked-YYYYMMDD)
with semantically meaningful names derived from AI-generated commit
messages. The text generation prompt now returns a branch field alongside
subject and body, and a new suggestCommitAndBranch endpoint exposes this
to the web client for the default-branch checkout flow.
Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Add virtualized rendering and filtered item handling in `BranchToolbar`
- Memoize branch-derived data and sync highlight scrolling for large branch sets
- Convert `ComboboxList` to `forwardRef` to support virtualizer scroll targeting
- tighten win32 command availability checks for PATHEXT and PATH delimiter handling
- add server tests for Windows executable resolution edge cases
- stop branch/create flows after checkout/create failures to avoid stale optimistic UI
- remove OpenInPicker side effect that persisted last editor on render
- Dispatch `thread.meta.update` with the renamed branch after `git.renameBranch`
- Remove pre-rename active-branch status check and related skip path
- Update reactor tests to assert branch metadata moves to generated branch
- Remove git command execution for commit hash retrieval
- Simplify commit hash resolution to use environment variable and embedded hash only
- Clean up unused code in IPC handler registration
- embed `t3codeCommitHash` into staged desktop package metadata during builds
- resolve commit hash from env/package/git and display it as About panel version
- replace React Query mutations with direct git API calls wrapped in `useTransition`
- show toast errors for branch create/checkout failures and keep optimistic branch updates
- disable branch controls during pending actions and refresh branches when opening menu
- add `zed` to shared editor contracts and Open In picker
- add Zed icon and wire launch resolution tests on macOS
- wrap branch optimistic updates in `startTransition` to avoid sync warnings
- Add server-side command detection and return `availableEditors` in server config
- Update Chat header Open In picker to show only installed editors and handle empty state
- Extend server/web tests and contracts for `availableEditors`; remove unused branch-sync logic
- use `useOptimistic` in `BranchToolbar` to update active branch immediately
- keep optimistic branch in sync on success and roll back on mutation errors
- Skip auto-rename when the active worktree branch no longer matches the temp branch
- Update reactor tests to cover branch-switch and first-turn rename behavior
- Show the actual current branch in the toolbar and use a VS Code icon in Open In picker
- add VS Code to editor contracts and picker UI
- use `code --goto` for line/column targets in open resolution
- refine chat scroll intent handling to avoid unwanted stick-to-bottom jumps
- run `gitCheckout` via `Effect.scoped` to satisfy new `Scope` requirement
- update `GitCore.checkoutBranch` service signature to include `Scope.Scope`
- upgrade Effect catalog refs and `@types/node` to latest pinned versions
Adds visual active-item highlighting to the command menu, suppresses
trigger detection when the cursor is adjacent to a mention pill, and
resets transient UI state on thread change.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Treat mention pills as atomic cursor units in Lexical selection math
- Add left/right arrow + selection normalization behavior around mention nodes
- Expand collapsed mention cursor before trigger detection so @path menu closes correctly
- Update mention pill rendering for non-editable, non-selectable chips and theme-aware icons
- Add tests for collapsed-to-expanded cursor mapping and trigger behavior
Introduce ComposerPromptEditor component using Lexical for rich text
editing with @-mention support for files. Includes mention detection
utilities and tests.
Co-Authored-By: Claude Opus 4.5 <[email protected]>
getDestructiveMenuIcon fell back to resolveIconPath("png") on
Windows/Linux which resolved to the T3 Code app icon, not a trash
icon. Restrict the icon to macOS where createFromNamedImage("trash")
provides the correct system icon.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
All exit paths in commitRename now use a thread-guarded finishRename
helper that only clears renamingThreadId when it still matches the
original threadId. Prevents a stale onBlur from cancelling a newly
started rename on a different thread.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Remove the duplicate DesktopContextMenuItem interface and use the
shared ContextMenuItem type from @t3tools/contracts instead.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
After the async dispatch, only clear renamingThreadId if it still
matches the thread being renamed, preventing a second rename's
input from being cleared by the first's completion.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Re-export ContextMenuItem and replace the inlined
{ id: T; label: string; destructive?: boolean } definitions in
wsNativeApi, contextMenuFallback, and the test file.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Only used internally within ipc.ts for DesktopBridge and NativeApi
type signatures, so no need to export it.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Prevents Space from triggering the parent SidebarMenuSubButton's
navigation handler while typing in the inline rename input.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
The inline rename replaces the prompt dialog entirely, so remove the
promptDialog.ts file, IPC channels, bridge methods, and related tests.
Context menu improvements (destructive, position) are kept.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Thread rename now uses an inline input directly in the sidebar row
instead of opening a separate Electron BrowserWindow or browser
window.prompt. Enter commits, Escape cancels, blur saves.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Revert bare function calls / IIFEs back to useMemo for: modelOptions,
workLogEntries, latestTurnHasToolActivity, pendingApprovals, timelineEntries,
revertTurnCountByUserMessageId, completionSummary, and
completionDividerBeforeEntryId.
Add EMPTY_ACTIVITIES module-level constant so the ?? [] fallback doesn't
create a new array reference every render, which was defeating memoization.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Hoist removeOrphanedTerminalStates to a top-level selector in EventRouter
for consistency with other store selectors
- Convert timelineMessages IIFE to useMemo with proper deps
- Suppress no-map-spread in ChatView (spread is conditional, immutability required)
- Suppress exhaustive-deps for autoFocus in TerminalViewport (mount-time only)
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Add setTerminalFocusRequestId call when terminal opens via toggle so the
terminal panel receives focus automatically
- Call clearTerminalState when deleting threads in the Sidebar and add
removeOrphanedTerminalStates to prune stale entries after read model sync
- Track optimisticUserMessages via ref and revoke their blob URLs in the
unmount cleanup effect to prevent memory leaks
Co-authored-by: Julius Marminge <[email protected]>
- Deep clone DEFAULT_THREAD_TERMINAL_STATE in createDefaultThreadTerminalState
- Remove imperative getTerminalState from terminal store; export
selectThreadTerminalState for reactive selectors instead
- Fix Sidebar terminal activity indicator not updating (was using
non-reactive getter)
- Add no-op bailouts to app store transitions (updateThread,
markThreadVisited, markThreadUnread, setError, setThreadBranch,
setProjectExpanded, setRuntimeMode) to prevent unnecessary re-renders
- Use createDefaultThreadTerminalState in clearTerminalState to avoid
storing frozen reference
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Mount `ChatView` with `key={threadId}` to fully reset UI state on thread switch
- Replace effect-driven local state with direct derived values and cleaner cleanup paths
- Simplify async command/script flows and minor context memo handling in sidebar/ui components
Remove duplicate selector declarations introduced during rebase and restore the streamlined AppStore shape so Zustand selector usage remains consistent.
Restore Sidebar cleanup semantics and pure store test assertions so lint/typecheck stay green after rebasing.
Made-with: Cursor
- Replace `getTerminalState` reads with `selectThreadTerminalState` in ChatView and Sidebar
- Split terminal reducer into pure thread terminal operations used by the Zustand store
- Drop persisted default thread entries and add tests for the new operation helpers
Drop the temporary selector overload from useStore and migrate the remaining selector call sites to the unified { state, dispatch } API so the store surface stays single-path.
Made-with: Cursor
- Main store: replace useReducer with Zustand; pure state transition
functions (syncServerReadModel, markThreadVisited, setError, etc.)
called via store methods. Persist via subscribe.
- Terminal store: single store keyed by threadId; replace
dispatchTerminalAction with direct methods (setTerminalOpen,
setTerminalHeight, splitTerminal, newTerminal, setActiveTerminal,
closeTerminal, setTerminalActivity). Pure reduceThreadTerminalState
used internally.
- Update all consumers to call dispatch.method(...) and terminal
store methods. Fix store tests to use markThreadUnread pure fn.
- Fix Fragment import in store.ts; fix unused get param for lint.
Made-with: Cursor
- Delete draftThreadTerminalState.ts (was only re-exporting shared module)
- Replace draftThreadTerminalState.test.ts with threadTerminalState.test.ts
using createDefaultThreadTerminalState and reduceThreadTerminalState
- Draft threads are first-class: same helpers and types as persisted threads
Made-with: Cursor
- Add shared threadTerminalState.ts: ThreadTerminalState type, default state,
normalize helpers, and single reduceThreadTerminalState() used by both flows
- Refactor store.ts to use shared terminal reducer and helpers; terminal
actions map to reduceThreadTerminalState(threadTerminalSlice(thread), action)
- Make draftThreadTerminalState.ts re-export shared module (same shape/actions)
- Add terminalState to composer draft store: getDraftThreadTerminalState,
setDraftThreadTerminalAction, clearDraftThreadTerminalState; draft thread
shape matches Thread terminal slice
- ChatView: move draft terminal from useState into composer draft store; use
same actions for draft and persisted; hydrate then clear draft terminal
when reconciling server state
Made-with: Cursor
Adds local terminal state management for draft threads before they're
promoted to server threads. Terminal operations (open, split, create,
close, activate, resize) now work on draft threads and hydrate into
the server thread state when the draft is promoted.
Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Remove Action union/reducer dispatch path in `store.ts`
- Extract per-action state transition helpers and apply via `setAppState`
- Update `store.test.ts` to validate behavior through `useStore` actions
- Replace broad `useStore` state reads with targeted selector/action hooks across chat, diff, sidebar, and routing views
- Remove dispatch-style calls in favor of direct store actions to reduce unnecessary rerenders
- Improve chat UI interactions (composer menu navigation, image preview buttons, modal click targets)
- Add local `react-doctor` agent skill docs under `apps/web/.agents/react-doctor`
timelineEntries is derived from workLogEntries; the timelineEntries
effect already runs when work log changes. Dropped duplicate effect
and unused workLogCount variable.
Made-with: Cursor
collectUserMessageBlobPreviewUrls returns a compact array (image+blob only).
Consumer now indexes by image position, not full attachment index, so
blob URLs apply to the correct server attachments when some are skipped.
Made-with: Cursor
- Keep auto-scroll pinned to bottom during thread changes, composer resize, and streaming updates
- Improve virtualized timeline measurement/keying to prevent stale height reuse between threads
- Hand off blob image preview URLs from optimistic to server messages to avoid flicker/revocation races
- Stop `findFirstAvailableOffset` only when a required port exceeds `MAX_PORT`
- Add test covering offsets where only non-required ports are out of range
- Probe localhost ports and increment offsets when base ports are taken
- Resolve server/web offsets by mode while honoring explicit port/dev-url overrides
- Add tests for offset selection and per-mode fallback behavior
- replace `Effect.forkDetach` with `Effect.forkScoped` when refreshing checked-out branch upstream refs
- keep checkout responsive while ensuring the background task stays tied to scope lifecycle
- Track and persist `envMode` in composer draft thread state
- Keep worktree mode for local drafts even when `worktreePath` is null
- Update branch toolbar/chat/sidebar to use effective draft env mode
- Add tests for env mode persistence and undefined option merges
- allow `runProjectScript` for local draft threads when explicitly enabled
- move setup script execution to run after server thread creation
- gate setup script on worktree/base-branch availability and pass resolved worktree cwd
- Keep existing `branch` and `worktreePath` values when `setProjectDraftThreadId` receives `undefined`
- Add a regression test covering the undefined-update case
- Remove stale `draftsByThreadId` entries when project-thread mappings are replaced or cleared
- Preserve drafts when a thread is still mapped to another project
- Parse persisted image `dataUrl` payloads more defensively and use `Object.hasOwn` for draft-thread existence checks
- replace `read*` draft selectors with `getDraftThread`/`getDraftThreadByProjectId`
- centralize persisted localStorage parsing/caching in `composerDraftStore`
- make ChatView fallback read persisted attachments from in-memory store state
- Track draft thread metadata in composer draft store
- Reuse and update local draft threads from Sidebar/ChatView
- Create server thread only when sending first message, with rollback on failure
- Add/expand draft-thread store tests for mapping and context updates
- move project draft thread ID persistence/actions into `composerDraftStore`
- remove legacy `projectDraftThreads` module and update `ChatView`/`Sidebar` callers
- keep image dedupe stable across hydration and avoid revoking blob URLs on composer clear
- add store tests for project-thread mapping and composer clear behavior
- drop deprecated model slug aliases (`gpt-5`, `gpt-5-codex`, `gpt-5-codex-spark`)
- Reuse hidden draft threads while applying requested branch/worktree updates before navigation
- Export composer draft storage key and clone blob preview URLs when re-adding images after retry
- Deduplicate composer images by file signature (within and across calls) and add store tests for URL revoke behavior
- add a zustand-backed composer draft store with localStorage persistence for prompt, cursor, model/effort, and image attachments
- wire ChatView to draft state, restore/clear drafts correctly, and warn when an attachment cannot be persisted
- track per-project draft thread IDs so Sidebar reuses hidden draft threads and excludes empty drafts from thread lists
- Move install, lint, typecheck, and test steps ahead of release commit/tag in `release.yml`
- Add `buildVersion` to staged desktop `package.json` and set it to the app version
- Lowercase sanitized thread segments when creating attachment IDs
- Add coverage for mixed-case thread IDs in attachment store and projection pipeline tests
- Parse thread segments from attachment IDs using a UUID-aware pattern
- Prevent revert/delete cleanup from removing files belonging to similarly prefixed threads
- Add tests for prefix-collision cases in attachment store and projection pipeline
- Sanitize thread-derived attachment ID segments to safe, bounded tokens
- Resolve attachment IDs only when a matching file exists on disk
- Return 404 (not 400) for missing attachment IDs in the attachment route
- Add attachmentStore tests for ID sanitization and extension-based path lookup
- add attachment store helpers for IDs, route paths, and file resolution
- stop projection pipeline from mutating/storing data URLs; keep attachment metadata unchanged
- update Codex send/branch generation flows and tests to resolve images via attachment IDs
- add `ServerConfig.layerTest(cwd, stateDir)` to standardize test wiring
- require `ServerConfig` in `CodexTextGeneration` attachment path resolution
- update orchestration/projection tests and harness to use managed runtimes with explicit config
- accept `data:image/...;...;base64,...` headers while still rejecting invalid formats
- add `imageMime` tests for mime params, non-base64 URLs, and missing mime types
- fork branch-generation prompt effect at call site in `ProviderCommandReactor`
- Replace manual JSON schema constants and parse helpers with `Schema.Struct` definitions
- Generate JSON Schema from Effect Schema and decode output via `Schema.fromJsonString`
- Map `SchemaError` to `TextGenerationError` for invalid Codex responses
- Update `ProviderCommandReactor` test mock typing for `generateBranchName`
- Make branch-name generation return a required string instead of nullable output
- Propagate invalid Codex branch payloads as `TextGenerationError` instead of silently falling back
- Update provider command reactor to catch generation failures, log warnings, and skip rename safely
- add shared attachment path normalization and resolution helpers
- reuse persisted image files for turn start and branch name generation
- cover persisted attachment flow in text generation and reactor tests
- remove `git.renameBranch` from WS/contracts/native API surface and update server/web tests
- use `git branch -m -- ...` in GitCore to safely separate branch rename arguments
- Generate and rename temporary `t3code/*` worktree branches on first user turn in `ProviderCommandReactor`
- Remove websocket/client branch-generation RPCs and related contract/API surface
- Update Codex text-generation prompt to include attachment metadata only when attachments exist, with expanded tests
- Compute ahead count from base branch when upstream is missing
- Skip push/PR actions when no local commits are ahead
- Update server and UI tests for no-upstream push/PR behavior
- Change quick action to `Push` (not `Push & create PR`) when branch has no upstream and is not ahead
- Keep `Create PR` menu item disabled until the branch has commits ahead
- Add/adjust logic tests for both no-ahead and ahead scenarios
- Treat no-upstream branches as publishable: enable Push/Create PR and update quick actions
- Route Create PR menu action through commit+push+PR flow when appropriate
- Simplify Git action dialog to commit-only and add "Commit on new branch" option
- Prompt before commit/push actions on the default branch
- Allow one-click create+checkout of an auto-named feature branch and continue
- Add logic/tests for date-based unique auto feature branch naming
- add GitHub Actions release workflow for v*.*.* tags with preflight checks
- build and publish macOS, Linux, and Windows desktop artifacts in one release
- replace DMG-only script with cross-platform `dist:desktop:artifact` flow
- document release, signing setup, and new desktop dist commands
- fall back to plain checkout (detached HEAD) when `--track` would clash with an existing local branch
- add GitCore coverage for the conflict fallback path
- simplify branch-name derivation in BranchToolbar to consistently strip the first remote segment
- Fall back to empty remote branch and remote name data when git remote queries fail
- Log warnings instead of failing `listBranches`
- Add integration test covering remote lookup failure fallback
- add `remoteName` to git branch contract metadata
- resolve remote refs using full remote names (including slashes)
- avoid fallback to wrong local checkout when remote ref is missing
- update branch toolbar logic/tests to map and dedupe remote branches correctly
- Deduplicate branch list by removing remote refs that match an existing local branch
- Move remote-ref local-name derivation into shared BranchToolbar logic
- Add logic tests for remote-ref parsing and deduplication behavior
- Include remote refs in branch listings, ordered after local branches
- Auto-track remote branches on checkout when no local branch exists
- Update branch picker to label remote branches and store local branch name after checkout
- Add click handling on diff file headers (`data-title`) to open files via native `openInEditor`
- Resolve file paths against active thread/project cwd before launching editor
- Add header hover affordance and tighten diff panel spacing
- Show PR number/title in a tooltip on each thread PR icon
- Open PR links externally from the sidebar and show error toasts on failure
- Improve thread row keyboard handling after switching to a non-button render
Co-authored-by: codex <[email protected]>
- Wrap rendered markdown code blocks with a copy action button
- Show copy/check icons with transient "Copied" state and cleanup
- Style button to appear on hover/focus without shifting code layout
- Reuse in-flight highlight requests and allow later non-streaming renders to cache results
- Stabilize code block highlight state updates to avoid stale or redundant rerenders
- Export and reuse `fnv1a32` from `diffRendering` for shared cache key hashing
- Inject diff palette overrides via `unsafeCSS` in `DiffPanel`
- Add `diff-panel-viewport` background and keep file container border/background styling in `index.css`
- Switch panel root from `bg-card` to `bg-background` for consistent surface tone
- add diff-specific wrapper classes in `DiffPanel` for targeted theming
- override diff renderer color variables to match card/background palette
- soften chat markdown Shiki code-block background for consistency
- Replace `rehype-highlight`/`highlight.js` with `@pierre/diffs` highlighter in `ChatMarkdown`
- Add LRU caching and in-flight dedupe for highlighted code, with streaming-aware behavior
- Extract shared diff theme resolution utility and add unit tests for new LRU cache
- Write projected attachments under the thread directory using `messageSegment-fileName`
- Avoid nested per-message folders while preserving unique, deterministic file paths
- Update projection pipeline tests to match new attachment URLs and on-disk paths
- Make projection attachment writes use last-write-wins per file path
- Always write attachment files so updated message attachments replace stale bytes
- Add regression test covering same message/attachment index update behavior
- Treat `attachments: []` as an explicit update instead of dropping the field
- Add regression test covering attachment clearing for an existing thread message
- Open preview from the full image set instead of a single image
- Add previous/next controls with ArrowLeft/ArrowRight keyboard support
- Keep Escape-to-close behavior and show current image position
- Materialize only valid image data URLs and restrict inferred file extensions to a safe whitelist
- Preserve existing message attachments on upsert unless explicitly replaced or cleared
- Serve static `/` via `index.html` and block traversal attempts in static file requests
- Store message attachments in `projection_thread_messages.attachments_json`
- Materialize base64 image attachments to `stateDir/attachments` during projection
- Serve `/attachments/*` from the server and resolve preview URLs from WebSocket origin
- Add migration and tests for projection materialization and attachment serving
- Read and validate `cwd` from persisted runtime payload when restarting sessions
- Apply persisted `cwd` during stale-session recovery paths, including `sendTurn`
- Add tests to verify resumed sessions preserve the original working directory
- Ignore late write calls after a terminal session has already exited
- Add regression test for trailing writes after exit
- Close terminal drawer session once an exit event is handled
- Update favicon regex parsing to support rel/href in either order
- Add route tests for HTML link tags and object-style metadata with href-first ordering
- move `/api/project-favicon` handling into a dedicated server route with coverage for root and source-linked icons
- wire `wsServer` to use the new route helper
- treat any running session as unsettled in `isLatestTurnSettled` to prevent stale latest-turn banners, with test coverage
- Add `isLatestTurnSettled` to avoid treating an active running turn as complete
- Use the guard in `ChatView` for visited timestamps and completion summary/divider rendering
- Add unit tests covering running, ready, and incomplete-timestamp cases
- add `OrchestrationLatestTurn` schema and store full turn state/timestamps/message linkage
- update server projector/snapshot queries to populate `latestTurn` from session + projection_turns
- migrate web store/components to consume `latestTurn` and adjust related tests
- Use `ProviderTurnId` in `CheckpointReactor` tests instead of `TurnId`
- Guard `event.turnId` access in provider runtime ingestion when the field is absent
- Remove redundant runtime schema aliases for thread and turn IDs
- Use `ProviderThreadId` and `ProviderTurnId` directly across runtime event contracts
- Ignore auxiliary/non-active turn completions for session lifecycle and checkpoints
- Restrict runtime thread/turn IDs to provider IDs in contracts
- Add regression tests and ADR for lifecycle ownership rules
- Pass explicit Pierre light/dark theme into diff render options
- Re-key file diffs on resolved theme so views rerender on theme switch
- Stabilize `useTheme` snapshots to propagate system theme updates reliably
- Reorder restart flow to bind the new provider session before stopping the old one
- Log (and swallow) stop-session failures for superseded sessions
- Add regression test ensuring failed restart does not stop the active session
- Make `approvalPolicy` and `sandboxMode` required in orchestration contracts and turn-start flow
- Add defaults in provider reactors/ingestion to guarantee values are always set
- Store and hydrate both fields in projection persistence, snapshots, and related tests
Use conditional spreading for these properties to handle undefined
values correctly with exactOptionalPropertyTypes.
Co-Authored-By: Claude Opus 4.5 <[email protected]>
- add default `.t3/keybindings.json` for terminal/chat/editor/diff shortcuts
- include initial provider log files and SQLite state artifacts under `apps/server/.t3`
- Persist `approvalPolicy` and `sandboxMode` on orchestration sessions
- Reuse existing sessions when runtime mode is unchanged
- Stop and recreate provider sessions when runtime mode settings change
- Add reactor tests for reuse vs restart behavior
- Add `approvalPolicy` and `sandboxMode` to turn-start command and requested payload contracts
- Pass runtime mode-derived values from `ChatView` when dispatching `thread.turn.start`
- Thread provider options through decider/reactor into session startup, with tests updated
- Fetch orchestration snapshot when bootstrap project/thread IDs are absent
- Resolve project by current workspace and choose latest non-deleted thread
- Continue auto-navigation and expansion using resolved fallback IDs
- Server welcome now includes bootstrap project/thread IDs when cwd project/thread already exist
- Added regression test for reconnecting with persisted bootstrap state
- Root route ignores post-dispose welcome handling and marks thread as handled after navigate
- Track latest `pathname` in a ref for bootstrap event handling
- Prevent effect resubscriptions by removing `pathname` from deps
- Keep auto-navigation gated to root route using current path
- Create or reuse cwd project, create initial thread, and include bootstrap IDs in `server.welcome`
- Update web event routing to expand the project and auto-navigate from `/` to the bootstrapped thread
- Extend WebSocket welcome contract and add server/web tests for bootstrap payload handling
- Guard `onSend` with an in-flight ref to block double submits
- Set send phase before worktree prep and always clear in-flight state in `finally`
- Sync thread branch/worktree path immediately and await setup script execution
- Add `sendInFlightRef` guard in `ChatView` send handler
- Set sending state before async work and always clear it in `finally`
- Wrap early send flow in one `try/finally` to avoid double-submit races
- show an explicit error when New worktree mode has no base branch selected
- sync thread branch/worktree path immediately after creation
- run setup script in the new worktree terminal before continuing
Co-authored-by: codex <[email protected]>
- Drop optional `text` from `ThreadMessageAssistantCompleteCommand`
- Stop passing text on assistant-complete ingestion and decider paths
- Ensure completion events no longer overwrite message content
- Remove spilled-state cache tracking for buffered assistant messages
- Emit any remaining buffered text as a finalize delta on completion
- Keep assistant completion payload text empty in buffered mode
- Change provider runtime ingestion to flush the entire buffered assistant text once it crosses the max size
- Remove partial-retention logic and its keep-chars constant to simplify memory safety behavior
- cap buffered assistant text memory and spill older chunks as delta events
- finalize buffered messages by emitting retained remainder before completion when spilled
- add regression coverage for oversized buffered deltas and tighten type-safe test assertions
- Replace per-thread/turn/message delivery-mode caches with a single `Ref`
- Always complete assistant messages with buffered text from message state
- Remove obsolete delivery-mode cleanup and resolution paths
Use conditional spread for turnId to avoid passing undefined
explicitly when the target type expects an optional property.
Co-Authored-By: Claude Opus 4.5 <[email protected]>
- add `AssistantDeliveryMode` contracts and carry mode through turn-start events
- default assistant responses to buffered mode and preserve buffered text until completion
- support streaming mode end-to-end with ingestion/decider updates and test coverage
- add a Settings toggle to enable assistant streaming in the chat UI
- Append pending user messages to the timeline before server echo arrives
- Reuse message ID/timestamp for optimistic and sent payloads to avoid duplicates
- Remove optimistic entries on sync or send failure
- Replace boolean `isSending` with `sendPhase` state
- Show "Preparing worktree..." status before first-turn dispatch
- Keep composer editable while preventing duplicate sends and restore input on pre-send failures
- subscribe to terminal events in root route and dispatch terminal activity updates
- add reducer support to maintain `runningTerminalIds` per thread/terminal
- add unit tests for terminal event mapping and store activity state transitions
- Use generic type parameter for stream errors instead of unknown
- Type ServerShape errors as ServerLifecycleError instead of unknown
- Add error mapping for autoBootstrapProject and httpServerListen
- Type makeServerProviderLayer with ProviderUnsupportedError
- Use Effect.try with decodeUnknownSync in projector to avoid unknown requirements
- Fix test layer types from any/unknown to never
Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Use domain errors directly in GitManager tests (`GitHubCliError`, `TextGenerationError`)
- Remove fixture-only GH error normalization in test scaffolding
- Introduce shared `PtyAdapterInitializationError` and use it in NodePTY adapter init
- Replace raw `Effect.promise`/generic errors with `Effect.tryPromise` and tagged schema errors
- Improve orchestration harness/test reliability with explicit timeout/runtime error types
- Tighten related tests and error assertions to match typed error flows
- add `gitMutationKeys` and attach mutation keys across git mutation options
- switch GitActionsControl loading state to `useIsMutating` with cwd-scoped keys
- add tests for cwd-scoped mutation keys and mutation option wiring
- Add `mark-unread` option to thread context menu and dispatch reducer action
- Implement `MARK_THREAD_UNREAD` to set `lastVisitedAt` just before latest completion
- Add reducer tests for unread behavior and no-op when no completed turn
- Update fallback context menu styling so only delete uses destructive color
- Bind `mod+d` to `diff.toggle` when terminal is not focused
- Wire ChatView to handle `diff.toggle` and show its shortcut in the diff button tooltip
- Limit sidebar `mod+b` listener to mobile to avoid desktop shortcut conflicts
- Extend web/contracts keybinding tests and command list for `diff.toggle`
- Prefer `T3CODE_STATE_DIR` from env when `--state-dir` is unset or blank
- Throw on invalid `T3CODE_PORT` overrides and always recompute `VITE_WS_URL`
- Add tests for env/state-dir precedence, blank overrides, and invalid ports
- make integration harness dispose path always remove temp root dirs via `Effect.ensuring`
- preserve shutdown failure by surfacing the first teardown error cause
- add integration test that forces `providerService.stopAll` failure and verifies temp dir cleanup
- default root dev commands to `T3CODE_STATE_DIR=~/.t3/dev`
- add `--` flag forwarding in `scripts/dev-runner.mjs` for server env flags
- resolve desktop state dir from `T3CODE_STATE_DIR` with new tests for desktop and dev runner
- pass a cache scope into `getRenderablePatch` and include resolved theme in DiffPanel cache keys
- add a test proving `buildPatchCacheKey` changes when cache scope changes
- detect `:line` and `:line:column` suffixes in open targets
- pass `--goto` when launching Cursor so it jumps to the cursor location
- add tests covering both line-only and line+column targets
- Wrap processDomainEvent in catchCause to prevent the reactor fiber from
terminating on handler errors, matching the pattern used by
ProviderRuntimeIngestion and CheckpointReactor.
- Replace duplicated resolveEffectiveThreadCwd with the shared
resolveThreadWorkspaceCwd from checkpointing/Utils.ts.
- Sync and persist missing default keybindings on server startup without overriding existing command mappings
- Return `keybindingsConfigPath` from `server.getConfig` and add Settings UI action to open `keybindings.json`
- Update server/keybindings tests to cover bootstrapping, conflict handling, and config responses
- Require `threadId` when starting provider sessions and route recovery via persisted bindings
- Persist and propagate provider `resumeCursor`/`providerThreadId` instead of synthesizing values
- Expose full session bindings in `ProviderSessionDirectory` and update tests/integration fixtures
- Rename sqlite state file from `orchestration.sqlite` to `state.sqlite`
- Decode `server.welcome`, terminal, and orchestration push events with Effect schemas
- Drop malformed payloads with warning logs instead of forwarding invalid data
- Add wsNativeApi tests for valid forwarding, caching, and malformed-payload handling
- Restructure Chat, DiffPanel, and Sidebar headers for cleaner Electron drag/no-drag behavior
- Keep turn-strip controls interactive while preserving draggable titlebar regions
- Lower inline diff panel minimum width from 28rem to 26rem for tighter layouts
- map `checkpoint/captured` to `thread.turnDiff.complete` and record turn status/id
- handle `thread.revert` to truncate messages and turn summaries in read model
- migrate event store from `better-sqlite3` to `node:sqlite` and add safe close/idempotent stop tests
Move state management from client to server using an event-sourced architecture:
- Add SQLite-backed event store with append-only event log
- Add orchestration engine with command queue, reducer, and read model
- Add Effect-based PubSub for real-time read model updates to clients
- Define orchestration schemas in contracts (commands, events, read model)
- Simplify client-side store by removing persistence layer
- Remove obsolete client-side persistence tests
Co-Authored-By: Claude Opus 4.5 <[email protected]>
Consolidate the repeated pattern of destructuring and removing diff/diffTurnId/diffFilePath
search params into a single stripDiffSearchParams() function in diffRouteSearch.ts.
Replaces 5 identical destructuring blocks across 3 files with calls to the shared helper.
Applied via @cursor push command
- Extract `DiffWorkerPoolProvider` into its own component and wrap `_chat` outlet with it
- Render/lazy-load `DiffPanel` from `/_chat/$threadId` so diff UI state and close behavior live with thread routing
- Keep responsive sheet vs inline diff presentation with route-level fallback loading UI
- Parse and validate `diff`, `diffTurnId`, and `diffFilePath` from chat route search
- Switch ChatView/DiffPanel diff open/target actions to router navigation instead of store actions
- Remove diff-specific state/actions from the app store and update reducer tests
- Prefer route thread id over stored diff thread when rendering diffs
- When visiting a different thread with diff open, retarget diff state and clear stale turn/file selection
- Add reducer test coverage for open-diff retargeting behavior
- Add left/right controls, edge fades, and wheel-to-horizontal scrolling for turn chips
- Auto-scroll selected turn chip into view and hide the chip strip scrollbar
- Simplify chip metadata to show compact per-turn time
- Add `optimizeDeps.include` entries for `@pierre/diffs` packages in web Vite config
- Improves dev startup/runtime stability for diff rendering modules
Scope invalidation to only the checkpoint diff query for the newly
captured turn instead of invalidating all provider queries. The
checkpoint/captured event carries a turnCount in its payload, so we
use a predicate to match only the query whose toTurnCount equals the
captured turn. This prevents N unnecessary refetches of immutable
diffs for already-completed turns on each new turn completion.
- Load per-turn checkpoint diffs in `ChatView` and show loading/error states in the timeline
- Drive changed-file chips/stats from checkpoint diff results instead of cached turn summary files
- Prevent reducer from rederiving completed turn summaries on late `turn/diff/updated` events; add regression test
- emit `checkpoint/captured` from `ProviderManager` after checkpoint init/capture
- add backend test coverage for the new checkpoint-captured notification flow
- refresh provider queries on `checkpoint/captured` and only re-derive diffs on `turn/completed`
- Remove persisted/stored patch bodies from turn diff summaries and keep metadata-only file stats
- Drop checkpoint diff hydration paths in chat/diff views; rely on selected checkpoint/conversation diffs only
- Sync checkpoint turn counts on session ensure and tune checkpoint diff query retry/backoff for not-ready errors
- Update tests for session logic, persistence, store reducer, and provider query retry behavior
- Dispatch `MARK_THREAD_VISITED` when `activeThreadId` changes in root route
- Add reducer handling to update a thread's `lastVisitedAt`
- Add reducer test coverage for selecting a thread updates visit time
- Add `@tanstack/react-virtual` to web dependencies
- Render chat timeline with virtualized rows for work logs, messages, and working indicator
- Replace end-of-list sentinel approach with scroll-container-based virtualization
- remove `activeThreadId` from web store state and persistence schema
- drive thread-scoped event handling and toast visibility from router params
- simplify chat index/route flow and add explicit `apps/web/vite.config.js`
- Switch web router setup to TanStack file routes and generated `routeTree.gen.ts`
- Move app bootstrap/event wiring into new root route component
- Enable TanStack router Vite plugin and ignore generated route tree in oxlint
- add route-based chat layout with index and `/$threadId` views
- navigate sidebar thread actions through router instead of store-only selection
- extract shared thread creation into `threadFactory` and wire new router deps
- wrap `git worktree remove` errors with command and cwd context
- add server test covering failed worktree removal messaging
- show an error toast and log details when orphaned worktree cleanup fails
- Restore null CWD in sessionOverrides for thread/start and thread/resume
so the Codex app server can distinguish 'no override' from an explicit
path (e.g., to reuse a resumed thread's original CWD).
- Use backreference in diff --git fallback regex to correctly parse paths
containing ' b/' (e.g., binary diffs without +++ b/ lines).
- Add test exercising the git header fallback for binary diffs with ' b/'
in the path.
Applied via @cursor push command
- upgrade `@pierre/diffs` to `^1.1.0-beta.16`
- switch file diff list to `Virtualizer` for smoother large patch rendering
- adjust diff panel container/layout handling and theme typing
- Keep the diff viewer alive when hidden to avoid remount churn
- Share diff worker pool setup via a dedicated provider
- Add `keepMounted` support to `SheetPopup` for sheet-mode persistence
- Wrap `DiffPanel` in `WorkerPoolContextProvider` and add a dedicated diffs worker
- Use content-based patch cache keys to stabilize `parsePatchFiles` caching
- Add tests for cache key stability, whitespace normalization, and content changes
- Include `cacheScope` in checkpoint diff query keys
- Pass turn/conversation-specific scopes from `ChatView` and `DiffPanel`
- Add tests for key separation and API argument forwarding
- update `useDebouncedValue` import to `@tanstack/react-pacer`
- add missing `diffThreadId`, `diffTurnId`, and `diffFilePath` in thread continuity test state
- add shared provider checkpoint diff query options and keys
- refactor `ChatView` and `DiffPanel` to fetch diffs via React Query
- persist selected-turn checkpoint diffs back into thread state for reuse
- Add a confirmation dialog before checkpoint revert
- Warn that newer messages and turn diffs will be discarded
- Cancel revert when the user does not confirm
- add reusable `ui/toggle` and `ui/toggle-group` components built on Base UI
- switch diff view mode controls and chat header diff toggle to use the new toggle primitives
- add server support to diff filesystem checkpoints, including root/HEAD fallbacks and lazy checkpoint initialization
- wire new `providers.getCheckpointDiff` WebSocket route through provider manager and contracts
- update web app to load per-turn diffs from checkpoints and improve diff panel behavior on narrow screens
- Replace placeholder diff sidebar with real turn/file patch rendering
- Link assistant messages to changed-file summaries and open targeted diffs
- Persist diff selection state in the store and cover parsing/reducer behavior with tests
- Lazy-load `DiffPanel` to reduce initial bundle cost
- add `FilesystemCheckpointStore` to capture, restore, and prune per-turn git refs
- wire checkpoint init/capture into `ProviderManager` with per-session locking and error events
- require checkpoint presence before rollback and restore workspace state after revert
- add tests for checkpoint store behavior and provider rollback integration
- add provider/WS contracts and server RPC handlers for listing/reverting checkpoints
- read and rollback Codex thread turns in the app server manager
- add ChatView checkpoint menu + store reducer support to revert local thread state
- expand backend, websocket, store, and contract tests for checkpoint flows
Move the duplicated script normalization logic (dedup-by-id + single
runOnWorktreeCreate enforcement) from apps/web/src/store.ts and
apps/server/src/projectRegistry.ts into packages/contracts/src/project.ts
so both consumers share one canonical implementation.
Applied via @cursor push command
Remove injectEnvIntoShellCommand, shellEscapePosix,
shellEscapeWindowsSetValue, ENV_KEY_PATTERN, and the now-unused
isWindowsPlatform import. These were leftover from an earlier approach
where env vars were injected into the shell command string, replaced
by passing env directly to terminal.open.
Applied via @cursor push command
- Remove autoFocus from the main terminal setup effect dependency array to
prevent full terminal teardown/recreation when switching tabs in split view.
Focus is already handled by a dedicated effect.
- Change threadTerminalRuntimeEnv memo dependency from activeProject to
activeProject?.cwd so unrelated project state changes (e.g. saving scripts)
don't trigger terminal re-initialization.
- Unexport injectEnvIntoShellCommand which is never imported by production
code (env injection is handled server-side), and remove its tests.
Applied via @cursor push command
- make `cols`/`rows` optional in terminal open contracts
- default new/restarted sessions to 120x30 when size hints are missing
- reuse existing terminal dimensions unless a new size is explicitly requested
- only send script terminal size hints when creating a new terminal
- Clear form fields only after the dialog close completes to avoid stale state during transitions
- Keep icon picker closed when the dialog closes
Co-authored-by: codex <[email protected]>
- add optional `env` to terminal open contract and validate env keys/limits
- propagate runtime env from web terminal/script launches to server PTY spawn
- start `zsh` with `-o nopromptsp` to avoid trailing `%` markers and add coverage
- add server `upsertKeybinding` flow to write `~/.t3/keybindings.json` and refresh cached config
- wire project script create/edit to save optional keybindings via the WS API
- improve script action UI with edit controls, icon picker, and preferred-script recall
- add coverage for keybinding upsert behavior in server and websocket tests
- add project-scoped script actions in the chat toolbar, including setup-on-worktree-create
- support dynamic `script.{id}.run` keybindings and command resolution
- persist and sync project scripts across web state, contracts, WebSocket API, and server registry
- add backend and frontend tests for script helpers, persistence, and registry behavior
- Switch composer menu arrow-key navigation to `Command`'s internal highlight handling
- Track highlighted item by id instead of manual index/keyboard state
- Remove custom hover/highlight plumbing and hidden-scroll sync logic
- Introduce a new test file to validate chunking behavior of git check-ignore to prevent oversized input strings.
- Adjust workspaceEntries.ts to implement chunking logic for git check-ignore, improving performance with large ignored path lists.
- Set a maximum byte limit for stdin in git check-ignore to enhance stability and prevent errors during processing.
- Reuse in-flight workspace index builds per cwd and cap `readdir` scan concurrency at 32
- Add server tests for build deduplication and directory read concurrency limits
- Track composer text in a ref so prompt replacements use current text after send/reset
- Replace slash-command menu glyph in ChatView with `BotIcon`
- Map `yml`/`yaml` to base YAML language id to avoid overly specific icons
- Add test coverage for GitHub workflow YAML icon selection
- Extract composer menu into memoized components for cleaner ChatView rendering
- Debounce path trigger queries and keep previous results while fetching
- Precompute searchable model fields to reduce repeated lowercase work
- render theme-aware VS Code icons for path suggestions in chat composer
- exclude `.convex` and gitignored paths more reliably in workspace indexing
- add tests plus a sync script and icon manifest/association data
- Build workspace index from `git ls-files` when in a Git repo, excluding ignored paths
- Skip configured ignored top-level directories during filesystem fallback indexing
- Update chat composer to insert `@path` directly in prompt and remove separate tagged-path chips
- Keep command menu navigation visible by scrolling the active/next item into view
- add `projects.searchEntries` API, contracts, and server-side indexed workspace search
- add composer trigger logic for `@` path suggestions and `/model` command completion
- include tagged paths in sent prompt/user-visible text and cover behavior with server/web tests
- Simplify the promise handling for opening PR links by directly using `void api.shell.openExternal(prUrl).catch(...)`
- Enhance error handling by adding a toast notification for failure cases, improving user feedback on PR link issues
- enforce max 4 terminals per thread in reducer and terminal normalization
- block split/new terminal actions in chat and drawer when limit is reached
- add reducer tests for split/new terminal cap behavior
- add `min-w-0` to ChatView container wrappers to allow proper flex shrinking
- make thread title truncatable with `truncate` and `title` tooltip
- keep action controls fixed-width with `shrink-0` to preserve header layout
- Introduce a new "clean" script to remove node_modules and build artifacts across apps and packages
- Enhances project maintenance by simplifying cleanup process
- Prevent `SET_THREAD_BRANCH` dispatch unless both `activeThreadId` and `syncedBranch` exist
- Avoids updating thread-branch state without an active thread context
- move branch-sync decision into `BranchToolbar.logic.ts`
- avoid auto-sync when env mode is `worktree` or thread has worktree path
- add unit tests for sync and no-sync cases
- Derive `activeSessionId` and `activeThreadId` before approval callbacks
- Avoid stale thread/session captures when submitting approval decisions
- Pass `hasMessages` to `MessagesTimeline` instead of the full thread
- Extract header, error, approvals, and timeline into memoized components
- Memoize `ChatMarkdown`, pickers, and handlers to reduce avoidable re-renders
- Reduce running-time ticker frequency from 250ms to 1000ms
- Replace `chat.newSameGitState` with `chat.newLocal` across contracts, server/web defaults, docs, and tests
- Make `chat.new` preserve branch/worktree state while `chat.newLocal` creates a local thread
- Show terminal close shortcut labels in drawer action tooltips and tab close controls
- Extend keybinding contracts/defaults with `terminal.close` and `chat.newSameGitState`
- Wire web handlers for `mod+w` to close focused terminal and `mod+shift+n` to open a thread preserving branch/worktree
- Update docs and keybinding tests across server, web, and contracts
- Replace `openPr`/`mergedPr` with `pr` in server and contracts
- Add PR `state` (`open`/`closed`/`merged`) to git status schema
- Resolve latest branch PR via `gh pr list --state all` sorted by `updatedAt`
- Add `dismissAfterVisibleMs` support to thread toasts
- Pause/resume countdown based on tab visibility and window focus
- Set Git action result toasts to dismiss after 10s when visible
- Show warning toast when attempting to delete a non-empty project
- Simplify confirmation copy to emphasize irreversible deletion
- Remove thread/worktree/session cleanup from project delete flow
- Prompt before deleting a project with thread and linked worktree counts
- Best-effort remove orphaned worktrees when project threads are deleted
- Show toast with error details if project deletion fails
- Add project right-click Delete action in `Sidebar` and clean up sessions/terminals before removal
- Add `DELETE_PROJECT` reducer action to remove the project, its threads, and reset active thread
- Add reducer test coverage for project deletion behavior
- Add a shared composer-focus scheduler in `ChatView`
- Refocus composer after runtime mode, model, effort, and env mode selections
- Let `BranchToolbar` request composer focus after branch/worktree actions
- set server config query `staleTime` to `Infinity` to avoid unnecessary refetches
- narrow `isWindowsPlatform` matching to Windows-prefixed identifiers
- add unit tests for Windows and non-Windows platform cases
- make resolved keybinding/shortcut schemas strict to reject unknown fields
- export server `DEFAULT_KEYBINDINGS` as source of truth and reuse it in ws tests
- simplify keybinding test fixtures and update docs to reference server defaults
- Move default keybindings, config parsing, validation, and merge logic out of `wsServer`
- Add `loadResolvedKeybindingsConfig(logger)` in `apps/server/src/keybindings.ts`
- Update server wiring docs to point to `server.getConfig` integration
- drop `key` and `when` from resolved keybinding rule schema/payload
- update server/web/contracts tests and keybindings docs for `whenAst`-only resolution
- delete unused web `LruCache` implementation and tests
- add server keybinding compiler for shortcuts and `when` AST parsing
- switch websocket/server config payload to resolved keybinding rules
- update web keybinding logic/types to consume resolved payload directly
- add/adjust contract, server, and web tests (including plus-key parsing) and docs
- Evaluate shortcut matches by resolving the last matching key+when rule, regardless of command
- Add cross-command precedence tests and switch assertions to `vitest` `assert`
- Clarify precedence behavior in `KEYBINDINGS.md`
- add `chat.new` and `editor.openFavorite` to keybinding contracts and server defaults
- use shared keybinding matching in sidebar/chat view instead of hardcoded Cmd/Ctrl combos
- document new commands/defaults and extend server/web keybinding tests
- add `serverConfigQueryOptions` in new `serverReactQuery` utility
- switch `ChatView` from manual `getConfig` effect/state to `useQuery`
- default to empty keybindings while config is unavailable
- Move default keybinding resolution/override merging into `server.getConfig`
- Return server-resolved keybindings to the web client instead of resolving in UI
- Update docs and tests to reflect server-side defaults, overrides, and truncation behavior
- Reuse `KeybindingRule` and `KeybindingsConfig` directly for resolved keybinding types
- Update normalization helper to accept `KeybindingRule` for consistent typing
- extend `server.getConfig` to return sanitized keybinding rules from `~/.t3/keybindings.json`
- apply resolved bindings in the web app for toggle/split/new terminal shortcuts and labels
- add contracts/docs and tests for config parsing, validation, and shortcut behavior
- server: only query open PRs when the current branch has an upstream; still fall back to merged PR lookup
- tests: cover status behavior for branches without upstream tracking
- web: fetch git status once per cwd, validate query data with schema parsing, and map merged PR badges by thread branch match
- extend `GitStatusResult` with nullable `mergedPr` metadata
- in server git status, query merged PR only when no open PR is found
- in sidebar, display a `Merged` status pill for threads on branches with merged PRs
- update server/web/contracts tests for the new status shape
- only auto-scroll when the user is already near the bottom
- centralize near-bottom detection in `chat-scroll.ts` with a 64px threshold
- add unit tests covering threshold and edge-case behavior
Co-authored-by: codex <[email protected]>
- Disable the quick sync action when local and upstream branches have diverged
- Treat mismatched branch/status data as out-of-sync and refresh before enabling actions
- Update GitActionsControl logic tests for diverged branch behavior
Co-authored-by: codex <[email protected]>
- derive upstream branch from `branch@{upstream}` and guard empty values
- fetch only `+refs/heads/<branch>:refs/remotes/<remote>/<branch>` instead of all remote refs
- add integration test asserting scoped fetch args during `checkoutBranch`
- treat post-checkout upstream fetch as best effort so checkout still succeeds
- route refresh fetch through `this.git(...)` for consistent behavior
- add regression test for fetch-timeout during branch checkout
- fetch tracked remote after checkout to update ahead/behind counts
- add integration test for behind count when remote branch advances
- invalidate git React Query data on `turn/completed` events in the web app
2026-02-15 00:53:20 -08:00
804 changed files with 191590 additions and 15224 deletions
description:btca is a cli for getting information from other git repositories by querying them with natural language. Spawns an external subagent to explore external codebases (i.e. a github repo) and answer questions about them. Great when integrating complex libraries, frameworks, or tools.
---
btca is a cli for asking questions about various folders, primarily git repositories. It's built to give you the exact information you need without bloating your context window. btca uses agents under the hood to answer your question, so prompt it the way you would prompt a tool similar to yourself.
For example, assuming you have a resource named `codex`, you can ask questions like:
```bash
btca ask -r codex -q "What is the return format for Codex App Server responses? Are there any edge cases worth knowing?"
```
Your prompt may include specific names for resources to use, if they do then you should try those first. If you need to check available resources, you can use the `btca resources` command.
New resources can be created if the ones you need do not yet exist.
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.
## 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`][1] and registers typed listeners in [`wsNativeApi`][2].
2. The server accepts the connection in [`wsServer`][3] and brings up the runtime graph defined in [`serverLayers`][7].
3. [`ServerReadiness`][4] waits until the key startup barriers are complete.
4. Once the server is ready, [`wsServer`][3] sends `server.welcome` from the contracts in [`ws.ts`][6] through [`ServerPushBus`][5].
5. The browser receives that ordered push through [`WsTransport`][1], and [`wsNativeApi`][2] 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`][1] and the browser API layer in [`nativeApi`][12].
2. [`wsServer`][3] decodes that request using the shared WebSocket contracts in [`ws.ts`][6] 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`][3] pushes those updates to the browser through [`ServerPushBus`][5] 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`][3] and [`ServerPushBus`][5].
-`.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun 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 secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
This is a living glossary for T3 Code. It explains what common terms mean in this codebase.
## Table of contents
- [Project and workspace](#project-and-workspace)
- [Thread timeline](#thread-timeline)
- [Orchestration](#orchestration)
- [Provider runtime](#provider-runtime)
- [Checkpointing](#checkpointing)
## Concepts
### Project and workspace
#### 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].
#### Workspace root
The root filesystem path for a project. In [the orchestration model][1], it is the base directory for branches and optional worktrees. See [workspace-layout.md][2].
#### Worktree
A Git worktree used as an isolated workspace for a thread. If a thread has a `worktreePath` in [the contracts][1], it runs there instead of in the main working tree. Git operations live in [GitCore.ts][3].
### Thread timeline
#### Thread
The main durable unit of conversation and workspace history. In [the orchestration contracts][1], a thread holds messages, activities, checkpoints, and session-related state. See [projector.ts][4].
#### Turn
A single user-to-assistant work cycle inside a thread. It starts with user input and ends when follow-up work like checkpointing settles. See [the contracts][1], [ProviderRuntimeIngestion.ts][5], and [CheckpointReactor.ts][6].
#### Activity
A user-visible log item attached to a thread. In [the contracts][1], activities cover important non-message events like approvals, tool actions, and failures. They are projected into thread state in [projector.ts][4].
### Orchestration
Orchestration is the server-side domain layer that turns runtime activity into stable app state. The main entry point is [OrchestrationEngine.ts][7], with core logic in [decider.ts][8] and [projector.ts][4].
#### Aggregate
The domain object a command or event belongs to. In [the contracts][1], that is usually `project` or `thread`. See [decider.ts][8].
#### Command
A typed request to change domain state. In [the contracts][1], commands are validated in [commandInvariants.ts][9] and turned into events by [decider.ts][8].
Examples include `thread.create`, `thread.turn.start`, and `thread.checkpoint.revert`.
#### Domain Event
A persisted fact that something already happened. In [the contracts][1], events are the source of truth, and [projector.ts][4] shows how they are applied.
Examples include `thread.created`, `thread.message-sent`, and `thread.turn-diff-completed`.
#### Decider
The pure orchestration logic that turns commands plus current state into events. The core implementation is in [decider.ts][8], with preconditions in [commandInvariants.ts][9].
#### Projection
A read-optimized view derived from events. See [projector.ts][4], [ProjectionPipeline.ts][11], and [ProjectionSnapshotQuery.ts][10].
#### Projector
The logic that applies domain events to the read model or projection tables. See [projector.ts][4] and [ProjectionPipeline.ts][11].
#### Read model
The current materialized view of orchestration state. In [the contracts][1], it holds projects, threads, messages, activities, checkpoints, and session state. See [ProjectionSnapshotQuery.ts][10] and [OrchestrationEngine.ts][7].
#### Reactor
A side-effecting service that handles follow-up work after events or runtime signals. Examples include [CheckpointReactor.ts][6], [ProviderCommandReactor.ts][12], and [ProviderRuntimeIngestion.ts][5].
#### Receipt
A 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].
#### 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].
### 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].
#### Provider
The backend agent runtime that actually performs work. See [ProviderService.ts][14], [ProviderAdapter.ts][15], and [CodexAdapter.ts][17].
#### Session
The live provider-backed runtime attached to a thread. Session shape is in [the orchestration contracts][1], and lifecycle is managed in [ProviderService.ts][14].
#### Runtime mode
The safety/access mode for a thread or session. In [the contracts][1], the main values are `approval-required` and `full-access`. See [runtime-modes.md][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].
#### 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].
#### Snapshot
A point-in-time view of state. The word is used in multiple layers, including orchestration, provider, and checkpointing. See [ProjectionSnapshotQuery.ts][10], [ProviderAdapter.ts][15], and [CheckpointStore.ts][19].
### Checkpointing
Checkpointing captures workspace state over time so the app can diff turns and restore earlier points. The main pieces are [CheckpointStore.ts][19], [CheckpointDiffQuery.ts][20], and [CheckpointReactor.ts][6].
#### Checkpoint
A saved snapshot of a thread workspace at a particular turn. In practice it is a hidden Git ref in [CheckpointStore.ts][19] plus a projected summary from [ProjectionCheckpoints.ts][21]. Capture and lifecycle work happen in [CheckpointReactor.ts][6].
#### Checkpoint ref
The durable identifier for a filesystem checkpoint, stored as a Git ref. It is typed in [the contracts][1], constructed in [Utils.ts][22], and used by [CheckpointStore.ts][19].
#### Checkpoint baseline
The starting checkpoint for diffing a thread timeline. This flow is surfaced through [RuntimeReceiptBus.ts][13], coordinated in [CheckpointReactor.ts][6], and supported by [Utils.ts][22].
#### Checkpoint diff
The patch difference between two checkpoints. Query logic lives in [CheckpointDiffQuery.ts][20], diff parsing lives in [Diffs.ts][23], and finalization is coordinated by [CheckpointReactor.ts][6].
#### Turn diff
The file patch and changed-file summary for one turn. It is usually computed in [CheckpointDiffQuery.ts][20], represented in [the contracts][1], and recorded into thread state by [projector.ts][4].
## Practical Shortcuts
- 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 `checkpoint`, think "workspace snapshot for diff/restore".
- If you see `quiesced`, think "all relevant follow-up work has gone idle".
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`:
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:
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.
### 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.
### 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
### 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
### 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.
## 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.
### 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.
## 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.
## 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.
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.
-`bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
-`bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
-`bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --base-dir ~/.t3-2`
-`bun run start` — Runs the production server (serves built web app as static files).
-`bun run build` — Builds contracts, web app, and server through Turbo.
-`bun run typecheck` — Strict TypeScript checks for all packages.
-`bun run test` — Runs workspace tests.
-`bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
-`bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
-`bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
-`bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
-`bun 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/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://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: `bun run dist:desktop:dmg -- --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
-`/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.
This is the working checklist for remediation execution.
Status values:
-`TODO`: Not started
-`IN_PROGRESS`: Currently being worked
-`BLOCKED`: Waiting on decision/dependency
-`DONE`: Implemented and verified
-`CLOSED_INVALID`: Stale/invalid review finding
Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
## Active Checklist
### Phase 1
- [x]`C002` A dispatch error in `processEvent` will terminate the `Effect.forever` loop, permanently halting event ingestion. Consider adding error recovery (e.g., `Effect.catchAll` with logging) around `processEvent` so failures don't kill the fiber.
- Audit note: Ingestion worker loop can terminate on unhandled processEvent failure.
- [x]`C003` Consider attaching a no-op error listener before `socket.write` (e.g., `socket.on('error', () => {})`) to prevent an unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake.
- Status: `DONE`
- Verdict: `valid`
- Severity: `High`
- Area: `WebSocket robustness`
- File: `apps/server/src/wsServer.ts:75`
- Threads: PRRT_kwDORLtfbc5v-cf4
- Audit note: Upgrade reject writes then destroys socket without defensive error listener.
- [x]`C012` Forked revert dispatch risks read model inconsistency
- Audit note: SessionId-only routing can misassociate events under races/rebinds.
- [x]`C020` On `message.completed`, the message ID is added to the set and `thread.message.assistant.complete` is dispatched. On `turn.completed`, the same set is iterated and `thread.message.assistant.complete` is dispatched again for each ID—including already-completed ones. Consider removing message IDs from the set after dispatching on `message.completed`, or filtering out already-completed IDs before the `turn.completed` loop.
- [x]`C026` Consider adding `.catch(() => {})` after `Effect.runPromise(handleMessage(ws, raw))` to prevent unhandled rejections from crashing the server if `encodeResponse` or setup logic fails.
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `WebSocket robustness`
- File: `apps/server/src/wsServer.ts:545`
- Threads: PRRT_kwDORLtfbc5wj4cE
- Audit note: runPromise result still not caught; rejection can surface unhandled.
- [x]`C027` WS message handler can cause unhandled promise rejection
- Audit note: Errors are swallowed to empty diff with warning; not fully silent but still lossy.
- [x]`C045``truncateDetail` slices to `limit - 1` then appends `"..."` (3 chars), producing strings of length `limit + 2`. Consider slicing to `limit - 3` instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: truncateDetail still overshoots limit.
- [x]`C046``latestMessageIdByTurnKey` is written to but never read, and `clearAssistantMessageIdsForTurn` doesn't clear its entries—only `clearTurnStateForSession` does. Consider removing this map entirely if unused, or clearing it alongside `turnMessageIdsByTurnKey` in `clearAssistantMessageIdsForTurn`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: latestMessageIdByTurnKey still unused/unpruned in per-turn clear path.
- [x]`C053` Consider using `socket.end(response)` instead of `socket.write(response)` + `socket.destroy()` to ensure the HTTP error response is fully flushed before closing the connection.
- Status: `DONE`
- Verdict: `valid`
- Severity: `Low`
- Area: `WebSocket robustness`
- File: `apps/server/src/wsServer.ts:83`
- Threads: PRRT_kwDORLtfbc5v-WPD
- Audit note: Still uses write+destroy rather than end() for rejection response.
- [ ]`C054` When array chunks contain a multi-byte UTF-8 character split across boundaries, decoding each chunk separately produces replacement characters. Consider using `Buffer.concat()` on all chunks before calling `.toString("utf8")`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- [x]`C059` Suggestion: don’t spread `params` into `body`; it can override `_tag` and mishandle non-object values. Keep `_tag` separate and nest `params` under a single key (e.g., `data`), or validate `params` is a plain object.
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `WebSocket robustness`
- File: `apps/web/src/wsTransport.ts:59`
- Threads: PRRT_kwDORLtfbc5whtrN
- Audit note: Transport \_tag override risk exists but current callsites are constrained.
### Phase 2
- [x]`C001` Non-atomic event appending can corrupt state on retry. If an error occurs mid-loop (lines 96-102) after some events are persisted but before the receipt is written, the command appears to fail. A retry generates new UUIDs via `crypto.randomUUID()` in the decider, appending duplicate events. Consider wrapping the loop in a transaction or using deterministic event IDs derived from `commandId`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Append/project/receipt are non-atomic; retry can duplicate events.
- [x]`C013` If `projectionPipeline.projectEvent` fails after `eventStore.append` succeeds, the event is persisted but `readModel` isn't updated, causing desync. Consider updating the in-memory `readModel` immediately after append (before the external projection), so local state stays consistent regardless of downstream failures.
- Audit note: Persisted event can outpace in-memory projection on mid-flight failure.
- [x]`C015` The gap-filling fallback logic can retain messages from turns that are about to be deleted, causing foreign key violations. Consider removing the fallback logic entirely, or filtering `fallbackUserMessages` and `fallbackAssistantMessages` to only include messages whose `turnId` is in `retainedTurnIds`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Message fallback retention issue is real, but prior FK-violation claim is overstated.
- [x]`C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes _after_ the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Edge schema strategy is in place across contracts/consumers (trim/normalize via schemas and decode at boundaries); CheckpointStore remains an internal repository boundary.
- [x]`C017``REQUIRED_SNAPSHOT_PROJECTORS` includes `pending-approvals` and `thread-turns`, but `getSnapshot` doesn't query their data. If these projectors lag behind, the returned `snapshotSequence` will be lower than what the included data actually reflects, causing clients to replay already-applied events. Consider filtering `REQUIRED_SNAPSHOT_PROJECTORS` to only include projectors whose data is actually fetched in the snapshot. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: handledTurnStartKeys still grows without pruning.
### Phase 5
- [ ]`C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after `=>` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Braced rename parsing still breaks paths like src/{old => new}/file.ts.
- [ ]`C010``loadCustomKeybindingsConfig` fails when the config file doesn't exist, which is expected for new users. Consider catching `ENOENT` and returning an empty array instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/keybindings.ts:418`
- Threads: PRRT_kwDORLtfbc5wxvIJ
- Audit note: ENOENT for missing keybindings config still not handled as empty/default.
- [ ]`C022` Fish shell outputs `$PATH` as space-separated, not colon-separated. Consider checking if the shell is fish and using `string join : $PATH` instead, or validating the result contains colons before assigning.
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/os-jank.ts:10`
- Threads: PRRT_kwDORLtfbc5wkRZM
- Audit note: fish PATH formatting risk still exists in os-jank path recovery.
- [ ]`C023` Using `-il` flags causes the shell to source profile scripts that may print banners or other text, polluting the captured `PATH`. Consider using `-lc` (login only, non-interactive) to reduce unwanted output.
- [x]`C029``parseFileUrlHref` already decodes the path (line 46), but `safeDecode` is called again here, corrupting filenames containing `%` sequences. Consider skipping the decode when `fileUrlTarget` is non-null.
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/web/src/markdown-links.ts:105`
- Threads: PRRT_kwDORLtfbc5wnVsU
- Audit note: file URL decoding still double-decodes in one path.
- [x]`C030``EXTERNAL_SCHEME_PATTERN` matches `script.ts:10` as a scheme because `.ts:` looks like `scheme:`. Consider requiring `://` after the colon, or checking that what follows the colon is not just digits. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/web/src/markdown-links.ts:111`
- Threads: PRRT_kwDORLtfbc5wnVsK
- Audit note: Scheme regex still misclassifies script.ts:10 as external scheme.
- [ ]`C038` Multi-byte UTF-8 characters split across chunks will be corrupted when decoding each chunk separately. Consider accumulating all chunks first, then decoding once, or use `TextDecoder` with `stream: true`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Chunk-by-chunk UTF-8 decode can still corrupt split multibyte characters.
- [x]`C039` The `+` key can be parsed (via trailing `+` handling) but cannot be encoded because `shortcut.key.includes("+")` returns true for the literal `+` key. Consider checking `shortcut.key === "+"` separately and encoding it as `"space"` style (e.g., a special token), or adjusting the condition to allow the single `+` character. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/keybindings.ts:352`
- Threads: PRRT_kwDORLtfbc5wxvIB
- Audit note: Parser/encoder mismatch remains, but encoder path currently low-use.
- [x]`C040``upsertKeybindingRule` has a race condition: concurrent calls read the same file state, then the last write overwrites earlier changes. Consider wrapping the read-modify-write sequence with `Effect.Semaphore` to serialize access. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Optimistic local+server dual update is intentional but can temporarily diverge.
- [x]`C037``Effect.callback` should return a cleanup function to close the server(s) on fiber interruption. Without it, the `Net.Server` handles keep the process alive and leak the port if the effect is cancelled. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `Other`
- File: `apps/server/src/config.ts:41`
- Threads: PRRT_kwDORLtfbc5wj4cO
- Audit note: Callback cleanup missing, but practical exposure is low in one-shot startup path.
- [ ]`C047``SqlSchema.findOneOption` can produce both SQL errors and decode errors, but `mapError` wraps all as `PersistenceSqlError`. Consider distinguishing `ParseError` from SQL errors and mapping decode failures to `PersistenceDecodeError` instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Decode and SQL errors still collapsed into one persistence error kind.
- [x]`C049``JSON.stringify(cause)` returns `undefined` for `undefined`, functions, or symbols, violating the `string` return type. Consider coercing the result to a string (e.g., `String(JSON.stringify(cause))`) or adding a fallback.
- Audit note: JSON.stringify(cause) may return undefined despite string expectations.
- [ ]`C050` The read-modify-write pattern (`getBySessionId` → merge → `upsert`) is susceptible to lost updates under concurrent writes. Consider wrapping in a transaction or adding optimistic concurrency control (e.g., version field) if concurrent session updates are expected. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: ProviderSessionDirectory upsert remains read-merge-write without concurrency control.
- [x]`C051` Using `??` for `providerThreadId` and `adapterKey` makes it impossible to clear these fields by passing `null`, since `null ?? existing` evaluates to `existing`. Consider using explicit `undefined` checks (like `resumeCursor` does) if clearing should be supported. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Null-clearing issue is real for providerThreadId; adapterKey part overstated.
- [ ]`C052` Race condition: `processHandle` may be `null` when `data` callback fires, since it's assigned after `Bun.spawn` returns. Consider initializing `BunPtyProcess` first, then passing it to the callback to avoid losing initial output. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Data callback may race before processHandle assignment.
- [ ]`C056` When `onOpenChange` is provided without `open`, the internal `_open` state never updates because `setOpenProp` takes precedence. Consider calling `_setOpen` when `openProp === undefined`, regardless of whether `setOpenProp` exists.
- Audit note: Bug pattern exists, but current callsites mostly avoid triggering it.
- [ ]`C057` The `resizable` object is recreated on every render, causing `SidebarRail`'s `useEffect` to repeatedly read localStorage and update the DOM. Consider memoizing the object with `useMemo`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Resizable object recreation still retriggers effect/storage reads.
- [ ]`C058` When `localStorage.getItem()` returns `null`, `Number(null)` evaluates to `0`, which passes `Number.isFinite(0)`. This causes the sidebar to clamp to `minWidth` on first load, overriding the `DIFF_INLINE_DEFAULT_WIDTH` CSS clamp. Consider checking for `null` or empty string before parsing, e.g. guard with `storedWidth === null || storedWidth === ''`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Number(null) -> 0 path still forces min width on initial load.
- [ ]`C060``defaultModel` should be `Schema.optional(Schema.NullOr(Schema.String))` to allow clearing the value. Currently there's no way to reset it to `null` since omitting means "no change" in patch semantics. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Rationale: Broad catch is intentional for worker liveness; transactional dispatch path prevents the claimed non-invariant idempotency break in current design.
- [x]`C021` Shared mutable default metadata object causes stale eventId
# Plan: Claude Code Integration (Orchestration Architecture)
## Why this plan was rewritten
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
3.`resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
4.`ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
---
## Architecture target
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
Key decisions:
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
---
## Phase 1: Contracts and command shape updates
### 1.1 Provider-aware model contract
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
Expected outcomes:
1. Introduce provider-scoped model lists (Codex + Claude).
2. Add helpers that resolve model by provider.
3. Preserve backwards compatibility for existing Codex defaults.
### 1.2 Turn-start provider intent
Update `packages/contracts/src/orchestration.ts`:
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
2. Carry provider through `ThreadTurnStartRequestedPayload`.
3. Keep existing command valid when provider is omitted.
This removes the implicit “Codex unless session already exists” behavior as the only path.
### 1.3 Provider session start input for Claude runtime knobs (completed)
Update `packages/contracts/src/provider.ts`:
1. Move provider-specific start fields into typed `providerOptions`:
-`providerOptions.codex`
-`providerOptions.claudeCode`
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
3. Deprecate/remove `resumeThreadId` from the generic start contract.
4. Treat `resumeCursor` as adapter-owned opaque state.
### 1.4 Contract tests (completed)
Update/add tests in `packages/contracts/src/*.test.ts` for:
1. New command payload shape.
2. Provider-aware model resolution behavior.
3. Breaking-change expectations for removed top-level provider fields.
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
Initial mapping target:
1. assistant text deltas -> `content.delta`
2. final assistant text -> `item.completed` and/or `turn.completed`
3. approval requests -> `request.opened`
4. approval results -> `request.resolved`
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
6. errors -> `runtime.error`
7. plan/proposed-plan content when derivable
Implementation note:
1. Keep raw Claude message on `raw` for debugging.
2. Prefer canonical item/request kinds over provider-native enums.
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
### 2.4 Resume cursor strategy
Define Claude-owned opaque resume state, e.g.:
```ts
interfaceClaudeResumeCursor{
readonlyversion: 1;
readonlythreadId?: string;
readonlysessionAt?: string;
}
```
Rules:
1. Serialize only adapter-owned state into `resumeCursor`.
2. Parse/validate only inside Claude adapter.
3. Store updated cursor when Claude runtime yields enough data to resume safely.
4. Never overload orchestration thread id as Claude thread id.
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
2. If a thread already has Claude session binding, reuse it.
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
---
## Phase 4: Checkpoint and revert strategy
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
Pick one explicit strategy:
### Option A: provider-native rewind
If SDK/runtime supports safe rewind:
1. implement in Claude adapter
2. keep `CheckpointReactor` unchanged
### Option B: session restart + state truncation shim
If no native rewind exists:
1. Claude adapter returns successful rollback by:
- stopping current Claude session
- clearing/rewriting stored Claude resume cursor to last safe resumable point
- forcing next turn to recreate session from persisted orchestration state
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
Whichever option is chosen:
1. behavior must be deterministic
2. checkpoint revert tests must pass under orchestration expectations
3. user-visible activity log should explain failures clearly when provider rollback is impossible
---
## Phase 5: Web integration
### 5.1 Provider picker and model picker
Update web state/UI:
1. allow choosing Claude as thread provider before first turn
2. show Claude model list from provider-aware model helpers
3. preserve existing Codex default behavior when provider omitted
Likely touch points:
1.`apps/web/src/store.ts`
2.`apps/web/src/components/ChatView.tsx`
3.`apps/web/src/types.ts`
4.`packages/shared/src/model.ts`
### 5.2 Settings for Claude executable/options
Add app settings if needed for:
1. Claude binary path
2. default permission mode
3. default max thinking tokens
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
### 5.3 Session rendering
No new WS channel should be needed. Claude should appear through existing:
1. thread messages
2. activities/worklog
3. approvals
4. session state
5. checkpoints/diffs
---
## Phase 6: Testing strategy
### 6.1 Contract tests
Cover:
1. provider-aware model schemas
2. provider field on turn-start command
3. provider-specific start options schema
### 6.2 Adapter layer tests
Add `ClaudeAdapter.test.ts` covering:
1. session start
2. event mapping
3. approval bridge
4. resume cursor parse/serialize
5. interrupt behavior
6. rollback behavior or explicit unsupported error path
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
### 6.3 Provider service integration tests
Extend provider integration coverage so Claude is exercised through `ProviderService`:
1. start Claude session
2. send turn
3. receive canonical runtime events
4. restart/recover using persisted binding
### 6.4 Orchestration integration tests
Add/extend integration tests around:
1. first-turn provider selection
2. Claude approval requests routed through orchestration
3. Claude runtime ingestion -> messages/activities/session updates
4. checkpoint revert behavior under Claude
5. stopAll/restart recovery
These should validate real orchestration flows, not just adapter behavior.
# Plan: Provider-Neutral Runtime Determinism and Flake Elimination
## Summary
Replace timing-sensitive websocket and orchestration behavior with explicit typed runtime boundaries, ordered push delivery, and server-owned completion receipts. The cutover is broad and single-shot: no compatibility shim, no mixed old/new transport. The design must reduce flakes without baking Codex-specific lifecycle semantics into generic runtime code.
## Implementation Status
All 7 sections are implemented. CI passes (format, lint, typecheck, test, browser test, build). One deferred item remains: the shared `WsTestClient` helper from section 7 — tests use direct transport subscription and receipt-based waits instead.
### New files
| File | Purpose |
|------|---------|
| `packages/shared/src/DrainableWorker.ts` | Queue-based Effect worker with deterministic `drain` signal |
-`packages/contracts/src/ws.ts` now derives push messages from a `WsPushPayloadByChannel` channel-to-schema map. `WsPush` is a union schema replacing `channel: string` + `data: unknown`.
- Every server push carries `sequence: number`, auto-incremented in `ServerPushBus`.
-`packages/shared/src/schemaJson.ts` provides structured decode diagnostics via `formatSchemaError`.
-`packages/contracts/src/ws.test.ts` covers typed push envelope validation and channel/payload mismatch rejection.
### 3. Introduce explicit server readiness and a single push pipeline — DONE
-`apps/server/src/wsServer/pushBus.ts`: `ServerPushBus` with `publishAll` (broadcast) and `publishClient` (targeted) methods, backed by one ordered path. All pushes flow through it.
-`apps/server/src/wsServer/readiness.ts`: `ServerReadiness` with Deferred-based barriers for HTTP listening, push bus, keybindings, terminal subscriptions, and orchestration subscriptions.
-`server.welcome` is emitted only after connection-scoped and server-scoped readiness is complete.
-`wsServer.ts` no longer publishes directly from ad hoc background streams.
### 4. Turn background watchers into explicit runtimes — DONE
-`apps/server/src/keybindings.ts` refactored as explicit `KeybindingsShape` service with `start`, `ready`, `snapshot` semantics.
- Initial config load, cache warmup, and dual watcher attachment (`fs.watch` + `watchFileWithStatPolling`) complete before `ready` resolves.
-`watchFileWithStatPolling.ts` is the thin adapter for environments where `fs.watch` is unreliable.
### 5. Replace polling-based orchestration waiting with receipts — DONE
-`RuntimeReceiptBus` service defines three receipt types: `CheckpointBaselineCapturedReceipt`, `CheckpointDiffFinalizedReceipt` (with `status: "ready"|"missing"|"error"`), and `TurnProcessingQuiescedReceipt`.
-`CheckpointReactor`, `ProviderCommandReactor`, and `ProviderRuntimeIngestion` use `DrainableWorker` and publish receipts on completion.
- Integration harness and checkpoint tests await receipts instead of polling snapshots and git refs.
### 6. Centralize client transport state and decoding — DONE
-`apps/web/src/wsTransport.ts` implements an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
- Two-phase decode (JSON parse → Schema validate) happens at the transport boundary. `wsNativeApi.ts` receives pre-validated messages.
- Cached latest welcome/config modeled as explicit `latestPushByChannel` state.
### 7. Replace ad hoc test helpers with semantic test clients — MOSTLY DONE
-`DrainableWorker` replaces timing-sensitive `Effect.sleep` with deterministic `drain()` across reactor tests.
- Orchestration harness waits on receipts/barriers instead of `waitForThread`, `waitForGitRef`, and retry loops.
- Behavioral assertions moved to deterministic unit-style harnesses; narrow integration tests kept for real filesystem/socket behavior.
- **Deferred:** Shared `WsTestClient` helper (connect, awaitSemanticWelcome, awaitTypedPush, trackSequence, matchRpcResponseById). Tests use direct transport subscription instead.
## Provider-Coupling Guardrails
- No generic runtime API may depend on Codex-native event names, thread IDs, or request payload shapes.
- No readiness barrier may be defined as "Codex has emitted X." Readiness is owned by the server runtime, not by provider event order.
- No websocket channel payload may contain raw provider-native payloads unless the channel is explicitly debug/internal.
- Any provider-specific divergence must be exposed through provider capabilities from `ProviderService.getCapabilities()`, not `if provider === "codex"` branches in shared runtime code.
- Generic tests must use canonical `ProviderRuntimeEvent` fixtures. Codex-specific ordering and translation tests stay in adapter/app-server suites only.
- Keep UI/provider-specific knobs such as Codex-only options scoped to provider UX code. Do not pull them into generic transport or orchestration state.
## Test Plan
- Contracts:
- schema tests for typed push envelopes and structured decode diagnostics
Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
## Primary goals
- Make auth server-wide, not WebSocket-only.
- Make insecure exposure hard to do accidentally.
- Preserve zero-login local desktop UX for desktop-managed environments.
- Support browser-native pairing and session auth.
- Leave room for native/mobile credentials later without rewriting the server boundary.
- Keep auth separate from transport and launch method.
## Non-goals
- Full multi-user authorization and RBAC.
- OAuth / SSO / enterprise identity.
- Passkeys or biometric UX in v1.
- Syncing auth state across environments.
- Designing the full remote environment product in this document.
## Core decisions
### 1. Auth is a server concern
Every privileged surface of the T3 server must go through the same auth policy engine:
- HTTP routes
- WebSocket upgrades
- RPC methods reached through WebSocket
The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
### 2. Pairing and session are different things
The system should distinguish:
- bootstrap credentials
- session credentials
Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
Session credentials are the durable credentials used after pairing.
Bootstrap should never become the long-lived request credential.
### 3. Auth and transport are separate
Auth must not be defined by how the client reached the server.
Examples:
- local desktop-managed server
- LAN `ws://`
- public `wss://`
- tunneled `wss://`
- SSH-forwarded `ws://127.0.0.1:<port>`
All of these should feed into the same auth model.
### 4. Exposure level changes defaults
The more exposed an environment is, the narrower the safe default should be.
The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it.
## Sequence diagrams
These flows are meant to anchor the auth model in concrete user journeys.
The important invariant across all of them is:
- access method is not the auth method
- launch method is not the auth method
- bootstrap credential is not the session credential
### Normal desktop user
This is the default desktop-managed local flow.
The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie.
PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
PrivateNet -> T3Server : websocket upgrade
T3Server --> PhoneBrowser : websocket accepted
```
### Desktop user adding new SSH hosts
SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment.
```text
Participants:
DesktopUser = local desktop user
DesktopMain = desktop app
SSH = ssh transport/session
RemoteHost = remote machine
RemoteT3 = remote T3 server
Frontend = desktop renderer
DesktopUser -> DesktopMain : add SSH host
DesktopMain -> SSH : connect to remote host
SSH -> RemoteHost : probe environment / verify t3 availability
DesktopMain -> SSH : run remote launch command
SSH -> RemoteHost : t3 remote launch --json
RemoteHost -> RemoteT3 : start or reuse server
RemoteT3 --> RemoteHost : port + environment metadata
note over RemoteT3 : policy = RemoteReachablePolicy
note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
Frontend -> DesktopMain : request bootstrap for selected environment
DesktopMain --> Frontend : short-lived bootstrap grant
Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
RemoteT3 -> RemoteT3 : validate bootstrap grant
RemoteT3 -> RemoteT3 : create browser session
RemoteT3 --> Frontend : Set-Cookie: session=...
Frontend -> RemoteT3 : GET /ws + authenticated cookie
RemoteT3 --> Frontend : websocket accepted
```
## Storage decisions
### Server secrets
Use a `ServerSecretStore` abstraction.
Preferred order (use a layer for each, resolve on startup):
1. OS secure storage if available
2. hardened filesystem fallback if not
The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials.
### Client credentials
Client-side credential persistence should prefer secure storage when available:
- desktop: OS keychain / secure store
- mobile: platform secure storage
- browser: cookie session for browser auth
This concern should stay in the client shell/runtime layer, not the server auth layer.
## What to build now
These are the parts worth building before remote environments ship:
1.`ServerAuth` service boundary.
2. route classification and route guards.
3.`ServerSecretStore` abstraction.
4. bootstrap vs session credential split.
5. browser session cookie codec as one session method.
6. explicit auth capabilities/config surfaced in contracts.
Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained.
## What to add as part of first remote-capable auth
1. Browser pairing flow using one-time bootstrap token and cookie session.
2. Desktop-managed auto-bootstrap for the local desktop-managed environment.
3. Auth-required defaults for any non-loopback or explicitly published server.
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
- Keep Zustand for orchestration read model and UI state.
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
## Target Architecture
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
## Phase 1: Infrastructure First
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
2. Build the AtomRpc client on top of that layer.
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
5. Land this as a no-behavior-change PR.
## Phase 2: Replace `wsNativeApi`-Owned Push State
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
6. Defer the desktop updater until the last phase.
## Phase 4: Move Root Invalidation Off `queryClient`
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
- config-affecting server events touch `server-config`
## Phase 5: Remove Imperative `NativeApi` Usage
1. Create narrow modules instead of a replacement mega-facade:
-`rpc/orchestrationActions.ts`
-`rpc/terminalActions.ts`
-`rpc/gitActions.ts`
-`rpc/projectActions.ts`
-`platform/desktopBridge.ts`
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
## Phase 6: Remove React Query Completely
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
4. Delete the old query-option tests.
## Public Interfaces And Types
- Preserve the current server-state hook names during the transition.
- Do not expose raw AtomRpc clients to components.
- Do not add Suspense as part of this migration.
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
## Test Plan
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
- Acceptance scenarios:
- welcome still bootstraps snapshot and navigation
- keybindings toast still responds to config stream updates
- git status/branches refresh after checkout/pull/worktree actions
- PR resolve dialog keeps cached result while typing
-`@` path search refreshes after file mutations and orchestration events
- diff panel refreshes when checkpoints arrive
- desktop updater still reflects push events and button actions
## Assumptions And Defaults
- Zustand stays in scope; only `react-query` is being removed.
-`desktopBridge` remains the only non-RPC boundary.
- The migration lands as 5-6 small PRs, each green independently.
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
- Topic: `orchestration_events.stream_id` vs event runtime `aggregateId` naming.
- Decision: persist canonical DB column name `stream_id`; map to runtime `aggregateId` where needed in decider/projector code.
### A2
- Topic: JSON column typing in SQLite for `payload`, `metadata`, projection payload/files, runtime cursor/payload.
- Decision: store as `TEXT` JSON with strict encode/decode schemas at boundaries.
### A3
- Topic: `snapshotSequence` dependency set for min-sequence computation.
- Decision: include all projectors used to construct snapshot payload (`projects`, `threads`, `messages`, `activities`, `sessions`, `turns`, `checkpoints`, `pending_approvals`).
### A4
- Topic: no-gap handoff mechanism in `7.4.7`.
- Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`.
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
## Project Snapshot
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
@@ -14,11 +19,16 @@ This repository is a VERY EARLY WIP. Proposing sweeping changes that improve lon
If a tradeoff is required, choose correctness and robustness over short-term convenience.
## Maintainability
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
## Package Roles
-`apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
-`apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
-`packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
-`packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
-`packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
## Codex App Server (Important)
@@ -29,7 +39,7 @@ How we use it in this codebase:
- Session startup/resume and turn lifecycle are brokered in `apps/server/src/codexAppServerManager.ts`.
- Provider dispatch and thread event logging are coordinated in `apps/server/src/providerManager.ts`.
- WebSocket server routes NativeApi methods in `apps/server/src/wsServer.ts`.
- Web app consumes provider event streams via WebSocket push on channel `providers.event`.
- Web app consumes orchestration domain events via WebSocket push on channel `orchestration.domainEvent` (provider runtime activity is projected into orchestration events server-side).
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
Run `npx t3` in any project directory to launch the web interface.
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
## Installation
## Architecture
> [!WARNING]
> T3 Code currently supports Codex and Claude.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
> - Claude: install Claude Code and run `claude auth login`
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) │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
## 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 Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## 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.
## Quick start
### Run without installing
```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
# Or from any project directory after publishing:
npx t3
```
## Scripts
### Desktop app
-`bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
-`bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
-`bun run dev:web` — Starts just the Vite dev server for the web app.
-`bun run start` — Runs the production server (serves built web app as static files).
-`bun run build` — Builds contracts, web app, and server through Turbo.
-`bun run typecheck` — Strict TypeScript checks for all packages.
-`bun run test` — Runs workspace tests.
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
### Running multiple dev instances
#### Windows (`winget`)
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
```bash
winget install T3Tools.T3Code
```
- Default ports: server `3773`, web `5173`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
#### macOS (Homebrew)
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
```bash
brew install --cask t3-code
```
## Runtime modes
#### Arch Linux (AUR)
T3 Code has a global runtime mode switch in the chat toolbar:
```bash
yay -S t3code-bin
```
- **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.
## Some notes
## Provider architecture
We are very very early in this project. Expect bugs.
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
We are not accepting contributions yet.
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for streaming provider events
Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
## Recommended Setup
Use a trusted private network that meshes your devices together, such as a tailnet.
That gives you:
- a stable address to connect to
- transport security at the network layer
- less exposure than opening the server to the public internet
## Enabling Network Access
There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
### 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.
3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
4. Use **Create Link** to generate a pairing link you can share with another device.
### Option 2: Headless Server (CLI)
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
Run the server with `t3 serve`.
```bash
npx t3 serve --host "$(tailscale ip -4)"
```
`t3 serve` starts the server without opening a browser and prints:
- a connection string
- a pairing token
- a pairing URL
- a QR code for the pairing URL
From there, connect from another device in either of these ways:
- scan the QR code on your phone
- in the desktop app, enter the full pairing URL
- in the desktop app, enter the host and token separately
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
> 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.
## How Pairing Works
The remote device does not need a long-lived secret up front.
Instead:
1.`t3 serve` issues a one-time owner pairing token.
2. The remote device exchanges that token with the server.
3. The server creates an authenticated session for that device.
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
## Managing Access Later
Use `t3 auth` to manage access after the initial pairing flow.
Typical uses:
- issue additional pairing credentials
- inspect active sessions
- revoke old pairing links or sessions
Use `t3 auth --help` and the nested subcommand help pages for the full reference.
## Security Notes
- Treat pairing URLs and pairing tokens like passwords.
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
Loaded 100 of 804 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.