Compare commits

..
Author SHA1 Message Date
Julius Marminge cab54fe7f4 whoop 2026-02-12 18:36:05 -08:00
Julius Marminge 1b7abe5cd7 Move approval derivation and thread visit tracking into core session log
- Moved pending-approval extraction to `session-logic` and reused it in `Sidebar` status rendering
- Added `lastVisitedAt` threading persistence through schema, types, hydrate/serialize paths, and tests
- Updated sidebar thread pills for completed/approval states and pulsing working status
- Marked active thread visits and completion visibility timestamps on selection and `turn/completed`
- Co-authored-by: codex <[email protected]>
2026-02-12 16:49:49 -08:00
Julius Marminge 1dca7012b5 Merge pull request #15 from pingdotgg/images 2026-02-12 15:52:03 -08:00
Julius Marminge ea16f6fdd7 spark 2026-02-12 15:49:22 -08:00
Julius Marminge 73bc60ef8a simp 2026-02-12 15:46:34 -08:00
Julius Marminge 86e7bd000c Align Electron drag headers and sidebar branding spacing
- Update `ChatView` so Electron uses a fixed 52px drag titlebar, including empty-thread state.
- Make `DiffPanel` header use the same Electron drag-region sizing.
- Consolidate Sidebar drag-region into branding row and remove separate spacer div.
- Co-authored-by: codex <[email protected]>
2026-02-12 15:43:05 -08:00
Julius Marminge 1cad53dae4 Allow attachments field in ChatView 2026-02-12 15:37:30 -08:00
Julius Marminge 760f15f2f9 Expand sendTurn attachment handling 2026-02-12 15:33:33 -08:00
Julius Marminge 3cf58f80d1 Add image paste drag drop dialog 2026-02-12 15:22:03 -08:00
Julius Marminge 44f3b3cb7c Merge pull request #13 from pingdotgg/codex/add-github-commit-push-ui 2026-02-12 14:53:53 -08:00
Julius Marmingeandcodex dd920846b9 Show git step details only on failure
- Render `step.detail` only for failed step states
- Keep failed detail text styled in warning red tone

Co-authored-by: codex <[email protected]>
2026-02-12 14:47:51 -08:00
Julius Marmingeandcodex b7af14ad3f Rework chat header actions and GitActions styling
- Remove branch badge and terminal toggle from ChatView header
- Keep GitActionsControl in the header action area
- Adjust GitActionsControl button styles to emphasize completed action state

Co-authored-by: codex <[email protected]>
2026-02-12 14:44:51 -08:00
Julius Marminge 8f6cd244e7 Use gpt-5.3-codex-spark for git text generation
- Add `gpt-5.3-codex-spark` with medium reasoning effort to commit/PR generation calls
- Inject process runner into `CodexTextGenerator` and add tests for model selection and failure passthrough
- Update PR modal to use status/result PR URLs and keep a single Open PR action path
2026-02-12 14:42:15 -08:00
Julius Marminge 95c8463706 Remove redundant commit message hint from Git actions modal
- Remove the “Leave this empty…” helper text under the commit message field
- Keep AI-generated commit message behavior unchanged
2026-02-12 14:30:43 -08:00
Julius Marminge 5a0f5e9f5e Improve Git action modal state and PR link handling
- Add an `Open PR` button in the result footer and handle link-open errors
- Populate the commit message field with the generated subject when available
- Refine disabled/selected action option styling while git actions are running
2026-02-12 14:28:45 -08:00
Julius Marmingeandcodex c643de8ba7 Enable safe external PR link opening in desktop app
- add desktop IPC handler to validate and open http(s) URLs via Electron shell
- expose `shell.openExternal` in shared NativeApi contracts and web bridge
- route Git PR opening and native API reads through the new `useNativeApi` hook

Co-authored-by: codex <[email protected]>
2026-02-12 14:24:41 -08:00
Julius Marmingeandcodex 9accd1ffb7 Improve git action menu and modal workflow
- Split Git actions into context-aware Commit, Push, and PR menu items
- Add modal action selection with clearer availability and disabled-state guidance
- Migrate git status and immediate actions to React Query and add a custom GitHub icon

Co-authored-by: codex <[email protected]>
2026-02-12 14:12:45 -08:00
Julius Marminge 62cc55ab06 Extract Git actions UI into dedicated GitActionsControl component
- Move git menu, modal, and stacked action logic out of `ChatView`
- Render a new `GitActionsControl` wired with `api` and `gitCwd`
2026-02-12 12:54:36 -08:00
Julius Marmingeandcodex 36bc85f54d Add Git action modal with custom commit message support
- Add a Git action confirmation modal with live commit/push/PR progress states
- Accept optional `commitMessage` input and skip AI message generation when provided
- Expand server and contracts tests for custom commit message handling

Co-authored-by: codex <[email protected]>
2026-02-12 12:22:05 -08:00
Julius Marminge 3c939e8e69 Use Lucide icons for ChatView git action menu
- Replace custom inline SVGs with Lucide commit, push, and GitHub icons
- Keep git action behavior unchanged while applying minor style cleanup
2026-02-12 11:20:38 -08:00
Julius Marminge 6fc632f9a1 Harden git and terminal flows and surface open PR status
- include open PR metadata in git status with graceful `gh` failure handling
- centralize git command execution in `GitCoreService` via `runProcess` with truncation support
- add PTY spawn-helper permission fixes, shell fallback retries, and tests for new behavior
2026-02-12 11:15:11 -08:00
Julius Marmingeandcodex ae296e59a4 Merge origin/main into codex/add-github-commit-push-ui
Co-authored-by: codex <[email protected]>
2026-02-12 02:18:19 -08:00
Julius Marminge 36cdceb4bf Fix ChatView height scroll 2026-02-12 02:12:40 -08:00
Julius Marmingeandcodex 3bfda73dce Address PR review comments for terminal integration
Co-authored-by: codex <[email protected]>
2026-02-12 02:12:40 -08:00
Julius Marminge 0133d9582c Improve terminal resizing and perf 2026-02-12 02:12:40 -08:00
Julius Marminge e0df5d5b58 Update status bar actions state 2026-02-11 18:08:16 -08:00
Julius Marminge 3697765f4d Disable git actions without changes 2026-02-11 18:02:32 -08:00
Julius Marmingeandcodex 533dbdfbda Address PR review feedback for git actions
Co-authored-by: codex <[email protected]>
2026-02-11 17:56:16 -08:00
Julius Marminge 98eb87f5cd Extract git core interfaces 2026-02-11 17:40:23 -08:00
Julius Marmingeandcodex 1768d31669 Merge origin/main into codex/add-github-commit-push-ui
Co-authored-by: codex <[email protected]>
2026-02-11 17:21:25 -08:00
Julius Marminge 39390c0b9a Add stacked git actions flow 2026-02-11 16:34:22 -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
Theo Browne e7c4292d27 more ui cleanup 2026-02-09 17:52:28 -08:00
141 changed files with 12524 additions and 17294 deletions

No files matched your search

