Compare commits

..
Author SHA1 Message Date
Julius Marminge 42b2a881b0 Fix ChatView height scroll 2026-02-11 18:08:34 -08:00
Julius Marmingeandcodex e4c1729ab3 Address PR review comments for terminal integration
Co-authored-by: codex <[email protected]>
2026-02-11 17:57:47 -08:00
Julius Marminge c561a86997 Improve terminal resizing and perf 2026-02-11 17:35:54 -08:00
Julius Marminge 16b81f7268 Merge pull request #3 from pingdotgg/juliusmarminge/git-integration 2026-02-11 15:53:31 -08:00
Julius MarmingeandClaude Opus 4.6 9442019235 Filter out stale worktree paths from branch listing
Worktrees in /tmp or other ephemeral locations get cleaned by the OS
but remain in git's worktree list as "prunable". These stale entries
caused branches to show a worktree label pointing at a non-existent
directory, leading to broken state when selected.

Now validates each worktree path with existsSync before including it
in the branch→worktreePath map.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 15:48:41 -08:00
Julius MarmingeandClaude Opus 4.6 cf66f53a55 Fix flash of 'Initialize git' when switching branch/worktree
branchesQuery.data is undefined while loading, so isRepo defaulted to
false — briefly showing the init button even for worktrees. Now defaults
to true while loading (only shows init when the query actually returns
isRepo: false).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 15:41:27 -08:00
Julius MarmingeandClaude Opus 4.6 d6ecf15805 Fix worktree→local branch switch causing 'already used by worktree' error
When in a secondary worktree and selecting a branch checked out in the
main worktree (e.g. main), the code skipped the worktree redirect
(because worktreePath === project.cwd) and tried git checkout, which
git rejected.

Now any branch with a worktreePath is handled as a redirect — main
worktree redirects to local (worktreePath=null), secondary worktrees
redirect to their path.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 15:36:11 -08:00
Julius MarmingeandClaude Opus 4.6 5b7af7b9f6 Fix session not restarting when switching to a worktree branch
When selecting a branch that lives in a different worktree, the store
updated the thread's worktreePath but the running session kept its
original cwd. The agent continued operating in the old directory.

- SET_THREAD_BRANCH now clears the session when worktreePath changes
- BranchToolbar stops the server-side session before dispatching the
  branch change, so the next message creates a fresh session with the
  correct cwd

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 15:33:01 -08:00
Julius MarmingeandClaude Opus 4.6 8324949b54 Enrich branches with worktree paths, fix toolbar display, and improve HMR config
- Add worktreePath to gitBranchSchema and populate from `git worktree list --porcelain`
- Redirect to existing worktree when selecting a branch that's already checked out
  (instead of failing with "already used by worktree")
- Distinguish main worktree (project cwd) from secondary worktrees in selection logic
- Fix toolbar to show three states: Local, Worktree (existing), New worktree (pending)
- Add explicit protocol/host to Vite HMR config for reliable Electron WebSocket
- Auto-open DevTools in dev mode for HMR debugging

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 15:22:17 -08:00
Julius MarmingeandClaude Opus 4.6 807e3d18de Add react-query, refactor BranchToolbar async state, and fix stale deps
- Add @tanstack/react-query and wire up QueryClientProvider in App.tsx
- Refactor BranchToolbar to use useQuery for branch listing and
  useMutation for checkout, create branch, and git init, replacing
  manual useState/useCallback/useEffect async patterns
- Fix branch sync effect and ChatView envMode effect to use stable
  primitive deps instead of full object references, preventing
  unnecessary re-runs on unrelated store dispatches

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 14:26:24 -08:00
Julius MarmingeandClaude Opus 4.6 198cc58377 Fix envMode reset bug and use shell-free git spawn
- ChatView: change useEffect dependency from [activeThread] (new object
  ref every dispatch) to [activeThread?.id, activeThread?.worktreePath]
  so envMode is no longer silently reset to "local" on unrelated store
  dispatches, making the worktree code path reachable.

- git.ts: replace shell command strings (runTerminalCommand + single-quote
  escaping) with a runGit helper that spawns git directly via argv array.
  Eliminates Windows quoting issues and the command injection surface.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 14:15:30 -08:00
Julius Marminge 6e3726ec32 Merge remote-tracking branch 'origin/main' into juliusmarminge/git-integration
# Conflicts:
#	apps/web/src/store.ts
#	apps/web/src/wsNativeApi.ts
#	packages/contracts/src/ipc.ts
2026-02-11 13:47:30 -08:00
Julius MarmingeandClaude Haiku 4.5 169d06f05b Add context menu to delete threads from sidebar
Adds right-click → Delete on sidebar thread items using Electron's
native Menu.popup() when running in desktop, with an imperative DOM
fallback for browser environments. The contextMenu.show() API is
generic so the returned item id is type-safe based on the items passed.

Co-Authored-By: Claude Haiku 4.5 <[email protected]>
2026-02-11 13:36:32 -08:00
Julius MarmingeandClaude Opus 4.6 7e5cd01d26 Polish turbo task graph and dev scripts
- Switch from turbo watch to turbo run --parallel for dev scripts
- Simplify contracts exports to use ./src/index.ts for types directly
- Add --watch --clean to contracts dev script
- Root dev task depends on contracts#build, is persistent
- Revert typecheck to depend on ^typecheck (contracts types from source)
- Remove redundant server dev task override
- Desktop dev depends only on t3#build (contracts implied)
- Uncomment server dist wait in dev-electron.mjs

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 12:54:19 -08:00
Julius MarmingeandClaude Opus 4.6 01c3e8266b Suppress tsdown inlineOnly warning for server build
tsdown escalates warnings to errors when CI=true. Adding
inlineOnly: false suppresses the bundled-dependency warning
since we intentionally inline contracts and zod.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 12:36:52 -08:00
Julius MarmingeandClaude Opus 4.6 ca356d0edb Fix server build: add zod to noExternal to prevent tsdown error
tsdown v0.20.3 errors when it detects undeclared dependencies in the
bundle. Since @t3tools/contracts (already in noExternal) transitively
pulls in zod, explicitly declare it to avoid the build failure.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 12:33:27 -08:00
Julius Marminge ceceba279f fix 2026-02-11 12:28:51 -08:00
Julius MarmingeandClaude Opus 4.6 e2052b8ae2 Fix dev:desktop task graph to match main's env var patterns
- Remove --filter=t3 from dev:desktop since electron spawns its own
  server from dist/index.mjs (running server via turbo would conflict)
- Add t3#build and contracts#build as dependencies of desktop dev task
  so the server is built before electron starts

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 12:15:59 -08:00
Julius MarmingeandClaude Opus 4.6 4ab095fd91 Fix CI typecheck: build contracts before typechecking dependents
- Change turbo typecheck task to dependsOn: ["^build"] so the contracts
  package generates .d.cts/.d.mts declaration files before downstream
  packages run tsc
- Revert contracts types back to generated declaration files
- Remove unused useGitState.ts that imported missing @tanstack/react-query

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 12:08:24 -08:00
Julius MarmingeandClaude Opus 4.6 74f6ce8600 Fix CI typecheck: point contracts types to source and remove dead code
- Point @t3tools/contracts type exports to ./src/index.ts instead of
  generated .d.cts/.d.mts files that only exist after build
- Remove unused useGitState.ts that imported missing @tanstack/react-query

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 12:06:58 -08:00
Julius MarmingeandClaude Opus 4.6 d6437a7e13 Move toolbar below chat input, fix electron preload bundling, and update build configs
- Move BranchToolbar below the chat input box to match Codex app layout
- Change worktree path to ~/.t3code/worktrees/{repo}/{branch}
- Split desktop tsdown config into separate main/preload builds to prevent
  code-splitting from leaking node:os into the sandboxed preload script
- Migrate turbo scripts to turbo watch, add desktop start/smoke-test tasks
- Update server output to .mjs, add CJS format, remove tsx dependency

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 11:44:24 -08:00
Julius Marminge 9fc5ad2083 plans 2026-02-11 09:00:18 -08:00
Julius Marminge 79ac59f04e eh 2026-02-11 09:00:18 -08:00
Julius Marmingeandcodex c13e9f89a9 Restore git toolbar via websocket backend
Co-authored-by: codex <[email protected]>
2026-02-11 09:00:18 -08:00
Julius Marmingeandcodex d1ecacda43 Polish git worktree helpers after rebase
Co-authored-by: codex <[email protected]>
2026-02-11 09:00:18 -08:00
Julius MarmingeandClaude Opus 4.6 647449069d Add test for listGitBranches from worktree cwd
Verifies that querying branches from a worktree directory correctly
reports the worktree's branch as current, while the main repo still
shows its own branch — the assumption the BranchToolbar fix relies on.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 09:00:18 -08:00
Julius MarmingeandClaude Opus 4.6 6ce773ff1e Fix branch query cwd for worktree threads and error banner light mode
Use worktree path instead of project cwd for git branch queries so
worktree threads correctly report their branch as current. Also update
error banner to use semantic color tokens for light mode support.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 09:00:18 -08:00
Julius MarmingeandClaude Opus 4.6 c5cbe15993 Fix "Open in editor" to respect worktree path
Both openInEditor and the Cmd+O shortcut now use the thread's
worktreePath when available instead of always using activeProject.cwd.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 09:00:18 -08:00
Julius Marminge 2a610f92b9 kewl 2026-02-11 09:00:18 -08:00
Julius Marminge 7e201486f1 resource management 2026-02-11 09:00:18 -08:00
Julius MarmingeandClaude Opus 4.6 f47dc3c78c Extract git functions and add integration tests
Move git operations (listGitBranches, checkoutGitBranch, createGitWorktree,
etc.) from main.ts into git.ts for testability. Add 20 integration tests
that run real git commands against temporary repos covering checkout,
branch creation, worktrees, conflicts, and thread-switching flows.

Also fix: branch checkout now runs regardless of envMode, worktree
creation passes cwd to ensureSession to avoid stale closure bug, and
current branch auto-fills on new threads.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 09:00:18 -08:00
Julius MarmingeandClaude Opus 4.6 e9cfe372bf Add light mode support for git branch picker and default branch label
Replace hardcoded dark-mode colors with theme-aware semantic classes
(bg-popover, text-foreground, bg-accent, etc.) so the branch picker
works in both light and dark mode. Detect the real default branch via
git symbolic-ref and show a "default" label (with "current" taking
precedence when both apply).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 09:00:18 -08:00
Julius MarmingeandClaude Opus 4.6 82253525f2 Add branch/worktreePath to persistence test expectation
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 09:00:18 -08:00
Julius MarmingeandClaude Opus 4.6 69e38a25c3 Fix typecheck errors for branch/worktree fields
Add non-null assertion for activeProject in worktree creation path
(guarded by earlier check) and add missing branch/worktreePath to
test fixture.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 09:00:18 -08:00
Julius MarmingeandClaude Opus 4.6 59448593d8 Add git checkout support and clear errors on success
Wire up git:checkout IPC channel across the full stack so branch
selection actually checks out the branch. Clear error banners when
a subsequent checkout or branch creation succeeds.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 09:00:18 -08:00
Julius MarmingeandClaude Opus 4.6 3047974fdc Add branch/env picker toolbar and create branch flow
Move branch picking from sidebar context menu into ChatView input
toolbar. Add env mode toggle (local/worktree) that locks after first
message, branch dropdown with create-new-branch inline form, and
wire up git:create-branch IPC channel.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-02-11 09:00:18 -08:00
Julius MarmingeandClaude Haiku 4.5 d64f78a949 Add git integration: branch picker + worktrees
Allows users to right-click "+ New thread" to create threads from specific git branches, with optional worktree creation for isolated work. Includes branch sorting (current/default first), graceful handling of non-git repos, and ability to initialize git repos.

- New git IPC contract (listBranches, createWorktree, removeWorktree, init)
- Branch context menu with worktree sub-option in Sidebar
- Thread model extended with branch/worktreePath fields
- Session cwd uses worktree path when available
- Branch sorting: current > main/master > alphabetical

