Compare commits

..
Author SHA1 Message Date
Julius Marminge 84ee10d7ed Add dynamic PR toast actions for Git run results
- Refactor Git action execution into a shared flow for modal and quick actions
- Show `Open PR` when URL exists, otherwise `Create PR` after `commit_push` when eligible
- Add unit tests for `getGitProgressToastAction` decision logic
2026-02-13 16:18:59 -08:00
Julius Marminge 9e3fa3e67f Fix Electron dev env and streamline Git action toast
- Remove `ELECTRON_RUN_AS_NODE` before spawning `electronmon` in desktop dev script
- Replace detailed multi-step Git progress toast with a compact status message + optional Open PR action
2026-02-13 15:26:36 -08:00
Julius Marminge 38de3417b8 Move git action progress to toast and stop auto-opening PRs
- Keep the git action modal in selection mode while actions run in a dismissible progress toast
- Remove automatic `gh pr view --web` calls; only return PR metadata and open links on explicit user action
- Update server/web tests to assert no implicit PR browser open behavior
2026-02-13 15:26:36 -08:00
Julius Marminge 4fff00c8c3 run backend as node 2026-02-13 00:19:32 -08:00
Julius Marmingeandcodex 6b916d3a6f Handle branch recency lookup failures in branch listing
- move branch recency parsing into `readBranchRecency`
- fall back to an empty recency map if lookup fails
- add test to ensure branches still list when recency read times out

Co-authored-by: codex <[email protected]>
2026-02-12 23:29:44 -08:00
Julius Marmingeandcodex 21580dc1b0 Prioritize current and default branches in branch list ordering
- Keep the current branch first
- Place the default branch second
- Sort remaining branches by most recent commit and update tests for this behavior

Co-authored-by: codex <[email protected]>
2026-02-12 23:29:44 -08:00
Julius Marminge ba9585966c Sort git branches by latest commit timestamp
- Order `listGitBranches` by each branch's most recent commit date
- Keep current/default/name tiebreakers for stable ordering
- Add integration test coverage with dated commits to verify recency sort
2026-02-12 23:29:44 -08:00
Julius Marminge 293f7b1507 Guard orphaned worktree deletion behind project context
- Require both orphaned worktree path and thread project before prompting delete
- Prevents delete confirmation when project metadata is unavailable
2026-02-12 22:57:56 -08:00
Julius Marminge 4f5eb3be4d Show worktree name in thread delete confirmation
- Format orphaned worktree paths to display only the final segment
- Apply formatting in Sidebar delete prompt for cleaner UX
- Add tests for Unix, Windows, trailing slash, and fallback cases
2026-02-12 22:57:56 -08:00
Julius Marmingeandcodex b6523a15dc Use Yes/No labels for desktop worktree confirm
Co-authored-by: codex <[email protected]>
2026-02-12 22:57:56 -08:00
Julius Marmingeandcodex 8a4fed1bf2 Guard worktree cleanup on missing project
Co-authored-by: codex <[email protected]>
2026-02-12 22:57:56 -08:00
Julius Marminge 0068a93cfa Add desktop-backed confirm dialog API for worktree deletion
- add `dialogs.confirm` to native IPC/contracts and desktop preload/main bridge
- switch sidebar worktree deletion prompt from `window.confirm` to native API
- add `showDesktopConfirmDialog` helper with unit tests for dialog behavior
2026-02-12 22:57:56 -08:00
Julius Marminge dd912666f2 Delete orphaned worktree when deleting a thread
- Prompt to remove the worktree when a deleted thread is its only reference
- Best-effort cleanup via `api.git.removeWorktree` after thread deletion
- Add `getOrphanedWorktreePathForThread` helper with unit tests
2026-02-12 22:57:56 -08:00
Julius Marminge 521238cf8e Simplify terminal toggle to only update visibility state
- Remove terminal close/exit API calls from `toggleTerminalVisibility`
- Keep toggle behavior as a pure UI state change for active thread
2026-02-12 22:44:14 -08:00
Julius Marminge 5da67c40eb Show pulsing terminal icon for active thread processes
- Replace terminal text badge with a right-aligned `TerminalIcon`
- Add accessible label/title: "Terminal process running"
- Keep pulse animation and terminal-active color styling
2026-02-12 22:24:03 -08:00
Julius Marminge 804572c8ff Tighten test fixtures for terminal options and event typing
- Pass subprocess test options only when defined in `terminalManager` tests
- Narrow web store terminal event fixtures to `started`/`activity` event shapes
2026-02-12 22:20:01 -08:00
Julius Marmingeandcodex ddc4a93c36 Emit terminal activity events from subprocess polling
- Add cross-platform subprocess polling in `TerminalManager` and emit `activity` events when child-process state changes
- Update web store to derive `runningTerminalIds` from `activity.hasRunningSubprocess` instead of start/restart events
- Extend terminal contracts and tests to include the new `activity` event type