+8 -3
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
@@ -41,5 +41,10 @@ jobs:
- name: Test
run: bun run test
- name: Smoke Test (t3 runtime)
run: bun run --cwd apps/t3 build && bun run smoke-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
+1
View File
@@ -3,6 +3,7 @@
"ignorePatterns": [
".plans",
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": ["dist", "node_modules", "bun.lock", "*.tsbuildinfo"],
"ignorePatterns": ["dist", "dist-electron", "node_modules", "bun.lock", "*.tsbuildinfo"],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"categories": {
"correctness": "warn",
+3 -3
View File
@@ -5,7 +5,7 @@ Move model alias/default normalization into `packages/contracts` so desktop and
## Motivation
- Removes duplicated logic between:
- `packages/runtime-core/src/codexAppServerManager.ts`
- `apps/desktop/src/codexAppServerManager.ts`
- `apps/renderer/src/model-logic.ts`
- Prevents behavior drift when model aliases/defaults are updated.
@@ -22,7 +22,7 @@ Move model alias/default normalization into `packages/contracts` so desktop and
- `resolveModelSlug`
- `DEFAULT_MODEL`
2. Export model utilities from `packages/contracts/src/index.ts`.
3. Update `packages/runtime-core/src/codexAppServerManager.ts` to replace local alias map/helper.
3. Update `apps/desktop/src/codexAppServerManager.ts` to replace local alias map/helper.
4. Update `apps/renderer/src/model-logic.ts` to wrap or re-export shared functions.
5. Update tests:
- Move/duplicate normalization tests to contracts.
@@ -38,5 +38,5 @@ Move model alias/default normalization into `packages/contracts` so desktop and
- Manual check that model selection and session start still send expected model slug.
## Done Criteria
- No duplicated alias/default map in runtime-core and renderer.
- No duplicated alias/default map in desktop and renderer.
- Shared model utilities are contract-tested.
+13 -13
View File
@@ -1,37 +1,37 @@
# Plan: Strengthen Typed WS RPC Boundaries in Runtime Server
# Plan: Strengthen Typed IPC Boundaries in Main Process
## Summary
Replace loose payload casting in runtime RPC handlers with strict schema parsing and typed helper wrappers.
Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers.
## Motivation
- `apps/t3/src/runtimeApiServer.ts` should avoid payload casts and parse all unknown input at the RPC boundary.
- `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`.
- Casts can hide contract breakages until runtime.
## Scope
- Runtime WebSocket RPC registration and method dispatch.
- Optional shared helper for method-level parse/dispatch registration.
- Desktop main process IPC registration.
- Optional shared helper for handler registration.
## Proposed Changes
1. Add RPC helper utility (e.g. `apps/t3/src/rpcHelpers.ts`) to:
1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to:
- Parse payload(s) with Zod schemas
- Standardize typed handler signatures
2. Refactor provider RPC handlers in `apps/t3/src/runtimeApiServer.ts` to use:
2. Refactor provider IPC handlers in `apps/desktop/src/main.ts` to use:
- `providerSessionStartInputSchema.parse`
- `providerSendTurnInputSchema.parse`
- `providerInterruptTurnInputSchema.parse`
- `providerStopSessionInputSchema.parse`
3. Apply same pattern to app/todo/agent/terminal/shell handlers where possible.
4. Add tests for parsing failure paths (invalid payloads).
3. Apply same pattern to agent/terminal handlers where possible.
4. Add tests for handler parsing failure paths (invalid payloads).
## Risks
- Refactor can subtly change RPC error shape/messages.
- Refactor can subtly change IPC error shape/messages.
- Helper abstraction should stay simple and not obscure control flow.
## Validation
- `bun run test`
- `bun run typecheck`
- Manual invalid payload check from websocket client/devtools to confirm fast failure.
- Manual invalid payload check from renderer/devtools to confirm fast failure.
## Done Criteria
- No runtime handler uses `payload as Parameters<...>`.
- All websocket RPC entrypoints parse unknown payloads at boundary.
- No provider handler uses `payload as Parameters<...>`.
- All IPC entrypoints parse unknown payloads at boundary.
+2 -2
View File
@@ -4,7 +4,7 @@
Split `CodexAppServerManager` into smaller modules with clear responsibilities.
## Motivation
- `packages/runtime-core/src/codexAppServerManager.ts` is large and mixes:
- `apps/desktop/src/codexAppServerManager.ts` is large and mixes:
- Process lifecycle
- JSON-RPC parsing/routing
- Session state transitions
@@ -12,7 +12,7 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- This increases regression risk and slows changes.
## Scope
- Runtime-core provider internals only.
- Desktop provider internals only.
- Keep external behavior/API stable.
## Proposed Changes
+4 -4
View File
@@ -4,18 +4,18 @@
Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely.
## Motivation
- `packages/runtime-core/src/providerManager.ts` opens a write stream in constructor.
- `apps/desktop/src/providerManager.ts` opens a write stream in constructor.
- Stream lifecycle is not explicit on shutdown.
## Scope
- Runtime-core provider logging behavior.
- Runtime server shutdown integration.
- Desktop provider logging behavior.
- App shutdown integration.
## Proposed Changes
1. Add explicit `dispose()` on `ProviderManager`:
- Remove event listeners
- End/close log stream
2. Call `providerManager.dispose()` from app shutdown path in `apps/t3/src/runtimeApiServer.ts` close flow.
2. Call `providerManager.dispose()` from app shutdown path in `apps/desktop/src/main.ts`.
3. Optional: change log format to JSON lines with stable fields.
4. Optional: per-session log files under `.logs/providers/`.
@@ -4,11 +4,11 @@
Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes.
## Motivation
- `packages/runtime-core/src/processManager.ts` maintains parallel maps and branch-heavy logic.
- `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic.
- New execution backends/providers will multiply complexity.
## Scope
- Runtime-core process execution internals.
- Desktop process execution internals.
- Preserve public `ProcessManager` API.
## Proposed Changes
@@ -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
+10 -12
View File
@@ -1,8 +1,8 @@
# AGENTS.md
# CLAUDE.md
## Project Snapshot
CodeThing is a minimal 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.
@@ -16,22 +16,20 @@ If a tradeoff is required, choose correctness and robustness over short-term con
## Package Roles
- `apps/t3`: Node CLI/runtime. Owns WebSocket server lifecycle, browser launch, and RPC routing.
- `apps/renderer`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state.
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket payloads, and model/session types.
- `packages/runtime-core`: Shared Node runtime services (`ProcessManager`, `TodoStore`, `ProviderManager`, `CodexAppServerManager`) used by `apps/t3`.
- Legacy desktop runtime wrapper package has been removed; `runtime-core` is the canonical runtime service source.
- Legacy desktop runtime wrapper package has been removed; `runtime-core` is the canonical runtime service source.
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## Codex App Server (Important)
CodeThing is currently Codex-first. The `t3` runtime starts `codex app-server` (JSON-RPC over stdio) per provider session, then streams structured events into the renderer through the provider APIs.
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 `packages/runtime-core/src/codexAppServerManager.ts`.
- Provider dispatch and thread event logging are coordinated in `packages/runtime-core/src/providerManager.ts`.
- Renderer consumes provider event streams via `nativeApi.providers.onEvent`.
- Session startup/resume and turn lifecycle are brokered in `apps/server/src/codexAppServerManager.ts`.
- Provider dispatch and thread event logging are coordinated in `apps/server/src/providerManager.ts`.
- WebSocket server routes NativeApi methods in `apps/server/src/wsServer.ts`.
- Web app consumes provider event streams via WebSocket push on channel `providers.event`.
Docs:
+66 -128
View File
@@ -1,156 +1,94 @@
# CodeThing (`t3`: Node + WebSocket + Browser)
# T3 Code
CodeThing now runs as a local Node.js runtime that serves a browser UI and exposes a local WebSocket API.
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
Current implementation is:
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.
1. Codex-first: connects to `codex app-server` and streams turn/item events.
2. Provider-ready: renderer speaks a provider abstraction so Claude Code can plug in later.
3. Typed end-to-end: contracts validate payloads across the WebSocket boundary.
## Architecture
## Quickstart
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```bash
npx t3
```
On launch, `t3`:
1. starts a local WebSocket runtime (`127.0.0.1`),
2. serves the web UI in your browser,
3. auto-connects to your current working directory as the default project.
CLI flags:
- `--no-open[=bool]` — disable browser auto-open (supports `true/false`, `1/0`, `yes/no`, `on/off` in equals form).
- `-o, --open[=bool]` — force browser auto-open (supports `true/false`, `1/0`, `yes/no`, `on/off` in equals form; overrides `T3_NO_OPEN`).
- `--backend-port <port>` — set WebSocket runtime port.
- `--web-port <port>` — set web UI port.
- `--cwd <path>` — choose launch project directory (defaults to current directory).
- `<path>` — shorthand positional argument equivalent to `--cwd <path>`.
- `-- <path>` — treat following argument as path even if it starts with `-`.
- `--version` — print CLI version.
- `--help` — print CLI usage.
`--cwd` (or positional path) must be a non-empty value pointing to an existing directory; startup fails fast with a clear error otherwise.
Port values must be decimal integers in the range `1..65535`.
If default ports are busy, `t3` will automatically retry with the next available port pair unless ports are explicitly pinned via CLI flags or environment variables.
Optional environment variables:
- `T3_NO_OPEN=1` — start runtime without auto-opening a browser window (parses `true/false`, `1/0`, `yes/no`, `on/off`).
- `T3_BACKEND_PORT` — override local WebSocket runtime port (default `4317`).
- `T3_WEB_PORT` — override local web UI port (default `4318`).
Runtime command semantics:
- `terminal.run` executes in the launch directory when `cwd` is omitted.
- Relative `cwd` values for `terminal.run` and `shell.openInEditor` resolve from the launch directory.
- `terminal.run` and `shell.openInEditor` reject empty/whitespace, missing, or non-directory cwd targets with structured request errors.
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
## Workspace layout
- `/apps/t3`: CLI launcher + local WebSocket runtime server.
- `/apps/renderer`: React + Vite UI for session control, conversation, and protocol event stream.
- `/packages/contracts`: shared Zod schemas + TypeScript types for WS protocol, provider events, and API contracts.
- `/packages/runtime-core`: shared Node runtime services (`ProcessManager`, `TodoStore`, `ProviderManager`, `CodexAppServerManager`) consumed by `apps/t3`.
- Legacy desktop runtime wrapper package has been removed; `runtime-core` is now the sole source of runtime service implementations.
- `/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.
- Note: test suites use an in-process fake `codex app-server` shim, so CI/local tests do not require the real Codex CLI.
- 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.
## Runtime boundary model
## Quick start
- `t3` starts a localhost-only WebSocket server.
- Launch URLs include an ephemeral WebSocket token so only the opened browser session can attach.
- Connections missing the token (or using a wrong token) are rejected by the runtime.
- Connections with duplicate token query parameters are also rejected (even when duplicate values match) to avoid ambiguous auth parsing.
- Runtime auth token lookup is strict on the lowercase `token` query key; alternate key casing is rejected.
- Connections with unexpected query parameters are rejected (auth mode requires only `token`; no-auth mode allows no query params).
- WebSocket control connections are accepted only on the root runtime path (`/`) to keep the API surface narrow.
- Unauthorized websocket attempts close with code `4001` and reason `unauthorized`.
- Browser renderer talks through a typed `NativeApi` adapter over that WebSocket.
- Runtime currently enforces a single active browser client (new client replaces old one).
- When replaced by a newer connection, the previous active websocket is closed with code `4000`.
- Replacement closes use reason string `replaced-by-new-client` for deterministic client handling.
- Renderer websocket connection errors now preserve close metadata (`code`/`reason`) to improve reconnect diagnostics.
- Renderer normalizes close metadata before diagnostics (e.g. trims close reasons and ignores malformed close codes) for cleaner error messages.
- Renderer decodes websocket message payloads from strings, `ArrayBuffer`, `ArrayBufferView` (e.g. `Uint8Array`/`DataView`), and `Blob`.
- Renderer validates provider/agent event payload shapes before dispatch, ignoring malformed event payloads to keep client state stable.
- Renderer validates critical RPC success payload shapes (`app.health`, `app.bootstrap`, `providers.listSessions`, `dialogs.pickFolder`, plus terminal/todo/provider/agent control flows) and fails fast on malformed responses.
- In-flight renderer requests now surface unauthorized/replacement disconnect causes explicitly.
- Renderer also fails in-flight requests immediately on websocket `error` events (without waiting for close) for faster feedback.
- After reconnect, renderer ignores stale events from prior sockets (including provider and agent streams) to avoid cross-connection state corruption.
- Initial websocket connect failures now include detailed diagnostics from socket/open and constructor failures (including nested/string/cause-chain payload messages, with bounded-depth fallback for malformed/cyclic payloads).
- Subsequent requests automatically reconnect after close/error disconnects, including idle (no pending request) error scenarios.
- Renderer now proactively resets the websocket after request send failures, rejects any in-flight requests, and reconnects cleanly on later requests.
- Send-failure request errors now include non-Error payload details when available (for clearer diagnostics).
- Runtime validates request payloads with shared Zod contracts.
- Websocket RPC method names are centralized in shared contracts (`WS_NATIVE_API_METHODS`), and runtime dispatch validates method strings against that shared list.
- Runtime tests now assert that every declared websocket method is wired through the server dispatch path (preventing contract/runtime drift).
- Runtime and renderer both validate critical success payloads with shared contracts to prevent malformed envelope data from entering app state.
- Core transport schemas (provider/agent/todo/terminal/app payloads) are strict objects, so unexpected fields are rejected at the contract boundary.
- Runtime successful responses always include `result` (using `null` for void methods) to keep websocket envelopes schema-safe.
- Websocket event envelopes are channel-typed (`provider:event`, `agent:output`, `agent:exit`) and validated against shared payload schemas.
- Websocket protocol envelopes are strict (unexpected top-level fields are rejected) to keep RPC/event parsing deterministic.
- Websocket request envelope guards also cap request id/method lengths (currently 256 chars each); over-limit requests are treated as malformed and ignored.
- Runtime error envelopes are bounded (`code`/`message` max lengths) and oversized error text is normalized before sending to avoid protocol-invalid responses.
- Blank/whitespace-only websocket ids, methods, and error fields are rejected at schema boundaries.
- Codex execution sandbox policy (`read-only`, `workspace-write`, `danger-full-access`) is still selected per session startup options.
- Static HTML responses are served with `Cache-Control: no-store`; built `/assets/*` files are served with long-lived immutable cache headers.
- Static file success responses include `Accept-Ranges: bytes`, `Vary: Range`, deterministic `ETag` and `Last-Modified` validators, plus hardened browser headers (`X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, `Cross-Origin-Resource-Policy`, `Cross-Origin-Opener-Policy`).
- Static files support single-range byte requests (`Range: bytes=...`) with standards-compliant `206` / `416` behavior.
- Static range parsing tolerates optional separator whitespace (e.g. `Range: bytes = 0 - 1023`).
- Oversized suffix ranges are normalized to full-file spans (for example `bytes=-999999` on small assets).
- Static non-range requests support `If-None-Match` and `If-Modified-Since` conditional caching via `304 Not Modified`.
- Static range requests support `If-Range` semantics (matched validator keeps `206`; mismatched validator falls back to full `200` response).
- `If-None-Match` / `If-Modified-Since` preconditions are evaluated before range handling, so satisfied validators return `304` even when a `Range` header is present.
- Static precondition headers `If-Match` and `If-Unmodified-Since` are enforced with `412 Precondition Failed` semantics.
- Failed `If-Match` checks take precedence over cache validators (e.g. matching `If-None-Match` still results in `412` if `If-Match` fails).
- Failed `If-Unmodified-Since` checks also return `412` before cache-based `304` handling.
- Wildcard validators are supported where applicable (`If-None-Match: *`, `If-Match: *`).
- Strong/weak validator semantics follow HTTP rules: weak ETags participate in `If-None-Match` weak comparison, but are rejected for strong-only checks (`If-Match`, `If-Range`).
- `412` static precondition responses include validator headers (`ETag`, `Last-Modified`) and range capability metadata (`Accept-Ranges`, `Vary: Range`).
- `416` unsatisfiable-range responses include both range metadata and validators (`Content-Range`, `Accept-Ranges`, `Vary: Range`, `ETag`, `Last-Modified`).
```bash
# Development (with hot reload)
bun run dev
## Runtime modes
# Desktop development
bun run dev:desktop
CodeThing has a global runtime mode switch in the sidebar:
# Production
bun run build
bun run start
- `Full access` (default): starts new sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- `Approval required`: starts new sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
Mode changes apply across all threads. Existing live sessions are restarted so old and new threads use the selected mode.
# Or from any project directory after publishing:
npx t3
```
## Scripts
- `bun run dev`: builds contracts, starts `t3` runtime, opens browser UI.
- `bun run build`: builds contracts, renderer static assets, and `t3` CLI bundle.
- `bun run typecheck`: strict TypeScript checks for all packages.
- `bun run test`: runs workspace tests.
- `bun run smoke-test`: runs end-to-end CLI/WebSocket smoke coverage (against the fake Codex app-server shim).
- `bun run --cwd apps/t3 dev`: run the CLI directly in dev mode.
- `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
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 depends on `nativeApi.providers.*`:
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
1. `startSession`
2. `sendTurn`
3. `interruptTurn`
4. `respondToRequest`
5. `stopSession`
6. `listSessions`
7. `onEvent`
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for streaming provider events
Codex is the only implemented provider right now. `claudeCode` is reserved in contracts/UI but currently returns a not-implemented runtime error.
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
Runtime app utilities exposed via `nativeApi.app.*`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`, `providers.listSessions`
- `shell.openInEditor`, `server.getConfig`
1. `bootstrap`
2. `health`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
## CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
+5 -3
View File
@@ -7,6 +7,8 @@
- [ ] Selecting folder should instantly create project
- [ ] New projects should go on top
- [ ] Projects should be sorted by latest thread update
- [ ] "Response" bar should ONLY appear on work completed
- [ ] "Response" bar should ONLY appear above the FINAL message in a series
- [ ] 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)
- [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.
}
}
+262
View File
@@ -0,0 +1,262 @@
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, shell } from "electron";
import { fixPath } from "./fixPath";
fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
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),
});
});
});
ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
if (typeof rawUrl !== "string" || rawUrl.length === 0) {
return false;
}
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return false;
}
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
return false;
}
try {
await shell.openExternal(parsedUrl.toString());
return true;
} catch {
return false;
}
});
}
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();
}
});
+14
View File
@@ -0,0 +1,14 @@
import { contextBridge, ipcRenderer } from "electron";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
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>,
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
});
+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>
-140
View File
@@ -1,140 +0,0 @@
import { useEffect, useRef } from "react";
import ChatView from "./components/ChatView";
import DiffPanel from "./components/DiffPanel";
import Sidebar from "./components/Sidebar";
import { readNativeApi } from "./session-logic";
import { StoreProvider, useStore } from "./store";
function EventRouter() {
const api = readNativeApi();
const { dispatch } = useStore();
const activeAssistantItemRef = useRef<string | null>(null);
useEffect(() => {
if (!api) return;
return api.providers.onEvent((event) => {
dispatch({
type: "APPLY_EVENT",
event,
activeAssistantItemRef,
});
});
}, [api, dispatch]);
return null;
}
function BootstrapRouter() {
const api = readNativeApi();
const { dispatch } = useStore();
useEffect(() => {
if (!api) return;
let cancelled = false;
void api.app
.bootstrap()
.then((bootstrap) => {
if (cancelled) return;
dispatch({
type: "BOOTSTRAP_FROM_SERVER",
bootstrap,
});
})
.catch((error) => {
if (cancelled) return;
dispatch({
type: "SET_RUNTIME_ERROR",
error:
error instanceof Error
? error.message
: "Could not connect to the local t3 runtime.",
});
});
return () => {
cancelled = true;
};
}, [api, dispatch]);
return null;
}
function RuntimeHealthRouter() {
const api = readNativeApi();
const { dispatch } = useStore();
useEffect(() => {
if (!api) return;
let cancelled = false;
const checkHealth = async () => {
try {
await api.app.health();
if (cancelled) return;
dispatch({ type: "SET_RUNTIME_ERROR", error: null });
} catch (error) {
if (cancelled) return;
dispatch({
type: "SET_RUNTIME_ERROR",
error:
error instanceof Error
? error.message
: "Could not connect to the local t3 runtime.",
});
}
};
void checkHealth();
const interval = window.setInterval(() => {
void checkHealth();
}, 8_000);
return () => {
cancelled = true;
window.clearInterval(interval);
};
}, [api, dispatch]);
return null;
}
function Layout() {
const api = readNativeApi();
const { state } = useStore();
if (!api) {
return (
<div className="flex h-screen flex-col bg-background text-foreground">
<div className="drag-region h-[52px] shrink-0" />
<div className="flex flex-1 items-center justify-center">
<p className="text-sm text-muted-foreground">Local t3 runtime unavailable.</p>
</div>
</div>
);
}
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<BootstrapRouter />
<RuntimeHealthRouter />
<EventRouter />
{state.runtimeError && state.projects.length === 0 && (
<div className="pointer-events-none fixed right-4 top-4 z-50 max-w-[440px] rounded-lg border border-rose-400/30 bg-rose-500/10 px-3 py-2 text-xs text-rose-100">
Runtime connection failed: {state.runtimeError}
</div>
)}
<Sidebar />
<ChatView />
{state.diffOpen && <DiffPanel />}
</div>
);
}
export default function App() {
return (
<StoreProvider>
<Layout />
</StoreProvider>
);
}
-181
View File
@@ -1,181 +0,0 @@
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import { describe, expect, it } from "vitest";
import { type AppState, reducer } from "./store";
import type { Thread } from "./types";
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
return {
sessionId: "sess-1",
provider: "codex",
status: "ready",
createdAt: "2026-02-09T00:00:00.000Z",
updatedAt: "2026-02-09T00:00:00.000Z",
...overrides,
};
}
function makeEvent(overrides: Partial<ProviderEvent> = {}): ProviderEvent {
return {
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-09T00:00:01.000Z",
method: "thread/started",
...overrides,
};
}
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: "thread-local-1",
codexThreadId: null,
projectId: "project-1",
title: "Thread",
model: "gpt-5.3-codex",
session: makeSession(),
messages: [],
events: [],
error: null,
createdAt: "2026-02-09T00:00:00.000Z",
...overrides,
};
}
function makeState(thread: Thread): AppState {
return {
projects: [
{
id: "project-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [thread],
activeThreadId: thread.id,
runtimeMode: "full-access",
diffOpen: false,
runtimeError: null,
};
}
describe("store reducer thread continuity", () => {
it("bootstraps project and active thread from runtime response", () => {
const state: AppState = {
projects: [],
threads: [],
activeThreadId: null,
runtimeMode: "full-access",
diffOpen: false,
runtimeError: null,
};
const session = makeSession({
sessionId: "sess-bootstrap",
threadId: "thr-bootstrap",
});
const next = reducer(state, {
type: "BOOTSTRAP_FROM_SERVER",
bootstrap: {
launchCwd: "/workspace",
projectName: "workspace",
provider: "codex",
model: "gpt-5.3-codex",
session,
},
});
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.cwd).toBe("/workspace");
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.session?.sessionId).toBe("sess-bootstrap");
expect(next.activeThreadId).toBe(next.threads[0]?.id ?? null);
});
it("surfaces bootstrap errors on the active thread", () => {
const state: AppState = {
projects: [],
threads: [],
activeThreadId: null,
runtimeMode: "full-access",
diffOpen: false,
runtimeError: null,
};
const next = reducer(state, {
type: "BOOTSTRAP_FROM_SERVER",
bootstrap: {
launchCwd: "/workspace",
projectName: "workspace",
provider: "codex",
model: "gpt-5.3-codex",
session: makeSession({
sessionId: "sess-bootstrap-error",
status: "error",
}),
bootstrapError: "Timed out waiting for initialize.",
},
});
expect(next.threads[0]?.error).toBe("Timed out waiting for initialize.");
});
it("stores runtime connection errors separately from thread errors", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SET_RUNTIME_ERROR",
error: "Connection refused",
});
expect(next.runtimeError).toBe("Connection refused");
expect(next.threads[0]?.error).toBeNull();
});
it("stores codexThreadId from UPDATE_SESSION", () => {
const state = makeState(
makeThread({
session: null,
}),
);
const next = reducer(state, {
type: "UPDATE_SESSION",
threadId: "thread-local-1",
session: makeSession({ threadId: "thr_123" }),
});
expect(next.threads[0]?.codexThreadId).toBe("thr_123");
});
it("backfills codexThreadId from routed provider events", () => {
const state = makeState(makeThread({ codexThreadId: null }));
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "thread/started",
payload: { thread: { id: "thr_backfilled" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.codexThreadId).toBe("thr_backfilled");
});
it("surfaces thread id mismatches without overwriting stored identity", () => {
const state = makeState(makeThread({ codexThreadId: "thr_expected" }));
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "turn/started",
threadId: "thr_unexpected",
payload: { turn: { id: "turn-1" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.codexThreadId).toBe("thr_expected");
expect(next.threads[0]?.error).toContain("Thread identity mismatch");
});
});
-9
View File
@@ -1,9 +0,0 @@
/// <reference types="vite/client" />
import type { NativeApi } from "@acme/contracts";
declare global {
interface Window {
nativeApi?: NativeApi;
}
}
File diff suppressed because it is too large. Load diff
-525
View File
@@ -1,525 +0,0 @@
import type {
AgentExit,
NativeApi,
OutputChunk,
ProviderEvent,
WsNativeApiMethod,
WsClientMessage,
WsEventMessage,
WsResponseMessage,
} from "@acme/contracts";
import {
WS_CLOSE_CODES,
WS_CLOSE_REASONS,
WS_EVENT_CHANNELS,
agentSessionIdSchema,
appBootstrapResultSchema,
appHealthResultSchema,
dialogsPickFolderResultSchema,
providerSessionListSchema,
providerSessionSchema,
providerTurnStartResultSchema,
terminalCommandResultSchema,
todoListSchema,
wsServerMessageSchema,
} from "@acme/contracts";
type PendingRequest = {
resolve: (value: unknown) => void;
reject: (error: Error) => void;
timeout: ReturnType<typeof setTimeout>;
};
type SubscriptionSet<TValue> = Set<(value: TValue) => void>;
type SafeParseResult<TValue> = { success: true; data: TValue } | { success: false };
type SchemaLike<TValue> = {
safeParse: (value: unknown) => SafeParseResult<TValue>;
};
const REQUEST_TIMEOUT_MS = 30_000;
const MAX_NESTED_ERROR_EXTRACTION_DEPTH = 8;
const textDecoder = new TextDecoder();
function closeDetailsFromEvent(event: unknown) {
const code = (event as { code?: unknown } | null)?.code;
const reason = (event as { reason?: unknown } | null)?.reason;
return {
code: normalizeCloseCode(code),
reason: normalizeNonEmptyString(reason),
};
}
function runtimeConnectErrorFromClose(event: unknown) {
const { code, reason } = closeDetailsFromEvent(event);
if (code === WS_CLOSE_CODES.unauthorized || reason === WS_CLOSE_REASONS.unauthorized) {
return new Error("Failed to connect to local t3 runtime: unauthorized websocket connection.");
}
if (
code === WS_CLOSE_CODES.replacedByNewClient ||
reason === WS_CLOSE_REASONS.replacedByNewClient
) {
return new Error(
"Failed to connect to local t3 runtime: replaced by a newer websocket client.",
);
}
if (code === null && (!reason || reason.length === 0)) {
return new Error("Failed to connect to local t3 runtime.");
}
if (code === null) {
return new Error(`Failed to connect to local t3 runtime (close reason: ${reason}).`);
}
if (!reason || reason.length === 0) {
return new Error(`Failed to connect to local t3 runtime (close code ${code}).`);
}
return new Error(`Failed to connect to local t3 runtime (close code ${code}: ${reason}).`);
}
function requestDisconnectError(id: string, event: unknown) {
const { code, reason } = closeDetailsFromEvent(event);
if (code === WS_CLOSE_CODES.unauthorized || reason === WS_CLOSE_REASONS.unauthorized) {
return new Error(`Request ${id} failed: websocket disconnected (unauthorized).`);
}
if (
code === WS_CLOSE_CODES.replacedByNewClient ||
reason === WS_CLOSE_REASONS.replacedByNewClient
) {
return new Error(`Request ${id} failed: websocket disconnected (replaced-by-new-client).`);
}
if (code === null && (!reason || reason.length === 0)) {
return new Error(`Request ${id} failed: websocket disconnected.`);
}
if (code === null) {
return new Error(`Request ${id} failed: websocket disconnected (reason: ${reason}).`);
}
if (!reason || reason.length === 0) {
return new Error(`Request ${id} failed: websocket disconnected (code ${code}).`);
}
return new Error(`Request ${id} failed: websocket disconnected (code ${code}: ${reason}).`);
}
function requestSocketError(id: string, event: unknown) {
const message = socketErrorMessage(event);
if (typeof message === "string" && message.length > 0) {
return new Error(`Request ${id} failed: websocket errored (${message}).`);
}
return new Error(`Request ${id} failed: websocket errored.`);
}
function runtimeConnectErrorFromSocketError(event: unknown) {
const message = socketErrorMessage(event);
if (typeof message === "string" && message.length > 0) {
return new Error(`Failed to connect to local t3 runtime: websocket error (${message}).`);
}
return new Error("Failed to connect to local t3 runtime.");
}
function runtimeConnectErrorFromConstructionError(error: unknown) {
const message = messageFromUnknown(error);
if (message) {
return new Error(`Failed to connect to local t3 runtime: websocket error (${message}).`);
}
return new Error("Failed to connect to local t3 runtime.");
}
function socketErrorMessage(event: unknown) {
return messageFromUnknown(event);
}
function messageFromUnknown(value: unknown, depth = 0): string | null {
if (depth > MAX_NESTED_ERROR_EXTRACTION_DEPTH) {
return null;
}
const direct = normalizeNonEmptyString(value);
if (direct) {
return direct;
}
const message = normalizeNonEmptyString((value as { message?: unknown } | null)?.message);
if (message) {
return message;
}
const nestedErrorMessage = messageFromUnknown(
(value as { error?: unknown } | null)?.error,
depth + 1,
);
if (nestedErrorMessage) {
return nestedErrorMessage;
}
return messageFromUnknown((value as { cause?: unknown } | null)?.cause, depth + 1);
}
function normalizeNonEmptyString(value: unknown) {
if (typeof value !== "string") {
return null;
}
const normalized = value.trim();
if (normalized.length === 0) {
return null;
}
return normalized;
}
function normalizeCloseCode(value: unknown) {
if (typeof value !== "number" || !Number.isInteger(value)) {
return null;
}
return value;
}
class WsNativeApiClient {
private socket: WebSocket | null = null;
private connectPromise: Promise<WebSocket> | null = null;
private nextRequestId = 1;
private pending = new Map<string, PendingRequest>();
private providerEventListeners: SubscriptionSet<ProviderEvent> = new Set();
private agentOutputListeners: SubscriptionSet<OutputChunk> = new Set();
private agentExitListeners: SubscriptionSet<AgentExit> = new Set();
constructor(private readonly wsUrl: string) {}
private rejectPendingRequests(errorForRequest: (id: string) => Error) {
for (const [id, pending] of this.pending.entries()) {
clearTimeout(pending.timeout);
pending.reject(errorForRequest(id));
}
this.pending.clear();
}
private connect() {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
return Promise.resolve(this.socket);
}
if (this.connectPromise) {
return this.connectPromise;
}
const connectAttempt = new Promise<WebSocket>((resolve, reject) => {
let socket: WebSocket;
try {
socket = new WebSocket(this.wsUrl);
} catch (error) {
reject(runtimeConnectErrorFromConstructionError(error));
return;
}
socket.binaryType = "arraybuffer";
this.socket = socket;
let hasOpened = false;
let connectionSettled = false;
const rejectConnection = (error?: Error) => {
if (connectionSettled) {
return;
}
connectionSettled = true;
this.connectPromise = null;
reject(error ?? new Error("Failed to connect to local t3 runtime."));
};
const resolveConnection = () => {
if (connectionSettled) {
return;
}
connectionSettled = true;
this.connectPromise = null;
resolve(socket);
};
socket.addEventListener("open", () => {
hasOpened = true;
resolveConnection();
});
socket.addEventListener("error", (event) => {
if (this.socket !== socket) {
if (!hasOpened) {
rejectConnection(runtimeConnectErrorFromSocketError(event));
}
return;
}
if (!hasOpened) {
rejectConnection(runtimeConnectErrorFromSocketError(event));
return;
}
this.socket = null;
this.rejectPendingRequests((id) => requestSocketError(id, event));
try {
socket.close();
} catch {
// best-effort close after error
}
});
socket.addEventListener("message", (event) => {
if (this.socket !== socket) {
return;
}
void this.handleMessage(event.data);
});
socket.addEventListener("close", (event) => {
if (this.socket !== socket) {
if (!hasOpened) {
rejectConnection(runtimeConnectErrorFromClose(event));
}
return;
}
this.socket = null;
if (!hasOpened) {
rejectConnection(runtimeConnectErrorFromClose(event));
return;
}
this.rejectPendingRequests((id) => requestDisconnectError(id, event));
});
});
this.connectPromise = connectAttempt;
connectAttempt.catch(() => {
if (this.connectPromise === connectAttempt) {
this.connectPromise = null;
}
});
return connectAttempt;
}
private async request(method: WsNativeApiMethod, params?: unknown) {
const socket = await this.connect();
const id = String(this.nextRequestId);
this.nextRequestId += 1;
const requestMessage: WsClientMessage = {
type: "request",
id,
method,
params,
};
const requestPromise = new Promise<unknown>((resolve, reject) => {
const timeout = setTimeout(() => {
this.pending.delete(id);
reject(new Error(`Request timed out for method '${method}'.`));
}, REQUEST_TIMEOUT_MS);
this.pending.set(id, { resolve, reject, timeout });
});
try {
socket.send(JSON.stringify(requestMessage));
} catch (error) {
const pending = this.pending.get(id);
if (pending) {
clearTimeout(pending.timeout);
this.pending.delete(id);
const sendErrorMessage = messageFromUnknown(error);
pending.reject(
new Error(
`Failed to send runtime request '${method}': ${sendErrorMessage ?? "unknown websocket failure"}`,
),
);
}
this.rejectPendingRequests((requestId) => requestSocketError(requestId, error));
if (this.socket === socket) {
this.socket = null;
}
try {
socket.close();
} catch {
// best-effort close after send failure
}
}
return requestPromise;
}
private async requestParsed<TValue>(
method: WsNativeApiMethod,
schema: SchemaLike<TValue>,
params?: unknown,
): Promise<TValue> {
const value = await this.request(method, params);
const parsed = schema.safeParse(value);
if (!parsed.success) {
throw new Error(`Runtime method '${method}' returned invalid response payload.`);
}
return parsed.data;
}
private async requestNullResult(method: WsNativeApiMethod, params?: unknown): Promise<void> {
const value = await this.request(method, params);
if (value !== null) {
throw new Error(`Runtime method '${method}' returned invalid response payload.`);
}
}
private handleResponse(message: WsResponseMessage) {
const pending = this.pending.get(message.id);
if (!pending) {
return;
}
this.pending.delete(message.id);
clearTimeout(pending.timeout);
if (message.ok) {
pending.resolve(message.result);
return;
}
pending.reject(new Error(message.error?.message ?? "Unknown runtime request failure."));
}
private handleEvent(message: WsEventMessage) {
if (message.channel === WS_EVENT_CHANNELS.providerEvent) {
for (const listener of this.providerEventListeners) {
listener(message.payload as ProviderEvent);
}
return;
}
if (message.channel === WS_EVENT_CHANNELS.agentOutput) {
for (const listener of this.agentOutputListeners) {
listener(message.payload as OutputChunk);
}
return;
}
if (message.channel === WS_EVENT_CHANNELS.agentExit) {
for (const listener of this.agentExitListeners) {
listener(message.payload as AgentExit);
}
}
}
private async decodeIncomingMessage(raw: unknown): Promise<string | null> {
if (typeof raw === "string") {
return raw;
}
if (ArrayBuffer.isView(raw)) {
return textDecoder.decode(raw);
}
if (raw instanceof ArrayBuffer) {
return textDecoder.decode(raw);
}
if (raw instanceof Blob) {
return raw.text();
}
return null;
}
private async handleMessage(raw: unknown) {
let decoded: string | null;
try {
decoded = await this.decodeIncomingMessage(raw);
} catch {
return;
}
if (!decoded) {
return;
}
let parsedRaw: unknown;
try {
parsedRaw = JSON.parse(decoded);
} catch {
return;
}
const parsed = wsServerMessageSchema.safeParse(parsedRaw);
if (!parsed.success) {
return;
}
if (parsed.data.type === "response") {
this.handleResponse(parsed.data);
return;
}
if (parsed.data.type === "event") {
this.handleEvent(parsed.data);
}
}
asNativeApi(): NativeApi {
return {
app: {
bootstrap: async () => this.requestParsed("app.bootstrap", appBootstrapResultSchema),
health: async () => this.requestParsed("app.health", appHealthResultSchema),
},
todos: {
list: async () => this.requestParsed("todos.list", todoListSchema),
add: async (input) => this.requestParsed("todos.add", todoListSchema, input),
toggle: async (id) => this.requestParsed("todos.toggle", todoListSchema, id),
remove: async (id) => this.requestParsed("todos.remove", todoListSchema, id),
},
dialogs: {
pickFolder: async () =>
this.requestParsed("dialogs.pickFolder", dialogsPickFolderResultSchema),
},
terminal: {
run: async (input) => this.requestParsed("terminal.run", terminalCommandResultSchema, input),
},
agent: {
spawn: async (config) => this.requestParsed("agent.spawn", agentSessionIdSchema, config),
kill: async (sessionId) => this.requestNullResult("agent.kill", sessionId),
write: async (sessionId, data) => this.requestNullResult("agent.write", { sessionId, data }),
onOutput: (callback) => {
this.agentOutputListeners.add(callback);
return () => {
this.agentOutputListeners.delete(callback);
};
},
onExit: (callback) => {
this.agentExitListeners.add(callback);
return () => {
this.agentExitListeners.delete(callback);
};
},
},
providers: {
startSession: async (input) =>
this.requestParsed("providers.startSession", providerSessionSchema, input),
sendTurn: async (input) =>
this.requestParsed("providers.sendTurn", providerTurnStartResultSchema, input),
interruptTurn: async (input) => this.requestNullResult("providers.interruptTurn", input),
respondToRequest: async (input) => this.requestNullResult("providers.respondToRequest", input),
stopSession: async (input) => this.requestNullResult("providers.stopSession", input),
listSessions: async () =>
this.requestParsed("providers.listSessions", providerSessionListSchema),
onEvent: (callback) => {
this.providerEventListeners.add(callback);
return () => {
this.providerEventListeners.delete(callback);
};
},
},
shell: {
openInEditor: async (cwd, editor) => this.requestNullResult("shell.openInEditor", { cwd, editor }),
},
};
}
}
function resolveWsUrl() {
const params = new URLSearchParams(window.location.search);
return params.get("ws") ?? "ws://127.0.0.1:4317";
}
let cachedApi: NativeApi | undefined;
export function getOrCreateWsNativeApi() {
if (cachedApi) {
return cachedApi;
}
cachedApi = new WsNativeApiClient(resolveWsUrl()).asNativeApi();
return cachedApi;
}
-22
View File
@@ -1,22 +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(),
],
server: {
port: Number(process.env.T3_WEB_PORT ?? 5173),
strictPort: true,
},
build: {
outDir: "dist",
emptyOutDir: true,
},
});
+32
View File
@@ -0,0 +1,32 @@
{
"name": "t3",
"version": "0.1.0",
"bin": {
"t3": "./dist/index.mjs"
},
"files": [
"dist"
],
"type": "module",
"main": "./dist/index.mjs",
"scripts": {
"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": {
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
"typescript": "^5.7.3"
}
}
+21
View File
@@ -0,0 +1,21 @@
/**
* 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";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const webDist = path.resolve(__dirname, "../../web/dist");
const target = path.resolve(__dirname, "../dist/client");
if (!fs.existsSync(webDist)) {
console.log(
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
);
process.exit(0);
}
fs.cpSync(webDist, target, { recursive: true });
console.log("✓ Bundled web app into dist/client");
@@ -0,0 +1,193 @@
import { describe, expect, it, vi } from "vitest";
import {
CodexAppServerManager,
classifyCodexStderrLine,
isRecoverableThreadResumeError,
normalizeCodexModelSlug,
} from "./codexAppServerManager";
function createSendTurnHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
const requireSession = vi
.spyOn(manager as unknown as { requireSession: (sessionId: string) => unknown }, "requireSession")
.mockReturnValue(context);
const sendRequest = vi
.spyOn(manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> }, "sendRequest")
.mockResolvedValue({
turn: {
id: "turn_1",
},
});
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, requireSession, sendRequest, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
});
it("ignores non-error structured codex logs", () => {
const line =
"2026-02-08T04:24:19.241256Z WARN codex_core::features: unknown feature key in config: skills";
expect(classifyCodexStderrLine(line)).toBeNull();
});
it("ignores known benign rollout path errors", () => {
const line =
"\u001b[2m2026-02-08T04:24:20.085687Z\u001b[0m \u001b[31mERROR\u001b[0m \u001b[2mcodex_core::rollout::list\u001b[0m: state db missing rollout path for thread 019c3b6c-46b8-7b70-ad23-82f824d161fb";
expect(classifyCodexStderrLine(line)).toBeNull();
});
it("keeps unknown structured errors", () => {
const line = "2026-02-08T04:24:20.085687Z ERROR codex_core::runtime: unrecoverable failure";
expect(classifyCodexStderrLine(line)).toEqual({
message: line,
});
});
it("keeps plain stderr messages", () => {
const line = "fatal: permission denied";
expect(classifyCodexStderrLine(line)).toEqual({
message: line,
});
});
});
describe("normalizeCodexModelSlug", () => {
it("maps 5.3 aliases to gpt-5.3-codex", () => {
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
expect(normalizeCodexModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
});
it("prefers codex id when model differs", () => {
expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe("gpt-5.3-codex");
});
it("keeps non-aliased models as-is", () => {
expect(normalizeCodexModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2");
});
});
describe("isRecoverableThreadResumeError", () => {
it("matches not-found resume errors", () => {
expect(
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")),
).toBe(false);
});
it("ignores non-recoverable resume errors", () => {
expect(
isRecoverableThreadResumeError(
new Error("thread/resume failed: timed out waiting for server"),
),
).toBe(false);
});
});
describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness();
const result = await manager.sendTurn({
sessionId: "sess_1",
input: "Inspect this image",
attachments: [
{
type: "image",
name: "error.png",
mimeType: "image/png",
sizeBytes: 1_024,
dataUrl: "data:image/png;base64,AAAA",
},
],
model: "gpt-5.3",
effort: "high",
});
expect(result).toEqual({
threadId: "thread_1",
turnId: "turn_1",
});
expect(requireSession).toHaveBeenCalledWith("sess_1");
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "text",
text: "Inspect this image",
text_elements: [],
},
{
type: "image",
url: "data:image/png;base64,AAAA",
},
],
model: "gpt-5.3-codex",
effort: "high",
});
expect(updateSession).toHaveBeenCalledWith(context, {
status: "running",
activeTurnId: "turn_1",
});
});
it("supports image-only turns", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
await manager.sendTurn({
sessionId: "sess_1",
attachments: [
{
type: "image",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 256,
dataUrl: "data:image/png;base64,BBBB",
},
],
});
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "image",
url: "data:image/png;base64,BBBB",
},
],
});
});
it("rejects empty turn input", async () => {
const { manager } = createSendTurnHarness();
await expect(
manager.sendTurn({
sessionId: "sess_1",
}),
).rejects.toThrow("Turn input must include text or attachments.");
});
});
@@ -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;
@@ -174,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: {
@@ -257,20 +257,40 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
throw new Error("Session is missing a thread id.");
}
const turnInput: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
type: "text",
text: input.input,
text_elements: [],
});
}
for (const attachment of input.attachments ?? []) {
if (attachment.type === "image") {
turnInput.push({
type: "image",
url: attachment.dataUrl,
});
}
}
if (turnInput.length === 0) {
throw new Error("Turn input must include text or attachments.");
}
const turnStartParams: {
threadId: string;
input: Array<{ type: "text"; text: string; text_elements: [] }>;
input: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
>;
model?: string;
effort?: string;
} = {
threadId: context.session.threadId,
input: [
{
type: "text",
text: input.input,
text_elements: [],
},
],
input: turnInput,
};
const normalizedModel = normalizeCodexModelSlug(input.model);
if (normalizedModel) {
+123
View File
@@ -0,0 +1,123 @@
import fs from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { CodexTextGenerator } from "./codexTextGenerator";
import type { ProcessRunOptions, ProcessRunResult } from "./processRunner";
type ProcessRunner = (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
function getArgValue(args: readonly string[], flag: string): string {
const index = args.indexOf(flag);
if (index < 0 || index + 1 >= args.length) {
throw new Error(`Missing argument value for ${flag}`);
}
const value = args[index + 1];
if (!value) {
throw new Error(`Missing argument value for ${flag}`);
}
return value;
}
function okResult(): ProcessRunResult {
return {
stdout: "",
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
function commitInput() {
return {
cwd: process.cwd(),
branch: "feat/example",
stagedSummary: "M apps/server/src/gitManager.ts",
stagedPatch: "diff --git a/file b/file",
};
}
describe("CodexTextGenerator", () => {
it("uses gpt-5.3-codex-spark when available with medium reasoning effort", async () => {
const models: string[] = [];
const configs: string[] = [];
const runner: ProcessRunner = async (command, args) => {
expect(command).toBe("codex");
models.push(getArgValue(args, "--model"));
configs.push(getArgValue(args, "--config"));
const outputPath = getArgValue(args, "--output-last-message");
await fs.writeFile(
outputPath,
JSON.stringify({
subject: "Add stacked git actions menu behavior",
body: "- Keep menu actions visible\n- Improve disabled states",
}),
"utf8",
);
return okResult();
};
const generator = new CodexTextGenerator({ runProcess: runner });
const result = await generator.generateCommitMessage(commitInput());
expect(result.subject).toBe("Add stacked git actions menu behavior");
expect(models).toEqual(["gpt-5.3-codex-spark"]);
expect(configs).toEqual(['model_reasoning_effort="medium"']);
});
it("uses gpt-5.3-codex-spark for PR content generation", async () => {
const models: string[] = [];
const runner: ProcessRunner = async (command, args) => {
expect(command).toBe("codex");
models.push(getArgValue(args, "--model"));
const outputPath = getArgValue(args, "--output-last-message");
await fs.writeFile(
outputPath,
JSON.stringify({
title: "Improve Git action modal behavior",
body: "## Summary\n- Update PR generation model\n\n## Testing\n- Not run",
}),
"utf8",
);
return okResult();
};
const generator = new CodexTextGenerator({ runProcess: runner });
const result = await generator.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feat/example",
commitSummary: "abc123 Update model",
diffSummary: "1 file changed",
diffPatch: "diff --git a/file b/file",
});
expect(result.title).toBe("Improve Git action modal behavior");
expect(models).toEqual(["gpt-5.3-codex-spark"]);
});
it("propagates generation failures without retrying a second model", async () => {
const models: string[] = [];
const runner: ProcessRunner = async (_command, args) => {
models.push(getArgValue(args, "--model"));
throw new Error("Request timed out while contacting Codex.");
};
const generator = new CodexTextGenerator({ runProcess: runner });
await expect(generator.generateCommitMessage(commitInput())).rejects.toThrow(
"Request timed out while contacting Codex.",
);
expect(models).toEqual(["gpt-5.3-codex-spark"]);
});
});
+267
View File
@@ -0,0 +1,267 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type {
CommitMessageGenerationInput,
CommitMessageGenerationResult,
PrContentGenerationInput,
PrContentGenerationResult,
TextGenerationService,
} from "./coreServices";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
type ProcessRunner = (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
const CODEX_MODEL = "gpt-5.3-codex-spark";
const CODEX_REASONING_EFFORT = "medium";
const COMMIT_OUTPUT_SCHEMA_JSON = {
type: "object",
properties: {
subject: { type: "string" },
body: { type: "string" },
},
required: ["subject", "body"],
additionalProperties: false,
} as const;
const PR_OUTPUT_SCHEMA_JSON = {
type: "object",
properties: {
title: { type: "string" },
body: { type: "string" },
},
required: ["title", "body"],
additionalProperties: false,
} as const;
function parseCommitOutput(raw: unknown): { subject: string; body: string } {
if (!raw || typeof raw !== "object") {
throw new Error("Codex returned a non-object commit message payload.");
}
const record = raw as Record<string, unknown>;
const subject = typeof record.subject === "string" ? record.subject.trim() : "";
const body = typeof record.body === "string" ? record.body : "";
if (subject.length === 0) {
throw new Error("Codex returned an empty commit subject.");
}
return { subject, body };
}
function parsePrOutput(raw: unknown): { title: string; body: string } {
if (!raw || typeof raw !== "object") {
throw new Error("Codex returned a non-object PR payload.");
}
const record = raw as Record<string, unknown>;
const title = typeof record.title === "string" ? record.title.trim() : "";
const body = typeof record.body === "string" ? record.body.trim() : "";
if (title.length === 0 || body.length === 0) {
throw new Error("Codex returned an invalid PR title/body payload.");
}
return { title, body };
}
function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
async function writeTempFile(prefix: string, content: string): Promise<string> {
const filePath = path.join(
os.tmpdir(),
`t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,
);
await fs.writeFile(filePath, content, "utf8");
return filePath;
}
async function safeUnlink(filePath: string): Promise<void> {
try {
await fs.unlink(filePath);
} catch {
// Best-effort cleanup.
}
}
function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
async function runCodexJson<T>({
cwd,
prompt,
outputSchemaJson,
parse,
run,
}: {
cwd: string;
prompt: string;
outputSchemaJson: object;
parse: (raw: unknown) => T;
run: ProcessRunner;
}): Promise<T> {
const schemaPath = await writeTempFile(
"codex-schema",
JSON.stringify(outputSchemaJson),
);
let outputPath: string | null = null;
try {
outputPath = await writeTempFile("codex-output", "");
await run(
"codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
CODEX_MODEL,
"--config",
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
"-",
],
{
cwd,
timeoutMs: 180_000,
stdin: prompt,
},
);
const rawOutput = (await fs.readFile(outputPath, "utf8")).trim();
if (rawOutput.length === 0) {
throw new Error("Codex returned an empty response.");
}
let parsedJson: unknown;
try {
parsedJson = JSON.parse(rawOutput);
} catch {
throw new Error("Codex returned invalid JSON output.");
}
return parse(parsedJson);
} finally {
await Promise.all([
safeUnlink(schemaPath),
...(outputPath ? [safeUnlink(outputPath)] : []),
]);
}
}
interface CodexTextGeneratorDeps {
runProcess?: ProcessRunner;
}
export class CodexTextGenerator implements TextGenerationService {
private readonly run: ProcessRunner;
constructor(deps: CodexTextGeneratorDeps = {}) {
this.run = deps.runProcess ?? runProcess;
}
async generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult> {
const prompt = [
"You write concise git commit messages.",
"Return a JSON object with keys: subject, body.",
"Rules:",
"- subject must be imperative, <= 72 chars, and no trailing period",
"- body can be empty string or short bullet points",
"- capture the primary user-visible or developer-visible change",
"",
`Branch: ${input.branch ?? "(detached)"}`,
"",
"Staged files:",
limitSection(input.stagedSummary, 6_000),
"",
"Staged patch:",
limitSection(input.stagedPatch, 40_000),
].join("\n");
const generated = await runCodexJson({
cwd: input.cwd,
prompt,
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
parse: (raw) => parseCommitOutput(raw),
run: this.run,
});
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
};
}
async generatePrContent(
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult> {
const prompt = [
"You write GitHub pull request content.",
"Return a JSON object with keys: title, body.",
"Rules:",
"- title should be concise and specific",
"- body must be markdown and include headings '## Summary' and '## Testing'",
"- under Summary, provide short bullet points",
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
"",
`Base branch: ${input.baseBranch}`,
`Head branch: ${input.headBranch}`,
"",
"Commits:",
limitSection(input.commitSummary, 12_000),
"",
"Diff stat:",
limitSection(input.diffSummary, 12_000),
"",
"Diff patch:",
limitSection(input.diffPatch, 40_000),
].join("\n");
const generated = await runCodexJson({
cwd: input.cwd,
prompt,
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
parse: (raw) => parsePrOutput(raw),
run: this.run,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
}
}
+35
View File
@@ -0,0 +1,35 @@
export interface CommitMessageGenerationInput {
cwd: string;
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}
export interface CommitMessageGenerationResult {
subject: string;
body: string;
}
export interface PrContentGenerationInput {
cwd: string;
baseBranch: string;
headBranch: string;
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
export interface PrContentGenerationResult {
title: string;
body: string;
}
export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult>;
}
+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 {
// Silently ignore — keep default PATH
}
}
+520
View File
@@ -0,0 +1,520 @@
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 {
GitCoreService,
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);
});
});
describe("GitCoreService", () => {
it("supports branch lifecycle operations through the service API", async () => {
await using tmp = await makeTmpDir();
const core = new GitCoreService();
await core.initRepo({ cwd: tmp.path });
await git(tmp.path, "config user.email '[email protected]'");
await git(tmp.path, "config user.name 'Test'");
await writeFile(path.join(tmp.path, "README.md"), "# test\n");
await git(tmp.path, "add .");
await git(tmp.path, "commit -m 'initial commit'");
await core.createBranch({ cwd: tmp.path, branch: "feature/service-api" });
await core.checkoutBranch({ cwd: tmp.path, branch: "feature/service-api" });
const branches = await core.listBranches({ cwd: tmp.path });
expect(branches.isRepo).toBe(true);
expect(branches.branches.find((branch) => branch.current)?.name).toBe("feature/service-api");
});
it("reports status details and dirty state", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
const clean = await core.status({ cwd: tmp.path });
expect(clean.hasWorkingTreeChanges).toBe(false);
expect(clean.branch).toBeTruthy();
await writeFile(path.join(tmp.path, "README.md"), "updated\n");
const dirty = await core.statusDetails(tmp.path);
expect(dirty.hasWorkingTreeChanges).toBe(true);
});
it("prepares commit context by auto-staging and creates commit", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
await writeFile(path.join(tmp.path, "README.md"), "new content\n");
const context = await core.prepareCommitContext(tmp.path);
expect(context).not.toBeNull();
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);
const created = await core.commit(
tmp.path,
"Add README update",
"- include updated content",
);
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
it("pushes with upstream setup and then skips when up to date", async () => {
await using tmp = await makeTmpDir();
await using remote = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await git(remote.path, "init --bare");
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
await createGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
await checkoutGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
await writeFile(path.join(tmp.path, "feature.txt"), "push me\n");
const core = new GitCoreService();
const context = await core.prepareCommitContext(tmp.path);
expect(context).not.toBeNull();
await core.commit(tmp.path, "Add feature file", "");
const pushed = await core.pushCurrentBranch(tmp.path, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(await git(tmp.path, "rev-parse --abbrev-ref @{upstream}")).toBe(
"origin/feature/core-push",
);
const skipped = await core.pushCurrentBranch(tmp.path, null);
expect(skipped.status).toBe("skipped_up_to_date");
});
});
});
+495
View File
@@ -0,0 +1,495 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
type GitCreateBranchInput,
type GitCreateWorktreeInput,
type GitCreateWorktreeResult,
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
} from "@t3tools/contracts";
import { type ProcessRunResult, runProcess } from "./processRunner";
export interface TerminalCommandInput {
command: string;
cwd: string;
timeoutMs?: number;
maxOutputBytes?: number;
}
export type TerminalCommandResult = ProcessRunResult;
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
upstreamRef: string | null;
}
export interface GitPreparedCommitContext {
stagedSummary: string;
stagedPatch: string;
}
export interface GitPushResult {
status: "pushed" | "skipped_up_to_date";
branch: string;
upstreamBranch?: string | undefined;
setUpstream?: boolean | undefined;
}
export interface GitRangeContext {
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
interface RunGitOptions {
timeoutMs?: number | undefined;
allowNonZeroExit?: boolean | undefined;
}
interface ExecuteGitOptions {
timeoutMs?: number | undefined;
allowNonZeroExit?: boolean | undefined;
fallbackErrorMessage?: string | undefined;
}
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
/** Spawn git directly with an argv array — no shell, no quoting needed. */
function runGit(
args: readonly string[],
cwd: string,
timeoutMs = 30_000,
): Promise<ProcessRunResult> {
return runProcess("git", args, {
cwd,
timeoutMs,
allowNonZeroExit: true,
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
outputMode: "truncate",
});
}
function trimStdout(value: string): string {
return value.trim();
}
function parseBranchAb(value: string): { ahead: number; behind: number } {
const match = value.match(/^\+(\d+)\s+-(\d+)$/);
if (!match) return { ahead: 0, behind: 0 };
return {
ahead: Number(match[1] ?? "0"),
behind: Number(match[2] ?? "0"),
};
}
function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
function normalizeGitSpawnError(cwd: string, error: unknown): Error {
if (!(error instanceof Error)) {
return new Error("Failed to run git command.");
}
if (!fs.existsSync(cwd)) {
return new Error(`Working directory does not exist: ${cwd}`);
}
if (error.message.includes("Command not found: git")) {
return new Error("Git is required but not available on PATH.");
}
return new Error(`Failed to run git command: ${error.message}`);
}
function normalizeGitExecutionError(args: readonly string[], result: TerminalCommandResult): Error {
const stderr = result.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return new Error("Current folder is not a git repository.");
}
if (result.timedOut) {
return new Error(`${commandLabel(args)} timed out.`);
}
const detail =
stderr.length > 0 ? stderr : `code=${result.code ?? "null"}, signal=${result.signal ?? "null"}`;
return new Error(`${commandLabel(args)} failed: ${detail}`);
}
async function runGitOrThrow(
cwd: string,
args: readonly string[],
options: RunGitOptions = {},
): Promise<TerminalCommandResult> {
let result: TerminalCommandResult;
try {
result = await runGit(args, cwd, options.timeoutMs);
} catch (error) {
throw normalizeGitSpawnError(cwd, error);
}
if (result.timedOut) {
throw normalizeGitExecutionError(args, result);
}
if (!options.allowNonZeroExit && result.code !== 0) {
throw normalizeGitExecutionError(args, result);
}
return result;
}
async function executeGit(
cwd: string,
args: readonly string[],
options: ExecuteGitOptions = {},
): Promise<TerminalCommandResult> {
const result = await runGitOrThrow(cwd, args, {
timeoutMs: options.timeoutMs,
allowNonZeroExit: true,
});
if (options.allowNonZeroExit || result.code === 0) {
return result;
}
const stderr = result.stderr.trim();
if (stderr.length > 0) {
throw new Error(stderr);
}
if (options.fallbackErrorMessage) {
throw new Error(options.fallbackErrorMessage);
}
throw normalizeGitExecutionError(args, result);
}
export class GitCoreService {
async status(raw: GitStatusInput): Promise<GitStatusResult> {
const input = gitStatusInputSchema.parse(raw);
const details = await this.statusDetails(input.cwd);
return gitStatusResultSchema.parse({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr: null,
});
}
async statusDetails(cwd: string): Promise<GitStatusDetails> {
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
for (const line of stdout.split(/\r?\n/g)) {
if (line.startsWith("# branch.head ")) {
const value = line.slice("# branch.head ".length).trim();
branch = value.startsWith("(") ? null : value;
continue;
}
if (line.startsWith("# branch.upstream ")) {
const value = line.slice("# branch.upstream ".length).trim();
upstreamRef = value.length > 0 ? value : null;
continue;
}
if (line.startsWith("# branch.ab ")) {
const value = line.slice("# branch.ab ".length).trim();
const parsed = parseBranchAb(value);
aheadCount = parsed.ahead;
behindCount = parsed.behind;
continue;
}
if (line.trim().length > 0 && !line.startsWith("#")) {
hasWorkingTreeChanges = true;
}
}
return {
branch,
upstreamRef,
hasWorkingTreeChanges,
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
};
}
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);
const stagedSummary = await this.gitStdout(cwd, [
"diff",
"--cached",
"--name-status",
]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}
const stagedPatch = await this.gitStdout(cwd, [
"diff",
"--cached",
"--patch",
"--minimal",
]);
return {
stagedSummary,
stagedPatch,
};
}
async commit(cwd: string, subject: string, body: string): Promise<{ commitSha: string }> {
const args = ["commit", "-m", subject];
const trimmedBody = body.trim();
if (trimmedBody.length > 0) {
args.push("-m", trimmedBody);
}
await this.git(cwd, args);
const commitSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"]));
return { commitSha };
}
async pushCurrentBranch(cwd: string, fallbackBranch: string | null): Promise<GitPushResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
throw new Error("Cannot push from detached HEAD.");
}
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
return {
status: "skipped_up_to_date",
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
}
if (!details.hasUpstream) {
await this.git(cwd, ["push", "-u", "origin", branch]);
return {
status: "pushed",
branch,
upstreamBranch: `origin/${branch}`,
setUpstream: true,
};
}
await this.git(cwd, ["push"]);
return {
status: "pushed",
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
setUpstream: false,
};
}
async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
this.gitStdout(cwd, ["log", "--oneline", range]),
this.gitStdout(cwd, ["diff", "--stat", range]),
this.gitStdout(cwd, ["diff", "--patch", "--minimal", range]),
]);
return {
commitSummary,
diffSummary,
diffPatch,
};
}
async readConfigValue(cwd: string, key: string): Promise<string | null> {
const stdout = await this.gitStdout(cwd, ["config", "--get", key], true);
const value = trimStdout(stdout);
return value.length > 0 ? value : null;
}
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
timeoutMs: 10_000,
allowNonZeroExit: true,
});
if (result.code !== 0) {
const stderr = result.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false };
}
throw new Error(stderr || "git branch failed");
}
const [defaultRef, worktreeList] = await Promise.all([
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
timeoutMs: 5_000,
allowNonZeroExit: true,
}),
executeGit(input.cwd, ["worktree", "list", "--porcelain"], {
timeoutMs: 5_000,
allowNonZeroExit: true,
}),
]);
const defaultBranch =
defaultRef.code === 0
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
: null;
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 };
}
async createWorktree(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);
await executeGit(
input.cwd,
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
{ fallbackErrorMessage: "git worktree add failed" },
);
return {
worktree: {
path: worktreePath,
branch: input.newBranch,
},
};
}
async removeWorktree(input: GitRemoveWorktreeInput): Promise<void> {
await executeGit(input.cwd, ["worktree", "remove", input.path], {
timeoutMs: 15_000,
fallbackErrorMessage: "git worktree remove failed",
});
}
async createBranch(input: GitCreateBranchInput): Promise<void> {
await executeGit(input.cwd, ["branch", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git branch create failed",
});
}
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
await executeGit(input.cwd, ["checkout", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
}
async initRepo(input: GitInitInput): Promise<void> {
await executeGit(input.cwd, ["init"], {
timeoutMs: 10_000,
fallbackErrorMessage: "git init failed",
});
}
async git(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<void> {
await executeGit(cwd, args, { allowNonZeroExit });
}
async gitStdout(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<string> {
const result = await executeGit(cwd, args, { allowNonZeroExit });
return result.stdout;
}
}
const defaultGitCoreService = new GitCoreService();
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];
const result = await runProcess(shellPath, args, {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? 30_000,
allowNonZeroExit: true,
maxBufferBytes: maxOutputBytes,
outputMode: "truncate",
});
if (!result.stdoutTruncated && !result.stderrTruncated) {
return result;
}
return {
...result,
stderr: `${result.stderr}\n[output truncated at ${maxOutputBytes} bytes]`,
};
}
export async function listGitBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
return defaultGitCoreService.listBranches(input);
}
export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
return defaultGitCoreService.createWorktree(input);
}
export async function removeGitWorktree(input: GitRemoveWorktreeInput): Promise<void> {
await defaultGitCoreService.removeWorktree(input);
}
export async function createGitBranch(input: GitCreateBranchInput): Promise<void> {
await defaultGitCoreService.createBranch(input);
}
export async function checkoutGitBranch(input: GitCheckoutInput): Promise<void> {
await defaultGitCoreService.checkoutBranch(input);
}
export async function initGitRepo(input: GitInitInput): Promise<void> {
await defaultGitCoreService.initRepo(input);
}
+490
View File
@@ -0,0 +1,490 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { GitManager } from "./gitManager";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
interface FakeGhScenario {
prListSequence?: string[];
createdPrUrl?: string;
defaultBranch?: string;
failWith?: Error;
}
interface FakeGitTextGenerator {
generateCommitMessage: (input: {
cwd: string;
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}) => Promise<{ subject: string; body: string }>;
generatePrContent: (input: {
cwd: string;
baseBranch: string;
headBranch: string;
commitSummary: string;
diffSummary: string;
diffPatch: string;
}) => Promise<{ title: string; body: string }>;
}
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
async function runGit(
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Promise<ProcessRunResult> {
return runProcess("git", args, { cwd, allowNonZeroExit });
}
async function runGitStdout(cwd: string, args: readonly string[]): Promise<string> {
const result = await runGit(cwd, args);
return result.stdout.trim();
}
async function initRepo(cwd: string): Promise<void> {
await runGit(cwd, ["init", "--initial-branch=main"]);
await runGit(cwd, ["config", "user.email", "[email protected]"]);
await runGit(cwd, ["config", "user.name", "Test User"]);
fs.writeFileSync(path.join(cwd, "README.md"), "hello\n");
await runGit(cwd, ["add", "README.md"]);
await runGit(cwd, ["commit", "-m", "Initial commit"]);
}
async function createBareRemote(): Promise<string> {
const remoteDir = makeTempDir("t3code-git-remote-");
await runProcess("git", ["init", "--bare"], { cwd: remoteDir });
return remoteDir;
}
function createTextGenerator(
overrides: Partial<FakeGitTextGenerator> = {},
): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
body: "",
}),
generatePrContent: async () => ({
title: "Add stacked git actions",
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
}),
...overrides,
};
}
function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
runner: (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
ghCalls: string[];
} {
const prListQueue = [...(scenario.prListSequence ?? [])];
const ghCalls: string[] = [];
const runner = async (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
): Promise<ProcessRunResult> => {
if (command !== "gh") {
return runProcess(command, args, options);
}
ghCalls.push(args.join(" "));
if (scenario.failWith) {
throw scenario.failWith;
}
if (args[0] === "pr" && args[1] === "list") {
const stdout = (prListQueue.shift() ?? "[]") + "\n";
return {
stdout,
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ??
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
if (args[0] === "pr" && args[1] === "view") {
return {
stdout: "",
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
if (args[0] === "repo" && args[1] === "view") {
return {
stdout: `${scenario.defaultBranch ?? "main"}\n`,
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
throw new Error(`Unexpected gh command: ${args.join(" ")}`);
};
return { runner, ghCalls };
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("GitManager", () => {
it("status includes open PR metadata when branch already has an open PR", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]);
const { runner } = createRunnerWithFakeGh({
prListSequence: [
JSON.stringify([
{
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseRefName: "main",
headRefName: "feature/status-open-pr",
},
]),
],
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const status = await manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-open-pr");
expect(status.openPr).toEqual({
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseBranch: "main",
headBranch: "feature/status-open-pr",
});
});
it("status is resilient to gh lookup failures and returns openPr null", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);
const { runner } = createRunnerWithFakeGh({
failWith: new Error("Command not found: gh"),
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const status = await manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-no-gh");
expect(status.openPr).toBeNull();
});
it("creates a commit when working tree is dirty", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit",
});
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("skipped_not_requested");
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
"Implement stacked git actions",
);
});
it("uses custom commit message when provided", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");
let generatedCount = 0;
const manager = new GitManager({
textGenerator: createTextGenerator({
generateCommitMessage: async () => {
generatedCount += 1;
return {
subject: "this should not be used",
body: "",
};
},
}),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit",
commitMessage: "feat: custom summary line\n\n- details from user",
});
expect(result.commit.status).toBe("created");
expect(result.commit.subject).toBe("feat: custom summary line");
expect(generatedCount).toBe(0);
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
"feat: custom summary line",
);
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%b"])).toContain(
"- details from user",
);
});
it("skips commit when there are no uncommitted changes", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit",
});
expect(result.commit.status).toBe("skipped_no_changes");
expect(result.push.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("skipped_not_requested");
});
it("commits and pushes with upstream auto-setup when needed", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push",
});
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
expect(await runGitStdout(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
"origin/feature/stacked-flow",
);
});
it("skips push when branch is already up to date", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]);
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push",
});
expect(result.commit.status).toBe("skipped_no_changes");
expect(result.push.status).toBe("skipped_up_to_date");
});
it("opens existing PR for commit/push/pr action", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);
const { runner, ghCalls } = createRunnerWithFakeGh({
prListSequence: [
JSON.stringify([
{
number: 42,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/existing-pr",
},
]),
],
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(42);
expect(
ghCalls.some((call) => call.startsWith("pr view feature/existing-pr --web")),
).toBe(true);
});
it("creates PR when one does not already exist", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
await runGit(repoDir, ["add", "changes.txt"]);
await runGit(repoDir, ["commit", "-m", "Feature commit"]);
await runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
await runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
const { runner, ghCalls } = createRunnerWithFakeGh({
prListSequence: [
"[]",
JSON.stringify([
{
number: 88,
title: "Add stacked git actions",
url: "https://github.com/pingdotgg/codething-mvp/pull/88",
baseRefName: "main",
headRefName: "feature-create-pr",
},
]),
],
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(88);
expect(
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
).toBe(true);
});
it("rejects push/pr actions from detached HEAD", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "--detach", "HEAD"]);
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
await expect(
manager.runStackedAction({
cwd: repoDir,
action: "commit_push",
}),
).rejects.toThrow("detached HEAD");
});
it("surfaces missing gh binary errors", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]);
const { runner } = createRunnerWithFakeGh({
failWith: new Error("Command not found: gh"),
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
await expect(
manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
}),
).rejects.toThrow("GitHub CLI (`gh`) is required");
});
it("surfaces gh auth errors with guidance", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]);
const { runner } = createRunnerWithFakeGh({
failWith: new Error("authentication failed"),
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
await expect(
manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
}),
).rejects.toThrow("gh auth login");
});
});
+506
View File
@@ -0,0 +1,506 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import {
gitRunStackedActionInputSchema,
gitRunStackedActionResultSchema,
gitStatusInputSchema,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type GitStatusInput,
type GitStatusResult,
} from "@t3tools/contracts";
import type {
CommitMessageGenerationResult,
PrContentGenerationResult,
TextGenerationService,
} from "./coreServices";
import { CodexTextGenerator } from "./codexTextGenerator";
import { GitCoreService } from "./git";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
const GH_CLI_TIMEOUT_MS = 30_000;
interface GitManagerDeps {
runProcess?: (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
textGenerator?: TextGenerationService;
gitCore?: GitCoreService;
}
interface OpenPrInfo {
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}
function parseOpenPrList(raw: unknown): OpenPrInfo[] {
if (!Array.isArray(raw)) return [];
const parsed: OpenPrInfo[] = [];
for (const entry of raw) {
if (!entry || typeof entry !== "object") continue;
const record = entry as Record<string, unknown>;
const number = record.number;
const title = record.title;
const url = record.url;
const baseRefName = record.baseRefName;
const headRefName = record.headRefName;
if (
typeof number !== "number" ||
!Number.isInteger(number) ||
number <= 0
) {
continue;
}
if (
typeof title !== "string" ||
typeof url !== "string" ||
typeof baseRefName !== "string" ||
typeof headRefName !== "string"
) {
continue;
}
parsed.push({
number,
title,
url,
baseRefName,
headRefName,
});
}
return parsed;
}
function trimStdout(value: string): string {
return value.trim();
}
function limitContext(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
return `${value.slice(0, maxChars)}\n\n[truncated]`;
}
function sanitizeCommitMessage(
generated: CommitMessageGenerationResult,
): CommitMessageGenerationResult {
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const subject = rawSubject.replace(/[.]+$/g, "").trim();
const safeSubject =
subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
return {
subject: safeSubject,
body: generated.body.trim(),
};
}
function parseCustomCommitMessage(raw: string): CommitMessageGenerationResult | null {
const normalized = raw.replace(/\r\n/g, "\n").trim();
if (normalized.length === 0) {
return null;
}
const [firstLine, ...rest] = normalized.split("\n");
const subject = firstLine?.trim() ?? "";
if (subject.length === 0) {
return null;
}
return {
subject,
body: rest.join("\n").trim(),
};
}
function extractBranchFromRef(ref: string): string {
const normalized = ref.trim();
if (normalized.startsWith("refs/remotes/")) {
const withoutPrefix = normalized.slice("refs/remotes/".length);
const firstSlash = withoutPrefix.indexOf("/");
if (firstSlash === -1) {
return withoutPrefix.trim();
}
return withoutPrefix.slice(firstSlash + 1).trim();
}
const firstSlash = normalized.indexOf("/");
if (firstSlash === -1) {
return normalized;
}
return normalized.slice(firstSlash + 1).trim();
}
function asCommandNotFound(
command: string,
error: unknown,
): Error | undefined {
if (!(error instanceof Error)) return undefined;
if (!error.message.includes(`Command not found: ${command}`)) return undefined;
if (command === "gh") {
return new Error("GitHub CLI (`gh`) is required but not available on PATH.");
}
if (command === "codex") {
return new Error("Codex CLI (`codex`) is required but not available on PATH.");
}
return new Error(`${command} is required but not available on PATH.`);
}
function normalizeGitHubAuthError(error: unknown): Error | undefined {
if (!(error instanceof Error)) return undefined;
const lower = error.message.toLowerCase();
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("gh auth login") ||
lower.includes("no oauth token")
) {
return new Error("GitHub CLI is not authenticated. Run `gh auth login` and retry.");
}
return undefined;
}
function toStatusOpenPr(pr: OpenPrInfo): {
number: number;
title: string;
url: string;
baseBranch: string;
headBranch: string;
} {
return {
number: pr.number,
title: pr.title,
url: pr.url,
baseBranch: pr.baseRefName,
headBranch: pr.headRefName,
};
}
export class GitManager {
private readonly run: NonNullable<GitManagerDeps["runProcess"]>;
private readonly textGenerator: TextGenerationService;
private readonly gitCore: GitCoreService;
constructor(deps: GitManagerDeps = {}) {
this.run = deps.runProcess ?? runProcess;
this.textGenerator = deps.textGenerator ?? new CodexTextGenerator();
this.gitCore = deps.gitCore ?? new GitCoreService();
}
async status(raw: GitStatusInput): Promise<GitStatusResult> {
const input = gitStatusInputSchema.parse(raw);
const details = await this.gitCore.statusDetails(input.cwd);
let openPr: ReturnType<typeof toStatusOpenPr> | null = null;
if (details.branch && details.hasUpstream) {
try {
const existing = await this.findOpenPr(input.cwd, details.branch);
if (existing) {
openPr = toStatusOpenPr(existing);
}
} catch {
// PR lookup is best-effort for status rendering.
}
}
return {
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr,
};
}
async runStackedAction(
raw: GitRunStackedActionInput,
): Promise<GitRunStackedActionResult> {
const input = gitRunStackedActionInputSchema.parse(raw);
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const initialStatus = await this.gitCore.statusDetails(input.cwd);
if (wantsPush && !initialStatus.branch) {
throw new Error("Cannot push from detached HEAD.");
}
if (wantsPr && !initialStatus.branch) {
throw new Error("Cannot create a pull request from detached HEAD.");
}
const commit = await this.runCommitStep(
input.cwd,
initialStatus.branch,
input.commitMessage,
);
const push = wantsPush
? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? await this.runPrStep(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
return gitRunStackedActionResultSchema.parse({
action: input.action,
commit,
push,
pr,
});
}
private async runCommitStep(
cwd: string,
branch: string | null,
commitMessage?: string,
): Promise<{
status: "created" | "skipped_no_changes";
commitSha?: string | undefined;
subject?: string | undefined;
}> {
const context = await this.gitCore.prepareCommitContext(cwd);
if (!context) {
return { status: "skipped_no_changes" };
}
let generated: CommitMessageGenerationResult | null = parseCustomCommitMessage(
commitMessage ?? "",
);
if (!generated) {
try {
generated = sanitizeCommitMessage(
await this.textGenerator.generateCommitMessage({
cwd,
branch,
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
}),
);
} catch (error) {
throw asCommandNotFound("codex", error) ?? error;
}
}
const { commitSha } = await this.gitCore.commit(cwd, generated.subject, generated.body);
return {
status: "created",
commitSha,
subject: generated.subject,
};
}
private async runPrStep(
cwd: string,
fallbackBranch: string | null,
): Promise<{
status: "created" | "opened_existing" | "skipped_not_requested";
url?: string | undefined;
number?: number | undefined;
baseBranch?: string | undefined;
headBranch?: string | undefined;
title?: string | undefined;
}> {
const details = await this.gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
throw new Error("Cannot create a pull request from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has not been pushed. Push before creating a PR.");
}
const existing = await this.findOpenPr(cwd, branch);
if (existing) {
await this.openPrInBrowser(cwd, branch);
return {
status: "opened_existing",
url: existing.url,
number: existing.number,
baseBranch: existing.baseRefName,
headBranch: existing.headRefName,
title: existing.title,
};
}
const baseBranch = await this.resolveBaseBranch(cwd, branch, details.upstreamRef);
const rangeContext = await this.gitCore.readRangeContext(cwd, baseBranch);
let generated: PrContentGenerationResult;
try {
generated = await this.textGenerator.generatePrContent({
cwd,
baseBranch,
headBranch: branch,
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
});
} catch (error) {
throw asCommandNotFound("codex", error) ?? error;
}
const bodyFile = path.join(
os.tmpdir(),
`t3code-pr-body-${process.pid}-${randomUUID()}.md`,
);
await fs.writeFile(bodyFile, generated.body, "utf8");
try {
await this.runGh(cwd, [
"pr",
"create",
"--base",
baseBranch,
"--head",
branch,
"--title",
generated.title,
"--body-file",
bodyFile,
]);
} finally {
try {
await fs.unlink(bodyFile);
} catch {
// Best-effort cleanup.
}
}
const created = await this.findOpenPr(cwd, branch);
await this.openPrInBrowser(cwd, branch);
if (!created) {
return {
status: "created",
baseBranch,
headBranch: branch,
title: generated.title,
};
}
return {
status: "created",
url: created.url,
number: created.number,
baseBranch: created.baseRefName,
headBranch: created.headRefName,
title: created.title,
};
}
private async openPrInBrowser(cwd: string, branch: string): Promise<void> {
try {
await this.runGh(cwd, ["pr", "view", branch, "--web"]);
} catch {
// Opening the browser is best-effort.
}
}
private async findOpenPr(
cwd: string,
branch: string,
): Promise<OpenPrInfo | null> {
const stdout = await this.runGhStdout(cwd, [
"pr",
"list",
"--head",
branch,
"--state",
"open",
"--limit",
"1",
"--json",
"number,title,url,baseRefName,headRefName",
]);
const raw = trimStdout(stdout);
if (raw.length === 0) return null;
let parsedJson: unknown;
try {
parsedJson = JSON.parse(raw);
} catch {
throw new Error("GitHub CLI returned invalid PR list JSON.");
}
const parsed = parseOpenPrList(parsedJson);
return parsed[0] ?? null;
}
private async resolveBaseBranch(
cwd: string,
branch: string,
upstreamRef: string | null,
): Promise<string> {
const configured = await this.gitCore.readConfigValue(
cwd,
`branch.${branch}.gh-merge-base`,
);
if (configured) return configured;
if (upstreamRef) {
const upstreamBranch = extractBranchFromRef(upstreamRef);
if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
return upstreamBranch;
}
}
try {
const ghDefault = await this.runGhStdout(cwd, [
"repo",
"view",
"--json",
"defaultBranchRef",
"--jq",
".defaultBranchRef.name",
]);
const defaultBranch = trimStdout(ghDefault);
if (defaultBranch.length > 0) return defaultBranch;
} catch {
// Fall through to deterministic fallback.
}
return "main";
}
private async runGh(cwd: string, args: readonly string[]): Promise<void> {
await this.runGhCommand(cwd, args);
}
private async runGhStdout(cwd: string, args: readonly string[]): Promise<string> {
const result = await this.runGhCommand(cwd, args);
return result.stdout;
}
private async runGhCommand(
cwd: string,
args: readonly string[],
): Promise<ProcessRunResult> {
try {
return await this.run("gh", args, {
cwd,
timeoutMs: GH_CLI_TIMEOUT_MS,
});
} catch (error) {
throw (
asCommandNotFound("gh", error) ??
normalizeGitHubAuthError(error) ??
(error instanceof Error ? error : new Error("GitHub CLI command failed."))
);
}
}
}
+176
View File
@@ -0,0 +1,176 @@
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();
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();
server.listen(preferred, () => {
server.close(() => resolve(preferred));
});
server.on("error", () => {
// Preferred port busy — let the OS pick one
const fallback = net.createServer();
fallback.listen(0, () => {
const addr = fallback.address();
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."));
});
});
fallback.on("error", reject);
});
});
}
function resolveStaticDir(): string | undefined {
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Check for bundled client (npm publish / npx scenario):
// dist/client/ lives alongside dist/index.js
const bundledClient = path.resolve(__dirname, "client");
try {
const stat = fs.statSync(path.join(bundledClient, "index.html"));
if (stat.isFile()) return bundledClient;
} catch {
// Not bundled — check monorepo layout
}
// 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;
} catch {
// Not found — probably dev mode, Vite will serve
}
return undefined;
}
async function main() {
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("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.",
});
}
const server = createServer({
port,
host: mode === "desktop" ? "127.0.0.1" : undefined,
cwd,
staticDir,
devUrl,
projectRegistry,
authToken,
});
await server.start();
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 T3 Code", { error: err });
process.exit(1);
});
+103
View File
@@ -0,0 +1,103 @@
import util from "node:util";
type LogLevel = "info" | "warn" | "error" | "event";
type LogContext = Record<string, unknown>;
const ANSI = {
reset: "\u001b[0m",
dim: "\u001b[2m",
cyan: "\u001b[36m",
yellow: "\u001b[33m",
red: "\u001b[31m",
magenta: "\u001b[35m",
} as const;
const LEVEL_LABEL: Record<LogLevel, string> = {
info: "INFO",
warn: "WARN",
error: "ERROR",
event: "EVENT",
};
const LEVEL_COLOR: Record<LogLevel, string> = {
info: ANSI.cyan,
warn: ANSI.yellow,
error: ANSI.red,
event: ANSI.magenta,
};
function useColors() {
return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined;
}
function colorize(value: string, color: string, enabled: boolean) {
return enabled ? `${color}${value}${ANSI.reset}` : value;
}
function timeStamp() {
return new Date().toISOString().slice(11, 23);
}
function formatValue(value: unknown) {
if (typeof value === "string") {
return JSON.stringify(value);
}
if (
typeof value === "number" ||
typeof value === "boolean" ||
value === null ||
value === undefined
) {
return String(value);
}
return util.inspect(value, {
depth: 4,
breakLength: Infinity,
compact: true,
maxArrayLength: 25,
maxStringLength: 320,
});
}
function formatContext(context: LogContext | undefined) {
if (!context) return "";
const entries = Object.entries(context).filter(([, value]) => value !== undefined);
if (entries.length === 0) return "";
return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
}
function write(level: LogLevel, scope: string, message: string, context?: LogContext) {
const colorEnabled = useColors();
const ts = colorize(timeStamp(), ANSI.dim, colorEnabled);
const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled);
const contextText = formatContext(context);
const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`;
if (level === "warn") {
console.warn(line);
return;
}
if (level === "error") {
console.error(line);
return;
}
console.log(line);
}
export function createLogger(scope: string) {
return {
info(message: string, context?: LogContext) {
write("info", scope, message, context);
},
warn(message: string, context?: LogContext) {
write("warn", scope, message, context);
},
error(message: string, context?: LogContext) {
write("error", scope, message, context);
},
event(message: string, context?: LogContext) {
write("event", scope, message, context);
},
};
}
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { runProcess } from "./processRunner";
describe("runProcess", () => {
it("fails when output exceeds max buffer in default mode", async () => {
await expect(
runProcess(
"node",
["-e", "process.stdout.write('x'.repeat(2048))"],
{ maxBufferBytes: 128 },
),
).rejects.toThrow("exceeded stdout buffer limit");
});
it("truncates output when outputMode is truncate", async () => {
const result = await runProcess(
"node",
["-e", "process.stdout.write('x'.repeat(2048))"],
{
maxBufferBytes: 128,
outputMode: "truncate",
},
);
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
expect(result.stdoutTruncated).toBe(true);
expect(result.stderrTruncated).toBe(false);
});
});
+271
View File
@@ -0,0 +1,271 @@
import { spawn } from "node:child_process";
export interface ProcessRunOptions {
cwd?: string | undefined;
timeoutMs?: number | undefined;
env?: NodeJS.ProcessEnv | undefined;
stdin?: string | undefined;
allowNonZeroExit?: boolean | undefined;
maxBufferBytes?: number | undefined;
outputMode?: "error" | "truncate" | undefined;
}
export interface ProcessRunResult {
stdout: string;
stderr: string;
code: number | null;
signal: NodeJS.Signals | null;
timedOut: boolean;
stdoutTruncated?: boolean | undefined;
stderrTruncated?: boolean | undefined;
}
function commandLabel(command: string, args: readonly string[]): string {
return [command, ...args].join(" ");
}
function normalizeSpawnError(
command: string,
args: readonly string[],
error: unknown,
): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to run ${commandLabel(command, args)}.`);
}
const maybeCode = (error as NodeJS.ErrnoException).code;
if (maybeCode === "ENOENT") {
return new Error(`Command not found: ${command}`);
}
return new Error(
`Failed to run ${commandLabel(command, args)}: ${error.message}`,
);
}
function normalizeExitError(
command: string,
args: readonly string[],
result: ProcessRunResult,
): Error {
const reason = result.timedOut
? "timed out"
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
const stderr = result.stderr.trim();
const detail = stderr.length > 0 ? ` ${stderr}` : "";
return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
}
function normalizeStdinError(
command: string,
args: readonly string[],
error: unknown,
): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to write stdin for ${commandLabel(command, args)}.`);
}
return new Error(
`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`,
);
}
function normalizeBufferError(
command: string,
args: readonly string[],
stream: "stdout" | "stderr",
maxBufferBytes: number,
): Error {
return new Error(
`${commandLabel(command, args)} exceeded ${stream} buffer limit (${maxBufferBytes} bytes).`,
);
}
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
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,
};
}
export async function runProcess(
command: string,
args: readonly string[],
options: ProcessRunOptions = {},
): Promise<ProcessRunResult> {
const timeoutMs = options.timeoutMs ?? 60_000;
const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
const outputMode = options.outputMode ?? "error";
return new Promise<ProcessRunResult>((resolve, reject) => {
const child = spawn(command, args, {
cwd: options.cwd,
env: options.env,
stdio: "pipe",
});
let stdout = "";
let stderr = "";
let stdoutBytes = 0;
let stderrBytes = 0;
let stdoutTruncated = false;
let stderrTruncated = false;
let timedOut = false;
let settled = false;
let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
const timeoutTimer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
forceKillTimer = setTimeout(() => {
child.kill("SIGKILL");
}, 1_000);
}, timeoutMs);
const finalize = (callback: () => void): void => {
if (settled) return;
settled = true;
clearTimeout(timeoutTimer);
if (forceKillTimer) {
clearTimeout(forceKillTimer);
}
callback();
};
const fail = (error: Error): void => {
child.kill("SIGTERM");
finalize(() => {
reject(error);
});
};
const appendOutput = (
stream: "stdout" | "stderr",
chunk: Buffer | string,
): Error | null => {
const chunkBuffer =
typeof chunk === "string" ? Buffer.from(chunk) : chunk;
const text = chunkBuffer.toString();
const byteLength = chunkBuffer.length;
if (stream === "stdout") {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(
stdout,
stdoutBytes,
chunkBuffer,
maxBufferBytes,
);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
stdoutTruncated = stdoutTruncated || appended.truncated;
return null;
}
stdout += text;
stdoutBytes += byteLength;
if (stdoutBytes > maxBufferBytes) {
return normalizeBufferError(command, args, "stdout", maxBufferBytes);
}
} else {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(
stderr,
stderrBytes,
chunkBuffer,
maxBufferBytes,
);
stderr = appended.next;
stderrBytes = appended.nextBytes;
stderrTruncated = stderrTruncated || appended.truncated;
return null;
}
stderr += text;
stderrBytes += byteLength;
if (stderrBytes > maxBufferBytes) {
return normalizeBufferError(command, args, "stderr", maxBufferBytes);
}
}
return null;
};
child.stdout.on("data", (chunk: Buffer | string) => {
const error = appendOutput("stdout", chunk);
if (error) {
fail(error);
}
});
child.stderr.on("data", (chunk: Buffer | string) => {
const error = appendOutput("stderr", chunk);
if (error) {
fail(error);
}
});
child.once("error", (error) => {
finalize(() => {
reject(normalizeSpawnError(command, args, error));
});
});
child.once("close", (code, signal) => {
const result: ProcessRunResult = {
stdout,
stderr,
code,
signal,
timedOut,
stdoutTruncated,
stderrTruncated,
};
finalize(() => {
if (
!options.allowNonZeroExit &&
(timedOut || (code !== null && code !== 0))
) {
reject(normalizeExitError(command, args, result));
return;
}
resolve(result);
});
});
child.stdin.once("error", (error) => {
fail(normalizeStdinError(command, args, error));
});
if (options.stdin !== undefined) {
child.stdin.write(options.stdin, (error) => {
if (error) {
fail(normalizeStdinError(command, args, error));
return;
}
child.stdin.end();
});
return;
}
child.stdin.end();
});
}
+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);
}
}
@@ -16,7 +16,7 @@ import {
providerSendTurnInputSchema,
providerSessionStartInputSchema,
providerStopSessionInputSchema,
} from "@acme/contracts";
} from "@t3tools/contracts";
import { CodexAppServerManager } from "./codexAppServerManager";
export interface ProviderManagerEvents {
+54
View File
@@ -0,0 +1,54 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { ensureNodePtySpawnHelperExecutable } from "./ptyAdapter";
function fileMode(filePath: string): number {
return fs.statSync(filePath).mode & 0o777;
}
describe("ensureNodePtySpawnHelperExecutable", () => {
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("adds executable bits when helper exists but is not executable", () => {
if (process.platform === "win32") return;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pty-helper-test-"));
tempDirs.push(dir);
const helperPath = path.join(dir, "spawn-helper");
fs.writeFileSync(helperPath, "#!/bin/sh\nexit 0\n", "utf8");
fs.chmodSync(helperPath, 0o644);
ensureNodePtySpawnHelperExecutable(helperPath);
expect(fileMode(helperPath) & 0o111).toBe(0o111);
});
it("keeps executable helper as executable", () => {
if (process.platform === "win32") return;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pty-helper-test-"));
tempDirs.push(dir);
const helperPath = path.join(dir, "spawn-helper");
fs.writeFileSync(helperPath, "#!/bin/sh\nexit 0\n", "utf8");
fs.chmodSync(helperPath, 0o755);
ensureNodePtySpawnHelperExecutable(helperPath);
expect(fileMode(helperPath) & 0o111).toBe(0o111);
});
it("does not throw when helper path is missing", () => {
const missing = path.join(os.tmpdir(), `does-not-exist-${Date.now()}`);
expect(() => ensureNodePtySpawnHelperExecutable(missing)).not.toThrow();
});
});
+138
View File
@@ -0,0 +1,138 @@
import fs from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
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;
}
const requireForNodePty = createRequire(import.meta.url);
let didEnsureSpawnHelperExecutable = false;
function resolveNodePtySpawnHelperPath(): string | null {
try {
const packageJsonPath = requireForNodePty.resolve("node-pty/package.json");
const packageDir = path.dirname(packageJsonPath);
const candidates = [
path.join(packageDir, "build", "Release", "spawn-helper"),
path.join(packageDir, "build", "Debug", "spawn-helper"),
path.join(
packageDir,
"prebuilds",
`${process.platform}-${process.arch}`,
"spawn-helper",
),
];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
return candidate;
}
}
return null;
} catch {
return null;
}
}
export function ensureNodePtySpawnHelperExecutable(explicitPath?: string): void {
if (process.platform === "win32") return;
if (!explicitPath && didEnsureSpawnHelperExecutable) return;
const helperPath = explicitPath ?? resolveNodePtySpawnHelperPath();
if (!helperPath) return;
if (!explicitPath) {
didEnsureSpawnHelperExecutable = true;
}
try {
const stat = fs.statSync(helperPath);
const mode = stat.mode & 0o777;
if ((mode & 0o111) === 0) {
fs.chmodSync(helperPath, mode | 0o111);
}
} catch {
// Best effort only. If chmod fails, node-pty spawn will surface the real error.
}
}
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 {
ensureNodePtySpawnHelperExecutable();
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);
}
}
+308
View File
@@ -0,0 +1,308 @@
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[] = [];
readonly spawnFailures: Error[] = [];
private nextPid = 9000;
spawn(input: PtySpawnInput): PtyProcess {
this.spawnInputs.push(input);
const failure = this.spawnFailures.shift();
if (failure) {
throw failure;
}
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,
options: { shellResolver?: () => string } = {},
) {
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: options.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();
});
it("retries with fallback shells when preferred shell spawn fails", async () => {
const { manager, ptyAdapter } = makeManager(5, {
shellResolver: () => "/definitely/missing-shell -l",
});
ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed."));
const snapshot = await manager.open(openInput());
expect(snapshot.status).toBe("running");
expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2);
expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell");
if (process.platform === "win32") {
expect(
ptyAdapter.spawnInputs.some(
(input) => input.shell === "cmd.exe" || input.shell === "powershell.exe",
),
).toBe(true);
} else {
expect(
ptyAdapter.spawnInputs.some((input) =>
["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(
input.shell,
),
),
).toBe(true);
}
manager.dispose();
});
});
+656
View File
@@ -0,0 +1,656 @@
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 normalizeShellCommand(value: string | undefined): string | null {
if (!value) return null;
const trimmed = value.trim();
if (trimmed.length === 0) return null;
if (process.platform === "win32") {
return trimmed;
}
const firstToken = trimmed.split(/\s+/g)[0]?.trim();
if (!firstToken) return null;
return firstToken.replace(/^['"]|['"]$/g, "");
}
function uniqueShells(shells: Array<string | null>): string[] {
const seen = new Set<string>();
const ordered: string[] = [];
for (const shell of shells) {
if (!shell || shell.length === 0) continue;
if (seen.has(shell)) continue;
seen.add(shell);
ordered.push(shell);
}
return ordered;
}
function resolveShellCandidates(shellResolver: () => string): string[] {
const requested = normalizeShellCommand(shellResolver());
if (process.platform === "win32") {
return uniqueShells([
requested,
process.env.ComSpec ?? null,
"powershell.exe",
"cmd.exe",
]);
}
return uniqueShells([
requested,
normalizeShellCommand(process.env.SHELL),
"/bin/zsh",
"/bin/bash",
"/bin/sh",
"zsh",
"bash",
"sh",
]);
}
function isRetryableShellSpawnError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const message = error.message.toLowerCase();
return (
message.includes("posix_spawnp failed") ||
message.includes("enoent") ||
message.includes("not found") ||
message.includes("file not found") ||
message.includes("no such file")
);
}
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();
let ptyProcess: PtyProcess | null = null;
let startedShell: string | null = null;
try {
const shellCandidates = resolveShellCandidates(this.shellResolver);
let lastSpawnError: unknown = null;
for (const shell of shellCandidates) {
try {
ptyProcess = this.ptyAdapter.spawn({
shell,
cwd: session.cwd,
cols: session.cols,
rows: session.rows,
env: process.env,
});
startedShell = shell;
break;
} catch (error) {
lastSpawnError = error;
if (!isRetryableShellSpawnError(error)) {
throw error;
}
}
}
if (!ptyProcess) {
const detail =
lastSpawnError instanceof Error
? lastSpawnError.message
: "Terminal start failed";
const tried =
shellCandidates.length > 0
? ` Tried shells: ${shellCandidates.join(", ")}.`
: "";
throw new Error(`${detail}.${tried}`.trim());
}
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,
...(startedShell ? { shell: startedShell } : {}),
});
}
}
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);
}
}
}
}
+648
View File
@@ -0,0 +1,648 @@
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 "@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[];
waiters: Array<(message: unknown) => void>;
}
const pendingBySocket = new WeakMap<WebSocket, PendingMessages>();
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 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);
ws.on("message", (raw) => {
const parsed = JSON.parse(String(raw));
const waiter = pending.waiters.shift();
if (waiter) {
waiter(parsed);
return;
}
pending.queue.push(parsed);
});
ws.once("open", () => resolve(ws));
ws.once("error", () => reject(new Error("WebSocket connection failed")));
});
}
function waitForMessage(ws: WebSocket): Promise<unknown> {
const pending = pendingBySocket.get(ws);
if (!pending) {
return Promise.reject(new Error("WebSocket not initialized"));
}
const queued = pending.queue.shift();
if (queued !== undefined) {
return Promise.resolve(queued);
}
return new Promise((resolve) => {
pending.waiters.push(resolve);
});
}
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);
// Wait for response with matching id
while (true) {
const parsed = (await waitForMessage(ws)) as Record<string, unknown>;
if (parsed.id === id) {
return parsed as WsResponse;
}
}
}
describe("WebSocket Server", () => {
let server: ReturnType<typeof createServer> | null = null;
const connections: WebSocket[] = [];
const tempDirs: string[] = [];
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;
gitManager?: {
status: (input: { cwd: string }) => Promise<unknown>;
runStackedAction: (input: { cwd: string; action: string }) => Promise<unknown>;
};
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.gitManager ? { gitManager: options.gitManager as never } : {}),
...(options.terminalManager
? { terminalManager: options.terminalManager }
: {}),
});
}
afterEach(async () => {
for (const ws of connections) {
ws.close();
}
connections.length = 0;
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 = createTestServer({ cwd: "/test/project" });
// Get the actual port after listen
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const ws = await connectWs(port);
connections.push(ws);
const message = (await waitForMessage(ws)) as WsPush;
expect(message.type).toBe("push");
expect(message.channel).toBe(WS_CHANNELS.serverWelcome);
expect(message.data).toEqual({
cwd: "/test/project",
projectName: "project",
});
});
it("logs outbound websocket push events in dev mode", async () => {
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {
// Keep test output clean while verifying websocket logs.
});
server = createTestServer({
cwd: "/test/project",
devUrl: "http://localhost:5173",
});
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
expect(
logSpy.mock.calls.some(([message]) => {
if (typeof message !== "string") return false;
return (
message.includes("[ws]") &&
message.includes("outgoing push") &&
message.includes(`channel="${WS_CHANNELS.serverWelcome}"`)
);
}),
).toBe(true);
});
it("responds to server.getConfig", async () => {
server = createTestServer({ cwd: "/my/workspace" });
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);
// Consume welcome message
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({ cwd: "/my/workspace" });
});
it("returns error for unknown methods", 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);
// Consume welcome
await waitForMessage(ws);
const response = await sendRequest(ws, "nonexistent.method");
expect(response.error).toBeDefined();
expect(response.error!.message).toContain("Unknown method");
});
it("responds to providers.listSessions with empty array", 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);
// Consume welcome
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.providersListSessions);
expect(response.error).toBeUndefined();
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 = 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);
// Consume welcome
await waitForMessage(ws);
// Send garbage
ws.send("not json at all");
const response = (await waitForMessage(ws)) as WsResponse;
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("responds to git.status via the git manager", async () => {
const gitManager = {
status: vi.fn().mockResolvedValue({
branch: "feature/test",
hasWorkingTreeChanges: true,
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
openPr: null,
}),
runStackedAction: vi.fn(),
};
server = createTestServer({ cwd: "/test", gitManager });
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.gitStatus, {
cwd: "/test",
});
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
branch: "feature/test",
hasWorkingTreeChanges: true,
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
openPr: null,
});
expect(gitManager.status).toHaveBeenCalledWith({ cwd: "/test" });
});
it("returns errors from git.runStackedAction", async () => {
const gitManager = {
status: vi.fn(),
runStackedAction: vi
.fn()
.mockRejectedValue(new Error("Cannot push from detached HEAD.")),
};
server = createTestServer({ cwd: "/test", gitManager });
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.gitRunStackedAction, {
cwd: "/test",
action: "commit_push",
});
expect(response.result).toBeUndefined();
expect(response.error?.message).toContain("detached HEAD");
expect(gitManager.runStackedAction).toHaveBeenCalledWith({
cwd: "/test",
action: "commit_push",
});
});
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);
});
});
+458
View File
@@ -0,0 +1,458 @@
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 "@t3tools/contracts";
import { WebSocketServer, type WebSocket } from "ws";
import { createLogger } from "./logger";
import { ProjectRegistry } from "./projectRegistry";
import { ProviderManager } from "./providerManager";
import { GitManager } from "./gitManager";
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",
".js": "application/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".png": "image/png",
".jpg": "image/jpeg",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".map": "application/json",
};
export interface ServerOptions {
port: number;
host?: string | undefined;
cwd: string;
staticDir?: string | undefined;
devUrl?: string | undefined;
logWebSocketEvents?: boolean | undefined;
projectRegistry?: ProjectRegistry | undefined;
gitManager?: GitManager | undefined;
terminalManager?: TerminalManager | undefined;
authToken?: string | undefined;
}
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;
}
export function createServer(options: ServerOptions) {
const {
port,
host,
cwd,
staticDir,
devUrl,
logWebSocketEvents: explicitLogWsEvents,
projectRegistry: providedRegistry,
gitManager: providedGitManager,
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 gitManager = providedGitManager ?? new GitManager();
const clients = new Set<WebSocket>();
const logger = createLogger("ws");
const logWebSocketEvents =
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
function logOutgoingPush(push: WsPush, recipients: number) {
if (!logWebSocketEvents) return;
logger.event("outgoing push", {
channel: push.channel,
recipients,
payload: push.data,
});
}
// Forward provider events to all connected WebSocket clients
providerManager.on("event", (event) => {
const push: WsPush = {
type: "push",
channel: WS_CHANNELS.providerEvent,
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);
});
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
if (devUrl) {
res.writeHead(302, { Location: devUrl });
res.end();
return;
}
// 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.");
return;
}
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
let filePath = path.join(staticDir, url.pathname);
// SPA fallback: if no file extension and not found, serve index.html
const ext = path.extname(filePath);
if (!ext) {
filePath = path.join(filePath, "index.html");
}
fs.stat(filePath, (err, stats) => {
if (err || !stats?.isFile()) {
// SPA fallback
const indexPath = path.join(staticDir, "index.html");
fs.readFile(indexPath, (readErr, data) => {
if (readErr) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
return;
}
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(data);
});
return;
}
const fileExt = path.extname(filePath);
const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream";
fs.readFile(filePath, (readErr, data) => {
if (readErr) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Internal Server Error");
return;
}
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
});
});
});
// WebSocket server — upgrades from the HTTP server
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);
// Send welcome message with project info
const segments = cwd.split(/[/\\]/).filter(Boolean);
const projectName = segments[segments.length - 1] ?? "project";
const welcome: WsPush = {
type: "push",
channel: WS_CHANNELS.serverWelcome,
data: { cwd, projectName },
};
logOutgoingPush(welcome, 1);
ws.send(JSON.stringify(welcome));
ws.on("message", (raw) => {
void handleMessage(ws, raw);
});
ws.on("close", () => {
clients.delete(ws);
});
ws.on("error", () => {
clients.delete(ws);
});
});
async function handleMessage(ws: WebSocket, raw: unknown) {
let request: WsRequest;
try {
const parsed = JSON.parse(String(raw));
request = wsRequestSchema.parse(parsed);
} catch {
const errorResponse: WsResponse = {
id: "unknown",
error: { message: "Invalid request format" },
};
ws.send(JSON.stringify(errorResponse));
return;
}
try {
const result = await routeRequest(request);
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 response: WsResponse = {
id: request.id,
error: { message },
};
ws.send(JSON.stringify(response));
}
}
async function routeRequest(request: WsRequest): Promise<unknown> {
switch (request.method) {
case WS_METHODS.providersStartSession:
return providerManager.startSession(request.params as never);
case WS_METHODS.providersSendTurn:
return providerManager.sendTurn(request.params as never);
case WS_METHODS.providersInterruptTurn:
return providerManager.interruptTurn(request.params as never);
case WS_METHODS.providersRespondToRequest:
return providerManager.respondToRequest(request.params as never);
case WS_METHODS.providersStopSession: {
providerManager.stopSession(request.params as never);
return undefined;
}
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;
editor: string;
};
if (!params?.cwd) throw new Error("cwd is required");
const editorDef = EDITORS.find((e) => e.id === params.editor);
if (!editorDef) throw new Error(`Unknown editor: ${params.editor}`);
if (!editorDef.command) {
// Can't open file manager programmatically from server, just succeed silently
return undefined;
}
const child = spawn(editorDef.command, [params.cwd], {
detached: true,
stdio: "ignore",
});
child.on("error", () => {
/* ignore spawn failures for detached editors */
});
child.unref();
return undefined;
}
case WS_METHODS.gitStatus:
return gitManager.status(request.params as never);
case WS_METHODS.gitRunStackedAction:
return gitManager.runStackedAction(request.params as never);
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 };
default:
throw new Error(`Unknown method: ${request.method}`);
}
}
function start() {
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);
});
}
async function stop(): Promise<void> {
terminalManager.off("event", onTerminalEvent);
providerManager.stopAll();
providerManager.dispose();
terminalManager.dispose();
for (const client of clients) {
client.close();
}
clients.clear();
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 };
}
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"types": ["node"],
"lib": ["ES2023", "esnext.disposable"]
},
"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",
},
});
+11
View File
@@ -0,0 +1,11 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"start": {
"dependsOn": ["build"],
"cache": false,
"persistent": true,
},
},
}
-28
View File
@@ -1,28 +0,0 @@
{
"name": "@acme/t3-runtime",
"version": "0.0.0",
"private": true,
"bin": {
"t3": "dist/cli.js"
},
"type": "module",
"scripts": {
"dev": "tsx src/cli.ts",
"build": "tsup --config tsup.config.ts",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@acme/contracts": "workspace:*",
"@acme/runtime-core": "workspace:*",
"ws": "^8.18.0"
},
"devDependencies": {
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsup": "^8.3.5",
"tsx": "^4.20.3",
"typescript": "^5.7.3"
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-1175
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-818
View File
@@ -1,818 +0,0 @@
import { spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { WebSocket, WebSocketServer, type RawData } from "ws";
import {
EDITORS,
DEFAULT_MODEL,
appBootstrapResultSchema,
appHealthResultSchema,
dialogsPickFolderResultSchema,
type ProviderSession,
type WsClientMessage,
type WsResponseMessage,
type WsServerMessage,
WS_EVENT_CHANNELS,
WS_ERROR_CODE_MAX_CHARS,
WS_ERROR_MESSAGE_MAX_CHARS,
WS_CLOSE_CODES,
WS_CLOSE_REASONS,
agentConfigSchema,
agentSessionIdSchema,
agentWriteInputSchema,
newTodoInputSchema,
todoIdSchema,
providerInterruptTurnInputSchema,
providerRespondToRequestInputSchema,
providerSendTurnInputSchema,
providerSessionListSchema,
providerSessionStartInputSchema,
providerSessionSchema,
providerStopSessionInputSchema,
providerTurnStartResultSchema,
type TerminalCommandInput,
shellOpenInEditorInputSchema,
terminalCommandResultSchema,
terminalCommandInputSchema,
todoListSchema,
wsClientMessageSchema,
wsNativeApiMethodSchema,
wsServerMessageSchema,
} from "@acme/contracts";
import { ProcessManager, ProviderManager, TodoStore } from "@acme/runtime-core";
interface RuntimeApiServerOptions {
port: number;
launchCwd: string;
bootstrapSessionTimeoutMs?: number;
authToken?: string;
}
interface RuntimeApiServer {
wsUrl: string;
close: () => Promise<void>;
}
interface JsonRpcErrorResult {
code: string;
message: string;
}
const BOOTSTRAP_SESSION_TIMEOUT_MS = 3_000;
const MAX_BOOTSTRAP_SESSION_TIMEOUT_MS = 120_000;
const MAX_WS_CLIENT_PAYLOAD_BYTES = 5 * 1024 * 1024;
const MAX_ERROR_PATH_CHARS = 2_048;
interface BootstrapSessionResult {
session: ProviderSession;
bootstrapError: string | undefined;
}
type WsServerEventMessage = Extract<WsServerMessage, { type: "event" }>;
function raceWithTimeout<T>(
promise: Promise<T>,
timeoutMs: number,
timeoutMessage: string,
): Promise<T> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(timeoutMessage));
}, timeoutMs);
timeout.unref();
promise.then(
(value) => {
clearTimeout(timeout);
resolve(value);
},
(error) => {
clearTimeout(timeout);
reject(error);
},
);
});
}
function responseSuccess(id: string, result: unknown): WsResponseMessage {
return {
type: "response",
id,
ok: true,
result: result === undefined ? null : result,
};
}
function responseError(id: string, error: JsonRpcErrorResult): WsResponseMessage {
const normalizedCode = normalizeErrorField(
error.code,
"request_failed",
WS_ERROR_CODE_MAX_CHARS,
);
const normalizedMessage = normalizeErrorField(
error.message,
"Request failed",
WS_ERROR_MESSAGE_MAX_CHARS,
);
return {
type: "response",
id,
ok: false,
error: {
code: normalizedCode,
message: normalizedMessage,
},
};
}
function normalizeErrorField(value: string, fallback: string, maxChars: number): string {
const trimmed = value.trim();
const safeValue = trimmed.length > 0 ? trimmed : fallback;
if (safeValue.length <= maxChars) {
return safeValue;
}
if (maxChars <= 1) {
return safeValue.slice(0, maxChars);
}
return `${safeValue.slice(0, maxChars - 1)}…`;
}
function summarizePathForError(candidatePath: string): string {
if (candidatePath.length <= MAX_ERROR_PATH_CHARS) {
return candidatePath;
}
const prefixLength = Math.floor((MAX_ERROR_PATH_CHARS - 1) / 2);
const suffixLength = MAX_ERROR_PATH_CHARS - 1 - prefixLength;
return `${candidatePath.slice(0, prefixLength)}…${candidatePath.slice(-suffixLength)}`;
}
function sendMessage(socket: WebSocket, message: unknown): void {
if (socket.readyState !== WebSocket.OPEN) {
return;
}
const parsedMessage = wsServerMessageSchema.safeParse(message);
if (!parsedMessage.success) {
return;
}
try {
socket.send(JSON.stringify(parsedMessage.data));
} catch {
// Best-effort event delivery. Socket may have transitioned states.
}
}
function decodeClientMessage(raw: RawData): string | null {
if (typeof raw === "string") {
return raw;
}
if (raw instanceof Buffer) {
return raw.toString("utf8");
}
if (raw instanceof ArrayBuffer) {
return Buffer.from(raw).toString("utf8");
}
if (Array.isArray(raw)) {
return Buffer.concat(raw).toString("utf8");
}
return null;
}
function openPathInFileManager(targetPath: string): void {
const command =
process.platform === "win32" ? "explorer" : process.platform === "darwin" ? "open" : "xdg-open";
const child = spawn(command, [targetPath], {
detached: true,
stdio: "ignore",
});
child.on("error", () => {
// Best-effort shell handoff.
});
child.unref();
}
async function tryCommand(command: string, args: string[]): Promise<string | null> {
return new Promise((resolve) => {
const child = spawn(command, args, {
stdio: ["ignore", "pipe", "ignore"],
});
let output = "";
child.stdout.on("data", (chunk: Buffer) => {
output += chunk.toString();
});
child.on("error", () => {
resolve(null);
});
child.on("close", (code) => {
if (code !== 0) {
resolve(null);
return;
}
const trimmed = output.trim();
resolve(trimmed.length > 0 ? trimmed : null);
});
});
}
async function pickFolder(): Promise<string | null> {
if (process.platform === "darwin") {
const script =
'try\nset selectedFolder to POSIX path of (choose folder with prompt "Choose a project folder")\nreturn selectedFolder\non error\nreturn ""\nend try';
const result = await tryCommand("osascript", ["-e", script]);
return result && result.length > 0 ? result : null;
}
if (process.platform === "win32") {
const powershellScript = [
"Add-Type -AssemblyName System.Windows.Forms",
"$dialog = New-Object System.Windows.Forms.FolderBrowserDialog",
'$dialog.Description = "Choose a project folder"',
"if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {",
" Write-Output $dialog.SelectedPath",
"}",
].join("; ");
const result = await tryCommand("powershell", ["-NoProfile", "-Command", powershellScript]);
return result && result.length > 0 ? result : null;
}
const zenity = await tryCommand("zenity", ["--file-selection", "--directory"]);
if (zenity) {
return zenity;
}
const kdialog = await tryCommand("kdialog", ["--getexistingdirectory"]);
if (kdialog) {
return kdialog;
}
return null;
}
async function runTerminalCommand(
parsed: TerminalCommandInput,
defaultCwd: string,
) {
const providedCwd = parsed.cwd ?? defaultCwd;
const resolvedCwd = resolveExistingDirectoryFromBase(
providedCwd,
"Working directory",
defaultCwd,
);
const shellPath =
process.platform === "win32"
? (process.env.ComSpec ?? "cmd.exe")
: (process.env.SHELL ?? "/bin/sh");
const args =
process.platform === "win32" ? ["/d", "/s", "/c", parsed.command] : ["-lc", parsed.command];
return new Promise<{
stdout: string;
stderr: string;
code: number | null;
signal: string | null;
timedOut: boolean;
}>((resolve, reject) => {
const child = spawn(shellPath, args, {
cwd: resolvedCwd,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let timedOut = false;
const timeout = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) {
child.kill("SIGKILL");
}
}, 1_000).unref();
}, parsed.timeoutMs ?? 30_000);
timeout.unref();
child.stdout?.on("data", (chunk: Buffer) => {
stdout += chunk.toString();
});
child.stderr?.on("data", (chunk: Buffer) => {
stderr += chunk.toString();
});
child.on("error", (error) => {
clearTimeout(timeout);
reject(error);
});
child.on("close", (code, signal) => {
clearTimeout(timeout);
resolve({
stdout,
stderr,
code: code ?? null,
signal: signal ?? null,
timedOut,
});
});
});
}
function resolveExistingDirectory(targetPath: string, label: string): string {
if (typeof targetPath !== "string" || targetPath.trim().length === 0) {
throw new Error(`${label} must be a non-empty path.`);
}
const candidate = path.resolve(targetPath);
let stats: fs.Stats;
try {
stats = fs.statSync(candidate);
} catch (error) {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
const safeCandidate = summarizePathForError(candidate);
if (code && code !== "ENOENT") {
throw new Error(`Failed to access ${label.toLowerCase()}: ${safeCandidate} (${code})`, {
cause: error,
});
}
throw new Error(`${label} does not exist: ${safeCandidate}`, {
cause: error,
});
}
if (!stats.isDirectory()) {
throw new Error(`${label} is not a directory: ${summarizePathForError(candidate)}`);
}
return candidate;
}
function resolveExistingDirectoryFromBase(
targetPath: string,
label: string,
baseDirectory: string,
): string {
if (typeof targetPath !== "string" || targetPath.trim().length === 0) {
throw new Error(`${label} must be a non-empty path.`);
}
const candidate = path.isAbsolute(targetPath)
? path.resolve(targetPath)
: path.resolve(baseDirectory, targetPath);
return resolveExistingDirectory(candidate, label);
}
export async function startRuntimeApiServer(
options: RuntimeApiServerOptions,
): Promise<RuntimeApiServer> {
if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65_535) {
throw new Error("Invalid runtime port: expected integer between 0 and 65535.");
}
const launchCwd = resolveExistingDirectory(options.launchCwd, "Invalid launchCwd");
if (options.authToken !== undefined && typeof options.authToken !== "string") {
throw new Error("Invalid runtime auth token: expected non-empty string.");
}
const authToken = options.authToken?.trim();
if (options.authToken !== undefined && !authToken) {
throw new Error("Invalid runtime auth token: expected non-empty string.");
}
const bootstrapSessionTimeoutMs =
options.bootstrapSessionTimeoutMs ?? BOOTSTRAP_SESSION_TIMEOUT_MS;
if (
!Number.isInteger(bootstrapSessionTimeoutMs) ||
bootstrapSessionTimeoutMs <= 0 ||
bootstrapSessionTimeoutMs > MAX_BOOTSTRAP_SESSION_TIMEOUT_MS
) {
throw new Error(
`Invalid bootstrapSessionTimeoutMs: expected integer between 1 and ${MAX_BOOTSTRAP_SESSION_TIMEOUT_MS}.`,
);
}
const providerManager = new ProviderManager();
const processManager = new ProcessManager();
const todoStore = new TodoStore(path.join(os.homedir(), ".t3", "todos.json"));
await todoStore.init();
let activeClient: WebSocket | null = null;
let launchSessionPromise: Promise<BootstrapSessionResult> | null = null;
let bootstrapFallbackSession: ProviderSession | null = null;
const emitEvent = <TChannel extends WsServerEventMessage["channel"]>(
channel: TChannel,
payload: Extract<WsServerEventMessage, { channel: TChannel }>["payload"],
) => {
if (!activeClient) {
return;
}
sendMessage(activeClient, {
type: "event",
channel,
payload,
});
};
processManager.on("output", (chunk) => {
emitEvent(WS_EVENT_CHANNELS.agentOutput, chunk);
});
processManager.on("exit", (payload) => {
emitEvent(WS_EVENT_CHANNELS.agentExit, payload);
});
providerManager.on("event", (payload) => {
emitEvent(WS_EVENT_CHANNELS.providerEvent, payload);
});
const createBootstrapErrorSession = (message: string): ProviderSession => {
const timestamp = new Date().toISOString();
return {
sessionId: `bootstrap-error-${Date.now()}`,
provider: "codex",
status: "error",
cwd: launchCwd,
model: DEFAULT_MODEL,
createdAt: timestamp,
updatedAt: timestamp,
lastError: message,
};
};
const ensureLaunchSession = async (): Promise<BootstrapSessionResult> => {
const isLaunchProjectSession = (session: ProviderSession) => {
if (!session.cwd) {
return false;
}
return path.resolve(session.cwd) === launchCwd;
};
const existingSession = providerManager
.listSessions()
.find((session) => isLaunchProjectSession(session) && session.status !== "closed");
if (existingSession) {
bootstrapFallbackSession = null;
return {
session: existingSession,
bootstrapError: undefined,
};
}
if (bootstrapFallbackSession) {
return {
session: bootstrapFallbackSession,
bootstrapError: bootstrapFallbackSession.lastError,
};
}
if (launchSessionPromise) {
return launchSessionPromise;
}
launchSessionPromise = (async () => {
try {
const startedSession = await raceWithTimeout(
providerManager.startSession({
provider: "codex",
cwd: launchCwd,
model: DEFAULT_MODEL,
approvalPolicy: "never",
sandboxMode: "danger-full-access",
}),
bootstrapSessionTimeoutMs,
"Timed out starting launch session.",
);
bootstrapFallbackSession = null;
return {
session: startedSession,
bootstrapError: undefined,
};
} catch (error) {
const message =
error instanceof Error
? error.message
: "Failed to initialize Codex launch session.";
const fallbackSession = (() => {
if (!bootstrapFallbackSession) {
return createBootstrapErrorSession(message);
}
return Object.assign({}, bootstrapFallbackSession, {
lastError: message,
updatedAt: new Date().toISOString(),
}) as ProviderSession;
})();
bootstrapFallbackSession = fallbackSession;
return {
session: fallbackSession,
bootstrapError: message,
};
} finally {
launchSessionPromise = null;
}
})();
const pendingLaunchSessionPromise = launchSessionPromise;
if (!pendingLaunchSessionPromise) {
throw new Error("Could not initialize launch session promise.");
}
return pendingLaunchSessionPromise;
};
const wss = new WebSocketServer({
host: "127.0.0.1",
port: options.port,
maxPayload: MAX_WS_CLIENT_PAYLOAD_BYTES,
perMessageDeflate: false,
});
const isAuthorizedConnection = (requestUrl: string | undefined) => {
if (!requestUrl) {
return authToken === null;
}
try {
const request = new URL(requestUrl, "ws://127.0.0.1");
if (request.pathname !== "/") {
return false;
}
if (!authToken) {
return request.searchParams.size === 0;
}
const tokens = request.searchParams.getAll("token");
return (
request.searchParams.size === 1 &&
tokens.length === 1 &&
tokens[0] === authToken
);
} catch {
return false;
}
};
const resolveMethod = async (method: string, params: unknown) => {
const parsedMethod = wsNativeApiMethodSchema.safeParse(method);
if (!parsedMethod.success) {
throw new Error(`Unknown API method: ${method}`);
}
const apiMethod = parsedMethod.data;
switch (apiMethod) {
case "app.bootstrap": {
const bootstrap = await ensureLaunchSession();
const payload = {
launchCwd,
projectName: path.basename(launchCwd) || launchCwd,
provider: "codex",
model: bootstrap.session.model ?? DEFAULT_MODEL,
session: bootstrap.session,
...(bootstrap.bootstrapError
? { bootstrapError: bootstrap.bootstrapError }
: {}),
};
return appBootstrapResultSchema.parse(payload);
}
case "app.health": {
const payload = {
status: "ok",
launchCwd,
sessionCount: providerManager.listSessions().length,
activeClientConnected: activeClient !== null,
};
return appHealthResultSchema.parse(payload);
}
case "todos.list":
return todoListSchema.parse(await todoStore.list());
case "todos.add":
return todoListSchema.parse(await todoStore.add(newTodoInputSchema.parse(params)));
case "todos.toggle":
return todoListSchema.parse(await todoStore.toggle(todoIdSchema.parse(params)));
case "todos.remove":
return todoListSchema.parse(await todoStore.remove(todoIdSchema.parse(params)));
case "dialogs.pickFolder":
return dialogsPickFolderResultSchema.parse(await pickFolder());
case "terminal.run":
return terminalCommandResultSchema.parse(
await runTerminalCommand(terminalCommandInputSchema.parse(params), launchCwd),
);
case "agent.spawn":
return agentSessionIdSchema.parse(processManager.spawn(agentConfigSchema.parse(params)));
case "agent.kill":
processManager.kill(agentSessionIdSchema.parse(params));
return null;
case "agent.write": {
const parsed = agentWriteInputSchema.parse(params);
processManager.write(parsed.sessionId, parsed.data);
return null;
}
case "providers.startSession": {
const session = await providerManager.startSession(
providerSessionStartInputSchema.parse(params),
);
bootstrapFallbackSession = null;
return providerSessionSchema.parse(session);
}
case "providers.sendTurn":
return providerTurnStartResultSchema.parse(
await providerManager.sendTurn(providerSendTurnInputSchema.parse(params)),
);
case "providers.interruptTurn":
await providerManager.interruptTurn(providerInterruptTurnInputSchema.parse(params));
return null;
case "providers.respondToRequest":
await providerManager.respondToRequest(providerRespondToRequestInputSchema.parse(params));
return null;
case "providers.stopSession":
providerManager.stopSession(providerStopSessionInputSchema.parse(params));
return null;
case "providers.listSessions":
return providerSessionListSchema.parse(providerManager.listSessions());
case "shell.openInEditor": {
const parsed = shellOpenInEditorInputSchema.parse(params);
const targetPath = resolveExistingDirectoryFromBase(parsed.cwd, "Editor target", launchCwd);
const editor = EDITORS.find((entry) => entry.id === parsed.editor);
if (!editor) {
throw new Error(`Unknown editor: ${parsed.editor}`);
}
if (!editor.command) {
openPathInFileManager(targetPath);
return null;
}
const child = spawn(editor.command, [targetPath], {
detached: true,
stdio: "ignore",
});
child.on("error", () => {
// Best-effort editor launch.
});
child.unref();
return null;
}
default: {
const unreachableMethod: never = apiMethod;
throw new Error(`Unknown API method: ${unreachableMethod}`);
}
}
};
wss.on("connection", (socket, request) => {
if (!isAuthorizedConnection(request.url)) {
socket.close(WS_CLOSE_CODES.unauthorized, WS_CLOSE_REASONS.unauthorized);
return;
}
if (activeClient && activeClient !== socket) {
activeClient.close(
WS_CLOSE_CODES.replacedByNewClient,
WS_CLOSE_REASONS.replacedByNewClient,
);
}
activeClient = socket;
sendMessage(socket, {
type: "hello",
version: 1,
launchCwd,
});
socket.on("message", async (raw) => {
const decoded = decodeClientMessage(raw);
if (!decoded) {
return;
}
const maybeParsed = (() => {
try {
return JSON.parse(decoded) as unknown;
} catch {
return null;
}
})();
if (!maybeParsed) {
return;
}
const parsed = wsClientMessageSchema.safeParse(maybeParsed);
if (!parsed.success) {
return;
}
const message = parsed.data as WsClientMessage;
try {
const result = await resolveMethod(message.method, message.params);
sendMessage(socket, responseSuccess(message.id, result));
} catch (error) {
sendMessage(
socket,
responseError(message.id, {
code: "request_failed",
message: error instanceof Error ? error.message : "Request failed",
}),
);
}
});
socket.on("close", () => {
if (activeClient === socket) {
activeClient = null;
}
});
socket.on("error", () => {
// Connection-level protocol/socket errors are expected occasionally
// (for example oversized client payloads). Keep server process alive.
if (activeClient === socket && socket.readyState !== WebSocket.OPEN) {
activeClient = null;
}
});
});
try {
await new Promise<void>((resolve, reject) => {
if (wss.address()) {
resolve();
return;
}
const onListening = () => {
wss.off("error", onError);
resolve();
};
const onError = (error: Error) => {
wss.off("listening", onListening);
reject(error);
};
wss.once("listening", onListening);
wss.once("error", onError);
});
} catch (error) {
processManager.killAll();
providerManager.stopAll();
providerManager.dispose();
await new Promise<void>((resolve) => {
try {
wss.close(() => resolve());
} catch {
resolve();
}
});
throw error;
}
const address = wss.address();
const resolvedPort =
typeof address === "object" && address !== null ? address.port : options.port;
const wsBaseUrl = `ws://127.0.0.1:${resolvedPort}`;
const wsUrl = authToken
? `${wsBaseUrl}?token=${encodeURIComponent(authToken)}`
: wsBaseUrl;
let closePromise: Promise<void> | null = null;
return {
wsUrl,
close() {
if (closePromise) {
return closePromise;
}
closePromise = (async () => {
processManager.killAll();
providerManager.stopAll();
providerManager.dispose();
activeClient = null;
for (const client of wss.clients) {
client.terminate();
}
await new Promise<void>((resolve) => {
wss.close(() => resolve());
});
})();
return closePromise;
},
};
}
-56
View File
@@ -1,56 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
const RUNTIME_SOURCE_FILES = ["cli.ts", "runtimeApiServer.ts"] as const;
describe("runtime architecture boundaries", () => {
it("keeps runtime API server wired through runtime-core services", () => {
const sourcePath = path.resolve(import.meta.dirname, "runtimeApiServer.ts");
const source = fs.readFileSync(sourcePath, "utf8");
expect(source).toContain("from \"@acme/runtime-core\"");
expect(source).toContain("ProcessManager");
expect(source).toContain("ProviderManager");
expect(source).toContain("TodoStore");
});
for (const fileName of RUNTIME_SOURCE_FILES) {
it(`avoids direct desktop service imports in ${fileName}`, () => {
const sourcePath = path.resolve(import.meta.dirname, fileName);
const source = fs.readFileSync(sourcePath, "utf8");
expect(source).not.toContain("../../desktop/src/");
});
}
it("does not rely on a legacy desktop workspace package", () => {
const legacyDesktopPackagePath = path.resolve(
import.meta.dirname,
"..",
"..",
"desktop",
"package.json",
);
expect(fs.existsSync(legacyDesktopPackagePath)).toBe(false);
});
it("keeps runtime-core bundled into published t3 runtime output", () => {
const tsupConfigPath = path.resolve(import.meta.dirname, "..", "tsup.config.ts");
const tsupConfigSource = fs.readFileSync(tsupConfigPath, "utf8");
expect(tsupConfigSource).toContain("\"@acme/runtime-core\"");
expect(tsupConfigSource).toContain("noExternal");
});
it("keeps smoke tests independent from real codex installation", () => {
const smokeScriptPath = path.resolve(import.meta.dirname, "..", "scripts", "smoke-test.mjs");
const smokeScriptSource = fs.readFileSync(smokeScriptPath, "utf8");
expect(smokeScriptSource).toContain("../../../test-support/fakeCodexAppServer.mjs");
expect(smokeScriptSource).toContain("createFakeCodexAppServerBinary");
expect(smokeScriptSource).toContain("PATH: `${fakeCodex.tempDir}${path.delimiter}");
expect(smokeScriptSource).toContain("fs.rmSync(fakeCodex.tempDir");
});
});
-7
View File
@@ -1,7 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src", "tsup.config.ts"]
}
-10
View File
@@ -1,10 +0,0 @@
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/cli.ts"],
format: ["esm"],
dts: true,
clean: true,
noExternal: ["@acme/contracts", "@acme/runtime-core"],
outDir: "dist",
});
+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"
}
}
+197
View File
@@ -0,0 +1,197 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useEffect, useRef } from "react";
import ChatView from "./components/ChatView";
import DiffPanel from "./components/DiffPanel";
import Sidebar from "./components/Sidebar";
import { isElectron } from "./env";
import { DEFAULT_MODEL } from "./model-logic";
import { StoreProvider, useStore } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types";
import { onServerWelcome } from "./wsNativeApi";
import { useNativeApi } from "./hooks/useNativeApi";
function EventRouter() {
const api = useNativeApi();
const { dispatch } = useStore();
const activeAssistantItemRef = useRef<string | null>(null);
useEffect(() => {
if (!api) return;
return api.providers.onEvent((event) => {
dispatch({
type: "APPLY_EVENT",
event,
activeAssistantItemRef,
});
});
}, [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;
}
function AutoProjectBootstrap() {
const { state, dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
// Browser mode bootstraps from server welcome.
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
if (isElectron) return;
return onServerWelcome((payload) => {
if (bootstrappedRef.current) return;
// Don't create duplicate projects for the same cwd
const existing = state.projects.find((p) => p.cwd === payload.cwd);
if (existing) {
bootstrappedRef.current = true;
// Ensure a thread is active
const existingThread = state.threads.find((t) => t.projectId === existing.id);
if (existingThread && !state.activeThreadId) {
dispatch({
type: "SET_ACTIVE_THREAD",
threadId: existingThread.id,
});
}
return;
}
bootstrappedRef.current = true;
// Create project + thread from server cwd
const projectId = crypto.randomUUID();
dispatch({
type: "ADD_PROJECT",
project: {
id: projectId,
name: payload.projectName,
cwd: payload.cwd,
model: DEFAULT_MODEL,
expanded: true,
},
});
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
codexThreadId: null,
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,
},
});
});
}, [state.projects, state.threads, state.activeThreadId, dispatch]);
return null;
}
function DesktopProjectBootstrap() {
const api = useNativeApi();
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 = useNativeApi();
const { state } = useStore();
if (!api) {
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 T3 Code server...</p>
</div>
</div>
);
}
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<EventRouter />
<AutoProjectBootstrap />
<DesktopProjectBootstrap />
<Sidebar />
<ChatView />
{state.diffOpen && <DiffPanel />}
</div>
);
}
const queryClient = new QueryClient();
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<StoreProvider>
<Layout />
</StoreProvider>
</QueryClientProvider>
);
}
+319
View File
@@ -0,0 +1,319 @@
import type { GitBranch } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef, useState } from "react";
import { useStore } from "../store";
import { useNativeApi } from "../hooks/useNativeApi";
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 = useNativeApi();
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>
);
}
File diff suppressed because it is too large. Load diff
@@ -1,3 +1,4 @@
import { isElectron } from "../env";
import { useStore } from "../store";
export default function DiffPanel() {
@@ -6,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="drag-region flex items-center justify-between border-b border-border px-4 pt-[28px] pb-3">
<div
className={`flex items-center justify-between border-b border-border px-4 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
>
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
<button
type="button"
@@ -0,0 +1,831 @@
import {
type GitRunStackedActionResult,
type GitStackedAction,
type GitStatusResult,
type NativeApi,
} from "@t3tools/contracts";
import { queryOptions, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
CheckIcon,
CircleIcon,
CloudUploadIcon,
GitCommitIcon,
Loader2Icon,
MinusIcon,
XIcon,
} from "lucide-react";
import { GitHubIcon } from "./Icons";
interface GitActionsControlProps {
api: NativeApi | undefined;
gitCwd: string | null;
}
type GitActionIconName = "commit" | "push" | "pr";
interface GitActionMenuItem {
id: "commit" | "push" | "pr";
label: string;
disabled: boolean;
icon: GitActionIconName;
kind: "open_modal" | "run_action" | "open_pr";
action?: GitStackedAction;
}
interface GitModalActionOption {
action: GitStackedAction;
label: string;
disabled: boolean;
icon: GitActionIconName;
detail?: string;
}
type GitProgressStepStatus = "pending" | "running" | "completed" | "skipped" | "failed";
interface GitProgressStep {
id: "generate" | "commit" | "push" | "pr";
label: string;
status: GitProgressStepStatus;
detail?: string;
}
function GitActionIcon(props: { icon: GitActionIconName; disabled: boolean }) {
const toneClass = props.disabled ? "text-muted-foreground/45" : "text-foreground/85";
if (props.icon === "commit") {
return <GitCommitIcon className={`h-5 w-5 shrink-0 ${toneClass}`} />;
}
if (props.icon === "push") {
return <CloudUploadIcon className={`h-5 w-5 shrink-0 ${toneClass}`} />;
}
return <GitHubIcon className={`h-5 w-5 shrink-0 ${toneClass}`} />;
}
function gitActionModalTitle(): string {
return "Commit your changes";
}
function initialGitProgressSteps(
action: GitStackedAction,
commitMessage: string,
): GitProgressStep[] {
const hasCustomMessage = commitMessage.trim().length > 0;
const steps: GitProgressStep[] = [];
if (!hasCustomMessage) {
steps.push({
id: "generate",
label: "Generate commit message",
status: "pending",
});
}
steps.push({
id: "commit",
label: "Commit changes",
status: "pending",
});
if (action !== "commit") {
steps.push({
id: "push",
label: "Push branch",
status: "pending",
});
}
if (action === "commit_push_pr") {
steps.push({
id: "pr",
label: "Create or open PR",
status: "pending",
});
}
return steps;
}
function updateProgressStep(
steps: GitProgressStep[],
id: GitProgressStep["id"],
status: GitProgressStepStatus,
detail?: string,
): GitProgressStep[] {
return steps.map((step) => {
if (step.id !== id) return step;
return {
...step,
status,
...(detail ? { detail } : {}),
};
});
}
function runActionLabel(action: GitStackedAction): string {
if (action === "commit") return "Commit changes";
if (action === "commit_push") return "Commit and push";
return "Commit and create PR";
}
function buildGitActionMenuItems(
gitStatus: GitStatusResult | null,
isDisabled: boolean,
): GitActionMenuItem[] {
if (!gitStatus) return [];
const hasBranch = gitStatus.branch !== null;
const hasOpenPr = gitStatus.openPr !== null;
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasAhead = gitStatus.aheadCount > 0;
const canCommit = !isDisabled && hasChanges;
const canPush = !isDisabled && hasBranch && !hasChanges && hasAhead;
const canOpenPr = !isDisabled && hasOpenPr;
const canCreatePr =
!isDisabled &&
hasBranch &&
!hasOpenPr &&
!hasChanges &&
gitStatus.hasUpstream &&
gitStatus.behindCount === 0;
return [
{
id: "commit",
label: "Commit",
disabled: !canCommit,
icon: "commit",
kind: "open_modal",
},
{
id: "push",
label: "Push",
disabled: !canPush,
icon: "push",
kind: "run_action",
action: "commit_push",
},
hasOpenPr
? {
id: "pr",
label: "View PR",
disabled: !canOpenPr,
icon: "pr",
kind: "open_pr",
}
: {
id: "pr",
label: "Create PR",
disabled: !canCreatePr,
icon: "pr",
kind: "run_action",
action: "commit_push_pr",
},
];
}
function buildGitModalActionOptions(
gitStatus: GitStatusResult | null,
isDisabled: boolean,
): GitModalActionOption[] {
const hasBranch = gitStatus?.branch !== null;
const hasOpenPr = gitStatus?.openPr !== null;
return [
{
action: "commit",
label: "Commit",
disabled: isDisabled,
icon: "commit",
},
{
action: "commit_push",
label: "Commit and push",
disabled: isDisabled || !hasBranch,
icon: "push",
...(!hasBranch ? { detail: "Requires an attached branch." } : {}),
},
{
action: "commit_push_pr",
label: "Commit and create PR",
disabled: isDisabled || !hasBranch || hasOpenPr,
icon: "pr",
...(!hasBranch
? { detail: "Requires an attached branch." }
: hasOpenPr
? { detail: "A PR is already open for this branch." }
: {}),
},
];
}
function getGitStatusQueryKey(gitCwd: string | null): readonly ["git", "status", string | null] {
return ["git", "status", gitCwd];
}
function gitStatusQueryOptions(api: NativeApi | undefined, gitCwd: string | null) {
return queryOptions({
queryKey: getGitStatusQueryKey(gitCwd),
queryFn: async () => {
if (!api || !gitCwd) {
throw new Error("Git status is unavailable.");
}
return api.git.status({ cwd: gitCwd });
},
enabled: !!api && !!gitCwd,
});
}
export default function GitActionsControl({ api, gitCwd }: GitActionsControlProps) {
const queryClient = useQueryClient();
const [isGitMenuOpen, setIsGitMenuOpen] = useState(false);
const [isGitModalActionRunning, setIsGitModalActionRunning] = useState(false);
const [gitActionError, setGitActionError] = useState<string | null>(null);
const [isGitModalOpen, setIsGitModalOpen] = useState(false);
const [gitModalSelectedAction, setGitModalSelectedAction] = useState<GitStackedAction>("commit");
const [gitModalCommitMessage, setGitModalCommitMessage] = useState("");
const [gitModalProgress, setGitModalProgress] = useState<GitProgressStep[]>([]);
const [gitModalError, setGitModalError] = useState<string | null>(null);
const [gitModalResult, setGitModalResult] = useState<GitRunStackedActionResult | null>(null);
const gitMenuRef = useRef<HTMLDivElement>(null);
const { data: gitStatus = null, error: gitStatusError } = useQuery(
gitStatusQueryOptions(api, gitCwd),
);
const runImmediateGitActionMutation = useMutation({
mutationFn: async (action: GitStackedAction) => {
if (!api || !gitCwd) {
throw new Error("Git action is unavailable.");
}
return api.git.runStackedAction({ cwd: gitCwd, action });
},
onMutate: () => {
setIsGitMenuOpen(false);
setGitActionError(null);
setGitModalError(null);
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["git"] });
},
onError: (error) => {
setGitActionError(error instanceof Error ? error.message : "Git action failed.");
},
});
const isGitActionRunning = isGitModalActionRunning || runImmediateGitActionMutation.isPending;
const gitBaseDisabled = !api || !gitCwd || !gitStatus || isGitActionRunning;
const gitActionMenuItems = useMemo(
() => buildGitActionMenuItems(gitStatus, gitBaseDisabled),
[gitBaseDisabled, gitStatus],
);
const gitModalActionOptions = useMemo(
() => buildGitModalActionOptions(gitStatus, !gitStatus || isGitActionRunning),
[gitStatus, isGitActionRunning],
);
const selectedGitModalActionOption = useMemo(
() => gitModalActionOptions.find((option) => option.action === gitModalSelectedAction) ?? null,
[gitModalActionOptions, gitModalSelectedAction],
);
const visibleGitActionError = gitActionError ?? gitStatusError?.message;
const gitModalOpenPrUrl = gitModalResult?.pr.url ?? gitStatus?.openPr?.url ?? null;
const gitModalHasProgress = gitModalProgress.length > 0;
const gitModalSelectionMode = !gitModalHasProgress && gitModalResult === null;
const gitModalSteps = gitModalProgress;
const refreshGitStatus = useCallback(async () => {
if (!api || !gitCwd) return;
await queryClient.invalidateQueries({ queryKey: ["git"] });
setGitActionError(null);
}, [api, gitCwd, queryClient]);
const openGitActionModal = useCallback(() => {
setIsGitMenuOpen(false);
setIsGitModalOpen(true);
setGitModalSelectedAction("commit");
setGitModalCommitMessage("");
setGitModalProgress([]);
setGitModalError(null);
setGitModalResult(null);
setGitActionError(null);
}, []);
const closeGitActionModal = useCallback(() => {
if (isGitActionRunning) return;
setIsGitModalOpen(false);
setGitModalSelectedAction("commit");
setGitModalCommitMessage("");
setGitModalProgress([]);
setGitModalError(null);
setGitModalResult(null);
}, [isGitActionRunning]);
const runGitActionImmediately = useCallback(
(action: GitStackedAction) => {
runImmediateGitActionMutation.mutate(action);
},
[runImmediateGitActionMutation],
);
const openExistingPr = useCallback(() => {
setIsGitMenuOpen(false);
setGitActionError(null);
if (!api) {
setGitActionError("Link opening is unavailable.");
return;
}
const prUrl = gitStatus?.openPr?.url ?? null;
if (!prUrl) {
setGitActionError("No open PR found for the current branch.");
return;
}
void api.shell.openExternal(prUrl).catch((error) => {
setGitActionError(error instanceof Error ? error.message : "Unable to open PR link.");
});
}, [api, gitStatus?.openPr?.url]);
const openPrFromModal = useCallback(() => {
if (!api) {
setGitModalError("Link opening is unavailable.");
return;
}
const prUrl = gitModalOpenPrUrl;
if (!prUrl) return;
void api.shell.openExternal(prUrl).catch((error) => {
setGitModalError(error instanceof Error ? error.message : "Unable to open PR link.");
});
}, [api, gitModalOpenPrUrl]);
const runGitAction = useCallback(async () => {
if (!api || !gitCwd || !isGitModalOpen) return;
if (!selectedGitModalActionOption || selectedGitModalActionOption.disabled) return;
const actionCwd = gitCwd;
const action = selectedGitModalActionOption.action;
const commitMessage = gitModalCommitMessage.trim();
const includeGeneratedCommitMessage = commitMessage.length === 0;
setIsGitModalActionRunning(true);
setGitModalError(null);
setGitActionError(null);
setGitModalResult(null);
setGitModalProgress(initialGitProgressSteps(action, commitMessage));
let commit: GitRunStackedActionResult["commit"] = {
status: "skipped_no_changes",
};
let push: GitRunStackedActionResult["push"] = {
status: "skipped_not_requested",
};
let pr: GitRunStackedActionResult["pr"] = {
status: "skipped_not_requested",
};
const updateStep = (
id: GitProgressStep["id"],
status: GitProgressStepStatus,
detail?: string,
) => {
setGitModalProgress((steps) => updateProgressStep(steps, id, status, detail));
};
try {
if (includeGeneratedCommitMessage) {
updateStep("generate", "running");
} else {
updateStep("commit", "running");
}
const commitRun = await api.git.runStackedAction({
cwd: actionCwd,
action: "commit",
...(commitMessage.length > 0 ? { commitMessage } : {}),
});
commit = commitRun.commit;
if (includeGeneratedCommitMessage) {
if (commitRun.commit.status === "created") {
if (commitRun.commit.subject) {
setGitModalCommitMessage(commitRun.commit.subject);
}
updateStep("generate", "completed");
} else {
updateStep("generate", "skipped", "No local changes to commit.");
}
}
if (commitRun.commit.status === "created") {
updateStep("commit", "completed", commitRun.commit.subject ?? "Committed local changes.");
} else {
updateStep("commit", "skipped", "No local changes to commit.");
}
if (action !== "commit") {
updateStep("push", "running");
const pushRun = await api.git.runStackedAction({
cwd: actionCwd,
action: "commit_push",
});
push = pushRun.push;
if (pushRun.push.status === "pushed") {
updateStep(
"push",
"completed",
pushRun.push.upstreamBranch
? `Pushed to ${pushRun.push.upstreamBranch}.`
: "Pushed latest commits.",
);
} else {
updateStep("push", "skipped", "Branch already up to date.");
}
}
if (action === "commit_push_pr") {
updateStep("pr", "running");
const prRun = await api.git.runStackedAction({
cwd: actionCwd,
action: "commit_push_pr",
});
pr = prRun.pr;
if (prRun.pr.status === "opened_existing") {
updateStep(
"pr",
"completed",
prRun.pr.number ? `Opened existing PR #${prRun.pr.number}.` : "Opened existing PR.",
);
} else if (prRun.pr.status === "created") {
updateStep(
"pr",
"completed",
prRun.pr.number ? `Created PR #${prRun.pr.number}.` : "Created PR.",
);
} else {
updateStep("pr", "skipped", "PR step was not requested.");
}
}
setGitModalResult({ action, commit, push, pr });
} catch (error) {
const message = error instanceof Error ? error.message : "Git action failed.";
setGitModalError(message);
setGitActionError(message);
setGitModalProgress((steps) => {
const active = steps.find((step) => step.status === "running");
if (!active) return steps;
return updateProgressStep(steps, active.id, "failed", message);
});
} finally {
setIsGitModalActionRunning(false);
await refreshGitStatus().catch(() => undefined);
}
}, [
api,
gitCwd,
gitModalCommitMessage,
isGitModalOpen,
refreshGitStatus,
selectedGitModalActionOption,
]);
useEffect(() => {
setGitActionError(null);
setGitModalError(null);
setIsGitModalOpen(false);
setGitModalSelectedAction("commit");
setGitModalCommitMessage("");
setGitModalProgress([]);
setGitModalResult(null);
}, [gitCwd]);
useEffect(() => {
if (!isGitModalOpen) return;
if (selectedGitModalActionOption && !selectedGitModalActionOption.disabled) return;
const fallback = gitModalActionOptions.find((option) => !option.disabled);
if (fallback) {
setGitModalSelectedAction(fallback.action);
}
}, [gitModalActionOptions, isGitModalOpen, selectedGitModalActionOption]);
useEffect(() => {
if (!isGitMenuOpen) return;
const handleClickOutside = (event: MouseEvent) => {
if (!gitMenuRef.current) return;
if (event.target instanceof Node && !gitMenuRef.current.contains(event.target)) {
setIsGitMenuOpen(false);
}
};
window.addEventListener("mousedown", handleClickOutside);
return () => {
window.removeEventListener("mousedown", handleClickOutside);
};
}, [isGitMenuOpen]);
useEffect(() => {
if (!isGitModalOpen) return;
const handleEscape = (event: globalThis.KeyboardEvent) => {
if (event.key !== "Escape") return;
if (isGitActionRunning) return;
closeGitActionModal();
};
window.addEventListener("keydown", handleEscape);
return () => {
window.removeEventListener("keydown", handleEscape);
};
}, [closeGitActionModal, isGitActionRunning, isGitModalOpen]);
if (!gitCwd) return null;
return (
<>
<div className="relative" ref={gitMenuRef}>
<button
type="button"
className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-[10px] text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80 disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => {
if (!isGitMenuOpen) {
void refreshGitStatus().catch(() => undefined);
}
setIsGitMenuOpen((v) => !v);
}}
disabled={!gitStatus || isGitActionRunning}
>
{isGitActionRunning ? "Running..." : "Git actions"}
<span aria-hidden="true">▾</span>
</button>
{isGitMenuOpen && (
<div className="absolute right-0 top-full z-50 mt-1 w-[280px] rounded-3xl border border-border bg-popover p-3 shadow-xl">
<p className="px-3 pb-2 text-[13px] text-muted-foreground/75">Git actions</p>
{gitActionMenuItems.map((item) => {
return (
<button
key={`${item.id}-${item.label}`}
type="button"
className="mb-1.5 flex w-full items-center gap-3 rounded-2xl px-3 py-2.5 text-left text-[14px] text-foreground transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:text-muted-foreground/65"
disabled={item.disabled}
onClick={() => {
if (item.kind === "open_modal") {
openGitActionModal();
return;
}
if (item.kind === "open_pr") {
openExistingPr();
return;
}
if (item.action) {
void runGitActionImmediately(item.action);
}
}}
>
<GitActionIcon icon={item.icon} disabled={item.disabled} />
<span>{item.label}</span>
</button>
);
})}
{gitStatus?.branch === null && (
<p className="px-2 pt-1 text-[10px] text-amber-500 dark:text-amber-300">
Detached HEAD: push and PR actions are unavailable.
</p>
)}
{gitStatus &&
gitStatus.branch !== null &&
!gitStatus.hasWorkingTreeChanges &&
gitStatus.aheadCount === 0 &&
gitStatus.behindCount > 0 && (
<p className="px-3 pt-1 text-[10px] text-amber-500 dark:text-amber-300">
Branch is behind upstream. Pull/rebase before opening a PR.
</p>
)}
{visibleGitActionError && (
<p className="px-3 pt-2 text-[11px] text-rose-500 dark:text-rose-300">
{visibleGitActionError}
</p>
)}
</div>
)}
</div>
{isGitModalOpen && (
<div
className="fixed inset-0 z-80 flex items-center justify-center bg-black/35 px-4 py-6"
onMouseDown={() => {
closeGitActionModal();
}}
>
<div
className="w-full max-w-[640px] rounded-3xl border border-border bg-popover p-6 shadow-2xl"
role="dialog"
aria-modal="true"
aria-label="Git action confirmation"
onMouseDown={(event) => {
event.stopPropagation();
}}
>
<div className="flex items-start justify-between gap-4">
<div className="flex items-center gap-3">
<div className="rounded-2xl bg-accent p-3">
<GitActionIcon
icon={selectedGitModalActionOption?.icon ?? "commit"}
disabled={false}
/>
</div>
<div>
<p className="text-xs uppercase tracking-[0.14em] text-muted-foreground/70">
Git actions
</p>
<h3 className="text-3xl font-semibold tracking-tight text-foreground">
{gitActionModalTitle()}
</h3>
</div>
</div>
<button
type="button"
className="rounded-md p-1 text-muted-foreground/60 transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"
onClick={closeGitActionModal}
disabled={isGitActionRunning}
aria-label="Close git action dialog"
>
<XIcon className="h-5 w-5" />
</button>
</div>
<div className="mt-6 space-y-2 rounded-2xl border border-border/80 bg-card/40 px-4 py-3">
<div className="flex items-center justify-between gap-4 text-sm">
<span className="text-muted-foreground/70">Branch</span>
<span className="font-mono text-foreground">
{gitStatus?.branch ?? "(detached HEAD)"}
</span>
</div>
<div className="flex items-center justify-between gap-4 text-sm">
<span className="text-muted-foreground/70">Changes</span>
<span className="text-foreground">
{gitStatus?.hasWorkingTreeChanges
? "Working tree has changes"
: "No local changes"}
</span>
</div>
</div>
<div className="mt-6">
<label
htmlFor="git-commit-message"
className="mb-2 block text-sm font-medium text-foreground"
>
Commit message
</label>
<textarea
id="git-commit-message"
rows={3}
className="w-full resize-none rounded-2xl border border-border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:border-ring focus:outline-none disabled:cursor-not-allowed disabled:opacity-70"
placeholder="Leave blank to autogenerate a commit message"
value={gitModalCommitMessage}
onChange={(event) => setGitModalCommitMessage(event.target.value)}
disabled={!gitModalSelectionMode || isGitActionRunning}
/>
</div>
<div className="mt-6">
<p className="text-sm font-medium text-foreground">Next steps</p>
<div className="mt-2 overflow-hidden rounded-2xl border border-border">
{gitModalSelectionMode &&
gitModalActionOptions.map((option, index) => {
const borderClass =
index < gitModalActionOptions.length - 1 ? "border-b border-border/70" : "";
const selected = option.action === gitModalSelectedAction && !option.disabled;
const disabled = option.disabled || isGitActionRunning;
return (
<button
key={option.action}
type="button"
className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors duration-150 ${borderClass} ${
selected
? "bg-accent/55"
: disabled
? "bg-card/25"
: "bg-card/45 hover:bg-accent/35"
} disabled:cursor-not-allowed`}
disabled={disabled}
onClick={() => {
setGitModalSelectedAction(option.action);
}}
>
<span className="mt-0.5">
<GitActionIcon icon={option.icon} disabled={option.disabled} />
</span>
<div className="min-w-0 flex-1">
<p
className={`text-sm ${disabled ? "text-muted-foreground/60" : "text-foreground"}`}
>
{option.label}
</p>
{option.detail && (
<p
className={`mt-0.5 text-xs ${disabled ? "text-muted-foreground/55" : "text-muted-foreground/70"}`}
>
{option.detail}
</p>
)}
</div>
{selected && !disabled ? (
<CheckIcon className="mt-0.5 h-4 w-4 shrink-0 text-foreground" />
) : null}
</button>
);
})}
{!gitModalSelectionMode &&
gitModalSteps.map((step, index) => {
const borderClass =
index < gitModalSteps.length - 1 ? "border-b border-border/70" : "";
return (
<div
key={step.id}
className={`flex items-start gap-3 bg-card/45 px-4 py-3 ${borderClass}`}
>
<span className="mt-0.5">
{step.status === "running" ? (
<Loader2Icon className="h-4 w-4 animate-spin text-foreground" />
) : step.status === "completed" ? (
<CheckIcon className="h-4 w-4 text-emerald-600 dark:text-emerald-300" />
) : step.status === "skipped" ? (
<MinusIcon className="h-4 w-4 text-muted-foreground/70" />
) : step.status === "failed" ? (
<XIcon className="h-4 w-4 text-rose-500 dark:text-rose-300" />
) : (
<CircleIcon className="h-4 w-4 text-muted-foreground/60" />
)}
</span>
<div className="min-w-0">
<p className="text-sm text-foreground">{step.label}</p>
{step.status === "failed" && step.detail && (
<p className="mt-0.5 text-xs text-rose-500 dark:text-rose-300">
{step.detail}
</p>
)}
</div>
</div>
);
})}
</div>
</div>
{(gitModalError ?? visibleGitActionError) && (
<div className="mt-4 rounded-lg border border-rose-300/50 bg-rose-500/10 px-3 py-2 text-xs text-rose-600 dark:text-rose-200">
{gitModalError ?? visibleGitActionError}
</div>
)}
<div className="mt-6 flex justify-end gap-2">
{gitModalResult && gitModalOpenPrUrl && (
<button
type="button"
className="rounded-xl border border-border px-4 py-2 text-sm text-foreground transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-60"
onClick={openPrFromModal}
disabled={isGitActionRunning}
>
Open PR
</button>
)}
<button
type="button"
className={
gitModalResult
? "rounded-xl bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors duration-150 hover:bg-foreground/90 disabled:cursor-not-allowed disabled:opacity-60"
: "rounded-xl border border-border px-4 py-2 text-sm text-foreground transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-60"
}
onClick={closeGitActionModal}
disabled={isGitActionRunning}
>
{gitModalResult ? "Done" : "Cancel"}
</button>
{!gitModalResult && (
<button
type="button"
className="rounded-xl bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors duration-150 hover:bg-foreground/90 disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => {
void runGitAction();
}}
disabled={isGitActionRunning || !selectedGitModalActionOption}
>
{isGitActionRunning
? "Running..."
: gitModalSelectionMode
? "Continue"
: runActionLabel(gitModalSelectedAction)}
</button>
)}
</div>
</div>
</div>
)}
</>
);
}
+15
View File
@@ -0,0 +1,15 @@
import type { SVGProps } from "react";
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
export const GitHubIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 1024 1024" fill="none">
<path
fillRule="evenodd"
clipRule="evenodd"
d="M8 0C3.58 0 0 3.58 0 8C0 11.54 2.29 14.53 5.47 15.59C5.87 15.66 6.02 15.42 6.02 15.21C6.02 15.02 6.01 14.39 6.01 13.72C4 14.09 3.48 13.23 3.32 12.78C3.23 12.55 2.84 11.84 2.5 11.65C2.22 11.5 1.82 11.13 2.49 11.12C3.12 11.11 3.57 11.7 3.72 11.94C4.44 13.15 5.59 12.81 6.05 12.6C6.12 12.08 6.33 11.73 6.56 11.53C4.78 11.33 2.92 10.64 2.92 7.58C2.92 6.71 3.23 5.99 3.74 5.43C3.66 5.23 3.38 4.41 3.82 3.31C3.82 3.31 4.49 3.1 6.02 4.13C6.66 3.95 7.34 3.86 8.02 3.86C8.7 3.86 9.38 3.95 10.02 4.13C11.55 3.09 12.22 3.31 12.22 3.31C12.66 4.41 12.38 5.23 12.3 5.43C12.81 5.99 13.12 6.7 13.12 7.58C13.12 10.65 11.25 11.33 9.47 11.53C9.76 11.78 10.01 12.26 10.01 13.01C10.01 14.08 10 14.94 10 15.21C10 15.42 10.15 15.67 10.55 15.59C13.71 14.53 16 11.53 16 8C16 3.58 12.42 0 8 0Z"
transform="scale(64)"
fill="#1B1F23"
/>
</svg>
);
@@ -1,10 +1,12 @@
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { readNativeApi } from "../session-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
import type { Project } from "../types";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, type Project, type Thread } from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
function formatRelativeTime(iso: string): string {
@@ -17,54 +19,195 @@ function formatRelativeTime(iso: string): string {
return `${Math.floor(hours / 24)}d ago`;
}
function threadStatusLabel(
status: "connecting" | "ready" | "running" | "error" | "closed" | undefined,
): "Working" | "Connecting" | null {
if (status === "running") return "Working";
if (status === "connecting") return "Connecting";
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";
}
interface ThreadStatusPill {
label: "Working" | "Connecting" | "Completed" | "Awaiting response";
colorClass: string;
dotClass: string;
pulse: boolean;
}
function hasUnseenCompletion(thread: Thread): boolean {
if (!thread.latestTurnCompletedAt) return false;
const completedAt = Date.parse(thread.latestTurnCompletedAt);
if (Number.isNaN(completedAt)) return false;
if (!thread.lastVisitedAt) return true;
const lastVisitedAt = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAt)) return true;
return completedAt > lastVisitedAt;
}
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
if (hasPendingApprovals) {
return {
label: "Awaiting response",
colorClass: "text-amber-600 dark:text-amber-300/90",
dotClass: "bg-amber-500 dark:bg-amber-300/90",
pulse: false,
};
}
if (thread.session?.status === "running") {
return {
label: "Working",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (thread.session?.status === "connecting") {
return {
label: "Connecting",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (hasUnseenCompletion(thread)) {
return {
label: "Completed",
colorClass: "text-emerald-600 dark:text-emerald-300/90",
dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
pulse: false,
};
}
return null;
}
export default function Sidebar() {
const { state, dispatch } = useStore();
const api = readNativeApi();
const api = useNativeApi();
const { theme, setTheme } = useTheme();
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const [isAddingProject, setIsAddingProject] = useState(false);
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<string, boolean>();
for (const thread of state.threads) {
map.set(thread.id, derivePendingApprovals(thread.events).length > 0);
}
return map;
}, [state.threads]);
const handleNewThread = useCallback(
(projectId: string) => {
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: "New thread",
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 = () => {
const cwd = newCwd.trim();
if (!cwd) return;
const name = cwd.split("/").findLast((segment) => segment.length > 0) ?? "project";
const project: Project = {
id: crypto.randomUUID(),
name,
cwd,
model: DEFAULT_MODEL,
expanded: true,
};
dispatch({ type: "ADD_PROJECT", project });
setNewCwd("");
setAddingProject(false);
};
const handleNewThread = (projectId: string) => {
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: "New thread",
model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL,
session: null,
messages: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
},
});
void addProjectFromPath(newCwd);
};
const handlePickFolder = async () => {
@@ -73,12 +216,46 @@ export default function Sidebar() {
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 =
@@ -107,46 +284,24 @@ export default function Sidebar() {
if (!projectId) return;
event.preventDefault();
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: "New thread",
model: state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL,
session: null,
messages: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
},
});
handleNewThread(projectId);
};
window.addEventListener("keydown", onWindowKeyDown);
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [dispatch, state.activeThreadId, state.projects, state.threads]);
}, [handleNewThread, state.activeThreadId, state.projects, state.threads]);
return (
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
{/* Drag region / traffic light space */}
<div className="drag-region h-[52px] shrink-0" />
{/* Branding */}
<div className="flex items-center gap-2 px-4 pb-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 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-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>
{state.runtimeError && (
<span className="rounded-full border border-rose-400/30 bg-rose-500/10 px-2 py-0.5 text-[9px] font-medium uppercase tracking-wider text-rose-100">
Offline
</span>
)}
<button
type="button"
className="rounded-md p-1.5 text-muted-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-muted-foreground"
@@ -215,7 +370,10 @@ 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 = threadStatusPill(
thread,
pendingApprovalByThreadId.get(thread.id) === true,
);
return (
<button
key={thread.id}
@@ -231,12 +389,25 @@ 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={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{threadStatus.label}</span>
</span>
)}
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
@@ -287,12 +458,12 @@ export default function Sidebar() {
if (e.key === "Escape") setAddingProject(false);
}}
/>
{api && (
{isElectron && api && (
<button
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>
@@ -302,8 +473,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`;
}
});
});
}
+8
View File
@@ -0,0 +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 web-app
* code executes, so this is reliable at module load time.
*/
export const isElectron =
typeof window !== "undefined" &&
(window.desktopBridge !== undefined || window.nativeApi !== undefined);
@@ -91,4 +91,32 @@ describe("buildBootstrapInput", () => {
expect(result.omittedCount).toBe(1);
expect(result.truncated).toBe(true);
});
it("captures user image attachment context in transcript blocks", () => {
const result = buildBootstrapInput(
[
{
id: "u-image",
role: "user",
text: "",
attachments: [
{
type: "image",
id: "img-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 2_048,
},
],
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
],
"What does this error mean?",
1_500,
);
expect(result.text).toContain("Attached image");
expect(result.text).toContain("screenshot.png");
});
});
@@ -18,8 +18,34 @@ function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
return message.role === "assistant" ? "ASSISTANT" : "USER";
}
function attachmentSummary(message: ChatMessage): string | null {
const imageAttachments = message.attachments?.filter((attachment) => attachment.type === "image");
const count = imageAttachments?.length ?? 0;
if (count === 0) {
return null;
}
const names = imageAttachments?.slice(0, 3).map((image) => image.name) ?? [];
const namesSummary = names.join(", ");
const extraCount = count - names.length;
const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";
return `[Attached image${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
}
function buildMessageBlock(message: ChatMessage): string {
return `${messageRoleLabel(message)}:\n${message.text}`;
const text = message.text;
const attachments = attachmentSummary(message);
if (text && attachments) {
return `${messageRoleLabel(message)}:\n${text}\n${attachments}`;
}
if (text) {
return `${messageRoleLabel(message)}:\n${text}`;
}
if (attachments) {
return `${messageRoleLabel(message)}:\n${attachments}`;
}
return `${messageRoleLabel(message)}:\n(empty message)`;
}
function finalizeWithPrompt(
+6
View File
@@ -0,0 +1,6 @@
import { useMemo } from "react";
import { readNativeApi } from "../session-logic";
export function useNativeApi() {
return useMemo(() => readNativeApi(), []);
}
@@ -1,8 +1,8 @@
import { useEffect, useSyncExternalStore } from "react";
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> = [];
@@ -28,7 +28,7 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
document.documentElement.classList.toggle("dark", isDark);
if (suppressTransitions) {
// Force a reflow so the no-transitions class takes effect before removal
void document.documentElement.offsetHeight;
document.documentElement.offsetHeight;
requestAnimationFrame(() => {
document.documentElement.classList.remove("no-transitions");
});
@@ -75,11 +75,11 @@ export function useTheme() {
const resolvedTheme: "light" | "dark" =
theme === "system" ? (getSystemDark() ? "dark" : "light") : theme;
const setTheme = (next: Theme) => {
const setTheme = useCallback((next: Theme) => {
localStorage.setItem(STORAGE_KEY, next);
applyTheme(next, true);
emitChange();
};
}, []);
// Keep DOM in sync on mount/change
useEffect(() => {
@@ -83,18 +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%);
--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);
@@ -124,8 +124,8 @@
--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%);
@@ -135,7 +135,7 @@
--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);
@@ -161,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;
@@ -224,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;
@@ -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,22 +116,102 @@ 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",
lastVisitedAt: "2026-02-08T10:01:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalOpen).toBe(true);
expect(hydrated?.threads[0]?.terminalHeight).toBe(360);
expect(hydrated?.threads[0]?.lastVisitedAt).toBe("2026-02-08T10:01:00.000Z");
});
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: [
{
id: "m-1",
role: "user",
text: "Hi",
attachments: [
{
type: "image",
id: "img-1",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 4_096,
previewUrl: "blob:preview-1",
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
@@ -134,6 +219,9 @@ describe("toPersistedState", () => {
events: [],
error: "boom",
createdAt: "2026-02-08T10:00:00.000Z",
lastVisitedAt: "2026-02-08T10:02:00.000Z",
branch: null,
worktreePath: null,
};
const persisted = toPersistedState({
@@ -151,7 +239,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 +247,30 @@ describe("toPersistedState", () => {
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
messages: thread.messages,
terminalOpen: true,
terminalHeight: 320,
messages: [
{
id: "m-1",
role: "user",
text: "Hi",
attachments: [
{
type: "image",
id: "img-1",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 4_096,
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
createdAt: thread.createdAt,
lastVisitedAt: thread.lastVisitedAt,
branch: null,
worktreePath: null,
});
const persistedThread = persisted.threads[0];
expect(persistedThread).toBeDefined();
@@ -1,7 +1,13 @@
import { z } from "zod";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import { DEFAULT_RUNTIME_MODE, type Project, type RuntimeMode, type Thread } from "./types";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
type Thread,
} from "./types";
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
@@ -17,6 +23,17 @@ const persistedMessageSchema = z.object({
id: z.string().min(1),
role: z.enum(["user", "assistant"]),
text: z.string(),
attachments: z
.array(
z.object({
type: z.literal("image"),
id: z.string().min(1),
name: z.string().min(1),
mimeType: z.string().min(1),
sizeBytes: z.number().int().min(1),
}),
)
.optional(),
createdAt: z.string().min(1),
streaming: z.boolean(),
});
@@ -27,8 +44,15 @@ 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),
lastVisitedAt: z.string().min(1).optional(),
branch: z.string().min(1).nullable().optional(),
worktreePath: z.string().min(1).nullable().optional(),
});
const persistedStateBodySchema = z.object({
@@ -57,7 +81,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,
@@ -99,14 +135,28 @@ 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,
streaming: false,
})),
messages: thread.messages.map((message) => {
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
return {
id: message.id,
role: message.role,
text: message.text,
...(hydratedAttachments && hydratedAttachments.length > 0
? { attachments: hydratedAttachments }
: {}),
createdAt: message.createdAt,
streaming: false,
};
}),
events: [],
error: null,
createdAt: thread.createdAt,
lastVisitedAt: thread.lastVisitedAt,
branch: thread.branch ?? null,
worktreePath: thread.worktreePath ?? null,
};
}
@@ -149,9 +199,9 @@ export function hydratePersistedState(
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,
@@ -159,8 +209,30 @@ export function toPersistedState(
projectId: thread.projectId,
title: thread.title,
model: thread.model,
messages: thread.messages,
terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight,
messages: thread.messages.map((message) => ({
id: message.id,
role: message.role,
text: message.text,
...(message.attachments && message.attachments.length > 0
? {
attachments: message.attachments.map((attachment) => ({
type: attachment.type,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
})),
}
: {}),
createdAt: message.createdAt,
streaming: message.streaming,
})),
createdAt: thread.createdAt,
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
branch: thread.branch,
worktreePath: thread.worktreePath,
})),
activeThreadId: state.activeThreadId,
runtimeMode: state.runtimeMode,
@@ -1,9 +1,10 @@
import { describe, expect, it } from "vitest";
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import {
type WorkLogEntry,
applyEventToMessages,
derivePendingApprovals,
deriveTimelineEntries,
deriveWorkLogEntries,
evolveSession,
@@ -134,7 +135,7 @@ describe("deriveWorkLogEntries", () => {
expect(entries[0]?.label).toBe("Tool call");
});
it("logs turn completion with elapsed time", () => {
it("does not surface successful turn completion as a work-log row", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
@@ -154,7 +155,38 @@ describe("deriveWorkLogEntries", () => {
"turn-1",
);
expect(entries[0]?.label).toBe("Turn complete in 10s");
expect(entries).toHaveLength(0);
});
it("shows failed turn completion in the work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:10.000Z",
payload: {
turn: {
id: "turn-1",
status: "failed",
error: { message: "sandbox denied" },
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Turn failed");
expect(entries[0]?.detail).toBe("sandbox denied");
});
it("hides reasoning and agent-message noise from the visible work log", () => {
@@ -229,11 +261,45 @@ describe("deriveWorkLogEntries", () => {
"turn-1",
);
expect(entries.map((entry) => entry.label)).toEqual([
"Turn complete in 8.0s",
"Tool call complete",
"Tool call",
]);
expect(entries.map((entry) => entry.label)).toEqual(["Tool call"]);
});
it("coalesces command start/completed lifecycle into one entry", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-command-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
makeEvent({
id: "evt-command-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Command run");
expect(entries[0]?.detail).toBe("git status --short");
});
it("preserves full tool-call detail text without data truncation", () => {
@@ -257,6 +323,50 @@ describe("deriveWorkLogEntries", () => {
expect(entries[0]?.detail).toBe(longCommand);
});
it("hides generic tool-call rows that have no identifying detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call" },
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(0);
});
it("includes collab tool-call rows with tool name detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-collab-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: {
id: "item-collab",
type: "collabAgentToolCall",
tool: "spawnAgent",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Tool call");
expect(entries[0]?.detail).toBe("spawnAgent");
});
it("can derive work-log entries across all turns when not scoped", () => {
const entries = deriveWorkLogEntries(
[
@@ -283,6 +393,73 @@ describe("deriveWorkLogEntries", () => {
});
});
describe("derivePendingApprovals", () => {
it("returns pending command/file-change approvals", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { command: "git commit -m 'msg'" },
}),
]);
expect(approvals).toEqual([
{
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
detail: "git commit -m 'msg'",
},
]);
});
it("removes approvals after a decision event", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-decision",
method: "item/requestApproval/decision",
requestId: "req-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/fileChange/requestApproval",
requestId: "req-1",
requestKind: "file-change",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
it("clears pending approvals after turn completion", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
});
describe("evolveSession", () => {
it("updates thread id when thread starts", () => {
const previous = makeSession();
@@ -1,6 +1,6 @@
import type { ProviderEvent, ProviderKind, ProviderSession } from "@acme/contracts";
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@t3tools/contracts";
import type { ChatMessage, SessionPhase } from "./types";
import { getOrCreateWsNativeApi } from "./wsNativeApi";
import { createWsNativeApi } from "./wsNativeApi";
export const PROVIDER_OPTIONS: Array<{
value: ProviderKind;
@@ -11,9 +11,21 @@ export const PROVIDER_OPTIONS: Array<{
{ value: "claudeCode", label: "Claude Code (soon)", available: false },
];
export function readNativeApi() {
let cachedApi: NativeApi | undefined;
export function readNativeApi(): NativeApi | undefined {
if (typeof window === "undefined") return undefined;
return window.nativeApi ?? getOrCreateWsNativeApi();
if (cachedApi) return cachedApi;
// Prefer Electron preload bridge if available
if (window.nativeApi) {
cachedApi = window.nativeApi;
return cachedApi;
}
// Fall back to WebSocket transport
cachedApi = createWsNativeApi();
return cachedApi;
}
export function asObject(value: unknown): Record<string, unknown> | undefined {
@@ -66,6 +78,13 @@ export interface WorkLogEntry {
tone: "thinking" | "tool" | "info" | "error";
}
export interface PendingApproval {
requestId: string;
requestKind: "command" | "file-change";
createdAt: string;
detail?: string;
}
export type TimelineEntry =
| {
id: string;
@@ -86,6 +105,52 @@ function normalizeDetail(value: string | undefined): string | undefined {
return trimmed.length > 0 ? trimmed : undefined;
}
function approvalDetail(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const command = asString(payload?.command);
if (command) return command;
return asString(payload?.reason);
}
export function derivePendingApprovals(events: ProviderEvent[]): PendingApproval[] {
const pending = new Map<string, PendingApproval>();
const ordered = [...events].toReversed();
for (const event of ordered) {
if (
event.method === "session/closed" ||
event.method === "session/exited" ||
event.method === "turn/completed"
) {
pending.clear();
continue;
}
const requestId = event.requestId ?? asString(asObject(event.payload)?.requestId);
if (!requestId) continue;
if (
event.kind === "request" &&
(event.requestKind === "command" || event.requestKind === "file-change")
) {
const detail = approvalDetail(event);
pending.set(requestId, {
requestId,
requestKind: event.requestKind,
createdAt: event.createdAt,
...(detail ? { detail } : {}),
});
continue;
}
if (event.method === "item/requestApproval/decision") {
pending.delete(requestId);
}
}
return Array.from(pending.values());
}
function normalizeItemType(raw: string | undefined): string {
if (!raw) return "item";
return raw
@@ -128,15 +193,28 @@ function itemTypeMeta(type: string): {
return { label: "Work item", tone: "info" };
}
interface ItemLifecycleCandidate {
id: string;
itemId?: string;
createdAt: string;
label: string;
detail?: string;
tone: WorkLogEntry["tone"];
phase: "started" | "completed";
}
function extractDetail(
payload: Record<string, unknown> | undefined,
item: Record<string, unknown> | undefined,
): string | undefined {
const candidates = [
asString(item?.command),
asString(item?.tool),
asString(item?.name),
asString(item?.title),
asString(item?.summary),
asString(item?.text),
asString(item?.command),
asString(item?.prompt),
asString(payload?.message),
asString(payload?.prompt),
asString(payload?.command),
@@ -149,7 +227,7 @@ function extractDetail(
return undefined;
}
function entryFromItemLifecycle(event: ProviderEvent): WorkLogEntry | null {
function lifecycleCandidateFromItemEvent(event: ProviderEvent): ItemLifecycleCandidate | null {
const payload = asObject(event.payload);
const item = asObject(payload?.item);
const normalizedType = normalizeItemType(asString(item?.type));
@@ -167,14 +245,16 @@ function entryFromItemLifecycle(event: ProviderEvent): WorkLogEntry | null {
return null;
}
const label = isCompleted ? `${meta.label} complete` : meta.label;
const detail = extractDetail(payload, item);
const itemId = event.itemId ?? asString(item?.id);
return {
id: event.id,
...(itemId ? { itemId } : {}),
createdAt: event.createdAt,
label,
label: meta.label,
...(detail ? { detail } : {}),
tone: meta.tone,
phase: isCompleted ? "completed" : "started",
};
}
@@ -217,7 +297,7 @@ function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
};
}
function entryFromNotification(event: ProviderEvent, turnStartedAt: number): WorkLogEntry | null {
function entryFromNotification(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "notification") return null;
if (shouldDropMethod(event.method)) return null;
if (event.method === "item/agentMessage/delta") return null;
@@ -230,32 +310,22 @@ function entryFromNotification(event: ProviderEvent, turnStartedAt: number): Wor
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
if (status !== "failed") {
return null;
}
const turnError = asObject(turn?.error);
const turnErrorMessage = asString(turnError?.message);
const turnErrorDetail = normalizeDetail(turnErrorMessage);
const eventAt = Date.parse(event.createdAt);
const durationMs =
Number.isNaN(turnStartedAt) || Number.isNaN(eventAt) || eventAt < turnStartedAt
? undefined
: eventAt - turnStartedAt;
return {
id: event.id,
createdAt: event.createdAt,
label:
status === "failed"
? "Turn failed"
: durationMs !== undefined
? `Turn complete in ${formatDuration(durationMs)}`
: "Turn complete",
label: "Turn failed",
...(turnErrorDetail ? { detail: turnErrorDetail } : {}),
tone: status === "failed" ? "error" : "info",
tone: "error",
};
}
const lifecycleEntry = entryFromItemLifecycle(event);
if (lifecycleEntry) return lifecycleEntry;
if (event.method.startsWith("item/")) return null;
return null;
@@ -295,19 +365,56 @@ export function deriveWorkLogEntries(
: undefined;
const turnStartedAt = turnStartedAtIso ? Date.parse(turnStartedAtIso) : Number.NaN;
const shouldIncludeEvent = (event: ProviderEvent): boolean => {
if (!turnId) return true;
const scopedTurnId = eventTurnId(event);
if (scopedTurnId && scopedTurnId !== turnId) {
return false;
}
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
const eventAt = Date.parse(event.createdAt);
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
return false;
}
}
return true;
};
const completedLifecycleItemIds = new Set<string>();
for (const event of ordered) {
if (turnId) {
const scopedTurnId = eventTurnId(event);
if (scopedTurnId && scopedTurnId !== turnId) {
if (!shouldIncludeEvent(event)) continue;
const candidate = lifecycleCandidateFromItemEvent(event);
if (candidate?.phase === "completed" && candidate.itemId) {
completedLifecycleItemIds.add(candidate.itemId);
}
}
for (const event of ordered) {
if (!shouldIncludeEvent(event)) continue;
const lifecycleCandidate = lifecycleCandidateFromItemEvent(event);
if (lifecycleCandidate) {
if (
lifecycleCandidate.phase === "started" &&
lifecycleCandidate.itemId &&
completedLifecycleItemIds.has(lifecycleCandidate.itemId)
) {
continue;
}
if (lifecycleCandidate.label === "Tool call" && !lifecycleCandidate.detail) {
continue;
}
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
const eventAt = Date.parse(event.createdAt);
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
continue;
}
}
entries.push({
id: lifecycleCandidate.id,
createdAt: lifecycleCandidate.createdAt,
label: lifecycleCandidate.label,
...(lifecycleCandidate.detail ? { detail: lifecycleCandidate.detail } : {}),
tone: lifecycleCandidate.tone,
});
continue;
}
const fromRequest = entryFromRequest(event);
@@ -316,7 +423,7 @@ export function deriveWorkLogEntries(
continue;
}
const fromNotification = entryFromNotification(event, turnStartedAt);
const fromNotification = entryFromNotification(event);
if (fromNotification) {
entries.push(fromNotification);
continue;
+266
View File
@@ -0,0 +1,266 @@
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 {
return {
sessionId: "sess-1",
provider: "codex",
status: "ready",
createdAt: "2026-02-09T00:00:00.000Z",
updatedAt: "2026-02-09T00:00:00.000Z",
...overrides,
};
}
function makeEvent(overrides: Partial<ProviderEvent> = {}): ProviderEvent {
return {
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-09T00:00:01.000Z",
method: "thread/started",
...overrides,
};
}
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: "thread-local-1",
codexThreadId: null,
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,
};
}
function makeState(thread: Thread): AppState {
return {
projects: [
{
id: "project-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [thread],
activeThreadId: thread.id,
runtimeMode: "full-access",
diffOpen: false,
};
}
describe("store reducer thread continuity", () => {
it("stores codexThreadId from UPDATE_SESSION", () => {
const state = makeState(
makeThread({
session: null,
}),
);
const next = reducer(state, {
type: "UPDATE_SESSION",
threadId: "thread-local-1",
session: makeSession({ threadId: "thr_123" }),
});
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, {
type: "APPLY_EVENT",
event: makeEvent({
method: "thread/started",
payload: { thread: { id: "thr_backfilled" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.codexThreadId).toBe("thr_backfilled");
});
it("ignores events from a foreign thread within the same session", () => {
const state = makeState(makeThread({ codexThreadId: "thr_expected" }));
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "turn/started",
threadId: "thr_unexpected",
payload: { turn: { id: "turn-1" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next).toBe(state);
});
it("rebases thread identity on thread/started during connect", () => {
const state = makeState(
makeThread({
codexThreadId: "thr_old",
session: makeSession({
status: "connecting",
threadId: "thr_old",
}),
}),
);
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "thread/started",
threadId: "thr_new",
payload: { thread: { id: "thr_new" } },
}),
activeAssistantItemRef: { current: null },
});
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");
});
it("marks the active thread as visited when selected", () => {
const state = makeState(
makeThread({
lastVisitedAt: "2000-01-01T00:00:00.000Z",
}),
);
const next = reducer(state, {
type: "SET_ACTIVE_THREAD",
threadId: "thread-local-1",
});
expect(next.activeThreadId).toBe("thread-local-1");
expect(next.threads[0]?.lastVisitedAt).toBeDefined();
expect(next.threads[0]?.lastVisitedAt).not.toBe("2000-01-01T00:00:00.000Z");
});
it("marks completion as seen immediately for the active thread", () => {
const state = makeState(
makeThread({
session: makeSession({
status: "running",
activeTurnId: "turn-1",
}),
lastVisitedAt: "2026-02-08T10:00:00.000Z",
}),
);
const completedAt = "2026-02-08T10:00:10.000Z";
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "turn/completed",
turnId: "turn-1",
createdAt: completedAt,
payload: { turn: { id: "turn-1", status: "completed" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.latestTurnCompletedAt).toBe(completedAt);
expect(next.threads[0]?.lastVisitedAt).toBe(completedAt);
});
});
@@ -8,19 +8,29 @@ import {
useReducer,
} from "react";
import type { AppBootstrapResult, 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 { DEFAULT_RUNTIME_MODE, type Project, type RuntimeMode, type Thread } from "./types";
import {
type ChatAttachment,
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
type Thread,
} from "./types";
// ── Actions ──────────────────────────────────────────────────────────
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";
@@ -28,13 +38,24 @@ type Action =
activeAssistantItemRef: { current: string | null };
}
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
| { type: "PUSH_USER_MESSAGE"; threadId: string; id: string; text: string }
| {
type: "PUSH_USER_MESSAGE";
threadId: string;
id: string;
text: string;
attachments?: ChatAttachment[];
}
| { 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_THREAD_BRANCH";
threadId: string;
branch: string | null;
worktreePath: string | null;
}
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode }
| { type: "SET_RUNTIME_ERROR"; error: string | null }
| { type: "BOOTSTRAP_FROM_SERVER"; bootstrap: AppBootstrapResult };
| { type: "DELETE_THREAD"; threadId: string };
// ── State ────────────────────────────────────────────────────────────
@@ -44,11 +65,14 @@ export interface AppState {
activeThreadId: string | null;
runtimeMode: RuntimeMode;
diffOpen: boolean;
runtimeError: string | null;
}
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",
@@ -60,7 +84,6 @@ const initialState: AppState = {
activeThreadId: null,
runtimeMode: DEFAULT_RUNTIME_MODE,
diffOpen: false,
runtimeError: null,
};
// ── Helpers ──────────────────────────────────────────────────────────
@@ -70,19 +93,20 @@ 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;
return { ...hydrated, diffOpen: false, runtimeError: null };
return { ...hydrated, diffOpen: false };
} catch {
return initialState;
}
@@ -123,7 +147,34 @@ function getEventTurnId(event: ProviderEvent): string | undefined {
function getEventThreadId(event: ProviderEvent): string | undefined {
if (event.threadId) return event.threadId;
const payload = asObject(event.payload);
return asString(payload?.threadId) ?? asString(asObject(payload?.thread)?.id);
const payloadThread = asObject(payload?.thread);
const payloadMessage = asObject(payload?.msg);
return (
asString(payload?.threadId) ??
asString(payloadThread?.id) ??
asString(payload?.conversationId) ??
asString(payload?.thread_id) ??
asString(payloadMessage?.thread_id)
);
}
function shouldIgnoreForeignThreadEvent(thread: Thread, event: ProviderEvent): boolean {
const eventThreadId = getEventThreadId(event);
if (!eventThreadId) {
return false;
}
const expectedThreadId = thread.session?.threadId ?? thread.codexThreadId;
if (!expectedThreadId || eventThreadId === expectedThreadId) {
return false;
}
// During connect, accept a thread/started notification as an identity rebind.
if (event.method === "thread/started" && thread.session?.status === "connecting") {
return false;
}
return true;
}
function durationMs(startIso: string, endIso: string): number | undefined {
@@ -170,6 +221,9 @@ function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread>
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: [
@@ -181,6 +235,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,
@@ -197,13 +293,50 @@ export function reducer(state: AppState, action: Action): AppState {
{
...action.thread,
model: resolveModelSlug(action.thread.model),
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
},
],
activeThreadId: action.thread.id,
};
case "SET_ACTIVE_THREAD":
return { ...state, activeThreadId: action.threadId };
case "SET_ACTIVE_THREAD": {
const visitedAt = new Date().toISOString();
return {
...state,
activeThreadId: action.threadId,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
lastVisitedAt: visitedAt,
})),
};
}
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 };
@@ -212,6 +345,7 @@ export function reducer(state: AppState, action: Action): AppState {
const { event, activeAssistantItemRef } = action;
const target = findThreadBySessionId(state.threads, event.sessionId);
if (!target) return state;
if (shouldIgnoreForeignThreadEvent(target, event)) return state;
return {
...state,
@@ -219,24 +353,22 @@ export function reducer(state: AppState, action: Action): AppState {
...t,
...(() => {
const eventThreadId = getEventThreadId(event);
const hasThreadMismatch =
t.codexThreadId !== null &&
eventThreadId !== undefined &&
eventThreadId !== t.codexThreadId;
const threadMismatchError = hasThreadMismatch
? `Thread identity mismatch: expected ${t.codexThreadId}, received ${eventThreadId}.`
: null;
const shouldRebindIdentity =
event.method === "thread/started" && t.session?.status === "connecting";
return {
codexThreadId: t.codexThreadId ?? eventThreadId ?? null,
error:
threadMismatchError ??
(event.kind === "error" && event.message ? event.message : t.error),
codexThreadId: shouldRebindIdentity
? (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),
events: [event, ...t.events],
...updateTurnFields(t, event),
...(event.method === "turn/completed" && t.id === state.activeThreadId
? { lastVisitedAt: event.createdAt }
: {}),
})),
};
}
@@ -268,6 +400,9 @@ export function reducer(state: AppState, action: Action): AppState {
id: action.id,
role: "user" as const,
text: action.text,
...(action.attachments && action.attachments.length > 0
? { attachments: action.attachments }
: {}),
createdAt: new Date().toISOString(),
streaming: false,
},
@@ -302,85 +437,35 @@ 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 "SET_RUNTIME_ERROR":
return {
...state,
runtimeError: action.error,
};
case "BOOTSTRAP_FROM_SERVER": {
const { bootstrap } = action;
const existingProject = state.projects.find((project) => project.cwd === bootstrap.launchCwd);
const projectId = existingProject?.id ?? crypto.randomUUID();
const project =
existingProject ??
({
id: projectId,
name: bootstrap.projectName,
cwd: bootstrap.launchCwd,
model: resolveModelSlug(bootstrap.model),
expanded: true,
} satisfies Project);
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
const existingThread =
state.threads.find((thread) => thread.session?.sessionId === bootstrap.session.sessionId) ??
projectThreads.find(
(thread) =>
bootstrap.session.threadId !== undefined &&
thread.codexThreadId === bootstrap.session.threadId,
) ??
projectThreads[0];
const activeThreadId = existingThread?.id ?? crypto.randomUUID();
const thread =
existingThread ??
({
id: activeThreadId,
codexThreadId: bootstrap.session.threadId ?? null,
projectId,
title: "New thread",
model: resolveModelSlug(bootstrap.model),
session: bootstrap.session,
messages: [],
events: [],
error: bootstrap.bootstrapError ?? null,
createdAt: new Date().toISOString(),
} satisfies Thread);
return {
...state,
projects: existingProject
? state.projects.map((entry) =>
entry.id === existingProject.id
? {
...entry,
model: resolveModelSlug(bootstrap.model),
}
: entry,
)
: [project, ...state.projects],
threads: state.threads
.map((entry) =>
entry.id === thread.id
? {
...entry,
session: bootstrap.session,
codexThreadId: bootstrap.session.threadId ?? entry.codexThreadId,
error: bootstrap.bootstrapError ?? entry.error,
}
: entry,
)
.concat(existingThread ? [] : [thread]),
activeThreadId,
runtimeError: null,
};
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:
+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,13 +1,26 @@
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 ChatImageAttachment {
type: "image";
id: string;
name: string;
mimeType: string;
sizeBytes: number;
previewUrl?: string;
}
export type ChatAttachment = ChatImageAttachment;
export interface ChatMessage {
id: string;
role: "user" | "assistant";
text: string;
attachments?: ChatAttachment[];
createdAt: string;
streaming: boolean;
}
@@ -26,6 +39,8 @@ export interface Thread {
projectId: string;
title: string;
model: string;
terminalOpen: boolean;
terminalHeight: number;
session: ProviderSession | null;
messages: ChatMessage[];
events: ProviderEvent[];
@@ -35,4 +50,7 @@ export interface Thread {
latestTurnStartedAt?: string | undefined;
latestTurnCompletedAt?: string | undefined;
latestTurnDurationMs?: number | undefined;
lastVisitedAt?: string | undefined;
branch: string | null;
worktreePath: string | null;
}
+17
View File
@@ -0,0 +1,17 @@
/// <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>;
openExternal: (url: string) => Promise<boolean>;
}
declare global {
interface Window {
nativeApi?: NativeApi;
desktopBridge?: DesktopBridge;
}
}
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more