Co-Authored-By: Claude Haiku 4.5 <[email protected]>
2026-02-11 09:00:18 -08:00
Theo Browne 9023d13929 todo 2026-02-10 01:41:53 -08:00
Theo Browne 5120f7fec7 renames 2026-02-09 22:19:49 -08:00
Theo Browne b5bab3eb13 rebrand 2026-02-09 22:19:49 -08:00
8ebd2479cf bring back electron (+ websocket/package changes) (#10)
* feat: scaffold apps/server package and WebSocket protocol types

- Create apps/server with package.json, tsconfig, tsup config
- Copy codexAppServerManager, providerManager, fixPath from desktop (no Electron deps)
- Add WebSocket message protocol schemas (WsRequest, WsResponse, WsPush) to @acme/contracts
- Define WS_METHODS and WS_CHANNELS constants for type-safe routing

Co-authored-by: Theo Browne <[email protected]>

* feat: implement WebSocket + HTTP server and CLI entry point

- wsServer.ts: WebSocket server routes NativeApi methods, serves static files
  - Provider events pushed to all connected clients
  - SPA fallback for client-side routing
  - Server welcome message with cwd/projectName on connect
- index.ts: CLI entry point
  - Auto-detects available port (default 3773)
  - Resolves renderer dist for static serving
  - Opens browser on startup via 'open' package
  - Graceful shutdown on SIGINT/SIGTERM

Co-authored-by: Theo Browne <[email protected]>

* feat: WebSocket transport and NativeApi implementation for browser

- wsTransport.ts: WebSocket client with request/response, push subscriptions,
  auto-reconnect with exponential backoff
- wsNativeApi.ts: Full NativeApi implementation over WebSocket transport
  - All provider methods routed through WS_METHODS
  - Provider events streamed via WS_CHANNELS.providerEvent
  - Todos/terminal/agent stubbed (not needed for web mode)
  - dialogs.pickFolder returns null (text input fallback in UI)
- session-logic.ts: readNativeApi() now auto-detects environment
  - Prefers Electron preload bridge if available (window.nativeApi)
  - Falls back to WebSocket transport for browser mode
- onServerWelcome() hook for renderer to receive cwd on connect

Co-authored-by: Theo Browne <[email protected]>

* feat: adapt renderer for browser mode

- App.tsx: Add AutoProjectBootstrap that listens for server welcome
  and auto-creates project + thread from server's cwd
- Sidebar: Conditionalize drag region (Electron only), hide Browse button in browser
- ChatView: Conditionalize drag region, adjust padding for browser
- DiffPanel: Same drag region treatment
- index.html: Update title to 'CodeThing'
- env.ts: isElectron detection utility

Co-authored-by: Theo Browne <[email protected]>

* feat: monorepo & CLI integration

- Root package.json: Add dev, dev:server, dev:web, start scripts
  - dev runs both server and renderer in parallel via turbo
  - VITE_WS_URL injected so renderer connects to server in dev mode
- turbo.json: Add WS env vars to globalEnv
- vite.config.ts: Inject VITE_WS_URL at build time for WS server discovery
- wsTransport.ts: Use VITE_WS_URL env var in dev, fall back to page URL in prod
- Server dev script: Uses tsx for direct TypeScript execution with VITE_DEV_SERVER_URL

Co-authored-by: Theo Browne <[email protected]>

* feat: remove Electron desktop app, clean up contracts and docs

- Delete apps/desktop/ entirely (replaced by apps/server)
- Remove IPC_CHANNELS constant from contracts (no longer needed)
- Keep NativeApi interface (still the renderer's API contract)
- Keep EDITORS constant (used by both server and renderer)
- Update README.md with new architecture diagram and scripts
- Update AGENTS.md with new package roles and architecture

Co-authored-by: Theo Browne <[email protected]>

* test: add WebSocket server integration tests

- Tests welcome message on connect with cwd/projectName
- Tests server.getConfig method
- Tests providers.listSessions returns empty array
- Tests error response for unknown methods
- Tests graceful handling of invalid JSON
- All 73 tests pass across 12 test files

Co-authored-by: Theo Browne <[email protected]>

* fix: address lint warnings in new files

- wsTransport.ts: Use addEventListener instead of on-function assignments
- wsServer.ts: Replace filter(Boolean).pop() with direct array access
- wsServer.test.ts: Use addEventListener for WebSocket events

Co-authored-by: Theo Browne <[email protected]>

* fix: race condition in auto-project bootstrap + cleanup

- wsNativeApi: Cache last welcome payload and replay to late subscribers.
  Fixes race where WS connect + welcome arrives before React effect fires.
- App.tsx: Add bootstrappedRef to prevent duplicate project creation,
  skip bootstrap in Electron mode
- wsTransport: Use standard import.meta.env for VITE_WS_URL access
- CLAUDE.md: Fix header (was incorrectly '# AGENTS.md')

Co-authored-by: Theo Browne <[email protected]>

* fix: use tsx command directly in server dev script

Use 'tsx src/index.ts' instead of 'node --import tsx' for simpler dev execution

Co-authored-by: Theo Browne <[email protected]>

* chore: clean up stale Electron references and config

- Remove smoke-test script (was desktop-only)
- Remove dist-electron from turbo outputs and .gitignore
- Rename ELECTRON_RENDERER_PORT → PORT in vite.config.ts
- Clean up turbo globalEnv (remove ELECTRON_RENDERER_PORT, WS_SERVER_PORT)
- Update CI workflow to use bun 1.3.9 (matches package.json engines)

Co-authored-by: Theo Browne <[email protected]>

* feat: make t3 package publishable for npx

- Remove private:true so package can be published to npm
- Add files field to limit published files to dist/
- Move @acme/contracts to devDependencies (bundled by tsup)
- Add @acme/renderer devDependency for turbo build ordering
- Add bundle-client.mjs: copies renderer build into dist/client/
- Update resolveStaticDir to check dist/client/ first (npx scenario),
  then fall back to monorepo layout (../../renderer/dist)
- Full build pipeline: contracts → renderer → server + bundle client

Co-authored-by: Theo Browne <[email protected]>

* fix tests

* turborepo and better logging

* bring back electron

* fix

* Promise catching fixes

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
2026-02-09 22:15:48 -08:00
88 changed files with 6404 additions and 905 deletions

No files matched your search

+9 -1
View File
@@ -8,7 +8,7 @@ on:
jobs:
quality:
name: Lint, Typecheck, Test
name: Lint, Typecheck, Test, Build
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -40,3 +40,11 @@ jobs:
- name: Test
run: bun run test
- name: Build desktop pipeline
run: bun run build:desktop
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
@@ -0,0 +1,74 @@
# Branch/Environment Picker in ChatView Input
## Summary
Add a secondary toolbar below the ChatView input area (similar to Codex UI) that lets users select the target branch and environment mode (Local vs New worktree) before sending their first message.
## UX
- A toolbar appears **below** the input form (always visible when it's a git repo)
- Two controls:
1. **Environment mode** (left side): toggles between "Local" and "New worktree" — **locked after first message** (no longer clickable, just shows current mode as label)
2. **Branch picker** (right side): dropdown showing local branches — **always changeable**, even after messages are sent
- If not a git repo, the toolbar is hidden entirely (thread uses project cwd as-is)
## Changes
### 0. Install `@tanstack/react-query` in `apps/renderer`
Add dependency + wrap app in `QueryClientProvider`.
### 1. `apps/renderer/src/store.ts` — MODIFY
Add a new action to the reducer:
```ts
| { type: "SET_THREAD_BRANCH"; threadId: string; branch: string | null; worktreePath: string | null }
```
Reducer case updates `branch` and `worktreePath` on the thread.
### 2. `apps/renderer/src/components/ChatView.tsx` — MODIFY
**Fetch branches** via `useQuery`:
```ts
const branchQuery = useQuery({
queryKey: ["git-branches", activeProject?.cwd],
queryFn: () => api.git.listBranches({ cwd: activeProject!.cwd }),
enabled: !!activeProject,
});
```
**Local state:**
- `envMode: "local" | "worktree"` — environment mode (local component state)
**UI:** Below the `<form>`, render a toolbar bar (hidden if `!branchQuery.data?.isRepo`):
- Left side: env mode button ("Local" / "New worktree") — disabled after first message (locked in)
- Right side: branch dropdown from `branchQuery.data.branches`
- Both styled like existing model picker (small text, chevron, dropdown menus)
**Behavior:**
- Branch picker is always active — changing branch dispatches `SET_THREAD_BRANCH` immediately
- Env mode is only clickable when `activeThread.messages.length === 0`. After first message, it becomes a static label showing the locked-in mode
- On first send (`onSend`): if `envMode === "worktree"` and a branch is selected, call `api.git.createWorktree` before starting the session, then dispatch `SET_THREAD_BRANCH` with the worktreePath
- `ensureSession` already uses `activeThread.worktreePath ?? activeProject.cwd`
### Files to modify
1. `apps/renderer/package.json` — add `@tanstack/react-query`
2. `apps/renderer/src/main.tsx` (or App entry) — wrap in `QueryClientProvider`
3. `apps/renderer/src/store.ts` — add `SET_THREAD_BRANCH` action
4. `apps/renderer/src/components/ChatView.tsx` — branch/env picker UI with `useQuery`
## Verification
1. `turbo build` — compiles
2. Create a new thread → branch bar appears below input with "Local" + current branch
3. Change branch in dropdown → branch updates on thread
4. Toggle "New worktree" → send message → worktree created, session uses worktree cwd
5. After first message: env mode label locks to "Worktree" (not clickable), branch picker still works
6. Non-git project → no branch bar shown
+99
View File
@@ -0,0 +1,99 @@
# Git Flows Integration Tests
## Overview
Real integration tests that run actual git commands against temporary repos. No mocking.
## Step 1: Extract git functions into `apps/desktop/src/git.ts`
The git functions (`listGitBranches`, `createGitWorktree`, `removeGitWorktree`, `createGitBranch`, `checkoutGitBranch`, `initGitRepo`) and their helper `runTerminalCommand` are currently private in `main.ts`. Extract them into a new `apps/desktop/src/git.ts` module with named exports.
`main.ts` will import and re-use them — no behavior change, just moving code.
**Files modified:**
- `apps/desktop/src/git.ts` — new file with all git functions exported
- `apps/desktop/src/main.ts` — import from `./git` instead of defining inline
## Step 2: Create `apps/desktop/src/git.test.ts`
Integration tests using real temp git repos. Each test group creates a fresh temp directory with `git init`, makes commits, creates branches as needed, and cleans up after.
### Setup/teardown pattern
```ts
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
listGitBranches,
createGitBranch,
checkoutGitBranch,
createGitWorktree,
removeGitWorktree,
initGitRepo,
} from "./git";
// Helper: run a raw git command in a dir (for test setup, not under test)
// Helper: create an initial commit (git needs at least one commit for branches)
```
### Test groups
**1. initGitRepo**
- Creates a valid git repo in a temp dir
- listGitBranches reports `isRepo: true` after init
**2. listGitBranches**
- Returns `isRepo: false` for non-git directory
- Returns the current branch with `current: true`
- Sorts current branch first
- Lists multiple branches after creating them
- `isDefault` is false when no remote (no origin/HEAD)
**3. checkoutGitBranch**
- Checks out an existing branch (current flag moves)
- Throws when branch doesn't exist
- Throws when checkout would overwrite uncommitted changes (dirty working tree)
**4. createGitBranch**
- Creates a new branch (appears in listGitBranches)
- Throws when branch already exists
**5. createGitWorktree + removeGitWorktree**
- Creates a worktree directory at the expected path
- Worktree has the correct branch checked out
- Throws when branch is already checked out in another worktree
- removeGitWorktree cleans up the worktree
**6. Full flow: local branch checkout**
- init → commit → create branch → checkout → verify current
**7. Full flow: worktree creation from selected branch**
- init → commit → create branch → create worktree → verify worktree dir exists and has correct branch
**8. Full flow: thread switching simulation**
- init → commit → create branch-a, branch-b → checkout a → checkout b → checkout a → verify current matches
**9. Full flow: checkout conflict**
- init → commit → create branch → modify file (unstaged) → checkout other branch → expect error
## Verification
```bash
# Run the git integration tests
cd apps/desktop && bun run test
# Or just the git test file
npx vitest run apps/desktop/src/git.test.ts
```
+103
View File
@@ -0,0 +1,103 @@
# Git Flows Test Plan
## Overview
Add tests for git branch/worktree flows. Two files:
1. **Extend** `apps/renderer/src/store.test.ts` — reducer tests for `SET_THREAD_BRANCH`
2. **Create** `apps/renderer/src/git-flows.test.ts` — flow logic tests
All tests are pure Vitest unit tests (no React rendering). They test the reducer directly and simulate handler logic via sequential reducer dispatches + mocked API calls.
## File 1: `apps/renderer/src/store.test.ts` (extend)
Add `describe("SET_THREAD_BRANCH reducer")` with 6 tests:
- Sets branch + worktreePath atomically
- Clears both to null
- Updates branch while preserving worktreePath
- Does not affect other threads (multi-thread state)
- No-op for nonexistent thread id
- Does not mutate messages, error, or session fields
Uses existing `makeThread`, `makeState` factories.
## File 2: `apps/renderer/src/git-flows.test.ts` (new)
### Factories
- `makeThread()`, `makeState()`, `makeSession()` — same pattern as store.test.ts
- `makeBranch()` — creates `GitBranch` objects
- `makeMessage()` — creates `ChatMessage` objects
- `makeGitApi()` — returns `{ checkout, createWorktree, createBranch, listBranches }` with `vi.fn()` mocks
### Test groups (~30 tests total)
**1. Local branch checkout flow** (2 tests)
- Successful checkout → SET_THREAD_BRANCH updates branch
- Checkout failure → SET_ERROR, branch unchanged
**2. Thread branch conflict on send** (3 tests)
- Two threads maintain independent branch state after SET_ACTIVE_THREAD
- Branch state preserved through multiple thread switches + updates
- Checkout failure on thread switch sets error only on target thread
**3. Worktree creation on send** (5 tests)
- First message in worktree mode → createWorktree → SET_THREAD_BRANCH with worktreePath
- No worktree when messages already exist
- No worktree in local envMode
- No worktree when worktreePath already set
- createWorktree failure → SET_ERROR, send aborted, no messages pushed
**4. Env mode locking** (4 tests)
- envLocked=false when no messages
- envLocked=true with messages
- Transitions false→true after PUSH_USER_MESSAGE
- Remains true after SET_ERROR and UPDATE_SESSION
**5. Auto-fill current branch** (3 tests)
- Dispatches SET_THREAD_BRANCH when thread has no branch and current branch exists
- Does not overwrite existing branch
- No-op when no branch is marked current
**6. Default branch detection** (2 tests)
- isDefault flag on branch objects
- current and isDefault can be on different branches
**7. Branch creation + checkout** (3 tests)
- Successful create + checkout updates branch
- createBranch failure → error, branch unchanged
- checkout failure after successful create → error, branch unchanged
**8. Session CWD resolution** (3 tests)
- Uses worktreePath when available
- cwdOverride takes precedence over worktreePath
- Falls back to project cwd when no worktree
**9. Error handling patterns** (4 tests)
- SET_ERROR sets error on correct thread
- SET_ERROR with null clears error
- Error on one thread doesn't affect others
- Error cleared before successful branch operations
## Verification
```bash
# Run all renderer tests
cd apps/renderer && bun run test
# Run just the new test file
npx vitest run apps/renderer/src/git-flows.test.ts
# Run just the store tests
npx vitest run apps/renderer/src/store.test.ts
```
@@ -0,0 +1,115 @@
# Git Integration: Branch Picker + Worktrees
## Summary
Add git integration to let users start new threads from a specific branch, optionally creating a git worktree for isolated agent work.
## UX Flow
- **Left click** "+ New thread" → immediately creates a thread (current behavior, unchanged)
- **Right click** "+ New thread" → opens a context menu with git options:
- List of local branches → clicking one creates a thread on that branch (uses project cwd)
- Each branch has a "worktree" sub-option → creates a worktree, then creates thread with worktree as cwd
- When thread has a worktree, the agent session uses the worktree path as its cwd
- If git fails (not a repo), context menu shows "Not a git repository" disabled item
## Changes
### 1. `packages/contracts/src/git.ts` — CREATE
New Zod schemas and types:
- `gitListBranchesInputSchema` — `{ cwd: string }`
- `gitCreateWorktreeInputSchema` — `{ cwd: string, branch: string, path?: string }`
- `gitRemoveWorktreeInputSchema` — `{ cwd: string, path: string }`
- `gitBranchSchema` — `{ name: string, current: boolean }`
- Result types for each
### 2. `packages/contracts/src/ipc.ts` — MODIFY
- Add 3 IPC channels: `git:list-branches`, `git:create-worktree`, `git:remove-worktree`
- Add `git` namespace to `NativeApi` with `listBranches`, `createWorktree`, `removeWorktree`
### 3. `packages/contracts/src/index.ts` — MODIFY
- Add `export * from "./git"`
### 4. `apps/desktop/src/main.ts` — MODIFY
Add 3 IPC handlers + helper functions:
- `listGitBranches()` — runs `git branch --no-color`, parses output into `{ name, current }[]`
- `createGitWorktree()` — runs `git worktree add <path> <branch>`, defaults path to `../{repo}-worktrees/{branch}`
- `removeGitWorktree()` — runs `git worktree remove <path>`
Reuses existing `runTerminalCommand()`.
### 5. `apps/desktop/src/preload.ts` — MODIFY
Add `git` namespace with 3 `ipcRenderer.invoke` calls.
### 6. `apps/renderer/src/types.ts` — MODIFY
Add to `Thread`:
```
branch: string | null
worktreePath: string | null
```
### 7. `apps/renderer/src/persistenceSchema.ts` — MODIFY
- Add optional `branch`/`worktreePath` to persisted thread schema (`.nullable().optional()` for backwards compat)
- Add V3 schema, update union
- Update `hydrateThread` to default new fields to `null`
- Update `toPersistedState` to serialize new fields
### 8. `apps/renderer/src/store.ts` — MODIFY
- Update persisted state key to v3, keep v2 as legacy fallback
### 9. `apps/renderer/src/components/Sidebar.tsx` — MODIFY (main UI work)
- Keep existing left-click `handleNewThread` unchanged (immediate thread creation)
- Add `onContextMenu` handler to "+ New thread" buttons (both global and per-project)
- On right-click: fetch branches via `api.git.listBranches`, show a custom context menu
- Context menu items: branch names, each with a nested option to create with worktree
- Clicking a branch → creates thread with `branch` set, title = branch name
- Clicking "with worktree" → calls `api.git.createWorktree` first, then creates thread with `worktreePath`
- Show branch badge on thread list items
- If not a git repo, show "Not a git repository" as disabled menu item
Context menu component: a positioned `<div>` with `position: fixed` anchored to the click position, dismissed on click-outside or Escape. Follows the existing dropdown pattern from ChatView's model picker.
### 10. `apps/renderer/src/components/ChatView.tsx` — MODIFY
- Line 157: use `activeThread.worktreePath ?? activeProject.cwd` as session cwd
- Show branch/worktree badge in header bar
## Implementation Order
1. `packages/contracts/src/git.ts` (new schemas)
2. `packages/contracts/src/ipc.ts` + `index.ts` (wire up channels)
3. `apps/desktop/src/main.ts` (git command handlers)
4. `apps/desktop/src/preload.ts` (bridge methods)
5. `apps/renderer/src/types.ts` (Thread type update)
6. `apps/renderer/src/persistenceSchema.ts` + `store.ts` (persistence migration)
7. `apps/renderer/src/components/Sidebar.tsx` (branch picker UI)
8. `apps/renderer/src/components/ChatView.tsx` (worktree cwd + badge)
## Edge Cases
- **Not a git repo**: `git branch` fails → context menu shows "Not a git repository" disabled item
- **Branch has slashes**: `feature/foo` → worktree dir becomes `feature-foo`
- **Worktree exists**: git error surfaces to user via inline error message in context menu
- **No persistence breakage**: `.nullable().optional()` fields parse fine with old data
## Verification
1. `turbo build` — confirm contracts/desktop/renderer all compile
2. Launch app, add a project pointing to a git repo
3. Click "+ New thread" → verify branch list loads
4. Select a branch, click Start → thread created with branch in title
5. Enable worktree checkbox, pick branch, Start → verify worktree directory created on disk
6. Send a message in worktree thread → verify agent runs in worktree cwd
7. Add a non-git project → verify graceful error, can still create thread
+11 -4
View File
@@ -1,11 +1,13 @@
# CLAUDE.md
## Project Snapshot
CodeThing 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 code agents like Codex and Claude Code (coming soon).
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
## Core Priorities
1. Performance first.
2. Reliability first.
3. Keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).
@@ -13,23 +15,28 @@ 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.
## 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/renderer`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `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.
## Codex App Server (Important)
CodeThing is currently Codex-first. The server starts `codex app-server` (JSON-RPC over stdio) per provider session, then streams structured events to the browser through WebSocket push messages.
T3 Code is currently Codex-first. The server starts `codex app-server` (JSON-RPC over stdio) per provider session, then streams structured events to the browser through WebSocket push messages.
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`.
- Renderer consumes provider event streams via WebSocket push on channel `providers.event`.
- Web app consumes provider event streams via WebSocket push on channel `providers.event`.
Docs:
- Codex App Server docs: https://developers.openai.com/codex/sdk/#app-server
## Reference Repos
- Open-source Codex repo: https://github.com/openai/codex
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
+21 -15
View File
@@ -1,12 +1,13 @@
# CodeThing
# T3 Code
CodeThing 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-first, with Claude Code support 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.
## Architecture
CodeThing runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
@@ -28,15 +29,16 @@ CodeThing runs as a **Node.js WebSocket server** that wraps `codex app-server` (
## Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built renderer, and opens the browser on start.
- `/apps/renderer`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/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 CodeThing (for example via API key or ChatGPT auth supported by Codex).
- CodeThing starts the server via `codex app-server` per session.
- 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
@@ -44,6 +46,9 @@ CodeThing runs as a **Node.js WebSocket server** that wraps `codex app-server` (
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Production
bun run build
bun run start
@@ -54,29 +59,30 @@ npx t3
## Scripts
- `bun run dev` — Starts contracts, server, and web dev tasks via Turborepo's parallel task runner.
- `bun run dev:server` — Starts just the WebSocket server (uses tsx for TS execution).
- `bun run dev:web` — Starts just the Vite dev server for the renderer.
- `bun run start` — Runs the production server (serves built renderer as static files).
- `bun run build` — Builds contracts, renderer, and server through Turbo.
- `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.
## Runtime modes
CodeThing has a global runtime mode switch in the chat toolbar:
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.
## Provider architecture
The renderer communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
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**: `{ type: "push", channel, data }` for streaming provider events
Methods mirror the `NativeApi` interface defined in `@acme/contracts`:
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`, `providers.listSessions`
- `shell.openInEditor`, `server.getConfig`
+2
View File
@@ -10,3 +10,5 @@
- [x] "Response" bar should ONLY appear on work completed
- [x] "Response" bar should ONLY appear above the FINAL message in a series
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
- [ ] Insta focus input on new thread creation
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
+1
View File
@@ -0,0 +1 @@
dist-electron/
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:electron": "bun run scripts/dev-electron.mjs",
"build": "tsdown",
"start": "electron dist-electron/main.js",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"electron": "33.4.11"
},
"devDependencies": {
"@types/node": "^22.10.2",
"electronmon": "^2.0.2",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
"wait-on": "^8.0.2"
}
}
+28
View File
@@ -0,0 +1,28 @@
import { spawn } from "node:child_process";
import waitOn from "wait-on";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
const devServerUrl = `http://localhost:${port}`;
await waitOn({
resources: [
`tcp:${port}`,
"file:dist-electron/main.js",
"file:dist-electron/preload.js",
"file:../server/dist/index.mjs",
],
});
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
const child = spawn(command, ["dist-electron/main.js"], {
stdio: "inherit",
env: {
...process.env,
VITE_DEV_SERVER_URL: devServerUrl,
},
});
child.on("exit", (code) => {
process.exit(code ?? 0);
});
+57
View File
@@ -0,0 +1,57 @@
import { spawn } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
const mainJs = resolve(desktopDir, "dist-electron/main.js");
console.log("\nLaunching Electron smoke test...");
const child = spawn(electronBin, [mainJs], {
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
VITE_DEV_SERVER_URL: "",
ELECTRON_ENABLE_LOGGING: "1",
},
});
let output = "";
child.stdout.on("data", (chunk) => {
output += chunk.toString();
});
child.stderr.on("data", (chunk) => {
output += chunk.toString();
});
const timeout = setTimeout(() => {
child.kill();
}, 8_000);
child.on("exit", () => {
clearTimeout(timeout);
const fatalPatterns = [
"Cannot find module",
"MODULE_NOT_FOUND",
"Refused to execute",
"Uncaught Error",
"Uncaught TypeError",
"Uncaught ReferenceError",
];
const failures = fatalPatterns.filter((pattern) => output.includes(pattern));
if (failures.length > 0) {
console.error("\nDesktop smoke test failed:");
for (const failure of failures) {
console.error(` - ${failure}`);
}
console.error("\nFull output:\n" + output);
process.exit(1);
}
console.log("Desktop smoke test passed.");
process.exit(0);
});
+18
View File
@@ -0,0 +1,18 @@
import { execFileSync } from "node:child_process";
export function fixPath(): void {
if (process.platform !== "darwin") return;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
encoding: "utf8",
timeout: 5000,
});
if (result) {
process.env.PATH = result;
}
} catch {
// Keep inherited PATH if shell lookup fails.
}
}
+236
View File
@@ -0,0 +1,236 @@
import { spawn, type ChildProcess } from "node:child_process";
import { randomBytes } from "node:crypto";
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu } from "electron";
import { fixPath } from "./fixPath";
fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const ROOT_DIR = path.resolve(__dirname, "../../..");
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess | null = null;
let backendPort = 0;
let backendAuthToken = "";
let backendWsUrl = "";
let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
async function reserveLoopbackPort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.listen(0, "127.0.0.1", () => {
const address = probe.address();
const port = typeof address === "object" && address !== null ? address.port : 0;
probe.close(() => {
if (port > 0) {
resolve(port);
return;
}
reject(new Error("Failed to reserve backend port"));
});
});
probe.on("error", reject);
});
}
function backendEnv(): NodeJS.ProcessEnv {
return {
...process.env,
T3CODE_MODE: "desktop",
T3CODE_NO_BROWSER: "1",
T3CODE_PORT: String(backendPort),
T3CODE_STATE_DIR: STATE_DIR,
T3CODE_AUTH_TOKEN: backendAuthToken,
};
}
function scheduleBackendRestart(reason: string): void {
if (isQuitting || restartTimer) return;
const delayMs = Math.min(500 * 2 ** restartAttempt, 10_000);
restartAttempt += 1;
console.error(`[desktop] backend exited unexpectedly (${reason}); restarting in ${delayMs}ms`);
restartTimer = setTimeout(() => {
restartTimer = null;
startBackend();
}, delayMs);
}
function startBackend(): void {
if (isQuitting || backendProcess) return;
if (!fs.existsSync(BACKEND_ENTRY)) {
scheduleBackendRestart(`missing server entry at ${BACKEND_ENTRY}`);
return;
}
const child = spawn(process.execPath, [BACKEND_ENTRY], {
cwd: ROOT_DIR,
env: backendEnv(),
stdio: "inherit",
});
backendProcess = child;
child.once("spawn", () => {
restartAttempt = 0;
});
child.on("error", (error) => {
if (backendProcess === child) {
backendProcess = null;
}
scheduleBackendRestart(error.message);
});
child.on("exit", (code, signal) => {
if (backendProcess === child) {
backendProcess = null;
}
if (isQuitting) return;
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
scheduleBackendRestart(reason);
});
}
function stopBackend(): void {
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = null;
}
const child = backendProcess;
backendProcess = null;
if (!child) return;
if (!child.killed) {
child.kill("SIGTERM");
setTimeout(() => {
if (!child.killed) {
child.kill("SIGKILL");
}
}, 2_000).unref();
}
}
function registerIpcHandlers(): void {
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
const result = owner
? await dialog.showOpenDialog(owner, {
properties: ["openDirectory", "createDirectory"],
})
: await dialog.showOpenDialog({
properties: ["openDirectory", "createDirectory"],
});
if (result.canceled) return null;
return result.filePaths[0] ?? null;
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
if (!window) return null;
return new Promise<string | null>((resolve) => {
const menu = Menu.buildFromTemplate(
items.map((item) => ({
label: item.label,
click: () => resolve(item.id),
})),
);
menu.popup({
window,
callback: () => resolve(null),
});
});
});
}
function createWindow(): BrowserWindow {
const window = new BrowserWindow({
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: false,
autoHideMenuBar: true,
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 16, y: 18 },
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
},
});
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
window.once("ready-to-show", () => {
window.show();
});
if (isDevelopment) {
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
window.webContents.openDevTools({ mode: "detach" });
} else {
if (!fs.existsSync(WEB_ENTRY)) {
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
}
void window.loadFile(WEB_ENTRY);
}
window.on("closed", () => {
if (mainWindow === window) {
mainWindow = null;
}
});
return window;
}
async function bootstrap(): Promise<void> {
backendPort = await reserveLoopbackPort();
backendAuthToken = randomBytes(24).toString("hex");
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
registerIpcHandlers();
startBackend();
mainWindow = createWindow();
}
app.on("before-quit", () => {
isQuitting = true;
stopBackend();
});
app.whenReady().then(() => {
void bootstrap();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
mainWindow = createWindow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
+12
View File
@@ -0,0 +1,12 @@
import { contextBridge, ipcRenderer } from "electron";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
showContextMenu: (items: { id: string; label: string }[]) =>
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
});
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"types": ["node", "electron"],
"lib": ["ES2023", "DOM", "esnext.disposable"]
},
"include": ["src", "tsdown.config.ts"]
}
+21
View File
@@ -0,0 +1,21 @@
import { defineConfig } from "tsdown";
const shared = {
format: "cjs" as const,
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".js" }),
};
export default defineConfig([
{
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: ["@t3tools/contracts"],
},
{
...shared,
entry: ["src/preload.ts"],
},
]);
+24
View File
@@ -0,0 +1,24 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist-electron/**"],
},
"dev": {
"dependsOn": ["t3#build"],
"persistent": true,
},
"start": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"persistent": true,
},
"smoke-test": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"outputs": [],
},
},
}
-12
View File
@@ -1,12 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CodeThing</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
-9
View File
@@ -1,9 +0,0 @@
/// <reference types="vite/client" />
import type { NativeApi } from "@acme/contracts";
declare global {
interface Window {
nativeApi?: NativeApi;
}
}
-107
View File
@@ -1,107 +0,0 @@
import {
type NativeApi,
WS_CHANNELS,
WS_METHODS,
type WsWelcomePayload,
} from "@acme/contracts";
import { WsTransport } from "./wsTransport";
let instance: { api: NativeApi; transport: WsTransport } | null = null;
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
let lastWelcome: WsWelcomePayload | null = null;
/**
* Subscribe to the server welcome message. If a welcome was already received
* before this call, the listener fires synchronously with the cached payload.
* This avoids the race between WebSocket connect and React effect registration.
*/
export function onServerWelcome(
listener: (payload: WsWelcomePayload) => void,
): () => void {
welcomeListeners.add(listener);
// Replay cached welcome for late subscribers
if (lastWelcome) {
try {
listener(lastWelcome);
} catch {
// Swallow listener errors
}
}
return () => {
welcomeListeners.delete(listener);
};
}
export function createWsNativeApi(): NativeApi {
if (instance) return instance.api;
const transport = new WsTransport();
// Listen for server welcome and forward to registered listeners.
// Also cache it so late subscribers (React effects) get it immediately.
transport.subscribe(WS_CHANNELS.serverWelcome, (data) => {
const payload = data as WsWelcomePayload;
lastWelcome = payload;
for (const listener of welcomeListeners) {
try {
listener(payload);
} catch {
// Swallow listener errors
}
}
});
const api: NativeApi = {
todos: {
list: async () => [],
add: async () => [],
toggle: async () => [],
remove: async () => [],
},
dialogs: {
pickFolder: async () => null,
},
terminal: {
run: async () => ({
stdout: "",
stderr: "Terminal not available in web mode",
code: 1,
signal: null,
timedOut: false,
}),
},
agent: {
spawn: async () => "",
kill: async () => {},
write: async () => {},
onOutput: () => () => {},
onExit: () => () => {},
},
providers: {
startSession: (input) =>
transport.request(WS_METHODS.providersStartSession, input),
sendTurn: (input) =>
transport.request(WS_METHODS.providersSendTurn, input),
interruptTurn: (input) =>
transport.request(WS_METHODS.providersInterruptTurn, input),
respondToRequest: (input) =>
transport.request(WS_METHODS.providersRespondToRequest, input),
stopSession: (input) =>
transport.request(WS_METHODS.providersStopSession, input),
listSessions: () =>
transport.request(WS_METHODS.providersListSessions),
onEvent: (callback) =>
transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void),
},
shell: {
openInEditor: (cwd, editor) =>
transport.request(WS_METHODS.shellOpenInEditor, { cwd, editor }),
},
};
instance = { api, transport };
return api;
}
-28
View File
@@ -1,28 +0,0 @@
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [
react({
babel: {
plugins: [["babel-plugin-react-compiler", { target: "19" }]],
},
}),
tailwindcss(),
],
define: {
// In dev mode, tell the renderer where the WebSocket server lives
"import.meta.env.VITE_WS_URL": JSON.stringify(
process.env.VITE_WS_URL ?? "",
),
},
server: {
port: Number(process.env.PORT ?? 5173),
strictPort: true,
},
build: {
outDir: "dist",
emptyOutDir: true,
},
});
+10 -10
View File
@@ -1,32 +1,32 @@
{
"name": "t3",
"version": "0.1.0",
"type": "module",
"bin": {
"t3": "./dist/index.js"
"t3": "./dist/index.mjs"
},
"main": "./dist/index.js",
"files": [
"dist"
],
"type": "module",
"main": "./dist/index.mjs",
"scripts": {
"dev": "VITE_DEV_SERVER_URL=http://localhost:5173 tsx src/index.ts",
"build": "tsup && node scripts/bundle-client.mjs",
"start": "node dist/index.js",
"dev": "VITE_DEV_SERVER_URL=http://localhost:5173 bun run src/index.ts",
"build": "tsdown && node scripts/bundle-client.mjs",
"start": "node dist/index.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@acme/contracts": "workspace:*",
"@acme/renderer": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsup": "^8.3.5",
"tsx": "^4.19.0",
"tsdown": "^0.20.3",
"typescript": "^5.7.3"
}
}
+6 -6
View File
@@ -1,5 +1,5 @@
/**
* Copies the built renderer into dist/client/ so the published npm package
* Copies the built web app into dist/client/ so the published npm package
* includes the web UI. This runs as a post-build step.
*/
import fs from "node:fs";
@@ -7,15 +7,15 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rendererDist = path.resolve(__dirname, "../../renderer/dist");
const webDist = path.resolve(__dirname, "../../web/dist");
const target = path.resolve(__dirname, "../dist/client");
if (!fs.existsSync(rendererDist)) {
if (!fs.existsSync(webDist)) {
console.log(
"⚠ Renderer dist not found — skipping client bundle. Run `bun run --cwd apps/renderer build` first.",
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
);
process.exit(0);
}
fs.cpSync(rendererDist, target, { recursive: true });
console.log("✓ Bundled renderer into dist/client");
fs.cpSync(webDist, target, { recursive: true });
console.log("✓ Bundled web app into dist/client");
@@ -57,17 +57,13 @@ describe("normalizeCodexModelSlug", () => {
describe("isRecoverableThreadResumeError", () => {
it("matches not-found resume errors", () => {
expect(
isRecoverableThreadResumeError(
new Error("thread/resume failed: thread not found"),
),
isRecoverableThreadResumeError(new Error("thread/resume failed: thread not found")),
).toBe(true);
});
it("ignores non-resume errors", () => {
expect(
isRecoverableThreadResumeError(
new Error("thread/start failed: permission denied"),
),
isRecoverableThreadResumeError(new Error("thread/start failed: permission denied")),
).toBe(false);
});
+15 -37
View File
@@ -11,8 +11,8 @@ import type {
ProviderSession,
ProviderSessionStartInput,
ProviderTurnStartResult,
} from "@acme/contracts";
import { normalizeModelSlug } from "@acme/contracts";
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/contracts";
type PendingRequestKey = string;
@@ -26,9 +26,7 @@ interface PendingRequest {
interface PendingApprovalRequest {
requestId: string;
jsonRpcId: string | number;
method:
| "item/commandExecution/requestApproval"
| "item/fileChange/requestApproval";
method: "item/commandExecution/requestApproval" | "item/fileChange/requestApproval";
requestKind: ProviderRequestKind;
threadId?: string;
turnId?: string;
@@ -122,16 +120,12 @@ export function classifyCodexStderrLine(rawLine: string): { message: string } |
}
export function isRecoverableThreadResumeError(error: unknown): boolean {
const message = (
error instanceof Error ? error.message : String(error)
).toLowerCase();
const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
if (!message.includes("thread/resume")) {
return false;
}
return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) =>
message.includes(snippet),
);
return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
}
export interface CodexAppServerManagerEvents {
@@ -180,8 +174,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
try {
await this.sendRequest(context, "initialize", {
clientInfo: {
name: "codething_desktop",
title: "CodeThing Desktop",
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
@@ -209,14 +203,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
if (input.resumeThreadId) {
try {
threadOpenMethod = "thread/resume";
threadOpenResponse = await this.sendRequest(
context,
"thread/resume",
{
...sessionOverrides,
threadId: input.resumeThreadId,
},
);
threadOpenResponse = await this.sendRequest(context, "thread/resume", {
...sessionOverrides,
threadId: input.resumeThreadId,
});
} catch (error) {
if (!isRecoverableThreadResumeError(error)) {
throw error;
@@ -228,19 +218,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
"session/threadResumeFallback",
`Could not resume thread ${input.resumeThreadId}; started a new thread instead.`,
);
threadOpenResponse = await this.sendRequest(
context,
"thread/start",
threadStartParams,
);
threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
}
} else {
threadOpenMethod = "thread/start";
threadOpenResponse = await this.sendRequest(
context,
"thread/start",
threadStartParams,
);
threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
}
const threadOpenRecord = this.readObject(threadOpenResponse);
@@ -248,9 +230,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
this.readString(this.readObject(threadOpenRecord, "thread"), "id") ??
this.readString(threadOpenRecord, "threadId");
if (!threadId) {
throw new Error(
`${threadOpenMethod} response did not include a thread id.`,
);
throw new Error(`${threadOpenMethod} response did not include a thread id.`);
}
this.updateSession(context, {
@@ -732,9 +712,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
};
}
private requestKindForMethod(
method: string,
): ProviderRequestKind | undefined {
private requestKindForMethod(method: string): ProviderRequestKind | undefined {
if (method === "item/commandExecution/requestApproval") {
return "command";
}
+438
View File
@@ -0,0 +1,438 @@
import { existsSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
checkoutGitBranch,
createGitBranch,
createGitWorktree,
initGitRepo,
listGitBranches,
removeGitWorktree,
runTerminalCommand,
} from "./git";
// ── Helpers ──
/** Run a raw git command for test setup (not under test). */
async function git(cwd: string, command: string): Promise<string> {
const result = await runTerminalCommand({
command: `git ${command}`,
cwd,
timeoutMs: 10_000,
});
if (result.code !== 0) {
throw new Error(`git ${command} failed: ${result.stderr}`);
}
return result.stdout.trim();
}
/** Create a disposable temp directory that cleans up automatically. */
async function makeTmpDir() {
const dir = await mkdtemp(path.join(tmpdir(), "git-test-"));
return {
path: dir,
[Symbol.asyncDispose]: async () => {
await rm(dir, { recursive: true, force: true });
},
};
}
/** Create a repo with an initial commit so branches work. */
async function initRepoWithCommit(cwd: string): Promise<void> {
await initGitRepo({ cwd });
await git(cwd, "config user.email '[email protected]'");
await git(cwd, "config user.name 'Test'");
await writeFile(path.join(cwd, "README.md"), "# test\n");
await git(cwd, "add .");
await git(cwd, "commit -m 'initial commit'");
}
// ── Tests ──
describe("git integration", () => {
describe("runTerminalCommand", () => {
it("caps captured output when maxOutputBytes is exceeded", async () => {
const result = await runTerminalCommand({
command: `node -e "process.stdout.write('x'.repeat(2000))"`,
cwd: process.cwd(),
timeoutMs: 10_000,
maxOutputBytes: 128,
});
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
expect(result.stderr).toContain("output truncated");
});
});
// ── initGitRepo ──
describe("initGitRepo", () => {
it("creates a valid git repo", async () => {
await using tmp = await makeTmpDir();
await initGitRepo({ cwd: tmp.path });
expect(existsSync(path.join(tmp.path, ".git"))).toBe(true);
});
it("listGitBranches reports isRepo: true after init + commit", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const result = await listGitBranches({ cwd: tmp.path });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThanOrEqual(1);
});
});
// ── listGitBranches ──
describe("listGitBranches", () => {
it("returns isRepo: false for non-git directory", async () => {
await using tmp = await makeTmpDir();
const result = await listGitBranches({ cwd: tmp.path });
expect(result.isRepo).toBe(false);
expect(result.branches).toEqual([]);
});
it("returns the current branch with current: true", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const result = await listGitBranches({ cwd: tmp.path });
const current = result.branches.find((b) => b.current);
expect(current).toBeDefined();
expect(current!.current).toBe(true);
});
it("sorts current branch first", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "aaa-first-alpha" });
await createGitBranch({ cwd: tmp.path, branch: "zzz-last" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.current).toBe(true);
});
it("lists multiple branches after creating them", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "feature-a" });
await createGitBranch({ cwd: tmp.path, branch: "feature-b" });
const result = await listGitBranches({ cwd: tmp.path });
const names = result.branches.map((b) => b.name);
expect(names).toContain("feature-a");
expect(names).toContain("feature-b");
});
it("isDefault is false when no remote exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
});
});
// ── checkoutGitBranch ──
describe("checkoutGitBranch", () => {
it("checks out an existing branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "feature" });
await checkoutGitBranch({ cwd: tmp.path, branch: "feature" });
const result = await listGitBranches({ cwd: tmp.path });
const current = result.branches.find((b) => b.current);
expect(current!.name).toBe("feature");
});
it("throws when branch does not exist", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "nonexistent" })).rejects.toThrow();
});
it("throws when checkout would overwrite uncommitted changes", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "other" });
// Create a conflicting change: modify README on current branch
await writeFile(path.join(tmp.path, "README.md"), "modified\n");
await git(tmp.path, "add README.md");
// First, checkout other branch cleanly
await git(tmp.path, "stash");
await checkoutGitBranch({ cwd: tmp.path, branch: "other" });
await writeFile(path.join(tmp.path, "README.md"), "other content\n");
await git(tmp.path, "add .");
await git(tmp.path, "commit -m 'other change'");
// Go back to default branch
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => !b.current,
)!.name;
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
// Make uncommitted changes to the same file
await writeFile(path.join(tmp.path, "README.md"), "conflicting local\n");
// Checkout should fail due to uncommitted changes
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "other" })).rejects.toThrow();
});
});
// ── createGitBranch ──
describe("createGitBranch", () => {
it("creates a new branch visible in listGitBranches", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "new-feature" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches.some((b) => b.name === "new-feature")).toBe(true);
});
it("throws when branch already exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "dupe" });
await expect(createGitBranch({ cwd: tmp.path, branch: "dupe" })).rejects.toThrow();
});
});
// ── createGitWorktree + removeGitWorktree ──
describe("createGitWorktree", () => {
it("creates a worktree with a new branch from the base branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "worktree-out");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
const result = await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "wt-branch",
path: wtPath,
});
expect(result.worktree.path).toBe(wtPath);
expect(result.worktree.branch).toBe("wt-branch");
expect(existsSync(wtPath)).toBe(true);
expect(existsSync(path.join(wtPath, "README.md"))).toBe(true);
// Clean up worktree before tmp dir disposal
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
it("worktree has the new branch checked out", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "wt-check-dir");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "wt-check",
path: wtPath,
});
// Verify the worktree is on the new branch
const branchOutput = await git(wtPath, "branch --show-current");
expect(branchOutput).toBe("wt-check");
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
it("throws when new branch name already exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "existing" });
const wtPath = path.join(tmp.path, "wt-conflict");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await expect(
createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "existing",
path: wtPath,
}),
).rejects.toThrow();
});
it("listGitBranches from worktree cwd reports worktree branch as current", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "wt-list-dir");
const mainBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await createGitWorktree({
cwd: tmp.path,
branch: mainBranch,
newBranch: "wt-list",
path: wtPath,
});
// listGitBranches from the worktree should show wt-list as current
const wtBranches = await listGitBranches({ cwd: wtPath });
expect(wtBranches.isRepo).toBe(true);
const wtCurrent = wtBranches.branches.find((b) => b.current);
expect(wtCurrent!.name).toBe("wt-list");
// Main repo should still show the original branch as current
const mainBranches = await listGitBranches({ cwd: tmp.path });
const mainCurrent = mainBranches.branches.find((b) => b.current);
expect(mainCurrent!.name).toBe(mainBranch);
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
it("removeGitWorktree cleans up the worktree", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "wt-remove-dir");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "wt-remove",
path: wtPath,
});
expect(existsSync(wtPath)).toBe(true);
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
expect(existsSync(wtPath)).toBe(false);
});
});
// ── Full flow: local branch checkout ──
describe("full flow: local branch checkout", () => {
it("init → commit → create branch → checkout → verify current", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "feature-login" });
await checkoutGitBranch({ cwd: tmp.path, branch: "feature-login" });
const result = await listGitBranches({ cwd: tmp.path });
const current = result.branches.find((b) => b.current);
expect(current!.name).toBe("feature-login");
});
});
// ── Full flow: worktree creation from base branch ──
describe("full flow: worktree creation", () => {
it("creates worktree with new branch from current branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
const wtPath = path.join(tmp.path, "my-worktree");
const result = await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "feature-wt",
path: wtPath,
});
// Worktree exists
expect(existsSync(result.worktree.path)).toBe(true);
// Main repo still on original branch
const mainBranches = await listGitBranches({ cwd: tmp.path });
const mainCurrent = mainBranches.branches.find((b) => b.current);
expect(mainCurrent!.name).toBe(currentBranch);
// Worktree is on the new branch
const wtBranch = await git(wtPath, "branch --show-current");
expect(wtBranch).toBe("feature-wt");
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
});
});
// ── Full flow: thread switching simulation ──
describe("full flow: thread switching (checkout toggling)", () => {
it("checkout a → checkout b → checkout a → current matches", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "branch-a" });
await createGitBranch({ cwd: tmp.path, branch: "branch-b" });
// Simulate switching to thread A's branch
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" });
let branches = await listGitBranches({ cwd: tmp.path });
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
// Simulate switching to thread B's branch
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-b" });
branches = await listGitBranches({ cwd: tmp.path });
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-b");
// Switch back to thread A
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" });
branches = await listGitBranches({ cwd: tmp.path });
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
});
});
// ── Full flow: checkout conflict ──
describe("full flow: checkout conflict", () => {
it("uncommitted changes prevent checkout to a diverged branch", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "diverged" });
// Make diverged branch have different file content
await checkoutGitBranch({ cwd: tmp.path, branch: "diverged" });
await writeFile(path.join(tmp.path, "README.md"), "diverged content\n");
await git(tmp.path, "add .");
await git(tmp.path, "commit -m 'diverge'");
// Actually, let's just get back to the initial branch explicitly
const allBranches = await listGitBranches({ cwd: tmp.path });
const initialBranch = allBranches.branches.find((b) => b.name !== "diverged")!.name;
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
// Make local uncommitted changes to the same file
await writeFile(path.join(tmp.path, "README.md"), "local uncommitted\n");
// Attempt checkout should fail
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "diverged" })).rejects.toThrow();
// Current branch should still be the initial one
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch);
});
});
});
+298
View File
@@ -0,0 +1,298 @@
import { spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type {
GitCheckoutInput,
GitCreateBranchInput,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
GitListBranchesInput,
GitListBranchesResult,
GitRemoveWorktreeInput,
} from "@t3tools/contracts";
export interface TerminalCommandInput {
command: string;
cwd: string;
timeoutMs?: number;
maxOutputBytes?: number;
}
export interface TerminalCommandResult {
stdout: string;
stderr: string;
code: number | null;
signal: NodeJS.Signals | null;
timedOut: boolean;
}
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
function appendChunkWithinLimit(
target: string,
currentBytes: number,
chunk: Buffer,
maxBytes: number,
): {
next: string;
nextBytes: number;
truncated: boolean;
} {
const remaining = maxBytes - currentBytes;
if (remaining <= 0) {
return { next: target, nextBytes: currentBytes, truncated: true };
}
if (chunk.length <= remaining) {
return {
next: `${target}${chunk.toString()}`,
nextBytes: currentBytes + chunk.length,
truncated: false,
};
}
return {
next: `${target}${chunk.subarray(0, remaining).toString()}`,
nextBytes: currentBytes + remaining,
truncated: true,
};
}
/** Spawn git directly with an argv array — no shell, no quoting needed. */
function runGit(args: string[], cwd: string, timeoutMs = 30_000): Promise<TerminalCommandResult> {
return new Promise((resolve, reject) => {
const child = spawn("git", args, {
cwd,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
const maxOutputBytes = DEFAULT_MAX_OUTPUT_BYTES;
let stdout = "";
let stderr = "";
let stdoutBytes = 0;
let stderrBytes = 0;
let timedOut = false;
let outputTruncated = false;
const timeout = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
setTimeout(() => {
if (!child.killed) child.kill("SIGKILL");
}, 1_000).unref();
}, timeoutMs);
child.stdout?.on("data", (chunk: Buffer) => {
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunk, maxOutputBytes);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
outputTruncated = outputTruncated || appended.truncated;
});
child.stderr?.on("data", (chunk: Buffer) => {
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunk, maxOutputBytes);
stderr = appended.next;
stderrBytes = appended.nextBytes;
outputTruncated = outputTruncated || appended.truncated;
});
child.on("error", (error) => {
clearTimeout(timeout);
reject(error);
});
child.on("close", (code, signal) => {
clearTimeout(timeout);
if (outputTruncated) {
stderr = `${stderr}\n[output truncated at ${maxOutputBytes} bytes]`;
}
resolve({ stdout, stderr, code: code ?? null, signal: signal ?? null, timedOut });
});
});
}
export async function runTerminalCommand(
input: TerminalCommandInput,
): Promise<TerminalCommandResult> {
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const shellPath =
process.platform === "win32"
? (process.env.ComSpec ?? "cmd.exe")
: (process.env.SHELL ?? "/bin/sh");
const args =
process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
return new Promise((resolve, reject) => {
const child = spawn(shellPath, args, {
cwd: input.cwd,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let stdoutBytes = 0;
let stderrBytes = 0;
let timedOut = false;
let outputTruncated = false;
const timeout = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
setTimeout(() => {
if (!child.killed) {
child.kill("SIGKILL");
}
}, 1_000).unref();
}, input.timeoutMs ?? 30_000);
child.stdout?.on("data", (chunk: Buffer) => {
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunk, maxOutputBytes);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
outputTruncated = outputTruncated || appended.truncated;
});
child.stderr?.on("data", (chunk: Buffer) => {
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunk, maxOutputBytes);
stderr = appended.next;
stderrBytes = appended.nextBytes;
outputTruncated = outputTruncated || appended.truncated;
});
child.on("error", (error) => {
clearTimeout(timeout);
reject(error);
});
child.on("close", (code, signal) => {
clearTimeout(timeout);
if (outputTruncated) {
stderr = `${stderr}\n[output truncated at ${maxOutputBytes} bytes]`;
}
resolve({
stdout,
stderr,
code: code ?? null,
signal: signal ?? null,
timedOut,
});
});
});
}
export async function listGitBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
const result = await runGit(["branch", "--no-color"], input.cwd, 10_000);
if (result.code !== 0) {
const stderr = result.stderr.trim();
if (stderr.includes("not a git repository")) {
return { branches: [], isRepo: false };
}
throw new Error(stderr || "git branch failed");
}
// Resolve the real default branch from the remote
const [defaultRef, worktreeList] = await Promise.all([
runGit(["symbolic-ref", "refs/remotes/origin/HEAD"], input.cwd, 5_000),
runGit(["worktree", "list", "--porcelain"], input.cwd, 5_000),
]);
const defaultBranch =
defaultRef.code === 0 ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "") : null;
// Build branch-name → worktree-path map from porcelain output.
// Only include worktrees whose directories still exist on disk (skip prunable/stale ones).
const worktreeMap = new Map<string, string>();
if (worktreeList.code === 0) {
let currentPath: string | null = null;
for (const line of worktreeList.stdout.split("\n")) {
if (line.startsWith("worktree ")) {
const candidatePath = line.slice("worktree ".length);
currentPath = fs.existsSync(candidatePath) ? candidatePath : null;
} else if (line.startsWith("branch refs/heads/") && currentPath) {
worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
} else if (line === "") {
currentPath = null;
}
}
}
const branches = result.stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const name = line.replace(/^[*+]\s+/, "");
return {
name,
current: line.startsWith("* "),
isDefault: name === defaultBranch,
worktreePath: worktreeMap.get(name) ?? null,
};
})
.toSorted((a, b) => {
if (a.current !== b.current) return a.current ? -1 : 1;
if (a.isDefault !== b.isDefault) return a.isDefault ? -1 : 1;
return a.name.localeCompare(b.name);
});
return { branches, isRepo: true };
}
export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
const sanitizedBranch = input.newBranch.replace(/\//g, "-");
const repoName = path.basename(input.cwd);
const worktreePath =
input.path ?? path.join(os.homedir(), ".t3", "worktrees", repoName, sanitizedBranch);
// Create a new branch from the base branch in a new worktree
const result = await runGit(
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
input.cwd,
);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git worktree add failed");
}
return {
worktree: {
path: worktreePath,
branch: input.newBranch,
},
};
}
export async function removeGitWorktree(input: GitRemoveWorktreeInput): Promise<void> {
const result = await runGit(["worktree", "remove", input.path], input.cwd, 15_000);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git worktree remove failed");
}
}
export async function createGitBranch(input: GitCreateBranchInput): Promise<void> {
const result = await runGit(["branch", input.branch], input.cwd, 10_000);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git branch create failed");
}
}
export async function checkoutGitBranch(input: GitCheckoutInput): Promise<void> {
const result = await runGit(["checkout", input.branch], input.cwd, 10_000);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git checkout failed");
}
}
export async function initGitRepo(input: GitInitInput): Promise<void> {
const result = await runGit(["init"], input.cwd, 10_000);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git init failed");
}
}
+103 -37
View File
@@ -1,10 +1,12 @@
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { fixPath } from "./fixPath";
import { createLogger } from "./logger";
import { ProjectRegistry } from "./projectRegistry";
import { createServer } from "./wsServer";
fixPath();
@@ -13,6 +15,40 @@ const DEFAULT_PORT = 3773;
const cwd = process.cwd();
const logger = createLogger("server");
type RuntimeMode = "web" | "desktop";
function parseBooleanEnv(value: string | undefined): boolean | undefined {
if (value === undefined) return undefined;
const normalized = value.trim().toLowerCase();
if (["1", "true", "yes", "on"].includes(normalized)) return true;
if (["0", "false", "no", "off"].includes(normalized)) return false;
return undefined;
}
function parsePort(value: string | undefined): number | undefined {
if (!value) return undefined;
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
throw new Error(`Invalid T3CODE_PORT: ${value}`);
}
return parsed;
}
function expandHomePath(input: string): string {
if (input === "~") return os.homedir();
if (input.startsWith("~/")) {
return path.join(os.homedir(), input.slice(2));
}
return input;
}
function resolveStateDir(raw: string | undefined): string {
if (!raw || raw.trim().length === 0) {
return path.join(os.homedir(), ".t3", "userdata");
}
return path.resolve(expandHomePath(raw.trim()));
}
async function findAvailablePort(preferred: number): Promise<number> {
return new Promise((resolve, reject) => {
const server = net.createServer();
@@ -24,8 +60,7 @@ async function findAvailablePort(preferred: number): Promise<number> {
const fallback = net.createServer();
fallback.listen(0, () => {
const addr = fallback.address();
const port =
typeof addr === "object" && addr !== null ? addr.port : 0;
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
fallback.close(() => {
if (port > 0) resolve(port);
else reject(new Error("Could not find an available port."));
@@ -49,8 +84,8 @@ function resolveStaticDir(): string | undefined {
// Not bundled — check monorepo layout
}
// Monorepo layout: apps/server/dist/index.js → apps/renderer/dist/
const monorepoClient = path.resolve(__dirname, "../../renderer/dist");
// Monorepo layout: apps/server/dist/index.js → apps/web/dist/
const monorepoClient = path.resolve(__dirname, "../../web/dist");
try {
const stat = fs.statSync(path.join(monorepoClient, "index.html"));
if (stat.isFile()) return monorepoClient;
@@ -62,49 +97,80 @@ function resolveStaticDir(): string | undefined {
}
async function main() {
const port = await findAvailablePort(DEFAULT_PORT);
const mode: RuntimeMode = process.env.T3CODE_MODE === "desktop" ? "desktop" : "web";
const requestedPort = parsePort(process.env.T3CODE_PORT);
const port =
requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT));
const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
const projectRegistry = new ProjectRegistry(stateDir);
const devUrl = process.env.VITE_DEV_SERVER_URL;
const noBrowser = parseBooleanEnv(process.env.T3CODE_NO_BROWSER) ?? mode === "desktop";
const authToken = process.env.T3CODE_AUTH_TOKEN;
const staticDir = devUrl ? undefined : resolveStaticDir();
if (!devUrl && !staticDir) {
logger.warn(
"renderer bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
{
hint:
"Run `bun run --cwd apps/renderer build` or set VITE_DEV_SERVER_URL for dev mode.",
},
);
}
const server = createServer({ port, cwd, staticDir, devUrl });
await server.start();
const url = `http://localhost:${port}`;
logger.info("CodeThing running", { url, cwd });
// Open browser (dynamic import because `open` is ESM-only)
try {
const open = await import("open");
const target = devUrl ?? url;
await open.default(target);
} catch {
logger.info("browser auto-open unavailable", {
hint: `Open ${devUrl ?? url} in your browser.`,
logger.warn("web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable", {
hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
});
}
// Graceful shutdown
const shutdown = () => {
logger.info("shutting down");
server.stop();
process.exit(0);
};
const server = createServer({
port,
host: mode === "desktop" ? "127.0.0.1" : undefined,
cwd,
staticDir,
devUrl,
projectRegistry,
authToken,
});
await server.start();
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
const url = `http://localhost:${port}`;
logger.info("T3 Code running", {
url,
cwd,
mode,
stateDir,
authEnabled: Boolean(authToken),
});
// Open browser (dynamic import because `open` is ESM-only)
if (!noBrowser) {
try {
const open = await import("open");
const target = devUrl ?? url;
await open.default(target);
} catch {
logger.info("browser auto-open unavailable", {
hint: `Open ${devUrl ?? url} in your browser.`,
});
}
}
// Graceful shutdown
let shuttingDown = false;
async function shutdown() {
if (shuttingDown) return;
shuttingDown = true;
logger.info("shutting down");
try {
await server.stop();
process.exit(0);
} catch (error) {
logger.error("failed to stop server cleanly", { error });
process.exit(1);
}
}
process.on("SIGINT", () => {
void shutdown();
});
process.on("SIGTERM", () => {
void shutdown();
});
}
main().catch((err) => {
logger.error("failed to start CodeThing", { error: err });
logger.error("failed to start T3 Code", { error: err });
process.exit(1);
});
+172
View File
@@ -0,0 +1,172 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import {
type ProjectAddInput,
type ProjectAddResult,
type ProjectListResult,
type ProjectRecord,
type ProjectRemoveInput,
projectAddInputSchema,
projectRecordSchema,
projectRemoveInputSchema,
} from "@t3tools/contracts";
function normalizeCwd(rawCwd: string): string {
const resolved = path.resolve(rawCwd.trim());
const normalized = path.normalize(resolved);
if (process.platform === "win32") {
return normalized.toLowerCase();
}
return normalized;
}
function isDirectory(cwd: string): boolean {
try {
return fs.statSync(cwd).isDirectory();
} catch {
return false;
}
}
function inferProjectName(cwd: string): string {
const name = path.basename(cwd);
return name.length > 0 ? name : "project";
}
export class ProjectRegistry {
private readonly stateDir: string;
private readonly filePath: string;
private projects: ProjectRecord[];
constructor(stateDir: string) {
this.stateDir = stateDir;
this.filePath = path.join(this.stateDir, "projects.json");
fs.mkdirSync(this.stateDir, { recursive: true });
this.projects = this.loadFromDisk();
}
list(): ProjectListResult {
return this.projects.map((project) => ({ ...project }));
}
add(raw: ProjectAddInput): ProjectAddResult {
const input = projectAddInputSchema.parse(raw);
const normalizedCwd = normalizeCwd(input.cwd);
if (!isDirectory(normalizedCwd)) {
throw new Error(`Project path does not exist: ${normalizedCwd}`);
}
const existing = this.projects.find((project) => normalizeCwd(project.cwd) === normalizedCwd);
if (existing) {
return { project: { ...existing }, created: false };
}
const now = new Date().toISOString();
const project: ProjectRecord = {
id: randomUUID(),
cwd: normalizedCwd,
name: inferProjectName(normalizedCwd),
createdAt: now,
updatedAt: now,
};
this.projects = [project, ...this.projects];
this.persist();
return { project: { ...project }, created: true };
}
remove(raw: ProjectRemoveInput): void {
const input = projectRemoveInputSchema.parse(raw);
const next = this.projects.filter((project) => project.id !== input.id);
if (next.length === this.projects.length) {
return;
}
this.projects = next;
this.persist();
}
private loadFromDisk(): ProjectRecord[] {
const loaded = this.readPersistedProjects();
const deduped = new Map<string, ProjectRecord>();
const normalizedProjects: ProjectRecord[] = [];
for (const project of loaded) {
const normalizedCwd = normalizeCwd(project.cwd);
if (!isDirectory(normalizedCwd)) {
continue;
}
if (deduped.has(normalizedCwd)) {
continue;
}
const normalizedProject: ProjectRecord = {
...project,
cwd: normalizedCwd,
name:
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
};
deduped.set(normalizedCwd, normalizedProject);
normalizedProjects.push(normalizedProject);
}
const changed =
normalizedProjects.length !== loaded.length ||
normalizedProjects.some((project, index) => {
const source = loaded[index];
if (!source) return true;
return (
source.id !== project.id ||
source.cwd !== project.cwd ||
source.name !== project.name ||
source.createdAt !== project.createdAt ||
source.updatedAt !== project.updatedAt
);
});
if (changed) {
this.projects = normalizedProjects;
this.persist();
}
return normalizedProjects;
}
private readPersistedProjects(): ProjectRecord[] {
try {
const raw = fs.readFileSync(this.filePath, "utf8");
const parsed = JSON.parse(raw) as { projects?: unknown };
if (!parsed || !Array.isArray(parsed.projects)) {
return [];
}
const projects: ProjectRecord[] = [];
for (const candidate of parsed.projects) {
const row = projectRecordSchema.safeParse(candidate);
if (!row.success) {
continue;
}
projects.push(row.data);
}
return projects;
} catch {
return [];
}
}
private persist(): void {
const payload = JSON.stringify(
{
version: 1,
projects: this.projects,
},
null,
2,
);
const tempFile = `${this.filePath}.tmp-${process.pid}-${Date.now()}`;
fs.writeFileSync(tempFile, payload);
fs.renameSync(tempFile, this.filePath);
}
}
+1 -4
View File
@@ -16,10 +16,7 @@ describe("ProviderManager", () => {
method: string;
threadId: string;
}) => void;
threadLogStreams: Map<
string,
{ writableEnded: boolean; destroyed: boolean }
>;
threadLogStreams: Map<string, { writableEnded: boolean; destroyed: boolean }>;
};
internals.onCodexEvent({
id: "evt-1",
+3 -10
View File
@@ -16,7 +16,7 @@ import {
providerSendTurnInputSchema,
providerSessionStartInputSchema,
providerStopSessionInputSchema,
} from "@acme/contracts";
} from "@t3tools/contracts";
import { CodexAppServerManager } from "./codexAppServerManager";
export interface ProviderManagerEvents {
@@ -87,11 +87,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
await this.codex.respondToRequest(
input.sessionId,
input.requestId,
input.decision,
);
await this.codex.respondToRequest(input.sessionId, input.requestId, input.decision);
}
stopSession(raw: ProviderStopSessionInput): void {
@@ -151,10 +147,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
private resolveThreadId(event: ProviderEvent): string | undefined {
const fromPayload = this.readThreadIdFromPayload(event.payload);
const threadId =
event.threadId ??
fromPayload ??
this.sessionThreadIds.get(event.sessionId);
const threadId = event.threadId ?? fromPayload ?? this.sessionThreadIds.get(event.sessionId);
if (threadId) {
this.sessionThreadIds.set(event.sessionId, threadId);
+79
View File
@@ -0,0 +1,79 @@
import * as nodePty from "node-pty";
export interface PtyExitEvent {
exitCode: number;
signal: number | null;
}
export interface PtyProcess {
readonly pid: number;
write(data: string): void;
resize(cols: number, rows: number): void;
kill(signal?: string): void;
onData(callback: (data: string) => void): () => void;
onExit(callback: (event: PtyExitEvent) => void): () => void;
}
export interface PtySpawnInput {
shell: string;
cwd: string;
cols: number;
rows: number;
env: NodeJS.ProcessEnv;
}
export interface PtyAdapter {
spawn(input: PtySpawnInput): PtyProcess;
}
class NodePtyProcess implements PtyProcess {
constructor(private readonly process: nodePty.IPty) {}
get pid(): number {
return this.process.pid;
}
write(data: string): void {
this.process.write(data);
}
resize(cols: number, rows: number): void {
this.process.resize(cols, rows);
}
kill(signal?: string): void {
this.process.kill(signal);
}
onData(callback: (data: string) => void): () => void {
const disposable = this.process.onData(callback);
return () => {
disposable.dispose();
};
}
onExit(callback: (event: PtyExitEvent) => void): () => void {
const disposable = this.process.onExit((event) => {
callback({
exitCode: event.exitCode,
signal: event.signal ?? null,
});
});
return () => {
disposable.dispose();
};
}
}
export class NodePtyAdapter implements PtyAdapter {
spawn(input: PtySpawnInput): PtyProcess {
const ptyProcess = nodePty.spawn(input.shell, [], {
cwd: input.cwd,
cols: input.cols,
rows: input.rows,
env: input.env,
name: globalThis.process.platform === "win32" ? "xterm-color" : "xterm-256color",
});
return new NodePtyProcess(ptyProcess);
}
}
+269
View File
@@ -0,0 +1,269 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type {
TerminalEvent,
TerminalOpenInput,
} from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter";
import { TerminalManager } from "./terminalManager";
class FakePtyProcess implements PtyProcess {
readonly writes: string[] = [];
readonly resizeCalls: Array<{ cols: number; rows: number }> = [];
private readonly dataListeners = new Set<(data: string) => void>();
private readonly exitListeners = new Set<(event: PtyExitEvent) => void>();
killed = false;
constructor(readonly pid: number) {}
write(data: string): void {
this.writes.push(data);
}
resize(cols: number, rows: number): void {
this.resizeCalls.push({ cols, rows });
}
kill(): void {
this.killed = true;
}
onData(callback: (data: string) => void): () => void {
this.dataListeners.add(callback);
return () => {
this.dataListeners.delete(callback);
};
}
onExit(callback: (event: PtyExitEvent) => void): () => void {
this.exitListeners.add(callback);
return () => {
this.exitListeners.delete(callback);
};
}
emitData(data: string): void {
for (const listener of this.dataListeners) {
listener(data);
}
}
emitExit(event: PtyExitEvent): void {
for (const listener of this.exitListeners) {
listener(event);
}
}
}
class FakePtyAdapter implements PtyAdapter {
readonly spawnInputs: PtySpawnInput[] = [];
readonly processes: FakePtyProcess[] = [];
private nextPid = 9000;
spawn(input: PtySpawnInput): PtyProcess {
this.spawnInputs.push(input);
const process = new FakePtyProcess(this.nextPid++);
this.processes.push(process);
return process;
}
}
function waitFor(predicate: () => boolean, timeoutMs = 800): Promise<void> {
const started = Date.now();
return new Promise((resolve, reject) => {
const poll = () => {
if (predicate()) {
resolve();
return;
}
if (Date.now() - started > timeoutMs) {
reject(new Error("Timed out waiting for condition"));
return;
}
setTimeout(poll, 15);
};
poll();
});
}
function openInput(overrides: Partial<TerminalOpenInput> = {}): TerminalOpenInput {
return {
threadId: "thread-1",
cwd: process.cwd(),
cols: 100,
rows: 24,
...overrides,
};
}
function historyLogName(threadId: string): string {
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}.log`;
}
function historyLogPath(logsDir: string, threadId = "thread-1"): string {
return path.join(logsDir, historyLogName(threadId));
}
describe("TerminalManager", () => {
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
function makeManager(historyLineLimit = 5) {
const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-"));
tempDirs.push(logsDir);
const ptyAdapter = new FakePtyAdapter();
const manager = new TerminalManager({
logsDir,
ptyAdapter,
historyLineLimit,
shellResolver: () => "/bin/bash",
});
return { logsDir, ptyAdapter, manager };
}
it("spawns lazily and reuses running terminal per thread", async () => {
const { manager, ptyAdapter } = makeManager();
const [first, second] = await Promise.all([manager.open(openInput()), manager.open(openInput())]);
const third = await manager.open(openInput());
expect(first.threadId).toBe("thread-1");
expect(second.threadId).toBe("thread-1");
expect(third.threadId).toBe("thread-1");
expect(ptyAdapter.spawnInputs).toHaveLength(1);
manager.dispose();
});
it("forwards write and resize to active pty process", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
await manager.write({ threadId: "thread-1", data: "ls\n" });
await manager.resize({ threadId: "thread-1", cols: 120, rows: 30 });
expect(process.writes).toEqual(["ls\n"]);
expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]);
manager.dispose();
});
it("clears transcript and emits cleared event", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
const events: TerminalEvent[] = [];
manager.on("event", (event) => {
events.push(event);
});
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("hello\n");
await waitFor(() => fs.existsSync(historyLogPath(logsDir)));
await manager.clear({ threadId: "thread-1" });
await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === "");
expect(events.some((event) => event.type === "cleared")).toBe(true);
manager.dispose();
});
it("restarts terminal with empty transcript and respawns pty", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput());
const firstProcess = ptyAdapter.processes[0];
expect(firstProcess).toBeDefined();
if (!firstProcess) return;
firstProcess.emitData("before restart\n");
await waitFor(() => fs.existsSync(historyLogPath(logsDir)));
const snapshot = await manager.restart(openInput());
expect(snapshot.history).toBe("");
expect(snapshot.status).toBe("running");
expect(ptyAdapter.spawnInputs).toHaveLength(2);
await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === "");
manager.dispose();
});
it("emits exited event and reopens with clean transcript after exit", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
const events: TerminalEvent[] = [];
manager.on("event", (event) => {
events.push(event);
});
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("old data\n");
await waitFor(() => fs.existsSync(historyLogPath(logsDir)));
process.emitExit({ exitCode: 0, signal: 0 });
await waitFor(() => events.some((event) => event.type === "exited"));
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("");
expect(ptyAdapter.spawnInputs).toHaveLength(2);
expect(fs.readFileSync(historyLogPath(logsDir), "utf8")).toBe("");
manager.dispose();
});
it("caps persisted history to configured line limit", async () => {
const { manager, ptyAdapter } = makeManager(3);
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("line1\nline2\nline3\nline4\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
const nonEmptyLines = reopened.history.split("\n").filter((line) => line.length > 0);
expect(nonEmptyLines).toEqual(["line2", "line3", "line4"]);
manager.dispose();
});
it("deletes history file when close(deleteHistory=true)", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("bye\n");
await waitFor(() => fs.existsSync(historyLogPath(logsDir)));
await manager.close({ threadId: "thread-1", deleteHistory: true });
expect(fs.existsSync(historyLogPath(logsDir))).toBe(false);
manager.dispose();
});
it("loads existing legacy transcript filenames and keeps new naming for writes", async () => {
const { manager, logsDir } = makeManager();
const legacyPath = path.join(logsDir, "thread-1.log");
fs.writeFileSync(legacyPath, "legacy-line\n", "utf8");
const snapshot = await manager.open(openInput());
expect(snapshot.history).toBe("legacy-line\n");
expect(fs.existsSync(legacyPath)).toBe(true);
manager.dispose();
});
});
+566
View File
@@ -0,0 +1,566 @@
import { EventEmitter } from "node:events";
import fs from "node:fs";
import path from "node:path";
import {
type TerminalCloseInput,
type TerminalEvent,
type TerminalOpenInput,
type TerminalSessionSnapshot,
type TerminalSessionStatus,
type TerminalThreadInput,
type TerminalWriteInput,
terminalCloseInputSchema,
terminalOpenInputSchema,
terminalResizeInputSchema,
terminalThreadInputSchema,
terminalWriteInputSchema,
} from "@t3tools/contracts";
import { createLogger } from "./logger";
import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
export interface TerminalManagerEvents {
event: [event: TerminalEvent];
}
export interface TerminalManagerOptions {
logsDir?: string;
historyLineLimit?: number;
ptyAdapter?: PtyAdapter;
shellResolver?: () => string;
}
interface TerminalSessionState {
threadId: string;
cwd: string;
status: TerminalSessionStatus;
pid: number | null;
history: string;
exitCode: number | null;
exitSignal: number | null;
updatedAt: string;
cols: number;
rows: number;
process: PtyProcess | null;
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
}
function defaultShellResolver(): string {
if (process.platform === "win32") {
return process.env.ComSpec ?? "cmd.exe";
}
return process.env.SHELL ?? "bash";
}
function capHistory(history: string, maxLines: number): string {
if (history.length === 0) return history;
const hasTrailingNewline = history.endsWith("\n");
const lines = history.split("\n");
if (hasTrailingNewline) {
lines.pop();
}
if (lines.length <= maxLines) return history;
const capped = lines.slice(lines.length - maxLines).join("\n");
return hasTrailingNewline ? `${capped}\n` : capped;
}
function legacySafeThreadId(threadId: string): string {
return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
}
function toSafeThreadId(threadId: string): string {
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
}
export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private readonly sessions = new Map<string, TerminalSessionState>();
private readonly logsDir: string;
private readonly historyLineLimit: number;
private readonly ptyAdapter: PtyAdapter;
private readonly shellResolver: () => string;
private readonly persistQueues = new Map<string, Promise<void>>();
private readonly persistTimers = new Map<string, ReturnType<typeof setTimeout>>();
private readonly pendingPersistHistory = new Map<string, string>();
private readonly threadLocks = new Map<string, Promise<void>>();
private readonly persistDebounceMs: number;
private readonly logger = createLogger("terminal");
constructor(options: TerminalManagerOptions = {}) {
super();
this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals");
this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter();
this.shellResolver = options.shellResolver ?? defaultShellResolver;
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
fs.mkdirSync(this.logsDir, { recursive: true });
}
async open(raw: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const input = terminalOpenInputSchema.parse(raw);
return this.runWithThreadLock(input.threadId, async () => {
await this.assertValidCwd(input.cwd);
const existing = this.sessions.get(input.threadId);
if (!existing) {
await this.flushPersistQueue(input.threadId);
const history = await this.readHistory(input.threadId);
const session: TerminalSessionState = {
threadId: input.threadId,
cwd: input.cwd,
status: "starting",
pid: null,
history,
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
cols: input.cols,
rows: input.rows,
process: null,
unsubscribeData: null,
unsubscribeExit: null,
};
this.sessions.set(input.threadId, session);
this.startSession(session, input, "started");
return this.snapshot(session);
}
if (existing.cwd !== input.cwd) {
this.stopProcess(existing);
existing.cwd = input.cwd;
existing.history = "";
await this.persistHistory(existing.threadId, existing.history);
} else if (existing.status === "exited" || existing.status === "error") {
existing.history = "";
await this.persistHistory(existing.threadId, existing.history);
}
if (!existing.process) {
this.startSession(existing, input, "started");
return this.snapshot(existing);
}
if (existing.cols !== input.cols || existing.rows !== input.rows) {
existing.cols = input.cols;
existing.rows = input.rows;
existing.process.resize(input.cols, input.rows);
existing.updatedAt = new Date().toISOString();
}
return this.snapshot(existing);
});
}
async write(raw: TerminalWriteInput): Promise<void> {
const input = terminalWriteInputSchema.parse(raw);
const session = this.requireSession(input.threadId);
if (!session.process || session.status !== "running") {
throw new Error(`Terminal is not running for thread: ${input.threadId}`);
}
session.process.write(input.data);
}
async resize(raw: TerminalThreadInput & { cols: number; rows: number }): Promise<void> {
const input = terminalResizeInputSchema.parse(raw);
const session = this.requireSession(input.threadId);
if (!session.process || session.status !== "running") {
throw new Error(`Terminal is not running for thread: ${input.threadId}`);
}
session.cols = input.cols;
session.rows = input.rows;
session.updatedAt = new Date().toISOString();
session.process.resize(input.cols, input.rows);
}
async clear(raw: TerminalThreadInput): Promise<void> {
const input = terminalThreadInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => {
const session = this.requireSession(input.threadId);
session.history = "";
session.updatedAt = new Date().toISOString();
await this.persistHistory(input.threadId, session.history);
this.emitEvent({
type: "cleared",
threadId: input.threadId,
createdAt: new Date().toISOString(),
});
});
}
async restart(raw: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const input = terminalOpenInputSchema.parse(raw);
return this.runWithThreadLock(input.threadId, async () => {
await this.assertValidCwd(input.cwd);
let session = this.sessions.get(input.threadId);
if (!session) {
session = {
threadId: input.threadId,
cwd: input.cwd,
status: "starting",
pid: null,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
cols: input.cols,
rows: input.rows,
process: null,
unsubscribeData: null,
unsubscribeExit: null,
};
this.sessions.set(input.threadId, session);
} else {
this.stopProcess(session);
session.cwd = input.cwd;
}
session.history = "";
await this.persistHistory(input.threadId, session.history);
this.startSession(session, input, "restarted");
return this.snapshot(session);
});
}
async close(raw: TerminalCloseInput): Promise<void> {
const input = terminalCloseInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => {
const session = this.sessions.get(input.threadId);
if (session) {
this.stopProcess(session);
this.sessions.delete(input.threadId);
}
await this.flushPersistQueue(input.threadId);
if (input.deleteHistory) {
await this.deleteHistory(input.threadId);
}
});
}
dispose(): void {
for (const session of this.sessions.values()) {
this.stopProcess(session);
}
this.sessions.clear();
for (const timer of this.persistTimers.values()) {
clearTimeout(timer);
}
this.persistTimers.clear();
this.pendingPersistHistory.clear();
this.threadLocks.clear();
this.persistQueues.clear();
}
private startSession(
session: TerminalSessionState,
input: TerminalOpenInput,
eventType: "started" | "restarted",
): void {
this.stopProcess(session);
session.status = "starting";
session.cwd = input.cwd;
session.cols = input.cols;
session.rows = input.rows;
session.exitCode = null;
session.exitSignal = null;
session.updatedAt = new Date().toISOString();
const shell = this.shellResolver();
let ptyProcess: PtyProcess | null = null;
try {
ptyProcess = this.ptyAdapter.spawn({
shell,
cwd: session.cwd,
cols: session.cols,
rows: session.rows,
env: process.env,
});
session.process = ptyProcess;
session.pid = ptyProcess.pid;
session.status = "running";
session.updatedAt = new Date().toISOString();
session.unsubscribeData = ptyProcess.onData((data) => {
this.onProcessData(session, data);
});
session.unsubscribeExit = ptyProcess.onExit((event) => {
this.onProcessExit(session, event);
});
this.emitEvent({
type: eventType,
threadId: session.threadId,
createdAt: new Date().toISOString(),
snapshot: this.snapshot(session),
});
} catch (error) {
if (ptyProcess) {
try {
ptyProcess.kill();
} catch {
// Ignore kill errors during failed startup cleanup.
}
}
session.status = "error";
session.pid = null;
session.process = null;
session.updatedAt = new Date().toISOString();
const message = error instanceof Error ? error.message : "Terminal start failed";
this.emitEvent({
type: "error",
threadId: session.threadId,
createdAt: new Date().toISOString(),
message,
});
this.logger.error("failed to start terminal", {
threadId: session.threadId,
error: message,
});
}
}
private onProcessData(session: TerminalSessionState, data: string): void {
session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
session.updatedAt = new Date().toISOString();
this.queuePersist(session.threadId, session.history);
this.emitEvent({
type: "output",
threadId: session.threadId,
createdAt: new Date().toISOString(),
data,
});
}
private onProcessExit(session: TerminalSessionState, event: PtyExitEvent): void {
this.cleanupProcessHandles(session);
session.process = null;
session.pid = null;
session.status = "exited";
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
session.updatedAt = new Date().toISOString();
this.emitEvent({
type: "exited",
threadId: session.threadId,
createdAt: new Date().toISOString(),
exitCode: session.exitCode,
exitSignal: session.exitSignal,
});
}
private stopProcess(session: TerminalSessionState): void {
const process = session.process;
if (!process) return;
this.cleanupProcessHandles(session);
session.process = null;
session.pid = null;
session.status = "exited";
session.updatedAt = new Date().toISOString();
try {
process.kill();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.logger.warn("failed to kill terminal process", {
threadId: session.threadId,
error: message,
});
}
}
private cleanupProcessHandles(session: TerminalSessionState): void {
session.unsubscribeData?.();
session.unsubscribeData = null;
session.unsubscribeExit?.();
session.unsubscribeExit = null;
}
private queuePersist(threadId: string, history: string): void {
this.pendingPersistHistory.set(threadId, history);
this.schedulePersist(threadId);
}
private async persistHistory(threadId: string, history: string): Promise<void> {
this.clearPersistTimer(threadId);
this.pendingPersistHistory.delete(threadId);
await this.enqueuePersistWrite(threadId, history);
}
private enqueuePersistWrite(threadId: string, history: string): Promise<void> {
const task = async () => {
await fs.promises.writeFile(this.historyPath(threadId), history, "utf8");
};
const previous = this.persistQueues.get(threadId) ?? Promise.resolve();
const next = previous
.catch(() => undefined)
.then(task)
.catch((error) => {
this.logger.warn("failed to persist terminal history", {
threadId,
error: error instanceof Error ? error.message : String(error),
});
});
this.persistQueues.set(threadId, next);
const finalized = next.finally(() => {
if (this.persistQueues.get(threadId) === next) {
this.persistQueues.delete(threadId);
}
if (this.pendingPersistHistory.has(threadId) && !this.persistTimers.has(threadId)) {
this.schedulePersist(threadId);
}
});
void finalized.catch(() => undefined);
return finalized;
}
private schedulePersist(threadId: string): void {
if (this.persistTimers.has(threadId)) return;
const timer = setTimeout(() => {
this.persistTimers.delete(threadId);
const pendingHistory = this.pendingPersistHistory.get(threadId);
if (pendingHistory === undefined) return;
this.pendingPersistHistory.delete(threadId);
void this.enqueuePersistWrite(threadId, pendingHistory);
}, this.persistDebounceMs);
this.persistTimers.set(threadId, timer);
}
private clearPersistTimer(threadId: string): void {
const timer = this.persistTimers.get(threadId);
if (!timer) return;
clearTimeout(timer);
this.persistTimers.delete(threadId);
}
private async readHistory(threadId: string): Promise<string> {
try {
const raw = await fs.promises.readFile(this.historyPath(threadId), "utf8");
const capped = capHistory(raw, this.historyLineLimit);
if (capped !== raw) {
await fs.promises.writeFile(this.historyPath(threadId), capped, "utf8");
}
return capped;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
throw error;
}
}
try {
const raw = await fs.promises.readFile(this.legacyHistoryPath(threadId), "utf8");
const capped = capHistory(raw, this.historyLineLimit);
if (capped !== raw) {
await fs.promises.writeFile(this.legacyHistoryPath(threadId), capped, "utf8");
}
return capped;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return "";
}
throw error;
}
}
private async deleteHistory(threadId: string): Promise<void> {
try {
await Promise.all([
fs.promises.rm(this.historyPath(threadId), { force: true }),
fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }),
]);
} catch (error) {
this.logger.warn("failed to delete terminal history", {
threadId,
error: error instanceof Error ? error.message : String(error),
});
}
}
private async flushPersistQueue(threadId: string): Promise<void> {
this.clearPersistTimer(threadId);
while (true) {
const pendingHistory = this.pendingPersistHistory.get(threadId);
if (pendingHistory !== undefined) {
this.pendingPersistHistory.delete(threadId);
await this.enqueuePersistWrite(threadId, pendingHistory);
}
const pending = this.persistQueues.get(threadId);
if (!pending) {
return;
}
await pending.catch(() => undefined);
}
}
private async assertValidCwd(cwd: string): Promise<void> {
let stats: fs.Stats;
try {
stats = await fs.promises.stat(cwd);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
throw new Error(`Terminal cwd does not exist: ${cwd}`, { cause: error });
}
throw error;
}
if (!stats.isDirectory()) {
throw new Error(`Terminal cwd is not a directory: ${cwd}`);
}
}
private requireSession(threadId: string): TerminalSessionState {
const session = this.sessions.get(threadId);
if (!session) {
throw new Error(`Unknown terminal thread: ${threadId}`);
}
return session;
}
private snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
return {
threadId: session.threadId,
cwd: session.cwd,
status: session.status,
pid: session.pid,
history: session.history,
exitCode: session.exitCode,
exitSignal: session.exitSignal,
updatedAt: session.updatedAt,
};
}
private emitEvent(event: TerminalEvent): void {
this.emit("event", event);
}
private historyPath(threadId: string): string {
return path.join(this.logsDir, `${toSafeThreadId(threadId)}.log`);
}
private legacyHistoryPath(threadId: string): string {
return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`);
}
private async runWithThreadLock<T>(
threadId: string,
task: () => Promise<T>,
): Promise<T> {
const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
let release: () => void = () => {};
const current = new Promise<void>((resolve) => {
release = resolve;
});
this.threadLocks.set(threadId, current);
await previous.catch(() => undefined);
try {
return await task();
} finally {
release();
if (this.threadLocks.get(threadId) === current) {
this.threadLocks.delete(threadId);
}
}
}
}
+390 -17
View File
@@ -1,8 +1,23 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { EventEmitter } from "node:events";
import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
import WebSocket from "ws";
import { WS_CHANNELS, WS_METHODS, type WsPush, type WsResponse } from "@acme/contracts";
import { WS_CHANNELS, WS_METHODS, type WsPush, type WsResponse } from "@t3tools/contracts";
import { ProjectRegistry } from "./projectRegistry";
import type {
TerminalCloseInput,
TerminalEvent,
TerminalOpenInput,
TerminalSessionSnapshot,
TerminalThreadInput,
TerminalWriteInput,
} from "@t3tools/contracts";
import type { TerminalManager } from "./terminalManager";
interface PendingMessages {
queue: unknown[];
@@ -11,9 +26,95 @@ interface PendingMessages {
const pendingBySocket = new WeakMap<WebSocket, PendingMessages>();
function connectWs(port: number): Promise<WebSocket> {
class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }> {
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
async open(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const now = new Date().toISOString();
const snapshot: TerminalSessionSnapshot = {
threadId: input.threadId,
cwd: input.cwd,
status: "running",
pid: 4242,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: now,
};
this.sessions.set(input.threadId, snapshot);
queueMicrotask(() => {
this.emit("event", {
type: "started",
threadId: input.threadId,
createdAt: now,
snapshot,
});
});
return snapshot;
}
async write(input: TerminalWriteInput): Promise<void> {
const existing = this.sessions.get(input.threadId);
if (!existing) {
throw new Error(`Unknown terminal thread: ${input.threadId}`);
}
queueMicrotask(() => {
this.emit("event", {
type: "output",
threadId: input.threadId,
createdAt: new Date().toISOString(),
data: input.data,
});
});
}
async resize(_input: TerminalThreadInput & { cols: number; rows: number }): Promise<void> {}
async clear(input: TerminalThreadInput): Promise<void> {
queueMicrotask(() => {
this.emit("event", {
type: "cleared",
threadId: input.threadId,
createdAt: new Date().toISOString(),
});
});
}
async restart(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const now = new Date().toISOString();
const snapshot: TerminalSessionSnapshot = {
threadId: input.threadId,
cwd: input.cwd,
status: "running",
pid: 5252,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: now,
};
this.sessions.set(input.threadId, snapshot);
queueMicrotask(() => {
this.emit("event", {
type: "restarted",
threadId: input.threadId,
createdAt: now,
snapshot,
});
});
return snapshot;
}
async close(input: TerminalCloseInput): Promise<void> {
this.sessions.delete(input.threadId);
}
dispose(): void {}
}
function connectWs(port: number, token?: string): Promise<WebSocket> {
return new Promise((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${port}`);
const query = token ? `?token=${encodeURIComponent(token)}` : "";
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
const pending: PendingMessages = { queue: [], waiters: [] };
pendingBySocket.set(ws, pending);
@@ -48,11 +149,7 @@ function waitForMessage(ws: WebSocket): Promise<unknown> {
});
}
async function sendRequest(
ws: WebSocket,
method: string,
params?: unknown,
): Promise<WsResponse> {
async function sendRequest(ws: WebSocket, method: string, params?: unknown): Promise<WsResponse> {
const id = crypto.randomUUID();
const message = JSON.stringify({ id, method, ...(params !== undefined ? { params } : {}) });
ws.send(message);
@@ -69,19 +166,53 @@ async function sendRequest(
describe("WebSocket Server", () => {
let server: ReturnType<typeof createServer> | null = null;
const connections: WebSocket[] = [];
const tempDirs: string[] = [];
afterEach(() => {
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
function createTestServer(
options: {
cwd?: string;
devUrl?: string;
authToken?: string;
stateDir?: string;
terminalManager?: TerminalManager;
} = {},
): ReturnType<typeof createServer> {
const stateDir = options.stateDir ?? makeTempDir("t3code-ws-state-");
return createServer({
port: 0,
cwd: options.cwd ?? "/test/project",
...(options.devUrl ? { devUrl: options.devUrl } : {}),
...(options.authToken ? { authToken: options.authToken } : {}),
projectRegistry: new ProjectRegistry(stateDir),
...(options.terminalManager
? { terminalManager: options.terminalManager }
: {}),
});
}
afterEach(async () => {
for (const ws of connections) {
ws.close();
}
connections.length = 0;
server?.stop();
if (server) {
await server.stop();
}
server = null;
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
vi.restoreAllMocks();
});
it("sends welcome message on connect", async () => {
server = createServer({ port: 0, cwd: "/test/project" });
server = createTestServer({ cwd: "/test/project" });
// Get the actual port after listen
await server.start();
const addr = server.httpServer.address();
@@ -105,8 +236,7 @@ describe("WebSocket Server", () => {
// Keep test output clean while verifying websocket logs.
});
server = createServer({
port: 0,
server = createTestServer({
cwd: "/test/project",
devUrl: "http://localhost:5173",
});
@@ -132,7 +262,7 @@ describe("WebSocket Server", () => {
});
it("responds to server.getConfig", async () => {
server = createServer({ port: 0, cwd: "/my/workspace" });
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -149,7 +279,7 @@ describe("WebSocket Server", () => {
});
it("returns error for unknown methods", async () => {
server = createServer({ port: 0, cwd: "/test" });
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -166,7 +296,7 @@ describe("WebSocket Server", () => {
});
it("responds to providers.listSessions with empty array", async () => {
server = createServer({ port: 0, cwd: "/test" });
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -182,8 +312,113 @@ describe("WebSocket Server", () => {
expect(response.result).toEqual([]);
});
it("routes terminal RPC methods and broadcasts terminal events", async () => {
const cwd = makeTempDir("t3code-ws-terminal-cwd-");
const terminalManager = new MockTerminalManager();
server = createTestServer({
cwd: "/test",
terminalManager: terminalManager as unknown as TerminalManager,
});
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const open = await sendRequest(ws, WS_METHODS.terminalOpen, {
threadId: "thread-1",
cwd,
cols: 100,
rows: 24,
});
expect(open.error).toBeUndefined();
expect((open.result as TerminalSessionSnapshot).threadId).toBe("thread-1");
const write = await sendRequest(ws, WS_METHODS.terminalWrite, {
threadId: "thread-1",
data: "echo hello\n",
});
expect(write.error).toBeUndefined();
const resize = await sendRequest(ws, WS_METHODS.terminalResize, {
threadId: "thread-1",
cols: 120,
rows: 30,
});
expect(resize.error).toBeUndefined();
const clear = await sendRequest(ws, WS_METHODS.terminalClear, {
threadId: "thread-1",
});
expect(clear.error).toBeUndefined();
const restart = await sendRequest(ws, WS_METHODS.terminalRestart, {
threadId: "thread-1",
cwd,
cols: 120,
rows: 30,
});
expect(restart.error).toBeUndefined();
const close = await sendRequest(ws, WS_METHODS.terminalClose, {
threadId: "thread-1",
deleteHistory: true,
});
expect(close.error).toBeUndefined();
const manualEvent: TerminalEvent = {
type: "output",
threadId: "thread-1",
createdAt: new Date().toISOString(),
data: "manual test output\n",
};
terminalManager.emit("event", manualEvent);
const push = (await waitForMessage(ws)) as WsPush;
expect(push.type).toBe("push");
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
expect((push.data as TerminalEvent).type).toBe("output");
});
it("detaches terminal event listener on stop for injected manager", async () => {
const terminalManager = new MockTerminalManager();
server = createTestServer({
cwd: "/test",
terminalManager: terminalManager as unknown as TerminalManager,
});
await server.start();
expect(terminalManager.listenerCount("event")).toBe(1);
await server.stop();
server = null;
expect(terminalManager.listenerCount("event")).toBe(0);
});
it("returns validation errors for invalid terminal open params", async () => {
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.terminalOpen, {
threadId: "",
cwd: "",
cols: 1,
rows: 1,
});
expect(response.error).toBeDefined();
});
it("handles invalid JSON gracefully", async () => {
server = createServer({ port: 0, cwd: "/test" });
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -201,4 +436,142 @@ describe("WebSocket Server", () => {
expect(response.error).toBeDefined();
expect(response.error!.message).toContain("Invalid request format");
});
it("supports projects list/add/dedupe/remove", async () => {
const stateDir = makeTempDir("t3code-ws-projects-state-");
const firstProjectCwd = makeTempDir("t3code-ws-project-a-");
server = createTestServer({ stateDir, cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const emptyList = await sendRequest(ws, WS_METHODS.projectsList);
expect(emptyList.error).toBeUndefined();
expect(emptyList.result).toEqual([]);
const created = await sendRequest(ws, WS_METHODS.projectsAdd, {
cwd: firstProjectCwd,
});
expect(created.error).toBeUndefined();
expect((created.result as { created: boolean }).created).toBe(true);
const duplicate = await sendRequest(ws, WS_METHODS.projectsAdd, {
cwd: firstProjectCwd,
});
expect(duplicate.error).toBeUndefined();
expect((duplicate.result as { created: boolean }).created).toBe(false);
const listed = await sendRequest(ws, WS_METHODS.projectsList);
expect(listed.error).toBeUndefined();
const listedProjects = listed.result as Array<{ id: string; cwd: string }>;
expect(listedProjects).toHaveLength(1);
const projectId = listedProjects[0]?.id;
expect(projectId).toBeTruthy();
if (!projectId) return;
const removed = await sendRequest(ws, WS_METHODS.projectsRemove, {
id: projectId,
});
expect(removed.error).toBeUndefined();
const afterRemove = await sendRequest(ws, WS_METHODS.projectsList);
expect(afterRemove.error).toBeUndefined();
expect(afterRemove.result).toEqual([]);
});
it("supports git methods over websocket", async () => {
const repoCwd = makeTempDir("t3code-ws-git-project-");
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const beforeInit = await sendRequest(ws, WS_METHODS.gitListBranches, { cwd: repoCwd });
expect(beforeInit.error).toBeUndefined();
expect(beforeInit.result).toEqual({ branches: [], isRepo: false });
const initResponse = await sendRequest(ws, WS_METHODS.gitInit, { cwd: repoCwd });
expect(initResponse.error).toBeUndefined();
const afterInit = await sendRequest(ws, WS_METHODS.gitListBranches, {
cwd: repoCwd,
});
expect(afterInit.error).toBeUndefined();
expect((afterInit.result as { isRepo: boolean }).isRepo).toBe(true);
});
it("prunes missing projects on startup", async () => {
const stateDir = makeTempDir("t3code-ws-prune-state-");
const existing = makeTempDir("t3code-ws-existing-project-");
const missing = path.join(stateDir, "definitely-missing");
const now = new Date().toISOString();
const projectsFile = path.join(stateDir, "projects.json");
fs.writeFileSync(
projectsFile,
JSON.stringify(
{
version: 1,
projects: [
{
id: "project-existing",
cwd: existing,
name: "existing",
createdAt: now,
updatedAt: now,
},
{
id: "project-missing",
cwd: missing,
name: "missing",
createdAt: now,
updatedAt: now,
},
],
},
null,
2,
),
);
server = createTestServer({ stateDir, cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.projectsList);
expect(response.error).toBeUndefined();
const listed = response.result as Array<{ id: string }>;
expect(listed).toHaveLength(1);
expect(listed[0]?.id).toBe("project-existing");
});
it("rejects websocket connections without a valid auth token", async () => {
server = createTestServer({ cwd: "/test", authToken: "secret-token" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
await expect(connectWs(port)).rejects.toThrow("WebSocket connection failed");
const authorizedWs = await connectWs(port, "secret-token");
connections.push(authorizedWs);
const welcome = (await waitForMessage(authorizedWs)) as WsPush;
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
});
});
+185 -15
View File
@@ -1,21 +1,34 @@
import { spawn } from "node:child_process";
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import type { Duplex } from "node:stream";
import {
EDITORS,
WS_CHANNELS,
WS_METHODS,
type TerminalEvent,
type WsPush,
type WsRequest,
type WsResponse,
wsRequestSchema,
} from "@acme/contracts";
} from "@t3tools/contracts";
import { WebSocketServer, type WebSocket } from "ws";
import { createLogger } from "./logger";
import { ProjectRegistry } from "./projectRegistry";
import { ProviderManager } from "./providerManager";
import {
checkoutGitBranch,
createGitBranch,
createGitWorktree,
initGitRepo,
listGitBranches,
removeGitWorktree,
} from "./git";
import { TerminalManager } from "./terminalManager";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -34,10 +47,14 @@ const MIME_TYPES: Record<string, string> = {
export interface ServerOptions {
port: number;
host?: string | undefined;
cwd: string;
staticDir?: string | undefined;
devUrl?: string | undefined;
logWebSocketEvents?: boolean | undefined;
projectRegistry?: ProjectRegistry | undefined;
terminalManager?: TerminalManager | undefined;
authToken?: string | undefined;
}
function parseBooleanEnv(value: string | undefined): boolean | undefined {
@@ -49,14 +66,25 @@ function parseBooleanEnv(value: string | undefined): boolean | undefined {
}
export function createServer(options: ServerOptions) {
const { port, cwd, staticDir, devUrl, logWebSocketEvents: explicitLogWsEvents } = options;
const {
port,
host,
cwd,
staticDir,
devUrl,
logWebSocketEvents: explicitLogWsEvents,
projectRegistry: providedRegistry,
terminalManager: providedTerminalManager,
authToken,
} = options;
const providerManager = new ProviderManager();
const terminalManager = providedTerminalManager ?? new TerminalManager();
const projectRegistry =
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
const clients = new Set<WebSocket>();
const logger = createLogger("ws");
const logWebSocketEvents =
explicitLogWsEvents ??
parseBooleanEnv(process.env.CODETHING_LOG_WS_EVENTS) ??
Boolean(devUrl);
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
function logOutgoingPush(push: WsPush, recipients: number) {
if (!logWebSocketEvents) return;
@@ -85,6 +113,24 @@ export function createServer(options: ServerOptions) {
logOutgoingPush(push, recipients);
});
const onTerminalEvent = (event: TerminalEvent) => {
const push: WsPush = {
type: "push",
channel: WS_CHANNELS.terminalEvent,
data: event,
};
const message = JSON.stringify(push);
let recipients = 0;
for (const client of clients) {
if (client.readyState === client.OPEN) {
client.send(message);
recipients += 1;
}
}
logOutgoingPush(push, recipients);
};
terminalManager.on("event", onTerminalEvent);
// HTTP server — serves static files or redirects to Vite dev server
const httpServer = http.createServer((req, res) => {
// In dev mode, redirect to Vite dev server
@@ -94,7 +140,7 @@ export function createServer(options: ServerOptions) {
return;
}
// Serve static files from the renderer build
// Serve static files from the web app build
if (!staticDir) {
res.writeHead(503, { "Content-Type": "text/plain" });
res.end("No static directory configured and no dev URL set.");
@@ -142,7 +188,41 @@ export function createServer(options: ServerOptions) {
});
// WebSocket server — upgrades from the HTTP server
const wss = new WebSocketServer({ server: httpServer });
const wss = new WebSocketServer({ noServer: true });
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
socket.write(
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
"Connection: close\r\n" +
"Content-Type: text/plain\r\n" +
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
"\r\n" +
message,
);
socket.destroy();
}
httpServer.on("upgrade", (request, socket, head) => {
if (authToken) {
let providedToken: string | null = null;
try {
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
providedToken = url.searchParams.get("token");
} catch {
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
return;
}
if (providedToken !== authToken) {
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
return;
}
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit("connection", ws, request);
});
});
wss.on("connection", (ws) => {
clients.add(ws);
@@ -191,8 +271,7 @@ export function createServer(options: ServerOptions) {
const response: WsResponse = { id: request.id, result };
ws.send(JSON.stringify(response));
} catch (err) {
const message =
err instanceof Error ? err.message : "Unknown server error";
const message = err instanceof Error ? err.message : "Unknown server error";
const response: WsResponse = {
id: request.id,
error: { message },
@@ -223,6 +302,16 @@ export function createServer(options: ServerOptions) {
case WS_METHODS.providersListSessions:
return providerManager.listSessions();
case WS_METHODS.projectsList:
return projectRegistry.list();
case WS_METHODS.projectsAdd:
return projectRegistry.add(request.params as never);
case WS_METHODS.projectsRemove:
projectRegistry.remove(request.params as never);
return undefined;
case WS_METHODS.shellOpenInEditor: {
const params = request.params as {
cwd: string;
@@ -246,6 +335,46 @@ export function createServer(options: ServerOptions) {
return undefined;
}
case WS_METHODS.gitListBranches:
return listGitBranches(request.params as never);
case WS_METHODS.gitCreateWorktree:
return createGitWorktree(request.params as never);
case WS_METHODS.gitRemoveWorktree:
return removeGitWorktree(request.params as never);
case WS_METHODS.gitCreateBranch:
return createGitBranch(request.params as never);
case WS_METHODS.gitCheckout:
return checkoutGitBranch(request.params as never);
case WS_METHODS.gitInit:
return initGitRepo(request.params as never);
case WS_METHODS.terminalOpen:
return terminalManager.open(request.params as never);
case WS_METHODS.terminalWrite:
await terminalManager.write(request.params as never);
return undefined;
case WS_METHODS.terminalResize:
await terminalManager.resize(request.params as never);
return undefined;
case WS_METHODS.terminalClear:
await terminalManager.clear(request.params as never);
return undefined;
case WS_METHODS.terminalRestart:
return terminalManager.restart(request.params as never);
case WS_METHODS.terminalClose:
await terminalManager.close(request.params as never);
return undefined;
case WS_METHODS.serverGetConfig:
return { cwd };
@@ -255,24 +384,65 @@ export function createServer(options: ServerOptions) {
}
function start() {
return new Promise<void>((resolve) => {
httpServer.listen(port, () => {
return new Promise<void>((resolve, reject) => {
const onError = (error: Error) => {
httpServer.off("error", onError);
reject(error);
};
httpServer.once("error", onError);
const onListening = () => {
httpServer.off("error", onError);
resolve();
});
};
if (host) {
httpServer.listen(port, host, onListening);
return;
}
httpServer.listen(port, onListening);
});
}
function stop() {
async function stop(): Promise<void> {
terminalManager.off("event", onTerminalEvent);
providerManager.stopAll();
providerManager.dispose();
terminalManager.dispose();
for (const client of clients) {
client.close();
}
clients.clear();
wss.close();
httpServer.close();
const isServerNotRunningError = (error: unknown): boolean => {
if (!(error instanceof Error)) return false;
const maybeCode = (error as NodeJS.ErrnoException).code;
return (
maybeCode === "ERR_SERVER_NOT_RUNNING" ||
error.message.toLowerCase().includes("not running")
);
};
const closeWebSocketServer = new Promise<void>((resolve, reject) => {
wss.close((error) => {
if (error && !isServerNotRunningError(error)) {
reject(error);
return;
}
resolve();
});
});
const closeHttpServer = new Promise<void>((resolve, reject) => {
httpServer.close((error) => {
if (error && !isServerNotRunningError(error)) {
reject(error);
return;
}
resolve();
});
});
await Promise.all([closeWebSocketServer, closeHttpServer]);
}
return { start, stop, httpServer };
+2 -2
View File
@@ -3,7 +3,7 @@
"compilerOptions": {
"composite": true,
"types": ["node"],
"lib": ["ES2023"]
"lib": ["ES2023", "esnext.disposable"]
},
"include": ["src", "tsup.config.ts"]
"include": ["src", "tsdown.config.ts"]
}
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from "tsdown";
export default defineConfig({
entry: ["src/index.ts"],
format: ["esm", "cjs"],
outDir: "dist",
sourcemap: true,
clean: true,
noExternal: ["@t3tools/contracts", "zod"],
inlineOnly: false,
banner: {
js: "#!/usr/bin/env node\n",
},
});
-13
View File
@@ -1,13 +0,0 @@
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts"],
format: "esm",
outDir: "dist",
sourcemap: true,
clean: true,
noExternal: ["@acme/contracts"],
banner: {
js: '#!/usr/bin/env node\n',
},
});
+11
View File
@@ -0,0 +1,11 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"start": {
"dependsOn": ["build"],
"cache": false,
"persistent": true,
},
},
}
+18
View File
@@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300..800;1,9..40,300..800&display=swap"
rel="stylesheet"
/>
<title>T3 Code</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
@@ -1,5 +1,5 @@
{
"name": "@acme/renderer",
"name": "@t3tools/web",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -11,7 +11,10 @@
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@acme/contracts": "workspace:*",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-query": "^5.90.0",
"highlight.js": "^11.11.1",
"lucide-react": "^0.563.0",
"react": "^19.0.0",
@@ -25,10 +28,10 @@
"@tailwindcss/vite": "^4.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.4",
"@vitejs/plugin-react": "^5.1.4",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"tailwindcss": "^4.0.0",
"typescript": "^5.7.3",
"vite": "^6.0.5"
"vite": "^8.0.0-beta.12"
}
}
@@ -1,3 +1,4 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useEffect, useMemo, useRef } from "react";
import ChatView from "./components/ChatView";
@@ -7,6 +8,7 @@ import { isElectron } from "./env";
import { DEFAULT_MODEL } from "./model-logic";
import { readNativeApi } from "./session-logic";
import { StoreProvider, useStore } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types";
import { onServerWelcome } from "./wsNativeApi";
function EventRouter() {
@@ -25,6 +27,18 @@ function EventRouter() {
});
}, [api, dispatch]);
useEffect(() => {
if (!api) return;
return api.terminal.onEvent((event) => {
if (event.type !== "exited") return;
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: event.threadId,
open: false,
});
});
}, [api, dispatch]);
return null;
}
@@ -33,7 +47,8 @@ function AutoProjectBootstrap() {
const bootstrappedRef = useRef(false);
useEffect(() => {
// Only relevant in browser mode — Electron doesn't send server welcome
// Browser mode bootstraps from server welcome.
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
if (isElectron) return;
return onServerWelcome((payload) => {
@@ -44,9 +59,7 @@ function AutoProjectBootstrap() {
if (existing) {
bootstrappedRef.current = true;
// Ensure a thread is active
const existingThread = state.threads.find(
(t) => t.projectId === existing.id,
);
const existingThread = state.threads.find((t) => t.projectId === existing.id);
if (existingThread && !state.activeThreadId) {
dispatch({
type: "SET_ACTIVE_THREAD",
@@ -78,11 +91,15 @@ function AutoProjectBootstrap() {
projectId,
title: "New thread",
model: DEFAULT_MODEL,
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
session: null,
messages: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
branch: null,
worktreePath: null,
},
});
});
@@ -91,6 +108,56 @@ function AutoProjectBootstrap() {
return null;
}
function DesktopProjectBootstrap() {
const api = useMemo(() => readNativeApi(), []);
const { dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
if (!isElectron || !api || bootstrappedRef.current) return;
let disposed = false;
let retryDelayMs = 500;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
const attemptBootstrap = async () => {
try {
const projects = await api.projects.list();
if (disposed) return;
dispatch({
type: "SYNC_PROJECTS",
projects: projects.map((project) => ({
id: project.id,
name: project.name,
cwd: project.cwd,
model: DEFAULT_MODEL,
expanded: true,
})),
});
bootstrappedRef.current = true;
} catch {
if (disposed) return;
retryTimer = setTimeout(() => {
retryTimer = null;
void attemptBootstrap();
}, retryDelayMs);
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
}
};
void attemptBootstrap();
return () => {
disposed = true;
if (retryTimer) {
clearTimeout(retryTimer);
}
};
}, [api, dispatch]);
return null;
}
function Layout() {
const api = useMemo(() => readNativeApi(), []);
const { state } = useStore();
@@ -99,9 +166,7 @@ function Layout() {
return (
<div className="flex h-screen flex-col bg-background text-foreground">
<div className="flex flex-1 items-center justify-center">
<p className="text-sm text-muted-foreground">
Connecting to CodeThing server...
</p>
<p className="text-sm text-muted-foreground">Connecting to T3 Code server...</p>
</div>
</div>
);
@@ -111,6 +176,7 @@ function Layout() {
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<EventRouter />
<AutoProjectBootstrap />
<DesktopProjectBootstrap />
<Sidebar />
<ChatView />
{state.diffOpen && <DiffPanel />}
@@ -118,10 +184,14 @@ function Layout() {
);
}
const queryClient = new QueryClient();
export default function App() {
return (
<StoreProvider>
<Layout />
</StoreProvider>
<QueryClientProvider client={queryClient}>
<StoreProvider>
<Layout />
</StoreProvider>
</QueryClientProvider>
);
}
+315
View File
@@ -0,0 +1,315 @@
import type { GitBranch } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useMemo, useRef, useState } from "react";
import { readNativeApi } from "../session-logic";
import { useStore } from "../store";
interface BranchToolbarProps {
envMode: "local" | "worktree";
onEnvModeChange: (mode: "local" | "worktree") => void;
envLocked: boolean;
}
export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: BranchToolbarProps) {
const { state, dispatch } = useStore();
const api = useMemo(() => readNativeApi(), []);
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [isCreatingBranch, setIsCreatingBranch] = useState(false);
const [newBranchName, setNewBranchName] = useState("");
const branchMenuRef = useRef<HTMLDivElement>(null);
const activeThread = state.threads.find((thread) => thread.id === state.activeThreadId);
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
const activeThreadId = activeThread?.id;
const activeThreadBranch = activeThread?.branch ?? null;
const activeWorktreePath = activeThread?.worktreePath ?? null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd;
// ── Queries ───────────────────────────────────────────────────────────
const branchesQuery = useQuery({
queryKey: ["git", "branches", branchCwd],
queryFn: () => api!.git.listBranches({ cwd: branchCwd! }),
enabled: !!api && !!branchCwd,
});
const branches = branchesQuery.data?.branches ?? [];
// Default to true while loading — showing "Initialize git" during a fetch is wrong,
// and worktrees are inherently git repos.
const isRepo = branchesQuery.data?.isRepo ?? !branchesQuery.isLoading;
// ── Mutations ─────────────────────────────────────────────────────────
const checkoutMutation = useMutation({
mutationFn: (branch: string) => api!.git.checkout({ cwd: branchCwd!, branch }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["git", "branches", branchCwd] }),
onError: (error) =>
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch."),
});
const createBranchMutation = useMutation({
mutationFn: (branch: string) =>
api!.git
.createBranch({ cwd: branchCwd!, branch })
.then(() => api!.git.checkout({ cwd: branchCwd!, branch })),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["git", "branches", branchCwd] }),
onError: (error) =>
setThreadError(error instanceof Error ? error.message : "Failed to create branch."),
});
const initMutation = useMutation({
mutationFn: () => api!.git.init({ cwd: branchCwd! }),
onSuccess: () => {
setThreadError(null);
queryClient.invalidateQueries({ queryKey: ["git", "branches", branchCwd] });
},
onError: (error) =>
setThreadError(error instanceof Error ? error.message : "Failed to initialize git repo."),
});
// ── Effects ───────────────────────────────────────────────────────────
// Keep thread branch synced to git current branch for local threads.
const queryBranches = branchesQuery.data?.branches;
useEffect(() => {
if (!activeThreadId || activeWorktreePath) return;
const current = queryBranches?.find((branch) => branch.current);
if (!current) return;
if (current.name === activeThreadBranch) return;
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: current.name,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
useEffect(() => {
if (!isBranchMenuOpen) return;
const handleClickOutside = (event: MouseEvent) => {
if (!branchMenuRef.current) return;
if (event.target instanceof Node && !branchMenuRef.current.contains(event.target)) {
setIsBranchMenuOpen(false);
}
};
window.addEventListener("mousedown", handleClickOutside);
return () => {
window.removeEventListener("mousedown", handleClickOutside);
};
}, [isBranchMenuOpen]);
// ── Helpers ───────────────────────────────────────────────────────────
const setThreadError = (error: string | null) => {
if (!activeThreadId) return;
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error });
};
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
if (!activeThreadId) return;
// If the effective cwd is about to change, stop the running session so the
// next message creates a new one with the correct cwd.
const sessionId = activeThread?.session?.sessionId;
if (sessionId && worktreePath !== activeWorktreePath) {
void api?.providers.stopSession({ sessionId }).catch(() => undefined);
}
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
};
const selectBranch = (branch: GitBranch) => {
if (!api || !activeThreadId || !branchCwd) return;
// For new worktree mode, selecting a branch picks the base branch.
if (envMode === "worktree" && !envLocked && !activeWorktreePath) {
setThreadError(null);
setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
return;
}
// If the branch already lives in a worktree, redirect there instead of
// trying to checkout (which git would reject with "already used by worktree").
if (branch.worktreePath) {
const isMainWorktree = branch.worktreePath === activeProject?.cwd;
setThreadError(null);
// Main worktree → switch back to local (project cwd, worktreePath=null).
// Secondary worktree → point the thread at that worktree path.
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
setIsBranchMenuOpen(false);
return;
}
checkoutMutation.mutate(branch.name, {
onSuccess: () => {
setThreadError(null);
setThreadBranch(branch.name, activeWorktreePath);
setIsBranchMenuOpen(false);
},
});
};
const createBranch = () => {
const name = newBranchName.trim();
if (!api || !activeThreadId || !branchCwd || !name) return;
createBranchMutation.mutate(name, {
onSuccess: () => {
setThreadError(null);
setThreadBranch(name, activeWorktreePath);
setNewBranchName("");
setIsCreatingBranch(false);
setIsBranchMenuOpen(false);
},
});
};
if (!activeThread || !activeProject) return null;
return (
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
<div className="flex items-center gap-2">
{envLocked || activeWorktreePath ? (
<span className="inline-flex items-center gap-1.5 px-1 text-[12px] text-muted-foreground/55">
{activeWorktreePath ? "Worktree" : "Local"}
</span>
) : (
<button
type="button"
className={`inline-flex items-center gap-1.5 rounded-lg px-2 py-1 text-[12px] transition-colors duration-150 ${
envMode === "worktree"
? "bg-accent text-foreground/80"
: "text-muted-foreground/60 hover:bg-accent/50 hover:text-muted-foreground/80"
}`}
onClick={() => onEnvModeChange(envMode === "local" ? "worktree" : "local")}
>
{envMode === "worktree" ? "New worktree" : "Local"}
</button>
)}
</div>
{!isRepo ? (
<button
type="button"
className="inline-flex items-center gap-1.5 rounded-lg border border-border px-2 py-1 text-[12px] text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80 disabled:cursor-not-allowed disabled:opacity-50"
disabled={!branchCwd || initMutation.isPending}
onClick={() => initMutation.mutate()}
>
{initMutation.isPending ? "Initializing\u2026" : "Initialize git"}
</button>
) : (
<div className="relative" ref={branchMenuRef}>
<button
type="button"
className="inline-flex items-center gap-1.5 rounded-lg px-2 py-1 text-[12px] text-muted-foreground/60 transition-colors duration-150 hover:bg-accent/50 hover:text-muted-foreground/80"
onClick={() => setIsBranchMenuOpen((open) => !open)}
disabled={branchesQuery.isLoading}
>
<span className="max-w-[240px] truncate font-mono">
{activeThread.branch
? envMode === "worktree" && !activeWorktreePath
? `From ${activeThread.branch}`
: activeThread.branch
: "Select branch"}
</span>
<svg
width="10"
height="10"
viewBox="0 0 10 10"
fill="none"
className="opacity-40"
aria-hidden="true"
>
<path
d="M2.5 4L5 6.5L7.5 4"
stroke="currentColor"
strokeWidth="1.2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
{isBranchMenuOpen && (
<div className="absolute bottom-full right-0 z-20 mb-2 w-[320px] rounded-2xl border border-border bg-popover/95 p-2 shadow-[0_16px_40px_rgba(0,0,0,0.55)] backdrop-blur">
<p className="px-2 py-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/55">
Branch
</p>
<div className="max-h-64 overflow-y-auto">
{branches.map((branch) => {
const isSelected = branch.name === activeThread.branch;
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
return (
<button
key={branch.name}
type="button"
className={`mb-0.5 flex w-full items-center justify-between gap-2 rounded-xl px-2 py-1.5 text-left font-mono text-xs transition-colors duration-150 ${
isSelected
? "bg-accent text-foreground"
: "text-foreground/90 hover:bg-accent/50"
}`}
onClick={() => selectBranch(branch)}
>
<span className="truncate">{branch.name}</span>
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
</span>
)}
</button>
);
})}
</div>
{envMode === "local" && (
<>
<div className="mx-1 my-1 h-px bg-border" />
{isCreatingBranch ? (
<form
className="flex items-center gap-1 px-1"
onSubmit={(event) => {
event.preventDefault();
createBranch();
}}
>
<input
type="text"
className="flex-1 rounded-lg border border-border bg-background px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/30 focus:border-ring focus:outline-none"
placeholder="branch-name"
value={newBranchName}
onChange={(event) => setNewBranchName(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Escape") {
setIsCreatingBranch(false);
setNewBranchName("");
}
}}
// biome-ignore lint/a11y/noAutofocus: branch name input should focus when shown
autoFocus
/>
<button
type="submit"
disabled={!newBranchName.trim() || createBranchMutation.isPending}
className="rounded-lg px-2 py-1.5 text-xs text-muted-foreground/70 transition-colors hover:bg-accent hover:text-foreground/80 disabled:opacity-30"
>
Create
</button>
</form>
) : (
<button
type="button"
className="w-full rounded-lg px-2 py-1.5 text-left text-xs text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80"
onClick={() => setIsCreatingBranch(true)}
>
+ New branch
</button>
)}
</>
)}
</div>
)}
</div>
)}
</div>
);
}
@@ -2,18 +2,19 @@ import {
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
type ProviderApprovalDecision,
type ProviderEvent,
} from "@acme/contracts";
} from "@t3tools/contracts";
import {
type FormEvent,
Fragment,
type KeyboardEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { EDITORS, type EditorId } from "@acme/contracts";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { isElectron } from "../env";
import { buildBootstrapInput } from "../historyBootstrap";
import {
@@ -33,7 +34,10 @@ import {
readNativeApi,
} from "../session-logic";
import { useStore } from "../store";
import BranchToolbar from "./BranchToolbar";
import { isTerminalToggleShortcut } from "../terminal-shortcuts";
import ChatMarkdown from "./ChatMarkdown";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt);
@@ -50,7 +54,7 @@ function editorLabel(editor: (typeof EDITORS)[number]): string {
return editor.command ? editor.label : FILE_MANAGER_LABEL;
}
const LAST_EDITOR_KEY = "codething:last-editor";
const LAST_EDITOR_KEY = "t3code:last-editor";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
@@ -91,23 +95,17 @@ function approvalDetail(event: ProviderEvent): string | undefined {
return asString(payload?.reason);
}
function derivePendingApprovals(
events: ProviderEvent[],
): PendingApprovalCard[] {
function derivePendingApprovals(events: ProviderEvent[]): PendingApprovalCard[] {
const pending = new Map<string, PendingApprovalCard>();
const ordered = [...events].toReversed();
for (const event of ordered) {
if (
event.method === "session/closed" ||
event.method === "session/exited"
) {
if (event.method === "session/closed" || event.method === "session/exited") {
pending.clear();
continue;
}
const requestId =
event.requestId ?? asString(asRecord(event.payload)?.requestId);
const requestId = event.requestId ?? asString(asRecord(event.payload)?.requestId);
if (!requestId) continue;
if (
@@ -142,26 +140,23 @@ export default function ChatView() {
const [isEditorMenuOpen, setIsEditorMenuOpen] = useState(false);
const [lastEditor, setLastEditor] = useState<EditorId>(() => {
const stored = localStorage.getItem(LAST_EDITOR_KEY);
return EDITORS.some((e) => e.id === stored)
? (stored as EditorId)
: EDITORS[0].id;
return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id;
});
const [selectedEffort, setSelectedEffort] =
useState<string>(DEFAULT_REASONING);
const [selectedEffort, setSelectedEffort] = useState<string>(DEFAULT_REASONING);
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
const [respondingRequestIds, setRespondingRequestIds] = useState<string[]>(
[],
);
const [expandedWorkGroups, setExpandedWorkGroups] = useState<
Record<string, boolean>
>({});
const [respondingRequestIds, setRespondingRequestIds] = useState<string[]>([]);
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const messagesEndRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const modelMenuRef = useRef<HTMLDivElement>(null);
const editorMenuRef = useRef<HTMLDivElement>(null);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const activeThreadId = activeThread?.id ?? null;
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
const selectedModel = resolveModelSlug(
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
@@ -175,11 +170,7 @@ export default function ChatView() {
[activeThread?.events],
);
const latestTurnWorkEntries = useMemo(
() =>
deriveWorkLogEntries(
activeThread?.events ?? [],
activeThread?.latestTurnId,
),
() => deriveWorkLogEntries(activeThread?.events ?? [], activeThread?.latestTurnId),
[activeThread?.events, activeThread?.latestTurnId],
);
const pendingApprovals = useMemo(
@@ -265,19 +256,39 @@ export default function ChatView() {
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
} as const);
const envLocked = Boolean(
activeThread &&
(activeThread.messages.length > 0 ||
(activeThread.session !== null && activeThread.session.status !== "closed")),
);
const terminalShortcutHint = navigator.platform.includes("Mac")
? "\u2318J"
: "Ctrl+J";
const focusComposer = useCallback(() => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.focus();
const cursor = textarea.value.length;
textarea.setSelectionRange(cursor, cursor);
}, []);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadId) return;
const isOpen = Boolean(activeThread?.terminalOpen);
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: !isOpen,
});
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
const handleRuntimeModeChange = async (
mode: "approval-required" | "full-access",
) => {
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return;
dispatch({ type: "SET_RUNTIME_MODE", mode });
if (!api) return;
const sessionIds = state.threads
.map((t) => t.session)
.filter(
(s): s is NonNullable<typeof s> => s !== null && s.status !== "closed",
)
.filter((s): s is NonNullable<typeof s> => s !== null && s.status !== "closed")
.map((s) => s.sessionId);
if (sessionIds.length === 0) return;
@@ -285,9 +296,7 @@ export default function ChatView() {
setIsSwitchingRuntimeMode(true);
try {
await Promise.all(
sessionIds.map((id) =>
api.providers.stopSession({ sessionId: id }).catch(() => undefined),
),
sessionIds.map((id) => api.providers.stopSession({ sessionId: id }).catch(() => undefined)),
);
} finally {
setIsSwitchingRuntimeMode(false);
@@ -309,6 +318,12 @@ export default function ChatView() {
setExpandedWorkGroups({});
}, [activeThread?.id]);
const activeWorktreePath = activeThread?.worktreePath;
useEffect(() => {
if (!activeThread?.id) return;
setEnvMode(activeWorktreePath ? "worktree" : "local");
}, [activeThread?.id, activeWorktreePath]);
// Auto-resize textarea
useEffect(() => {
const ta = textareaRef.current;
@@ -348,10 +363,7 @@ export default function ChatView() {
const handleClickOutside = (event: MouseEvent) => {
if (!editorMenuRef.current) return;
if (
event.target instanceof Node &&
!editorMenuRef.current.contains(event.target)
) {
if (event.target instanceof Node && !editorMenuRef.current.contains(event.target)) {
setIsEditorMenuOpen(false);
}
};
@@ -368,23 +380,56 @@ export default function ChatView() {
if (e.key === "o" && (e.metaKey || e.ctrlKey) && !e.shiftKey) {
if (api && activeProject) {
e.preventDefault();
void api.shell.openInEditor(activeProject.cwd, lastEditor);
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
void api.shell.openInEditor(cwd, lastEditor);
}
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [api, activeProject, lastEditor]);
}, [api, activeProject, activeThread, lastEditor]);
useEffect(() => {
if (!activeThreadId) return;
const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false;
const current = Boolean(activeThread?.terminalOpen);
if (!previous && current) {
setTerminalFocusRequestId((value) => value + 1);
} else if (previous && !current) {
terminalOpenByThreadRef.current[activeThreadId] = current;
const frame = window.requestAnimationFrame(() => {
focusComposer();
});
return () => {
window.cancelAnimationFrame(frame);
};
}
terminalOpenByThreadRef.current[activeThreadId] = current;
}, [activeThread?.terminalOpen, activeThreadId, focusComposer]);
useEffect(() => {
const handler = (event: globalThis.KeyboardEvent) => {
if (!activeThreadId) return;
if (!isTerminalToggleShortcut(event)) return;
event.preventDefault();
toggleTerminalVisibility();
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [activeThreadId, toggleTerminalVisibility]);
const openInEditor = (editorId: EditorId) => {
if (!api || !activeProject) return;
void api.shell.openInEditor(activeProject.cwd, editorId);
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
void api.shell.openInEditor(cwd, editorId);
setLastEditor(editorId);
localStorage.setItem(LAST_EDITOR_KEY, editorId);
setIsEditorMenuOpen(false);
};
const ensureSession = async (): Promise<EnsuredSessionInfo | null> => {
const ensureSession = async (cwdOverride?: string): Promise<EnsuredSessionInfo | null> => {
if (!api || !activeThread || !activeProject) return null;
if (activeThread.session && activeThread.session.status !== "closed") {
const sessionThreadId = activeThread.session.threadId ?? null;
@@ -406,7 +451,7 @@ export default function ChatView() {
try {
const session = await api.providers.startSession({
provider: "codex",
cwd: activeProject.cwd || undefined,
cwd: cwdOverride ?? activeThread.worktreePath ?? activeProject.cwd,
model: selectedModel || undefined,
resumeThreadId: priorCodexThreadId ?? undefined,
approvalPolicy: runtimeSessionConfig.approvalPolicy,
@@ -446,6 +491,39 @@ export default function ChatView() {
if (!api || !activeThread || isSending || isConnecting) return;
const trimmed = prompt.trim();
if (!trimmed) return;
if (!activeProject) return;
// On first message: lock in branch + create worktree if needed.
let sessionCwd: string | undefined;
if (
activeThread.messages.length === 0 &&
activeThread.branch &&
envMode === "worktree" &&
!activeThread.worktreePath
) {
try {
const newBranch = `codething/${crypto.randomUUID().slice(0, 8)}`;
const result = await api.git.createWorktree({
cwd: activeProject.cwd,
branch: activeThread.branch,
newBranch,
});
sessionCwd = result.worktree.path;
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThread.id,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to create worktree",
});
return;
}
}
// Auto-title from first message
if (activeThread.messages.length === 0) {
@@ -471,21 +549,16 @@ export default function ChatView() {
const previousMessages = activeThread.messages;
setPrompt("");
const sessionInfo = await ensureSession();
const sessionInfo = await ensureSession(sessionCwd);
if (!sessionInfo) return;
setIsSending(true);
try {
const shouldBootstrap =
previousMessages.length > 0 &&
(sessionInfo.continuityState === "new" ||
sessionInfo.continuityState === "fallback_new");
(sessionInfo.continuityState === "new" || sessionInfo.continuityState === "fallback_new");
const input = shouldBootstrap
? buildBootstrapInput(
previousMessages,
trimmed,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
).text
? buildBootstrapInput(previousMessages, trimmed, PROVIDER_SEND_TURN_MAX_INPUT_CHARS).text
: trimmed;
await api.providers.sendTurn({
sessionId: sessionInfo.sessionId,
@@ -512,10 +585,7 @@ export default function ChatView() {
});
};
const onRespondToApproval = async (
requestId: string,
decision: ProviderApprovalDecision,
) => {
const onRespondToApproval = async (requestId: string, decision: ProviderApprovalDecision) => {
if (!api || !activeThread?.session) return;
setRespondingRequestIds((existing) =>
@@ -531,15 +601,10 @@ export default function ChatView() {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error:
err instanceof Error
? err.message
: "Failed to submit approval decision.",
error: err instanceof Error ? err.message : "Failed to submit approval decision.",
});
} finally {
setRespondingRequestIds((existing) =>
existing.filter((id) => id !== requestId),
);
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
}
};
@@ -563,7 +628,7 @@ export default function ChatView() {
// Empty state: no active thread
if (!activeThread) {
return (
<div className="flex flex-1 flex-col bg-background text-muted-foreground/40">
<div className="flex min-h-0 flex-1 flex-col bg-background text-muted-foreground/40">
{isElectron && <div className="drag-region h-[52px] shrink-0" />}
<div className="flex flex-1 items-center justify-center">
<div className="text-center">
@@ -575,13 +640,24 @@ export default function ChatView() {
}
return (
<div className="flex flex-1 flex-col bg-background">
<div className="flex min-h-0 flex-1 flex-col bg-background">
{/* Top bar */}
<header className={`flex items-center justify-between border-b border-border px-5 pb-3 ${isElectron ? "drag-region pt-[28px]" : "pt-3"}`}>
<header
className={`flex items-center justify-between border-b border-border px-5 pb-3 ${isElectron ? "drag-region pt-[28px]" : "pt-3"}`}
>
<div className="flex items-center gap-3">
<h2 className="text-sm font-medium text-foreground">
{activeThread.title}
</h2>
<h2 className="text-sm font-medium text-foreground">{activeThread.title}</h2>
{activeProject && (
<span className="rounded-full bg-accent px-2 py-0.5 text-[10px] text-muted-foreground/50">
{activeProject.name}
</span>
)}
{activeThread.branch && (
<span className="rounded-full bg-accent px-2 py-0.5 font-mono text-[10px] text-muted-foreground/50">
{activeThread.branch}
{activeThread.worktreePath ? " (worktree)" : ""}
</span>
)}
</div>
<div className="flex items-center gap-3">
{/* Open in editor */}
@@ -606,9 +682,7 @@ export default function ChatView() {
{editorLabel(editor)}
{editor.id === lastEditor && (
<kbd className="ml-auto text-[9px] text-muted-foreground/40">
{navigator.platform.includes("Mac")
? "\u2318O"
: "Ctrl+O"}
{navigator.platform.includes("Mac") ? "\u2318O" : "Ctrl+O"}
</kbd>
)}
</button>
@@ -618,6 +692,17 @@ export default function ChatView() {
</div>
)}
{/* Diff toggle */}
<button
type="button"
className={`rounded-md px-2 py-1 text-[10px] transition-colors duration-150 ${
activeThread.terminalOpen
? "bg-accent text-foreground"
: "text-muted-foreground/40 hover:text-muted-foreground/60"
}`}
onClick={toggleTerminalVisibility}
>
Terminal <span className="text-muted-foreground/50">{terminalShortcutHint}</span>
</button>
<button
type="button"
className={`rounded-md px-2 py-1 text-[10px] transition-colors duration-150 ${
@@ -634,7 +719,7 @@ export default function ChatView() {
{/* Error banner */}
{activeThread.error && (
<div className="mx-4 mt-3 rounded-lg border border-rose-400/20 bg-rose-900/20 px-3 py-2 text-xs text-rose-200">
<div className="mx-4 mt-3 rounded-lg border border-destructive/20 bg-destructive/10 px-3 py-2 text-xs text-destructive">
{activeThread.error}
</div>
)}
@@ -642,9 +727,7 @@ export default function ChatView() {
{pendingApprovals.length > 0 && (
<div className="mx-4 mt-3 space-y-2">
{pendingApprovals.map((approval) => {
const isResponding = respondingRequestIds.includes(
approval.requestId,
);
const isResponding = respondingRequestIds.includes(approval.requestId);
return (
<div
key={approval.requestId}
@@ -668,9 +751,7 @@ export default function ChatView() {
type="button"
className="rounded-md border border-border bg-accent px-2 py-1 text-[11px] text-foreground transition-colors duration-150 hover:bg-accent/80 disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() =>
void onRespondToApproval(approval.requestId, "accept")
}
onClick={() => void onRespondToApproval(approval.requestId, "accept")}
>
Approve once
</button>
@@ -678,12 +759,7 @@ export default function ChatView() {
type="button"
className="rounded-md border border-sky-300/30 bg-sky-500/[0.15] px-2 py-1 text-[11px] text-sky-100 transition-colors duration-150 hover:bg-sky-500/[0.22] disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() =>
void onRespondToApproval(
approval.requestId,
"acceptForSession",
)
}
onClick={() => void onRespondToApproval(approval.requestId, "acceptForSession")}
>
Always allow this session
</button>
@@ -691,9 +767,7 @@ export default function ChatView() {
type="button"
className="rounded-md border border-border px-2 py-1 text-[11px] text-foreground/90 transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() =>
void onRespondToApproval(approval.requestId, "decline")
}
onClick={() => void onRespondToApproval(approval.requestId, "decline")}
>
Decline
</button>
@@ -701,9 +775,7 @@ export default function ChatView() {
type="button"
className="rounded-md border border-rose-300/30 bg-rose-500/[0.12] px-2 py-1 text-[11px] text-rose-100 transition-colors duration-150 hover:bg-rose-500/[0.2] disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() =>
void onRespondToApproval(approval.requestId, "cancel")
}
onClick={() => void onRespondToApproval(approval.requestId, "cancel")}
>
Cancel turn
</button>
@@ -715,18 +787,17 @@ export default function ChatView() {
)}
{/* Messages */}
<div className="flex-1 overflow-y-auto px-5 py-4">
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">
{activeThread.messages.length === 0 && !isWorking ? (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">Send a message to start the conversation.</p>
<p className="text-sm text-muted-foreground/30">
Send a message to start the conversation.
</p>
</div>
) : (
<div className="mx-auto max-w-3xl space-y-4">
{timelineEntries.map((timelineEntry, index) => {
if (
timelineEntry.kind === "work" &&
timelineEntries[index - 1]?.kind === "work"
) {
if (timelineEntry.kind === "work" && timelineEntries[index - 1]?.kind === "work") {
return null;
}
@@ -747,16 +818,13 @@ export default function ChatView() {
const groupId = timelineEntry.id;
const isExpanded = expandedWorkGroups[groupId] ?? false;
const hasOverflow =
groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
: groupedEntries;
const hiddenCount = groupedEntries.length - visibleEntries.length;
const onlyToolEntries = groupedEntries.every(
(entry) => entry.tone === "tool",
);
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
const groupLabel = onlyToolEntries
? groupedEntries.length === 1
? "Tool call"
@@ -842,9 +910,7 @@ export default function ChatView() {
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary
? `Response • ${completionSummary}`
: "Response"}
{completionSummary ? `Response • ${completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
@@ -853,24 +919,17 @@ export default function ChatView() {
<ChatMarkdown
text={
timelineEntry.message.text ||
(timelineEntry.message.streaming
? ""
: "(empty response)")
(timelineEntry.message.streaming ? "" : "(empty response)")
}
/>
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
{formatMessageMeta(
timelineEntry.message.createdAt,
timelineEntry.message.streaming
? formatElapsed(
timelineEntry.message.createdAt,
nowIso,
)
? formatElapsed(timelineEntry.message.createdAt, nowIso)
: formatElapsed(
timelineEntry.message.createdAt,
assistantCompletionByItemId.get(
timelineEntry.message.id,
),
assistantCompletionByItemId.get(timelineEntry.message.id),
),
)}
</p>
@@ -896,7 +955,7 @@ export default function ChatView() {
</div>
{/* Input bar */}
<div className="px-5 pb-4 pt-2">
<div className="px-5 pb-1 pt-2">
<form onSubmit={onSend} className="mx-auto max-w-3xl">
<div className="group rounded-[20px] border border-border bg-card transition-colors duration-200 focus-within:border-ring">
{/* Textarea area */}
@@ -1026,9 +1085,7 @@ export default function ChatView() {
disabled={isSwitchingRuntimeMode}
onClick={() =>
void handleRuntimeModeChange(
state.runtimeMode === "full-access"
? "approval-required"
: "full-access",
state.runtimeMode === "full-access" ? "approval-required" : "full-access",
)
}
title={
@@ -1038,13 +1095,7 @@ export default function ChatView() {
}
>
{state.runtimeMode === "full-access" ? (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
aria-hidden="true"
>
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
<rect
x="2"
y="5.5"
@@ -1062,13 +1113,7 @@ export default function ChatView() {
/>
</svg>
) : (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
aria-hidden="true"
>
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
<rect
x="2"
y="5.5"
@@ -1086,11 +1131,7 @@ export default function ChatView() {
/>
</svg>
)}
<span>
{state.runtimeMode === "full-access"
? "Full access"
: "Supervised"}
</span>
<span>{state.runtimeMode === "full-access" ? "Full access" : "Supervised"}</span>
</button>
</div>
@@ -1165,6 +1206,33 @@ export default function ChatView() {
</div>
</form>
</div>
<BranchToolbar envMode={envMode} onEnvModeChange={setEnvMode} envLocked={envLocked} />
{activeThread.terminalOpen && api && activeProject && (
<ThreadTerminalDrawer
key={activeThread.id}
api={api}
threadId={activeThread.id}
cwd={activeProject.cwd}
height={activeThread.terminalHeight}
focusRequestId={terminalFocusRequestId}
onHeightChange={(height) =>
dispatch({
type: "SET_THREAD_TERMINAL_HEIGHT",
threadId: activeThread.id,
height,
})
}
onThreadExited={() =>
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThread.id,
open: false,
})
}
/>
)}
</div>
);
}
@@ -7,7 +7,9 @@ export default function DiffPanel() {
return (
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
{/* Header */}
<div className={`flex items-center justify-between border-b border-border px-4 pb-3 ${isElectron ? "drag-region pt-[28px]" : "pt-3"}`}>
<div
className={`flex items-center justify-between border-b border-border px-4 pb-3 ${isElectron ? "drag-region pt-[28px]" : "pt-3"}`}
>
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
<button
type="button"
@@ -5,7 +5,7 @@ import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { readNativeApi } from "../session-logic";
import { useStore } from "../store";
import type { Project } from "../types";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, type Project } from "../types";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
function formatRelativeTime(iso: string): string {
@@ -18,6 +18,13 @@ function formatRelativeTime(iso: string): string {
return `${Math.floor(hours / 24)}d ago`;
}
function inferProjectName(cwd: string): string {
const normalized = cwd.replace(/\\/g, "/").replace(/\/+$/, "");
const parts = normalized.split("/");
const last = parts[parts.length - 1];
return last && last.length > 0 ? last : "project";
}
function threadStatusLabel(
status: "connecting" | "ready" | "running" | "error" | "closed" | undefined,
): "Working" | "Connecting" | null {
@@ -33,22 +40,7 @@ export default function Sidebar() {
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const handleAddProject = () => {
const cwd = newCwd.trim();
if (!cwd) return;
const name = cwd.split("/").filter(Boolean).pop() ?? "project";
const project: Project = {
id: crypto.randomUUID(),
name,
cwd,
model: DEFAULT_MODEL,
expanded: true,
};
dispatch({ type: "ADD_PROJECT", project });
setNewCwd("");
setAddingProject(false);
};
const [isAddingProject, setIsAddingProject] = useState(false);
const handleNewThread = useCallback(
(projectId: string) => {
@@ -59,32 +51,153 @@ export default function Sidebar() {
codexThreadId: null,
projectId,
title: "New thread",
model:
state.projects.find((p) => p.id === projectId)?.model ??
DEFAULT_MODEL,
model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL,
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
session: null,
messages: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
branch: null,
worktreePath: null,
},
});
},
[dispatch, state.projects],
);
const focusMostRecentThreadForProject = useCallback(
(projectId: string) => {
const latestThread = state.threads
.filter((thread) => thread.projectId === projectId)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
if (byDate !== 0) return byDate;
return b.id.localeCompare(a.id);
})[0];
if (!latestThread) return;
dispatch({
type: "SET_ACTIVE_THREAD",
threadId: latestThread.id,
});
},
[dispatch, state.threads],
);
const addProjectFromPath = useCallback(
async (rawCwd: string) => {
const cwd = rawCwd.trim();
if (!cwd || isAddingProject) return;
setIsAddingProject(true);
try {
if (isElectron && api) {
const result = await api.projects.add({ cwd });
const project: Project = {
id: result.project.id,
name: result.project.name,
cwd: result.project.cwd,
model: DEFAULT_MODEL,
expanded: true,
};
const existingById = state.projects.find((p) => p.id === project.id);
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
if (!existingById && !existingByCwd) {
dispatch({ type: "ADD_PROJECT", project });
}
const resolvedProjectId = existingByCwd?.id ?? project.id;
if (result.created) {
handleNewThread(resolvedProjectId);
} else {
focusMostRecentThreadForProject(resolvedProjectId);
}
} else {
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
return;
}
const name = inferProjectName(cwd);
const project: Project = {
id: crypto.randomUUID(),
name,
cwd,
model: DEFAULT_MODEL,
expanded: true,
};
dispatch({ type: "ADD_PROJECT", project });
handleNewThread(project.id);
}
} finally {
setIsAddingProject(false);
setNewCwd("");
setAddingProject(false);
}
},
[
api,
dispatch,
focusMostRecentThreadForProject,
handleNewThread,
isAddingProject,
state.projects,
],
);
const handleAddProject = () => {
void addProjectFromPath(newCwd);
};
const handlePickFolder = async () => {
if (!api || isPickingFolder) return;
setIsPickingFolder(true);
try {
const pickedPath = await api.dialogs.pickFolder();
if (!pickedPath) return;
setNewCwd(pickedPath);
await addProjectFromPath(pickedPath);
} finally {
setIsPickingFolder(false);
}
};
const handleThreadContextMenu = useCallback(
async (threadId: string, position: { x: number; y: number }) => {
if (!api) return;
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
if (clicked !== "delete") return;
const thread = state.threads.find((t) => t.id === threadId);
if (!thread) return;
// Stop active session if running
if (thread.session?.sessionId) {
try {
await api.providers.stopSession({
sessionId: thread.session.sessionId,
});
} catch {
// Session may already be stopped
}
}
try {
await api.terminal.close({
threadId,
deleteHistory: true,
});
} catch {
// Terminal may already be closed
}
dispatch({ type: "DELETE_THREAD", threadId });
},
[api, dispatch, state.threads],
);
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
const isNewThreadShortcut =
@@ -108,9 +221,7 @@ export default function Sidebar() {
}
}
const activeThread = state.threads.find(
(t) => t.id === state.activeThreadId,
);
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
@@ -129,12 +240,9 @@ export default function Sidebar() {
{/* Drag region / traffic light space (Electron only) */}
{isElectron && <div className="drag-region h-[52px] shrink-0" />}
{/* Branding */}
<div className={`flex items-center gap-2 px-4 pb-4 ${isElectron ? "" : "pt-4"}`}>
<div className="flex h-7 w-7 items-center justify-center rounded-lg bg-primary text-xs font-bold text-primary-foreground">
CT
</div>
<div className={`flex items-center gap-2.5 px-4 pb-4 ${isElectron ? "" : "pt-4"}`}>
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
CodeThing
T3 <span className="font-normal text-muted-foreground">Code</span>
</span>
<button
type="button"
@@ -177,10 +285,8 @@ export default function Sidebar() {
{state.projects.map((project) => {
const threads = state.threads
.filter((t) => t.projectId === project.id)
.sort((a, b) => {
const byDate =
new Date(b.createdAt).getTime() -
new Date(a.createdAt).getTime();
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
if (byDate !== 0) return byDate;
return b.id.localeCompare(a.id);
});
@@ -206,15 +312,15 @@ export default function Sidebar() {
<div className="ml-2 border-l border-border/80 pl-2">
{threads.map((thread) => {
const isActive = state.activeThreadId === thread.id;
const threadStatus = threadStatusLabel(
thread.session?.status,
);
const threadStatus = threadStatusLabel(thread.session?.status);
return (
<button
key={thread.id}
type="button"
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 ${
isActive ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-secondary"
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-secondary"
}`}
onClick={() =>
dispatch({
@@ -222,19 +328,22 @@ export default function Sidebar() {
threadId: thread.id,
})
}
onContextMenu={(e) => {
e.preventDefault();
void handleThreadContextMenu(thread.id, {
x: e.clientX,
y: e.clientY,
});
}}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
{threadStatus && (
<span className="inline-flex items-center gap-1 text-[10px] text-sky-600 dark:text-sky-300/80">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-500 dark:bg-sky-300/80" />
<span className="hidden xl:inline">
{threadStatus}
</span>
<span className="hidden xl:inline">{threadStatus}</span>
</span>
)}
<span className="min-w-0 flex-1 truncate text-xs">
{thread.title}
</span>
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
</div>
<span className="shrink-0 text-[10px] text-muted-foreground/40">
{formatRelativeTime(thread.createdAt)}
@@ -287,7 +396,7 @@ export default function Sidebar() {
type="button"
className="mb-2 flex w-full items-center justify-center rounded-md border border-border px-2 py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => void handlePickFolder()}
disabled={isPickingFolder}
disabled={isPickingFolder || isAddingProject}
>
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
</button>
@@ -297,8 +406,9 @@ export default function Sidebar() {
type="button"
className="flex-1 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90"
onClick={handleAddProject}
disabled={isAddingProject}
>
Add
{isAddingProject ? "Adding..." : "Add"}
</button>
<button
type="button"
@@ -0,0 +1,459 @@
import { FitAddon } from "@xterm/addon-fit";
import { type NativeApi } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
type PointerEvent as ReactPointerEvent,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { isTerminalClearShortcut } from "../terminal-shortcuts";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "../types";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
function maxDrawerHeight(): number {
if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
return Math.max(
MIN_DRAWER_HEIGHT,
Math.floor(window.innerHeight * MAX_DRAWER_HEIGHT_RATIO),
);
}
function clampDrawerHeight(height: number): number {
const safeHeight = Number.isFinite(height)
? height
: DEFAULT_THREAD_TERMINAL_HEIGHT;
const maxHeight = maxDrawerHeight();
return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight);
}
function writeSystemMessage(terminal: Terminal, message: string): void {
terminal.write(`\r\n[terminal] ${message}\r\n`);
}
function terminalThemeFromApp(): ITheme {
const isDark = document.documentElement.classList.contains("dark");
const bodyStyles = getComputedStyle(document.body);
const background =
bodyStyles.backgroundColor || (isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)");
const foreground =
bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)");
if (isDark) {
return {
background,
foreground,
cursor: "rgb(180, 203, 255)",
selectionBackground: "rgba(180, 203, 255, 0.25)",
scrollbarSliderBackground: "rgba(255, 255, 255, 0.1)",
scrollbarSliderHoverBackground: "rgba(255, 255, 255, 0.18)",
scrollbarSliderActiveBackground: "rgba(255, 255, 255, 0.22)",
black: "rgb(24, 30, 38)",
red: "rgb(255, 122, 142)",
green: "rgb(134, 231, 149)",
yellow: "rgb(244, 205, 114)",
blue: "rgb(137, 190, 255)",
magenta: "rgb(208, 176, 255)",
cyan: "rgb(124, 232, 237)",
white: "rgb(210, 218, 230)",
brightBlack: "rgb(110, 120, 136)",
brightRed: "rgb(255, 168, 180)",
brightGreen: "rgb(176, 245, 186)",
brightYellow: "rgb(255, 224, 149)",
brightBlue: "rgb(174, 210, 255)",
brightMagenta: "rgb(229, 203, 255)",
brightCyan: "rgb(167, 244, 247)",
brightWhite: "rgb(244, 247, 252)",
};
}
return {
background,
foreground,
cursor: "rgb(38, 56, 78)",
selectionBackground: "rgba(37, 63, 99, 0.2)",
scrollbarSliderBackground: "rgba(0, 0, 0, 0.15)",
scrollbarSliderHoverBackground: "rgba(0, 0, 0, 0.25)",
scrollbarSliderActiveBackground: "rgba(0, 0, 0, 0.3)",
black: "rgb(44, 53, 66)",
red: "rgb(191, 70, 87)",
green: "rgb(60, 126, 86)",
yellow: "rgb(146, 112, 35)",
blue: "rgb(72, 102, 163)",
magenta: "rgb(132, 86, 149)",
cyan: "rgb(53, 127, 141)",
white: "rgb(210, 215, 223)",
brightBlack: "rgb(112, 123, 140)",
brightRed: "rgb(212, 95, 112)",
brightGreen: "rgb(85, 148, 111)",
brightYellow: "rgb(173, 133, 45)",
brightBlue: "rgb(91, 124, 194)",
brightMagenta: "rgb(153, 107, 172)",
brightCyan: "rgb(70, 149, 164)",
brightWhite: "rgb(236, 240, 246)",
};
}
interface ThreadTerminalDrawerProps {
api: NativeApi;
threadId: string;
cwd: string;
height: number;
focusRequestId: number;
onHeightChange: (height: number) => void;
onThreadExited: () => void;
}
export default function ThreadTerminalDrawer({
api,
threadId,
cwd,
height,
focusRequestId,
onHeightChange,
onThreadExited,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
const containerRef = useRef<HTMLDivElement>(null);
const terminalRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const drawerHeightRef = useRef(drawerHeight);
const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
const onHeightChangeRef = useRef(onHeightChange);
const onThreadExitedRef = useRef(onThreadExited);
const resizeStateRef = useRef<{
pointerId: number;
startY: number;
startHeight: number;
} | null>(null);
const didResizeDuringDragRef = useRef(false);
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
}, [onHeightChange]);
useEffect(() => {
onThreadExitedRef.current = onThreadExited;
}, [onThreadExited]);
useEffect(() => {
drawerHeightRef.current = drawerHeight;
}, [drawerHeight]);
const syncHeight = useCallback(
(nextHeight: number) => {
const clampedHeight = clampDrawerHeight(nextHeight);
if (lastSyncedHeightRef.current === clampedHeight) return;
lastSyncedHeightRef.current = clampedHeight;
onHeightChangeRef.current(clampedHeight);
},
[],
);
const fitAndResizeTerminal = useCallback((preserveBottom = false) => {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
const wasAtBottom =
preserveBottom &&
activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
activeFitAddon.fit();
if (wasAtBottom) {
activeTerminal.scrollToBottom();
}
void api.terminal
.resize({
threadId,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
})
.catch(() => undefined);
}, [api, threadId]);
useEffect(() => {
const clampedHeight = clampDrawerHeight(height);
setDrawerHeight(clampedHeight);
lastSyncedHeightRef.current = clampedHeight;
}, [height, threadId]);
const handleResizePointerDown = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
didResizeDuringDragRef.current = false;
resizeStateRef.current = {
pointerId: event.pointerId,
startY: event.clientY,
startHeight: drawerHeightRef.current,
};
},
[],
);
const handleResizePointerMove = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
event.preventDefault();
const clampedHeight = clampDrawerHeight(
resizeState.startHeight + (resizeState.startY - event.clientY),
);
if (clampedHeight === drawerHeightRef.current) {
return;
}
didResizeDuringDragRef.current = true;
drawerHeightRef.current = clampedHeight;
setDrawerHeight(clampedHeight);
},
[],
);
const handleResizePointerEnd = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
resizeStateRef.current = null;
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
if (!didResizeDuringDragRef.current) {
return;
}
syncHeight(drawerHeightRef.current);
fitAndResizeTerminal(true);
},
[fitAndResizeTerminal, syncHeight],
);
useEffect(() => {
const onWindowResize = () => {
const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
const changed = clampedHeight !== drawerHeightRef.current;
if (changed) {
setDrawerHeight(clampedHeight);
} else {
fitAndResizeTerminal(true);
}
if (!resizeStateRef.current) {
syncHeight(clampedHeight);
}
};
window.addEventListener("resize", onWindowResize);
return () => {
window.removeEventListener("resize", onWindowResize);
};
}, [fitAndResizeTerminal, syncHeight]);
useEffect(() => {
return () => {
syncHeight(drawerHeightRef.current);
};
}, [syncHeight]);
useEffect(() => {
const mount = containerRef.current;
if (!mount) return;
let disposed = false;
const fitAddon = new FitAddon();
const terminal = new Terminal({
cursorBlink: true,
lineHeight: 1.2,
fontSize: 12,
scrollback: 5_000,
fontFamily:
'"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
theme: terminalThemeFromApp(),
});
terminal.loadAddon(fitAddon);
terminal.open(mount);
fitAddon.fit();
terminalRef.current = terminal;
fitAddonRef.current = fitAddon;
const sendClearShortcut = async () => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
try {
await api.terminal.write({ threadId, data: "\u000c" });
} catch (error) {
writeSystemMessage(
activeTerminal,
error instanceof Error ? error.message : "Failed to clear terminal",
);
}
};
terminal.attachCustomKeyEventHandler((event) => {
if (!isTerminalClearShortcut(event)) return true;
event.preventDefault();
event.stopPropagation();
void sendClearShortcut();
return false;
});
const inputDisposable = terminal.onData((data) => {
void api.terminal
.write({ threadId, data })
.catch((err) =>
writeSystemMessage(
terminal,
err instanceof Error ? err.message : "Terminal write failed",
),
);
});
const themeObserver = new MutationObserver(() => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
activeTerminal.options.theme = terminalThemeFromApp();
activeTerminal.refresh(0, activeTerminal.rows - 1);
});
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ["class", "style"],
});
const openTerminal = async () => {
try {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
activeFitAddon.fit();
const snapshot = await api.terminal.open({
threadId,
cwd,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
});
if (disposed) return;
activeTerminal.write("\u001bc");
if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history);
}
window.requestAnimationFrame(() => {
activeTerminal.focus();
});
} catch (err) {
if (disposed) return;
writeSystemMessage(
terminal,
err instanceof Error ? err.message : "Failed to open terminal",
);
}
};
const unsubscribe = api.terminal.onEvent((event) => {
if (event.threadId !== threadId) return;
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
if (event.type === "output") {
activeTerminal.write(event.data);
return;
}
if (event.type === "started" || event.type === "restarted") {
activeTerminal.write("\u001bc");
if (event.snapshot.history.length > 0) {
activeTerminal.write(event.snapshot.history);
}
return;
}
if (event.type === "cleared") {
activeTerminal.clear();
activeTerminal.write("\u001bc");
return;
}
if (event.type === "error") {
writeSystemMessage(activeTerminal, event.message);
return;
}
if (event.type === "exited") {
onThreadExitedRef.current();
}
});
const fitTimer = window.setTimeout(() => {
fitAndResizeTerminal(true);
}, 30);
void openTerminal();
return () => {
disposed = true;
window.clearTimeout(fitTimer);
unsubscribe();
inputDisposable.dispose();
themeObserver.disconnect();
terminalRef.current = null;
fitAddonRef.current = null;
terminal.dispose();
};
}, [api, cwd, fitAndResizeTerminal, threadId]);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const frame = window.requestAnimationFrame(() => {
terminal.focus();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [focusRequestId]);
useEffect(() => {
const terminal = terminalRef.current;
const fitAddon = fitAddonRef.current;
if (!terminal || !fitAddon) return;
const wasAtBottom = terminal.buffer.active.viewportY >= terminal.buffer.active.baseY;
const frame = window.requestAnimationFrame(() => {
fitAddon.fit();
if (wasAtBottom) {
terminal.scrollToBottom();
}
void api.terminal
.resize({
threadId,
cols: terminal.cols,
rows: terminal.rows,
})
.catch(() => undefined);
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [api, cwd, drawerHeight, threadId]);
return (
<aside
className="thread-terminal-drawer flex shrink-0 flex-col border-t border-border/80 bg-background"
style={{ height: `${drawerHeight}px` }}
>
<div
className="flex h-2 cursor-row-resize items-center justify-center"
onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerEnd}
onPointerCancel={handleResizePointerEnd}
>
<div className="h-px w-10 rounded-full bg-border/80" />
</div>
<div className="min-h-0 w-full flex-1 px-1.5 pb-1">
<div
ref={containerRef}
className="h-full w-full overflow-hidden rounded-[4px]"
/>
</div>
</aside>
);
}
+64
View File
@@ -0,0 +1,64 @@
/**
* Imperative DOM-based context menu for non-Electron environments.
* Shows a positioned dropdown and returns a promise that resolves
* with the clicked item id, or null if dismissed.
*/
export function showContextMenuFallback<T extends string>(
items: readonly { id: T; label: string }[],
position?: { x: number; y: number },
): Promise<T | null> {
return new Promise<T | null>((resolve) => {
const overlay = document.createElement("div");
overlay.style.cssText = "position:fixed;inset:0;z-index:9999";
const menu = document.createElement("div");
menu.className =
"fixed z-[10000] min-w-[140px] rounded-md border border-border bg-popover py-1 shadow-xl animate-in fade-in zoom-in-95";
const x = position?.x ?? 0;
const y = position?.y ?? 0;
menu.style.top = `${y}px`;
menu.style.left = `${x}px`;
function cleanup(result: T | null) {
document.removeEventListener("keydown", onKeyDown);
overlay.remove();
menu.remove();
resolve(result);
}
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") {
e.preventDefault();
cleanup(null);
}
}
overlay.addEventListener("mousedown", () => cleanup(null));
document.addEventListener("keydown", onKeyDown);
for (const item of items) {
const btn = document.createElement("button");
btn.type = "button";
btn.textContent = item.label;
btn.className =
"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default";
btn.addEventListener("click", () => cleanup(item.id));
menu.appendChild(btn);
}
document.body.appendChild(overlay);
document.body.appendChild(menu);
// Adjust if menu overflows viewport
requestAnimationFrame(() => {
const rect = menu.getBoundingClientRect();
if (rect.right > window.innerWidth) {
menu.style.left = `${window.innerWidth - rect.width - 4}px`;
}
if (rect.bottom > window.innerHeight) {
menu.style.top = `${window.innerHeight - rect.height - 4}px`;
}
});
});
}
@@ -1,7 +1,8 @@
/**
* True when running inside the Electron preload bridge, false in a regular browser.
* The preload script sets window.nativeApi via contextBridge before any renderer
* The preload script sets window.nativeApi via contextBridge before any web-app
* code executes, so this is reliable at module load time.
*/
export const isElectron =
typeof window !== "undefined" && window.nativeApi !== undefined;
typeof window !== "undefined" &&
(window.desktopBridge !== undefined || window.nativeApi !== undefined);
@@ -36,13 +36,8 @@ export function buildBootstrapInput(
latestPrompt: string,
maxChars: number,
): BootstrapInputResult {
const budget = Number.isFinite(maxChars)
? Math.max(1, Math.floor(maxChars))
: 1;
const promptOnly =
latestPrompt.length <= budget
? latestPrompt
: latestPrompt.slice(0, budget);
const budget = Number.isFinite(maxChars) ? Math.max(1, Math.floor(maxChars)) : 1;
const promptOnly = latestPrompt.length <= budget ? latestPrompt : latestPrompt.slice(0, budget);
if (previousMessages.length === 0) {
return {
@@ -87,8 +82,7 @@ export function buildBootstrapInput(
let includedChronological = [...includedNewestFirst].reverse();
while (true) {
const omittedCount =
newestFirstBlocks.length - includedChronological.length;
const omittedCount = newestFirstBlocks.length - includedChronological.length;
const transcriptBody =
omittedCount > 0
? includedChronological.length > 0
@@ -101,8 +95,7 @@ export function buildBootstrapInput(
text: finalized,
includedCount: includedChronological.length,
omittedCount,
truncated:
omittedCount > 0 || latestPrompt.length !== promptOnly.length,
truncated: omittedCount > 0 || latestPrompt.length !== promptOnly.length,
};
}
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useSyncExternalStore } from "react";
type Theme = "light" | "dark" | "system";
const STORAGE_KEY = "codething:theme";
const STORAGE_KEY = "t3code:theme";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
let listeners: Array<() => void> = [];
@@ -83,22 +83,18 @@
--card-foreground: var(--color-neutral-800);
--popover: var(--color-white);
--popover-foreground: var(--color-neutral-800);
--primary: var(--color-neutral-800);
--primary-foreground: var(--color-neutral-50);
--primary: oklch(0.488 0.217 264);
--primary-foreground: var(--color-white);
--secondary: --alpha(var(--color-black) / 4%);
--secondary-foreground: var(--color-neutral-800);
--muted: --alpha(var(--color-black) / 4%);
--muted-foreground: color-mix(
in srgb,
var(--color-neutral-500) 90%,
var(--color-black)
);
--accent: --alpha(var(--color-black) / 4%);
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-black));
--accent: --alpha(var(--color-black) / 5%);
--accent-foreground: var(--color-neutral-800);
--destructive: var(--color-red-500);
--border: --alpha(var(--color-black) / 8%);
--input: --alpha(var(--color-black) / 10%);
--ring: var(--color-neutral-400);
--ring: oklch(0.488 0.217 264);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
@@ -122,36 +118,24 @@
@variant dark {
color-scheme: dark;
--background: color-mix(
in srgb,
var(--color-neutral-950) 95%,
var(--color-white)
);
--background: color-mix(in srgb, var(--color-neutral-950) 95%, var(--color-white));
--foreground: var(--color-neutral-100);
--card: color-mix(in srgb, var(--background) 98%, var(--color-white));
--card-foreground: var(--color-neutral-100);
--popover: color-mix(in srgb, var(--background) 98%, var(--color-white));
--popover-foreground: var(--color-neutral-100);
--primary: var(--color-neutral-100);
--primary-foreground: var(--color-neutral-800);
--primary: oklch(0.588 0.217 264);
--primary-foreground: var(--color-white);
--secondary: --alpha(var(--color-white) / 4%);
--secondary-foreground: var(--color-neutral-100);
--muted: --alpha(var(--color-white) / 4%);
--muted-foreground: color-mix(
in srgb,
var(--color-neutral-500) 90%,
var(--color-white)
);
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-white));
--accent: --alpha(var(--color-white) / 4%);
--accent-foreground: var(--color-neutral-100);
--destructive: color-mix(
in srgb,
var(--color-red-500) 90%,
var(--color-white)
);
--destructive: color-mix(in srgb, var(--color-red-500) 90%, var(--color-white));
--border: --alpha(var(--color-white) / 6%);
--input: --alpha(var(--color-white) / 8%);
--ring: var(--color-neutral-500);
--ring: oklch(0.588 0.217 264);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
@@ -177,7 +161,12 @@
body {
font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
"DM Sans",
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
system-ui,
sans-serif;
margin: 0;
padding: 0;
min-height: 100vh;
@@ -240,6 +229,20 @@ input {
background: rgba(255, 255, 255, 0.18);
}
/* Terminal drawer scrollbar parity with chat */
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical {
width: 6px !important;
}
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar > .slider {
border-radius: 3px;
}
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical > .slider {
width: 6px !important;
left: 0 !important;
}
/* Reasoning select -- clickable label surface */
label:has(> select#reasoning-effort) {
position: relative;
@@ -287,11 +290,7 @@ label:has(> select#reasoning-effort) select {
.chat-markdown a {
color: var(--info-foreground);
text-decoration: underline;
text-decoration-color: color-mix(
in srgb,
var(--info-foreground) 40%,
transparent
);
text-decoration-color: color-mix(in srgb, var(--info-foreground) 40%, transparent);
}
.chat-markdown a:hover {
@@ -1,5 +1,6 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "@xterm/xterm/css/xterm.css";
import "highlight.js/styles/github-dark.css";
import App from "./App";
File renamed without changes.
@@ -3,7 +3,7 @@ export {
MODEL_OPTIONS,
normalizeModelSlug,
resolveModelSlug,
} from "@acme/contracts";
} from "@t3tools/contracts";
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
export const DEFAULT_REASONING = "high";
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types";
import type { Thread } from "./types";
describe("hydratePersistedState", () => {
@@ -47,6 +48,8 @@ describe("hydratePersistedState", () => {
expect(hydrated?.projects[0]?.model).toBe(DEFAULT_MODEL);
expect(hydrated?.threads[0]?.model).toBe(DEFAULT_MODEL);
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
expect(hydrated?.runtimeMode).toBe("full-access");
});
@@ -87,6 +90,8 @@ describe("hydratePersistedState", () => {
expect(hydrated).not.toBeNull();
expect(hydrated?.threads.map((thread) => thread.id)).toEqual(["t-1"]);
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.activeThreadId).toBe("t-1");
expect(hydrated?.runtimeMode).toBe("full-access");
});
@@ -111,16 +116,84 @@ describe("hydratePersistedState", () => {
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.runtimeMode).toBe("approval-required");
});
it("hydrates terminal fields from v6 payload", () => {
const payload = JSON.stringify({
version: 6,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [
{
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 360,
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalOpen).toBe(true);
expect(hydrated?.threads[0]?.terminalHeight).toBe(360);
});
it("defaults terminalHeight when hydrating v5 payloads", () => {
const payload = JSON.stringify({
version: 5,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [
{
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
});
});
describe("toPersistedState", () => {
it("writes v4 payload and strips non-persisted thread fields", () => {
it("writes v6 payload and strips non-persisted thread fields", () => {
const thread: Thread = {
id: "t-1",
codexThreadId: "thr_1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 320,
session: null,
messages: [
{
@@ -134,6 +207,8 @@ describe("toPersistedState", () => {
events: [],
error: "boom",
createdAt: "2026-02-08T10:00:00.000Z",
branch: null,
worktreePath: null,
};
const persisted = toPersistedState({
@@ -151,7 +226,7 @@ describe("toPersistedState", () => {
runtimeMode: "full-access",
});
expect(persisted.version).toBe(4);
expect(persisted.version).toBe(6);
expect(persisted.runtimeMode).toBe("full-access");
expect(persisted.threads[0]).toEqual({
id: "t-1",
@@ -159,8 +234,12 @@ describe("toPersistedState", () => {
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 320,
messages: thread.messages,
createdAt: thread.createdAt,
branch: null,
worktreePath: null,
});
const persistedThread = persisted.threads[0];
expect(persistedThread).toBeDefined();
@@ -2,6 +2,7 @@ import { z } from "zod";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
@@ -32,8 +33,14 @@ const persistedThreadSchema = z.object({
projectId: z.string().min(1),
title: z.string().min(1),
model: z.string().min(1),
terminalOpen: z.boolean().default(false),
terminalHeight: z.number().int().min(120).max(4_096).default(
DEFAULT_THREAD_TERMINAL_HEIGHT,
),
messages: z.array(persistedMessageSchema),
createdAt: z.string().min(1),
branch: z.string().min(1).nullable().optional(),
worktreePath: z.string().min(1).nullable().optional(),
});
const persistedStateBodySchema = z.object({
@@ -62,7 +69,19 @@ export const persistedStateV4Schema = persistedStateBodySchema.extend({
version: z.literal(4).optional(),
});
export const persistedStateV6Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(6).optional(),
});
export const persistedStateV5Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(5).optional(),
});
const persistedStateSchema = z.union([
persistedStateV6Schema,
persistedStateV5Schema,
persistedStateV4Schema,
persistedStateV3Schema,
persistedStateV2Schema,
@@ -104,6 +123,8 @@ function hydrateThread(
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
terminalOpen: thread.terminalOpen ?? false,
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
session: null,
messages: thread.messages.map((message) => ({
...message,
@@ -112,6 +133,8 @@ function hydrateThread(
events: [],
error: null,
createdAt: thread.createdAt,
branch: thread.branch ?? null,
worktreePath: thread.worktreePath ?? null,
};
}
@@ -146,21 +169,17 @@ export function hydratePersistedState(
return {
projects,
threads,
activeThreadId: hasActiveThread
? parsedState.data.activeThreadId
: (threads[0]?.id ?? null),
activeThreadId: hasActiveThread ? parsedState.data.activeThreadId : (threads[0]?.id ?? null),
runtimeMode:
"runtimeMode" in parsedState.data
? parsedState.data.runtimeMode
: DEFAULT_RUNTIME_MODE,
"runtimeMode" in parsedState.data ? parsedState.data.runtimeMode : DEFAULT_RUNTIME_MODE,
};
}
export function toPersistedState(
state: PersistedStoreSnapshot,
): z.infer<typeof persistedStateV4Schema> {
): z.infer<typeof persistedStateV6Schema> {
return {
version: 4,
version: 6,
projects: state.projects,
threads: state.threads.map((thread) => ({
id: thread.id,
@@ -168,8 +187,12 @@ export function toPersistedState(
projectId: thread.projectId,
title: thread.title,
model: thread.model,
terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight,
messages: thread.messages,
createdAt: thread.createdAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
})),
activeThreadId: state.activeThreadId,
runtimeMode: state.runtimeMode,
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import {
type WorkLogEntry,
applyEventToMessages,
@@ -1,4 +1,4 @@
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@acme/contracts";
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@t3tools/contracts";
import type { ChatMessage, SessionPhase } from "./types";
import { createWsNativeApi } from "./wsNativeApi";
@@ -109,11 +109,7 @@ function normalizeItemType(raw: string | undefined): string {
}
function shouldDropItemType(type: string): boolean {
if (
type.includes("preamble") ||
type.includes("reasoning") ||
type.includes("thought")
) {
if (type.includes("preamble") || type.includes("reasoning") || type.includes("thought")) {
return true;
}
@@ -121,11 +117,7 @@ function shouldDropItemType(type: string): boolean {
}
function shouldShowItemLifecycle(type: string): boolean {
return (
type.includes("tool") ||
type.includes("command") ||
type.includes("file change")
);
return type.includes("tool") || type.includes("command") || type.includes("file change");
}
function shouldDropMethod(method: string): boolean {
@@ -182,9 +174,7 @@ function extractDetail(
return undefined;
}
function lifecycleCandidateFromItemEvent(
event: ProviderEvent,
): ItemLifecycleCandidate | null {
function lifecycleCandidateFromItemEvent(event: ProviderEvent): ItemLifecycleCandidate | null {
const payload = asObject(event.payload);
const item = asObject(payload?.item);
const normalizedType = normalizeItemType(asString(item?.type));
@@ -360,10 +350,7 @@ export function deriveWorkLogEntries(
) {
continue;
}
if (
lifecycleCandidate.label === "Tool call" &&
!lifecycleCandidate.detail
) {
if (lifecycleCandidate.label === "Tool call" && !lifecycleCandidate.detail) {
continue;
}
@@ -371,9 +358,7 @@ export function deriveWorkLogEntries(
id: lifecycleCandidate.id,
createdAt: lifecycleCandidate.createdAt,
label: lifecycleCandidate.label,
...(lifecycleCandidate.detail
? { detail: lifecycleCandidate.detail }
: {}),
...(lifecycleCandidate.detail ? { detail: lifecycleCandidate.detail } : {}),
tone: lifecycleCandidate.tone,
});
continue;
@@ -1,12 +1,11 @@
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { type AppState, reducer } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types";
import type { Thread } from "./types";
function makeSession(
overrides: Partial<ProviderSession> = {},
): ProviderSession {
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
return {
sessionId: "sess-1",
provider: "codex",
@@ -36,11 +35,15 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
projectId: "project-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
session: makeSession(),
messages: [],
events: [],
error: null,
createdAt: "2026-02-09T00:00:00.000Z",
branch: null,
worktreePath: null,
...overrides,
};
}
@@ -79,6 +82,35 @@ describe("store reducer thread continuity", () => {
expect(next.threads[0]?.codexThreadId).toBe("thr_123");
});
it("toggles terminal open state per thread", () => {
const state = makeState(makeThread({ terminalOpen: false }));
const next = reducer(state, {
type: "TOGGLE_THREAD_TERMINAL",
threadId: "thread-local-1",
});
expect(next.threads[0]?.terminalOpen).toBe(true);
});
it("sets terminal open state per thread", () => {
const state = makeState(makeThread({ terminalOpen: true }));
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_OPEN",
threadId: "thread-local-1",
open: false,
});
expect(next.threads[0]?.terminalOpen).toBe(false);
});
it("sets terminal height per thread", () => {
const state = makeState(makeThread({ terminalHeight: 280 }));
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_HEIGHT",
threadId: "thread-local-1",
height: 360,
});
expect(next.threads[0]?.terminalHeight).toBe(360);
});
it("backfills codexThreadId from routed provider events", () => {
const state = makeState(makeThread({ codexThreadId: null }));
const next = reducer(state, {
@@ -131,4 +163,60 @@ describe("store reducer thread continuity", () => {
expect(next.threads[0]?.codexThreadId).toBe("thr_new");
expect(next.threads[0]?.session?.threadId).toBe("thr_new");
});
it("reconciles project ids by cwd when syncing backend projects", () => {
const state: AppState = {
projects: [
{
id: "project-old-a",
name: "A",
cwd: "/tmp/a",
model: "gpt-5.3-codex",
expanded: false,
},
{
id: "project-old-b",
name: "B",
cwd: "/tmp/b",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [
makeThread({
id: "thread-a",
projectId: "project-old-a",
}),
makeThread({
id: "thread-b",
projectId: "project-old-b",
}),
],
activeThreadId: "thread-b",
runtimeMode: "full-access",
diffOpen: false,
};
const next = reducer(state, {
type: "SYNC_PROJECTS",
projects: [
{
id: "project-new-a",
name: "A",
cwd: "/tmp/a",
model: "gpt-5.3-codex",
expanded: true,
},
],
});
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.id).toBe("project-new-a");
// Preserve existing project UI preferences by cwd
expect(next.projects[0]?.expanded).toBe(false);
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.id).toBe("thread-a");
expect(next.threads[0]?.projectId).toBe("project-new-a");
expect(next.activeThreadId).toBe("thread-a");
});
});
@@ -8,15 +8,10 @@ import {
useReducer,
} from "react";
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import {
applyEventToMessages,
asObject,
asString,
evolveSession,
} from "./session-logic";
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
import {
DEFAULT_RUNTIME_MODE,
type Project,
@@ -28,9 +23,13 @@ import {
type Action =
| { type: "ADD_PROJECT"; project: Project }
| { type: "SYNC_PROJECTS"; projects: Project[] }
| { type: "TOGGLE_PROJECT"; projectId: string }
| { type: "ADD_THREAD"; thread: Thread }
| { type: "SET_ACTIVE_THREAD"; threadId: string }
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: string; open: boolean }
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: string; height: number }
| { type: "TOGGLE_DIFF" }
| {
type: "APPLY_EVENT";
@@ -42,7 +41,14 @@ type Action =
| { type: "SET_ERROR"; threadId: string; error: string | null }
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
| {
type: "SET_THREAD_BRANCH";
threadId: string;
branch: string | null;
worktreePath: string | null;
}
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode }
| { type: "DELETE_THREAD"; threadId: string };
// ── State ────────────────────────────────────────────────────────────
@@ -54,8 +60,12 @@ export interface AppState {
diffOpen: boolean;
}
const PERSISTED_STATE_KEY = "codething:renderer-state:v4";
const PERSISTED_STATE_KEY = "t3code:renderer-state:v6";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
"t3code:renderer-state:v3",
"codething:renderer-state:v4",
"codething:renderer-state:v3",
"codething:renderer-state:v2",
"codething:renderer-state:v1",
@@ -76,15 +86,16 @@ function readPersistedState(): AppState {
try {
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
const [legacyV3Key, legacyV2Key, legacyV1Key] = LEGACY_PERSISTED_STATE_KEYS;
const rawLegacyV3 = window.localStorage.getItem(legacyV3Key);
const rawLegacyV2 = window.localStorage.getItem(legacyV2Key);
const rawLegacyV1 = window.localStorage.getItem(legacyV1Key);
const raw = rawCurrent ?? rawLegacyV3 ?? rawLegacyV2 ?? rawLegacyV1;
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) =>
window.localStorage.getItem(key),
);
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
const raw = rawCurrent ?? rawLegacy;
if (!raw) return initialState;
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
const hydrated = hydratePersistedState(
raw,
!rawCurrent && !rawLegacyV3 && !rawLegacyV2 && Boolean(rawLegacyV1),
!rawCurrent && raw === rawCodethingV1,
);
if (!hydrated) return initialState;
@@ -98,10 +109,7 @@ function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
PERSISTED_STATE_KEY,
JSON.stringify(toPersistedState(state)),
);
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
@@ -143,10 +151,7 @@ function getEventThreadId(event: ProviderEvent): string | undefined {
);
}
function shouldIgnoreForeignThreadEvent(
thread: Thread,
event: ProviderEvent,
): boolean {
function shouldIgnoreForeignThreadEvent(thread: Thread, event: ProviderEvent): boolean {
const eventThreadId = getEventThreadId(event);
if (!eventThreadId) {
return false;
@@ -175,10 +180,7 @@ function durationMs(startIso: string, endIso: string): number | undefined {
return end - start;
}
function updateTurnFields(
thread: Thread,
event: ProviderEvent,
): Partial<Thread> {
function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread> {
if (event.method === "turn/started") {
return {
latestTurnId: getEventTurnId(event) ?? thread.latestTurnId,
@@ -195,9 +197,7 @@ function updateTurnFields(
? thread.latestTurnStartedAt
: undefined;
const elapsed =
startedAt && startedAt.length > 0
? durationMs(startedAt, event.createdAt)
: undefined;
startedAt && startedAt.length > 0 ? durationMs(startedAt, event.createdAt) : undefined;
return {
latestTurnId: completedTurnId ?? thread.latestTurnId,
@@ -214,6 +214,9 @@ function updateTurnFields(
export function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "ADD_PROJECT":
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
return state;
}
return {
...state,
projects: [
@@ -225,6 +228,48 @@ export function reducer(state: AppState, action: Action): AppState {
],
};
case "SYNC_PROJECTS": {
const previousByCwd = new Map(
state.projects.map((project) => [project.cwd, project] as const),
);
const nextProjects = action.projects.map((project) => {
const previous = previousByCwd.get(project.cwd);
return {
...project,
model: resolveModelSlug(previous?.model ?? project.model),
expanded: previous?.expanded ?? project.expanded,
};
});
const previousProjectById = new Map(
state.projects.map((project) => [project.id, project] as const),
);
const nextProjectIdByCwd = new Map(
nextProjects.map((project) => [project.cwd, project.id] as const),
);
const nextThreads = state.threads
.map((thread) => {
const previousProject = previousProjectById.get(thread.projectId);
if (!previousProject) return null;
const mappedProjectId = nextProjectIdByCwd.get(previousProject.cwd);
if (!mappedProjectId) return null;
return {
...thread,
projectId: mappedProjectId,
};
})
.filter((thread): thread is Thread => thread !== null);
const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId)
? state.activeThreadId
: (nextThreads[0]?.id ?? null);
return {
...state,
projects: nextProjects,
threads: nextThreads,
activeThreadId,
};
}
case "TOGGLE_PROJECT":
return {
...state,
@@ -249,6 +294,33 @@ export function reducer(state: AppState, action: Action): AppState {
case "SET_ACTIVE_THREAD":
return { ...state, activeThreadId: action.threadId };
case "TOGGLE_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
terminalOpen: !t.terminalOpen,
})),
};
case "SET_THREAD_TERMINAL_OPEN":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
terminalOpen: action.open,
})),
};
case "SET_THREAD_TERMINAL_HEIGHT":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
terminalHeight: action.height,
})),
};
case "TOGGLE_DIFF":
return { ...state, diffOpen: !state.diffOpen };
@@ -265,24 +337,16 @@ export function reducer(state: AppState, action: Action): AppState {
...(() => {
const eventThreadId = getEventThreadId(event);
const shouldRebindIdentity =
event.method === "thread/started" &&
t.session?.status === "connecting";
event.method === "thread/started" && t.session?.status === "connecting";
return {
codexThreadId: shouldRebindIdentity
? eventThreadId ?? t.codexThreadId
: t.codexThreadId ?? eventThreadId ?? null,
error:
(event.kind === "error" && event.message
? event.message
: t.error),
? (eventThreadId ?? t.codexThreadId)
: (t.codexThreadId ?? eventThreadId ?? null),
error: event.kind === "error" && event.message ? event.message : t.error,
};
})(),
session: t.session ? evolveSession(t.session, event) : t.session,
messages: applyEventToMessages(
t.messages,
event,
activeAssistantItemRef,
),
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
events: [event, ...t.events],
...updateTurnFields(t, event),
})),
@@ -350,12 +414,37 @@ export function reducer(state: AppState, action: Action): AppState {
})),
};
case "SET_THREAD_BRANCH": {
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => {
// When the effective cwd changes (worktreePath differs), the old
// session is no longer valid — clear it so ensureSession creates a
// new one with the correct cwd on the next message.
const cwdChanged = t.worktreePath !== action.worktreePath;
return {
...t,
branch: action.branch,
worktreePath: action.worktreePath,
...(cwdChanged ? { session: null } : {}),
};
}),
};
}
case "SET_RUNTIME_MODE":
return {
...state,
runtimeMode: action.mode,
};
case "DELETE_THREAD": {
const threads = state.threads.filter((t) => t.id !== action.threadId);
const activeThreadId =
state.activeThreadId === action.threadId ? (threads[0]?.id ?? null) : state.activeThreadId;
return { ...state, threads, activeThreadId };
}
default:
return state;
}
+88
View File
@@ -0,0 +1,88 @@
import { describe, expect, it } from "vitest";
import {
isTerminalClearShortcut,
isTerminalToggleShortcut,
type ShortcutEventLike,
} from "./terminal-shortcuts";
function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
return {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
...overrides,
};
}
describe("isTerminalToggleShortcut", () => {
it("matches Cmd+J on macOS", () => {
expect(
isTerminalToggleShortcut(event({ metaKey: true }), "MacIntel"),
).toBe(true);
});
it("matches Ctrl+J on non-macOS", () => {
expect(
isTerminalToggleShortcut(event({ ctrlKey: true }), "Win32"),
).toBe(true);
});
it("rejects wrong modifiers", () => {
expect(
isTerminalToggleShortcut(
event({ ctrlKey: true, shiftKey: true }),
"Win32",
),
).toBe(false);
expect(
isTerminalToggleShortcut(event({ metaKey: true, altKey: true }), "MacIntel"),
).toBe(false);
});
it("rejects non-j keys", () => {
expect(
isTerminalToggleShortcut(event({ key: "k", ctrlKey: true }), "Linux"),
).toBe(false);
});
});
describe("isTerminalClearShortcut", () => {
it("matches Ctrl+L on all platforms", () => {
expect(
isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux"),
).toBe(true);
expect(
isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel"),
).toBe(true);
});
it("matches Cmd+K on macOS", () => {
expect(
isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel"),
).toBe(true);
});
it("rejects Cmd+K on non-macOS", () => {
expect(
isTerminalClearShortcut(event({ key: "k", metaKey: true }), "Win32"),
).toBe(false);
});
it("rejects wrong modifiers", () => {
expect(
isTerminalClearShortcut(
event({ key: "l", ctrlKey: true, shiftKey: true }),
"Linux",
),
).toBe(false);
expect(
isTerminalClearShortcut(
event({ key: "k", metaKey: true, altKey: true }),
"MacIntel",
),
).toBe(false);
});
});
+52
View File
@@ -0,0 +1,52 @@
export interface ShortcutEventLike {
key: string;
metaKey: boolean;
ctrlKey: boolean;
shiftKey: boolean;
altKey: boolean;
}
function isMacPlatform(platform: string): boolean {
return /mac|iphone|ipad|ipod/i.test(platform);
}
export function isTerminalToggleShortcut(
event: ShortcutEventLike,
platform = navigator.platform,
): boolean {
const key = event.key.toLowerCase();
if (key !== "j") return false;
if (event.shiftKey || event.altKey) return false;
if (isMacPlatform(platform)) {
return event.metaKey && !event.ctrlKey;
}
return event.ctrlKey && !event.metaKey;
}
export function isTerminalClearShortcut(
event: ShortcutEventLike,
platform = navigator.platform,
): boolean {
const key = event.key.toLowerCase();
if (
key === "l" &&
event.ctrlKey &&
!event.metaKey &&
!event.altKey &&
!event.shiftKey
) {
return true;
}
return (
isMacPlatform(platform) &&
key === "k" &&
event.metaKey &&
!event.ctrlKey &&
!event.altKey &&
!event.shiftKey
);
}
@@ -1,8 +1,9 @@
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
export type RuntimeMode = "approval-required" | "full-access";
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
export interface ChatMessage {
id: string;
@@ -26,6 +27,8 @@ export interface Thread {
projectId: string;
title: string;
model: string;
terminalOpen: boolean;
terminalHeight: number;
session: ProviderSession | null;
messages: ChatMessage[];
events: ProviderEvent[];
@@ -35,4 +38,6 @@ export interface Thread {
latestTurnStartedAt?: string | undefined;
latestTurnCompletedAt?: string | undefined;
latestTurnDurationMs?: number | undefined;
branch: string | null;
worktreePath: string | null;
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference types="vite/client" />
import type { NativeApi } from "@t3tools/contracts";
interface DesktopBridge {
getWsUrl: () => string | null;
pickFolder: () => Promise<string | null>;
showContextMenu: (items: readonly { id: string; label: string }[]) => Promise<string | null>;
}
declare global {
interface Window {
nativeApi?: NativeApi;
desktopBridge?: DesktopBridge;
}
}
+123
View File
@@ -0,0 +1,123 @@
import { type NativeApi, WS_CHANNELS, WS_METHODS, type WsWelcomePayload } from "@t3tools/contracts";
import { showContextMenuFallback } from "./contextMenuFallback";
import { WsTransport } from "./wsTransport";
let instance: { api: NativeApi; transport: WsTransport } | null = null;
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
let lastWelcome: WsWelcomePayload | null = null;
/**
* Subscribe to the server welcome message. If a welcome was already received
* before this call, the listener fires synchronously with the cached payload.
* This avoids the race between WebSocket connect and React effect registration.
*/
export function onServerWelcome(listener: (payload: WsWelcomePayload) => void): () => void {
welcomeListeners.add(listener);
// Replay cached welcome for late subscribers
if (lastWelcome) {
try {
listener(lastWelcome);
} catch {
// Swallow listener errors
}
}
return () => {
welcomeListeners.delete(listener);
};
}
export function createWsNativeApi(): NativeApi {
if (instance) return instance.api;
const transport = new WsTransport();
// Listen for server welcome and forward to registered listeners.
// Also cache it so late subscribers (React effects) get it immediately.
transport.subscribe(WS_CHANNELS.serverWelcome, (data) => {
const payload = data as WsWelcomePayload;
lastWelcome = payload;
for (const listener of welcomeListeners) {
try {
listener(payload);
} catch {
// Swallow listener errors
}
}
});
const api: NativeApi = {
todos: {
list: async () => [],
add: async () => [],
toggle: async () => [],
remove: async () => [],
},
dialogs: {
pickFolder: async () => {
if (!window.desktopBridge) return null;
return window.desktopBridge.pickFolder();
},
},
terminal: {
open: (input) => transport.request(WS_METHODS.terminalOpen, input),
write: (input) => transport.request(WS_METHODS.terminalWrite, input),
resize: (input) => transport.request(WS_METHODS.terminalResize, input),
clear: (input) => transport.request(WS_METHODS.terminalClear, input),
restart: (input) => transport.request(WS_METHODS.terminalRestart, input),
close: (input) => transport.request(WS_METHODS.terminalClose, input),
onEvent: (callback) =>
transport.subscribe(WS_CHANNELS.terminalEvent, callback as (data: unknown) => void),
},
agent: {
spawn: async () => "",
kill: async () => {},
write: async () => {},
onOutput: () => () => {},
onExit: () => () => {},
},
providers: {
startSession: (input) => transport.request(WS_METHODS.providersStartSession, input),
sendTurn: (input) => transport.request(WS_METHODS.providersSendTurn, input),
interruptTurn: (input) => transport.request(WS_METHODS.providersInterruptTurn, input),
respondToRequest: (input) => transport.request(WS_METHODS.providersRespondToRequest, input),
stopSession: (input) => transport.request(WS_METHODS.providersStopSession, input),
listSessions: () => transport.request(WS_METHODS.providersListSessions),
onEvent: (callback) =>
transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void),
},
projects: {
list: () => transport.request(WS_METHODS.projectsList),
add: (input) => transport.request(WS_METHODS.projectsAdd, input),
remove: (input) => transport.request(WS_METHODS.projectsRemove, input),
},
shell: {
openInEditor: (cwd, editor) =>
transport.request(WS_METHODS.shellOpenInEditor, { cwd, editor }),
},
git: {
listBranches: (input) => transport.request(WS_METHODS.gitListBranches, input),
createWorktree: (input) => transport.request(WS_METHODS.gitCreateWorktree, input),
removeWorktree: (input) => transport.request(WS_METHODS.gitRemoveWorktree, input),
createBranch: (input) => transport.request(WS_METHODS.gitCreateBranch, input),
checkout: (input) => transport.request(WS_METHODS.gitCheckout, input),
init: (input) => transport.request(WS_METHODS.gitInit, input),
},
contextMenu: {
show: async <T extends string>(
items: readonly { id: T; label: string }[],
position?: { x: number; y: number },
): Promise<T | null> => {
if (window.desktopBridge) {
return window.desktopBridge.showContextMenu(items) as Promise<T | null>;
}
return showContextMenuFallback(items, position);
},
},
};
instance = { api, transport };
return api;
}
@@ -1,4 +1,4 @@
import type { WsPush, WsRequest, WsResponse } from "@acme/contracts";
import type { WsPush, WsRequest, WsResponse } from "@t3tools/contracts";
type PushListener = (data: unknown) => void;
@@ -22,14 +22,17 @@ export class WsTransport {
private readonly url: string;
constructor(url?: string) {
const bridgeUrl = window.desktopBridge?.getWsUrl();
// In dev mode, VITE_WS_URL points to the server's WebSocket endpoint.
// In production, the page is served by the WS server on the same host:port.
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
this.url =
url ??
(envUrl && envUrl.length > 0
? envUrl
: `ws://${window.location.hostname}:${window.location.port}`);
(bridgeUrl && bridgeUrl.length > 0
? bridgeUrl
: envUrl && envUrl.length > 0
? envUrl
: `ws://${window.location.hostname}:${window.location.port}`);
this.connect();
}
@@ -182,9 +185,8 @@ export class WsTransport {
if (this.disposed) return;
const delay =
RECONNECT_DELAYS_MS[
Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)
] ?? RECONNECT_DELAYS_MS[0]!;
RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)] ??
RECONNECT_DELAYS_MS[0]!;
this.reconnectAttempt++;
this.reconnectTimer = setTimeout(() => {
File renamed without changes.
+9
View File
@@ -0,0 +1,9 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"dev": {
"persistent": true,
},
},
}
+35
View File
@@ -0,0 +1,35 @@
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
const port = Number(process.env.PORT ?? 5173);
export default defineConfig({
plugins: [
react({
babel: {
plugins: [["babel-plugin-react-compiler", { target: "19" }]],
},
}),
tailwindcss(),
],
define: {
// In dev mode, tell the web app where the WebSocket server lives
"import.meta.env.VITE_WS_URL": JSON.stringify(process.env.VITE_WS_URL ?? ""),
},
server: {
port,
strictPort: true,
hmr: {
// Explicit config so Vite's HMR WebSocket connects reliably
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
// connection logs — enable "Verbose" in DevTools to see them.
protocol: "ws",
host: "localhost",
},
},
build: {
outDir: "dist",
emptyOutDir: true,
},
});
+476 -172
View File
File diff suppressed because it is too large. Load diff
+11 -7
View File
@@ -1,28 +1,32 @@
{
"name": "ct-round-5",
"name": "@t3tools/monorepo",
"private": true,
"workspaces": [
"apps/*",
"packages/*"
],
"scripts": {
"dev": "CODETHING_LOG_WS_EVENTS=1 VITE_WS_URL=ws://localhost:3773 turbo run dev --ui=tui --filter=@acme/contracts --filter=@acme/renderer --filter=t3 --parallel",
"dev:server": "bun run build:contracts && bun run --cwd apps/server dev",
"dev:web": "VITE_WS_URL=ws://localhost:3773 bun run --cwd apps/renderer dev",
"start": "node apps/server/dist/index.js",
"dev": "T3CODE_LOG_WS_EVENTS=1 VITE_WS_URL=ws://localhost:3773 turbo run dev --ui=tui --filter=@t3tools/contracts --filter=@t3tools/web --filter=t3 --parallel",
"dev:server": "turbo run dev --filter=t3",
"dev:web": "VITE_WS_URL=ws://localhost:3773 turbo run dev --filter=@t3tools/web",
"dev:desktop": "turbo run dev --filter=@t3tools/desktop --filter=@t3tools/web --parallel",
"start": "turbo run start --filter=t3",
"start:desktop": "turbo run start --filter=@t3tools/desktop",
"build": "turbo run build",
"build:desktop": "turbo run build --filter=@t3tools/desktop --filter=t3",
"typecheck": "turbo run typecheck",
"lint": "oxlint --report-unused-disable-directives",
"test": "turbo run test",
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
"fmt": "oxfmt",
"build:contracts": "bun run --cwd packages/contracts build"
"build:contracts": "turbo run build --filter=@t3tools/contracts"
},
"devDependencies": {
"oxfmt": "^0.28.0",
"oxlint": "^1.43.0",
"turbo": "^2.3.3",
"typescript": "^5.7.3",
"vitest": "^3.0.0"
"vitest": "^4.0.0"
},
"engines": {
"bun": ">=1.3.9"
+6 -6
View File
@@ -1,5 +1,5 @@
{
"name": "@acme/contracts",
"name": "@t3tools/contracts",
"version": "0.0.0",
"private": true,
"files": [
@@ -7,18 +7,18 @@
],
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"import": "./dist/index.js",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"scripts": {
"dev": "tsup src/index.ts --format esm,cjs --dts --watch --clean",
"build": "tsup src/index.ts --format esm,cjs --dts --clean",
"dev": "tsdown src/index.ts --format esm,cjs --dts --watch --clean",
"build": "tsdown src/index.ts --format esm,cjs --dts --clean",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
@@ -26,7 +26,7 @@
"zod": "^3.24.1"
},
"devDependencies": {
"tsup": "^8.3.5",
"tsdown": "^0.20.3",
"typescript": "^5.7.3"
}
}
+69
View File
@@ -0,0 +1,69 @@
import { z } from "zod";
// ── Input schemas ──
export const gitListBranchesInputSchema = z.object({
cwd: z.string().min(1),
});
export const gitCreateWorktreeInputSchema = z.object({
cwd: z.string().min(1),
/** Base branch to create the worktree from. */
branch: z.string().min(1),
/** New branch name to create in the worktree. */
newBranch: z.string().min(1),
path: z.string().min(1).optional(),
});
export const gitRemoveWorktreeInputSchema = z.object({
cwd: z.string().min(1),
path: z.string().min(1),
});
export const gitCreateBranchInputSchema = z.object({
cwd: z.string().min(1),
branch: z.string().min(1),
});
export const gitCheckoutInputSchema = z.object({
cwd: z.string().min(1),
branch: z.string().min(1),
});
export const gitInitInputSchema = z.object({
cwd: z.string().min(1),
});
// ── Output schemas ──
export const gitBranchSchema = z.object({
name: z.string().min(1),
current: z.boolean(),
isDefault: z.boolean(),
worktreePath: z.string().min(1).nullable(),
});
export const gitWorktreeSchema = z.object({
path: z.string().min(1),
branch: z.string().min(1),
});
// ── Types ──
export type GitListBranchesInput = z.infer<typeof gitListBranchesInputSchema>;
export type GitBranch = z.infer<typeof gitBranchSchema>;
export type GitCreateWorktreeInput = z.infer<typeof gitCreateWorktreeInputSchema>;
export type GitWorktree = z.infer<typeof gitWorktreeSchema>;
export type GitRemoveWorktreeInput = z.infer<typeof gitRemoveWorktreeInputSchema>;
export type GitCreateBranchInput = z.infer<typeof gitCreateBranchInputSchema>;
export type GitCheckoutInput = z.infer<typeof gitCheckoutInputSchema>;
export type GitInitInput = z.infer<typeof gitInitInputSchema>;
export interface GitListBranchesResult {
branches: GitBranch[];
isRepo: boolean;
}
export interface GitCreateWorktreeResult {
worktree: GitWorktree;
}
+2
View File
@@ -5,3 +5,5 @@ export * from "./terminal";
export * from "./provider";
export * from "./model";
export * from "./ws";
export * from "./project";
export * from "./git";
+51 -2
View File
@@ -1,4 +1,14 @@
import type { AgentConfig, AgentExit, OutputChunk } from "./agent";
import type {
GitCheckoutInput,
GitCreateBranchInput,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
GitListBranchesInput,
GitListBranchesResult,
GitRemoveWorktreeInput,
} from "./git";
import type {
ProviderEvent,
ProviderInterruptTurnInput,
@@ -9,7 +19,21 @@ import type {
ProviderStopSessionInput,
ProviderTurnStartResult,
} from "./provider";
import type { TerminalCommandInput, TerminalCommandResult } from "./terminal";
import type {
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectRemoveInput,
} from "./project";
import type {
TerminalCloseInput,
TerminalEvent,
TerminalOpenInput,
TerminalResizeInput,
TerminalSessionSnapshot,
TerminalThreadInput,
TerminalWriteInput,
} from "./terminal";
import type { NewTodoInput, Todo } from "./todo";
export const EDITORS = [
@@ -30,7 +54,13 @@ export interface NativeApi {
pickFolder: () => Promise<string | null>;
};
terminal: {
run: (input: TerminalCommandInput) => Promise<TerminalCommandResult>;
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
write: (input: TerminalWriteInput) => Promise<void>;
resize: (input: TerminalResizeInput) => Promise<void>;
clear: (input: TerminalThreadInput) => Promise<void>;
restart: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
close: (input: TerminalCloseInput) => Promise<void>;
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
};
agent: {
spawn: (config: AgentConfig) => Promise<string>;
@@ -48,7 +78,26 @@ export interface NativeApi {
listSessions: () => Promise<ProviderSession[]>;
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
};
projects: {
list: () => Promise<ProjectListResult>;
add: (input: ProjectAddInput) => Promise<ProjectAddResult>;
remove: (input: ProjectRemoveInput) => Promise<void>;
};
shell: {
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
};
git: {
listBranches: (input: GitListBranchesInput) => Promise<GitListBranchesResult>;
createWorktree: (input: GitCreateWorktreeInput) => Promise<GitCreateWorktreeResult>;
removeWorktree: (input: GitRemoveWorktreeInput) => Promise<void>;
createBranch: (input: GitCreateBranchInput) => Promise<void>;
checkout: (input: GitCheckoutInput) => Promise<void>;
init: (input: GitInitInput) => Promise<void>;
};
contextMenu: {
show: <T extends string>(
items: readonly { id: T; label: string }[],
position?: { x: number; y: number },
) => Promise<T | null>;
};
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import {
projectAddInputSchema,
projectAddResultSchema,
projectListResultSchema,
projectRemoveInputSchema,
} from "./project";
describe("project contracts", () => {
it("parses project list result", () => {
const result = projectListResultSchema.parse([
{
id: "project-1",
cwd: "/tmp/project",
name: "project",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
]);
expect(result).toHaveLength(1);
expect(result[0]?.id).toBe("project-1");
});
it("trims add input cwd", () => {
const parsed = projectAddInputSchema.parse({ cwd: " /tmp/project " });
expect(parsed.cwd).toBe("/tmp/project");
});
it("requires add result created flag", () => {
const parsed = projectAddResultSchema.parse({
project: {
id: "project-1",
cwd: "/tmp/project",
name: "project",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
created: true,
});
expect(parsed.created).toBe(true);
});
it("parses remove input", () => {
const parsed = projectRemoveInputSchema.parse({ id: "project-1" });
expect(parsed.id).toBe("project-1");
});
});
+30
View File
@@ -0,0 +1,30 @@
import { z } from "zod";
export const projectRecordSchema = z.object({
id: z.string().min(1),
cwd: z.string().min(1),
name: z.string().min(1),
createdAt: z.string().datetime(),
updatedAt: z.string().datetime(),
});
export const projectListResultSchema = z.array(projectRecordSchema);
export const projectAddInputSchema = z.object({
cwd: z.string().trim().min(1),
});
export const projectAddResultSchema = z.object({
project: projectRecordSchema,
created: z.boolean(),
});
export const projectRemoveInputSchema = z.object({
id: z.string().min(1),
});
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
+6 -21
View File
@@ -83,12 +83,7 @@ export const providerRespondToRequestInputSchema = z.object({
decision: providerApprovalDecisionSchema,
});
export const providerEventKindSchema = z.enum([
"session",
"notification",
"request",
"error",
]);
export const providerEventKindSchema = z.enum(["session", "notification", "request", "error"]);
export const providerEventSchema = z.object({
id: z.string().min(1),
@@ -111,24 +106,14 @@ export type ProviderKind = z.infer<typeof providerKindSchema>;
export type ProviderApprovalPolicy = z.infer<typeof providerApprovalPolicySchema>;
export type ProviderSandboxMode = z.infer<typeof providerSandboxModeSchema>;
export type ProviderRequestKind = z.infer<typeof providerRequestKindSchema>;
export type ProviderApprovalDecision = z.infer<
typeof providerApprovalDecisionSchema
>;
export type ProviderApprovalDecision = z.infer<typeof providerApprovalDecisionSchema>;
export type ProviderSessionStatus = z.infer<typeof providerSessionStatusSchema>;
export type ProviderSession = z.infer<typeof providerSessionSchema>;
export type ProviderSessionStartInput = z.input<typeof providerSessionStartInputSchema>;
export type ProviderSendTurnInput = z.input<typeof providerSendTurnInputSchema>;
export type ProviderTurnStartResult = z.infer<
typeof providerTurnStartResultSchema
>;
export type ProviderInterruptTurnInput = z.input<
typeof providerInterruptTurnInputSchema
>;
export type ProviderStopSessionInput = z.input<
typeof providerStopSessionInputSchema
>;
export type ProviderRespondToRequestInput = z.input<
typeof providerRespondToRequestInputSchema
>;
export type ProviderTurnStartResult = z.infer<typeof providerTurnStartResultSchema>;
export type ProviderInterruptTurnInput = z.input<typeof providerInterruptTurnInputSchema>;
export type ProviderStopSessionInput = z.input<typeof providerStopSessionInputSchema>;
export type ProviderRespondToRequestInput = z.input<typeof providerRespondToRequestInputSchema>;
export type ProviderEventKind = z.infer<typeof providerEventKindSchema>;
export type ProviderEvent = z.infer<typeof providerEventSchema>;
+107 -13
View File
@@ -1,24 +1,118 @@
import { describe, expect, it } from "vitest";
import { terminalCommandInputSchema } from "./terminal";
import {
terminalCloseInputSchema,
terminalEventSchema,
terminalOpenInputSchema,
terminalResizeInputSchema,
terminalSessionSnapshotSchema,
terminalThreadInputSchema,
terminalWriteInputSchema,
} from "./terminal";
describe("terminalCommandInputSchema", () => {
it("accepts a valid command", () => {
const result = terminalCommandInputSchema.safeParse({
command: "echo hello",
describe("terminalOpenInputSchema", () => {
it("accepts valid open input", () => {
const result = terminalOpenInputSchema.safeParse({
threadId: "thread-1",
cwd: "/tmp/project",
cols: 120,
rows: 40,
});
expect(result.success).toBe(true);
});
it("trims whitespace", () => {
const result = terminalCommandInputSchema.parse({
command: " echo hello ",
it("rejects invalid bounds", () => {
const result = terminalOpenInputSchema.safeParse({
threadId: "thread-1",
cwd: "/tmp/project",
cols: 10,
rows: 2,
});
expect(result.command).toBe("echo hello");
});
it("rejects an empty command", () => {
const result = terminalCommandInputSchema.safeParse({ command: " " });
expect(result.success).toBe(false);
});
});
describe("terminalWriteInputSchema", () => {
it("accepts non-empty data", () => {
const result = terminalWriteInputSchema.safeParse({
threadId: "thread-1",
data: "echo hello\n",
});
expect(result.success).toBe(true);
});
it("rejects empty data", () => {
const result = terminalWriteInputSchema.safeParse({
threadId: "thread-1",
data: "",
});
expect(result.success).toBe(false);
});
});
describe("terminalThreadInputSchema", () => {
it("trims thread ids", () => {
const parsed = terminalThreadInputSchema.parse({ threadId: " thread-1 " });
expect(parsed.threadId).toBe("thread-1");
});
});
describe("terminalResizeInputSchema", () => {
it("accepts valid size", () => {
const result = terminalResizeInputSchema.safeParse({
threadId: "thread-1",
cols: 80,
rows: 24,
});
expect(result.success).toBe(true);
});
});
describe("terminalCloseInputSchema", () => {
it("accepts optional deleteHistory", () => {
const result = terminalCloseInputSchema.safeParse({
threadId: "thread-1",
deleteHistory: true,
});
expect(result.success).toBe(true);
});
});
describe("terminalSessionSnapshotSchema", () => {
it("accepts running snapshots", () => {
const result = terminalSessionSnapshotSchema.safeParse({
threadId: "thread-1",
cwd: "/tmp/project",
status: "running",
pid: 1234,
history: "hello\n",
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
});
expect(result.success).toBe(true);
});
});
describe("terminalEventSchema", () => {
it("accepts output events", () => {
const result = terminalEventSchema.safeParse({
type: "output",
threadId: "thread-1",
createdAt: new Date().toISOString(),
data: "line\n",
});
expect(result.success).toBe(true);
});
it("accepts exited events", () => {
const result = terminalEventSchema.safeParse({
type: "exited",
threadId: "thread-1",
createdAt: new Date().toISOString(),
exitCode: 0,
exitSignal: null,
});
expect(result.success).toBe(true);
});
});
+92 -12
View File
@@ -1,18 +1,98 @@
import { z } from "zod";
export const terminalCommandInputSchema = z.object({
command: z.string().trim().min(1).max(4000),
cwd: z.string().min(1).optional(),
timeoutMs: z.number().int().positive().max(120_000).optional(),
const terminalColsSchema = z.number().int().min(20).max(400);
const terminalRowsSchema = z.number().int().min(5).max(200);
export const terminalThreadInputSchema = z.object({
threadId: z.string().trim().min(1),
});
export const terminalCommandResultSchema = z.object({
stdout: z.string(),
stderr: z.string(),
code: z.number().nullable(),
signal: z.string().nullable(),
timedOut: z.boolean(),
export const terminalOpenInputSchema = terminalThreadInputSchema.extend({
cwd: z.string().trim().min(1),
cols: terminalColsSchema,
rows: terminalRowsSchema,
});
export type TerminalCommandInput = z.infer<typeof terminalCommandInputSchema>;
export type TerminalCommandResult = z.infer<typeof terminalCommandResultSchema>;
export const terminalWriteInputSchema = terminalThreadInputSchema.extend({
data: z.string().min(1).max(65_536),
});
export const terminalResizeInputSchema = terminalThreadInputSchema.extend({
cols: terminalColsSchema,
rows: terminalRowsSchema,
});
export const terminalCloseInputSchema = terminalThreadInputSchema.extend({
deleteHistory: z.boolean().optional(),
});
export const terminalSessionStatusSchema = z.enum([
"starting",
"running",
"exited",
"error",
]);
export const terminalSessionSnapshotSchema = z.object({
threadId: z.string().min(1),
cwd: z.string().min(1),
status: terminalSessionStatusSchema,
pid: z.number().int().positive().nullable(),
history: z.string(),
exitCode: z.number().int().nullable(),
exitSignal: z.number().int().nullable(),
updatedAt: z.string().datetime(),
});
const terminalEventBaseSchema = z.object({
threadId: z.string().min(1),
createdAt: z.string().datetime(),
});
export const terminalStartedEventSchema = terminalEventBaseSchema.extend({
type: z.literal("started"),
snapshot: terminalSessionSnapshotSchema,
});
export const terminalOutputEventSchema = terminalEventBaseSchema.extend({
type: z.literal("output"),
data: z.string(),
});
export const terminalExitedEventSchema = terminalEventBaseSchema.extend({
type: z.literal("exited"),
exitCode: z.number().int().nullable(),
exitSignal: z.number().int().nullable(),
});
export const terminalErrorEventSchema = terminalEventBaseSchema.extend({
type: z.literal("error"),
message: z.string().min(1),
});
export const terminalClearedEventSchema = terminalEventBaseSchema.extend({
type: z.literal("cleared"),
});
export const terminalRestartedEventSchema = terminalEventBaseSchema.extend({
type: z.literal("restarted"),
snapshot: terminalSessionSnapshotSchema,
});
export const terminalEventSchema = z.discriminatedUnion("type", [
terminalStartedEventSchema,
terminalOutputEventSchema,
terminalExitedEventSchema,
terminalErrorEventSchema,
terminalClearedEventSchema,
terminalRestartedEventSchema,
]);
export type TerminalThreadInput = z.input<typeof terminalThreadInputSchema>;
export type TerminalOpenInput = z.input<typeof terminalOpenInputSchema>;
export type TerminalWriteInput = z.input<typeof terminalWriteInputSchema>;
export type TerminalResizeInput = z.input<typeof terminalResizeInputSchema>;
export type TerminalCloseInput = z.input<typeof terminalCloseInputSchema>;
export type TerminalSessionStatus = z.infer<typeof terminalSessionStatusSchema>;
export type TerminalSessionSnapshot = z.infer<typeof terminalSessionSnapshotSchema>;
export type TerminalEvent = z.infer<typeof terminalEventSchema>;
+22
View File
@@ -11,9 +11,30 @@ export const WS_METHODS = {
providersStopSession: "providers.stopSession",
providersListSessions: "providers.listSessions",
// Project registry methods
projectsList: "projects.list",
projectsAdd: "projects.add",
projectsRemove: "projects.remove",
// Shell methods
shellOpenInEditor: "shell.openInEditor",
// Git methods
gitListBranches: "git.listBranches",
gitCreateWorktree: "git.createWorktree",
gitRemoveWorktree: "git.removeWorktree",
gitCreateBranch: "git.createBranch",
gitCheckout: "git.checkout",
gitInit: "git.init",
// Terminal methods
terminalOpen: "terminal.open",
terminalWrite: "terminal.write",
terminalResize: "terminal.resize",
terminalClear: "terminal.clear",
terminalRestart: "terminal.restart",
terminalClose: "terminal.close",
// Server meta
serverGetConfig: "server.getConfig",
} as const;
@@ -22,6 +43,7 @@ export const WS_METHODS = {
export const WS_CHANNELS = {
providerEvent: "providers.event",
terminalEvent: "terminal.event",
serverWelcome: "server.welcome",
} as const;
+9 -3
View File
@@ -4,15 +4,21 @@
"PORT",
"VITE_WS_URL",
"VITE_DEV_SERVER_URL",
"CODETHING_LOG_WS_EVENTS"
"T3CODE_LOG_WS_EVENTS",
"T3CODE_MODE",
"T3CODE_PORT",
"T3CODE_NO_BROWSER",
"T3CODE_STATE_DIR",
"T3CODE_AUTH_TOKEN",
"T3CODE_DESKTOP_WS_URL"
],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"]
"outputs": ["dist/**", "dist-electron/**"]
},
"dev": {
"dependsOn": ["@acme/contracts#build"],
"dependsOn": ["@t3tools/contracts#build"],
"cache": false,
"persistent": true
},
+11 -1
View File
@@ -1,3 +1,13 @@
import * as path from "node:path";
import { defineConfig } from "vitest/config";
export default defineConfig({});
export default defineConfig({
resolve: {
alias: [
{
find: /^@t3tools\/contracts$/,
replacement: path.resolve(import.meta.dirname, "./packages/contracts/src/index.ts"),
},
],
},
});