Co-authored-by: codex <[email protected]>
2026-02-12 22:20:01 -08:00
Julius Marminge 901579233c Close terminal session when hiding terminal panel
- Attempt `api.terminal.close` when toggling an open terminal off
- Fall back to sending `exit` if close is unavailable or fails
- Include `api` in callback dependencies to keep behavior current
2026-02-12 22:20:01 -08:00
Julius Marminge d27b08bae6 Migrate legacy terminal history to terminal-scoped log path
- On open, read legacy transcript files and write them to the new terminal-scoped history path
- Remove legacy files after migration and warn if cleanup fails
- Update tests to assert migration, content preservation, and legacy file removal
2026-02-12 22:20:01 -08:00
Julius Marminge 485747b892 Track thread terminal running state across UI and store
- add `terminalRunning` to thread state and hydration defaults
- apply terminal events in reducer to sync running/open state (close drawer on exit)
- wire drawer running-state callbacks and show a Terminal status pill in sidebar
- extend store and persistence tests for terminal running/exited behavior
2026-02-12 22:20:01 -08:00
Julius Marminge 15380f2b5f Add dev runner for deterministic multi-instance port offsets
- Route `dev*` scripts through `scripts/dev-runner.mjs` to compute shared server/web port offsets
- Support `T3CODE_DEV_INSTANCE` (hashed or numeric) and explicit `T3CODE_PORT_OFFSET`
- Document multi-instance usage and allow server `VITE_DEV_SERVER_URL` override
2026-02-12 21:41:42 -08:00
Julius Marminge 48b1f7c388 current color github icon 2026-02-12 21:27:50 -08:00
Julius Marminge b26e2d192e Clear terminal history on close and prefer git cwd
- Pass `deleteHistory: true` when closing a terminal
- Fallback path now clears terminal before sending `exit`
- Use `gitCwd` as terminal cwd when available
2026-02-12 21:24:49 -08:00
Julius Marminge e6d6450728 Use terminal close API with exit fallback in ChatView
- Call `api.terminal.close` when available when closing a terminal tab
- Fall back to writing `exit\n` to preserve compatibility with older/uninitialized terminals
2026-02-12 21:24:49 -08:00
Julius Marmingeandmacroscopeapp[bot] 739205872f Update apps/web/src/components/ThreadTerminalDrawer.tsx
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
2026-02-12 21:24:49 -08:00
Julius Marminge 07210d0c91 Migrate thread terminals to grouped layout model
- Replace `terminalLayout`/`splitTerminalIds` with `terminalGroups` and `activeTerminalGroupId`
- Update terminal drawer UI to render grouped splits with a terminal sidebar
- Bump persisted web state to v7 with legacy v6 migration coverage in tests
2026-02-12 21:24:49 -08:00
Julius Marminge ee463f6b76 Add close-terminal actions and state handling in thread drawer
- Add terminal close controls in tab and split terminal views
- Send `exit` before closing and update active terminal/focus in chat state
- Add reducer support and tests for closing tabs, split fallback, and final-terminal drawer hide
2026-02-12 21:24:49 -08:00
Julius Marminge 800eb3b547 Add per-thread multi-terminal sessions and UI state
- Support multiple terminal IDs per thread across contracts, server manager, and WS handling
- Persist terminal history per terminal ID and allow closing all terminals for a thread
- Update web thread state and terminal drawer to create, split, and switch active terminals
- Expand tests for multi-terminal behavior and terminal ID propagation
2026-02-12 21:24:49 -08:00
Julius Marminge 854068dc56 lint 2026-02-12 19:36:40 -08:00
Julius Marminge ccaa58e393 terminal links 2026-02-12 19:36:40 -08:00
Julius Marminge 6d6991bca1 Refine pending approval panel styles
- Constrain pending approval cards to a centered max-width section with updated padding
- Improve light/dark theme contrast for approval detail text and action buttons
- Keep existing approval actions and behavior unchanged while updating visual hierarchy
2026-02-12 18:45:46 -08:00
Julius Marminge 057770ebfc whoop 2026-02-12 18:37:41 -08:00
Julius Marminge 052314b65f 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 18:37:41 -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
Theo Browne 4d3ad5bdc7 more todos 2026-02-09 02:08:00 -08:00
Theo Browne 3bac67030b Add agent guide and Claude symlink 2026-02-09 02:07:17 -08:00
Theo Browne 1bec9288c4 More todos 2026-02-09 01:55:46 -08:00
Theo Browne 57f5b8362a Add durable Codex thread continuity and history bootstrap fallback 2026-02-09 01:42:58 -08:00
Theo Browne ccb0e0cf56 more cleanup 2026-02-09 01:38:48 -08:00
Theo Browne 1ab3256204 light mode round 2 2026-02-09 01:27:01 -08:00
Theo Browne 377d21211a Revert "light mode (#4)"
This reverts commit c51f252ff2.
2026-02-09 01:19:46 -08:00
Julius MarmingeandClaude Opus 4.6 c51f252ff2 light mode (#4)
* init components

* use them

* Fix select trigger styling in dark mode and add open state highlight

Remove dark mode background bleed on select triggers and add accent
background when popup is open.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-02-09 01:13:42 -08:00
Julius Marminge 70a9a043ee oxc stack (#1)
* oxc stacak

* kewl

* unused

* unused
2026-02-09 01:11:20 -08:00
eef57db955 Add open-in-editor feature with Cmd+O shortcut (#2)
* Add open-in-editor feature with Cmd+O shortcut

Add dropdown in header to open workspace in Cursor or system file manager (Finder/Explorer/Files). Include Cmd+O/Ctrl+O global keyboard shortcut to open in last-used editor, persisted to localStorage.

Co-Authored-By: Claude Haiku 4.5 <[email protected]>

* Move editor definitions to contracts for strict IPC typing

EDITORS config and EditorId type now live in @acme/contracts so the
shell.openInEditor IPC channel is strictly typed end-to-end. The main
process uses the contract's command field (null = file manager via
shell.openPath).

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* Fix biome formatting issues

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: add error handling and address review feedback

- Validate cwd is non-empty in shell:open-in-editor IPC handler
- Check shell.openPath() return value and throw on error
- Attach spawn error listener to prevent crashes from missing CLI
- Validate localStorage lastEditor against known EDITORS list
- Only call preventDefault() for Cmd+O when action will run

Co-authored-by: Julius Marminge <[email protected]>

---------

Co-authored-by: Claude Haiku 4.5 <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-02-09 01:06:49 -08:00
Theo Browne 7a68e570eb better 2026-02-09 00:48:59 -08:00
Theo Browne 99a906753e approvals 2026-02-09 00:16:23 -08:00
Theo Browne de5df2690d feat(renderer): simplify thread UI and reduce work-log noise
- remove model picker when creating projects and default to the project model

- add Cmd+Shift+O shortcut to open a new thread in the active project

- remove project/status pills from chat chrome for a cleaner layout

- only surface actionable item lifecycle events (tool/command/file change)

- add tests covering reasoning and agent-message filtering
2026-02-08 23:09:54 -08:00
Theo Browne 1bd823cd20 lots of small progress 2026-02-08 22:26:18 -08:00
Theo Browne 153a130a09 more cleanup 2026-02-08 15:46:00 -08:00
Theo Browne 2fc9336528 more cleanup 2026-02-08 15:04:13 -08:00
Theo Browne 87483c3a95 more render changes, more plans 2026-02-08 14:55:43 -08:00
Theo Browne 54bc785f36 Probably fine 2026-02-08 14:21:55 -08:00
Theo Browne 2f4051ed30 better logging 2026-02-08 14:11:19 -08:00
Theo Browne f0ac593068 Better input box and react compiler 2026-02-08 00:28:21 -08:00
Theo Browne fdb654de45 progress 2026-02-08 00:15:07 -08:00
Theo Browne 733c4633bf bugfix set 1 2026-02-07 21:36:13 -08:00
Theo Browne 548cd113b2 model picker 2026-02-07 20:58:25 -08:00
Theo Browne 13501e85f6 working kind of 2026-02-07 20:42:35 -08:00
Theo Browne 0aefe6d10a more ui 2026-02-07 20:23:21 -08:00
Theo Browne 9ae4d50a98 More redesign work 2026-02-07 20:19:55 -08:00
Theo Browne f733cb7e5f codex working ish 2026-02-07 20:07:11 -08:00
Theo Browne 58261b9ba0 terminal 2026-02-07 19:40:41 -08:00
Theo Browne 25825929ba more testing to prevent issues 2026-02-07 19:27:26 -08:00
Theo Browne 68d778ba50 ugh 2026-02-07 19:24:16 -08:00
Theo Browne f194c9661c Monorepo electron init 2026-02-07 17:28:14 -08:00
134 changed files with 21696 additions and 23 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
---
name: btca-cli
description: btca is a cli for getting information from other git repositories by querying them with natural language. Spawns an external subagent to explore external codebases (i.e. a github repo) and answer questions about them. Great when integrating complex libraries, frameworks, or tools.
---
btca is a cli for asking questions about various folders, primarily git repositories. It's built to give you the exact information you need without bloating your context window. btca uses agents under the hood to answer your question, so prompt it the way you would prompt a tool similar to yourself.
For example, assuming you have a resource named `codex`, you can ask questions like:
```bash
btca ask -r codex -q "What is the return format for Codex App Server responses? Are there any edge cases worth knowing?"
```
Your prompt may include specific names for resources to use, if they do then you should try those first. If you need to check available resources, you can use the `btca resources` command.
New resources can be created if the ones you need do not yet exist.
```bash
btca add -n svelte-dev https://github.com/sveltejs/svelte.dev
```
@@ -0,0 +1,3 @@
interface:
display_name: "BTCA CLI"
short_description: "Help with BTCA CLI setup and usage workflows"
+50
View File
@@ -0,0 +1,50 @@
name: CI
on:
pull_request:
push:
branches:
- main
jobs:
quality:
name: Lint, Typecheck, Test, Build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.3.9
- name: Cache Bun and Turbo
uses: actions/cache@v4
with:
path: |
~/.bun/install/cache
.turbo
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
restore-keys: |
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- name: Test
run: bun run test
- name: Build desktop pipeline
run: bun run build:desktop
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
+12
View File
@@ -0,0 +1,12 @@
node_modules
.bun
.turbo
.DS_Store
*.log
*.tsbuildinfo
apps/*/dist
packages/*/dist
.env
.env.local
build/
.logs/
+12
View File
@@ -0,0 +1,12 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
".plans",
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo"
],
"experimentalSortPackageJson": {}
}
+13
View File
@@ -0,0 +1,13 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": ["dist", "dist-electron", "node_modules", "bun.lock", "*.tsbuildinfo"],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"categories": {
"correctness": "warn",
"suspicious": "warn",
"perf": "warn"
},
"rules": {
"react-in-jsx-scope": "off"
}
}
+42
View File
@@ -0,0 +1,42 @@
# Plan: Centralize Model Normalization in Contracts
## Summary
Move model alias/default normalization into `packages/contracts` so desktop and renderer use one shared source of truth.
## Motivation
- Removes duplicated logic between:
- `apps/desktop/src/codexAppServerManager.ts`
- `apps/renderer/src/model-logic.ts`
- Prevents behavior drift when model aliases/defaults are updated.
## Scope
- Add shared model utilities to contracts.
- Update desktop and renderer to consume shared utilities.
- Keep renderer-specific display options in renderer.
## Proposed Changes
1. Add `packages/contracts/src/model.ts` with:
- Canonical model list
- Alias map
- `normalizeModelSlug`
- `resolveModelSlug`
- `DEFAULT_MODEL`
2. Export model utilities from `packages/contracts/src/index.ts`.
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.
- Keep renderer tests focused on renderer-only behavior.
## Risks
- Desktop/renderer may currently rely on slightly different fallback behavior.
- Import graph must avoid bundling issues for Electron main/preload.
## Validation
- `bun run test`
- `bun run typecheck`
- Manual check that model selection and session start still send expected model slug.
## Done Criteria
- No duplicated alias/default map in desktop and renderer.
- Shared model utilities are contract-tested.
+37
View File
@@ -0,0 +1,37 @@
# Plan: Strengthen Typed IPC Boundaries in Main Process
## Summary
Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers.
## Motivation
- `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`.
- Casts can hide contract breakages until runtime.
## Scope
- Desktop main process IPC registration.
- Optional shared helper for handler registration.
## Proposed Changes
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 IPC handlers in `apps/desktop/src/main.ts` to use:
- `providerSessionStartInputSchema.parse`
- `providerSendTurnInputSchema.parse`
- `providerInterruptTurnInputSchema.parse`
- `providerStopSessionInputSchema.parse`
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 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 renderer/devtools to confirm fast failure.
## Done Criteria
- No provider handler uses `payload as Parameters<...>`.
- All IPC entrypoints parse unknown payloads at boundary.
@@ -0,0 +1,41 @@
# Plan: Decompose CodexAppServerManager
## Summary
Split `CodexAppServerManager` into smaller modules with clear responsibilities.
## Motivation
- `apps/desktop/src/codexAppServerManager.ts` is large and mixes:
- Process lifecycle
- JSON-RPC parsing/routing
- Session state transitions
- Event emission
- This increases regression risk and slows changes.
## Scope
- Desktop provider internals only.
- Keep external behavior/API stable.
## Proposed Changes
1. Extract modules:
- `codex/processLifecycle.ts`
- `codex/jsonrpcRouter.ts`
- `codex/sessionState.ts`
- `codex/parsing.ts`
2. Keep `CodexAppServerManager` as thin orchestrator/facade.
3. Move pure helpers (`classifyCodexStderrLine`, route parsing) into unit-testable files.
4. Add targeted unit tests for:
- Message classification
- Request/notification/response routing
- Session state transitions
## Risks
- Reordering event handling can change behavior.
- Must preserve pending request timeout/cancellation semantics.
## Validation
- Existing tests pass.
- Add module-level tests for parsing and transition logic.
## Done Criteria
- Main manager file materially smaller and orchestration-focused.
- Core protocol/state logic covered by focused tests.
+40
View File
@@ -0,0 +1,40 @@
# Plan: Split ChatView into Smaller UI/Logic Units
## Summary
Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
## Motivation
- `apps/renderer/src/components/ChatView.tsx` is large and handles:
- Session orchestration
- Send/interrupt actions
- Timeline rendering
- Header/status UI
- Composer UI
- Hard to test and maintain as one component.
## Scope
- Renderer component boundaries and hooks.
- Keep visual behavior unchanged.
## Proposed Changes
1. Create hook: `apps/renderer/src/hooks/useChatSession.ts`
- `ensureSession`
- `sendTurn`
- `interruptTurn`
2. Split presentational components:
- `components/chat/ThreadHeader.tsx`
- `components/chat/MessageTimeline.tsx`
- `components/chat/ComposerBar.tsx`
3. Keep `ChatView.tsx` as container wiring store + hook + child components.
4. Add focused tests for hook behavior (error handling, session reuse).
## Risks
- Refactor can break subtle UI interactions (auto-scroll, menu close, keyboard send).
## Validation
- `bun run test`
- Manual smoke: send, stream, interrupt, model switch.
## Done Criteria
- `ChatView.tsx` significantly reduced and easier to scan.
- Session logic isolated from rendering.
@@ -0,0 +1,34 @@
# Plan: Move Renderer Persisted-State Validation to Zod
## Summary
Use explicit Zod schemas for localStorage state parsing and migration.
## Motivation
- `apps/renderer/src/store.ts` has large manual sanitize functions.
- Manual type guards are verbose and easier to get wrong during schema evolution.
## Scope
- Renderer state hydration/persistence path.
- No backend/protocol changes.
## Proposed Changes
1. Add schema module: `apps/renderer/src/persistenceSchema.ts`
- Persisted payload versions (`v1`, `v2`)
- Thread/message/project schemas
2. Replace `sanitizeProjects/sanitizeThreads/sanitizeMessages` with schema parsing + transforms.
3. Keep migration logic explicit (legacy model migration and key migration).
4. Add tests for:
- Invalid payload fallback to initial state
- Legacy payload migration
- Unknown thread/project references filtered
## Risks
- Overly strict schemas could drop valid historical data unexpectedly.
## Validation
- Unit tests for migration/hydration.
- Manual reload test with existing localStorage data.
## Done Criteria
- Store hydration logic is schema-driven.
- Migration behavior is tested and documented.
+31
View File
@@ -0,0 +1,31 @@
# Plan: Add Provider Log Stream Lifecycle Management
## Summary
Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely.
## Motivation
- `apps/desktop/src/providerManager.ts` opens a write stream in constructor.
- Stream lifecycle is not explicit on shutdown.
## Scope
- 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/desktop/src/main.ts`.
3. Optional: change log format to JSON lines with stable fields.
4. Optional: per-session log files under `.logs/providers/`.
## Risks
- Improper close sequencing may lose final log lines.
## Validation
- Manual run/quit cycle to ensure no open handle warnings.
- Confirm logs flush on quit and file descriptors are not leaked.
## Done Criteria
- ProviderManager owns complete log stream lifecycle.
- Shutdown path explicitly disposes provider resources.
+34
View File
@@ -0,0 +1,34 @@
# Plan: Add CI Workflow for Core Quality Gates
## Summary
Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-test) on pushes and PRs.
## Motivation
- Repository currently has no CI workflow files.
- Quality checks are only local/manual.
## Scope
- `.github/workflows/ci.yml`
- Bun + Turbo setup in CI.
## Proposed Changes
1. Add `ci.yml` with jobs:
- Setup Bun and Node environment
- Install deps
- `bun run lint`
- `bun run typecheck`
- `bun run test`
2. Add separate optional job for `bun run smoke-test` (desktop/Electron).
3. Configure caching for Bun/Turbo as appropriate.
## Risks
- Smoke test may be flaky in headless CI environments.
- CI runtime can grow if caching is misconfigured.
## Validation
- Verify workflow runs on a branch PR.
- Ensure failures surface clearly by job name.
## Done Criteria
- CI blocks regressions in lint/typecheck/test.
- Workflow docs added to README.
+32
View File
@@ -0,0 +1,32 @@
# Plan: Add Pre-Commit Formatting/Lint Hooks
## Summary
Introduce pre-commit automation so formatting and basic lint checks happen before commits.
## Motivation
- Current lint failures include formatting-only issues.
- Shift-left feedback reduces noisy CI failures and cleanup churn.
## Scope
- Root tooling config and package scripts.
- No runtime code changes.
## Proposed Changes
1. Add hook tooling (e.g. Husky + lint-staged or Lefthook).
2. Configure staged-file tasks:
- `biome format --write`
- `biome check`
3. Add setup docs in README.
4. Keep checks fast to avoid developer friction.
## Risks
- Slow hooks can frustrate contributors and be bypassed.
- Need to ensure compatibility with Bun workspace setup.
## Validation
- Create sample staged changes and verify hook behavior.
- Confirm formatting fixes are applied automatically.
## Done Criteria
- Pre-commit hook installed and documented.
- Formatting-only lint failures drop significantly.
+35
View File
@@ -0,0 +1,35 @@
# Plan: Expand Event/State Transition Test Coverage
## Summary
Add focused tests for renderer event handling and session evolution logic.
## Motivation
- Core behavior is event-driven and stateful.
- Existing renderer tests cover only a subset of timeline/model behavior.
## Scope
- `apps/renderer/src/session-logic.test.ts`
- Optional reducer tests for `apps/renderer/src/store.ts`.
## Proposed Changes
1. Add tests for `evolveSession`:
- `thread/started`
- `turn/started`
- `turn/completed` success/failure
- error/session closed events
2. Add tests for `applyEventToMessages`:
- start/delta/completed flow
- out-of-order event cases
- turn completion clearing streaming flags
3. Add reducer integration tests for `APPLY_EVENT`.
## Risks
- Tests may be brittle if event payload fixtures are too coupled to implementation details.
## Validation
- `bun run test`
- Ensure new tests remain deterministic and fast.
## Done Criteria
- High-risk event transitions are covered by unit tests.
- Regressions in stream assembly/session status are caught quickly.
@@ -0,0 +1,35 @@
# Plan: Unify Process and PTY Session Abstractions in ProcessManager
## Summary
Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes.
## Motivation
- `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic.
- New execution backends/providers will multiply complexity.
## Scope
- Desktop process execution internals.
- Preserve public `ProcessManager` API.
## Proposed Changes
1. Introduce internal interface (e.g. `RuntimeSession`):
- `write(data)`
- `kill()`
- lifecycle/output event hooks
2. Implement:
- `ChildProcessSession`
- `PtySession`
3. Replace dual maps with one `Map<string, RuntimeSession>`.
4. Keep output/exit event contract unchanged.
5. Add tests for both implementations.
## Risks
- PTY behavior differs by platform; abstraction must not hide required differences.
## Validation
- Existing `processManager.test.ts` passes.
- Add PTY-path tests where feasible.
## Done Criteria
- Manager no longer branches per backend in `write/kill/killAll`.
- Session backends are independently testable.
+12
View File
@@ -0,0 +1,12 @@
# Maintainability Plans
1. `01-shared-model-normalization.md`
2. `02-typed-ipc-boundaries.md`
3. `03-split-codex-app-server-manager.md`
4. `04-split-chatview-component.md`
5. `05-zod-persisted-state-validation.md`
6. `06-provider-logstream-lifecycle.md`
7. `07-ci-quality-gates.md`
8. `08-precommit-format-and-lint.md`
9. `09-event-state-test-expansion.md`
10. `10-unify-process-session-abstraction.md`
@@ -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
+3
View File
@@ -0,0 +1,3 @@
{
"recommendations": ["oxc.oxc-vscode"]
}
+8
View File
@@ -0,0 +1,8 @@
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "oxc.oxc-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.oxc": "always"
},
"oxc.unusedDisableDirectives": "warn"
}
+43
View File
@@ -0,0 +1,43 @@
# CLAUDE.md
## Project Snapshot
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
## Core Priorities
1. Performance first.
2. Reliability first.
3. Keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).
If a tradeoff is required, choose correctness and robustness over short-term convenience.
## Package Roles
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/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)
T3 Code is currently Codex-first. The server starts `codex app-server` (JSON-RPC over stdio) per provider session, then streams structured events to the browser through WebSocket push messages.
How we use it in this codebase:
- Session startup/resume and turn lifecycle are brokered in `apps/server/src/codexAppServerManager.ts`.
- Provider dispatch and thread event logging are coordinated in `apps/server/src/providerManager.ts`.
- WebSocket server routes NativeApi methods in `apps/server/src/wsServer.ts`.
- Web app consumes provider event streams via WebSocket push on channel `providers.event`.
Docs:
- Codex App Server docs: https://developers.openai.com/codex/sdk/#app-server
## Reference Repos
- Open-source Codex repo: https://github.com/openai/codex
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+107
View File
@@ -0,0 +1,107 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
Run `npx t3` in any project directory to launch the web interface.
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
## Architecture
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
## Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## Codex prerequisites
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
## Quick start
```bash
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
bun run build
bun run start
# Or from any project directory after publishing:
npx t3
```
## Scripts
- `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.
### Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5173`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
## 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 web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for streaming provider events
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`, `providers.listSessions`
- `shell.openInEditor`, `server.getConfig`
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`.
+14
View File
@@ -0,0 +1,14 @@
## TODO
- [ ] 1 click copy in codeblocks
- [ ] Pasting/adding images to submit with prompts
- [ ] Only show last 10 threads for a given project
- [ ] Thread archiving
- [ ] Selecting folder should instantly create project
- [ ] New projects should go on top
- [ ] Projects should be sorted by latest thread update
- [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"
}
}
+31
View File
@@ -0,0 +1,31 @@
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 childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(command, ["dist-electron/main.js"], {
stdio: "inherit",
env: {
...childEnv,
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);
});
+57
View File
@@ -0,0 +1,57 @@
import type { BrowserWindow } from "electron";
import { beforeEach, describe, expect, it, vi } from "vitest";
const { showMessageBoxMock } = vi.hoisted(() => ({
showMessageBoxMock: vi.fn(),
}));
vi.mock("electron", () => ({
dialog: {
showMessageBox: showMessageBoxMock,
},
}));
import { showDesktopConfirmDialog } from "./confirmDialog";
describe("showDesktopConfirmDialog", () => {
beforeEach(() => {
showMessageBoxMock.mockReset();
});
it("returns false and does not open a dialog for empty messages", async () => {
const result = await showDesktopConfirmDialog(" ", null);
expect(result).toBe(false);
expect(showMessageBoxMock).not.toHaveBeenCalled();
});
it("opens a dialog for the focused window and returns true on confirm", async () => {
const ownerWindow = { id: 1 } as BrowserWindow;
showMessageBoxMock.mockResolvedValue({ response: 1 });
const result = await showDesktopConfirmDialog("Delete worktree?", ownerWindow);
expect(result).toBe(true);
expect(showMessageBoxMock).toHaveBeenCalledWith(
ownerWindow,
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
it("opens an app-level dialog when there is no focused window", async () => {
showMessageBoxMock.mockResolvedValue({ response: 0 });
const result = await showDesktopConfirmDialog("Delete worktree?", null);
expect(result).toBe(false);
expect(showMessageBoxMock).toHaveBeenCalledWith(
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
});
+26
View File
@@ -0,0 +1,26 @@
import { type BrowserWindow, dialog } from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export async function showDesktopConfirmDialog(
message: string,
ownerWindow: BrowserWindow | null,
): Promise<boolean> {
const normalizedMessage = message.trim();
if (normalizedMessage.length === 0) {
return false;
}
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: CONFIRM_BUTTON_INDEX,
cancelId: 0,
noLink: true,
message: normalizedMessage,
};
const result = ownerWindow
? await dialog.showMessageBox(ownerWindow, options)
: await dialog.showMessageBox(options);
return result.response === CONFIRM_BUTTON_INDEX;
}
+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.
}
}
+279
View File
@@ -0,0 +1,279 @@
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 { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
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,
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
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(CONFIRM_CHANNEL);
ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
if (typeof message !== "string") {
return false;
}
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
return showDesktopConfirmDialog(message, owner);
});
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();
}
});
+16
View File
@@ -0,0 +1,16 @@
import { contextBridge, ipcRenderer } from "electron";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
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>,
confirm: (message: string) => ipcRenderer.invoke(CONFIRM_CHANNEL, message) as Promise<boolean>,
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": [],
},
},
}
@@ -1,10 +0,0 @@
import { View, Text } from "react-native";
export function RemoteHandoffCard(props: { machine: string; latencyMs: number }) {
return (
<View className="rounded-2xl bg-surface-2 p-4">
<Text className="font-semibold">Ready on {props.machine}</Text>
<Text className="text-success">Handoff in {props.latencyMs}ms</Text>
</View>
);
}
@@ -1,6 +0,0 @@
const PULSE = ["✦", "✧", "·", "✧"] as const;
export function environmentLabel(connected: number, total: number, frame: number): string {
const pulse = PULSE[frame % PULSE.length];
return `${pulse} ${connected}/${total} ready`;
}
+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=${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.");
});
});
+845
View File
@@ -0,0 +1,845 @@
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { EventEmitter } from "node:events";
import readline from "node:readline";
import type {
ProviderApprovalDecision,
ProviderEvent,
ProviderRequestKind,
ProviderSendTurnInput,
ProviderSession,
ProviderSessionStartInput,
ProviderTurnStartResult,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/contracts";
type PendingRequestKey = string;
interface PendingRequest {
method: string;
timeout: ReturnType<typeof setTimeout>;
resolve: (value: unknown) => void;
reject: (error: Error) => void;
}
interface PendingApprovalRequest {
requestId: string;
jsonRpcId: string | number;
method: "item/commandExecution/requestApproval" | "item/fileChange/requestApproval";
requestKind: ProviderRequestKind;
threadId?: string;
turnId?: string;
itemId?: string;
}
interface CodexSessionContext {
session: ProviderSession;
child: ChildProcessWithoutNullStreams;
output: readline.Interface;
pending: Map<PendingRequestKey, PendingRequest>;
pendingApprovals: Map<string, PendingApprovalRequest>;
nextRequestId: number;
stopping: boolean;
}
interface JsonRpcError {
code?: number;
message?: string;
}
interface JsonRpcRequest {
id: string | number;
method: string;
params?: unknown;
}
interface JsonRpcResponse {
id: string | number;
result?: unknown;
error?: JsonRpcError;
}
interface JsonRpcNotification {
method: string;
params?: unknown;
}
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
const CODEX_STDERR_LOG_REGEX =
/^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/;
const BENIGN_ERROR_LOG_SNIPPETS = [
"state db missing rollout path for thread",
"state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
];
const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"not found",
"missing thread",
"no such thread",
"unknown thread",
"does not exist",
];
export function normalizeCodexModelSlug(
model: string | undefined | null,
preferredId?: string,
): string | undefined {
const normalized = normalizeModelSlug(model);
if (!normalized) {
return undefined;
}
if (preferredId?.endsWith("-codex") && preferredId !== normalized) {
return preferredId;
}
return normalized;
}
export function classifyCodexStderrLine(rawLine: string): { message: string } | null {
const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim();
if (!line) {
return null;
}
const match = line.match(CODEX_STDERR_LOG_REGEX);
if (match) {
const level = match[1];
if (level && level !== "ERROR") {
return null;
}
const isBenignError = BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet));
if (isBenignError) {
return null;
}
}
return { message: line };
}
export function isRecoverableThreadResumeError(error: unknown): boolean {
const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
if (!message.includes("thread/resume")) {
return false;
}
return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
}
export interface CodexAppServerManagerEvents {
event: [event: ProviderEvent];
}
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
private readonly sessions = new Map<string, CodexSessionContext>();
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
const sessionId = randomUUID();
const now = new Date().toISOString();
const session: ProviderSession = {
sessionId,
provider: "codex",
status: "connecting",
model: normalizeCodexModelSlug(input.model),
cwd: input.cwd,
createdAt: now,
updatedAt: now,
};
const child = spawn("codex", ["app-server"], {
cwd: input.cwd,
env: process.env,
stdio: ["pipe", "pipe", "pipe"],
});
const output = readline.createInterface({ input: child.stdout });
const context: CodexSessionContext = {
session,
child,
output,
pending: new Map(),
pendingApprovals: new Map(),
nextRequestId: 1,
stopping: false,
};
this.sessions.set(sessionId, context);
this.attachProcessListeners(context);
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
try {
await this.sendRequest(context, "initialize", {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: false,
},
});
this.writeMessage(context, { method: "initialized" });
const normalizedModel = normalizeCodexModelSlug(input.model);
const sessionOverrides = {
model: normalizedModel ?? null,
cwd: input.cwd ?? null,
approvalPolicy: input.approvalPolicy,
sandbox: input.sandboxMode,
};
const threadStartParams = {
...sessionOverrides,
experimentalRawEvents: false,
};
let threadOpenMethod: "thread/start" | "thread/resume" = "thread/start";
let threadOpenResponse: unknown;
if (input.resumeThreadId) {
try {
threadOpenMethod = "thread/resume";
threadOpenResponse = await this.sendRequest(context, "thread/resume", {
...sessionOverrides,
threadId: input.resumeThreadId,
});
} catch (error) {
if (!isRecoverableThreadResumeError(error)) {
throw error;
}
threadOpenMethod = "thread/start";
this.emitLifecycleEvent(
context,
"session/threadResumeFallback",
`Could not resume thread ${input.resumeThreadId}; started a new thread instead.`,
);
threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
}
} else {
threadOpenMethod = "thread/start";
threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
}
const threadOpenRecord = this.readObject(threadOpenResponse);
const threadId =
this.readString(this.readObject(threadOpenRecord, "thread"), "id") ??
this.readString(threadOpenRecord, "threadId");
if (!threadId) {
throw new Error(`${threadOpenMethod} response did not include a thread id.`);
}
this.updateSession(context, {
status: "ready",
threadId,
});
this.emitLifecycleEvent(context, "session/ready", `Connected to thread ${threadId}`);
return { ...context.session };
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to start Codex session.";
this.updateSession(context, {
status: "error",
lastError: message,
});
this.emitErrorEvent(context, "session/startFailed", message);
this.stopSession(sessionId);
throw new Error(message, { cause: error });
}
}
async sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
const context = this.requireSession(input.sessionId);
if (!context.session.threadId) {
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: [] }
| { type: "image"; url: string }
>;
model?: string;
effort?: string;
} = {
threadId: context.session.threadId,
input: turnInput,
};
const normalizedModel = normalizeCodexModelSlug(input.model);
if (normalizedModel) {
turnStartParams.model = normalizedModel;
}
if (input.effort) {
turnStartParams.effort = input.effort;
}
const response = await this.sendRequest(context, "turn/start", turnStartParams);
const turn = this.readObject(this.readObject(response), "turn");
const turnId = this.readString(turn, "id");
if (!turnId) {
throw new Error("turn/start response did not include a turn id.");
}
this.updateSession(context, {
status: "running",
activeTurnId: turnId,
});
return {
threadId: context.session.threadId,
turnId,
};
}
async interruptTurn(sessionId: string, turnId?: string): Promise<void> {
const context = this.requireSession(sessionId);
const effectiveTurnId = turnId ?? context.session.activeTurnId;
if (!effectiveTurnId || !context.session.threadId) {
return;
}
await this.sendRequest(context, "turn/interrupt", {
threadId: context.session.threadId,
turnId: effectiveTurnId,
});
}
async respondToRequest(
sessionId: string,
requestId: string,
decision: ProviderApprovalDecision,
): Promise<void> {
const context = this.requireSession(sessionId);
const pendingRequest = context.pendingApprovals.get(requestId);
if (!pendingRequest) {
throw new Error(`Unknown pending approval request: ${requestId}`);
}
context.pendingApprovals.delete(requestId);
this.writeMessage(context, {
id: pendingRequest.jsonRpcId,
result: {
decision,
},
});
this.emitEvent({
id: randomUUID(),
kind: "notification",
provider: "codex",
sessionId: context.session.sessionId,
createdAt: new Date().toISOString(),
method: "item/requestApproval/decision",
threadId: pendingRequest.threadId,
turnId: pendingRequest.turnId,
itemId: pendingRequest.itemId,
requestId: pendingRequest.requestId,
requestKind: pendingRequest.requestKind,
payload: {
requestId: pendingRequest.requestId,
requestKind: pendingRequest.requestKind,
decision,
},
});
}
stopSession(sessionId: string): void {
const context = this.sessions.get(sessionId);
if (!context) {
return;
}
context.stopping = true;
for (const pending of context.pending.values()) {
clearTimeout(pending.timeout);
pending.reject(new Error("Session stopped before request completed."));
}
context.pending.clear();
context.pendingApprovals.clear();
context.output.close();
if (!context.child.killed) {
context.child.kill();
}
this.updateSession(context, {
status: "closed",
activeTurnId: undefined,
});
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
this.sessions.delete(sessionId);
}
listSessions(): ProviderSession[] {
return Array.from(this.sessions.values(), ({ session }) => ({
...session,
}));
}
hasSession(sessionId: string): boolean {
return this.sessions.has(sessionId);
}
stopAll(): void {
for (const sessionId of this.sessions.keys()) {
this.stopSession(sessionId);
}
}
private requireSession(sessionId: string): CodexSessionContext {
const context = this.sessions.get(sessionId);
if (!context) {
throw new Error(`Unknown session: ${sessionId}`);
}
if (context.session.status === "closed") {
throw new Error(`Session is closed: ${sessionId}`);
}
return context;
}
private attachProcessListeners(context: CodexSessionContext): void {
context.output.on("line", (line) => {
this.handleStdoutLine(context, line);
});
context.child.stderr.on("data", (chunk: Buffer) => {
const raw = chunk.toString();
const lines = raw.split(/\r?\n/g);
for (const rawLine of lines) {
const classified = classifyCodexStderrLine(rawLine);
if (!classified) {
continue;
}
this.emitErrorEvent(context, "process/stderr", classified.message);
}
});
context.child.on("error", (error) => {
const message = error.message || "codex app-server process errored.";
this.updateSession(context, {
status: "error",
lastError: message,
});
this.emitErrorEvent(context, "process/error", message);
});
context.child.on("exit", (code, signal) => {
if (context.stopping) {
return;
}
const message = `codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`;
this.updateSession(context, {
status: "closed",
activeTurnId: undefined,
lastError: code === 0 ? context.session.lastError : message,
});
this.emitLifecycleEvent(context, "session/exited", message);
this.sessions.delete(context.session.sessionId);
});
}
private handleStdoutLine(context: CodexSessionContext, line: string): void {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
this.emitErrorEvent(
context,
"protocol/parseError",
"Received invalid JSON from codex app-server.",
);
return;
}
if (!parsed || typeof parsed !== "object") {
this.emitErrorEvent(
context,
"protocol/invalidMessage",
"Received non-object protocol message.",
);
return;
}
if (this.isServerRequest(parsed)) {
this.handleServerRequest(context, parsed);
return;
}
if (this.isServerNotification(parsed)) {
this.handleServerNotification(context, parsed);
return;
}
if (this.isResponse(parsed)) {
this.handleResponse(context, parsed);
return;
}
this.emitErrorEvent(
context,
"protocol/unrecognizedMessage",
"Received protocol message in an unknown shape.",
);
}
private handleServerNotification(
context: CodexSessionContext,
notification: JsonRpcNotification,
): void {
const route = this.readRouteFields(notification.params);
const textDelta =
notification.method === "item/agentMessage/delta"
? this.readString(notification.params, "delta")
: undefined;
this.emitEvent({
id: randomUUID(),
kind: "notification",
provider: "codex",
sessionId: context.session.sessionId,
createdAt: new Date().toISOString(),
method: notification.method,
threadId: route.threadId,
turnId: route.turnId,
itemId: route.itemId,
textDelta,
payload: notification.params,
});
if (notification.method === "thread/started") {
const threadId = this.readString(this.readObject(notification.params)?.thread, "id");
if (threadId) {
this.updateSession(context, { threadId });
}
return;
}
if (notification.method === "turn/started") {
const turnId = this.readString(this.readObject(notification.params)?.turn, "id");
this.updateSession(context, {
status: "running",
activeTurnId: turnId,
});
return;
}
if (notification.method === "turn/completed") {
const turn = this.readObject(notification.params, "turn");
const status = this.readString(turn, "status");
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
this.updateSession(context, {
status: status === "failed" ? "error" : "ready",
activeTurnId: undefined,
lastError: errorMessage ?? context.session.lastError,
});
return;
}
if (notification.method === "error") {
const message = this.readString(this.readObject(notification.params)?.error, "message");
const willRetry = this.readBoolean(notification.params, "willRetry");
this.updateSession(context, {
status: willRetry ? "running" : "error",
lastError: message ?? context.session.lastError,
});
}
}
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
const route = this.readRouteFields(request.params);
const requestKind = this.requestKindForMethod(request.method);
let requestId: string | undefined;
if (requestKind) {
requestId = randomUUID();
const pendingRequest: PendingApprovalRequest = {
requestId,
jsonRpcId: request.id,
method:
requestKind === "command"
? "item/commandExecution/requestApproval"
: "item/fileChange/requestApproval",
requestKind,
...(route.threadId ? { threadId: route.threadId } : {}),
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
};
context.pendingApprovals.set(requestId, pendingRequest);
}
this.emitEvent({
id: randomUUID(),
kind: "request",
provider: "codex",
sessionId: context.session.sessionId,
createdAt: new Date().toISOString(),
method: request.method,
threadId: route.threadId,
turnId: route.turnId,
itemId: route.itemId,
requestId,
requestKind,
payload: request.params,
});
if (requestKind) {
return;
}
if (request.method === "item/tool/requestUserInput") {
this.writeMessage(context, {
id: request.id,
result: { answers: {} },
});
return;
}
this.writeMessage(context, {
id: request.id,
error: {
code: -32601,
message: `Unsupported server request: ${request.method}`,
},
});
}
private handleResponse(context: CodexSessionContext, response: JsonRpcResponse): void {
const key = String(response.id);
const pending = context.pending.get(key);
if (!pending) {
return;
}
clearTimeout(pending.timeout);
context.pending.delete(key);
if (response.error?.message) {
pending.reject(new Error(`${pending.method} failed: ${String(response.error.message)}`));
return;
}
pending.resolve(response.result);
}
private async sendRequest<TResponse>(
context: CodexSessionContext,
method: string,
params: unknown,
timeoutMs = 20_000,
): Promise<TResponse> {
const id = context.nextRequestId;
context.nextRequestId += 1;
const result = await new Promise<unknown>((resolve, reject) => {
const timeout = setTimeout(() => {
context.pending.delete(String(id));
reject(new Error(`Timed out waiting for ${method}.`));
}, timeoutMs);
context.pending.set(String(id), {
method,
timeout,
resolve,
reject,
});
this.writeMessage(context, {
method,
id,
params,
});
});
return result as TResponse;
}
private writeMessage(context: CodexSessionContext, message: unknown): void {
const encoded = JSON.stringify(message);
if (!context.child.stdin.writable) {
throw new Error("Cannot write to codex app-server stdin.");
}
context.child.stdin.write(`${encoded}\n`);
}
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
this.emitEvent({
id: randomUUID(),
kind: "session",
provider: "codex",
sessionId: context.session.sessionId,
createdAt: new Date().toISOString(),
method,
message,
});
}
private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
this.emitEvent({
id: randomUUID(),
kind: "error",
provider: "codex",
sessionId: context.session.sessionId,
createdAt: new Date().toISOString(),
method,
message,
});
}
private emitEvent(event: ProviderEvent): void {
this.emit("event", event);
}
private updateSession(context: CodexSessionContext, updates: Partial<ProviderSession>): void {
context.session = {
...context.session,
...updates,
updatedAt: new Date().toISOString(),
};
}
private requestKindForMethod(method: string): ProviderRequestKind | undefined {
if (method === "item/commandExecution/requestApproval") {
return "command";
}
if (method === "item/fileChange/requestApproval") {
return "file-change";
}
return undefined;
}
private isServerRequest(value: unknown): value is JsonRpcRequest {
if (!value || typeof value !== "object") {
return false;
}
const candidate = value as Record<string, unknown>;
return (
typeof candidate.method === "string" &&
(typeof candidate.id === "string" || typeof candidate.id === "number")
);
}
private isServerNotification(value: unknown): value is JsonRpcNotification {
if (!value || typeof value !== "object") {
return false;
}
const candidate = value as Record<string, unknown>;
return typeof candidate.method === "string" && !("id" in candidate);
}
private isResponse(value: unknown): value is JsonRpcResponse {
if (!value || typeof value !== "object") {
return false;
}
const candidate = value as Record<string, unknown>;
const hasId = typeof candidate.id === "string" || typeof candidate.id === "number";
const hasMethod = typeof candidate.method === "string";
return hasId && !hasMethod;
}
private readRouteFields(params: unknown): {
threadId?: string;
turnId?: string;
itemId?: string;
} {
const route: {
threadId?: string;
turnId?: string;
itemId?: string;
} = {};
const threadId =
this.readString(params, "threadId") ??
this.readString(this.readObject(params, "thread"), "id");
const turnId =
this.readString(params, "turnId") ?? this.readString(this.readObject(params, "turn"), "id");
const itemId =
this.readString(params, "itemId") ?? this.readString(this.readObject(params, "item"), "id");
if (threadId) {
route.threadId = threadId;
}
if (turnId) {
route.turnId = turnId;
}
if (itemId) {
route.itemId = itemId;
}
return route;
}
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
const target =
key === undefined
? value
: value && typeof value === "object"
? (value as Record<string, unknown>)[key]
: undefined;
if (!target || typeof target !== "object") {
return undefined;
}
return target as Record<string, unknown>;
}
private readString(value: unknown, key: string): string | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const candidate = (value as Record<string, unknown>)[key];
return typeof candidate === "string" ? candidate : undefined;
}
private readBoolean(value: unknown, key: string): boolean | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const candidate = (value as Record<string, unknown>)[key];
return typeof candidate === "boolean" ? candidate : undefined;
}
}
+252
View File
@@ -0,0 +1,252 @@
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";
const CODEX_REASONING_EFFORT = "low";
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
}
}
+623
View File
@@ -0,0 +1,623 @@
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, vi } 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'");
}
async function commitWithDate(
cwd: string,
fileName: string,
fileContents: string,
dateIsoString: string,
message: string,
): Promise<void> {
await writeFile(path.join(cwd, fileName), fileContents);
await git(cwd, `add ${fileName}`);
const commitResult = await runTerminalCommand({
command: `GIT_AUTHOR_DATE="${dateIsoString}" GIT_COMMITTER_DATE="${dateIsoString}" git commit -m "${message}"`,
cwd,
timeoutMs: 10_000,
});
if (commitResult.code !== 0) {
throw new Error(`git dated commit failed: ${commitResult.stderr}`);
}
}
// ── 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("keeps current branch first and sorts the remaining branches by recency", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(branch) => branch.current,
)!.name;
await createGitBranch({ cwd: tmp.path, branch: "older-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
await commitWithDate(
tmp.path,
"older.txt",
"older branch change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"older branch change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await commitWithDate(
tmp.path,
"newer.txt",
"newer branch change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer branch change",
);
// Switch away to show current branch is pinned, then remaining branches are recency-sorted.
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.name).toBe("older-branch");
expect(result.branches[1]!.name).toBe("newer-branch");
});
it("keeps default branch right after current branch", async () => {
await using tmp = await makeTmpDir();
await using remote = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(remote.path, "init --bare");
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(tmp.path, `push -u origin ${defaultBranch}`);
await git(tmp.path, `remote set-head origin ${defaultBranch}`);
await createGitBranch({ cwd: tmp.path, branch: "current-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
await commitWithDate(
tmp.path,
"current.txt",
"current change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"current change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await commitWithDate(
tmp.path,
"newer.txt",
"newer change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.name).toBe("current-branch");
expect(result.branches[1]!.name).toBe(defaultBranch);
expect(result.branches[2]!.name).toBe("newer-branch");
});
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");
});
it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
const recencySpy = vi
.spyOn(core as any, "readBranchRecency")
.mockRejectedValueOnce(new Error("timeout"));
const result = await core.listBranches({ cwd: tmp.path });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThan(0);
expect(result.branches[0]?.current).toBe(true);
recencySpy.mockRestore();
});
});
});
+534
View File
@@ -0,0 +1,534 @@
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;
}
private async readBranchRecency(cwd: string): Promise<Map<string, number>> {
const branchRecency = await executeGit(
cwd,
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
{
timeoutMs: 15_000,
allowNonZeroExit: true,
},
);
const branchLastCommit = new Map<string, number>();
if (branchRecency.code !== 0) {
return branchLastCommit;
}
for (const line of branchRecency.stdout.split("\n")) {
if (line.length === 0) {
continue;
}
const [name, lastCommitRaw] = line.split("\t");
if (!name) {
continue;
}
const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
}
return branchLastCommit;
}
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
() => new Map<string, number>(),
);
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, branchLastCommit] = 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,
}),
branchRecencyPromise,
]);
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) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
if (aPriority !== bPriority) return aPriority - bPriority;
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
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);
}
+489
View File
@@ -0,0 +1,489 @@
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("returns existing PR metadata 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 "))).toBe(false);
});
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);
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
});
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");
});
});
+496
View File
@@ -0,0 +1,496 @@
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) {
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);
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 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);
}
}
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import { ProviderManager } from "./providerManager";
describe("ProviderManager", () => {
it("detaches provider event listener and ends thread log streams on dispose", () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: { listenerCount: (event: string) => number };
onCodexEvent: (event: {
id: string;
kind: "notification";
provider: "codex";
sessionId: string;
createdAt: string;
method: string;
threadId: string;
}) => void;
threadLogStreams: Map<string, { writableEnded: boolean; destroyed: boolean }>;
};
internals.onCodexEvent({
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: new Date().toISOString(),
method: "thread/started",
threadId: "thread-1",
});
const stream = internals.threadLogStreams.get("thread-1");
expect(stream).toBeDefined();
if (!stream) return;
expect(internals.codex.listenerCount("event")).toBe(1);
manager.dispose();
expect(internals.codex.listenerCount("event")).toBe(0);
expect(stream.writableEnded || stream.destroyed).toBe(true);
expect(internals.threadLogStreams.size).toBe(0);
});
it("allows multiple dispose calls", () => {
const manager = new ProviderManager();
manager.dispose();
expect(() => manager.dispose()).not.toThrow();
});
it("rejects request responses for unknown sessions", async () => {
const manager = new ProviderManager();
await expect(
manager.respondToRequest({
sessionId: "missing-session",
requestId: "req-1",
decision: "accept",
}),
).rejects.toThrow("Unknown provider session: missing-session");
manager.dispose();
});
});
+202
View File
@@ -0,0 +1,202 @@
import { EventEmitter } from "node:events";
import fs from "node:fs";
import path from "node:path";
import {
type ProviderEvent,
type ProviderInterruptTurnInput,
type ProviderRespondToRequestInput,
type ProviderSendTurnInput,
type ProviderSession,
type ProviderSessionStartInput,
type ProviderStopSessionInput,
type ProviderTurnStartResult,
providerInterruptTurnInputSchema,
providerRespondToRequestInputSchema,
providerSendTurnInputSchema,
providerSessionStartInputSchema,
providerStopSessionInputSchema,
} from "@t3tools/contracts";
import { CodexAppServerManager } from "./codexAppServerManager";
export interface ProviderManagerEvents {
event: [event: ProviderEvent];
}
export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
private readonly codex = new CodexAppServerManager();
private readonly threadLogsDir: string;
private readonly threadLogStreams = new Map<string, fs.WriteStream>();
private readonly sessionThreadIds = new Map<string, string>();
private readonly pendingEventsBySession = new Map<string, ProviderEvent[]>();
private disposed = false;
private readonly onCodexEvent = (event: ProviderEvent) => {
if (this.disposed) {
return;
}
this.routeEventToThreadLog(event);
this.emit("event", event);
};
constructor() {
super();
const logsDir = path.resolve(process.cwd(), ".logs");
this.threadLogsDir = path.join(logsDir, "threads");
fs.mkdirSync(this.threadLogsDir, { recursive: true });
this.codex.on("event", this.onCodexEvent);
}
async startSession(raw: ProviderSessionStartInput): Promise<ProviderSession> {
const input = providerSessionStartInputSchema.parse(raw);
if (input.provider !== "codex") {
throw new Error(`Provider '${input.provider}' is not implemented yet.`);
}
const session = await this.codex.startSession(input);
if (session.threadId) {
this.sessionThreadIds.set(session.sessionId, session.threadId);
this.flushPendingSessionEvents(session.sessionId, session.threadId);
}
return session;
}
async sendTurn(raw: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
const input = providerSendTurnInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
return this.codex.sendTurn(input);
}
async interruptTurn(raw: ProviderInterruptTurnInput): Promise<void> {
const input = providerInterruptTurnInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
await this.codex.interruptTurn(input.sessionId, input.turnId);
}
async respondToRequest(raw: ProviderRespondToRequestInput): Promise<void> {
const input = providerRespondToRequestInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
await this.codex.respondToRequest(input.sessionId, input.requestId, input.decision);
}
stopSession(raw: ProviderStopSessionInput): void {
const input = providerStopSessionInputSchema.parse(raw);
this.codex.stopSession(input.sessionId);
this.sessionThreadIds.delete(input.sessionId);
this.pendingEventsBySession.delete(input.sessionId);
}
listSessions(): ProviderSession[] {
return this.codex.listSessions();
}
stopAll(): void {
this.codex.stopAll();
}
dispose(): void {
if (this.disposed) {
return;
}
this.disposed = true;
this.codex.off("event", this.onCodexEvent);
for (const stream of this.threadLogStreams.values()) {
stream.end();
}
this.threadLogStreams.clear();
this.sessionThreadIds.clear();
this.pendingEventsBySession.clear();
}
private routeEventToThreadLog(event: ProviderEvent): void {
const threadId = this.resolveThreadId(event);
if (!threadId) {
const pending = this.pendingEventsBySession.get(event.sessionId) ?? [];
pending.push(event);
this.pendingEventsBySession.set(event.sessionId, pending.slice(-100));
return;
}
this.flushPendingSessionEvents(event.sessionId, threadId);
this.writeThreadEvent(threadId, event);
}
private flushPendingSessionEvents(sessionId: string, threadId: string): void {
const pending = this.pendingEventsBySession.get(sessionId);
if (!pending || pending.length === 0) {
return;
}
for (const event of pending) {
this.writeThreadEvent(threadId, event);
}
this.pendingEventsBySession.delete(sessionId);
}
private resolveThreadId(event: ProviderEvent): string | undefined {
const fromPayload = this.readThreadIdFromPayload(event.payload);
const threadId = event.threadId ?? fromPayload ?? this.sessionThreadIds.get(event.sessionId);
if (threadId) {
this.sessionThreadIds.set(event.sessionId, threadId);
}
return threadId;
}
private readThreadIdFromPayload(payload: unknown): string | undefined {
if (!payload || typeof payload !== "object") {
return undefined;
}
const record = payload as Record<string, unknown>;
const direct = record.threadId;
if (typeof direct === "string" && direct.length > 0) {
return direct;
}
const thread = record.thread;
if (!thread || typeof thread !== "object") {
return undefined;
}
const nested = (thread as Record<string, unknown>).id;
if (typeof nested === "string" && nested.length > 0) {
return nested;
}
return undefined;
}
private writeThreadEvent(threadId: string, event: ProviderEvent): void {
const stream = this.getOrCreateThreadLogStream(threadId);
stream.write(`${JSON.stringify(event)}\n`);
}
private getOrCreateThreadLogStream(threadId: string): fs.WriteStream {
const cached = this.threadLogStreams.get(threadId);
if (cached) {
return cached;
}
const safeThreadId = threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
const stream = fs.createWriteStream(
path.join(this.threadLogsDir, `${safeThreadId}.events.ndjson`),
{ flags: "a" },
);
this.threadLogStreams.set(threadId, stream);
return stream;
}
}
+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);
}
}
+427
View File
@@ -0,0 +1,427 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { DEFAULT_TERMINAL_ID, type TerminalEvent, type 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 multiTerminalHistoryLogName(threadId: string, terminalId: string): string {
const threadPart = `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
if (terminalId === DEFAULT_TERMINAL_ID) {
return `${threadPart}.log`;
}
return `${threadPart}_${Buffer.from(terminalId, "utf8").toString("base64url")}.log`;
}
function historyLogPath(logsDir: string, threadId = "thread-1"): string {
return path.join(logsDir, historyLogName(threadId));
}
function multiTerminalHistoryLogPath(
logsDir: string,
threadId = "thread-1",
terminalId = "default",
): string {
return path.join(logsDir, multiTerminalHistoryLogName(threadId, terminalId));
}
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;
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
subprocessPollIntervalMs?: number;
} = {},
) {
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"),
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
...(options.subprocessPollIntervalMs
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
: {}),
});
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(first.terminalId).toBe("default");
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("supports multiple terminals per thread with isolated sessions", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput({ terminalId: "default" }));
await manager.open(openInput({ terminalId: "term-2" }));
const first = ptyAdapter.processes[0];
const second = ptyAdapter.processes[1];
expect(first).toBeDefined();
expect(second).toBeDefined();
if (!first || !second) return;
await manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" });
await manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" });
expect(first.writes).toEqual(["pwd\n"]);
expect(second.writes).toEqual(["ls\n"]);
expect(ptyAdapter.spawnInputs).toHaveLength(2);
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);
expect(
events.some(
(event) =>
event.type === "cleared" &&
event.threadId === "thread-1" &&
event.terminalId === "default",
),
).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("emits subprocess activity events when child-process state changes", async () => {
let hasRunningSubprocess = false;
const { manager } = makeManager(5, {
subprocessChecker: async () => hasRunningSubprocess,
subprocessPollIntervalMs: 20,
});
const events: TerminalEvent[] = [];
manager.on("event", (event) => {
events.push(event);
});
await manager.open(openInput());
await waitFor(() => events.some((event) => event.type === "started"));
expect(events.some((event) => event.type === "activity")).toBe(false);
hasRunningSubprocess = true;
await waitFor(
() =>
events.some(
(event) => event.type === "activity" && event.hasRunningSubprocess === true,
),
1_200,
);
hasRunningSubprocess = false;
await waitFor(
() =>
events.some(
(event) => event.type === "activity" && event.hasRunningSubprocess === false,
),
1_200,
);
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("closes all terminals for a thread when close omits terminalId", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput({ terminalId: "default" }));
await manager.open(openInput({ terminalId: "sidecar" }));
const defaultProcess = ptyAdapter.processes[0];
const sidecarProcess = ptyAdapter.processes[1];
expect(defaultProcess).toBeDefined();
expect(sidecarProcess).toBeDefined();
if (!defaultProcess || !sidecarProcess) return;
defaultProcess.emitData("default\n");
sidecarProcess.emitData("sidecar\n");
await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default")));
await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar")));
await manager.close({ threadId: "thread-1", deleteHistory: true });
expect(defaultProcess.killed).toBe(true);
expect(sidecarProcess.killed).toBe(true);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(
false,
);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(
false,
);
manager.dispose();
});
it("migrates legacy transcript filenames to terminal-scoped history path on open", async () => {
const { manager, logsDir } = makeManager();
const legacyPath = path.join(logsDir, "thread-1.log");
const nextPath = historyLogPath(logsDir);
fs.writeFileSync(legacyPath, "legacy-line\n", "utf8");
const snapshot = await manager.open(openInput());
expect(snapshot.history).toBe("legacy-line\n");
expect(fs.existsSync(nextPath)).toBe(true);
expect(fs.readFileSync(nextPath, "utf8")).toBe("legacy-line\n");
expect(fs.existsSync(legacyPath)).toBe(false);
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();
});
});
+965
View File
@@ -0,0 +1,965 @@
import { EventEmitter } from "node:events";
import fs from "node:fs";
import path from "node:path";
import {
DEFAULT_TERMINAL_ID,
type TerminalClearInput,
type TerminalCloseInput,
type TerminalEvent,
type TerminalOpenInput,
type TerminalResizeInput,
type TerminalSessionSnapshot,
type TerminalSessionStatus,
type TerminalWriteInput,
terminalClearInputSchema,
terminalCloseInputSchema,
terminalOpenInputSchema,
terminalResizeInputSchema,
terminalWriteInputSchema,
} from "@t3tools/contracts";
import { createLogger } from "./logger";
import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
import { runProcess } from "./processRunner";
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
export interface TerminalManagerEvents {
event: [event: TerminalEvent];
}
export interface TerminalManagerOptions {
logsDir?: string;
historyLineLimit?: number;
ptyAdapter?: PtyAdapter;
shellResolver?: () => string;
subprocessChecker?: TerminalSubprocessChecker;
subprocessPollIntervalMs?: number;
}
interface TerminalSessionState {
threadId: string;
terminalId: 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;
hasRunningSubprocess: boolean;
}
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")
);
}
async function checkWindowsSubprocessActivity(terminalPid: number): Promise<boolean> {
const command = [
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
"if ($children) { exit 0 }",
"exit 1",
].join("; ");
try {
const result = await runProcess(
"powershell.exe",
["-NoProfile", "-NonInteractive", "-Command", command],
{
timeoutMs: 1_500,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
},
);
return result.code === 0;
} catch {
return false;
}
}
async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolean> {
try {
const pgrepResult = await runProcess("pgrep", ["-P", String(terminalPid)], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
});
if (pgrepResult.code === 0) {
return pgrepResult.stdout.trim().length > 0;
}
if (pgrepResult.code === 1) {
return false;
}
} catch {
// Fall back to ps when pgrep is unavailable.
}
try {
const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
});
if (psResult.code !== 0) {
return false;
}
for (const line of psResult.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
if (ppid === terminalPid) {
return true;
}
}
return false;
} catch {
return false;
}
}
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return false;
}
if (process.platform === "win32") {
return checkWindowsSubprocessActivity(terminalPid);
}
return checkPosixSubprocessActivity(terminalPid);
}
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")}`;
}
function toSafeTerminalId(terminalId: string): string {
return Buffer.from(terminalId, "utf8").toString("base64url");
}
function toSessionKey(threadId: string, terminalId: string): string {
return `${threadId}\u0000${terminalId}`;
}
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 subprocessChecker: TerminalSubprocessChecker;
private readonly subprocessPollIntervalMs: number;
private subprocessPollTimer: ReturnType<typeof setInterval> | null = null;
private subprocessPollInFlight = false;
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;
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
this.subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_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 sessionKey = toSessionKey(input.threadId, input.terminalId);
const existing = this.sessions.get(sessionKey);
if (!existing) {
await this.flushPersistQueue(input.threadId, input.terminalId);
const history = await this.readHistory(input.threadId, input.terminalId);
const session: TerminalSessionState = {
threadId: input.threadId,
terminalId: input.terminalId,
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,
hasRunningSubprocess: false,
};
this.sessions.set(sessionKey, 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.terminalId, existing.history);
} else if (existing.status === "exited" || existing.status === "error") {
existing.history = "";
await this.persistHistory(existing.threadId, existing.terminalId, 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, input.terminalId);
if (!session.process || session.status !== "running") {
throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
}
session.process.write(input.data);
}
async resize(raw: TerminalResizeInput): Promise<void> {
const input = terminalResizeInputSchema.parse(raw);
const session = this.requireSession(input.threadId, input.terminalId);
if (!session.process || session.status !== "running") {
throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
}
session.cols = input.cols;
session.rows = input.rows;
session.updatedAt = new Date().toISOString();
session.process.resize(input.cols, input.rows);
}
async clear(raw: TerminalClearInput): Promise<void> {
const input = terminalClearInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => {
const session = this.requireSession(input.threadId, input.terminalId);
session.history = "";
session.updatedAt = new Date().toISOString();
await this.persistHistory(input.threadId, input.terminalId, session.history);
this.emitEvent({
type: "cleared",
threadId: input.threadId,
terminalId: input.terminalId,
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);
const sessionKey = toSessionKey(input.threadId, input.terminalId);
let session = this.sessions.get(sessionKey);
if (!session) {
session = {
threadId: input.threadId,
terminalId: input.terminalId,
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,
hasRunningSubprocess: false,
};
this.sessions.set(sessionKey, session);
} else {
this.stopProcess(session);
session.cwd = input.cwd;
}
session.history = "";
await this.persistHistory(input.threadId, input.terminalId, 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 () => {
if (input.terminalId) {
await this.closeSession(
input.threadId,
input.terminalId,
input.deleteHistory === true,
);
return;
}
const threadSessions = this.sessionsForThread(input.threadId);
for (const session of threadSessions) {
this.stopProcess(session);
this.sessions.delete(toSessionKey(session.threadId, session.terminalId));
}
await Promise.all(
threadSessions.map((session) =>
this.flushPersistQueue(session.threadId, session.terminalId),
),
);
if (input.deleteHistory) {
await this.deleteAllHistoryForThread(input.threadId);
}
this.updateSubprocessPollingState();
});
}
dispose(): void {
this.stopSubprocessPolling();
const sessions = [...this.sessions.values()];
this.sessions.clear();
for (const session of sessions) {
this.stopProcess(session);
}
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.hasRunningSubprocess = false;
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.updateSubprocessPollingState();
this.emitEvent({
type: eventType,
threadId: session.threadId,
terminalId: session.terminalId,
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.hasRunningSubprocess = false;
session.updatedAt = new Date().toISOString();
this.updateSubprocessPollingState();
const message = error instanceof Error ? error.message : "Terminal start failed";
this.emitEvent({
type: "error",
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
message,
});
this.logger.error("failed to start terminal", {
threadId: session.threadId,
terminalId: session.terminalId,
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.terminalId, session.history);
this.emitEvent({
type: "output",
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
data,
});
}
private onProcessExit(session: TerminalSessionState, event: PtyExitEvent): void {
this.cleanupProcessHandles(session);
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
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,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
exitCode: session.exitCode,
exitSignal: session.exitSignal,
});
this.updateSubprocessPollingState();
}
private stopProcess(session: TerminalSessionState): void {
const process = session.process;
if (!process) return;
this.cleanupProcessHandles(session);
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
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,
terminalId: session.terminalId,
error: message,
});
}
this.updateSubprocessPollingState();
}
private cleanupProcessHandles(session: TerminalSessionState): void {
session.unsubscribeData?.();
session.unsubscribeData = null;
session.unsubscribeExit?.();
session.unsubscribeExit = null;
}
private queuePersist(threadId: string, terminalId: string, history: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
this.pendingPersistHistory.set(persistenceKey, history);
this.schedulePersist(threadId, terminalId);
}
private async persistHistory(
threadId: string,
terminalId: string,
history: string,
): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
this.clearPersistTimer(threadId, terminalId);
this.pendingPersistHistory.delete(persistenceKey);
await this.enqueuePersistWrite(threadId, terminalId, history);
}
private enqueuePersistWrite(
threadId: string,
terminalId: string,
history: string,
): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
const task = async () => {
await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8");
};
const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve();
const next = previous
.catch(() => undefined)
.then(task)
.catch((error) => {
this.logger.warn("failed to persist terminal history", {
threadId,
terminalId,
error: error instanceof Error ? error.message : String(error),
});
});
this.persistQueues.set(persistenceKey, next);
const finalized = next.finally(() => {
if (this.persistQueues.get(persistenceKey) === next) {
this.persistQueues.delete(persistenceKey);
}
if (
this.pendingPersistHistory.has(persistenceKey) &&
!this.persistTimers.has(persistenceKey)
) {
this.schedulePersist(threadId, terminalId);
}
});
void finalized.catch(() => undefined);
return finalized;
}
private schedulePersist(threadId: string, terminalId: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
if (this.persistTimers.has(persistenceKey)) return;
const timer = setTimeout(() => {
this.persistTimers.delete(persistenceKey);
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
if (pendingHistory === undefined) return;
this.pendingPersistHistory.delete(persistenceKey);
void this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
}, this.persistDebounceMs);
this.persistTimers.set(persistenceKey, timer);
}
private clearPersistTimer(threadId: string, terminalId: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
const timer = this.persistTimers.get(persistenceKey);
if (!timer) return;
clearTimeout(timer);
this.persistTimers.delete(persistenceKey);
}
private async readHistory(threadId: string, terminalId: string): Promise<string> {
const nextPath = this.historyPath(threadId, terminalId);
try {
const raw = await fs.promises.readFile(nextPath, "utf8");
const capped = capHistory(raw, this.historyLineLimit);
if (capped !== raw) {
await fs.promises.writeFile(nextPath, capped, "utf8");
}
return capped;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
throw error;
}
}
if (terminalId !== DEFAULT_TERMINAL_ID) {
return "";
}
const legacyPath = this.legacyHistoryPath(threadId);
try {
const raw = await fs.promises.readFile(legacyPath, "utf8");
const capped = capHistory(raw, this.historyLineLimit);
// Migrate legacy transcript filename to the terminal-scoped path.
await fs.promises.writeFile(nextPath, capped, "utf8");
try {
await fs.promises.rm(legacyPath, { force: true });
} catch (cleanupError) {
this.logger.warn("failed to remove legacy terminal history", {
threadId,
error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
});
}
return capped;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return "";
}
throw error;
}
}
private async deleteHistory(threadId: string, terminalId: string): Promise<void> {
const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })];
if (terminalId === DEFAULT_TERMINAL_ID) {
deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }));
}
try {
await Promise.all(deletions);
} catch (error) {
this.logger.warn("failed to delete terminal history", {
threadId,
terminalId,
error: error instanceof Error ? error.message : String(error),
});
}
}
private async flushPersistQueue(threadId: string, terminalId: string): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
this.clearPersistTimer(threadId, terminalId);
while (true) {
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
if (pendingHistory !== undefined) {
this.pendingPersistHistory.delete(persistenceKey);
await this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
}
const pending = this.persistQueues.get(persistenceKey);
if (!pending) {
return;
}
await pending.catch(() => undefined);
}
}
private updateSubprocessPollingState(): void {
const hasRunningSessions = [...this.sessions.values()].some(
(session) => session.status === "running" && session.pid !== null,
);
if (hasRunningSessions) {
this.ensureSubprocessPolling();
return;
}
this.stopSubprocessPolling();
}
private ensureSubprocessPolling(): void {
if (this.subprocessPollTimer) return;
this.subprocessPollTimer = setInterval(() => {
void this.pollSubprocessActivity();
}, this.subprocessPollIntervalMs);
this.subprocessPollTimer.unref?.();
void this.pollSubprocessActivity();
}
private stopSubprocessPolling(): void {
if (!this.subprocessPollTimer) return;
clearInterval(this.subprocessPollTimer);
this.subprocessPollTimer = null;
}
private async pollSubprocessActivity(): Promise<void> {
if (this.subprocessPollInFlight) return;
const runningSessions = [...this.sessions.values()].filter(
(session): session is TerminalSessionState & { pid: number } =>
session.status === "running" && Number.isInteger(session.pid),
);
if (runningSessions.length === 0) {
this.stopSubprocessPolling();
return;
}
this.subprocessPollInFlight = true;
try {
await Promise.all(
runningSessions.map(async (session) => {
const terminalPid = session.pid;
let hasRunningSubprocess = false;
try {
hasRunningSubprocess = await this.subprocessChecker(terminalPid);
} catch (error) {
this.logger.warn("failed to check terminal subprocess activity", {
threadId: session.threadId,
terminalId: session.terminalId,
terminalPid,
error: error instanceof Error ? error.message : String(error),
});
return;
}
const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId));
if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) {
return;
}
if (liveSession.hasRunningSubprocess === hasRunningSubprocess) {
return;
}
liveSession.hasRunningSubprocess = hasRunningSubprocess;
liveSession.updatedAt = new Date().toISOString();
this.emitEvent({
type: "activity",
threadId: liveSession.threadId,
terminalId: liveSession.terminalId,
createdAt: new Date().toISOString(),
hasRunningSubprocess,
});
}),
);
} finally {
this.subprocessPollInFlight = false;
}
}
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 async closeSession(
threadId: string,
terminalId: string,
deleteHistory: boolean,
): Promise<void> {
const key = toSessionKey(threadId, terminalId);
const session = this.sessions.get(key);
if (session) {
this.stopProcess(session);
this.sessions.delete(key);
}
this.updateSubprocessPollingState();
await this.flushPersistQueue(threadId, terminalId);
if (deleteHistory) {
await this.deleteHistory(threadId, terminalId);
}
}
private sessionsForThread(threadId: string): TerminalSessionState[] {
return [...this.sessions.values()].filter((session) => session.threadId === threadId);
}
private async deleteAllHistoryForThread(threadId: string): Promise<void> {
const threadPrefix = `${toSafeThreadId(threadId)}_`;
try {
const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true });
const removals = entries
.filter((entry) => entry.isFile())
.map((entry) => entry.name)
.filter(
(name) =>
name === `${toSafeThreadId(threadId)}.log` ||
name === `${legacySafeThreadId(threadId)}.log` ||
name.startsWith(threadPrefix),
)
.map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true }));
await Promise.all(removals);
} catch (error) {
this.logger.warn("failed to delete terminal histories for thread", {
threadId,
error: error instanceof Error ? error.message : String(error),
});
}
}
private requireSession(threadId: string, terminalId: string): TerminalSessionState {
const session = this.sessions.get(toSessionKey(threadId, terminalId));
if (!session) {
throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`);
}
return session;
}
private snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
return {
threadId: session.threadId,
terminalId: session.terminalId,
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, terminalId: string): string {
const threadPart = toSafeThreadId(threadId);
if (terminalId === DEFAULT_TERMINAL_ID) {
return path.join(this.logsDir, `${threadPart}.log`);
}
return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.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);
}
}
}
}
+679
View File
@@ -0,0 +1,679 @@
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 {
DEFAULT_TERMINAL_ID,
WS_CHANNELS,
WS_METHODS,
type WsPush,
type WsResponse,
} from "@t3tools/contracts";
import { ProjectRegistry } from "./projectRegistry";
import type {
TerminalClearInput,
TerminalCloseInput,
TerminalEvent,
TerminalOpenInput,
TerminalResizeInput,
TerminalSessionSnapshot,
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>();
private key(threadId: string, terminalId: string): string {
return `${threadId}\u0000${terminalId}`;
}
async open(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const now = new Date().toISOString();
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const snapshot: TerminalSessionSnapshot = {
threadId: input.threadId,
terminalId,
cwd: input.cwd,
status: "running",
pid: 4242,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: now,
};
this.sessions.set(this.key(input.threadId, terminalId), snapshot);
queueMicrotask(() => {
this.emit("event", {
type: "started",
threadId: input.threadId,
terminalId,
createdAt: now,
snapshot,
});
});
return snapshot;
}
async write(input: TerminalWriteInput): Promise<void> {
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const existing = this.sessions.get(this.key(input.threadId, terminalId));
if (!existing) {
throw new Error(`Unknown terminal thread: ${input.threadId}`);
}
queueMicrotask(() => {
this.emit("event", {
type: "output",
threadId: input.threadId,
terminalId,
createdAt: new Date().toISOString(),
data: input.data,
});
});
}
async resize(_input: TerminalResizeInput): Promise<void> {}
async clear(input: TerminalClearInput): Promise<void> {
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
queueMicrotask(() => {
this.emit("event", {
type: "cleared",
threadId: input.threadId,
terminalId,
createdAt: new Date().toISOString(),
});
});
}
async restart(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const now = new Date().toISOString();
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const snapshot: TerminalSessionSnapshot = {
threadId: input.threadId,
terminalId,
cwd: input.cwd,
status: "running",
pid: 5252,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: now,
};
this.sessions.set(this.key(input.threadId, terminalId), snapshot);
queueMicrotask(() => {
this.emit("event", {
type: "restarted",
threadId: input.threadId,
terminalId,
createdAt: now,
snapshot,
});
});
return snapshot;
}
async close(input: TerminalCloseInput): Promise<void> {
if (input.terminalId) {
this.sessions.delete(this.key(input.threadId, input.terminalId));
return;
}
for (const key of [...this.sessions.keys()]) {
if (key.startsWith(`${input.threadId}\u0000`)) {
this.sessions.delete(key);
}
}
}
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");
expect((open.result as TerminalSessionSnapshot).terminalId).toBe(DEFAULT_TERMINAL_ID);
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",
terminalId: DEFAULT_TERMINAL_ID,
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,
},
},
}
+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>
+37
View File
@@ -0,0 +1,37 @@
{
"name": "@t3tools/web",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@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",
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
"rehype-highlight": "^7.0.2",
"remark-gfm": "^4.0.1",
"zod": "^3.24.1"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@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": "^8.0.0-beta.12"
}
}
+205
View File
@@ -0,0 +1,205 @@
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, DEFAULT_THREAD_TERMINAL_ID } 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) => {
dispatch({
type: "APPLY_TERMINAL_EVENT",
event,
});
});
}, [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,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
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>
);
}
+28
View File
@@ -0,0 +1,28 @@
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight";
import remarkGfm from "remark-gfm";
interface ChatMarkdownProps {
text: string;
}
const markdownComponents: Components = {
a({ node: _node, ...props }) {
return <a {...props} target="_blank" rel="noreferrer" />;
},
};
export default function ChatMarkdown({ text }: ChatMarkdownProps) {
return (
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[[rehypeHighlight, { detect: true, ignoreMissing: true }]]}
components={markdownComponents}
>
{text}
</ReactMarkdown>
</div>
);
}
File diff suppressed because it is too large. Load diff
+55
View File
@@ -0,0 +1,55 @@
import { isElectron } from "../env";
import { useStore } from "../store";
export default function DiffPanel() {
const { dispatch } = useStore();
return (
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
{/* Header */}
<div
className={`flex items-center justify-between border-b border-border px-4 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
>
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
<button
type="button"
className="text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground"
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
<span className="text-sm">&times;</span>
</button>
</div>
{/* Placeholder content */}
<div className="flex-1 overflow-y-auto p-4">
<div className="space-y-3">
<div className="rounded-lg border border-border/80 bg-muted p-3">
<div className="mb-2 flex items-center gap-2">
<span className="rounded bg-emerald-500/20 px-1.5 py-0.5 text-[9px] font-medium text-emerald-400">
M
</span>
<span className="font-mono text-xs text-muted-foreground/80">src/App.tsx</span>
</div>
<div className="space-y-0.5 font-mono text-[11px]">
<div className="text-red-400/60">- const oldValue = "hello";</div>
<div className="text-emerald-400/60">+ const newValue = "world";</div>
</div>
</div>
<div className="rounded-lg border border-border/80 bg-muted p-3">
<div className="flex items-center gap-2">
<span className="rounded bg-blue-500/20 px-1.5 py-0.5 text-[9px] font-medium text-blue-400">
A
</span>
<span className="font-mono text-xs text-muted-foreground/80">src/utils.ts</span>
</div>
</div>
</div>
<p className="mt-6 text-center text-[10px] text-muted-foreground/30">
Diff integration coming soon
</p>
</div>
</aside>
);
}
@@ -0,0 +1,905 @@
import {
type GitRunStackedActionResult,
type GitStackedAction,
type GitStatusResult,
type NativeApi,
} from "@t3tools/contracts";
import { queryOptions, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
CheckIcon,
CloudUploadIcon,
GitCommitIcon,
Loader2Icon,
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;
}
interface GitProgressToastAction {
kind: "open_pr" | "create_pr";
label: "Open PR" | "Create PR";
}
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 runningStepMessage(stepId: GitProgressStep["id"]): string {
if (stepId === "generate") return "Generating commit message...";
if (stepId === "commit") return "Committing changes...";
if (stepId === "push") return "Pushing branch...";
return "Preparing pull request...";
}
function gitActionModalTitle(): string {
return "Commit your changes";
}
function initialGitProgressSteps(action: GitStackedAction, includeGenerateStep: boolean): GitProgressStep[] {
const steps: GitProgressStep[] = [];
if (includeGenerateStep) {
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 canCreatePrFromStatus(gitStatus: GitStatusResult | null): boolean {
if (!gitStatus) return false;
const hasBranch = gitStatus.branch !== null;
const hasOpenPr = gitStatus.openPr !== null;
return (
hasBranch &&
!hasOpenPr &&
!gitStatus.hasWorkingTreeChanges &&
gitStatus.hasUpstream &&
gitStatus.behindCount === 0
);
}
export function getGitProgressToastAction(params: {
isRunning: boolean;
hasError: boolean;
result: GitRunStackedActionResult | null;
gitStatus: GitStatusResult | null;
openPrUrl: string | null;
}): GitProgressToastAction | null {
if (params.isRunning || params.hasError || !params.result) {
return null;
}
if (params.openPrUrl) {
return {
kind: "open_pr",
label: "Open PR",
};
}
if (params.result.action === "commit_push" && canCreatePrFromStatus(params.gitStatus)) {
return {
kind: "create_pr",
label: "Create PR",
};
}
return null;
}
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 && canCreatePrFromStatus(gitStatus);
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 [isGitProgressToastVisible, setIsGitProgressToastVisible] = useState(false);
const gitMenuRef = useRef<HTMLDivElement>(null);
const { data: gitStatus = null, error: gitStatusError } = useQuery(
gitStatusQueryOptions(api, gitCwd),
);
const isGitActionRunning = isGitModalActionRunning;
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 gitProgressToastOpenPrUrl = gitModalResult?.pr.url ?? gitStatus?.openPr?.url ?? null;
const showGitProgressToast =
isGitProgressToastVisible &&
(isGitModalActionRunning ||
gitModalProgress.length > 0 ||
gitModalError !== null ||
gitModalResult !== null);
const activeGitProgressStep = useMemo(
() => gitModalProgress.find((step) => step.status === "running") ?? null,
[gitModalProgress],
);
const gitProgressToastStatus = isGitModalActionRunning
? "running"
: gitModalError
? "failed"
: "done";
const gitProgressToastMessage = isGitModalActionRunning
? runningStepMessage(activeGitProgressStep?.id ?? "commit")
: gitModalError
? "Git action failed."
: "Done.";
const gitProgressToastAction = useMemo(
() =>
getGitProgressToastAction({
isRunning: isGitModalActionRunning,
hasError: gitModalError !== null,
result: gitModalResult,
gitStatus,
openPrUrl: gitProgressToastOpenPrUrl,
}),
[
gitModalError,
gitModalResult,
gitProgressToastOpenPrUrl,
gitStatus,
isGitModalActionRunning,
],
);
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("");
setIsGitProgressToastVisible(false);
setGitModalProgress([]);
setGitModalError(null);
setGitModalResult(null);
setGitActionError(null);
}, []);
const closeGitActionModal = useCallback(() => {
if (isGitActionRunning) return;
setIsGitModalOpen(false);
setGitModalSelectedAction("commit");
setGitModalCommitMessage("");
}, [isGitActionRunning]);
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 openPrFromToast = useCallback(() => {
if (!api) {
setGitModalError("Link opening is unavailable.");
return;
}
const prUrl = gitProgressToastOpenPrUrl;
if (!prUrl) return;
void api.shell.openExternal(prUrl).catch((error) => {
setGitModalError(error instanceof Error ? error.message : "Unable to open PR link.");
});
}, [api, gitProgressToastOpenPrUrl]);
const dismissGitProgressToast = useCallback(() => {
if (isGitModalActionRunning) return;
setIsGitProgressToastVisible(false);
setGitModalProgress([]);
setGitModalError(null);
setGitModalResult(null);
}, [isGitModalActionRunning]);
const executeGitAction = useCallback(
async (params: {
action: GitStackedAction;
commitMessage: string;
includeGeneratedCommitMessage: boolean;
closeModal: boolean;
}) => {
if (!api || !gitCwd) return;
const actionCwd = gitCwd;
const { action, closeModal, commitMessage, includeGeneratedCommitMessage } = params;
setIsGitMenuOpen(false);
if (closeModal) {
setIsGitModalOpen(false);
}
setIsGitProgressToastVisible(true);
setIsGitModalActionRunning(true);
setGitModalError(null);
setGitActionError(null);
setGitModalResult(null);
setGitModalProgress(initialGitProgressSteps(action, includeGeneratedCommitMessage));
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, refreshGitStatus],
);
const runGitActionImmediately = useCallback(
(action: GitStackedAction) => {
void executeGitAction({
action,
commitMessage: "",
includeGeneratedCommitMessage: false,
closeModal: false,
});
},
[executeGitAction],
);
const runGitAction = useCallback(() => {
if (!selectedGitModalActionOption || selectedGitModalActionOption.disabled) return;
const commitMessage = gitModalCommitMessage.trim();
void executeGitAction({
action: selectedGitModalActionOption.action,
commitMessage,
includeGeneratedCommitMessage: commitMessage.length === 0,
closeModal: true,
});
}, [executeGitAction, gitModalCommitMessage, selectedGitModalActionOption]);
useEffect(() => {
setGitActionError(null);
setGitModalError(null);
setIsGitModalOpen(false);
setIsGitProgressToastVisible(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}
>
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={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">
{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>
);
})}
</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">
<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={closeGitActionModal}
disabled={isGitActionRunning}
>
Cancel
</button>
<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={() => {
runGitAction();
}}
disabled={isGitActionRunning || !selectedGitModalActionOption}
>
{runActionLabel(gitModalSelectedAction)}
</button>
</div>
</div>
</div>
)}
{showGitProgressToast && (
<div
className="fixed bottom-4 right-4 z-[90]"
role="status"
aria-live="polite"
>
<div className="flex max-w-[calc(100vw-2rem)] items-center gap-2 rounded-xl border border-border bg-popover/95 px-3 py-2 shadow-xl backdrop-blur">
<span className="shrink-0">
{gitProgressToastStatus === "running" ? (
<Loader2Icon className="h-4 w-4 animate-spin text-foreground" />
) : gitProgressToastStatus === "failed" ? (
<XIcon className="h-4 w-4 text-rose-500 dark:text-rose-300" />
) : (
<CheckIcon className="h-4 w-4 text-emerald-600 dark:text-emerald-300" />
)}
</span>
<span className="min-w-0 truncate text-sm text-foreground">{gitProgressToastMessage}</span>
{!isGitModalActionRunning && gitProgressToastAction && (
<button
type="button"
className="rounded-md bg-foreground px-2.5 py-1 text-xs font-medium text-background transition-colors duration-150 hover:bg-foreground/90 disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => {
if (gitProgressToastAction.kind === "open_pr") {
openPrFromToast();
return;
}
runGitActionImmediately("commit_push_pr");
}}
disabled={isGitModalActionRunning}
>
{gitProgressToastAction.label}
</button>
)}
<button
type="button"
className="rounded p-1 text-muted-foreground/60 transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"
onClick={dismissGitProgressToast}
disabled={isGitModalActionRunning}
aria-label="Dismiss git action progress toast"
>
<XIcon className="h-4 w-4" />
</button>
</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="currentColor"
/>
</svg>
);
+579
View File
@@ -0,0 +1,579 @@
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
type Project,
type Thread,
} from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
function formatRelativeTime(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const minutes = Math.floor(diff / 60_000);
if (minutes < 1) return "just now";
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
function inferProjectName(cwd: string): string {
const normalized = cwd.replace(/\\/g, "/").replace(/\/+$/, "");
const parts = normalized.split("/");
const last = parts[parts.length - 1];
return last && last.length > 0 ? last : "project";
}
interface ThreadStatusPill {
label: "Working" | "Connecting" | "Completed" | "Awaiting response";
colorClass: string;
dotClass: string;
pulse: boolean;
}
interface TerminalStatusIndicator {
label: "Terminal process running";
colorClass: 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;
}
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
if (thread.runningTerminalIds.length === 0) {
return null;
}
return {
label: "Terminal process running",
colorClass: "text-teal-600 dark:text-teal-300/90",
pulse: true,
};
}
export default function Sidebar() {
const { state, dispatch } = useStore();
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,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
branch: null,
worktreePath: null,
},
});
},
[dispatch, state.projects],
);
const focusMostRecentThreadForProject = useCallback(
(projectId: string) => {
const latestThread = state.threads
.filter((thread) => thread.projectId === projectId)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
if (byDate !== 0) return byDate;
return b.id.localeCompare(a.id);
})[0];
if (!latestThread) return;
dispatch({
type: "SET_ACTIVE_THREAD",
threadId: latestThread.id,
});
},
[dispatch, state.threads],
);
const addProjectFromPath = useCallback(
async (rawCwd: string) => {
const cwd = rawCwd.trim();
if (!cwd || isAddingProject) return;
setIsAddingProject(true);
try {
if (isElectron && api) {
const result = await api.projects.add({ cwd });
const project: Project = {
id: result.project.id,
name: result.project.name,
cwd: result.project.cwd,
model: DEFAULT_MODEL,
expanded: true,
};
const existingById = state.projects.find((p) => p.id === project.id);
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
if (!existingById && !existingByCwd) {
dispatch({ type: "ADD_PROJECT", project });
}
const resolvedProjectId = existingByCwd?.id ?? project.id;
if (result.created) {
handleNewThread(resolvedProjectId);
} else {
focusMostRecentThreadForProject(resolvedProjectId);
}
} else {
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
return;
}
const name = inferProjectName(cwd);
const project: Project = {
id: crypto.randomUUID(),
name,
cwd,
model: DEFAULT_MODEL,
expanded: true,
};
dispatch({ type: "ADD_PROJECT", project });
handleNewThread(project.id);
}
} finally {
setIsAddingProject(false);
setNewCwd("");
setAddingProject(false);
}
},
[
api,
dispatch,
focusMostRecentThreadForProject,
handleNewThread,
isAddingProject,
state.projects,
],
);
const handleAddProject = () => {
void addProjectFromPath(newCwd);
};
const handlePickFolder = async () => {
if (!api || isPickingFolder) return;
setIsPickingFolder(true);
try {
const pickedPath = await api.dialogs.pickFolder();
if (!pickedPath) return;
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;
const threadProject = state.projects.find((project) => project.id === thread.projectId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
));
// 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 });
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
return;
}
try {
await api.git.removeWorktree({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
});
} catch {
// Worktree deletion is best-effort and should not block thread deletion.
}
},
[api, dispatch, state.projects, state.threads],
);
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
const isNewThreadShortcut =
event.metaKey &&
event.shiftKey &&
!event.ctrlKey &&
!event.altKey &&
event.key.toLowerCase() === "o";
if (!isNewThreadShortcut) return;
const target = event.target;
if (target instanceof HTMLElement) {
const tagName = target.tagName;
if (
target.isContentEditable ||
tagName === "INPUT" ||
tagName === "TEXTAREA" ||
tagName === "SELECT"
) {
return;
}
}
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId);
};
window.addEventListener("keydown", onWindowKeyDown);
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [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">
{/* Branding */}
<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">
T3 <span className="font-normal text-muted-foreground">Code</span>
</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"
onClick={() => setTheme(THEME_CYCLE[theme])}
aria-label={`Theme: ${theme}`}
title={`Theme: ${theme}`}
>
{theme === "system" ? (
<MonitorIcon className="size-3.5" />
) : theme === "light" ? (
<SunIcon className="size-3.5" />
) : (
<MoonIcon className="size-3.5" />
)}
</button>
</div>
{/* New thread (global) */}
<div className="px-3 pb-3">
<button
type="button"
className="flex w-full items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent"
onClick={() => {
if (state.projects.length === 0) {
setAddingProject(true);
return;
}
const firstProject = state.projects[0];
if (firstProject) handleNewThread(firstProject.id);
}}
>
<span className="text-foreground">+</span>
New thread
</button>
</div>
{/* Project list */}
<nav className="flex-1 overflow-y-auto px-2">
{state.projects.map((project) => {
const threads = state.threads
.filter((t) => t.projectId === project.id)
.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);
});
return (
<div key={project.id} className="mb-1">
{/* Project header */}
<button
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"
onClick={() => dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })}
>
<span className="text-[10px] text-muted-foreground/70">
{project.expanded ? "▼" : "▶"}
</span>
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
</button>
{/* Threads */}
{project.expanded && (
<div className="ml-2 border-l border-border/80 pl-2">
{threads.map((thread) => {
const isActive = state.activeThreadId === thread.id;
const threadStatus = threadStatusPill(
thread,
pendingApprovalByThreadId.get(thread.id) === true,
);
const terminalStatus = terminalStatusIndicator(thread);
return (
<button
key={thread.id}
type="button"
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 ${
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-secondary"
}`}
onClick={() =>
dispatch({
type: "SET_ACTIVE_THREAD",
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] ${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>
</div>
<div className="ml-2 flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
/>
</span>
)}
<span className="text-[10px] text-muted-foreground/40">
{formatRelativeTime(thread.createdAt)}
</span>
</div>
</button>
);
})}
{/* New thread within project */}
<button
type="button"
className="flex w-full items-center gap-1 px-2 py-1 text-[10px] text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground/80"
onClick={() => handleNewThread(project.id)}
>
<span>+</span> New thread
</button>
</div>
)}
</div>
);
})}
{state.projects.length === 0 && !addingProject && (
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
No projects yet.
<br />
Add one to get started.
</div>
)}
</nav>
{/* Add project form */}
{addingProject ? (
<div className="border-t border-border p-3">
<p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">
Add project
</p>
<input
className="mb-2 w-full rounded-md border border-border bg-secondary px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:border-ring focus:outline-none"
placeholder="/path/to/project"
value={newCwd}
onChange={(e) => setNewCwd(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleAddProject();
if (e.key === "Escape") setAddingProject(false);
}}
/>
{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 || isAddingProject}
>
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
</button>
)}
<div className="flex gap-2">
<button
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}
>
{isAddingProject ? "Adding..." : "Add"}
</button>
<button
type="button"
className="flex-1 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground/80 transition-colors duration-150 hover:bg-secondary"
onClick={() => setAddingProject(false)}
>
Cancel
</button>
</div>
</div>
) : (
<div className="border-t border-border p-3">
<button
type="button"
className="flex w-full items-center justify-center gap-1 rounded-md border border-dashed border-border py-2 text-xs text-muted-foreground/70 transition-colors duration-150 hover:border-ring hover:text-muted-foreground"
onClick={() => setAddingProject(true)}
>
+ Add project
</button>
</div>
)}
</aside>
);
}
@@ -0,0 +1,864 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
import { type NativeApi } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
type PointerEvent as ReactPointerEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
extractTerminalLinks,
isTerminalLinkActivation,
preferredTerminalEditor,
resolvePathLinkTarget,
} from "../terminal-links";
import { isTerminalClearShortcut } from "../terminal-shortcuts";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
type ThreadTerminalGroup,
} 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 TerminalViewportProps {
api: NativeApi;
threadId: string;
terminalId: string;
cwd: string;
focusRequestId: number;
autoFocus: boolean;
resizeEpoch: number;
drawerHeight: number;
}
function TerminalViewport({
api,
threadId,
terminalId,
cwd,
focusRequestId,
autoFocus,
resizeEpoch,
drawerHeight,
}: TerminalViewportProps) {
const containerRef = useRef<HTMLDivElement>(null);
const terminalRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
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, terminalId, 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 terminalLinksDisposable = terminal.registerLinkProvider({
provideLinks: (bufferLineNumber, callback) => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) {
callback(undefined);
return;
}
const line = activeTerminal.buffer.active.getLine(bufferLineNumber - 1);
if (!line) {
callback(undefined);
return;
}
const lineText = line.translateToString(true);
const matches = extractTerminalLinks(lineText);
if (matches.length === 0) {
callback(undefined);
return;
}
callback(
matches.map((match) => ({
text: match.text,
range: {
start: { x: match.start + 1, y: bufferLineNumber },
end: { x: match.end, y: bufferLineNumber },
},
activate: (event: MouseEvent) => {
if (!isTerminalLinkActivation(event)) {
return;
}
const latestTerminal = terminalRef.current;
if (!latestTerminal) {
return;
}
if (match.kind === "url") {
void api.shell.openExternal(match.text).catch((error) => {
writeSystemMessage(
latestTerminal,
error instanceof Error ? error.message : "Unable to open link",
);
});
return;
}
const target = resolvePathLinkTarget(match.text, cwd);
void api.shell.openInEditor(target, preferredTerminalEditor()).catch((error) => {
writeSystemMessage(
latestTerminal,
error instanceof Error ? error.message : "Unable to open path",
);
});
},
})),
);
},
});
const inputDisposable = terminal.onData((data) => {
void api.terminal
.write({ threadId, terminalId, 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,
terminalId,
cwd,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
});
if (disposed) return;
activeTerminal.write("\u001bc");
if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history);
}
if (autoFocus) {
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 || event.terminalId !== terminalId) 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") {
const details = [
typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
]
.filter((value): value is string => value !== null)
.join(", ");
writeSystemMessage(
activeTerminal,
details.length > 0 ? `Process exited (${details})` : "Process exited",
);
}
});
const fitTimer = window.setTimeout(() => {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
const wasAtBottom =
activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
activeFitAddon.fit();
if (wasAtBottom) {
activeTerminal.scrollToBottom();
}
void api.terminal
.resize({
threadId,
terminalId,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
})
.catch(() => undefined);
}, 30);
void openTerminal();
return () => {
disposed = true;
window.clearTimeout(fitTimer);
unsubscribe();
inputDisposable.dispose();
terminalLinksDisposable.dispose();
themeObserver.disconnect();
terminalRef.current = null;
fitAddonRef.current = null;
terminal.dispose();
};
}, [api, cwd, terminalId, threadId]);
useEffect(() => {
if (!autoFocus) return;
const terminal = terminalRef.current;
if (!terminal) return;
const frame = window.requestAnimationFrame(() => {
terminal.focus();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [autoFocus, 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,
terminalId,
cols: terminal.cols,
rows: terminal.rows,
})
.catch(() => undefined);
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [api, drawerHeight, resizeEpoch, terminalId, threadId]);
return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
}
interface ThreadTerminalDrawerProps {
api: NativeApi;
threadId: string;
cwd: string;
height: number;
terminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
focusRequestId: number;
onSplitTerminal: () => void;
onNewTerminal: () => void;
onActiveTerminalChange: (terminalId: string) => void;
onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void;
}
export default function ThreadTerminalDrawer({
api,
threadId,
cwd,
height,
terminalIds,
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
focusRequestId,
onSplitTerminal,
onNewTerminal,
onActiveTerminalChange,
onCloseTerminal,
onHeightChange,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
const [resizeEpoch, setResizeEpoch] = useState(0);
const drawerHeightRef = useRef(drawerHeight);
const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
const onHeightChangeRef = useRef(onHeightChange);
const resizeStateRef = useRef<{
pointerId: number;
startY: number;
startHeight: number;
} | null>(null);
const didResizeDuringDragRef = useRef(false);
const normalizedTerminalIds = useMemo(() => {
const cleaned = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
return cleaned.length > 0 ? cleaned : [DEFAULT_THREAD_TERMINAL_ID];
}, [terminalIds]);
const resolvedActiveTerminalId = normalizedTerminalIds.includes(activeTerminalId)
? activeTerminalId
: (normalizedTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const resolvedTerminalGroups = useMemo(() => {
const validTerminalIdSet = new Set(normalizedTerminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const nextGroups: ThreadTerminalGroup[] = [];
const assignUniqueGroupId = (groupId: string): string => {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
};
for (const terminalGroup of terminalGroups) {
const nextTerminalIds = [
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
].filter((terminalId) => {
if (!validTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (nextTerminalIds.length === 0) continue;
for (const terminalId of nextTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
terminalGroup.id.trim().length > 0
? terminalGroup.id.trim()
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
nextGroups.push({
id: assignUniqueGroupId(baseGroupId),
terminalIds: nextTerminalIds,
});
}
for (const terminalId of normalizedTerminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
nextGroups.push({
id: assignUniqueGroupId(`group-${terminalId}`),
terminalIds: [terminalId],
});
}
if (nextGroups.length > 0) {
return nextGroups;
}
return [
{
id: `group-${resolvedActiveTerminalId}`,
terminalIds: [resolvedActiveTerminalId],
},
];
}, [normalizedTerminalIds, resolvedActiveTerminalId, terminalGroups]);
const resolvedActiveGroupIndex = useMemo(() => {
const indexById = resolvedTerminalGroups.findIndex(
(terminalGroup) => terminalGroup.id === activeTerminalGroupId,
);
if (indexById >= 0) return indexById;
const indexByTerminal = resolvedTerminalGroups.findIndex((terminalGroup) =>
terminalGroup.terminalIds.includes(resolvedActiveTerminalId),
);
return indexByTerminal >= 0 ? indexByTerminal : 0;
}, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
const visibleTerminalIds =
resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [resolvedActiveTerminalId];
const hasTerminalSidebar = normalizedTerminalIds.length > 1;
const isSplitView = visibleTerminalIds.length > 1;
const showGroupHeaders =
resolvedTerminalGroups.length > 1 ||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
const terminalLabelById = useMemo(
() =>
new Map(
normalizedTerminalIds.map((terminalId, index) => [terminalId, `Terminal ${index + 1}`]),
),
[normalizedTerminalIds],
);
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
}, [onHeightChange]);
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);
}, []);
useEffect(() => {
const clampedHeight = clampDrawerHeight(height);
setDrawerHeight(clampedHeight);
drawerHeightRef.current = 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);
setResizeEpoch((value) => value + 1);
},
[syncHeight],
);
useEffect(() => {
const onWindowResize = () => {
const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
const changed = clampedHeight !== drawerHeightRef.current;
if (changed) {
setDrawerHeight(clampedHeight);
drawerHeightRef.current = clampedHeight;
}
if (!resizeStateRef.current) {
syncHeight(clampedHeight);
}
setResizeEpoch((value) => value + 1);
};
window.addEventListener("resize", onWindowResize);
return () => {
window.removeEventListener("resize", onWindowResize);
};
}, [syncHeight]);
useEffect(() => {
return () => {
syncHeight(drawerHeightRef.current);
};
}, [syncHeight]);
return (
<aside
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
style={{ height: `${drawerHeight}px` }}
>
<div
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerEnd}
onPointerCancel={handleResizePointerEnd}
/>
{!hasTerminalSidebar && (
<div className="pointer-events-none absolute right-2 top-2 z-20">
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
<button
type="button"
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal}
aria-label="Split Terminal"
title="Split Terminal"
>
<SquareSplitHorizontal className="size-3.25" />
</button>
<div className="h-4 w-px bg-border/80" />
<button
type="button"
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onNewTerminal}
aria-label="New Terminal"
title="New Terminal"
>
<Plus className="size-3.25" />
</button>
<div className="h-4 w-px bg-border/80" />
<button
type="button"
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
aria-label="Close Terminal"
title="Close Terminal"
>
<Trash2 className="size-3.25" />
</button>
</div>
</div>
)}
<div className="min-h-0 w-full flex-1">
<div className={`flex h-full min-h-0 ${hasTerminalSidebar ? "gap-1.5" : ""}`}>
<div className="min-w-0 flex-1">
{isSplitView ? (
<div
className="grid h-full w-full gap-0 overflow-x-auto"
style={{
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 1fr))`,
}}
>
{visibleTerminalIds.map((terminalId) => (
<div
key={terminalId}
className={`min-h-0 min-w-0 border-l first:border-l-0 ${
terminalId === resolvedActiveTerminalId
? "border-border"
: "border-border/70"
}`}
onMouseDown={() => {
if (terminalId !== resolvedActiveTerminalId) {
onActiveTerminalChange(terminalId);
}
}}
>
<div className="h-full p-1">
<TerminalViewport
api={api}
threadId={threadId}
terminalId={terminalId}
cwd={cwd}
focusRequestId={focusRequestId}
autoFocus={terminalId === resolvedActiveTerminalId}
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
/>
</div>
</div>
))}
</div>
) : (
<div className="h-full p-1">
<TerminalViewport
key={resolvedActiveTerminalId}
api={api}
threadId={threadId}
terminalId={resolvedActiveTerminalId}
cwd={cwd}
focusRequestId={focusRequestId}
autoFocus
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
/>
</div>
)}
</div>
{hasTerminalSidebar && (
<aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
<div className="inline-flex h-full items-stretch">
<button
type="button"
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onSplitTerminal}
aria-label="Split Terminal"
title="Split Terminal"
>
<SquareSplitHorizontal className="size-3.25" />
</button>
<button
type="button"
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onNewTerminal}
aria-label="New Terminal"
title="New Terminal"
>
<Plus className="size-3.25" />
</button>
<button
type="button"
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
aria-label="Close Terminal"
title="Close Terminal"
>
<Trash2 className="size-3.25" />
</button>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
{resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
const isGroupActive = terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
const groupActiveTerminalId = isGroupActive
? resolvedActiveTerminalId
: (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
return (
<div key={terminalGroup.id} className="pb-0.5">
{showGroupHeaders && (
<button
type="button"
className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
isGroupActive
? "bg-accent/70 text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
}`}
onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
>
{terminalGroup.terminalIds.length > 1
? `Split ${groupIndex + 1}`
: `Terminal ${groupIndex + 1}`}
</button>
)}
<div className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
return (
<div
key={terminalId}
className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
}`}
>
{showGroupHeaders && (
<span className="text-[10px] text-muted-foreground/80">└</span>
)}
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-1 text-left"
onClick={() => onActiveTerminalChange(terminalId)}
>
<TerminalSquare className="size-3 shrink-0" />
<span className="truncate">
{terminalLabelById.get(terminalId) ?? "Terminal"}
</span>
</button>
{normalizedTerminalIds.length > 1 && (
<button
type="button"
className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={(event) => {
event.stopPropagation();
onCloseTerminal(terminalId);
}}
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
>
×
</button>
)}
</div>
);
})}
</div>
</div>
);
})}
</div>
</aside>
)}
</div>
</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);
+90
View File
@@ -0,0 +1,90 @@
import type { GitRunStackedActionResult, GitStatusResult } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { getGitProgressToastAction } from "./components/GitActionsControl";
function makeStatus(overrides?: Partial<GitStatusResult>): GitStatusResult {
return {
branch: "feature/test-branch",
hasWorkingTreeChanges: false,
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
openPr: null,
...overrides,
};
}
function makeResult(overrides?: Partial<GitRunStackedActionResult>): GitRunStackedActionResult {
return {
action: "commit_push",
commit: { status: "skipped_no_changes" },
push: { status: "pushed", branch: "feature/test-branch" },
pr: { status: "skipped_not_requested" },
...overrides,
};
}
describe("getGitProgressToastAction", () => {
it("returns open PR action when a PR URL is available", () => {
const action = getGitProgressToastAction({
isRunning: false,
hasError: false,
result: makeResult(),
gitStatus: makeStatus(),
openPrUrl: "https://github.com/pingdotgg/codething-mvp/pull/42",
});
expect(action).toEqual({
kind: "open_pr",
label: "Open PR",
});
});
it("returns create PR action after push when branch can open a PR", () => {
const action = getGitProgressToastAction({
isRunning: false,
hasError: false,
result: makeResult({ action: "commit_push" }),
gitStatus: makeStatus(),
openPrUrl: null,
});
expect(action).toEqual({
kind: "create_pr",
label: "Create PR",
});
});
it("does not return create PR action for non-push actions", () => {
const action = getGitProgressToastAction({
isRunning: false,
hasError: false,
result: makeResult({ action: "commit" }),
gitStatus: makeStatus(),
openPrUrl: null,
});
expect(action).toBeNull();
});
it("returns null while running or failed", () => {
const running = getGitProgressToastAction({
isRunning: true,
hasError: false,
result: makeResult(),
gitStatus: makeStatus(),
openPrUrl: "https://github.com/pingdotgg/codething-mvp/pull/42",
});
const failed = getGitProgressToastAction({
isRunning: false,
hasError: true,
result: makeResult(),
gitStatus: makeStatus(),
openPrUrl: "https://github.com/pingdotgg/codething-mvp/pull/42",
});
expect(running).toBeNull();
expect(failed).toBeNull();
});
});
+122
View File
@@ -0,0 +1,122 @@
import { describe, expect, it } from "vitest";
import { buildBootstrapInput } from "./historyBootstrap";
describe("buildBootstrapInput", () => {
it("includes full transcript when under budget", () => {
const result = buildBootstrapInput(
[
{
id: "u-1",
role: "user",
text: "hello",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
{
id: "a-1",
role: "assistant",
text: "world",
createdAt: "2026-02-09T00:00:01.000Z",
streaming: false,
},
],
"what's next?",
1_500,
);
expect(result.includedCount).toBe(2);
expect(result.omittedCount).toBe(0);
expect(result.truncated).toBe(false);
expect(result.text).toContain("USER:\nhello");
expect(result.text).toContain("ASSISTANT:\nworld");
expect(result.text).toContain("Latest user request (answer this now):");
expect(result.text).toContain("what's next?");
});
it("truncates older transcript messages when over budget", () => {
const result = buildBootstrapInput(
[
{
id: "u-1",
role: "user",
text: "first question with details",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
{
id: "a-1",
role: "assistant",
text: "first answer with details",
createdAt: "2026-02-09T00:00:01.000Z",
streaming: false,
},
{
id: "u-2",
role: "user",
text: "second question with details",
createdAt: "2026-02-09T00:00:02.000Z",
streaming: false,
},
],
"final request",
320,
);
expect(result.truncated).toBe(true);
expect(result.omittedCount).toBeGreaterThan(0);
expect(result.includedCount).toBeLessThan(3);
expect(result.text).toContain("omitted to stay within input limits");
expect(result.text.length).toBeLessThanOrEqual(320);
});
it("preserves the latest prompt when prompt-only fallback is required", () => {
const latestPrompt = "Please keep this exact latest prompt.";
const result = buildBootstrapInput(
[
{
id: "u-1",
role: "user",
text: "old context",
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
],
latestPrompt,
latestPrompt.length + 3,
);
expect(result.text).toBe(latestPrompt);
expect(result.includedCount).toBe(0);
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");
});
});
+139
View File
@@ -0,0 +1,139 @@
import type { ChatMessage } from "./types";
export interface BootstrapInputResult {
text: string;
includedCount: number;
omittedCount: number;
truncated: boolean;
}
const BOOTSTRAP_PREAMBLE =
"Continue this conversation using the transcript context below. The final section is the latest user request to answer now.";
const TRANSCRIPT_HEADER = "Transcript context:";
const LATEST_PROMPT_HEADER = "Latest user request (answer this now):";
const OMITTED_SUMMARY = (count: number) =>
`[${count} earlier message(s) omitted to stay within input limits.]`;
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 {
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(
transcriptBody: string,
latestPrompt: string,
maxChars: number,
): string | null {
const text = `${BOOTSTRAP_PREAMBLE}\n\n${TRANSCRIPT_HEADER}\n${transcriptBody}\n\n${LATEST_PROMPT_HEADER}\n${latestPrompt}`;
return text.length <= maxChars ? text : null;
}
export function buildBootstrapInput(
previousMessages: ChatMessage[],
latestPrompt: string,
maxChars: number,
): BootstrapInputResult {
const budget = Number.isFinite(maxChars) ? Math.max(1, Math.floor(maxChars)) : 1;
const promptOnly = latestPrompt.length <= budget ? latestPrompt : latestPrompt.slice(0, budget);
if (previousMessages.length === 0) {
return {
text: promptOnly,
includedCount: 0,
omittedCount: 0,
truncated: promptOnly.length !== latestPrompt.length,
};
}
const newestFirstBlocks: string[] = [];
for (let index = previousMessages.length - 1; index >= 0; index -= 1) {
const message = previousMessages[index];
if (!message) continue;
newestFirstBlocks.push(buildMessageBlock(message));
}
if (newestFirstBlocks.length === 0) {
return {
text: promptOnly,
includedCount: 0,
omittedCount: previousMessages.length,
truncated: true,
};
}
// Include a contiguous suffix from newest to oldest, then reverse to chronological.
let includedNewestFirst: string[] = [];
for (const block of newestFirstBlocks) {
const nextNewestFirst = [...includedNewestFirst, block];
const nextChronological = nextNewestFirst.toReversed();
const omittedCount = newestFirstBlocks.length - nextChronological.length;
const transcriptBody =
omittedCount > 0
? `${OMITTED_SUMMARY(omittedCount)}\n\n${nextChronological.join("\n\n")}`
: nextChronological.join("\n\n");
if (!finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
break;
}
includedNewestFirst = nextNewestFirst;
}
let includedChronological = includedNewestFirst.toReversed();
while (true) {
const omittedCount = newestFirstBlocks.length - includedChronological.length;
const transcriptBody =
omittedCount > 0
? includedChronological.length > 0
? `${OMITTED_SUMMARY(omittedCount)}\n\n${includedChronological.join("\n\n")}`
: OMITTED_SUMMARY(omittedCount)
: includedChronological.join("\n\n");
const finalized = finalizeWithPrompt(transcriptBody, latestPrompt, budget);
if (finalized) {
return {
text: finalized,
includedCount: includedChronological.length,
omittedCount,
truncated: omittedCount > 0 || latestPrompt.length !== promptOnly.length,
};
}
if (includedChronological.length === 0) {
return {
text: promptOnly,
includedCount: 0,
omittedCount: previousMessages.length,
truncated: true,
};
}
includedChronological = includedChronological.slice(1);
}
}
+6
View File
@@ -0,0 +1,6 @@
import { useMemo } from "react";
import { readNativeApi } from "../session-logic";
export function useNativeApi() {
return useMemo(() => readNativeApi(), []);
}
+90
View File
@@ -0,0 +1,90 @@
import { useCallback, useEffect, useSyncExternalStore } from "react";
type Theme = "light" | "dark" | "system";
const STORAGE_KEY = "t3code:theme";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
let listeners: Array<() => void> = [];
function emitChange() {
for (const listener of listeners) listener();
}
function getSystemDark(): boolean {
return window.matchMedia(MEDIA_QUERY).matches;
}
function getStored(): Theme {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw === "light" || raw === "dark" || raw === "system") return raw;
return "system";
}
function applyTheme(theme: Theme, suppressTransitions = false) {
if (suppressTransitions) {
document.documentElement.classList.add("no-transitions");
}
const isDark = theme === "dark" || (theme === "system" && getSystemDark());
document.documentElement.classList.toggle("dark", isDark);
if (suppressTransitions) {
// Force a reflow so the no-transitions class takes effect before removal
document.documentElement.offsetHeight;
requestAnimationFrame(() => {
document.documentElement.classList.remove("no-transitions");
});
}
}
// Apply immediately on module load to prevent flash
applyTheme(getStored());
function getSnapshot(): Theme {
return getStored();
}
function subscribe(listener: () => void): () => void {
listeners.push(listener);
// Listen for system preference changes
const mq = window.matchMedia(MEDIA_QUERY);
const handleChange = () => {
if (getStored() === "system") applyTheme("system", true);
emitChange();
};
mq.addEventListener("change", handleChange);
// Listen for storage changes from other tabs
const handleStorage = (e: StorageEvent) => {
if (e.key === STORAGE_KEY) {
applyTheme(getStored(), true);
emitChange();
}
};
window.addEventListener("storage", handleStorage);
return () => {
listeners = listeners.filter((l) => l !== listener);
mq.removeEventListener("change", handleChange);
window.removeEventListener("storage", handleStorage);
};
}
export function useTheme() {
const theme = useSyncExternalStore(subscribe, getSnapshot);
const resolvedTheme: "light" | "dark" =
theme === "system" ? (getSystemDark() ? "dark" : "light") : theme;
const setTheme = useCallback((next: Theme) => {
localStorage.setItem(STORAGE_KEY, next);
applyTheme(next, true);
emitChange();
}, []);
// Keep DOM in sync on mount/change
useEffect(() => {
applyTheme(theme);
}, [theme]);
return { theme, setTheme, resolvedTheme } as const;
}
+339
View File
@@ -0,0 +1,339 @@
@import "tailwindcss";
@custom-variant dark (&:is(.dark, .dark *));
@theme inline {
--animate-skeleton: skeleton 2s -1s infinite linear;
--color-warning-foreground: var(--warning-foreground);
--color-warning: var(--warning);
--color-success-foreground: var(--success-foreground);
--color-success: var(--success);
--color-info-foreground: var(--info-foreground);
--color-info: var(--info);
--color-destructive-foreground: var(--destructive-foreground);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--color-foreground: var(--foreground);
--color-background: var(--background);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--radius-2xl: calc(var(--radius) + 8px);
--radius-3xl: calc(var(--radius) + 12px);
--radius-4xl: calc(var(--radius) + 16px);
@keyframes skeleton {
to {
background-position: -200% 0;
}
}
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
/* Suppress all transitions during theme changes */
.no-transitions,
.no-transitions *,
.no-transitions *::before,
.no-transitions *::after {
transition-duration: 0s !important;
animation-duration: 0s !important;
}
:root {
color-scheme: light;
--radius: 0.625rem;
--background: var(--color-white);
--foreground: var(--color-neutral-800);
--card: var(--color-white);
--card-foreground: var(--color-neutral-800);
--popover: var(--color-white);
--popover-foreground: var(--color-neutral-800);
--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) / 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: 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);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.141 0.005 285.823);
--sidebar-primary: oklch(0.21 0.006 285.885);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.967 0.001 286.375);
--sidebar-accent-foreground: oklch(0.21 0.006 285.885);
--sidebar-border: oklch(0.92 0.004 286.32);
--sidebar-ring: oklch(0.705 0.015 286.067);
--destructive-foreground: var(--color-red-700);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-700);
--success: var(--color-emerald-500);
--success-foreground: var(--color-emerald-700);
--warning: var(--color-amber-500);
--warning-foreground: var(--color-amber-700);
@variant dark {
color-scheme: dark;
--background: color-mix(in srgb, var(--color-neutral-950) 95%, var(--color-white));
--foreground: var(--color-neutral-100);
--card: color-mix(in srgb, var(--background) 98%, var(--color-white));
--card-foreground: var(--color-neutral-100);
--popover: color-mix(in srgb, var(--background) 98%, var(--color-white));
--popover-foreground: var(--color-neutral-100);
--primary: oklch(0.588 0.217 264);
--primary-foreground: var(--color-white);
--secondary: --alpha(var(--color-white) / 4%);
--secondary-foreground: var(--color-neutral-100);
--muted: --alpha(var(--color-white) / 4%);
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-white));
--accent: --alpha(var(--color-white) / 4%);
--accent-foreground: var(--color-neutral-100);
--destructive: color-mix(in srgb, var(--color-red-500) 90%, var(--color-white));
--border: --alpha(var(--color-white) / 6%);
--input: --alpha(var(--color-white) / 8%);
--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);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.21 0.006 285.885);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.274 0.006 286.033);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.552 0.016 285.938);
--destructive-foreground: var(--color-red-400);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-400);
--success: var(--color-emerald-500);
--success-foreground: var(--color-emerald-400);
--warning: var(--color-amber-500);
--warning-foreground: var(--color-amber-400);
}
}
body {
font-family:
"DM Sans",
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
system-ui,
sans-serif;
margin: 0;
padding: 0;
min-height: 100vh;
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
opacity: 0.035;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px 256px;
}
pre,
code,
textarea,
input {
font-family: "SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
}
/* Window drag region (frameless titlebar) */
.drag-region {
-webkit-app-region: drag;
}
.drag-region button,
.drag-region input,
.drag-region textarea,
.drag-region select,
.drag-region a {
-webkit-app-region: no-drag;
}
/* Scrollbar styling */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.15);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(0, 0, 0, 0.25);
}
.dark ::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.1);
}
.dark ::-webkit-scrollbar-thumb:hover {
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;
}
label:has(> select#reasoning-effort) select {
position: absolute;
inset: 0;
opacity: 0;
cursor: pointer;
width: 100%;
height: 100%;
}
/* Chat markdown rendering */
.chat-markdown {
overflow-wrap: anywhere;
}
.chat-markdown > :first-child {
margin-top: 0;
}
.chat-markdown > :last-child {
margin-bottom: 0;
}
.chat-markdown p,
.chat-markdown ul,
.chat-markdown ol,
.chat-markdown blockquote,
.chat-markdown pre,
.chat-markdown table {
margin: 0.65rem 0;
}
.chat-markdown ul,
.chat-markdown ol {
padding-left: 1.25rem;
}
.chat-markdown li + li {
margin-top: 0.25rem;
}
.chat-markdown a {
color: var(--info-foreground);
text-decoration: underline;
text-decoration-color: color-mix(in srgb, var(--info-foreground) 40%, transparent);
}
.chat-markdown a:hover {
opacity: 0.8;
}
.chat-markdown blockquote {
border-left: 2px solid var(--border);
padding-left: 0.8rem;
color: var(--muted-foreground);
}
.chat-markdown :not(pre) > code {
border: 1px solid var(--border);
border-radius: 0.375rem;
background: var(--muted);
padding: 0.1rem 0.35rem;
color: var(--foreground);
}
.chat-markdown pre {
overflow-x: auto;
border: 1px solid var(--border);
border-radius: 0.75rem;
background: var(--muted);
padding: 0.8rem 0.9rem;
}
.chat-markdown pre code {
border: none;
background: transparent;
padding: 0;
line-height: 1.5;
}
.chat-markdown table {
width: 100%;
border-collapse: collapse;
}
.chat-markdown th,
.chat-markdown td {
border: 1px solid var(--border);
padding: 0.35rem 0.45rem;
text-align: left;
}
+13
View File
@@ -0,0 +1,13 @@
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";
import "./index.css";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL, normalizeModelSlug, resolveModelSlug } from "./model-logic";
describe("normalizeModelSlug", () => {
it("maps 5.3 aliases to canonical codex slug", () => {
expect(normalizeModelSlug("5.3")).toBe("gpt-5.3-codex");
expect(normalizeModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
});
it("preserves non-aliased slugs", () => {
expect(normalizeModelSlug("gpt-5.3-codex")).toBe("gpt-5.3-codex");
expect(normalizeModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
});
it("returns null for empty input", () => {
expect(normalizeModelSlug("")).toBeNull();
expect(normalizeModelSlug(" ")).toBeNull();
expect(normalizeModelSlug(null)).toBeNull();
expect(normalizeModelSlug(undefined)).toBeNull();
});
});
describe("resolveModelSlug", () => {
it("falls back to default for unknown models", () => {
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL);
});
it("resolves supported hard-coded models", () => {
expect(resolveModelSlug("gpt-5.3-codex")).toBe("gpt-5.3-codex");
expect(resolveModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
expect(resolveModelSlug("gpt-5.2")).toBe("gpt-5.2");
});
});
+9
View File
@@ -0,0 +1,9 @@
export {
DEFAULT_MODEL,
MODEL_OPTIONS,
normalizeModelSlug,
resolveModelSlug,
} from "@t3tools/contracts";
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
export const DEFAULT_REASONING = "high";
+378
View File
@@ -0,0 +1,378 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import type { Thread } from "./types";
describe("hydratePersistedState", () => {
it("returns null for invalid payloads", () => {
expect(hydratePersistedState('{"projects":"bad"}', false)).toBeNull();
expect(hydratePersistedState("not-json", false)).toBeNull();
});
it("migrates the legacy default model to the current default", () => {
const payload = JSON.stringify({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.2-codex",
expanded: true,
},
],
threads: [
{
id: "t-1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.2-codex",
messages: [
{
id: "m-1",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: true,
},
],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, true);
expect(hydrated).not.toBeNull();
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]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
expect(hydrated?.runtimeMode).toBe("full-access");
});
it("filters unknown project references and repairs active thread", () => {
const payload = JSON.stringify({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
},
],
threads: [
{
id: "t-1",
projectId: "p-1",
title: "Valid thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
{
id: "t-2",
projectId: "p-missing",
title: "Dangling thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-2",
});
const hydrated = hydratePersistedState(payload, false);
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?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
expect(hydrated?.activeThreadId).toBe("t-1");
expect(hydrated?.runtimeMode).toBe("full-access");
});
it("hydrates runtime mode from v3 payload", () => {
const payload = JSON.stringify({
version: 3,
runtimeMode: "approval-required",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
},
],
threads: [],
activeThreadId: null,
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.runtimeMode).toBe("approval-required");
});
it("hydrates terminal fields from legacy 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,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalLayout: "tabs",
splitTerminalIds: [],
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]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe("term-2");
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
expect(hydrated?.threads[0]?.lastVisitedAt).toBe("2026-02-08T10:01:00.000Z");
});
it("hydrates legacy split layout into a grouped split", () => {
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,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: "term-2",
terminalLayout: "split",
splitTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
});
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);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
});
});
describe("toPersistedState", () => {
it("writes v7 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,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
runningTerminalIds: [],
activeTerminalId: "term-2",
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
],
activeTerminalGroupId: "group-term-2",
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,
},
],
events: [],
error: "boom",
createdAt: "2026-02-08T10:00:00.000Z",
lastVisitedAt: "2026-02-08T10:02:00.000Z",
branch: null,
worktreePath: null,
};
const persisted = toPersistedState({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [thread],
activeThreadId: "t-1",
runtimeMode: "full-access",
});
expect(persisted.version).toBe(7);
expect(persisted.runtimeMode).toBe("full-access");
expect(persisted.threads[0]).toEqual({
id: "t-1",
codexThreadId: "thr_1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 320,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
],
activeTerminalGroupId: "group-term-2",
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();
if (!persistedThread) return;
expect("error" in persistedThread).toBe(false);
expect("session" in persistedThread).toBe(false);
});
});
+354
View File
@@ -0,0 +1,354 @@
import { z } from "zod";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
type Thread,
type ThreadTerminalGroup,
} from "./types";
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
const persistedProjectSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
cwd: z.string().min(1),
model: z.string().min(1),
expanded: z.boolean(),
});
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(),
});
const persistedTerminalGroupSchema = z.object({
id: z.string().trim().min(1),
terminalIds: z.array(z.string().trim().min(1)),
});
const persistedThreadSchema = z.object({
id: z.string().min(1),
codexThreadId: z.string().min(1).nullable().default(null),
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,
),
terminalIds: z.array(z.string().trim().min(1)).default([DEFAULT_THREAD_TERMINAL_ID]),
activeTerminalId: z.string().trim().min(1).default(DEFAULT_THREAD_TERMINAL_ID),
terminalGroups: z.array(persistedTerminalGroupSchema).default([]),
activeTerminalGroupId: z.string().trim().min(1).optional(),
// Legacy v6 and older fields retained for migration.
terminalLayout: z.enum(["single", "split", "tabs"]).optional(),
splitTerminalIds: z.array(z.string().trim().min(1)).optional(),
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({
projects: z.array(persistedProjectSchema),
threads: z.array(persistedThreadSchema),
activeThreadId: z.string().min(1).nullable(),
});
const runtimeModeSchema = z.enum(["approval-required", "full-access"]);
export const persistedStateV1Schema = persistedStateBodySchema.extend({
version: z.literal(1).optional(),
});
export const persistedStateV2Schema = persistedStateBodySchema.extend({
version: z.literal(2).optional(),
});
export const persistedStateV3Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(3).optional(),
});
export const persistedStateV4Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(4).optional(),
});
export const persistedStateV6Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(6).optional(),
});
export const persistedStateV7Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(7).optional(),
});
export const persistedStateV5Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(5).optional(),
});
const persistedStateSchema = z.union([
persistedStateV7Schema,
persistedStateV6Schema,
persistedStateV5Schema,
persistedStateV4Schema,
persistedStateV3Schema,
persistedStateV2Schema,
persistedStateV1Schema,
]);
export interface PersistedStoreSnapshot {
projects: Project[];
threads: Thread[];
activeThreadId: string | null;
runtimeMode: RuntimeMode;
}
function maybeMigrateLegacyModel(model: string, isLegacyPayload: boolean): string {
if (!isLegacyPayload) {
return model;
}
return model === LEGACY_DEFAULT_MODEL ? DEFAULT_MODEL : model;
}
function hydrateProject(
project: z.infer<typeof persistedProjectSchema>,
isLegacyPayload: boolean,
): Project {
return {
...project,
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
};
}
function hydrateThread(
thread: z.infer<typeof persistedThreadSchema>,
isLegacyPayload: boolean,
): Thread {
const terminalIds = [...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
const safeTerminalIds =
terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId
: (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const safeTerminalIdSet = new Set(safeTerminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const normalizedGroups: ThreadTerminalGroup[] = [];
const assignUniqueGroupId = (groupId: string): string => {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
};
for (const terminalGroup of thread.terminalGroups) {
const nextTerminalIds = [
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
].filter((terminalId) => {
if (!safeTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (nextTerminalIds.length === 0) continue;
for (const terminalId of nextTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
terminalGroup.id.trim().length > 0
? terminalGroup.id.trim()
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
normalizedGroups.push({
id: assignUniqueGroupId(baseGroupId),
terminalIds: nextTerminalIds,
});
}
if (normalizedGroups.length === 0 && thread.terminalLayout === "split") {
const splitTerminalIds = [
...new Set((thread.splitTerminalIds ?? []).map((id) => id.trim()).filter((id) => id.length > 0)),
].filter((terminalId) => safeTerminalIdSet.has(terminalId));
if (splitTerminalIds.length >= 2) {
const splitGroupTerminalIds = splitTerminalIds.slice(0, 2);
for (const terminalId of splitGroupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
normalizedGroups.push({
id: assignUniqueGroupId(`group-${splitGroupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`),
terminalIds: splitGroupTerminalIds,
});
}
}
for (const terminalId of safeTerminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
normalizedGroups.push({
id: assignUniqueGroupId(`group-${terminalId}`),
terminalIds: [terminalId],
});
}
const activeGroupIndexFromId = normalizedGroups.findIndex(
(terminalGroup) => terminalGroup.id === thread.activeTerminalGroupId,
);
const activeGroupIndexFromTerminal = normalizedGroups.findIndex((terminalGroup) =>
terminalGroup.terminalIds.includes(activeTerminalId),
);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: (activeGroupIndexFromTerminal >= 0 ? activeGroupIndexFromTerminal : 0);
const activeTerminalGroupId =
normalizedGroups[activeGroupIndex]?.id ??
normalizedGroups[0]?.id ??
`group-${DEFAULT_THREAD_TERMINAL_ID}`;
return {
id: thread.id,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
terminalOpen: thread.terminalOpen ?? false,
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: safeTerminalIds,
runningTerminalIds: [],
activeTerminalId,
terminalGroups: normalizedGroups,
activeTerminalGroupId,
session: null,
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,
};
}
export function hydratePersistedState(
raw: string,
isLegacyPayload: boolean,
): PersistedStoreSnapshot | null {
let parsedJson: unknown;
try {
parsedJson = JSON.parse(raw);
} catch {
return null;
}
const parsedState = persistedStateSchema.safeParse(parsedJson);
if (!parsedState.success) {
return null;
}
const projects = parsedState.data.projects.map((project) =>
hydrateProject(project, isLegacyPayload),
);
const projectIds = new Set(projects.map((project) => project.id));
const threads = parsedState.data.threads
.map((thread) => hydrateThread(thread, isLegacyPayload))
.filter((thread) => projectIds.has(thread.projectId));
const hasActiveThread = Boolean(
parsedState.data.activeThreadId &&
threads.some((thread) => thread.id === parsedState.data.activeThreadId),
);
return {
projects,
threads,
activeThreadId: hasActiveThread ? parsedState.data.activeThreadId : (threads[0]?.id ?? null),
runtimeMode:
"runtimeMode" in parsedState.data ? parsedState.data.runtimeMode : DEFAULT_RUNTIME_MODE,
};
}
export function toPersistedState(
state: PersistedStoreSnapshot,
): z.infer<typeof persistedStateV7Schema> {
return {
version: 7,
projects: state.projects,
threads: state.threads.map((thread) => ({
id: thread.id,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
model: thread.model,
terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight,
terminalIds: thread.terminalIds,
activeTerminalId: thread.activeTerminalId,
terminalGroups: thread.terminalGroups,
activeTerminalGroupId: thread.activeTerminalGroupId,
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,
};
}
+700
View File
@@ -0,0 +1,700 @@
import { describe, expect, it } from "vitest";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import {
type WorkLogEntry,
applyEventToMessages,
derivePendingApprovals,
deriveTimelineEntries,
deriveWorkLogEntries,
evolveSession,
} from "./session-logic";
import type { ChatMessage } from "./types";
function makeEvent(overrides: Partial<ProviderEvent>): ProviderEvent {
return {
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-08T10:00:00.000Z",
method: "noop",
...overrides,
};
}
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
return {
sessionId: "sess-1",
provider: "codex",
status: "ready",
createdAt: "2026-02-08T09:59:00.000Z",
updatedAt: "2026-02-08T09:59:00.000Z",
...overrides,
};
}
describe("deriveTimelineEntries", () => {
it("interleaves messages and work entries by timestamp", () => {
const messages: ChatMessage[] = [
{
id: "m-user",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
{
id: "m-assistant",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:05:00.000Z",
streaming: false,
},
];
const workEntries: WorkLogEntry[] = [
{
id: "w-1",
label: "Tool call",
createdAt: "2026-02-08T10:02:00.000Z",
tone: "tool",
},
{
id: "w-2",
label: "Preamble",
createdAt: "2026-02-08T10:03:00.000Z",
tone: "thinking",
},
];
const timeline = deriveTimelineEntries(messages, workEntries);
expect(timeline.map((entry) => entry.id)).toEqual([
"message:m-user",
"work:w-1",
"work:w-2",
"message:m-assistant",
]);
});
it("prefers work entries when timestamps are equal", () => {
const messages: ChatMessage[] = [
{
id: "m-1",
role: "assistant",
text: "Done",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
];
const workEntries: WorkLogEntry[] = [
{
id: "w-1",
label: "Tool call",
createdAt: "2026-02-08T10:00:00.000Z",
tone: "tool",
},
];
const timeline = deriveTimelineEntries(messages, workEntries);
expect(timeline.map((entry) => entry.id)).toEqual(["work:w-1", "message:m-1"]);
});
});
describe("deriveWorkLogEntries", () => {
it("drops preamble/work events from the visible work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-1",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { item: { type: "preamble", text: "thinking" } },
}),
makeEvent({
id: "evt-2",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { item: { type: "work", text: "planning" } },
}),
makeEvent({
id: "evt-3",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: { item: { type: "tool_call", command: "ls -la" } },
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Tool call");
});
it("does not surface successful turn completion as a work-log row", () => {
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: "completed" } },
}),
],
"turn-1",
);
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", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-turn-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-summary-part",
method: "item/reasoning/summaryPartAdded",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-summary-delta",
method: "item/reasoning/summaryTextDelta",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
}),
makeEvent({
id: "evt-agent-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:03.000Z",
payload: {
item: { id: "item-msg", type: "agentMessage", text: "Working..." },
},
}),
makeEvent({
id: "evt-agent-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:04.000Z",
payload: {
item: {
id: "item-msg",
type: "agentMessage",
text: "Done response",
},
},
}),
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", command: "ls -la" },
},
}),
makeEvent({
id: "evt-tool-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:06.000Z",
payload: {
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
},
}),
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:08.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
],
"turn-1",
);
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", () => {
const longCommand =
'node ./scripts/sync.js --project ct-round-5 --mode dry-run --include "very long argument with lots of detail and metadata to verify there is no hard truncation in session logic"';
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", command: longCommand },
},
}),
],
"turn-1",
);
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(
[
makeEvent({
id: "evt-turn-1-tool",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { item: { type: "tool_call", command: "ls -la" } },
}),
makeEvent({
id: "evt-turn-2-tool",
method: "item/started",
turnId: "turn-2",
createdAt: "2026-02-08T10:00:02.000Z",
payload: { item: { type: "tool_call", command: "pwd" } },
}),
],
undefined,
);
expect(entries).toHaveLength(2);
expect(entries.map((entry) => entry.detail)).toEqual(["pwd", "ls -la"]);
});
});
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();
const next = evolveSession(
previous,
makeEvent({
method: "thread/started",
createdAt: "2026-02-08T10:01:00.000Z",
payload: { thread: { id: "thread-1" } },
}),
);
expect(next.threadId).toBe("thread-1");
expect(next.updatedAt).toBe("2026-02-08T10:01:00.000Z");
});
it("moves to running and records active turn on turn start", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:02:00.000Z",
}),
);
expect(next.status).toBe("running");
expect(next.activeTurnId).toBe("turn-1");
expect(next.updatedAt).toBe("2026-02-08T10:02:00.000Z");
});
it("returns to ready and clears active turn on successful completion", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
lastError: "older error",
});
const next = evolveSession(
previous,
makeEvent({
method: "turn/completed",
createdAt: "2026-02-08T10:03:00.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
);
expect(next.status).toBe("ready");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("older error");
});
it("marks session as error when turn fails", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
});
const next = evolveSession(
previous,
makeEvent({
method: "turn/completed",
createdAt: "2026-02-08T10:03:00.000Z",
payload: {
turn: { id: "turn-1", status: "failed", error: { message: "boom" } },
},
}),
);
expect(next.status).toBe("error");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("boom");
});
it("moves to error on runtime error events", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
kind: "error",
method: "runtime/error",
createdAt: "2026-02-08T10:04:00.000Z",
message: "runtime failure",
}),
);
expect(next.status).toBe("error");
expect(next.lastError).toBe("runtime failure");
});
it("closes session on close lifecycle events", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
});
const next = evolveSession(
previous,
makeEvent({
method: "session/closed",
createdAt: "2026-02-08T10:05:00.000Z",
message: "closed",
}),
);
expect(next.status).toBe("closed");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("closed");
});
});
describe("applyEventToMessages", () => {
it("handles start/delta/completed flow for assistant messages", () => {
const activeAssistantItemRef = { current: null as string | null };
const started = applyEventToMessages(
[],
makeEvent({
method: "item/started",
createdAt: "2026-02-08T10:00:00.000Z",
payload: {
item: {
id: "item-1",
type: "agentMessage",
text: "Hello",
},
},
}),
activeAssistantItemRef,
);
expect(started).toEqual([
{
id: "item-1",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: true,
},
]);
expect(activeAssistantItemRef.current).toBe("item-1");
const withDelta = applyEventToMessages(
started,
makeEvent({
method: "item/agentMessage/delta",
createdAt: "2026-02-08T10:00:01.000Z",
itemId: "item-1",
textDelta: " world",
}),
activeAssistantItemRef,
);
expect(withDelta[0]?.text).toBe("Hello world");
expect(withDelta[0]?.streaming).toBe(true);
const completed = applyEventToMessages(
withDelta,
makeEvent({
method: "item/completed",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-1",
type: "agentMessage",
text: "Hello world!",
},
},
}),
activeAssistantItemRef,
);
expect(completed[0]?.text).toBe("Hello world!");
expect(completed[0]?.streaming).toBe(false);
expect(activeAssistantItemRef.current).toBeNull();
});
it("supports out-of-order delta before started/completed", () => {
const activeAssistantItemRef = { current: null as string | null };
const withDelta = applyEventToMessages(
[],
makeEvent({
method: "item/agentMessage/delta",
createdAt: "2026-02-08T10:00:01.000Z",
itemId: "item-2",
textDelta: "Partial",
}),
activeAssistantItemRef,
);
expect(withDelta[0]?.id).toBe("item-2");
expect(withDelta[0]?.text).toBe("Partial");
expect(withDelta[0]?.streaming).toBe(true);
expect(activeAssistantItemRef.current).toBe("item-2");
const completed = applyEventToMessages(
withDelta,
makeEvent({
method: "item/completed",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-2",
type: "agentMessage",
text: "Partial + final",
},
},
}),
activeAssistantItemRef,
);
expect(completed[0]?.text).toBe("Partial + final");
expect(completed[0]?.streaming).toBe(false);
});
it("clears all streaming flags when turn completes", () => {
const previous: ChatMessage[] = [
{
id: "m-user",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
{
id: "m-assistant",
role: "assistant",
text: "Typing",
createdAt: "2026-02-08T10:00:01.000Z",
streaming: true,
},
];
const next = applyEventToMessages(
previous,
makeEvent({
method: "turn/completed",
}),
{ current: null },
);
expect(next.every((entry) => entry.streaming === false)).toBe(true);
});
});
+674
View File
@@ -0,0 +1,674 @@
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@t3tools/contracts";
import type { ChatMessage, SessionPhase } from "./types";
import { createWsNativeApi } from "./wsNativeApi";
export const PROVIDER_OPTIONS: Array<{
value: ProviderKind;
label: string;
available: boolean;
}> = [
{ value: "codex", label: "Codex", available: true },
{ value: "claudeCode", label: "Claude Code (soon)", available: false },
];
let cachedApi: NativeApi | undefined;
export function readNativeApi(): NativeApi | undefined {
if (typeof window === "undefined") return undefined;
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 {
if (!value || typeof value !== "object") return undefined;
return value as Record<string, unknown>;
}
export function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function formatTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
second: "2-digit",
}).format(new Date(isoDate));
}
export function formatDuration(durationMs: number): string {
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
const minutes = Math.floor(durationMs / 60_000);
const seconds = Math.round((durationMs % 60_000) / 1_000);
if (seconds === 0) return `${minutes}m`;
if (seconds === 60) return `${minutes + 1}m`;
return `${minutes}m ${seconds}s`;
}
export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
if (!endIso) return null;
const startedAt = Date.parse(startIso);
const endedAt = Date.parse(endIso);
if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
return null;
}
return formatDuration(endedAt - startedAt);
}
export interface WorkLogEntry {
id: string;
createdAt: string;
label: string;
detail?: string;
tone: "thinking" | "tool" | "info" | "error";
}
export interface PendingApproval {
requestId: string;
requestKind: "command" | "file-change";
createdAt: string;
detail?: string;
}
export type TimelineEntry =
| {
id: string;
kind: "message";
createdAt: string;
message: ChatMessage;
}
| {
id: string;
kind: "work";
createdAt: string;
entry: WorkLogEntry;
};
function normalizeDetail(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
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
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[._/-]/g, " ")
.replace(/\s+/g, " ")
.trim()
.toLowerCase();
}
function shouldDropItemType(type: string): boolean {
if (type.includes("preamble") || type.includes("reasoning") || type.includes("thought")) {
return true;
}
return type === "work" || type.startsWith("work ");
}
function shouldShowItemLifecycle(type: string): boolean {
return type.includes("tool") || type.includes("command") || type.includes("file change");
}
function shouldDropMethod(method: string): boolean {
return /(^|\/)(preamble|work|reasoning|thought)(\/|$)/i.test(method);
}
function itemTypeMeta(type: string): {
label: string;
tone: WorkLogEntry["tone"];
} {
if (type.includes("command")) {
return { label: "Command run", tone: "tool" };
}
if (type.includes("file change")) {
return { label: "File change", tone: "tool" };
}
if (type.includes("tool")) {
return { label: "Tool call", tone: "tool" };
}
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?.prompt),
asString(payload?.message),
asString(payload?.prompt),
asString(payload?.command),
];
for (const candidate of candidates) {
const detail = normalizeDetail(candidate);
if (detail) return detail;
}
return undefined;
}
function lifecycleCandidateFromItemEvent(event: ProviderEvent): ItemLifecycleCandidate | null {
const payload = asObject(event.payload);
const item = asObject(payload?.item);
const normalizedType = normalizeItemType(asString(item?.type));
if (shouldDropItemType(normalizedType) || shouldDropMethod(event.method)) {
return null;
}
if (!shouldShowItemLifecycle(normalizedType)) {
return null;
}
const meta = itemTypeMeta(normalizedType);
const isStarted = event.method === "item/started";
const isCompleted = event.method === "item/completed";
if (!isStarted && !isCompleted) {
return null;
}
const detail = extractDetail(payload, item);
const itemId = event.itemId ?? asString(item?.id);
return {
id: event.id,
...(itemId ? { itemId } : {}),
createdAt: event.createdAt,
label: meta.label,
...(detail ? { detail } : {}),
tone: meta.tone,
phase: isCompleted ? "completed" : "started",
};
}
function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "request") return null;
if (shouldDropMethod(event.method)) return null;
if (event.method.includes("commandExecution")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "Command approval requested",
tone: "tool",
};
}
if (event.method.includes("fileChange")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "File-change approval requested",
tone: "tool",
};
}
if (event.method.includes("requestUserInput")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "Tool requested user input",
tone: "tool",
};
}
return {
id: event.id,
createdAt: event.createdAt,
label: `Request: ${event.method}`,
tone: "info",
};
}
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;
if (event.method === "turn/started") {
return null;
}
if (event.method === "thread/started") return null;
if (event.method === "turn/completed") {
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);
return {
id: event.id,
createdAt: event.createdAt,
label: "Turn failed",
...(turnErrorDetail ? { detail: turnErrorDetail } : {}),
tone: "error",
};
}
if (event.method.startsWith("item/")) return null;
return null;
}
function entryFromError(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "error") return null;
if (shouldDropMethod(event.method)) return null;
const detail = normalizeDetail(event.message);
return {
id: event.id,
createdAt: event.createdAt,
label: "Runtime error",
...(detail ? { detail } : {}),
tone: "error",
};
}
function eventTurnId(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return event.turnId ?? asString(turn?.id);
}
export function deriveWorkLogEntries(
events: ProviderEvent[],
turnId: string | undefined,
): WorkLogEntry[] {
const ordered = [...events].toReversed();
const entries: WorkLogEntry[] = [];
const turnStartedAtIso = turnId
? ordered.find((event) => {
if (event.method !== "turn/started") return false;
return eventTurnId(event) === turnId;
})?.createdAt
: 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 (!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;
}
entries.push({
id: lifecycleCandidate.id,
createdAt: lifecycleCandidate.createdAt,
label: lifecycleCandidate.label,
...(lifecycleCandidate.detail ? { detail: lifecycleCandidate.detail } : {}),
tone: lifecycleCandidate.tone,
});
continue;
}
const fromRequest = entryFromRequest(event);
if (fromRequest) {
entries.push(fromRequest);
continue;
}
const fromNotification = entryFromNotification(event);
if (fromNotification) {
entries.push(fromNotification);
continue;
}
const fromError = entryFromError(event);
if (fromError) {
entries.push(fromError);
}
}
return entries;
}
function toTimestamp(isoDate: string): number {
const parsed = Date.parse(isoDate);
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
}
export function deriveTimelineEntries(
messages: ChatMessage[],
workEntries: WorkLogEntry[],
): TimelineEntry[] {
const timeline: TimelineEntry[] = [];
let messageIndex = 0;
let workIndex = 0;
while (messageIndex < messages.length || workIndex < workEntries.length) {
const message = messages[messageIndex];
const workEntry = workEntries[workIndex];
if (!message && workEntry) {
timeline.push({
id: `work:${workEntry.id}`,
kind: "work",
createdAt: workEntry.createdAt,
entry: workEntry,
});
workIndex += 1;
continue;
}
if (!workEntry && message) {
timeline.push({
id: `message:${message.id}`,
kind: "message",
createdAt: message.createdAt,
message,
});
messageIndex += 1;
continue;
}
if (!message || !workEntry) {
break;
}
const messageAt = toTimestamp(message.createdAt);
const workAt = toTimestamp(workEntry.createdAt);
if (workAt <= messageAt) {
timeline.push({
id: `work:${workEntry.id}`,
kind: "work",
createdAt: workEntry.createdAt,
entry: workEntry,
});
workIndex += 1;
continue;
}
timeline.push({
id: `message:${message.id}`,
kind: "message",
createdAt: message.createdAt,
message,
});
messageIndex += 1;
}
return timeline;
}
export function derivePhase(session: ProviderSession | null): SessionPhase {
if (!session || session.status === "closed") return "disconnected";
if (session.status === "connecting") return "connecting";
if (session.status === "running") return "running";
return "ready";
}
export function evolveSession(previous: ProviderSession, event: ProviderEvent): ProviderSession {
const payload = asObject(event.payload);
if (event.method === "thread/started") {
const thread = asObject(payload?.thread);
return {
...previous,
threadId: asString(thread?.id) ?? event.threadId ?? previous.threadId,
updatedAt: event.createdAt,
};
}
if (event.method === "turn/started") {
const turn = asObject(payload?.turn);
return {
...previous,
status: "running",
activeTurnId: asString(turn?.id) ?? event.turnId ?? previous.activeTurnId,
updatedAt: event.createdAt,
};
}
if (event.method === "turn/completed") {
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
const turnError = asObject(turn?.error);
return {
...previous,
status: status === "failed" ? "error" : "ready",
activeTurnId: undefined,
lastError: asString(turnError?.message) ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.kind === "error") {
return {
...previous,
status: "error",
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.method === "session/closed" || event.method === "session/exited") {
return {
...previous,
status: "closed",
activeTurnId: undefined,
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
return { ...previous, updatedAt: event.createdAt };
}
export function applyEventToMessages(
previous: ChatMessage[],
event: ProviderEvent,
activeAssistantItemRef: { current: string | null },
): ChatMessage[] {
const payload = asObject(event.payload);
if (event.method === "item/started") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return previous;
const itemId = asString(item?.id);
if (!itemId) return previous;
activeAssistantItemRef.current = itemId;
const seedText = asString(item?.text) ?? "";
const filtered = previous.filter((entry) => entry.id !== itemId);
return [
...filtered,
{
id: itemId,
role: "assistant",
text: seedText,
createdAt: event.createdAt,
streaming: true,
},
];
}
if (event.method === "item/agentMessage/delta") {
const itemId = event.itemId ?? asString(payload?.itemId);
const delta = event.textDelta ?? asString(payload?.delta) ?? "";
if (!itemId || !delta) return previous;
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
if (existingIndex === -1) {
activeAssistantItemRef.current = itemId;
return [
...previous,
{
id: itemId,
role: "assistant",
text: delta,
createdAt: event.createdAt,
streaming: true,
},
];
}
const updated = [...previous];
const existing = updated[existingIndex];
if (!existing) return previous;
updated[existingIndex] = {
...existing,
text: `${existing.text}${delta}`,
streaming: true,
};
return updated;
}
if (event.method === "item/completed") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return previous;
const itemId = asString(item?.id);
if (!itemId) return previous;
const fullText = asString(item?.text);
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
if (existingIndex === -1) {
return [
...previous,
{
id: itemId,
role: "assistant",
text: fullText ?? "",
createdAt: event.createdAt,
streaming: false,
},
];
}
const updated = [...previous];
const existing = updated[existingIndex];
if (!existing) return previous;
updated[existingIndex] = {
...existing,
text: fullText ?? existing.text,
streaming: false,
};
if (activeAssistantItemRef.current === itemId) {
activeAssistantItemRef.current = null;
}
return updated;
}
if (event.method === "turn/completed") {
return previous.map((entry) => ({ ...entry, streaming: false }));
}
return previous;
}
+536
View File
@@ -0,0 +1,536 @@
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { type AppState, reducer } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import type { Thread } from "./types";
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
type TerminalActivityEvent = Extract<TerminalEvent, { type: "activity" }>;
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,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
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,
};
}
function makeTerminalStartedEvent(
overrides: Partial<TerminalStartedEvent> = {},
): TerminalStartedEvent {
return {
type: "started",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:01.000Z",
snapshot: {
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
cwd: "/tmp/project",
status: "running",
pid: 1234,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: "2026-02-09T00:00:01.000Z",
},
...overrides,
};
}
function makeTerminalActivityEvent(
overrides: Partial<TerminalActivityEvent> = {},
): TerminalActivityEvent {
return {
type: "activity",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:02.000Z",
hasRunningSubprocess: true,
...overrides,
};
}
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("splits the active terminal into side-by-side mode", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SPLIT_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
]);
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("creates a new full-width terminal and switches to tab mode", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "NEW_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{ id: "group-term-2", terminalIds: ["term-2"] },
]);
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
});
it("switches the active terminal and restores its owning group", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
],
activeTerminalGroupId: "group-term-3",
}),
);
const next = reducer(state, {
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("supports splitting beyond two terminals in the same group", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "SPLIT_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-3",
});
expect(next.threads[0]?.terminalIds).toEqual([
DEFAULT_THREAD_TERMINAL_ID,
"term-2",
"term-3",
]);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
},
]);
expect(next.threads[0]?.activeTerminalId).toBe("term-3");
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("closes a terminal and keeps grouped layout coherent", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "CLOSE_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-3"]);
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
]);
});
it("closes the final terminal and hides the drawer", () => {
const state = makeState(
makeThread({
terminalOpen: true,
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID],
}),
);
const next = reducer(state, {
type: "CLOSE_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
});
expect(next.threads[0]?.terminalOpen).toBe(false);
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
]);
});
it("tracks running terminals from subprocess activity events", () => {
const state = makeState(makeThread());
const started = reducer(state, {
type: "APPLY_TERMINAL_EVENT",
event: makeTerminalStartedEvent(),
});
expect(started.threads[0]?.runningTerminalIds).toEqual([]);
const active = reducer(started, {
type: "APPLY_TERMINAL_EVENT",
event: makeTerminalActivityEvent(),
});
expect(active.threads[0]?.runningTerminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
const idle = reducer(active, {
type: "APPLY_TERMINAL_EVENT",
event: makeTerminalActivityEvent({ hasRunningSubprocess: false }),
});
expect(idle.threads[0]?.runningTerminalIds).toEqual([]);
const exited = reducer(active, {
type: "APPLY_TERMINAL_EVENT",
event: {
type: "exited",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:05.000Z",
exitCode: 0,
exitSignal: null,
},
});
expect(exited.threads[0]?.runningTerminalIds).toEqual([]);
});
it("keeps running status when another terminal in the thread is still running", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "APPLY_TERMINAL_EVENT",
event: {
type: "exited",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:07.000Z",
exitCode: 0,
exitSignal: null,
},
});
expect(next.threads[0]?.runningTerminalIds).toEqual(["term-2"]);
});
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);
});
});
+850
View File
@@ -0,0 +1,850 @@
import {
type Dispatch,
type ReactNode,
createContext,
createElement,
useContext,
useEffect,
useReducer,
} from "react";
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
import {
type ChatAttachment,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
type Thread,
type ThreadTerminalGroup,
} 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: "SPLIT_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "NEW_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "TOGGLE_DIFF" }
| {
type: "APPLY_EVENT";
event: ProviderEvent;
activeAssistantItemRef: { current: string | null };
}
| { type: "APPLY_TERMINAL_EVENT"; event: TerminalEvent }
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
| {
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: "DELETE_THREAD"; threadId: string };
// ── State ────────────────────────────────────────────────────────────
export interface AppState {
projects: Project[];
threads: Thread[];
activeThreadId: string | null;
runtimeMode: RuntimeMode;
diffOpen: boolean;
}
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v6",
"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",
] as const;
const initialState: AppState = {
projects: [],
threads: [],
activeThreadId: null,
runtimeMode: DEFAULT_RUNTIME_MODE,
diffOpen: false,
};
// ── Helpers ──────────────────────────────────────────────────────────
function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
try {
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
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 && raw === rawCodethingV1,
);
if (!hydrated) return initialState;
return { ...hydrated, diffOpen: false };
} catch {
return initialState;
}
}
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
}
}
function updateThread(
threads: Thread[],
threadId: string,
updater: (t: Thread) => Thread,
): Thread[] {
return threads.map((t) => (t.id === threadId ? updater(t) : t));
}
function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
const unique = [...new Set(ids)];
if (unique.length > 0) {
return unique;
}
return [DEFAULT_THREAD_TERMINAL_ID];
}
function normalizeRunningTerminalIds(
runningTerminalIds: string[],
terminalIds: string[],
): string[] {
if (runningTerminalIds.length === 0) return [];
const validTerminalIdSet = new Set(terminalIds);
return [...new Set(runningTerminalIds)]
.map((id) => id.trim())
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
}
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
}
function fallbackGroupId(terminalId: string): string {
return `group-${terminalId}`;
}
function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
}
function normalizeTerminalGroups(
thread: Thread,
terminalIds: string[],
): ThreadTerminalGroup[] {
const validTerminalIdSet = new Set(terminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const groups: ThreadTerminalGroup[] = [];
for (const group of thread.terminalGroups) {
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
if (!validTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (groupTerminalIds.length === 0) continue;
for (const terminalId of groupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
group.id.trim().length > 0
? group.id.trim()
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
groups.push({
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
terminalIds: groupTerminalIds,
});
}
for (const terminalId of terminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
groups.push({
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
terminalIds: [terminalId],
});
}
if (groups.length > 0) {
return groups;
}
return [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
];
}
function findGroupIndexByTerminalId(
terminalGroups: ThreadTerminalGroup[],
terminalId: string,
): number {
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
}
function normalizeThreadTerminals(thread: Thread): Thread {
const terminalIds = normalizeTerminalIds(thread.terminalIds);
const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId
: (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
const activeGroupIndexFromId = terminalGroups.findIndex(
(group) => group.id === thread.activeTerminalGroupId,
);
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(
terminalGroups,
activeTerminalId,
);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: (activeGroupIndexFromTerminal >= 0 ? activeGroupIndexFromTerminal : 0);
const activeTerminalGroupId =
terminalGroups[activeGroupIndex]?.id ??
terminalGroups[0]?.id ??
fallbackGroupId(activeTerminalId);
return {
...thread,
terminalIds,
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
};
}
function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
if (!thread.terminalIds.includes(terminalId)) {
return thread;
}
const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
if (remainingTerminalIds.length === 0) {
return normalizeThreadTerminals({
...thread,
terminalOpen: false,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
});
}
const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
const closedTerminalGroup = thread.terminalGroups.find((group) =>
group.terminalIds.includes(terminalId),
);
const closedTerminalGroupIndex = closedTerminalGroup
? closedTerminalGroup.terminalIds.indexOf(terminalId)
: -1;
const remainingTerminalsInClosedGroup = (
closedTerminalGroup?.terminalIds ?? []
).filter((id) => id !== terminalId);
const nextActiveTerminalId =
thread.activeTerminalId === terminalId
? (remainingTerminalsInClosedGroup[
Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
] ??
remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
remainingTerminalIds[0] ??
DEFAULT_THREAD_TERMINAL_ID)
: thread.activeTerminalId;
const nextTerminalGroups = thread.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
return normalizeThreadTerminals({
...thread,
terminalIds: remainingTerminalIds,
runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
activeTerminalId: nextActiveTerminalId,
terminalGroups: nextTerminalGroups,
});
}
function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
return threads.find((t) => t.session?.sessionId === sessionId);
}
function getEventTurnId(event: ProviderEvent): string | undefined {
if (event.turnId) return event.turnId;
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return asString(turn?.id);
}
function getEventThreadId(event: ProviderEvent): string | undefined {
if (event.threadId) return event.threadId;
const payload = asObject(event.payload);
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 {
const start = Date.parse(startIso);
const end = Date.parse(endIso);
if (Number.isNaN(start) || Number.isNaN(end) || end < start) {
return undefined;
}
return end - start;
}
function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread> {
if (event.method === "turn/started") {
return {
latestTurnId: getEventTurnId(event) ?? thread.latestTurnId,
latestTurnStartedAt: event.createdAt,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
};
}
if (event.method === "turn/completed") {
const completedTurnId = getEventTurnId(event) ?? thread.latestTurnId;
const startedAt =
completedTurnId && completedTurnId === thread.latestTurnId
? thread.latestTurnStartedAt
: undefined;
const elapsed =
startedAt && startedAt.length > 0 ? durationMs(startedAt, event.createdAt) : undefined;
return {
latestTurnId: completedTurnId ?? thread.latestTurnId,
latestTurnCompletedAt: event.createdAt,
latestTurnDurationMs: elapsed,
};
}
return {};
}
// ── Reducer ──────────────────────────────────────────────────────────
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: [
...state.projects,
{
...action.project,
model: resolveModelSlug(action.project.model),
},
],
};
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 normalizeThreadTerminals({
...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,
projects: state.projects.map((p) =>
p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
),
};
case "ADD_THREAD": {
const nextThread = normalizeThreadTerminals({
...action.thread,
model: resolveModelSlug(action.thread.model),
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
});
return {
...state,
threads: [...state.threads, nextThread],
activeThreadId: action.thread.id,
};
}
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 "SPLIT_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
...group,
terminalIds: [...group.terminalIds],
}));
let activeGroupIndex = terminalGroups.findIndex(
(group) => group.id === normalizedThread.activeTerminalGroupId,
);
if (activeGroupIndex < 0) {
activeGroupIndex = findGroupIndexByTerminalId(
terminalGroups,
normalizedThread.activeTerminalId,
);
}
if (activeGroupIndex < 0) {
terminalGroups.push({
id: fallbackGroupId(normalizedThread.activeTerminalId),
terminalIds: [normalizedThread.activeTerminalId],
});
activeGroupIndex = terminalGroups.length - 1;
}
const existingGroupIndex = findGroupIndexByTerminalId(
terminalGroups,
action.terminalId,
);
if (existingGroupIndex >= 0) {
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
existingGroupIndex
]!.terminalIds.filter((id) => id !== action.terminalId);
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
terminalGroups.splice(existingGroupIndex, 1);
if (existingGroupIndex < activeGroupIndex) {
activeGroupIndex -= 1;
}
}
}
const destinationGroup = terminalGroups[activeGroupIndex];
if (!destinationGroup) {
return normalizedThread;
}
if (!destinationGroup.terminalIds.includes(action.terminalId)) {
const anchorIndex = destinationGroup.terminalIds.indexOf(
normalizedThread.activeTerminalId,
);
if (anchorIndex >= 0) {
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
} else {
destinationGroup.terminalIds.push(action.terminalId);
}
}
return normalizeThreadTerminals({
...normalizedThread,
terminalIds,
activeTerminalId: action.terminalId,
activeTerminalGroupId: destinationGroup.id,
terminalGroups,
});
}),
};
case "NEW_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
const terminalGroups = normalizedThread.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
const nextGroupId = fallbackGroupId(action.terminalId);
terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
return normalizeThreadTerminals({
...normalizedThread,
terminalIds,
activeTerminalId: action.terminalId,
activeTerminalGroupId: nextGroupId,
terminalGroups,
});
}),
};
case "SET_THREAD_ACTIVE_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
if (!normalizedThread.terminalIds.includes(action.terminalId)) {
return thread;
}
const nextActiveGroupIndex = findGroupIndexByTerminalId(
normalizedThread.terminalGroups,
action.terminalId,
);
const activeTerminalGroupId =
nextActiveGroupIndex >= 0
? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
normalizedThread.activeTerminalGroupId)
: normalizedThread.activeTerminalGroupId;
return normalizeThreadTerminals({
...normalizedThread,
activeTerminalId: action.terminalId,
activeTerminalGroupId,
});
}),
};
case "CLOSE_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
closeThreadTerminal(thread, action.terminalId),
),
};
case "TOGGLE_DIFF":
return { ...state, diffOpen: !state.diffOpen };
case "APPLY_TERMINAL_EVENT":
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
return state;
}
return {
...state,
threads: updateThread(state.threads, action.event.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds);
if (
action.event.type === "started" ||
action.event.type === "restarted"
) {
runningTerminalIdSet.delete(action.event.terminalId);
} else if (action.event.type === "activity") {
if (action.event.hasRunningSubprocess) {
runningTerminalIdSet.add(action.event.terminalId);
} else {
runningTerminalIdSet.delete(action.event.terminalId);
}
} else if (action.event.type === "exited" || action.event.type === "error") {
runningTerminalIdSet.delete(action.event.terminalId);
}
return normalizeThreadTerminals({
...normalizedThread,
runningTerminalIds: [...runningTerminalIdSet],
});
}),
};
case "APPLY_EVENT": {
const { event, activeAssistantItemRef } = action;
const target = findThreadBySessionId(state.threads, event.sessionId);
if (!target) return state;
if (shouldIgnoreForeignThreadEvent(target, event)) return state;
return {
...state,
threads: updateThread(state.threads, target.id, (t) => ({
...t,
...(() => {
const eventThreadId = getEventThreadId(event);
const shouldRebindIdentity =
event.method === "thread/started" && t.session?.status === "connecting";
return {
codexThreadId: shouldRebindIdentity
? (eventThreadId ?? t.codexThreadId)
: (t.codexThreadId ?? eventThreadId ?? null),
error: event.kind === "error" && event.message ? event.message : t.error,
};
})(),
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 }
: {}),
})),
};
}
case "UPDATE_SESSION":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
session: action.session,
codexThreadId: action.session.threadId ?? t.codexThreadId,
events: [],
error: null,
latestTurnId: undefined,
latestTurnStartedAt: undefined,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
})),
};
case "PUSH_USER_MESSAGE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
messages: [
...t.messages,
{
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,
},
],
})),
};
case "SET_ERROR":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
error: action.error,
})),
};
case "SET_THREAD_TITLE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
title: action.title,
})),
};
case "SET_THREAD_MODEL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
model: resolveModelSlug(action.model),
})),
};
case "SET_THREAD_BRANCH": {
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => {
// When the effective cwd changes (worktreePath differs), the old
// session is no longer valid — clear it so ensureSession creates a
// new one with the correct cwd on the next message.
const cwdChanged = t.worktreePath !== action.worktreePath;
return {
...t,
branch: action.branch,
worktreePath: action.worktreePath,
...(cwdChanged ? { session: null } : {}),
};
}),
};
}
case "SET_RUNTIME_MODE":
return {
...state,
runtimeMode: action.mode,
};
case "DELETE_THREAD": {
const threads = state.threads.filter((t) => t.id !== action.threadId);
const activeThreadId =
state.activeThreadId === action.threadId ? (threads[0]?.id ?? null) : state.activeThreadId;
return { ...state, threads, activeThreadId };
}
default:
return state;
}
}
// ── Context ──────────────────────────────────────────────────────────
const StoreContext = createContext<{
state: AppState;
dispatch: Dispatch<Action>;
}>({ state: initialState, dispatch: () => {} });
export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
useEffect(() => {
persistState(state);
}, [state]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
}
export function useStore() {
return useContext(StoreContext);
}
+110
View File
@@ -0,0 +1,110 @@
import { describe, expect, it } from "vitest";
import {
extractTerminalLinks,
isTerminalLinkActivation,
resolvePathLinkTarget,
} from "./terminal-links";
describe("extractTerminalLinks", () => {
it("finds http urls and path tokens", () => {
const line =
"failed at https://example.com/docs and src/components/ThreadTerminalDrawer.tsx:42";
expect(extractTerminalLinks(line)).toEqual([
{
kind: "url",
text: "https://example.com/docs",
start: 10,
end: 34,
},
{
kind: "path",
text: "src/components/ThreadTerminalDrawer.tsx:42",
start: 39,
end: 81,
},
]);
});
it("trims trailing punctuation from links", () => {
const line = "(https://example.com/docs), ./src/main.ts:12.";
expect(extractTerminalLinks(line)).toEqual([
{
kind: "url",
text: "https://example.com/docs",
start: 1,
end: 25,
},
{
kind: "path",
text: "./src/main.ts:12",
start: 28,
end: 44,
},
]);
});
});
describe("resolvePathLinkTarget", () => {
it("resolves relative paths against cwd", () => {
expect(
resolvePathLinkTarget(
"src/components/ThreadTerminalDrawer.tsx:42:7",
"/Users/julius/project",
),
).toBe("/Users/julius/project/src/components/ThreadTerminalDrawer.tsx:42:7");
});
it("keeps absolute paths unchanged", () => {
expect(
resolvePathLinkTarget(
"/Users/julius/project/src/main.ts:12",
"/Users/julius/project",
),
).toBe("/Users/julius/project/src/main.ts:12");
});
});
describe("isTerminalLinkActivation", () => {
it("requires cmd on macOS", () => {
expect(
isTerminalLinkActivation(
{
metaKey: true,
ctrlKey: false,
},
"MacIntel",
),
).toBe(true);
expect(
isTerminalLinkActivation(
{
metaKey: false,
ctrlKey: true,
},
"MacIntel",
),
).toBe(false);
});
it("requires ctrl on non-macOS", () => {
expect(
isTerminalLinkActivation(
{
metaKey: false,
ctrlKey: true,
},
"Win32",
),
).toBe(true);
expect(
isTerminalLinkActivation(
{
metaKey: true,
ctrlKey: false,
},
"Linux",
),
).toBe(false);
});
});
+200
View File
@@ -0,0 +1,200 @@
import { EDITORS, type EditorId } from "@t3tools/contracts";
export type TerminalLinkKind = "url" | "path";
export interface TerminalLinkMatch {
kind: TerminalLinkKind;
text: string;
start: number;
end: number;
}
const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/g;
const FILE_PATH_PATTERN =
/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:\\|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
const LAST_EDITOR_KEY = "t3code:last-editor";
function isMacPlatform(platform: string): boolean {
return /mac|iphone|ipad|ipod/i.test(platform);
}
function trimClosingDelimiters(value: string): string {
let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
if (output.length === 0) return output;
const trimUnbalanced = (open: string, close: string) => {
while (output.endsWith(close)) {
const opens = output.split(open).length - 1;
const closes = output.split(close).length - 1;
if (opens >= closes) return;
output = output.slice(0, -1);
}
};
trimUnbalanced("(", ")");
trimUnbalanced("[", "]");
trimUnbalanced("{", "}");
return output;
}
function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
return a.start < b.end && b.start < a.end;
}
function collectMatches(
line: string,
kind: TerminalLinkKind,
pattern: RegExp,
existing: TerminalLinkMatch[],
): TerminalLinkMatch[] {
const matches: TerminalLinkMatch[] = [];
pattern.lastIndex = 0;
for (const rawMatch of line.matchAll(pattern)) {
const raw = rawMatch[0];
const start = rawMatch.index ?? -1;
if (start < 0 || raw.length === 0) continue;
const trimmed = trimClosingDelimiters(raw);
if (trimmed.length === 0) continue;
if (kind === "path" && /^https?:\/\//i.test(trimmed)) continue;
const candidate: TerminalLinkMatch = {
kind,
text: trimmed,
start,
end: start + trimmed.length,
};
const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
if (collides) continue;
matches.push(candidate);
}
return matches;
}
function isWindowsAbsolutePath(value: string): boolean {
return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
}
function isAbsolutePath(value: string): boolean {
return value.startsWith("/") || isWindowsAbsolutePath(value);
}
function isWindowsPathStyle(value: string): boolean {
return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);
}
function joinPath(base: string, next: string, separator: "/" | "\\"): string {
const cleanBase = base.replace(/[\\/]+$/, "");
if (separator === "\\") {
return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
}
return `${cleanBase}/${next.replace(/^\/+/, "")}`;
}
function inferHomeFromCwd(cwd: string): string | undefined {
const posixUser = cwd.match(/^\/Users\/([^/]+)/);
if (posixUser?.[1]) {
return `/Users/${posixUser[1]}`;
}
const posixHome = cwd.match(/^\/home\/([^/]+)/);
if (posixHome?.[1]) {
return `/home/${posixHome[1]}`;
}
const windowsUser = cwd.match(/^([A-Za-z]:\\Users\\[^\\]+)/);
if (windowsUser?.[1]) {
return windowsUser[1];
}
return undefined;
}
function splitPathAndPosition(value: string): {
path: string;
line: string | undefined;
column: string | undefined;
} {
let path = value;
let column: string | undefined;
let line: string | undefined;
const columnMatch = path.match(/:(\d+)$/);
if (!columnMatch?.[1]) {
return { path, line: undefined, column: undefined };
}
column = columnMatch[1];
path = path.slice(0, -columnMatch[0].length);
const lineMatch = path.match(/:(\d+)$/);
if (lineMatch?.[1]) {
line = lineMatch[1];
path = path.slice(0, -lineMatch[0].length);
} else {
line = column;
column = undefined;
}
return { path, line, column };
}
export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
const urlMatches = collectMatches(line, "url", URL_PATTERN, []);
const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, urlMatches);
return [...urlMatches, ...pathMatches].toSorted((a, b) => a.start - b.start);
}
export function isTerminalLinkActivation(
event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
platform = typeof navigator === "undefined" ? "" : navigator.platform,
): boolean {
if (platform.length === 0) return false;
return isMacPlatform(platform)
? event.metaKey && !event.ctrlKey
: event.ctrlKey && !event.metaKey;
}
export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
const { path, line, column } = splitPathAndPosition(rawPath);
let resolvedPath = path;
if (path.startsWith("~/")) {
const home = inferHomeFromCwd(cwd);
if (home) {
const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";
resolvedPath = joinPath(home, path.slice(2), separator);
}
} else if (!isAbsolutePath(path)) {
const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
resolvedPath = joinPath(cwd, path, separator);
}
if (!line) return resolvedPath;
return `${resolvedPath}:${line}${column ? `:${column}` : ""}`;
}
export function preferredTerminalEditor(): EditorId {
const fallback = EDITORS.find((editor) => editor.command)?.id ?? EDITORS[0]?.id ?? "cursor";
if (typeof window === "undefined") {
return fallback;
}
const storedEditor = window.localStorage.getItem(LAST_EDITOR_KEY);
if (!storedEditor) {
return fallback;
}
const configured = EDITORS.find((editor) => editor.id === storedEditor);
if (!configured?.command) {
return fallback;
}
return configured.id;
}
+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
);
}
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more