Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge 04ffe3b247 Fix processRunner exports, runtimeEnvironment leak, and null exit code message
- Remove unnecessary exports from processRunner.ts: toRuntimeCommandOptions,
  ManagedChildProcess, RuntimeCommandOptions, spawnPipedProcess,
  ProcessSpawnOptions, ProcessSpawnSyncOptions, killProcessTree
- Destructure runtimeEnvironment out of options in toRuntimeCommandOptions
  to prevent leaking it into ChildProcess.make
- Handle null exit code in detailFromResult to produce a clear message
  instead of 'Command exited with code null'

Co-authored-by: Julius Marminge <[email protected]>
2026-03-05 21:03:50 +00:00
Julius Marminge df5009c70b Handle null-exit and timeout failures in Codex and Git flows
- squash Effect causes to surface real Codex process error messages
- normalize Git process results to error on signal/null exit and keep details
- treat timed-out Codex health probes/auth checks as unavailable or warning with clear messages
- add tests for cause extraction, Git signal termination, and provider timeout paths
2026-03-05 11:44:07 -08:00
Julius Marminge 454d97f0cf Wire NodeServices into Codex app server manager runtime
- pass `NodeServices` service map through `CodexAdapter` and provider layer
- make `CodexAppServerManager` run effects with injected services
- update manager tests to initialize/dispose a NodeServices runtime per test
2026-03-05 11:17:54 -08:00
Julius Marmingeandcodex 4acb6e91ca Use Effect-managed Codex app-server process lifecycle
- Replace Node child process/readline handling with Effect streams and scoped handles
- Wire CodexAppServerManager to adapter services for runtime-managed execution
- Harden write/exit/stderr handling and close process scope on shutdown

Co-authored-by: codex <[email protected]>
2026-03-05 01:36:14 -08:00
Julius Marminge 45745a247a Improve Windows WSL process and editor/browser interop
- Centralize process spawning/termination in `processRunner` for consistent Windows behavior
- Add runtime environment detection to handle WSL-hosted command resolution
- Update open/editor/browser launch logic to prefer Linux shims and fall back to Windows executables
- Expand server tests for WSL launch paths and shared process helpers
2026-03-05 01:11:29 -08:00
Julius MarmingeandClaude Opus 4.6 b175d6b2a3 Fix CLI publish using stale package.json version
The publish_cli job was checking out the default ref instead of the
preflight commit, so it published with the pre-bump version. Add the
correct ref to checkout and a --app-version flag as a safety override.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-04 10:20:07 -08:00
github-actions[bot]andcodex c5c12aa738 chore(release): prepare v0.0.0-alpha.18
Co-authored-by: codex <[email protected]>
2026-03-04 18:01:45 +00:00
Julius Marminge 7241400edd Add electron-updater and refresh lockfile package versions
- add `electron-updater` dependency for `apps/desktop`
- bump workspace package versions from `0.0.0-alpha.13` to `0.0.0-alpha.16`
- update transitive lockfile entries accordingly
2026-03-04 09:58:22 -08:00
Julius Marminge 310fd0b187 Wait for child process tree shutdown before forcing kill
- add `childTreeGracePeriodMs` constant for shutdown timing
- await grace period after `TERM` before sending `KILL` to avoid dev process leaks
2026-03-04 09:58:22 -08:00
Julius Marminge db94743220 Remove electronmon-specific cleanup from desktop dev script
- drop `electronmon` from desktop dependencies
- stop killing stale processes by matching electronmon hook paths
- keep cleanup scoped to `--t3code-dev-root` processes only
2026-03-04 09:58:22 -08:00
Julius Marminge 07aaf37fd4 Prevent desktop dev Electron process leaks during restarts
- replace `electronmon` with explicit Electron spawn/stop lifecycle management
- debounce file-watch restarts for main/preload/server build outputs
- add stale-process cleanup and forced child-tree shutdown fallback
2026-03-04 09:58:22 -08:00
Julius MarmingeandClaude Opus 4.6 65a808808f Fix electron-updater auth for private GitHub repos
Use setFeedURL with private: true when a GitHub token is provided so
electron-updater queries the GitHub API instead of the public Atom feed
which rejects Bearer auth headers.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-04 00:27:47 -08:00
github-actions[bot]andcodex cca1aa1588 chore(release): prepare v0.0.0-alpha.16
Co-authored-by: codex <[email protected]>
2026-03-04 07:21:44 +00:00
Julius Marminge c9d4b773c9 Remove target arg from electron-builder invocation
- stop passing `options.target` to the electron-builder CLI
- keep platform flag, arch, and `--publish never` unchanged
2026-03-03 23:13:53 -08:00
github-actions[bot]andcodex e23f3102f4 chore(release): prepare v0.0.0-alpha.15
Co-authored-by: codex <[email protected]>
2026-03-04 06:35:27 +00:00
Julius Marminge ec89587c37 Refactor desktop update flow with retryable action results
- Extract desktop updater state transitions into `updateMachine` reducers with tests
- Extend update IPC/contracts to return `{accepted, completed, state}` for download/install actions
- Add web sidebar update-button logic for retryable download/install errors and clearer tooltips
2026-03-03 22:31:45 -08:00
Julius Marminge 32d89806d7 Extract desktop update state helpers and improve update UX
- Add `updateState` helpers for auto-update eligibility reasons and progress throttling
- Show a user-facing dialog when manual update checks are unavailable
- Ensure manual update checks can open a window when none exist
- Add tests for disable-reason logic and 10% download progress bucketing
2026-03-03 22:31:45 -08:00
Julius Marminge 2fd4e06b34 Allow update checks when status is available
- Stop skipping `checkForUpdates` when updater state is `available`
- Continue skipping only while an update is downloading or already downloaded
2026-03-03 22:31:45 -08:00
Julius Marminge 3cffdce1c1 Harden desktop auto-update timer lifecycle
- track and clear startup + poll update timers through one cleanup path
- prevent update checks from starting while the app is quitting
- reset startup timer before scheduling to avoid duplicate checks
2026-03-03 22:31:45 -08:00
Cursor AgentandJulius Marminge 6d2f4f4cdf fix: remove misleading log and redundant guard in handleCheckForUpdatesMenuClick
The guard for status === 'downloaded' logged 'skipping automatic install'
but the function only checks for updates, never installs. The guard was
also redundant since checkForUpdates() already returns early for
'downloaded', 'downloading', and 'available' statuses with correct
log messages.

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

Applied via @cursor push command
2026-03-03 22:31:45 -08:00
Julius Marminge 865d7bd684 Guard update install while app is quitting
- Prevent update install from running when shutdown is already in progress
- Ignore install IPC calls once `isQuitting` is set to avoid duplicate install attempts
2026-03-03 22:31:45 -08:00
Julius Marminge 392d63231c Harden desktop update flow and prevent duplicate update actions
- Skip redundant update checks while update is available/downloading/downloaded
- Wait for backend shutdown before `quitAndInstall` and improve updater error/progress handling
- Prevent sidebar update button clicks during download while preserving tooltip interactivity
2026-03-03 22:31:45 -08:00
Julius Marminge 7559f5ad70 style 2026-03-03 22:31:45 -08:00
Julius Marminge 605e8143e0 Prevent redundant checks during desktop update download
- Skip desktop auto-update checks while an update is downloading or already downloaded
- Subscribe to update-state events before initial fetch in sidebar to avoid stale state races
2026-03-03 22:31:45 -08:00
Julius Marmingeandcodex 5b056cd337 fix: remove duplicate catalog resolver after rebase
Co-authored-by: codex <[email protected]>
2026-03-03 22:31:45 -08:00
Julius Marminge 6c350489b1 Add desktop auto-update flow and publish updater assets
- wire `electron-updater` into desktop main/preload IPC and shared contracts
- add sidebar update action for download/install state in Electron UI
- update release workflow/build script to include `latest*.yml` and `*.blockmap` assets
2026-03-03 22:31:45 -08:00
julius 2ae63f4aa2 Fix shell: true side effects on Windows (orphaned processes, swallowed ENOENT)
Add tree-kill via taskkill /T /F in processRunner and codexAppServerManager so timeout enforcement and session stop properly terminate the entire process tree instead of just the cmd.exe wrapper. Detect Windows command not found (exit 9009) in normalizeExitError. Pre-validate editor commands with isCommandAvailable in open.ts before spawning. Fix ProviderHealth test import and dev-runner test path assertion for Windows.

Made-with: Cursor
2026-03-03 21:03:16 -08:00
julius 3d0233e3b0 fmt test 2026-03-03 21:03:16 -08:00
julius 64f2c3a465 effectify 2026-03-03 21:03:16 -08:00
julius 0a12333448 Fix Codex process spawning and health checks on Windows
- Run Codex-related child processes with `shell` on Windows for reliable command execution
- Switch provider auth probe to `codex login status` and update health-check expectations
- Use Node PTY on Windows instead of Bun PTY in server runtime setup
2026-03-03 21:03:16 -08:00
Julius Marminge 9db54c9b19 Handle Codex auth JSON arrays and flag missing auth markers
- Parse nested/array JSON auth status output from `codex auth status --json`
- Return `unauthenticated` when JSON contains `authenticated: false`
- Return warning when JSON is parseable but lacks an auth marker
2026-03-03 21:03:16 -08:00
julius 34430e3514 windows dev 2026-03-03 21:03:16 -08:00
Julius Marminge 99e44f2c23 Add Codex provider health status to server config and chat banner
- add startup ProviderHealth service/layer to probe Codex install and auth state
- extend server contracts and WS payloads to include provider statuses
- show non-ready provider warnings in ChatView and cover with server/web tests
2026-03-03 21:03:16 -08:00
github-actions[bot]andcodex 7a0f2d9b30 chore(release): prepare v0.0.0-alpha.14
Co-authored-by: codex <[email protected]>
2026-03-04 03:03:52 +00:00
Julius Marminge 4bf310f7ca disable provenacnes while repo is private 2026-03-03 18:59:11 -08:00
github-actions[bot]andcodex 8b9fbe701d chore(release): prepare v0.0.0-alpha.13
Co-authored-by: codex <[email protected]>
2026-03-04 02:25:54 +00:00
Julius Marminge 0c5be023e4 fix test 2026-03-03 18:22:29 -08:00
Julius Marminge 86e87a8789 better lables 2026-03-03 18:22:29 -08:00
Julius Marminge 404e78a506 logging 2026-03-03 18:22:29 -08:00
Julius Marminge 73563c7c25 Add Vitest to root devDependencies
- add `vitest` via catalog in root `package.json`
- update `bun.lock` to include the new workspace dependency
2026-03-03 18:22:29 -08:00
Julius Marminge 326595b148 Add Vitest to web app and remove unused composer/env props
- add `vitest` to `apps/web` devDependencies and lockfile
- remove unused `envMode` prop from `BranchToolbar` usage and signature
- drop unused composer command input ref in `ChatView`
2026-03-03 18:22:29 -08:00
Julius Marminge 41a8468b08 Add effect dependency to desktop app package
- include `effect` in `apps/desktop` runtime dependencies
- update `bun.lock` to reflect the new dependency
2026-03-03 18:22:29 -08:00
Julius Marminge ced2ecb6ba install node 2026-03-03 18:22:29 -08:00
Julius Marminge 2d746b3a7e rm 2026-03-03 18:22:29 -08:00
Julius Marminge e6ac39de75 Migrate dev-runner to typed Effect CLI config and env fallbacks
- Replace string-based env override plumbing with typed config/flag parsing
- Split server/web offset resolution from explicit port/dev-url overrides
- Refactor and expand dev-runner tests around offset/env behavior
- Add `vitest` as a contracts dev dependency for test execution
2026-03-03 18:22:29 -08:00
Julius Marminge b76a0a6c91 Migrate dev runner to TypeScript and share NetService
- Replace `scripts/dev-runner.mjs` with typed `scripts/dev-runner.ts` in a new `@t3tools/scripts` workspace
- Move networking helpers into `@t3tools/shared/Net` and reuse them in server and desktop
- Add shared NetService tests and align workspace deps to `catalog:` versions
2026-03-03 18:22:29 -08:00
Julius Marminge 9fdec3c2c8 Fix npm publish command process invocation
- Pass command and args directly to `ChildProcess.make` in the publish CLI
- Remove fragile template-literal invocation to ensure command runs reliably
2026-03-03 10:55:23 -08:00
Julius Marminge 760fe643e8 helper 2026-03-03 10:01:18 -08:00
Julius Marminge 93af851dc5 type 2026-03-03 10:01:18 -08:00
Julius Marminge fabb3e0734 Extract branch selector and refresh branches on menu open
- Move branch combobox logic into `BranchToolbarBranchSelector` to simplify `BranchToolbar`
- Re-fetch git branches when opening the selector so options are current
- Preserve draft env mode correctly when switching between main and worktree branches
2026-03-03 10:01:18 -08:00
Julius Marminge 9ca9a862a5 Fix branch selector default and loading behavior in worktree mode
- Default new worktree branch selection to the current checked-out branch when unset
- Extract branch value resolution into shared logic with tests
- Stabilize virtualized branch list scroll/measurement to avoid loading glitches
2026-03-03 10:01:18 -08:00
github-actions[bot]andcodex 827dc9ff9f chore(release): prepare v0.0.0-alpha.12
Co-authored-by: codex <[email protected]>
2026-03-03 18:01:00 +00:00
Julius Marminge 09b32ac9dd Extract slash model option filtering into shared app settings helper
- add `getSlashModelOptions` to centralize `/model` suggestion filtering
- include custom saved model slugs in slash-command suggestions
- update ChatView to consume shared helper and add focused tests
2026-03-03 09:31:54 -08:00
Julius Marminge 253684e280 kewl 2026-03-03 09:18:08 -08:00
Julius Marminge f6d40ce841 log? 2026-03-03 09:12:28 -08:00
github-actions[bot]andcodex 36fb1bb7e4 chore(release): prepare v0.0.0-alpha.11
Co-authored-by: codex <[email protected]>
2026-03-03 17:09:58 +00:00
Julius Marminge 4a82c1608f fix pub 2026-03-03 09:06:05 -08:00
github-actions[bot]andcodex 3efb3da007 chore(release): prepare v0.0.0-alpha.10
Co-authored-by: codex <[email protected]>
2026-03-03 08:33:23 +00:00
Julius Marminge 11606fd9c6 cli for pub 2026-03-03 00:30:15 -08:00
github-actions[bot]andcodex a935db07ef chore(release): prepare v0.0.0-alpha.9
Co-authored-by: codex <[email protected]>
2026-03-03 07:36:01 +00:00
Julius Marminge 98860a9549 ignore scripts on publish 2026-03-02 23:33:14 -08:00
github-actions[bot]andcodex 7688742b2a chore(release): prepare v0.0.0-alpha.8
Co-authored-by: codex <[email protected]>
2026-03-03 07:02:39 +00:00
Julius Marminge b2efe4f83c cwd 2026-03-02 22:56:37 -08:00
github-actions[bot]andcodex f934b435fa chore(release): prepare v0.0.0-alpha.7
Co-authored-by: codex <[email protected]>
2026-03-03 06:46:02 +00:00
Julius Marminge 3c121585da publish cli? 2026-03-02 22:42:21 -08:00
github-actions[bot]andcodex 40acfbd2df chore(release): prepare v0.0.0-alpha.6
Co-authored-by: codex <[email protected]>
2026-03-03 06:01:37 +00:00
Julius Marminge 0af61bf6ba verbose 2026-03-02 21:58:36 -08:00
github-actions[bot]andcodex 7b2968f2ff chore(release): prepare v0.0.0-alpha.5
Co-authored-by: codex <[email protected]>
2026-03-03 05:55:00 +00:00
Julius Marminge a1c7b98f98 fix build script 2026-03-02 20:59:56 -08:00
Julius Marmingeandcodex 99ea16a969 Restore Open PR CTA for commit_push with existing PR
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex ebe44d03a5 Revert git action button logic toward main behavior
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex dcd2d50768 Keep non-default quick action on full PR flow
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex f11764c517 Fix PR CTAs and quick action after push
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex 77c81b7468 Restore Open PR toast action after PR creation
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex 7a5ccd3310 Fix toast follow-up actions to avoid re-branching
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex e4df6fcf8e Scope default-branch PR confirmation to full stack
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marmingeandcodex b2be7f4e4f Address PR feedback on git workflows
Co-authored-by: codex <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge 94beb21a43 Skip commit progress stages when create-PR runs push-only
- pass `forcePushOnlyProgress` for the create-PR action
- add logic test to ensure only push and PR stages are shown
2026-03-02 20:46:05 -08:00
Julius Marminge 30e05538b7 Limit default-branch confirmation to direct push
- Stop showing default-branch confirmation for `commit_push_pr`
- Keep confirmation only for direct `commit_push` actions
- Update logic test to match the new behavior
2026-03-02 20:46:05 -08:00
Julius Marminge c884947ea8 Scope branch checkout effect during auto branch creation
- Wrap checkout in `Effect.scoped` when creating a new feature branch
- Align branch switch lifecycle with scoped effect handling
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 61289a152d Fix duplicated branch logic and feature-branch dialog on push-only
Deduplicate feature/ prefix logic in resolveAutoFeatureBranchName by
delegating to sanitizeFeatureBranchName. Skip the default-branch
confirmation dialog when there are no uncommitted changes (push-only),
since runFeatureBranchStep requires dirty worktree. Add merge-base
assertions to feature branch tests.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 906550f9af Merge feature-branch checkout into atomic runStackedAction
Consolidate the fragile 3-RPC flow (suggestCommitAndBranch → createBranch +
checkout → runStackedAction) into a single server-side operation triggered by
`runStackedAction({ featureBranch: true })`. The server now generates the
branch name via AI, deduplicates it, creates + checks out the branch, then
runs the normal commit/push/PR pipeline atomically.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge c2aaa89b57 Document contracts and shared package responsibilities
- Clarify that `packages/contracts` is schema-only with no runtime logic
- Add `packages/shared` as the home for shared runtime utilities and subpath exports
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 dde48e9414 Move branch sanitization from contracts to new shared package
Create @t3tools/shared with explicit subpath exports (no barrel) for
shared utility logic. Move sanitizeBranchFragment and
sanitizeFeatureBranchName to @t3tools/shared/git, keeping contracts
focused on schemas.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.6 b1608f41ad Extract branch sanitization to shared contracts module
Move sanitizeBranchFragment and sanitizeFeatureBranchName from three
duplicate definitions (CodexTextGeneration, GitManager, GitActionsControl)
into packages/contracts/src/git.ts. Remove the redundant double-sanitization
of branch names between the TextGeneration and GitManager layers —
CodexTextGeneration now owns sanitization of model output while GitManager
trusts the result and only sanitizes the custom commit message path.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge 78d89e3d35 non-dupicate 2026-03-02 20:46:05 -08:00
Julius Marminge 1309495218 optional 2026-03-02 20:46:05 -08:00
Julius MarmingeandClaude Opus 4.5 c34a4c69e5 Add AI-generated semantic branch naming for git commits
Replace date-based auto feature branch names (feature/stacked-YYYYMMDD)
with semantically meaningful names derived from AI-generated commit
messages. The text generation prompt now returns a branch field alongside
subject and body, and a new suggestCommitAndBranch endpoint exposes this
to the web client for the default-branch checkout flow.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-03-02 20:46:05 -08:00
Julius Marminge 2f6cac0cf0 no forwardref needed 2026-03-02 20:31:39 -08:00
Julius Marminge 5c26df3a4f Virtualize branch picker list and forward ComboboxList ref
- Add virtualized rendering and filtered item handling in `BranchToolbar`
- Memoize branch-derived data and sync highlight scrolling for large branch sets
- Convert `ComboboxList` to `forwardRef` to support virtualizer scroll targeting
2026-03-02 20:31:39 -08:00
Julius Marminge 302323a64b Fix Windows command detection and branch checkout error flow
- tighten win32 command availability checks for PATHEXT and PATH delimiter handling
- add server tests for Windows executable resolution edge cases
- stop branch/create flows after checkout/create failures to avoid stale optimistic UI
- remove OpenInPicker side effect that persisted last editor on render
2026-03-02 18:53:21 -08:00
Julius Marminge b981fad920 Sync thread metadata after worktree branch rename
- Dispatch `thread.meta.update` with the renamed branch after `git.renameBranch`
- Remove pre-rename active-branch status check and related skip path
- Update reactor tests to assert branch metadata moves to generated branch
2026-03-02 18:53:21 -08:00
Julius Marminge 8a2f2a5c2b Gate embedded commit hash lookup to packaged desktop builds
- Prefer `T3CODE_COMMIT_HASH` when set
- Return `null` for unpackaged desktop runs instead of reading embedded metadata
2026-03-02 18:53:21 -08:00
Julius Marminge e319735ed1 Refactor commit hash resolution in About panel
- Remove git command execution for commit hash retrieval
- Simplify commit hash resolution to use environment variable and embedded hash only
- Clean up unused code in IPC handler registration
2026-03-02 18:53:21 -08:00
Julius Marminge e7790490f1 Show desktop commit hash in About panel
- embed `t3codeCommitHash` into staged desktop package metadata during builds
- resolve commit hash from env/package/git and display it as About panel version
2026-03-02 18:53:21 -08:00
Julius Marminge a638978b75 Refactor branch toolbar actions to use transition-based git ops
- replace React Query mutations with direct git API calls wrapped in `useTransition`
- show toast errors for branch create/checkout failures and keep optimistic branch updates
- disable branch controls during pending actions and refresh branches when opening menu
2026-03-02 18:53:21 -08:00
Julius Marminge 4a08686e74 Add Zed editor support across open-in flow
- add `zed` to shared editor contracts and Open In picker
- add Zed icon and wire launch resolution tests on macOS
- wrap branch optimistic updates in `startTransition` to avoid sync warnings
2026-03-02 18:53:21 -08:00
Julius Marminge b3de2bd926 Expose available editors and gate Open In options
- Add server-side command detection and return `availableEditors` in server config
- Update Chat header Open In picker to show only installed editors and handle empty state
- Extend server/web tests and contracts for `availableEditors`; remove unused branch-sync logic
2026-03-02 18:53:21 -08:00
Julius Marminge b81ec02984 Show optimistic active branch during checkout and branch creation
- use `useOptimistic` in `BranchToolbar` to update active branch immediately
- keep optimistic branch in sync on success and roll back on mutation errors
2026-03-02 18:53:21 -08:00
Julius Marminge de61c0c42b Guard worktree branch rename and fix branch toolbar state
- Skip auto-rename when the active worktree branch no longer matches the temp branch
- Update reactor tests to cover branch-switch and first-turn rename behavior
- Show the actual current branch in the toolbar and use a VS Code icon in Open In picker
2026-03-02 18:53:21 -08:00
Julius Marminge ecb4a1efa4 Add VS Code open support and stabilize chat autoscroll
- add VS Code to editor contracts and picker UI
- use `code --goto` for line/column targets in open resolution
- refine chat scroll intent handling to avoid unwanted stick-to-bottom jumps
2026-03-02 16:06:17 -08:00
Julius Marminge 1b0093a483 fmt 2026-03-02 16:03:11 -08:00
Julius Marminge 06fc364ee1 Scope git checkout effects and bump Effect/Node dependencies
- run `gitCheckout` via `Effect.scoped` to satisfy new `Scope` requirement
- update `GitCore.checkoutBranch` service signature to include `Scope.Scope`
- upgrade Effect catalog refs and `@types/node` to latest pinned versions
2026-03-02 16:03:11 -08:00
Julius Marminge 094859bbc7 Allow chat composer to shrink within constrained layouts
- Replace composer form `min-w-fit` with `min-w-0` in `ChatView`
- Prevent overflow and improve responsiveness in narrow containers
2026-03-02 15:42:05 -08:00
Julius MarmingeandClaude Opus 4.6 5e78386cdc Improve composer menu highlighting and suppress triggers near mentions
Adds visual active-item highlighting to the command menu, suppresses
trigger detection when the cursor is adjacent to a mention pill, and
resets transient UI state on thread change.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 14:16:08 -08:00
Julius Marminge c378afeff8 Fix composer mention cursor handling and trigger detection
- Treat mention pills as atomic cursor units in Lexical selection math
- Add left/right arrow + selection normalization behavior around mention nodes
- Expand collapsed mention cursor before trigger detection so @path menu closes correctly
- Update mention pill rendering for non-editable, non-selectable chips and theme-aware icons
- Add tests for collapsed-to-expanded cursor mapping and trigger behavior
2026-03-02 14:16:08 -08:00
Julius MarmingeandClaude Opus 4.5 bf7002209e Add Lexical-based composer editor with file mention pills
Introduce ComposerPromptEditor component using Lexical for rich text
editing with @-mention support for files. Includes mention detection
utilities and tests.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-03-02 14:16:08 -08:00
Julius MarmingeandClaude Opus 4.6 a3aa4bd189 Fix destructive menu icon showing app logo on non-macOS
getDestructiveMenuIcon fell back to resolveIconPath("png") on
Windows/Linux which resolved to the T3 Code app icon, not a trash
icon. Restrict the icon to macOS where createFromNamedImage("trash")
provides the correct system icon.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 5a0006f7ef Guard all commitRename cleanup paths against concurrent renames
All exit paths in commitRename now use a thread-guarded finishRename
helper that only clears renamingThreadId when it still matches the
original threadId. Prevents a stale onBlur from cancelling a newly
started rename on a different thread.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 9e2e73c070 Import ContextMenuItem from contracts in desktop app
Remove the duplicate DesktopContextMenuItem interface and use the
shared ContextMenuItem type from @t3tools/contracts instead.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 c530e5d50f Guard commitRename cleanup against concurrent renames
After the async dispatch, only clear renamingThreadId if it still
matches the thread being renamed, preventing a second rename's
input from being cleared by the first's completion.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 674720c6cd Use shared ContextMenuItem type from contracts
Re-export ContextMenuItem and replace the inlined
{ id: T; label: string; destructive?: boolean } definitions in
wsNativeApi, contextMenuFallback, and the test file.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 58c9e4b96d Make ContextMenuItem interface module-private
Only used internally within ipc.ts for DesktopBridge and NativeApi
type signatures, so no need to export it.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 feb286379c Stop keydown propagation on rename input
Prevents Space from triggering the parent SidebarMenuSubButton's
navigation handler while typing in the inline rename input.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 cefe641586 Remove unused prompt dialog infrastructure
The inline rename replaces the prompt dialog entirely, so remove the
promptDialog.ts file, IPC channels, bridge methods, and related tests.
Context menu improvements (destructive, position) are kept.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 664451c296 Replace prompt dialog with inline rename in sidebar
Thread rename now uses an inline input directly in the sidebar row
instead of opening a separate Electron BrowserWindow or browser
window.prompt. Enter commits, Escape cancels, blur saves.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:49:04 -08:00
Julius MarmingeandClaude Opus 4.6 fd4ff8ca46 Restore lost useMemo calls in ChatView and fix threadActivities referential stability
Revert bare function calls / IIFEs back to useMemo for: modelOptions,
workLogEntries, latestTurnHasToolActivity, pendingApprovals, timelineEntries,
revertTurnCountByUserMessageId, completionSummary, and
completionDividerBeforeEntryId.

Add EMPTY_ACTIVITIES module-level constant so the ?? [] fallback doesn't
create a new array reference every render, which was defeating memoization.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:13:19 -08:00
Julius Marminge 1bcfbdf287 rm 2026-03-02 13:13:19 -08:00
Julius MarmingeandClaude Opus 4.6 4e45c1a6ab Fix store selector consistency, memoize timelineMessages, and suppress false-positive lint warnings
- Hoist removeOrphanedTerminalStates to a top-level selector in EventRouter
  for consistency with other store selectors
- Convert timelineMessages IIFE to useMemo with proper deps
- Suppress no-map-spread in ChatView (spread is conditional, immutability required)
- Suppress exhaustive-deps for autoFocus in TerminalViewport (mount-time only)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:13:19 -08:00
Cursor AgentandJulius Marminge 32fe80d164 Fix terminal focus on toggle, clean up orphaned terminal state, and revoke optimistic message blob URLs on unmount
- Add setTerminalFocusRequestId call when terminal opens via toggle so the
  terminal panel receives focus automatically
- Call clearTerminalState when deleting threads in the Sidebar and add
  removeOrphanedTerminalStates to prune stale entries after read model sync
- Track optimisticUserMessages via ref and revoke their blob URLs in the
  unmount cleanup effect to prevent memory leaks

Co-authored-by: Julius Marminge <[email protected]>
2026-03-02 13:13:19 -08:00
Julius Marmingeandmacroscopeapp[bot] 6e93d42023 Update apps/web/src/routes/__root.tsx
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
2026-03-02 13:13:19 -08:00
Julius MarmingeandClaude Opus 4.6 6f50867aa1 Improve store referential stability and fix reactive terminal state
- Deep clone DEFAULT_THREAD_TERMINAL_STATE in createDefaultThreadTerminalState
- Remove imperative getTerminalState from terminal store; export
  selectThreadTerminalState for reactive selectors instead
- Fix Sidebar terminal activity indicator not updating (was using
  non-reactive getter)
- Add no-op bailouts to app store transitions (updateThread,
  markThreadVisited, markThreadUnread, setError, setThreadBranch,
  setProjectExpanded, setRuntimeMode) to prevent unnecessary re-renders
- Use createDefaultThreadTerminalState in clearTerminalState to avoid
  storing frozen reference

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-02 13:13:19 -08:00
Julius Marminge 4fca60469d Reset ChatView per thread and simplify derived state handling
- Mount `ChatView` with `key={threadId}` to fully reset UI state on thread switch
- Replace effect-driven local state with direct derived values and cleaner cleanup paths
- Simplify async command/script flows and minor context memo handling in sidebar/ui components
2026-03-02 13:13:19 -08:00
Julius Marminge afcd824ae9 fix(web): resolve post-rebase selector/store regressions
Remove duplicate selector declarations introduced during rebase and restore the streamlined AppStore shape so Zustand selector usage remains consistent.
Restore Sidebar cleanup semantics and pure store test assertions so lint/typecheck stay green after rebasing.

Made-with: Cursor
2026-03-02 13:13:19 -08:00
Julius Marminge f84f279738 Refactor Zustand store usage to granular selectors
- Replace combined `useStore` state/dispatch wrapper with direct selector/action hooks across chat UI components
- Inline and harden terminal state transitions inside `terminalStateStore` and remove `threadTerminalState`
- Add `terminalStateStore` action tests covering defaults, splits, groups, activity, and close/reset behavior
2026-03-02 13:13:19 -08:00
Julius Marminge 246624ad3c Refactor terminal state store to use granular thread selectors
- Replace `getTerminalState` reads with `selectThreadTerminalState` in ChatView and Sidebar
- Split terminal reducer into pure thread terminal operations used by the Zustand store
- Drop persisted default thread entries and add tests for the new operation helpers
2026-03-02 13:13:19 -08:00
Julius Marminge 410444aead Remove useStore selector compatibility shim
Drop the temporary selector overload from useStore and migrate the remaining selector call sites to the unified { state, dispatch } API so the store surface stays single-path.

Made-with: Cursor
2026-03-02 13:13:19 -08:00
Julius Marminge 7522d3bde3 refactor(web): remove reducer pattern, use Zustand + pure functions
- Main store: replace useReducer with Zustand; pure state transition
  functions (syncServerReadModel, markThreadVisited, setError, etc.)
  called via store methods. Persist via subscribe.
- Terminal store: single store keyed by threadId; replace
  dispatchTerminalAction with direct methods (setTerminalOpen,
  setTerminalHeight, splitTerminal, newTerminal, setActiveTerminal,
  closeTerminal, setTerminalActivity). Pure reduceThreadTerminalState
  used internally.
- Update all consumers to call dispatch.method(...) and terminal
  store methods. Fix store tests to use markThreadUnread pure fn.
- Fix Fragment import in store.ts; fix unused get param for lint.

Made-with: Cursor
2026-03-02 13:13:19 -08:00
Julius Marminge ed26b84177 Remove draftThreadTerminalState re-exports; use threadTerminalState directly
- Delete draftThreadTerminalState.ts (was only re-exporting shared module)
- Replace draftThreadTerminalState.test.ts with threadTerminalState.test.ts
  using createDefaultThreadTerminalState and reduceThreadTerminalState
- Draft threads are first-class: same helpers and types as persisted threads

Made-with: Cursor
2026-03-02 13:13:19 -08:00
Julius Marminge ad4d12cf94 Unify draft and persisted thread terminal flow
- Add shared threadTerminalState.ts: ThreadTerminalState type, default state,
  normalize helpers, and single reduceThreadTerminalState() used by both flows
- Refactor store.ts to use shared terminal reducer and helpers; terminal
  actions map to reduceThreadTerminalState(threadTerminalSlice(thread), action)
- Make draftThreadTerminalState.ts re-export shared module (same shape/actions)
- Add terminalState to composer draft store: getDraftThreadTerminalState,
  setDraftThreadTerminalAction, clearDraftThreadTerminalState; draft thread
  shape matches Thread terminal slice
- ChatView: move draft terminal from useState into composer draft store; use
  same actions for draft and persisted; hydrate then clear draft terminal
  when reconciling server state

Made-with: Cursor
2026-03-02 13:13:19 -08:00
Julius MarmingeandClaude Opus 4.5 f6fd760e4e Enable terminals for local draft threads
Adds local terminal state management for draft threads before they're
promoted to server threads. Terminal operations (open, split, create,
close, activate, resize) now work on draft threads and hydrate into
the server thread state when the draft is promoted.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-03-02 13:13:19 -08:00
Julius Marminge 506a5260dc Refactor store actions to use direct Zustand state updaters
- Remove Action union/reducer dispatch path in `store.ts`
- Extract per-action state transition helpers and apply via `setAppState`
- Update `store.test.ts` to validate behavior through `useStore` actions
2026-03-02 13:13:19 -08:00
Julius Marminge d4c90d696d Simplify Zustand selectors by removing memoized callbacks
- Replace `useCallback`-wrapped `useStore` selectors with inline selectors
- Apply across chat, diff, branch toolbar, and chat thread route components
2026-03-02 13:13:19 -08:00
Julius Marminge be4d26a1b3 Refactor web store usage to granular selectors
- Replace broad `useStore` state reads with targeted selector/action hooks across chat, diff, sidebar, and routing views
- Remove dispatch-style calls in favor of direct store actions to reduce unnecessary rerenders
- Improve chat UI interactions (composer menu navigation, image preview buttons, modal click targets)
- Add local `react-doctor` agent skill docs under `apps/web/.agents/react-doctor`
2026-03-02 13:13:19 -08:00
Julius Marminge 5c09614319 refactor: remove redundant workLogCount stick-to-bottom effect
timelineEntries is derived from workLogEntries; the timelineEntries
effect already runs when work log changes. Dropped duplicate effect
and unused workLogCount variable.

Made-with: Cursor
2026-03-02 10:19:22 -08:00
Julius Marminge 4c846332c5 fix: align handoff preview URLs with image attachment index
collectUserMessageBlobPreviewUrls returns a compact array (image+blob only).
Consumer now indexes by image position, not full attachment index, so
blob URLs apply to the correct server attachments when some are skipped.

Made-with: Cursor
2026-03-02 10:19:22 -08:00
Julius Marminge a3a0cbf0f8 Stabilize chat scroll restoration across thread switches
- Keep auto-scroll pinned to bottom during thread changes, composer resize, and streaming updates
- Improve virtualized timeline measurement/keying to prevent stale height reuse between threads
- Hand off blob image preview URLs from optimistic to server messages to avoid flicker/revocation races
2026-03-02 10:19:22 -08:00
Julius Marminge 2c7101092a Set default cursor on sidebar session rows
- Add `cursor-default` to sidebar row classes in `Sidebar.tsx`
- Keeps list items from showing a pointer cursor while preserving hover/active styles
2026-03-02 00:06:23 -08:00
Julius Marminge 9f068356a4 Allow non-required dev ports to exceed max in offset search
- Stop `findFirstAvailableOffset` only when a required port exceeds `MAX_PORT`
- Add test covering offsets where only non-required ports are out of range
2026-03-01 23:53:31 -08:00
Julius Marminge f239c90628 Auto-select next available dev ports per mode
- Probe localhost ports and increment offsets when base ports are taken
- Resolve server/web offsets by mode while honoring explicit port/dev-url overrides
- Add tests for offset selection and per-mode fallback behavior
2026-03-01 23:53:31 -08:00
Julius Marminge 991dd05e72 Use forkScoped for background upstream refresh
- replace `Effect.forkDetach` with `Effect.forkScoped` when refreshing checked-out branch upstream refs
- keep checkout responsive while ensuring the background task stays tied to scope lifecycle
2026-03-01 23:24:22 -08:00
Julius Marminge 96bf54e293 Serve fallback project favicon when no icon file is found
- return an inline SVG favicon instead of 404 when project/icon files are missing
- add route test coverage for fallback response status and MIME type
2026-03-01 23:18:45 -08:00
Julius Marminge 5ca9b54d66 Preserve $defs in Codex output schema and refine sidebar header
- include JSON Schema `$defs` when writing Codex output schema files
- tighten sidebar wordmark sizing and spacing in Electron/web layouts
2026-03-01 23:11:44 -08:00
Julius Marminge 4ab5fca4ca Preserve draft env mode across thread and branch context updates
- Track and persist `envMode` in composer draft thread state
- Keep worktree mode for local drafts even when `worktreePath` is null
- Update branch toolbar/chat/sidebar to use effective draft env mode
- Add tests for env mode persistence and undefined option merges
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex 69a4fa8215 Show branch toolbar for local draft threads
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marminge 9e04bad0a5 Run setup script after promoting local draft threads
- allow `runProjectScript` for local draft threads when explicitly enabled
- move setup script execution to run after server thread creation
- gate setup script on worktree/base-branch availability and pass resolved worktree cwd
2026-03-01 22:36:35 -08:00
Julius Marminge a574d9c936 Cover runtime undefined draft thread options in store test
- Build options object with runtime `undefined` values via cast
- Pass object into `setProjectDraftThreadId` to verify handling path
2026-03-01 22:36:35 -08:00
Julius Marminge 005e13089a Preserve draft branch/worktree when update options are undefined
- Keep existing `branch` and `worktreePath` values when `setProjectDraftThreadId` receives `undefined`
- Add a regression test covering the undefined-update case
2026-03-01 22:36:35 -08:00
Julius Marminge d9cce6402a Clean up orphaned composer drafts and harden draft checks
- Remove stale `draftsByThreadId` entries when project-thread mappings are replaced or cleared
- Preserve drafts when a thread is still mapped to another project
- Parse persisted image `dataUrl` payloads more defensively and use `Object.hasOwn` for draft-thread existence checks
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex 508872e04b Preserve explicit DEFAULT_MODEL draft overrides
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marmingeandcodex aced302b63 Address PR review feedback for draft model/error/persistence handling
Co-authored-by: codex <[email protected]>
2026-03-01 22:36:35 -08:00
Julius Marminge 0b8dfee17b Simplify composer draft persistence and remove debug instrumentation
- Remove ChatView draft persistence debug logging and storage size plumbing
- Drop in-memory persisted draft cache; use JSON storage directly
- Reconcile attachment IDs from localStorage and streamline image hydration
2026-03-01 22:36:35 -08:00
Julius Marminge 6ab246676e Refactor draft thread lookups and cache persisted draft state
- replace `read*` draft selectors with `getDraftThread`/`getDraftThreadByProjectId`
- centralize persisted localStorage parsing/caching in `composerDraftStore`
- make ChatView fallback read persisted attachments from in-memory store state
2026-03-01 22:36:35 -08:00
Julius Marminge 122c94a24a Defer thread creation until first message send
- Track draft thread metadata in composer draft store
- Reuse and update local draft threads from Sidebar/ChatView
- Create server thread only when sending first message, with rollback on failure
- Add/expand draft-thread store tests for mapping and context updates
2026-03-01 22:36:35 -08:00
Julius Marminge b59c6d6ab1 Unify project draft thread state in composer draft store
- move project draft thread ID persistence/actions into `composerDraftStore`
- remove legacy `projectDraftThreads` module and update `ChatView`/`Sidebar` callers
- keep image dedupe stable across hydration and avoid revoking blob URLs on composer clear
- add store tests for project-thread mapping and composer clear behavior
- drop deprecated model slug aliases (`gpt-5`, `gpt-5-codex`, `gpt-5-codex-spark`)
2026-03-01 22:36:35 -08:00
Julius Marminge c9995995a4 Preserve draft metadata and dedupe composer image retries
- Reuse hidden draft threads while applying requested branch/worktree updates before navigation
- Export composer draft storage key and clone blob preview URLs when re-adding images after retry
- Deduplicate composer images by file signature (within and across calls) and add store tests for URL revoke behavior
2026-03-01 22:36:35 -08:00
Julius Marminge 545a9193e2 Persist per-thread composer drafts and reuse project draft threads
- add a zustand-backed composer draft store with localStorage persistence for prompt, cursor, model/effort, and image attachments
- wire ChatView to draft state, restore/clear drafts correctly, and warn when an attachment cannot be persisted
- track per-project draft thread IDs so Sidebar reuses hidden draft threads and excludes empty drafts from thread lists
2026-03-01 22:36:35 -08:00
Julius Marminge fa0205cba3 Run checks before release commit and set desktop buildVersion
- Move install, lint, typecheck, and test steps ahead of release commit/tag in `release.yml`
- Add `buildVersion` to staged desktop `package.json` and set it to the app version
2026-03-01 20:33:00 -08:00
github-actions[bot]andcodex 8a20bd7f54 chore(release): prepare v0.0.0-alpha.4
Co-authored-by: codex <[email protected]>
2026-03-02 04:23:28 +00:00
Julius Marmingeandcodex 10660f376c fix(server): remove duplicate branchExists declaration
Co-authored-by: codex <[email protected]>
2026-03-01 20:19:39 -08:00
Julius Marmingeandcodex ae235f7155 feat(ci): add release workflow_dispatch version tagging
Co-authored-by: codex <[email protected]>
2026-03-01 20:13:24 -08:00
Julius Marminge a356cd0d0f Remove unused attachment route path helpers
- delete route-to-path conversion helpers from `attachmentPaths`
- remove unused `attachmentRoutePath` export and route prefix import
2026-03-01 20:06:21 -08:00
Julius Marminge 58b932ffb8 Normalize attachment thread segments to lowercase
- Lowercase sanitized thread segments when creating attachment IDs
- Add coverage for mixed-case thread IDs in attachment store and projection pipeline tests
2026-03-01 20:06:21 -08:00
Julius Marminge d58af33fba Fix attachment cleanup to match exact thread segments
- Parse thread segments from attachment IDs using a UUID-aware pattern
- Prevent revert/delete cleanup from removing files belonging to similarly prefixed threads
- Add tests for prefix-collision cases in attachment store and projection pipeline
2026-03-01 20:06:21 -08:00
Julius Marminge a56418f8bc Reuse attachment thread segment sanitizer in projection pipeline
- export and reuse `toSafeThreadAttachmentSegment` from `attachmentStore`
- align projection attachment path logic with store-safe thread IDs
- update projection pipeline tests to cover thread IDs with spaces
2026-03-01 20:06:21 -08:00
Julius Marminge 596e1590df Read stdin before validating required image flag in codex test stub
- Move stdin capture earlier in fake codex script setup
- Ensure stdin-based assertions remain available even when image validation fails
2026-03-01 20:06:21 -08:00
Julius Marminge 70c9147c7f Harden attachment ID resolution and missing-file handling
- Sanitize thread-derived attachment ID segments to safe, bounded tokens
- Resolve attachment IDs only when a matching file exists on disk
- Return 404 (not 400) for missing attachment IDs in the attachment route
- Add attachmentStore tests for ID sanitization and extension-based path lookup
2026-03-01 20:06:21 -08:00
Julius Marminge c0054cb56f Switch image attachments to persisted ID-based paths
- add attachment store helpers for IDs, route paths, and file resolution
- stop projection pipeline from mutating/storing data URLs; keep attachment metadata unchanged
- update Codex send/branch generation flows and tests to resolve images via attachment IDs
2026-03-01 20:06:21 -08:00
Julius Marmingeandcodex 41734dfbbf fix: address PR review feedback
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:21 -08:00
Julius Marminge 8f42d34db9 Inject test ServerConfig across orchestration and git layers
- add `ServerConfig.layerTest(cwd, stateDir)` to standardize test wiring
- require `ServerConfig` in `CodexTextGeneration` attachment path resolution
- update orchestration/projection tests and harness to use managed runtimes with explicit config
2026-03-01 20:06:21 -08:00
Julius Marminge 70857ce299 Handle parameterized base64 image data URLs
- accept `data:image/...;...;base64,...` headers while still rejecting invalid formats
- add `imageMime` tests for mime params, non-base64 URLs, and missing mime types
- fork branch-generation prompt effect at call site in `ProviderCommandReactor`
2026-03-01 20:06:21 -08:00
Julius Marminge 5e0ec38383 Use Effect Schema to decode Codex structured outputs
- Replace manual JSON schema constants and parse helpers with `Schema.Struct` definitions
- Generate JSON Schema from Effect Schema and decode output via `Schema.fromJsonString`
- Map `SchemaError` to `TextGenerationError` for invalid Codex responses
- Update `ProviderCommandReactor` test mock typing for `generateBranchName`
2026-03-01 20:06:21 -08:00
Julius Marminge 913d0409f6 Handle branch-name generation failures as typed errors
- Make branch-name generation return a required string instead of nullable output
- Propagate invalid Codex branch payloads as `TextGenerationError` instead of silently falling back
- Update provider command reactor to catch generation failures, log warnings, and skip rename safely
2026-03-01 20:06:21 -08:00
Julius Marminge ac0e720de1 fine there 2026-03-01 20:06:21 -08:00
Julius Marminge 5144d32b77 nit 2026-03-01 20:06:21 -08:00
Julius Marminge 128cc21516 data uri for app server 2026-03-01 20:06:21 -08:00
Julius Marminge 215ff36362 nit 2026-03-01 20:06:21 -08:00
Julius Marminge 505b4d0bc3 Resolve persisted attachment paths across server pipelines
- add shared attachment path normalization and resolution helpers
- reuse persisted image files for turn start and branch name generation
- cover persisted attachment flow in text generation and reactor tests
2026-03-01 20:06:21 -08:00
Julius Marminge 343c0a9472 Generate temporary worktree branch names from UUID tokens
- Remove message/time hashing for temporary branch names in `ChatView`
- Use an 8-char UUID token while preserving backend-detected suffix format
2026-03-01 20:06:21 -08:00
Julius Marminge 82681606d0 Remove git.renameBranch RPC and harden branch rename args
- remove `git.renameBranch` from WS/contracts/native API surface and update server/web tests
- use `git branch -m -- ...` in GitCore to safely separate branch rename arguments
2026-03-01 20:06:21 -08:00
Julius Marminge c91b79b6e2 Scope upstream refresh in checkout effect lifecycle
- Replace fire-and-forget `Effect.runPromise` call with `Effect.forkScoped`
- Keep checkout responsive while tying upstream refresh to scoped effect management
2026-03-01 20:06:21 -08:00
Julius Marminge 5e55aa387f Move worktree branch auto-rename into provider turn reactor
- Generate and rename temporary `t3code/*` worktree branches on first user turn in `ProviderCommandReactor`
- Remove websocket/client branch-generation RPCs and related contract/API surface
- Update Codex text-generation prompt to include attachment metadata only when attachments exist, with expanded tests
2026-03-01 20:06:21 -08:00
Julius Marminge a21095bc9a Add AI-generated worktree branch naming and safe branch rename
- add `git.generateBranchName`, `git.generateAndRenameBranch`, and `git.renameBranch` websocket flows
- pass image attachments into Codex branch-name generation and normalize/sanitize results
- add GitCore branch rename with collision-safe numeric suffixing
- extract shared image MIME/data-url helpers and expand server/web tests for new behavior
2026-03-01 20:06:21 -08:00
Julius Marmingeandcodex ba03241df3 fix: address latest git action review feedback
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex a8059dc2c0 fix: reuse git action toast after feature-branch checkout
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex be873bca3e fix: widen default-branch action dialog
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Cursor AgentandJulius Marminge e8bde958f1 Fix: reset hasUpstream, aheadCount, behindCount in statusOverride after branch checkout
Co-authored-by: Julius Marminge <[email protected]>

Applied via @cursor push command
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex 95f21c1099 fix: make default-branch confirmation copy action-aware
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex 8cd92150b1 test: use dynamic default branch in remote-base-ahead case
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex d0ab35931e fix: resolve no-upstream base from origin tracking branches
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex 882684a80c fix: keep toast CTA git actions on the active feature branch
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex 96efd1cef0 fix: avoid no-upstream push skip when base cannot be resolved
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marmingeandcodex c8974ede6d refactor: dedupe git action new-branch flow
Co-authored-by: codex <[email protected]>
2026-03-01 20:06:01 -08:00
Julius Marminge 0c637e3d5e Handle no-upstream branches by comparing commits against base
- Compute ahead count from base branch when upstream is missing
- Skip push/PR actions when no local commits are ahead
- Update server and UI tests for no-upstream push/PR behavior
2026-03-01 20:06:01 -08:00
Julius Marminge 0e2d50a620 Require ahead commits before offering Create PR on untracked branches
- Change quick action to `Push` (not `Push & create PR`) when branch has no upstream and is not ahead
- Keep `Create PR` menu item disabled until the branch has commits ahead
- Add/adjust logic tests for both no-ahead and ahead scenarios
2026-03-01 20:06:01 -08:00
Julius Marminge f3b3c54859 Add coverage for no-upstream default-branch quick actions
- test push-only quick action on default branch without upstream
- verify push and create PR stay disabled when branch is behind
2026-03-01 20:06:01 -08:00
Julius Marminge 02eca40c3b Enable push/PR actions for branches without upstream
- Treat no-upstream branches as publishable: enable Push/Create PR and update quick actions
- Route Create PR menu action through commit+push+PR flow when appropriate
- Simplify Git action dialog to commit-only and add "Commit on new branch" option
2026-03-01 20:06:01 -08:00
Julius Marminge c6ee3aee9f Add default-branch safeguard with auto feature branch fallback
- Prompt before commit/push actions on the default branch
- Allow one-click create+checkout of an auto-named feature branch and continue
- Add logic/tests for date-based unique auto feature branch naming
2026-03-01 20:06:01 -08:00
Julius Marminge 586e0ecea9 Document lint and typecheck completion requirements
- add a Task Completion Requirements section to AGENTS.md
- require `bun lint` and `bun typecheck` before marking tasks done
2026-03-01 19:57:50 -08:00
Julius Marminge dcd18413a2 Update contracts description to effect/Schema in AGENTS.md
- Clarify that `packages/contracts` uses effect/Schema schemas instead of Zod
2026-03-01 19:45:11 -08:00
Julius Marminge 73f296b4cf type 2026-03-01 18:49:12 -08:00
Julius Marminge 1419bf3989 fix? 2026-03-01 18:41:36 -08:00
Julius Marminge dca85c402c prep npm 2026-03-01 18:18:47 -08:00
Julius Marminge 56a3ad0f8b kewl 2026-03-01 18:18:47 -08:00
Julius Marminge 36f484c25a verbose in ci 2026-03-01 18:18:47 -08:00
Julius Marminge 03c6685097 kewl 2026-03-01 18:18:47 -08:00
Julius Marminge 23afddfbf9 Add tagged desktop release pipeline and unified artifact builder
- add GitHub Actions release workflow for v*.*.* tags with preflight checks
- build and publish macOS, Linux, and Windows desktop artifacts in one release
- replace DMG-only script with cross-platform `dist:desktop:artifact` flow
- document release, signing setup, and new desktop dist commands
2026-03-01 18:18:47 -08:00
Julius Marminge e3a2dfb9d0 Fix diff panel padding and top spacing for virtualized files
- Use horizontal and bottom padding on the diff render surface
- Add top margin to the first diff file for consistent spacing
2026-03-01 10:31:13 -08:00
Julius Marminge 3dd004c323 Keep diff panel header sticky while scrolling
- Make the diffs header stick to the top of the panel
- Add header background and bottom border for readability
2026-03-01 10:31:13 -08:00
Julius Marminge 1af43dbf90 Handle remote checkout conflicts without duplicate local branch
- fall back to plain checkout (detached HEAD) when `--track` would clash with an existing local branch
- add GitCore coverage for the conflict fallback path
- simplify branch-name derivation in BranchToolbar to consistently strip the first remote segment
2026-02-28 21:56:22 -08:00
Julius Marminge 16fed12dcc Handle remote lookup failures in branch listing
- Fall back to empty remote branch and remote name data when git remote queries fail
- Log warnings instead of failing `listBranches`
- Add integration test covering remote lookup failure fallback
2026-02-28 21:56:22 -08:00
Julius Marminge 29825f2f8a Filter detached HEAD pseudo-refs from branch listings
- ignore branch lines starting with `(` when parsing `git branch` output
- add integration test to verify detached HEAD does not appear as a branch
2026-02-28 21:56:22 -08:00
Julius Marminge efcee4b863 Handle branch checkout and dedupe for slash-named remotes
- add `remoteName` to git branch contract metadata
- resolve remote refs using full remote names (including slashes)
- avoid fallback to wrong local checkout when remote ref is missing
- update branch toolbar logic/tests to map and dedupe remote branches correctly
2026-02-28 21:56:22 -08:00
Julius Marminge 26edcab8b4 Reorder sidebar thread status badges and title layout
- Move PR status indicator into the main thread info row
- Keep thread status badge and title grouped for consistent alignment
2026-02-28 21:56:22 -08:00
Julius Marminge c626892adf Hide duplicate remote branches when local branch exists
- Deduplicate branch list by removing remote refs that match an existing local branch
- Move remote-ref local-name derivation into shared BranchToolbar logic
- Add logic tests for remote-ref parsing and deduplication behavior
2026-02-28 21:56:22 -08:00
Julius Marminge 3c66cdf2fe Support remote branch listing and tracking checkout flow
- Include remote refs in branch listings, ordered after local branches
- Auto-track remote branches on checkout when no local branch exists
- Update branch picker to label remote branches and store local branch name after checkout
2026-02-28 21:56:22 -08:00
Julius Marminge db31c36213 Open diff files in editor from diff header clicks
- Add click handling on diff file headers (`data-title`) to open files via native `openInEditor`
- Resolve file paths against active thread/project cwd before launching editor
- Add header hover affordance and tighten diff panel spacing
2026-02-28 21:30:05 -08:00
Julius Marminge cafe3352f1 Remove redundant PR status title attribute
- Drop `title` from the PR status button in `Sidebar` to avoid duplicate tooltip text
2026-02-28 16:24:03 -08:00
Julius Marminge 7a39ce34fa Avoid popup-open false errors on mobile browsers
- Stop throwing when `window.open` returns `null` in `wsNativeApi`
- Keep opening external links in a new tab and rely on browser popup policy
2026-02-28 16:24:03 -08:00
Julius Marmingeandcodex 483702df77 Add clickable PR status tooltip in sidebar threads
- Show PR number/title in a tooltip on each thread PR icon
- Open PR links externally from the sidebar and show error toasts on failure
- Improve thread row keyboard handling after switching to a non-button render

Co-authored-by: codex <[email protected]>
2026-02-28 16:24:03 -08:00
Julius Marminge 206eb6a785 even better 2026-02-28 15:17:03 -08:00
Julius Marminge de9ec2bc73 kewl 2026-02-28 15:17:03 -08:00
Julius Marminge 1a66e517cd simp 2026-02-28 15:17:03 -08:00
Julius Marminge 33e6f35ce9 simp 2026-02-28 15:17:03 -08:00
Julius Marminge e8896fe02d Add copy button to chat markdown code blocks
- Wrap rendered markdown code blocks with a copy action button
- Show copy/check icons with transient "Copied" state and cleanup
- Style button to appear on hover/focus without shifting code layout
2026-02-28 15:17:03 -08:00
Julius Marminge e89b053269 Fix code highlight cache behavior for streaming markdown
- Reuse in-flight highlight requests and allow later non-streaming renders to cache results
- Stabilize code block highlight state updates to avoid stale or redundant rerenders
- Export and reuse `fnv1a32` from `diffRendering` for shared cache key hashing
2026-02-28 15:17:03 -08:00
Julius Marminge d052d481d8 Move diff theme overrides into DiffPanel unsafeCSS
- Inject diff palette overrides via `unsafeCSS` in `DiffPanel`
- Add `diff-panel-viewport` background and keep file container border/background styling in `index.css`
- Switch panel root from `bg-card` to `bg-background` for consistent surface tone
2026-02-28 15:17:03 -08:00
Julius Marminge fcbb494af7 Align diff panel surfaces with app theme colors
- add diff-specific wrapper classes in `DiffPanel` for targeted theming
- override diff renderer color variables to match card/background palette
- soften chat markdown Shiki code-block background for consistency
2026-02-28 15:17:03 -08:00
Julius Marminge 2980a853e5 Use shared Shiki highlighting for chat markdown code blocks
- Replace `rehype-highlight`/`highlight.js` with `@pierre/diffs` highlighter in `ChatMarkdown`
- Add LRU caching and in-flight dedupe for highlighted code, with streaming-aware behavior
- Extract shared diff theme resolution utility and add unit tests for new LRU cache
2026-02-28 15:17:03 -08:00
Theo Browne 56de1465fa feat: custom models (#121)
* custom models

* better fake version
2026-02-28 14:42:10 -08:00
Julius Marminge b500106fde Merge pull request #122 from pingdotgg/codething/10276f55 2026-02-28 11:33:43 -08:00
Julius Marminge 7f2a95fe14 Prefer open PR when resolving git status PR
- Update GitManager PR selection to return the latest open PR before merged ones
- Add regression test covering open-vs-merged ordering by updatedAt
2026-02-28 11:10:18 -08:00
Julius Marminge 4b3825e500 Merge remote-tracking branch 'origin/main' into codething/10276f55 2026-02-27 21:33:39 -08:00
Julius Marminge d48b42c017 fix type 2026-02-27 21:32:15 -08:00
Julius Marminge fb45896588 simplify layers 2026-02-27 21:30:46 -08:00
Julius Marminge b52518f85f Flatten attachment paths with message-prefixed filenames
- Write projected attachments under the thread directory using `messageSegment-fileName`
- Avoid nested per-message folders while preserving unique, deterministic file paths
- Update projection pipeline tests to match new attachment URLs and on-disk paths
2026-02-27 21:30:46 -08:00
Julius Marminge 3e99019af8 Serve attachments using URL-encoded relative paths
- Read attachment route paths without URI decoding before normalization
- Align test fixture paths with encoded thread/message/file names
2026-02-27 21:30:46 -08:00
Julius Marminge 7d4b02689e Overwrite attachment bytes for repeated message attachment index
- Make projection attachment writes use last-write-wins per file path
- Always write attachment files so updated message attachments replace stale bytes
- Add regression test covering same message/attachment index update behavior
2026-02-27 21:30:46 -08:00
Julius Marminge 9962f57ad0 Preserve empty attachment updates in projection pipeline
- Treat `attachments: []` as an explicit update instead of dropping the field
- Add regression test covering attachment clearing for an existing thread message
2026-02-27 21:30:46 -08:00
Julius Marminge 8b538e2802 dedupe 2026-02-27 21:30:46 -08:00
Julius Marminge a6c57e169a nit 2026-02-27 21:30:46 -08:00
Julius Marminge 6f92f0a668 kewl 2026-02-27 21:30:46 -08:00
Julius Marminge 35817601ff fixxx 2026-02-27 21:30:46 -08:00
Julius Marminge 2b154db938 Add gallery navigation to expanded chat image previews
- Open preview from the full image set instead of a single image
- Add previous/next controls with ArrowLeft/ArrowRight keyboard support
- Keep Escape-to-close behavior and show current image position
2026-02-27 21:30:46 -08:00
Julius Marminge b9ff7aa5cd Make attachment writes transactional and decode attachment URLs
- Stage attachment file writes until projector transactions commit, then apply write/prune/delete side effects
- Remove orphaned attachment files on thread revert and delete thread attachment dirs on thread deletion
- Serve URL-encoded attachment paths in `wsServer` and stream file responses
- Add regression tests for rollback safety, revert/delete cleanup, and encoded attachment URLs
2026-02-27 21:30:46 -08:00
Julius Marminge b5188e8cea Harden attachment materialization and static file path handling
- Materialize only valid image data URLs and restrict inferred file extensions to a safe whitelist
- Preserve existing message attachments on upsert unless explicitly replaced or cleared
- Serve static `/` via `index.html` and block traversal attempts in static file requests
2026-02-27 21:30:46 -08:00
Julius Marminge 992db16586 Persist and serve projected message image attachments
- Store message attachments in `projection_thread_messages.attachments_json`
- Materialize base64 image attachments to `stateDir/attachments` during projection
- Serve `/attachments/*` from the server and resolve preview URLs from WebSocket origin
- Add migration and tests for projection materialization and attachment serving
2026-02-27 21:30:46 -08:00
Julius Marminge 2aad749e24 Reuse persisted cwd when recovering stale provider sessions
- Read and validate `cwd` from persisted runtime payload when restarting sessions
- Apply persisted `cwd` during stale-session recovery paths, including `sendTurn`
- Add tests to verify resumed sessions preserve the original working directory
2026-02-27 20:58:21 -08:00
Julius Marminge aa267ebb05 clamp 2026-02-27 19:27:05 -08:00
Cursor AgentandJulius Marminge 1a33f25970 web: keep active turn out of virtualization
Co-authored-by: Julius Marminge <[email protected]>
2026-02-27 19:27:05 -08:00
Julius Marmingeandcodex e8dfc42f44 Merge origin/main into codething/4efb5794
Co-authored-by: codex <[email protected]>
2026-02-27 18:21:47 -08:00
Julius Marminge 21c823ecdc Guard delayed terminal exit callback
- Skip `onSessionExited` if exit handling was reset before timeout runs
- Prevent stale async exit callbacks from firing in terminal drawer
2026-02-27 18:08:18 -08:00
Julius Marminge 80498f1709 Handle terminal exit writes and auto-close exited terminal view
- Ignore late write calls after a terminal session has already exited
- Add regression test for trailing writes after exit
- Close terminal drawer session once an exit event is handled
2026-02-27 18:08:18 -08:00
Julius Marminge e6c5a4a4bb Handle favicon links when href precedes rel
- Update favicon regex parsing to support rel/href in either order
- Add route tests for HTML link tags and object-style metadata with href-first ordering
2026-02-27 15:21:31 -08:00
Julius Marminge 732b3abf99 match assets/{icon,logo} as well 2026-02-27 15:21:31 -08:00
Julius Marminge ffbf541ff8 Extract project favicon route and tighten turn-settled logic
- move `/api/project-favicon` handling into a dedicated server route with coverage for root and source-linked icons
- wire `wsServer` to use the new route helper
- treat any running session as unsettled in `isLatestTurnSettled` to prevent stale latest-turn banners, with test coverage
2026-02-27 15:21:31 -08:00
Julius Marminge 709f961e1c Gate latest-turn completion UI on settled turn state
- Add `isLatestTurnSettled` to avoid treating an active running turn as complete
- Use the guard in `ChatView` for visited timestamps and completion summary/divider rendering
- Add unit tests covering running, ready, and incomplete-timestamp cases
2026-02-27 15:21:31 -08:00
Theo Browne 1653383573 Remove my junk paths 2026-02-27 15:21:31 -08:00
Theo Browne c7ae6b9471 Favicons + custom port during dev 2026-02-27 15:21:31 -08:00
Julius Marminge bbcf9ba9db Show pending approvals in sidebar thread status
- derive pending approvals from thread activities and label status as "Pending Approval"
- remove `isolate` class from chat `SidebarInset` containers
2026-02-27 14:49:27 -08:00
Julius Marminge 3f81f9dcb4 Replace thread latestTurnId with structured latestTurn metadata
- add `OrchestrationLatestTurn` schema and store full turn state/timestamps/message linkage
- update server projector/snapshot queries to populate `latestTurn` from session + projection_turns
- migrate web store/components to consume `latestTurn` and adjust related tests
2026-02-27 14:10:34 -08:00
Julius Marminge b073fea5fb Handle provider turn IDs correctly in runtime ingestion
- Use `ProviderTurnId` in `CheckpointReactor` tests instead of `TurnId`
- Guard `event.turnId` access in provider runtime ingestion when the field is absent
2026-02-27 14:10:34 -08:00
Julius Marminge 834236931e Inline provider thread and turn ID schemas in runtime events
- Remove redundant runtime schema aliases for thread and turn IDs
- Use `ProviderThreadId` and `ProviderTurnId` directly across runtime event contracts
2026-02-27 14:10:34 -08:00
Julius Marminge 872b907372 Guard provider lifecycle updates to primary thread and active turn
- Ignore auxiliary/non-active turn completions for session lifecycle and checkpoints
- Restrict runtime thread/turn IDs to provider IDs in contracts
- Add regression tests and ADR for lifecycle ownership rules
2026-02-27 14:10:34 -08:00
Theo Browne 0b8e098c10 copy on hover, better button treatments (#110) 2026-02-27 14:06:09 -08:00
blacksmith-sh[bot] 7c6a0f869d Migrate workflows to Blacksmith (#111)
Co-authored-by: blacksmith-sh[bot] <157653362+blacksmith-sh[bot]@users.noreply.github.com>
2026-02-27 14:05:22 -08:00
Julius Marminge 3a43047102 Sync diff renderer theme with app theme changes
- Pass explicit Pierre light/dark theme into diff render options
- Re-key file diffs on resolved theme so views rerender on theme switch
- Stabilize `useTheme` snapshots to propagate system theme updates reliably
2026-02-27 11:09:21 -08:00
Julius Marminge 041acf158a fix nullability 2026-02-26 21:36:44 -08:00
Julius Marminge f9752d7c08 migr 2026-02-26 21:26:35 -08:00
Julius Marminge 766592b83b tone down defautls 2026-02-26 21:26:35 -08:00
Julius Marminge 1c3c412ce4 Disable two Effect lint rules in server tsconfig
- Turn off `preferSchemaOverJson`
- Turn off `globalErrorInEffectFailure`
2026-02-26 21:26:35 -08:00
Julius Marminge f9e6d1290d Handle session restart failures without dropping active thread session
- Reorder restart flow to bind the new provider session before stopping the old one
- Log (and swallow) stop-session failures for superseded sessions
- Add regression test ensuring failed restart does not stop the active session
2026-02-26 21:26:35 -08:00
Julius Marminge 8ef653fcc0 Persist required approval policy and sandbox mode for sessions
- Make `approvalPolicy` and `sandboxMode` required in orchestration contracts and turn-start flow
- Add defaults in provider reactors/ingestion to guarantee values are always set
- Store and hydrate both fields in projection persistence, snapshots, and related tests
2026-02-26 21:26:35 -08:00
Julius Marminge fb8d66b8d3 rm 2026-02-26 21:26:35 -08:00
Julius MarmingeandClaude Opus 4.5 e70b34de62 Fix type error with optional approvalPolicy and sandboxMode
Use conditional spreading for these properties to handle undefined
values correctly with exactOptionalPropertyTypes.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-02-26 21:26:35 -08:00
Julius Marminge b1584fab8f Add .t3 keybindings and initial local runtime state files
- add default `.t3/keybindings.json` for terminal/chat/editor/diff shortcuts
- include initial provider log files and SQLite state artifacts under `apps/server/.t3`
2026-02-26 21:26:35 -08:00
Julius Marminge 718084065e Restart provider sessions when runtime mode changes
- Persist `approvalPolicy` and `sandboxMode` on orchestration sessions
- Reuse existing sessions when runtime mode is unchanged
- Stop and recreate provider sessions when runtime mode settings change
- Add reactor tests for reuse vs restart behavior
2026-02-26 21:26:35 -08:00
Julius Marminge 57dd091e05 Propagate runtime approval and sandbox settings to turn startup
- Add `approvalPolicy` and `sandboxMode` to turn-start command and requested payload contracts
- Pass runtime mode-derived values from `ChatView` when dispatching `thread.turn.start`
- Thread provider options through decider/reactor into session startup, with tests updated
2026-02-26 21:26:35 -08:00
Julius Marminge a1f208f1e6 Provide NodeServices layer in wsServer bootstrap test
- inject `NodeServices.layer` into sqlite persistence setup in `wsServer.test.ts`
- fixes test runtime dependencies for existing-state bootstrap path
2026-02-26 21:05:53 -08:00
Julius Marminge 581aa7279f Require bootstrap IDs for root thread auto-navigation
- Remove snapshot fallback lookup for missing bootstrap project/thread IDs
- Only expand project and navigate when server payload includes both IDs
2026-02-26 21:05:53 -08:00
Julius Marminge 0b29924648 Recover bootstrap thread from snapshot when IDs are missing
- Fetch orchestration snapshot when bootstrap project/thread IDs are absent
- Resolve project by current workspace and choose latest non-deleted thread
- Continue auto-navigation and expansion using resolved fallback IDs
2026-02-26 21:05:53 -08:00
Julius Marminge 49472da669 Return existing bootstrap thread IDs in welcome and guard root navigatio
- Server welcome now includes bootstrap project/thread IDs when cwd project/thread already exist
- Added regression test for reconnecting with persisted bootstrap state
- Root route ignores post-dispose welcome handling and marks thread as handled after navigate
2026-02-26 21:05:53 -08:00
Julius Marminge 69a2eac2ff Use pathname ref in EventRouter bootstrap navigation
- Track latest `pathname` in a ref for bootstrap event handling
- Prevent effect resubscriptions by removing `pathname` from deps
- Keep auto-navigation gated to root route using current path
2026-02-26 21:05:53 -08:00
Julius Marminge 5fd632c357 Bootstrap default thread and route to it on server welcome
- Create or reuse cwd project, create initial thread, and include bootstrap IDs in `server.welcome`
- Update web event routing to expand the project and auto-navigate from `/` to the bootstrapped thread
- Extend WebSocket welcome contract and add server/web tests for bootstrap payload handling
2026-02-26 21:05:53 -08:00
Julius Marminge bb2164c945 Prevent duplicate sends and sync worktree branch state
- Guard `onSend` with an in-flight ref to block double submits
- Set send phase before worktree prep and always clear in-flight state in `finally`
- Sync thread branch/worktree path immediately and await setup script execution
2026-02-26 20:51:29 -08:00
Julius Marminge 8c91aa5570 Prevent duplicate sends while composer request is in flight
- Add `sendInFlightRef` guard in `ChatView` send handler
- Set sending state before async work and always clear it in `finally`
- Wrap early send flow in one `try/finally` to avoid double-submit races
2026-02-26 20:51:29 -08:00
Julius Marminge 6db8257b1e Stop forcing setup script to open a new terminal
- Remove `preferNewTerminal` when invoking `runProjectScript` in `ChatView`
- Lets setup scripts use default terminal behavior for worktree runs
2026-02-26 20:51:29 -08:00
Julius Marminge f6e7166e79 Capture threadId before async send flow
- Store `activeThread.id` once at send start and reuse it
- Prevents updates/errors from targeting the wrong thread during async worktree/send steps
2026-02-26 20:51:29 -08:00
Julius Marmingeandcodex 2da8290040 Require base branch before first send in worktree mode
- show an explicit error when New worktree mode has no base branch selected
- sync thread branch/worktree path immediately after creation
- run setup script in the new worktree terminal before continuing

Co-authored-by: codex <[email protected]>
2026-02-26 20:51:29 -08:00
Julius Marmingeandcodex 37e17e9207 Merge origin/main into codething/4efb5794
Co-authored-by: codex <[email protected]>
2026-02-19 16:12:13 -08:00
Julius Marmingeandcodex fe86836b43 Merge origin/main and resolve PR status/sidebar conflicts
Co-authored-by: codex <[email protected]>
2026-02-16 01:01:13 -08:00
Julius Marminge 973e62373e Unify git status PR info into a single pr field
- Replace `openPr`/`mergedPr` with `pr` in server and contracts
- Add PR `state` (`open`/`closed`/`merged`) to git status schema
- Resolve latest branch PR via `gh pr list --state all` sorted by `updatedAt`
2026-02-15 19:46:24 -08:00
Julius Marminge dcdb9ac923 Skip local-branch PR checks and dedupe sidebar git status
- server: only query open PRs when the current branch has an upstream; still fall back to merged PR lookup
- tests: cover status behavior for branches without upstream tracking
- web: fetch git status once per cwd, validate query data with schema parsing, and map merged PR badges by thread branch match
2026-02-15 14:28:03 -08:00
Julius Marminge 46347e2bd2 Show merged PR status when no open PR exists
- extend `GitStatusResult` with nullable `mergedPr` metadata
- in server git status, query merged PR only when no open PR is found
- in sidebar, display a `Merged` status pill for threads on branches with merged PRs
- update server/web/contracts tests for the new status shape
2026-02-15 14:04:48 -08:00
172 changed files with 22038 additions and 4344 deletions

No files matched your search

+1 -1
View File
@@ -9,7 +9,7 @@ on:
jobs:
quality:
name: Lint, Typecheck, Test, Build
runs-on: ubuntu-latest
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Checkout
uses: actions/checkout@v4
+330
View File
@@ -0,0 +1,330 @@
name: Release Desktop
on:
push:
tags:
- "v*.*.*"
workflow_dispatch:
inputs:
version:
description: "Release version (for example 1.2.3 or v1.2.3)"
required: true
type: string
permissions:
contents: write
id-token: write
jobs:
preflight:
name: Preflight
runs-on: ubuntu-24.04
outputs:
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
ref: ${{ steps.release_ref.outputs.value }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- id: release_meta
name: Resolve release version
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${{ github.event.inputs.version }}"
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Update version strings
if: github.event_name == 'workflow_dispatch'
env:
RELEASE_VERSION: ${{ steps.release_meta.outputs.version }}
run: |
node --input-type=module -e '
import { readFileSync, writeFileSync } from "node:fs";
const files = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
];
for (const file of files) {
const packageJson = JSON.parse(readFileSync(file, "utf8"));
packageJson.version = process.env.RELEASE_VERSION;
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
}
'
- name: Refresh lockfile
if: github.event_name == 'workflow_dispatch'
run: bun install
- 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: Commit and push release version + tag
if: github.event_name == 'workflow_dispatch'
shell: bash
env:
RELEASE_TAG: ${{ steps.release_meta.outputs.tag }}
run: |
if git ls-remote --exit-code --tags origin "$RELEASE_TAG" >/dev/null 2>&1; then
echo "Tag $RELEASE_TAG already exists on origin." >&2
exit 1
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
if ! git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG" -m "Co-authored-by: codex <[email protected]>"
fi
git tag "$RELEASE_TAG"
git push origin "HEAD:${GITHUB_REF_NAME}"
git push origin "refs/tags/$RELEASE_TAG"
- id: release_ref
name: Resolve source ref
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
echo "value=refs/tags/${{ steps.release_meta.outputs.tag }}" >> "$GITHUB_OUTPUT"
else
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
fi
build:
name: Build ${{ matrix.label }}
needs: preflight
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
include:
- label: macOS arm64
runner: macos-14
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: macos-15-intel
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: ubuntu-24.04
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: windows-2022
platform: win
target: nsis
arch: x64
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Build desktop artifact
shell: bash
env:
CSC_LINK: ${{ secrets.CSC_LINK }}
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
run: |
args=(
--platform "${{ matrix.platform }}"
--target "${{ matrix.target }}"
--arch "${{ matrix.arch }}"
--build-version "${{ needs.preflight.outputs.version }}"
--verbose
)
has_all() {
for value in "$@"; do
if [[ -z "$value" ]]; then
return 1
fi
done
return 0
}
if [[ "${{ matrix.platform }}" == "mac" ]]; then
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
printf '%s' "$APPLE_API_KEY" > "$key_path"
export APPLE_API_KEY="$key_path"
echo "macOS signing enabled."
args+=(--signed)
else
echo "macOS signing disabled (missing one or more Apple signing secrets)."
fi
elif [[ "${{ matrix.platform }}" == "win" ]]; then
if has_all \
"$AZURE_TENANT_ID" \
"$AZURE_CLIENT_ID" \
"$AZURE_CLIENT_SECRET" \
"$AZURE_TRUSTED_SIGNING_ENDPOINT" \
"$AZURE_TRUSTED_SIGNING_ACCOUNT_NAME" \
"$AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME" \
"$AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"; then
echo "Windows signing enabled (Azure Trusted Signing)."
args+=(--signed)
else
echo "Windows signing disabled (missing one or more Azure Trusted Signing secrets)."
fi
else
echo "Signing disabled for ${{ matrix.platform }}."
fi
bun run dist:desktop:artifact -- "${args[@]}"
- name: Collect release assets
shell: bash
run: |
set -euo pipefail
mkdir -p release-publish
shopt -s nullglob
for pattern in \
"release/*.dmg" \
"release/*.zip" \
"release/*.AppImage" \
"release/*.exe" \
"release/*.blockmap" \
"release/latest*.yml"; do
for file in $pattern; do
cp "$file" release-publish/
done
done
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
if [[ -f release-publish/latest-mac.yml ]]; then
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
fi
fi
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release-publish/*
if-no-files-found: error
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose
release:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
steps:
- name: Download all desktop artifacts
uses: actions/download-artifact@v4
with:
pattern: desktop-*
merge-multiple: true
path: release-assets
- name: Publish release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
name: T3 Code v${{ needs.preflight.outputs.version }}
generate_release_notes: true
files: |
release-assets/*.dmg
release-assets/*.zip
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/latest*.yml
fail_on_unmatched_files: true
+64
View File
@@ -0,0 +1,64 @@
import path from "path";
import fs from "fs";
const FAVICON_CANDIDATES = [
"favicon.svg", "favicon.ico", "favicon.png",
"public/favicon.svg", "public/favicon.ico", "public/favicon.png",
"app/favicon.ico", "app/favicon.png", "app/icon.svg", "app/icon.png", "app/icon.ico",
"src/favicon.ico", "src/favicon.svg", "src/app/favicon.ico", "src/app/icon.svg", "src/app/icon.png",
];
const ICON_SOURCE_FILES = [
"index.html", "public/index.html",
"app/routes/__root.tsx", "src/routes/__root.tsx",
"app/root.tsx", "src/root.tsx", "src/index.html",
];
const LINK_ICON_HTML_RE = /<link[^>]*rel=["'](?:icon|shortcut icon)["'][^>]*href=["']([^"'?]+)/i;
const LINK_ICON_OBJ_RE = /rel:\s*["'](?:icon|shortcut icon)["'][^}]*href:\s*["']([^"'?]+)/i;
function test(projectCwd) {
console.log("--- Testing:", projectCwd, "---");
for (const c of FAVICON_CANDIDATES) {
const full = path.join(projectCwd, c);
if (fs.existsSync(full) && fs.statSync(full).isFile()) {
console.log(" Phase 1 FOUND:", c);
return;
}
}
console.log(" Phase 1: no match");
for (const sf of ICON_SOURCE_FILES) {
const full = path.join(projectCwd, sf);
if (!fs.existsSync(full)) continue;
const content = fs.readFileSync(full, "utf8");
const href = content.match(LINK_ICON_HTML_RE)?.[1] || content.match(LINK_ICON_OBJ_RE)?.[1];
if (href) {
const clean = href.replace(/^\//, "");
const tryPaths = [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
for (const p of tryPaths) {
if (fs.existsSync(p)) {
console.log(" Phase 2 FOUND:", sf, "->", href, "->", p);
return;
}
}
console.log(" Phase 2 href found but file missing:", href);
}
}
console.log(" Phase 2: no match");
}
function getTestPaths() {
const cliPaths = process.argv.slice(2).map((p) => p.trim()).filter(Boolean);
if (cliPaths.length > 0) return cliPaths;
const envPaths = process.env.TEST_PATHS?.split(path.delimiter).map((p) => p.trim()).filter(Boolean);
if (envPaths?.length) return envPaths;
return [process.cwd()];
}
for (const p of getTestPaths()) {
test(path.resolve(p));
}
+10 -1
View File
@@ -1,5 +1,9 @@
# CLAUDE.md
## Task Completion Requirements
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
## Project Snapshot
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
@@ -14,11 +18,16 @@ This repository is a VERY EARLY WIP. Proposing sweeping changes that improve lon
If a tradeoff is required, choose correctness and robustness over short-term convenience.
## Maintainability
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
## Package Roles
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
## Codex App Server (Important)
+13 -1
View File
@@ -75,8 +75,11 @@ npx t3
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
### Desktop `.dmg` packaging notes
@@ -86,12 +89,18 @@ npx t3
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
### Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5173`
- Default ports: server `3773`, web `5733`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
@@ -122,3 +131,6 @@ 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`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
+9 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0",
"version": "0.0.0-alpha.18",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
@@ -14,15 +14,17 @@
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"electron": "40.6.0"
"effect": "catalog:",
"electron": "40.6.0",
"electron-updater": "^6.6.2"
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@types/node": "^22.10.2",
"electronmon": "^2.0.2",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
"@t3tools/shared": "workspace:*",
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
"wait-on": "^8.0.2"
},
"productName": "T3 Code (Alpha)"
+165 -28
View File
@@ -1,43 +1,171 @@
import { spawnSync } from "node:child_process";
import electronmon from "electronmon";
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
const devServerUrl = `http://localhost:${port}`;
const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200;
await waitOn({
resources: [
`tcp:${port}`,
"file:dist-electron/main.js",
"file:dist-electron/preload.js",
"file:../server/dist/index.mjs",
],
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
});
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const monitor = await electronmon({
cwd: desktopDir,
args: ["dist-electron/main.js"],
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
electronPath: resolveElectronPath(),
});
let shuttingDown = false;
let restartTimer = null;
let currentApp = null;
let restartQueue = Promise.resolve();
const expectedExits = new WeakSet();
const watchers = [];
function killChildTreeByPid(pid, signal) {
if (process.platform === "win32" || typeof pid !== "number") {
return;
}
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
}
function cleanupStaleDevApps() {
if (process.platform === "win32") {
return;
}
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
}
function startApp() {
if (shuttingDown || currentApp !== null) {
return;
}
const app = spawn(
resolveElectronPath(),
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
{
cwd: desktopDir,
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
stdio: "inherit",
},
);
currentApp = app;
app.once("error", () => {
if (currentApp === app) {
currentApp = null;
}
if (!shuttingDown) {
scheduleRestart();
}
});
app.once("exit", () => {
if (currentApp === app) {
currentApp = null;
}
if (!shuttingDown && !expectedExits.has(app)) {
scheduleRestart();
}
});
}
async function stopApp() {
const app = currentApp;
if (!app) {
return;
}
currentApp = null;
expectedExits.add(app);
await new Promise((resolve) => {
let settled = false;
const finish = () => {
if (settled) {
return;
}
settled = true;
resolve();
};
app.once("exit", finish);
app.kill("SIGTERM");
killChildTreeByPid(app.pid, "TERM");
setTimeout(() => {
if (settled) {
return;
}
app.kill("SIGKILL");
killChildTreeByPid(app.pid, "KILL");
finish();
}, forcedShutdownTimeoutMs).unref();
});
}
function scheduleRestart() {
if (shuttingDown) {
return;
}
if (restartTimer) {
clearTimeout(restartTimer);
}
restartTimer = setTimeout(() => {
restartTimer = null;
restartQueue = restartQueue
.catch(() => undefined)
.then(async () => {
await stopApp();
if (!shuttingDown) {
startApp();
}
});
}, restartDebounceMs);
}
function startWatchers() {
for (const { directory, files } of watchedDirectories) {
const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
return;
}
scheduleRestart();
});
watchers.push(watcher);
}
}
function killChildTree(signal) {
if (process.platform === "win32") {
return;
}
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
}
@@ -45,20 +173,29 @@ async function shutdown(exitCode) {
if (shuttingDown) return;
shuttingDown = true;
try {
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
} catch {
// Best effort only; fallback process kill below handles stubborn children.
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = null;
}
for (const watcher of watchers) {
watcher.close();
}
await stopApp();
killChildTree("TERM");
setTimeout(() => {
killChildTree("KILL");
}, 1_200).unref();
await new Promise((resolve) => {
setTimeout(resolve, childTreeGracePeriodMs);
});
killChildTree("KILL");
process.exit(exitCode);
}
startWatchers();
cleanupStaleDevApps();
startApp();
process.once("SIGINT", () => {
void shutdown(130);
});
+2 -2
View File
@@ -1,11 +1,11 @@
import { execFileSync } from "node:child_process";
import * as ChildProcess 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"], {
const result = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], {
encoding: "utf8",
timeout: 5000,
});
+749 -79
View File
File diff suppressed because it is too large. Load diff
+19 -1
View File
@@ -6,13 +6,17 @@ const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
showContextMenu: (items) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
@@ -25,4 +29,18 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
onUpdateState: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
if (typeof state !== "object" || state === null) return;
listener(state as Parameters<typeof listener>[0]);
};
ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
};
},
} satisfies DesktopBridge);
+74
View File
@@ -0,0 +1,74 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { afterEach, describe, expect, it } from "vitest";
const tempRoots: string[] = [];
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-rotating-log-"));
tempRoots.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempRoots.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("RotatingFileSink", () => {
it("rotates when writes exceed max bytes", () => {
const dir = makeTempDir();
const logPath = path.join(dir, "desktop-main.log");
const sink = new RotatingFileSink({
filePath: logPath,
maxBytes: 10,
maxFiles: 3,
});
sink.write("12345");
sink.write("67890");
sink.write("abc");
expect(fs.readFileSync(path.join(dir, "desktop-main.log"), "utf8")).toBe("abc");
expect(fs.readFileSync(path.join(dir, "desktop-main.log.1"), "utf8")).toBe("1234567890");
});
it("retains only maxFiles backups", () => {
const dir = makeTempDir();
const logPath = path.join(dir, "server-child.log");
const sink = new RotatingFileSink({
filePath: logPath,
maxBytes: 4,
maxFiles: 2,
});
sink.write("aaaa");
sink.write("bbbb");
sink.write("cccc");
sink.write("dddd");
expect(fs.existsSync(path.join(dir, "server-child.log.1"))).toBe(true);
expect(fs.existsSync(path.join(dir, "server-child.log.2"))).toBe(true);
expect(fs.existsSync(path.join(dir, "server-child.log.3"))).toBe(false);
});
it("prunes stale backups above maxFiles on startup", () => {
const dir = makeTempDir();
const logPath = path.join(dir, "desktop-main.log");
fs.writeFileSync(path.join(dir, "desktop-main.log.1"), "first");
fs.writeFileSync(path.join(dir, "desktop-main.log.4"), "stale");
const sink = new RotatingFileSink({
filePath: logPath,
maxBytes: 16,
maxFiles: 2,
});
sink.write("hello");
expect(fs.existsSync(path.join(dir, "desktop-main.log.4"))).toBe(false);
});
});
+130
View File
@@ -0,0 +1,130 @@
import { describe, expect, it } from "vitest";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
reduceDesktopUpdateStateOnCheckStart,
reduceDesktopUpdateStateOnDownloadComplete,
reduceDesktopUpdateStateOnDownloadFailure,
reduceDesktopUpdateStateOnDownloadProgress,
reduceDesktopUpdateStateOnDownloadStart,
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
describe("updateMachine", () => {
it("clears transient errors when a check starts", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "error",
message: "network",
errorContext: "check",
canRetry: true,
},
"2026-03-04T00:00:00.000Z",
);
expect(state.status).toBe("checking");
expect(state.message).toBeNull();
expect(state.errorContext).toBeNull();
expect(state.canRetry).toBe(false);
});
it("records a check failure without exposing an action", () => {
const state = reduceDesktopUpdateStateOnCheckFailure(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "checking",
},
"network unavailable",
"2026-03-04T00:00:00.000Z",
);
expect(state.status).toBe("error");
expect(state.errorContext).toBe("check");
expect(state.canRetry).toBe(true);
});
it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
downloadPercent: 43,
},
"checksum mismatch",
);
expect(state.status).toBe("available");
expect(state.availableVersion).toBe("1.1.0");
expect(state.errorContext).toBe("download");
expect(state.canRetry).toBe(true);
});
it("transitions to downloaded and then preserves install retry state", () => {
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
},
"1.1.0",
);
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");
expect(downloaded.status).toBe("downloaded");
expect(downloaded.downloadedVersion).toBe("1.1.0");
expect(failedInstall.status).toBe("downloaded");
expect(failedInstall.errorContext).toBe("install");
expect(failedInstall.canRetry).toBe(true);
});
it("clears stale download state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "error",
availableVersion: "1.1.0",
downloadedVersion: "1.1.0",
message: "old failure",
errorContext: "download",
canRetry: true,
},
"2026-03-04T00:00:00.000Z",
);
expect(state.status).toBe("up-to-date");
expect(state.availableVersion).toBeNull();
expect(state.downloadedVersion).toBeNull();
expect(state.message).toBeNull();
expect(state.errorContext).toBeNull();
});
it("tracks available, download start, and progress cleanly", () => {
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0"),
enabled: true,
status: "checking",
},
"1.1.0",
"2026-03-04T00:00:00.000Z",
);
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
expect(available.status).toBe("available");
expect(downloading.status).toBe("downloading");
expect(downloading.downloadPercent).toBe(0);
expect(progress.downloadPercent).toBe(55.5);
expect(progress.errorContext).toBeNull();
});
});
+155
View File
@@ -0,0 +1,155 @@
import type { DesktopUpdateState } from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
export function createInitialDesktopUpdateState(currentVersion: string): DesktopUpdateState {
return {
enabled: false,
status: "disabled",
currentVersion,
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
checkedAt: null,
message: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnCheckStart(
state: DesktopUpdateState,
checkedAt: string,
): DesktopUpdateState {
return {
...state,
status: "checking",
checkedAt,
message: null,
downloadPercent: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnCheckFailure(
state: DesktopUpdateState,
message: string,
checkedAt: string,
): DesktopUpdateState {
return {
...state,
status: "error",
message,
checkedAt,
downloadPercent: null,
errorContext: "check",
canRetry: true,
};
}
export function reduceDesktopUpdateStateOnUpdateAvailable(
state: DesktopUpdateState,
version: string,
checkedAt: string,
): DesktopUpdateState {
return {
...state,
status: "available",
availableVersion: version,
downloadedVersion: null,
downloadPercent: null,
checkedAt,
message: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnNoUpdate(
state: DesktopUpdateState,
checkedAt: string,
): DesktopUpdateState {
return {
...state,
status: "up-to-date",
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
checkedAt,
message: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnDownloadStart(
state: DesktopUpdateState,
): DesktopUpdateState {
return {
...state,
status: "downloading",
downloadPercent: 0,
message: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnDownloadFailure(
state: DesktopUpdateState,
message: string,
): DesktopUpdateState {
return {
...state,
status: nextStatusAfterDownloadFailure(state),
message,
downloadPercent: null,
errorContext: "download",
canRetry: getCanRetryAfterDownloadFailure(state),
};
}
export function reduceDesktopUpdateStateOnDownloadProgress(
state: DesktopUpdateState,
percent: number,
): DesktopUpdateState {
return {
...state,
status: "downloading",
downloadPercent: percent,
message: null,
errorContext: null,
canRetry: false,
};
}
export function reduceDesktopUpdateStateOnDownloadComplete(
state: DesktopUpdateState,
version: string,
): DesktopUpdateState {
return {
...state,
status: "downloaded",
availableVersion: version,
downloadedVersion: version,
downloadPercent: 100,
message: null,
errorContext: null,
canRetry: true,
};
}
export function reduceDesktopUpdateStateOnInstallFailure(
state: DesktopUpdateState,
message: string,
): DesktopUpdateState {
return {
...state,
status: "downloaded",
message,
errorContext: "install",
canRetry: true,
};
}
+142
View File
@@ -0,0 +1,142 @@
import { describe, expect, it } from "vitest";
import type { DesktopUpdateState } from "@t3tools/contracts";
import {
getCanRetryAfterDownloadFailure,
getAutoUpdateDisabledReason,
nextStatusAfterDownloadFailure,
shouldBroadcastDownloadProgress,
} from "./updateState";
const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
currentVersion: "1.0.0",
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
checkedAt: null,
message: null,
errorContext: null,
canRetry: false,
};
describe("shouldBroadcastDownloadProgress", () => {
it("broadcasts the first downloading progress update", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: null },
1,
),
).toBe(true);
});
it("skips progress updates within the same 10% bucket", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: 11.2 },
18.7,
),
).toBe(false);
});
it("broadcasts progress updates when a new 10% bucket is reached", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: 19.9 },
20.1,
),
).toBe(true);
});
it("broadcasts progress updates when a retry resets the download percentage", () => {
expect(
shouldBroadcastDownloadProgress(
{ ...baseState, status: "downloading", downloadPercent: 50.4 },
0.2,
),
).toBe(true);
});
});
describe("getAutoUpdateDisabledReason", () => {
it("reports development builds as disabled", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: true,
isPackaged: false,
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
}),
).toContain("packaged production builds");
});
it("reports env-disabled auto updates", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "darwin",
appImage: undefined,
disabledByEnv: true,
}),
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
});
it("reports linux non-AppImage builds as disabled", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "linux",
appImage: undefined,
disabledByEnv: false,
}),
).toContain("AppImage");
});
});
describe("nextStatusAfterDownloadFailure", () => {
it("returns available when an update version is still known", () => {
expect(
nextStatusAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: "1.1.0",
}),
).toBe("available");
});
it("returns error when no update version can be retried", () => {
expect(
nextStatusAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: null,
}),
).toBe("error");
});
});
describe("getCanRetryAfterDownloadFailure", () => {
it("returns true when an available version is still present", () => {
expect(
getCanRetryAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: "1.1.0",
}),
).toBe(true);
});
it("returns false when no version is available to retry", () => {
expect(
getCanRetryAfterDownloadFailure({
...baseState,
status: "downloading",
availableVersion: null,
}),
).toBe(false);
});
});
+48
View File
@@ -0,0 +1,48 @@
import type { DesktopUpdateState } from "@t3tools/contracts";
export function shouldBroadcastDownloadProgress(
currentState: DesktopUpdateState,
nextPercent: number,
): boolean {
if (currentState.status !== "downloading") {
return true;
}
const currentPercent = currentState.downloadPercent;
if (currentPercent === null) {
return true;
}
const previousStep = Math.floor(currentPercent / 10);
const nextStep = Math.floor(nextPercent / 10);
return nextStep !== previousStep || nextPercent === 100;
}
export function nextStatusAfterDownloadFailure(
currentState: DesktopUpdateState,
): DesktopUpdateState["status"] {
return currentState.availableVersion ? "available" : "error";
}
export function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean {
return currentState.availableVersion !== null;
}
export function getAutoUpdateDisabledReason(args: {
isDevelopment: boolean;
isPackaged: boolean;
platform: NodeJS.Platform;
appImage?: string | undefined;
disabledByEnv: boolean;
}): string | null {
if (args.isDevelopment || !args.isPackaged) {
return "Automatic updates are only available in packaged production builds.";
}
if (args.disabledByEnv) {
return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
}
if (args.platform === "linux" && !args.appImage) {
return "Automatic updates on Linux require running the AppImage build.";
}
return null;
}
+1 -1
View File
@@ -12,7 +12,7 @@ export default defineConfig([
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: ["@t3tools/contracts"],
noExternal: (id) => id.startsWith("@t3tools/"),
},
{
...shared,
@@ -23,6 +23,8 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
@@ -54,6 +56,7 @@ import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
} from "./TestProviderAdapter.integration.ts";
import { ServerConfig } from "../src/config.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -215,21 +218,29 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
CheckpointStoreLive,
providerLayer,
);
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
);
const gitCoreLayer = Layer.succeed(GitCore, {
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
Effect.succeed({ branch: input.newBranch }),
} as unknown as GitCoreShape);
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: null }),
} as unknown as TextGenerationShape);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(textGenerationLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
@@ -241,6 +252,7 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
);
const layer = orchestrationReactorLayer.pipe(
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(NodeServices.layer),
);
@@ -136,6 +136,8 @@ const startTurn = (input: {
text: input.text,
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: nowIso(),
});
@@ -317,7 +319,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
const secondTurnThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurnId === "turn-2" &&
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 2),
);
@@ -651,7 +653,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurnId === "turn-2" &&
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.activities.some((activity) => activity.turnId === "turn-2"),
8000,
+13 -10
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.1.0",
"version": "0.0.0-alpha.18",
"bin": {
"t3": "./dist/index.mjs"
},
@@ -8,10 +8,9 @@
"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.ts",
"dev": "bun run src/index.ts",
"build": "node scripts/cli.ts build",
"start": "node dist/index.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
@@ -27,15 +26,19 @@
"ws": "^8.18.0"
},
"devDependencies": {
"@effect/language-service": "0.75.1",
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "^1.3.9",
"@types/node": "^22.10.2",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0"
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"engines": {
"node": "^22.13 || ^23.4 || >=24.10"
}
}
-19
View File
@@ -1,19 +0,0 @@
/**
* 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 * as fs from "node:fs";
import * as path from "node:path";
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
const target = path.resolve(import.meta.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");
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
class CliError extends Data.TaggedError("CliError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
);
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(command);
const exitCode = yield* child.exitCode;
if (exitCode !== 0) {
return yield* new CliError({
message: `Command exited with non-zero exit code (${exitCode})`,
});
}
});
// ---------------------------------------------------------------------------
// build subcommand
// ---------------------------------------------------------------------------
const buildCmd = Command.make(
"build",
{
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
},
(config) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
yield* Effect.log("[cli] Running tsdown...");
yield* runCommand(
ChildProcess.make({
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
})`bun tsdown`,
);
const webDist = path.join(repoRoot, "apps/web/dist");
const clientTarget = path.join(serverDir, "dist/client");
if (yield* fs.exists(webDist)) {
yield* fs.copy(webDist, clientTarget);
yield* Effect.log("[cli] Bundled web app into dist/client");
} else {
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
}
}),
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
// ---------------------------------------------------------------------------
// publish subcommand
// ---------------------------------------------------------------------------
const publishCmd = Command.make(
"publish",
{
tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
access: Flag.string("access").pipe(Flag.withDefault("public")),
appVersion: Flag.string("app-version").pipe(Flag.optional),
provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
},
(config) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
const packageJsonPath = path.join(serverDir, "package.json");
const backupPath = `${packageJsonPath}.bak`;
// Assert build assets exist
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new CliError({
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
});
}
}
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
Effect.gen(function* () {
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
// Build package.json for publish
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg = {
name: serverPackageJson.name,
type: serverPackageJson.type,
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
};
// Resolve catalog: entries in production dependencies
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* Effect.log("[cli] Resolved package.json for publish");
}),
// Use: npm publish
() =>
Effect.gen(function* () {
const args = ["publish", "--access", config.access, "--tag", config.tag];
if (config.provenance) args.push("--provenance");
if (config.dryRun) args.push("--dry-run");
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
yield* runCommand(
ChildProcess.make("npm", [...args], {
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
}),
);
}),
// Release: restore
() =>
Effect.gen(function* () {
yield* fs.rename(backupPath, packageJsonPath);
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
}),
);
}),
).pipe(Command.withDescription("Publish the server package to npm."));
// ---------------------------------------------------------------------------
// root command
// ---------------------------------------------------------------------------
const cli = Command.make("cli").pipe(
Command.withDescription("T3 server build & publish CLI."),
Command.withSubcommands([buildCmd, publishCmd]),
);
Command.run(cli, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
NodeRuntime.runMain,
);
+28
View File
@@ -0,0 +1,28 @@
import path from "node:path";
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {
const normalized = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
if (normalized.length === 0 || normalized.startsWith("..") || normalized.includes("\0")) {
return null;
}
return normalized.replace(/\\/g, "/");
}
export function resolveAttachmentRelativePath(input: {
readonly stateDir: string;
readonly relativePath: string;
}): string | null {
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
if (!normalizedRelativePath) {
return null;
}
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
return null;
}
return filePath;
}
+77
View File
@@ -0,0 +1,77 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
createAttachmentId,
parseThreadSegmentFromAttachmentId,
resolveAttachmentPathById,
} from "./attachmentStore.ts";
describe("attachmentStore", () => {
it("sanitizes thread ids when creating attachment ids", () => {
const attachmentId = createAttachmentId("thread.folder/unsafe space");
expect(attachmentId).toBeTruthy();
if (!attachmentId) {
return;
}
const threadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
expect(threadSegment).toBeTruthy();
expect(threadSegment).toMatch(/^[a-z0-9_-]+$/i);
expect(threadSegment).not.toContain(".");
expect(threadSegment).not.toContain("%");
expect(threadSegment).not.toContain("/");
});
it("parses exact thread segments from attachment ids without prefix collisions", () => {
const fooId = "foo-00000000-0000-4000-8000-000000000001";
const fooBarId = "foo-bar-00000000-0000-4000-8000-000000000002";
expect(parseThreadSegmentFromAttachmentId(fooId)).toBe("foo");
expect(parseThreadSegmentFromAttachmentId(fooBarId)).toBe("foo-bar");
});
it("normalizes created thread segments to lowercase", () => {
const attachmentId = createAttachmentId("Thread.Foo");
expect(attachmentId).toBeTruthy();
if (!attachmentId) {
return;
}
expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const attachmentId = "thread-1-attachment";
const attachmentsDir = path.join(stateDir, "attachments");
fs.mkdirSync(attachmentsDir, { recursive: true });
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
fs.writeFileSync(pngPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
stateDir,
attachmentId,
});
expect(resolved).toBe(pngPath);
} finally {
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
it("returns null when no attachment file exists for the id", () => {
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const resolved = resolveAttachmentPathById({
stateDir,
attachmentId: "thread-1-missing",
});
expect(resolved).toBeNull();
} finally {
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
});
+110
View File
@@ -0,0 +1,110 @@
import { randomUUID } from "node:crypto";
import { existsSync } from "node:fs";
import type { ChatAttachment } from "@t3tools/contracts";
import {
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN =
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
const ATTACHMENT_ID_PATTERN = new RegExp(
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
"i",
);
export function toSafeThreadAttachmentSegment(threadId: string): string | null {
const segment = threadId
.trim()
.toLowerCase()
.replace(/[^a-z0-9_-]+/gi, "-")
.replace(/-+/g, "-")
.replace(/^[-_]+|[-_]+$/g, "")
.slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
.replace(/[-_]+$/g, "");
if (segment.length === 0) {
return null;
}
return segment;
}
export function createAttachmentId(threadId: string): string | null {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
return null;
}
return `${threadSegment}-${randomUUID()}`;
}
export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
return null;
}
const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
if (!match) {
return null;
}
return match[1]?.toLowerCase() ?? null;
}
export function attachmentRelativePath(attachment: ChatAttachment): string {
switch (attachment.type) {
case "image": {
const extension = inferImageExtension({
mimeType: attachment.mimeType,
fileName: attachment.name,
});
return `${attachment.id}${extension}`;
}
}
}
export function resolveAttachmentPath(input: {
readonly stateDir: string;
readonly attachment: ChatAttachment;
}): string | null {
return resolveAttachmentRelativePath({
stateDir: input.stateDir,
relativePath: attachmentRelativePath(input.attachment),
});
}
export function resolveAttachmentPathById(input: {
readonly stateDir: string;
readonly attachmentId: string;
}): string | null {
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
return null;
}
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
const maybePath = resolveAttachmentRelativePath({
stateDir: input.stateDir,
relativePath: `${normalizedId}${extension}`,
});
if (maybePath && existsSync(maybePath)) {
return maybePath;
}
}
return null;
}
export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
const normalized = normalizeAttachmentRelativePath(relativePath);
if (!normalized || normalized.includes("/")) {
return null;
}
const extensionIndex = normalized.lastIndexOf(".");
if (extensionIndex <= 0) {
return null;
}
const id = normalized.slice(0, extensionIndex);
return id.length > 0 && !id.includes(".") ? id : null;
}
@@ -45,7 +45,14 @@ function makeSnapshot(input: {
model: "gpt-5-codex",
branch: null,
worktreePath: input.worktreePath,
latestTurnId: TurnId.makeUnsafe("turn-1"),
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-01-01T00:00:00.000Z",
startedAt: "2026-01-01T00:00:00.000Z",
completedAt: "2026-01-01T00:00:00.000Z",
assistantMessageId: null,
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
+39 -12
View File
@@ -1,17 +1,44 @@
import { describe, expect, it, vi } from "vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Cause } from "effect";
import { ManagedRuntime, ServiceMap } from "effect";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ProviderSessionId } from "@t3tools/contracts";
import {
CodexAppServerManager,
classifyCodexStderrLine,
isRecoverableThreadResumeError,
messageFromCodexProcessCause,
normalizeCodexModelSlug,
} from "./codexAppServerManager";
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
let runtime: ManagedRuntime.ManagedRuntime<NodeServices.NodeServices, never> | null = null;
let services: ServiceMap.ServiceMap<NodeServices.NodeServices> | null = null;
beforeEach(async () => {
runtime = ManagedRuntime.make(NodeServices.layer);
services = await runtime.services();
});
afterEach(async () => {
services = null;
if (runtime) {
await runtime.dispose();
}
runtime = null;
});
function createManager() {
if (!services) {
throw new Error("Test runtime services not initialized.");
}
return new CodexAppServerManager(services);
}
function createSendTurnHarness() {
const manager = new CodexAppServerManager();
const manager = createManager();
const context = {
session: {
sessionId: "sess_1",
@@ -47,7 +74,7 @@ function createSendTurnHarness() {
}
function createThreadControlHarness() {
const manager = new CodexAppServerManager();
const manager = createManager();
const context = {
session: {
sessionId: "sess_1",
@@ -146,9 +173,15 @@ describe("isRecoverableThreadResumeError", () => {
});
});
describe("messageFromCodexProcessCause", () => {
it("extracts the underlying error message from an effect cause", () => {
expect(messageFromCodexProcessCause(Cause.fail(new Error("boom")))).toBe("boom");
});
});
describe("startSession", () => {
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
const manager = new CodexAppServerManager();
const manager = createManager();
const events: Array<{ method: string; kind: string; message?: string }> = [];
manager.on("event", (event) => {
events.push({
@@ -191,10 +224,7 @@ describe("sendTurn", () => {
attachments: [
{
type: "image",
name: "error.png",
mimeType: "image/png",
sizeBytes: 1_024,
dataUrl: "data:image/png;base64,AAAA",
url: "data:image/png;base64,AAAA",
},
],
model: "gpt-5.3",
@@ -242,10 +272,7 @@ describe("sendTurn", () => {
attachments: [
{
type: "image",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 256,
dataUrl: "data:image/png;base64,BBBB",
url: "data:image/png;base64,BBBB",
},
],
});
+140 -70
View File
@@ -1,7 +1,5 @@
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { EventEmitter } from "node:events";
import readline from "node:readline";
import {
ApprovalRequestId,
@@ -14,11 +12,14 @@ import {
normalizeModelSlug,
type ProviderApprovalDecision,
type ProviderEvent,
type ProviderSendTurnInput,
type ProviderSession,
type ProviderSessionStartInput,
type ProviderTurnStartResult,
} from "@t3tools/contracts";
import type * as NodeServices from "@effect/platform-node/NodeServices";
import { Cause, Effect, Exit, ServiceMap, Scope, Stream } from "effect";
import type { ChildProcessSpawner } from "effect/unstable/process";
import { makeRuntimeCommand, spawnManagedCommand } from "./processRunner";
type PendingRequestKey = string;
@@ -41,8 +42,8 @@ interface PendingApprovalRequest {
interface CodexSessionContext {
session: ProviderSession;
child: ChildProcessWithoutNullStreams;
output: readline.Interface;
child: ChildProcessSpawner.ChildProcessHandle;
scope: Scope.Closeable;
pending: Map<PendingRequestKey, PendingRequest>;
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
nextRequestId: number;
@@ -71,6 +72,14 @@ interface JsonRpcNotification {
params?: unknown;
}
export interface CodexAppServerSendTurnInput {
readonly sessionId: ProviderSessionId;
readonly input?: string;
readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>;
readonly model?: string;
readonly effort?: string;
}
export interface CodexThreadTurnSnapshot {
id: ProviderTurnId;
items: unknown[];
@@ -144,12 +153,32 @@ export function isRecoverableThreadResumeError(error: unknown): boolean {
return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
}
export function messageFromCodexProcessCause(cause: Cause.Cause<unknown>): string {
const squashed = Cause.squash(cause);
return squashed instanceof Error ? squashed.message : "codex app-server process errored.";
}
export interface CodexAppServerManagerEvents {
event: [event: ProviderEvent];
}
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();
private readonly runPromise: <A, E>(
effect: Effect.Effect<A, E, NodeServices.NodeServices>,
options?: Effect.RunOptions | undefined,
) => Promise<A>;
constructor(services?: ServiceMap.ServiceMap<NodeServices.NodeServices>) {
super();
this.runPromise = services
? Effect.runPromiseWith(services)
: ((effect, options) =>
Effect.runPromise(
effect as unknown as Effect.Effect<unknown, never>,
options,
)) as typeof this.runPromise;
}
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
const sessionId = ProviderSessionId.makeUnsafe(randomUUID());
@@ -171,20 +200,23 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const codexBinaryPath = input.codexBinaryPath ?? "codex";
const codexHomePath = input.codexHomePath;
const child = spawn(codexBinaryPath, ["app-server"], {
cwd: resolvedCwd,
env: {
...process.env,
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
},
stdio: ["pipe", "pipe", "pipe"],
});
const output = readline.createInterface({ input: child.stdout });
const managedProcess = await this.runPromise(
spawnManagedCommand(
makeRuntimeCommand(codexBinaryPath, ["app-server"], {
cwd: resolvedCwd,
env: {
...process.env,
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
},
extendEnv: false,
}),
),
);
context = {
session,
child,
output,
child: managedProcess.handle,
scope: managedProcess.scope,
pending: new Map(),
pendingApprovals: new Map(),
nextRequestId: 1,
@@ -192,7 +224,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
};
this.sessions.set(sessionId, context);
this.attachProcessListeners(context);
await this.attachProcessListeners(context);
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
@@ -207,7 +239,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
},
});
this.writeMessage(context, { method: "initialized" });
await this.writeMessage(context, { method: "initialized" });
const normalizedModel = normalizeCodexModelSlug(input.model);
const sessionOverrides = {
@@ -290,7 +322,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
}
async sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
const context = this.requireSession(input.sessionId);
if (!context.session.threadId) {
throw new Error("Session is missing a thread id.");
@@ -310,7 +342,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
if (attachment.type === "image") {
turnInput.push({
type: "image",
url: attachment.dataUrl,
url: attachment.url,
});
}
}
@@ -423,7 +455,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
context.pendingApprovals.delete(requestId);
this.writeMessage(context, {
await this.writeMessage(context, {
id: pendingRequest.jsonRpcId,
result: {
decision,
@@ -464,12 +496,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
context.pending.clear();
context.pendingApprovals.clear();
context.output.close();
if (!context.child.killed) {
context.child.kill();
}
void this.runPromise(Scope.close(context.scope, Exit.void)).catch(() => undefined);
this.updateSession(context, {
status: "closed",
@@ -508,47 +535,71 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return context;
}
private attachProcessListeners(context: CodexSessionContext): void {
context.output.on("line", (line) => {
this.handleStdoutLine(context, line);
});
private async attachProcessListeners(context: CodexSessionContext): Promise<void> {
await this.runPromise(
Effect.gen(
function* (this: CodexAppServerManager) {
yield* Effect.forkScoped(
Stream.runForEach(Stream.splitLines(Stream.decodeText(context.child.stdout)), (line) =>
Effect.sync(() => {
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;
}
yield* Effect.forkScoped(
Stream.runForEach(Stream.decodeText(context.child.stderr), (raw) =>
Effect.sync(() => {
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);
}
});
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);
});
yield* Effect.forkScoped(
Effect.matchCauseEffect(context.child.exitCode, {
onFailure: (cause) =>
Effect.sync(() => {
if (context.stopping) {
return;
}
context.child.on("exit", (code, signal) => {
if (context.stopping) {
return;
}
const message = messageFromCodexProcessCause(cause);
this.updateSession(context, {
status: "error",
activeTurnId: undefined,
lastError: message,
});
this.emitErrorEvent(context, "process/error", message);
this.sessions.delete(context.session.sessionId);
}),
onSuccess: (code) =>
Effect.sync(() => {
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);
});
const message = `codex app-server exited (code=${code}).`;
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);
}),
}),
);
}.bind(this),
).pipe(Scope.provide(context.scope)),
);
}
private handleStdoutLine(context: CodexSessionContext, line: string): void {
@@ -704,19 +755,31 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (request.method === "item/tool/requestUserInput") {
this.writeMessage(context, {
void this.writeMessage(context, {
id: request.id,
result: { answers: {} },
}).catch((error) => {
this.emitErrorEvent(
context,
"protocol/writeError",
error instanceof Error ? error.message : String(error),
);
});
return;
}
this.writeMessage(context, {
void this.writeMessage(context, {
id: request.id,
error: {
code: -32601,
message: `Unsupported server request: ${request.method}`,
},
}).catch((error) => {
this.emitErrorEvent(
context,
"protocol/writeError",
error instanceof Error ? error.message : String(error),
);
});
}
@@ -759,23 +822,30 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
resolve,
reject,
});
this.writeMessage(context, {
void this.writeMessage(context, {
method,
id,
params,
}).catch((error) => {
clearTimeout(timeout);
context.pending.delete(String(id));
reject(error instanceof Error ? error : new Error(String(error)));
});
});
return result as TResponse;
}
private writeMessage(context: CodexSessionContext, message: unknown): void {
private async writeMessage(context: CodexSessionContext, message: unknown): Promise<void> {
const encoded = JSON.stringify(message);
if (!context.child.stdin.writable) {
if (context.stopping) {
throw new Error("Cannot write to codex app-server stdin.");
}
context.child.stdin.write(`${encoded}\n`);
await this.runPromise(
Stream.run(context.child.stdin)(Stream.make(new TextEncoder().encode(`${encoded}\n`))).pipe(
Scope.provide(context.scope),
),
);
}
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
+22 -63
View File
@@ -1,13 +1,12 @@
/**
* ServerConfig and NetService - Runtime configuration services.
* ServerConfig - Runtime configuration services.
*
* Defines process-level server configuration and networking helpers used by
* startup and runtime layers.
*
* @module ServerConfig
*/
import * as Net from "node:net";
import { Data, Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
export const DEFAULT_PORT = 3773;
@@ -36,68 +35,28 @@ export interface ServerConfigShape {
*/
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
"t3/config/ServerConfig",
) {}
// Helpers
export class NetError extends Data.TaggedError("NetError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
/**
* NetServiceShape - Networking helper operations used during startup.
*/
export interface NetServiceShape {
/**
* Resolve an available listening port, preferring the provided port first.
*
* Falls back to an ephemeral OS-assigned port when the preferred port is in use.
*/
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
}
/**
* NetService - Service tag for startup networking helpers.
*/
export class NetService extends ServiceMap.Service<NetService, NetServiceShape>()(
"t3/config/NetService",
) {
static readonly layer = Layer.succeed(NetService, {
findAvailablePort: (preferred) =>
Effect.callback<number, NetError>((resume) => {
let fallbackServer: Net.Server | null = null;
const server = Net.createServer();
server.listen(preferred, () => {
server.close(() => resume(Effect.succeed(preferred)));
});
server.on("error", () => {
const fallback = Net.createServer();
fallback.listen(0, () => {
const addr = fallback.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
fallback.close(() => {
resume(
port > 0
? Effect.succeed(port)
: Effect.fail(new NetError({ message: "Could not find an available port." })),
);
});
});
fallback.on("error", (cause) => {
resume(
Effect.fail(new NetError({ message: "Failed to find an available port", cause })),
);
});
fallbackServer = fallback;
});
return Effect.sync(() => {
server.close();
fallbackServer?.close();
});
static readonly layerTest = (cwd: string, statedir: string) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const path = yield* Path.Path;
return {
cwd,
stateDir: statedir,
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
port: 0,
host: undefined,
authToken: undefined,
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
staticDir: undefined,
devUrl: undefined,
noBrowser: false,
};
}),
});
);
}
export const resolveStaticDir = Effect.fn(function* () {
@@ -3,10 +3,17 @@ import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { TextGenerationError } from "../Errors.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
CodexTextGenerationLive.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeCodexBinary(dir: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -21,13 +28,36 @@ function makeFakeCodexBinary(dir: string) {
"#!/bin/sh",
'output_path=""',
"while [ $# -gt 0 ]; do",
' if [ "$1" = "--image" ]; then',
" shift",
' if [ -n "$1" ]; then',
' seen_image="1"',
" fi",
" continue",
" fi",
' if [ "$1" = "--output-last-message" ]; then',
" shift",
' output_path="$1"',
" fi",
" shift",
"done",
"cat >/dev/null",
'stdin_content="$(cat)"',
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
' printf "%s\\n" "missing --image input" >&2',
" exit 2",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "stdin missing expected content" >&2',
" exit 3",
" }",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
' printf "%s\\n" "stdin contained forbidden content" >&2',
" exit 4",
" fi",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
"fi",
@@ -48,6 +78,9 @@ function withFakeCodexEnv<A, E, R>(
output: string;
exitCode?: number;
stderr?: string;
requireImage?: boolean;
stdinMustContain?: string;
stdinMustNotContain?: string;
},
effect: Effect.Effect<A, E, R>,
) {
@@ -60,6 +93,9 @@ function withFakeCodexEnv<A, E, R>(
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
@@ -76,6 +112,24 @@ function withFakeCodexEnv<A, E, R>(
} else {
delete process.env.T3_FAKE_CODEX_STDERR;
}
if (input.requireImage) {
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
} else {
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
}
if (input.stdinMustContain !== undefined) {
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
} else {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
}
if (input.stdinMustNotContain !== undefined) {
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
} else {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
}
});
return {
@@ -83,6 +137,9 @@ function withFakeCodexEnv<A, E, R>(
previousOutput,
previousExitCode,
previousStderr,
previousRequireImage,
previousStdinMustContain,
previousStdinMustNotContain,
};
}),
() => effect,
@@ -107,17 +164,32 @@ function withFakeCodexEnv<A, E, R>(
} else {
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
}
if (previous.previousRequireImage === undefined) {
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
} else {
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
}
if (previous.previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
}
if (previous.previousStdinMustNotContain === undefined) {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
}
}),
);
}
const CodexTextGenerationTestLayer = Layer.provideMerge(
CodexTextGenerationLive,
NodeServices.layer,
);
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
it.effect("generates and sanitizes commit messages", () =>
it.effect("generates and sanitizes commit messages without branch by default", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
@@ -125,6 +197,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
" Add important change to the system with too much detail and a trailing period.\nsecondary line",
body: "\n- added migration\n- updated tests\n",
}),
stdinMustNotContain: "branch must be a short semantic git branch fragment",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
@@ -139,6 +212,34 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
expect(generated.subject.length).toBeLessThanOrEqual(72);
expect(generated.subject.endsWith(".")).toBe(false);
expect(generated.body).toBe("- added migration\n- updated tests");
expect(generated.branch).toBeUndefined();
}),
),
);
it.effect("generates commit message with branch when includeBranch is true", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
subject: "Add important change",
body: "",
branch: "fix/important-system-change",
}),
stdinMustContain: "branch must be a short semantic git branch fragment",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
includeBranch: true,
});
expect(generated.subject).toBe("Add important change");
expect(generated.branch).toBe("feature/fix/important-system-change");
}),
),
);
@@ -170,6 +271,216 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
),
);
it.effect("generates branch names and normalizes branch fragments", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
branch: " Feat/Session ",
}),
stdinMustNotContain: "Image attachments supplied to the model",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Please update session handling.",
});
expect(generated.branch).toBe("feat/session");
}),
),
);
it.effect("omits attachment metadata section when no attachments are provided", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
branch: "fix/session-timeout",
}),
stdinMustNotContain: "Attachment metadata:",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Fix timeout behavior.",
});
expect(generated.branch).toBe("fix/session-timeout");
}),
),
);
it.effect("passes image attachments through as codex image inputs", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
branch: "fix/ui-regression",
}),
requireImage: true,
stdinMustContain: "Attachment metadata:",
},
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: attachmentId,
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
expect(generated.branch).toBe("fix/ui-regression");
}),
),
);
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
branch: "fix/ui-regression",
}),
requireImage: true,
},
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const attachmentId =
`thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: attachmentId,
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(
Effect.tap(() =>
fs.stat(imagePath).pipe(
Effect.map((fileInfo) => {
expect(fileInfo.type).toBe("File");
}),
),
),
Effect.ensuring(
fs.remove(imagePath).pipe(Effect.catch(() => Effect.void)),
),
);
expect(generated.branch).toBe("fix/ui-regression");
}),
),
);
it.effect("ignores missing attachment ids for codex image inputs", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
branch: "fix/ui-regression",
}),
requireImage: true,
},
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: missingAttachmentId,
name: "outside.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.message).toContain("missing --image input");
}
}),
),
);
it.effect(
"fails with typed TextGenerationError when codex returns wrong branch payload shape",
() =>
withFakeCodexEnv(
{
output: JSON.stringify({
title: "This is not a branch payload",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix websocket reconnect flake",
})
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.message).toContain("Codex returned invalid structured output");
}
}),
),
);
it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
withFakeCodexEnv(
{
+207 -173
View File
@@ -1,10 +1,16 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { Effect, FileSystem, Layer, Path, Schema } from "effect";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { runProcess } from "../../processRunner.ts";
import { TextGenerationError } from "../Errors.ts";
import {
type BranchNameGenerationInput,
type BranchNameGenerationResult,
type CommitMessageGenerationResult,
type PrContentGenerationResult,
type TextGenerationShape,
@@ -15,25 +21,16 @@ const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
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 toCodexOutputJsonSchema(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return {
...document.schema,
$defs: document.definitions,
};
}
return document.schema;
}
function normalizeCodexError(
operation: string,
@@ -71,32 +68,6 @@ function normalizeCodexError(
});
}
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);
@@ -127,25 +98,11 @@ function sanitizePrTitle(raw: string): string {
const makeCodexTextGeneration = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const readStreamAsString = <E>(
operation: string,
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, TextGenerationError> =>
Effect.gen(function* () {
let text = "";
yield* Stream.runForEach(stream, (chunk) =>
Effect.sync(() => {
text += Buffer.from(chunk).toString("utf8");
}),
).pipe(
Effect.mapError((cause) =>
normalizeCodexError(operation, cause, "Failed to collect process output"),
),
);
return text;
});
type MaterializedImageAttachments = {
readonly imagePaths: ReadonlyArray<string>;
};
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
@@ -171,109 +128,128 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
const runCodexJson = <T>({
const materializeImageAttachments = (
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
attachments: BranchNameGenerationInput["attachments"],
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
Effect.gen(function* () {
if (!attachments || attachments.length === 0) {
return { imagePaths: [] };
}
const imagePaths: string[] = [];
for (const attachment of attachments) {
if (attachment.type !== "image") {
continue;
}
const resolvedPath = resolveAttachmentPath({
stateDir: serverConfig.stateDir,
attachment,
});
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
continue;
}
const fileInfo = yield* fileSystem
.stat(resolvedPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
continue;
}
imagePaths.push(resolvedPath);
}
return { imagePaths };
});
const runCodexJson = <S extends Schema.Top>({
operation,
cwd,
prompt,
outputSchemaJson,
parse,
imagePaths = [],
cleanupPaths = [],
}: {
operation: "generateCommitMessage" | "generatePrContent";
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
cwd: string;
prompt: string;
outputSchemaJson: object;
parse: (raw: unknown) => T;
}): Effect.Effect<T, TextGenerationError> =>
outputSchemaJson: S;
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(outputSchemaJson),
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const runCodexCommand = Effect.gen(function* () {
const command = ChildProcess.make(
"codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
CODEX_MODEL,
"--config",
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
"-",
],
{
cwd,
stdin: {
stream: Stream.make(new TextEncoder().encode(prompt)),
const runCodexCommand = Effect.tryPromise({
try: async () => {
const result = await runProcess(
"codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
CODEX_MODEL,
"--config",
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
"-",
],
{
cwd,
stdin: prompt,
allowNonZeroExit: true,
timeoutMs: CODEX_TIMEOUT_MS,
maxBufferBytes: 1_000_000,
outputMode: "truncate",
},
},
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError((cause) =>
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
),
),
],
{ concurrency: "unbounded" },
);
if (result.timedOut) {
throw new TextGenerationError({ operation, detail: "Codex CLI request timed out." });
}
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Codex CLI command failed: ${detail}`
: `Codex CLI command failed with code ${exitCode}.`,
});
}
const stdout = result.stdout;
const stderr = result.stderr;
const exitCode = result.code ?? 0;
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
throw new TextGenerationError({
operation,
detail:
detail.length > 0
? `Codex CLI command failed: ${detail}`
: `Codex CLI command failed with code ${exitCode}.`,
});
}
},
catch: (error) =>
normalizeCodexError(operation, error, "Failed to execute Codex CLI process"),
});
const cleanup = Effect.all([safeUnlink(schemaPath), safeUnlink(outputPath)], {
concurrency: "unbounded",
}).pipe(Effect.asVoid);
const cleanup = Effect.all(
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
{
concurrency: "unbounded",
},
).pipe(Effect.asVoid);
return yield* Effect.gen(function* () {
yield* runCodexCommand.pipe(
Effect.scoped,
Effect.timeoutOption(CODEX_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
),
onSome: () => Effect.void,
}),
),
);
yield* runCodexCommand;
const rawOutput = yield* fileSystem.readFileString(outputPath).pipe(
return yield* fileSystem.readFileString(outputPath).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
@@ -282,40 +258,34 @@ const makeCodexTextGeneration = Effect.gen(function* () {
cause,
}),
),
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Codex returned invalid structured output.",
cause,
}),
),
),
);
const trimmed = rawOutput.trim();
if (trimmed.length === 0) {
return yield* new TextGenerationError({
operation,
detail: "Codex returned an empty response.",
});
}
const parsedJson = yield* Effect.try({
try: () => JSON.parse(trimmed) as unknown,
catch: (cause) =>
new TextGenerationError({
operation,
detail: "Codex returned invalid JSON output.",
cause,
}),
});
return yield* Effect.try({
try: () => parse(parsedJson),
catch: (cause) =>
normalizeCodexError(operation, cause, "Codex returned invalid structured output"),
});
}).pipe(Effect.ensuring(cleanup));
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
const wantsBranch = input.includeBranch === true;
const prompt = [
"You write concise git commit messages.",
"Return a JSON object with keys: subject, body.",
wantsBranch
? "Return a JSON object with keys: subject, body, branch."
: "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",
...(wantsBranch
? ["- branch must be a short semantic git branch fragment for this change"]
: []),
"- capture the primary user-visible or developer-visible change",
"",
`Branch: ${input.branch ?? "(detached)"}`,
@@ -327,18 +297,31 @@ const makeCodexTextGeneration = Effect.gen(function* () {
limitSection(input.stagedPatch, 40_000),
].join("\n");
const outputSchemaJson = wantsBranch
? Schema.Struct({
subject: Schema.String,
body: Schema.String,
branch: Schema.String,
})
: Schema.Struct({
subject: Schema.String,
body: Schema.String,
});
return runCodexJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
parse: (raw) => parseCommitOutput(raw),
outputSchemaJson,
}).pipe(
Effect.map(
(generated) =>
({
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
}) satisfies CommitMessageGenerationResult,
),
);
@@ -371,8 +354,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
parse: (raw) => parsePrOutput(raw),
outputSchemaJson: Schema.Struct({
title: Schema.String,
body: Schema.String,
}),
}).pipe(
Effect.map(
(generated) =>
@@ -384,9 +369,58 @@ const makeCodexTextGeneration = Effect.gen(function* () {
);
};
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
return Effect.gen(function* () {
const { imagePaths } = yield* materializeImageAttachments(
"generateBranchName",
input.attachments,
);
const attachmentLines = (input.attachments ?? []).map(
(attachment) =>
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
);
const promptSections = [
"You generate concise git branch names.",
"Return a JSON object with key: branch.",
"Rules:",
"- Branch should describe the requested work from the user message.",
"- Keep it short and specific (2-6 words).",
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
"- If images are attached, use them as primary context for visual/UI issues.",
"",
"User message:",
limitSection(input.message, 8_000),
];
if (attachmentLines.length > 0) {
promptSections.push(
"",
"Attachment metadata:",
limitSection(attachmentLines.join("\n"), 4_000),
);
}
const prompt = promptSections.join("\n");
const generated = yield* runCodexJson({
operation: "generateBranchName",
cwd: input.cwd,
prompt,
outputSchemaJson: Schema.Struct({
branch: Schema.String,
}),
imagePaths,
});
return {
branch: sanitizeBranchFragment(generated.branch),
} satisfies BranchNameGenerationResult;
});
};
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
} satisfies TextGenerationShape;
});
+479
View File
@@ -106,9 +106,11 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
listBranches: (input) => core.listBranches(input),
createWorktree: (input) => core.createWorktree(input),
removeWorktree: (input) => core.removeWorktree(input),
renameBranch: (input) => core.renameBranch(input),
createBranch: (input) => core.createBranch(input),
checkoutBranch: (input) => core.checkoutBranch(input),
initRepo: (input) => core.initRepo(input),
listLocalBranchNames: (cwd) => core.listLocalBranchNames(cwd),
} satisfies GitCoreShape;
});
@@ -154,6 +156,13 @@ function removeGitWorktree(input: Parameters<GitCoreShape["removeWorktree"]>[0])
});
}
function renameGitBranch(input: Parameters<GitCoreShape["renameBranch"]>[0]) {
return Effect.gen(function* () {
const core = yield* GitCore;
return yield* core.renameBranch(input);
});
}
function pullGitBranch({ cwd }: { cwd: string }) {
return Effect.gen(function* () {
const core = yield* GitCore;
@@ -266,6 +275,18 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("does not include detached HEAD pseudo-refs as branches", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* git(tmp, ["checkout", "--detach", "HEAD"]);
const result = yield* listGitBranches({ cwd: tmp });
expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false);
expect(result.branches.some((branch) => branch.current)).toBe(false);
}),
);
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -370,6 +391,82 @@ it.layer(TestLayer)("git integration", (it) => {
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
}),
);
it.effect("lists local branches first and remote branches last", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: tmp, branch: "feature/local-only" });
const remoteOnlyBranch = "feature/remote-only";
yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* listGitBranches({ cwd: tmp });
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
expect(firstRemoteIndex).toBeGreaterThan(0);
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
true,
);
expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe(
true,
);
expect(
result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),
).toBe(true);
expect(
result.branches.some(
(branch) => branch.name === "origin/feature/remote-only" && branch.isRemote,
),
).toBe(true);
}),
);
it.effect("includes remoteName metadata for remotes with slash in the name", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
const remoteName = "my-org/upstream";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", remoteName, remote]);
yield* git(tmp, ["push", "-u", remoteName, defaultBranch]);
const remoteOnlyBranch = "feature/remote-with-remote-name";
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* listGitBranches({ cwd: tmp });
const remoteBranch = result.branches.find(
(branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`,
);
expect(remoteBranch).toBeDefined();
expect(remoteBranch?.isRemote).toBe(true);
expect(remoteBranch?.remoteName).toBe(remoteName);
}),
);
});
// ── checkoutGitBranch ──
@@ -592,6 +689,87 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"does not silently checkout a local branch when a remote ref no longer exists",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: source, branch: "feature" });
const checkoutResult = yield* Effect.result(
checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
);
expect(checkoutResult._tag).toBe("Failure");
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
}),
);
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const remoteName = "my-org/upstream";
const featureBranch = "feature";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", remoteName, remote]);
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
yield* git(source, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["push", "-u", remoteName, featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
yield* git(source, ["branch", "-D", featureBranch]);
yield* checkoutGitBranch({ cwd: source, branch: `${remoteName}/${featureBranch}` });
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
}),
);
it.effect(
"falls back to detached checkout when --track would conflict with an existing local branch",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
// Keep local branch but remove tracking so `--track origin/<branch>`
// would attempt to create an already-existing local branch.
yield* git(source, ["branch", "--unset-upstream"]);
yield* checkoutGitBranch({ cwd: source, branch: `origin/${defaultBranch}` });
const core = yield* GitCore;
const status = yield* core.statusDetails(source);
expect(status.branch).toBeNull();
}),
);
it.effect("throws when checkout would overwrite uncommitted changes", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -650,6 +828,129 @@ it.layer(TestLayer)("git integration", (it) => {
);
});
// ── renameGitBranch ──
describe("renameGitBranch", () => {
it.effect("renames the current branch", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* createGitBranch({ cwd: tmp, branch: "feature/old-name" });
yield* checkoutGitBranch({ cwd: tmp, branch: "feature/old-name" });
const renamed = yield* renameGitBranch({
cwd: tmp,
oldBranch: "feature/old-name",
newBranch: "feature/new-name",
});
expect(renamed.branch).toBe("feature/new-name");
const branches = yield* listGitBranches({ cwd: tmp });
expect(branches.branches.some((branch) => branch.name === "feature/old-name")).toBe(false);
const current = branches.branches.find((branch) => branch.current);
expect(current?.name).toBe("feature/new-name");
}),
);
it.effect("returns success without git invocation when old/new names match", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const current = (yield* listGitBranches({ cwd: tmp })).branches.find((b) => b.current)!;
const renamed = yield* renameGitBranch({
cwd: tmp,
oldBranch: current.name,
newBranch: current.name,
});
expect(renamed.branch).toBe(current.name);
}),
);
it.effect("appends numeric suffix when target branch already exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session" });
yield* createGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
yield* checkoutGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
const renamed = yield* renameGitBranch({
cwd: tmp,
oldBranch: "t3code/tmp-working",
newBranch: "t3code/feat/session",
});
expect(renamed.branch).toBe("t3code/feat/session-1");
const branches = yield* listGitBranches({ cwd: tmp });
expect(branches.branches.some((branch) => branch.name === "t3code/feat/session")).toBe(
true,
);
expect(branches.branches.some((branch) => branch.name === "t3code/feat/session-1")).toBe(
true,
);
const current = branches.branches.find((branch) => branch.current);
expect(current?.name).toBe("t3code/feat/session-1");
}),
);
it.effect("increments suffix until it finds an available branch name", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session" });
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session-1" });
yield* createGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
yield* checkoutGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
const renamed = yield* renameGitBranch({
cwd: tmp,
oldBranch: "t3code/tmp-working",
newBranch: "t3code/feat/session",
});
expect(renamed.branch).toBe("t3code/feat/session-2");
}),
);
it.effect("uses '--' separator for branch rename arguments", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* createGitBranch({ cwd: tmp, branch: "feature/old-name" });
yield* checkoutGitBranch({ cwd: tmp, branch: "feature/old-name" });
const realGitService = yield* GitService;
let renameArgs: ReadonlyArray<string> | null = null;
const core = yield* makeIsolatedGitCore({
execute: (input) => {
if (input.args[0] === "branch" && input.args[1] === "-m") {
renameArgs = [...input.args];
}
return realGitService.execute(input);
},
});
const renamed = yield* core.renameBranch({
cwd: tmp,
oldBranch: "feature/old-name",
newBranch: "feature/new-name",
});
expect(renamed.branch).toBe("feature/new-name");
expect(renameArgs).toEqual([
"branch",
"-m",
"--",
"feature/old-name",
"feature/new-name",
]);
}),
);
});
// ── createGitWorktree + removeGitWorktree ──
describe("createGitWorktree", () => {
@@ -972,6 +1273,135 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("computes ahead count against base branch when no upstream is configured", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
yield* writeTextFile(path.join(tmp, "feature.txt"), "ahead of base\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature commit"]);
const details = yield* core.statusDetails(tmp);
expect(details.branch).toBe("feature/no-upstream-ahead");
expect(details.hasUpstream).toBe(false);
expect(details.aheadCount).toBe(1);
expect(details.behindCount).toBe(0);
}),
);
it.effect(
"computes ahead count against origin/default when local default branch is missing",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const initialBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", initialBranch]);
yield* git(source, ["checkout", "-b", "feature/remote-base-only"]);
yield* writeTextFile(
path.join(source, "feature.txt"),
`ahead of origin/${initialBranch}\n`,
);
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["branch", "-D", initialBranch]);
const core = yield* GitCore;
const details = yield* core.statusDetails(source);
expect(details.branch).toBe("feature/remote-base-only");
expect(details.hasUpstream).toBe(false);
expect(details.aheadCount).toBe(1);
expect(details.behindCount).toBe(0);
}),
);
it.effect("skips push when no upstream is configured and branch is not ahead of base", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("skipped_up_to_date");
expect(pushed.branch).toBe("feature/no-upstream-no-ahead");
expect(pushed.setUpstream).toBeUndefined();
}),
);
it.effect("pushes with upstream setup when no comparable base branch exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* git(tmp, ["init", "--initial-branch=trunk"]);
yield* git(tmp, ["config", "user.email", "[email protected]"]);
yield* git(tmp, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(tmp, "README.md"), "hello\n");
yield* git(tmp, ["add", "README.md"]);
yield* git(tmp, ["commit", "-m", "initial"]);
yield* git(remote, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["checkout", "-b", "feature/no-base"]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(pushed.upstreamBranch).toBe("origin/feature/no-base");
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
"origin/feature/no-base",
);
}),
);
it.effect(
"pushes with upstream setup when comparable base exists but remote branch is missing",
() =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const initialBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
yield* writeTextFile(path.join(tmp, "default-ahead.txt"), "ahead on default\n");
yield* git(tmp, ["add", "default-ahead.txt"]);
yield* git(tmp, ["commit", "-m", "default ahead"]);
const featureBranch = "feature/publish-no-upstream";
yield* git(tmp, ["checkout", "-b", featureBranch]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(pushed.upstreamBranch).toBe(`origin/${featureBranch}`);
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
`origin/${featureBranch}`,
);
expect(yield* git(tmp, ["ls-remote", "--heads", "origin", featureBranch])).toContain(
featureBranch,
);
}),
);
it.effect("includes command context when worktree removal fails", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1153,5 +1583,54 @@ it.layer(TestLayer)("git integration", (it) => {
expect(didFailRecency).toBe(true);
}),
);
it.effect("falls back to empty remote branch data when remote lookups fail", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* git(remote, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remote]);
const realGitService = yield* GitService;
let didFailRemoteBranches = false;
let didFailRemoteNames = false;
const core = yield* makeIsolatedGitCore({
execute: (input) => {
if (input.args.join(" ") === "branch --no-color --remotes") {
didFailRemoteBranches = true;
return Effect.fail(
new GitCommandError({
operation: "git.test.listBranchesRemoteBranches",
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "remote unavailable",
}),
);
}
if (input.args.join(" ") === "remote") {
didFailRemoteNames = true;
return Effect.fail(
new GitCommandError({
operation: "git.test.listBranchesRemoteNames",
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "remote unavailable",
}),
);
}
return realGitService.execute(input);
},
});
const result = yield* core.listBranches({ cwd: tmp });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThan(0);
expect(result.branches.every((branch) => !branch.isRemote)).toBe(true);
expect(didFailRemoteBranches).toBe(true);
expect(didFailRemoteNames).toBe(true);
}),
);
});
});
+502 -52
View File
@@ -7,6 +7,7 @@ import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
class StatusUpstreamRefreshCacheKey extends Data.Class<{
cwd: string;
@@ -76,10 +77,98 @@ function parsePorcelainPath(line: string): string | null {
return filePath.length > 0 ? filePath : null;
}
function parseBranchLine(line: string): { name: string; current: boolean } | null {
const trimmed = line.trim();
if (trimmed.length === 0) return null;
const name = trimmed.replace(/^[*+]\s+/, "");
// Exclude symbolic refs like: "origin/HEAD -> origin/main".
// Exclude detached HEAD pseudo-refs like: "(HEAD detached at origin/main)".
if (name.includes(" -> ") || name.startsWith("(")) return null;
return {
name,
current: trimmed.startsWith("* "),
};
}
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.toSorted((a, b) => b.length - a.length);
}
function parseRemoteRefWithRemoteNames(
branchName: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; localBranch: string } | null {
const trimmedBranchName = branchName.trim();
if (trimmedBranchName.length === 0) return null;
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedBranchName.startsWith(remotePrefix)) {
continue;
}
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
if (localBranch.length === 0) {
return null;
}
return {
remoteRef: trimmedBranchName,
remoteName,
localBranch,
};
}
return null;
}
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
for (const line of stdout.split("\n")) {
const trimmedLine = line.trim();
if (trimmedLine.length === 0) {
continue;
}
const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
const branchName = branchNameRaw?.trim() ?? "";
const upstreamBranch = upstreamBranchRaw.trim();
if (branchName.length === 0 || upstreamBranch.length === 0) {
continue;
}
if (upstreamBranch === upstreamRef) {
return branchName;
}
}
return null;
}
function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null {
const separatorIndex = branchName.indexOf("/");
if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) {
return null;
}
const localBranch = branchName.slice(separatorIndex + 1).trim();
return localBranch.length > 0 ? localBranch : null;
}
function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
function parseDefaultBranchFromRemoteHeadRef(value: string): string | null {
const trimmed = value.trim();
const prefix = "refs/remotes/origin/";
if (!trimmed.startsWith(prefix)) {
return null;
}
const branch = trimmed.slice(prefix.length).trim();
return branch.length > 0 ? branch : null;
}
function createGitCommandError(
operation: string,
cwd: string,
@@ -158,6 +247,43 @@ const makeGitCore = Effect.gen(function* () {
Effect.map((result) => result.stdout),
);
const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
executeGit(
"GitCore.branchExists",
cwd,
["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
{
allowNonZeroExit: true,
timeoutMs: 5_000,
},
).pipe(Effect.map((result) => result.code === 0));
const resolveAvailableBranchName = (
cwd: string,
desiredBranch: string,
): Effect.Effect<string, GitCommandError> =>
Effect.gen(function* () {
const isDesiredTaken = yield* branchExists(cwd, desiredBranch);
if (!isDesiredTaken) {
return desiredBranch;
}
for (let suffix = 1; suffix <= 100; suffix += 1) {
const candidate = `${desiredBranch}-${suffix}`;
const isCandidateTaken = yield* branchExists(cwd, candidate);
if (!isCandidateTaken) {
return candidate;
}
}
return yield* createGitCommandError(
"GitCore.renameBranch",
cwd,
["branch", "-m", "--", desiredBranch],
`Could not find an available branch name for '${desiredBranch}'.`,
);
});
const resolveCurrentUpstream = (
cwd: string,
): Effect.Effect<
@@ -259,12 +385,117 @@ const makeGitCore = Effect.gen(function* () {
yield* fetchUpstreamRef(cwd, upstream);
});
const resolveDefaultBranchName = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
executeGit(
"GitCore.resolveDefaultBranchName",
cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
{ allowNonZeroExit: true },
).pipe(
Effect.map((result) => {
if (result.code !== 0) {
return null;
}
return parseDefaultBranchFromRemoteHeadRef(result.stdout);
}),
);
const remoteBranchExists = (
cwd: string,
branch: string,
): Effect.Effect<boolean, GitCommandError> =>
executeGit(
"GitCore.remoteBranchExists",
cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`],
{
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0));
const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], {
allowNonZeroExit: true,
}).pipe(Effect.map((result) => result.code === 0));
const resolveBaseBranchForNoUpstream = (
cwd: string,
branch: string,
): Effect.Effect<string | null, GitCommandError> =>
Effect.gen(function* () {
const configuredBaseBranch = yield* runGitStdout(
"GitCore.resolveBaseBranchForNoUpstream.config",
cwd,
["config", "--get", `branch.${branch}.gh-merge-base`],
true,
).pipe(Effect.map((stdout) => stdout.trim()));
const defaultBranch = yield* resolveDefaultBranchName(cwd);
const candidates = [
configuredBaseBranch.length > 0 ? configuredBaseBranch : null,
defaultBranch,
...DEFAULT_BASE_BRANCH_CANDIDATES,
];
for (const candidate of candidates) {
if (!candidate) {
continue;
}
const normalizedCandidate = candidate.startsWith("origin/")
? candidate.slice("origin/".length)
: candidate;
if (normalizedCandidate.length === 0 || normalizedCandidate === branch) {
continue;
}
if (yield* branchExists(cwd, normalizedCandidate)) {
return normalizedCandidate;
}
if (yield* remoteBranchExists(cwd, normalizedCandidate)) {
return `origin/${normalizedCandidate}`;
}
}
return null;
});
const computeAheadCountAgainstBase = (
cwd: string,
branch: string,
): Effect.Effect<number, GitCommandError> =>
Effect.gen(function* () {
const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch);
if (!baseBranch) {
return 0;
}
const result = yield* executeGit(
"GitCore.computeAheadCountAgainstBase",
cwd,
["rev-list", "--count", `${baseBranch}..HEAD`],
{ allowNonZeroExit: true },
);
if (result.code !== 0) {
return 0;
}
const parsed = Number.parseInt(result.stdout.trim(), 10);
return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
});
const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
Effect.gen(function* () {
const branchRecency = yield* executeGit(
"GitCore.readBranchRecency",
cwd,
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
[
"for-each-ref",
"--format=%(refname:short)%09%(committerdate:unix)",
"refs/heads",
"refs/remotes",
],
{
timeoutMs: 15_000,
allowNonZeroExit: true,
@@ -343,6 +574,14 @@ const makeGitCore = Effect.gen(function* () {
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
if (!upstreamRef && branch) {
aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(0)),
);
behindCount = 0;
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
@@ -393,7 +632,7 @@ const makeGitCore = Effect.gen(function* () {
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr: null,
pr: null,
})),
);
@@ -452,12 +691,40 @@ const makeGitCore = Effect.gen(function* () {
);
}
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
return {
status: "skipped_up_to_date" as const,
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;
if (hasNoLocalDelta) {
if (details.hasUpstream) {
return {
status: "skipped_up_to_date" as const,
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
}
const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(null)),
);
if (comparableBaseBranch) {
const hasOriginRemote = yield* originRemoteExists(cwd).pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (!hasOriginRemote) {
return {
status: "skipped_up_to_date" as const,
branch,
};
}
const hasRemoteBranch = yield* remoteBranchExists(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (hasRemoteBranch) {
return {
status: "skipped_up_to_date" as const,
branch,
};
}
}
}
if (!details.hasUpstream) {
@@ -564,7 +831,7 @@ const makeGitCore = Effect.gen(function* () {
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
Effect.catch(() => Effect.succeed(new Map<string, number>())),
);
const result = yield* executeGit(
const localBranchResult = yield* executeGit(
"GitCore.listBranches.branchNoColor",
input.cwd,
["branch", "--no-color"],
@@ -574,8 +841,8 @@ const makeGitCore = Effect.gen(function* () {
},
);
if (result.code !== 0) {
const stderr = result.stderr.trim();
if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false };
}
@@ -587,31 +854,79 @@ const makeGitCore = Effect.gen(function* () {
);
}
const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
[
executeGit(
"GitCore.listBranches.defaultRef",
input.cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
),
executeGit(
"GitCore.listBranches.worktreeList",
input.cwd,
["worktree", "list", "--porcelain"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
),
branchRecencyPromise,
],
{ concurrency: "unbounded" },
const remoteBranchResultEffect = executeGit(
"GitCore.listBranches.remoteBranches",
input.cwd,
["branch", "--no-color", "--remotes"],
{
timeoutMs: 10_000,
allowNonZeroExit: true,
},
).pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`,
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
),
);
const remoteNamesResultEffect = executeGit(
"GitCore.listBranches.remoteNames",
input.cwd,
["remote"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`,
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
),
);
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
yield* Effect.all(
[
executeGit(
"GitCore.listBranches.defaultRef",
input.cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
),
executeGit(
"GitCore.listBranches.worktreeList",
input.cwd,
["worktree", "list", "--porcelain"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
),
remoteBranchResultEffect,
remoteNamesResultEffect,
branchRecencyPromise,
],
{ concurrency: "unbounded" },
);
const remoteNames =
remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
yield* Effect.logWarning(
`GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`,
);
}
if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) {
yield* Effect.logWarning(
`GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
);
}
const defaultBranch =
defaultRef.code === 0
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
@@ -636,19 +951,17 @@ const makeGitCore = Effect.gen(function* () {
}
}
const branches = result.stdout
const localBranches = localBranchResult.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,
};
})
.map(parseBranchLine)
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
.map((branch) => ({
name: branch.name,
current: branch.current,
isRemote: false,
isDefault: branch.name === defaultBranch,
worktreePath: worktreeMap.get(branch.name) ?? null,
}))
.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
@@ -660,6 +973,43 @@ const makeGitCore = Effect.gen(function* () {
return a.name.localeCompare(b.name);
});
const remoteBranches =
remoteBranchResult.code === 0
? remoteBranchResult.stdout
.split("\n")
.map(parseBranchLine)
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
.map((branch) => {
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames);
const remoteBranch: {
name: string;
current: boolean;
isRemote: boolean;
remoteName?: string;
isDefault: boolean;
worktreePath: string | null;
} = {
name: branch.name,
current: false,
isRemote: true,
isDefault: false,
worktreePath: null,
};
if (parsedRemoteRef) {
remoteBranch.remoteName = parsedRemoteRef.remoteName;
}
return remoteBranch;
})
.toSorted((a, b) => {
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);
})
: [];
const branches = [...localBranches, ...remoteBranches];
return { branches, isRepo: true };
});
@@ -711,6 +1061,26 @@ const makeGitCore = Effect.gen(function* () {
);
});
const renameBranch: GitCoreShape["renameBranch"] = (input) =>
Effect.gen(function* () {
if (input.oldBranch === input.newBranch) {
return { branch: input.newBranch };
}
const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch);
yield* executeGit(
"GitCore.renameBranch",
input.cwd,
["branch", "-m", "--", input.oldBranch, targetBranch],
{
timeoutMs: 10_000,
fallbackErrorMessage: "git branch rename failed",
},
);
return { branch: targetBranch };
});
const createBranch: GitCoreShape["createBranch"] = (input) =>
executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
timeoutMs: 10_000,
@@ -719,17 +1089,81 @@ const makeGitCore = Effect.gen(function* () {
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
Effect.gen(function* () {
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
const [localInputExists, remoteExists] = yield* Effect.all(
[
executeGit(
"GitCore.checkoutBranch.localInputExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0)),
executeGit(
"GitCore.checkoutBranch.remoteExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0)),
],
{ concurrency: "unbounded" },
);
const localTrackingBranch = remoteExists
? yield* executeGit(
"GitCore.checkoutBranch.localTrackingBranch",
input.cwd,
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(
Effect.map((result) =>
result.code === 0
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
: null,
),
)
: null;
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
const localTrackedBranchTargetExists =
remoteExists && localTrackedBranchCandidate
? yield* executeGit(
"GitCore.checkoutBranch.localTrackedBranchTargetExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0))
: false;
const checkoutArgs = localInputExists
? ["checkout", input.branch]
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
? ["checkout", input.branch]
: remoteExists && !localTrackingBranch
? ["checkout", "--track", input.branch]
: remoteExists && localTrackingBranch
? ["checkout", localTrackingBranch]
: ["checkout", input.branch];
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
// Refresh upstream refs in the background so checkout remains responsive.
yield* Effect.sync(() => {
void Effect.runPromise(
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
);
});
yield* Effect.forkScoped(
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
);
});
const initRepo: GitCoreShape["initRepo"] = (input) =>
@@ -738,6 +1172,20 @@ const makeGitCore = Effect.gen(function* () {
fallbackErrorMessage: "git init failed",
}).pipe(Effect.asVoid);
const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) =>
runGitStdout("GitCore.listLocalBranchNames", cwd, [
"branch",
"--list",
"--format=%(refname:short)",
]).pipe(
Effect.map((stdout) =>
stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0),
),
);
return {
status,
statusDetails,
@@ -750,9 +1198,11 @@ const makeGitCore = Effect.gen(function* () {
listBranches,
createWorktree,
removeWorktree,
renameBranch,
createBranch,
checkoutBranch,
initRepo,
listLocalBranchNames,
} satisfies GitCoreShape;
});
+293 -7
View File
@@ -32,7 +32,11 @@ interface FakeGitTextGeneration {
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
includeBranch?: boolean;
}) => Effect.Effect<
{ subject: string; body: string; branch?: string | undefined },
TextGenerationError
>;
generatePrContent: (input: {
cwd: string;
baseBranch: string;
@@ -41,6 +45,10 @@ interface FakeGitTextGeneration {
diffSummary: string;
diffPatch: string;
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
generateBranchName: (input: {
cwd: string;
message: string;
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
}
function makeTempDir(
@@ -100,16 +108,23 @@ function createBareRemote(): Effect.Effect<
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
const implementation: FakeGitTextGeneration = {
generateCommitMessage: () =>
generateCommitMessage: (input) =>
Effect.succeed({
subject: "Implement stacked git actions",
body: "",
...(input.includeBranch
? { branch: "feature/implement-stacked-git-actions" }
: {}),
}),
generatePrContent: () =>
Effect.succeed({
title: "Add stacked git actions",
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
}),
generateBranchName: () =>
Effect.succeed({
branch: "update-workflow",
}),
...overrides,
};
@@ -136,6 +151,17 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
}),
),
),
generateBranchName: (input) =>
implementation.generateBranchName(input).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation: "generateBranchName",
detail: "fake text generation failed",
...(cause !== undefined ? { cause } : {}),
}),
),
),
};
}
@@ -264,6 +290,7 @@ function runStackedAction(
cwd: string;
action: "commit" | "commit_push" | "commit_push_pr";
commitMessage?: string;
featureBranch?: boolean;
},
) {
return manager.runStackedAction(input);
@@ -297,7 +324,7 @@ function makeManager(input?: {
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
it.layer(GitManagerTestLayer)("GitManager", (it) => {
it.effect("status includes open PR metadata when branch already has an open PR", () =>
it.effect("status includes PR metadata when branch already has an open PR", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -324,17 +351,103 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-open-pr");
expect(status.openPr).toEqual({
expect(status.pr).toEqual({
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseBranch: "main",
headBranch: "feature/status-open-pr",
state: "open",
});
}),
);
it.effect("status is resilient to gh lookup failures and returns openPr null", () =>
it.effect("status returns merged PR state when latest PR was merged", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/status-merged-pr"]);
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 22,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
baseRefName: "main",
headRefName: "feature/status-merged-pr",
state: "MERGED",
mergedAt: "2026-01-30T10:00:00Z",
updatedAt: "2026-01-30T10:00:00Z",
},
]),
],
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-merged-pr");
expect(status.pr).toEqual({
number: 22,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
baseBranch: "main",
headBranch: "feature/status-merged-pr",
state: "merged",
});
}),
);
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]);
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 45,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/45",
baseRefName: "main",
headRefName: "feature/status-open-over-merged",
state: "MERGED",
mergedAt: "2026-01-31T10:00:00Z",
updatedAt: "2026-02-01T10:00:00Z",
},
{
number: 46,
title: "Open PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
baseRefName: "main",
headRefName: "feature/status-open-over-merged",
state: "OPEN",
updatedAt: "2026-01-30T10:00:00Z",
},
]),
],
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-open-over-merged");
expect(status.pr).toEqual({
number: 46,
title: "Open PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
baseBranch: "main",
headBranch: "feature/status-open-over-merged",
state: "open",
});
}),
);
it.effect("status is resilient to gh lookup failures and returns pr null", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -354,7 +467,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-no-gh");
expect(status.openPr).toBeNull();
expect(status.pr).toBeNull();
}),
);
@@ -370,6 +483,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("skipped_not_requested");
@@ -390,12 +504,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
textGeneration: {
generateCommitMessage: () =>
generateCommitMessage: (input) =>
Effect.sync(() => {
generatedCount += 1;
return {
subject: "this should not be used",
body: "",
...(input.includeBranch ? { branch: "feature/unused" } : {}),
};
}),
},
@@ -406,6 +521,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
commitMessage: "feat: custom summary line\n\n- details from user",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.commit.status).toBe("created");
expect(result.commit.subject).toBe("feat: custom summary line");
expect(generatedCount).toBe(0);
@@ -422,6 +538,101 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("creates feature branch, commits, and pushes with featureBranch option", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nfeature-branch\n");
let generatedCount = 0;
const { manager } = yield* makeManager({
textGeneration: {
generateCommitMessage: (input) =>
Effect.sync(() => {
generatedCount += 1;
return {
subject: "Implement stacked git actions",
body: "",
...(input.includeBranch
? { branch: "feature/implement-stacked-git-actions" }
: {}),
};
}),
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push",
featureBranch: true,
});
expect(result.branch.status).toBe("created");
expect(result.branch.name).toBe("feature/implement-stacked-git-actions");
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "HEAD"]).pipe(
Effect.map((result) => result.stdout.trim()),
),
).toBe("feature/implement-stacked-git-actions");
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
Effect.map((r) => r.stdout.trim()),
);
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", "HEAD"]).pipe(
Effect.map((r) => r.stdout.trim()),
);
expect(mergeBase).toBe(mainSha);
expect(generatedCount).toBe(1);
}),
);
it.effect("featureBranch uses custom commit message and derives branch name", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom-feature\n");
let generatedCount = 0;
const { manager } = yield* makeManager({
textGeneration: {
generateCommitMessage: (input) =>
Effect.sync(() => {
generatedCount += 1;
return {
subject: "unused",
body: "",
...(input.includeBranch ? { branch: "feature/unused" } : {}),
};
}),
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit",
featureBranch: true,
commitMessage: "feat: custom summary line\n\n- details from user",
});
expect(result.branch.status).toBe("created");
expect(result.branch.name).toBe("feature/feat-custom-summary-line");
expect(result.commit.status).toBe("created");
expect(result.commit.subject).toBe("feat: custom summary line");
expect(generatedCount).toBe(0);
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
Effect.map((r) => r.stdout.trim()),
);
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", result.branch.name!]).pipe(
Effect.map((r) => r.stdout.trim()),
);
expect(mergeBase).toBe(mainSha);
}),
);
it.effect("skips commit when there are no uncommitted changes", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -433,12 +644,32 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit",
});
expect(result.branch.status).toBe("skipped_not_requested");
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.effect("featureBranch returns error when worktree is clean", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const { manager } = yield* makeManager();
const errorMessage = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit",
featureBranch: true,
}).pipe(
Effect.flip,
Effect.map((error) => error.message),
);
expect(errorMessage).toContain("no changes to commit");
}),
);
it.effect("commits and pushes with upstream auto-setup when needed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -454,6 +685,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
@@ -465,6 +697,57 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"pushes and creates PR from a no-upstream branch when local commits are ahead of base",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/no-upstream-pr"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
"[]",
JSON.stringify([
{
number: 77,
title: "Add no-upstream PR flow",
url: "https://github.com/pingdotgg/codething-mvp/pull/77",
baseRefName: "main",
headRefName: "feature/no-upstream-pr",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
expect(result.pr.status).toBe("created");
expect(
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
Effect.map((result) => result.stdout.trim()),
),
).toBe("origin/feature/no-upstream-pr");
expect(
ghCalls.some((call) =>
call.includes("pr create --base main --head feature/no-upstream-pr"),
),
).toBe(true);
}),
);
it.effect("skips push when branch is already up to date", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -480,6 +763,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.commit.status).toBe("skipped_no_changes");
expect(result.push.status).toBe("skipped_up_to_date");
}),
@@ -514,6 +798,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(42);
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
@@ -554,6 +839,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr",
});
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(88);
expect(
+251 -29
View File
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Path } from "effect";
import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { GitManagerError } from "../Errors.ts";
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
@@ -16,6 +17,62 @@ interface OpenPrInfo {
headRefName: string;
}
interface PullRequestInfo extends OpenPrInfo {
state: "open" | "closed" | "merged";
updatedAt: string | null;
}
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
if (!Array.isArray(raw)) return [];
const parsed: PullRequestInfo[] = [];
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;
const state = record.state;
const mergedAt = record.mergedAt;
const updatedAt = record.updatedAt;
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
continue;
}
if (
typeof title !== "string" ||
typeof url !== "string" ||
typeof baseRefName !== "string" ||
typeof headRefName !== "string"
) {
continue;
}
let normalizedState: "open" | "closed" | "merged";
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
normalizedState = "merged";
} else if (state === "OPEN" || state === undefined || state === null) {
normalizedState = "open";
} else if (state === "CLOSED") {
normalizedState = "closed";
} else {
continue;
}
parsed.push({
number,
title,
url,
baseRefName,
headRefName,
state: normalizedState,
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
});
}
return parsed;
}
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
return new GitManagerError({
operation,
@@ -29,9 +86,14 @@ function limitContext(value: string, maxChars: number): string {
return `${value.slice(0, maxChars)}\n\n[truncated]`;
}
function sanitizeCommitMessage(generated: { subject: string; body: string }): {
function sanitizeCommitMessage(generated: {
subject: string;
body: string;
branch?: string | undefined;
}): {
subject: string;
body: string;
branch?: string | undefined;
} {
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const subject = rawSubject.replace(/[.]+$/g, "").trim();
@@ -39,9 +101,25 @@ function sanitizeCommitMessage(generated: { subject: string; body: string }): {
return {
subject: safeSubject,
body: generated.body.trim(),
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
};
}
interface CommitAndBranchSuggestion {
subject: string;
body: string;
branch?: string | undefined;
commitMessage: string;
}
function formatCommitMessage(subject: string, body: string): string {
const trimmedBody = body.trim();
if (trimmedBody.length === 0) {
return subject;
}
return `${subject}\n\n${trimmedBody}`;
}
function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
const normalized = raw.replace(/\r\n/g, "\n").trim();
if (normalized.length === 0) {
@@ -79,12 +157,13 @@ function extractBranchFromRef(ref: string): string {
return normalized.slice(firstSlash + 1).trim();
}
function toStatusOpenPr(pr: OpenPrInfo): {
function toStatusPr(pr: PullRequestInfo): {
number: number;
title: string;
url: string;
baseBranch: string;
headBranch: string;
state: "open" | "closed" | "merged";
} {
return {
number: pr.number,
@@ -92,6 +171,7 @@ function toStatusOpenPr(pr: OpenPrInfo): {
url: pr.url,
baseBranch: pr.baseRefName,
headBranch: pr.headRefName,
state: pr.state,
};
}
@@ -123,10 +203,56 @@ export const makeGitManager = Effect.gen(function* () {
url: first.url,
baseRefName: first.baseRefName,
headRefName: first.headRefName,
} satisfies OpenPrInfo;
state: "open",
updatedAt: null,
} satisfies PullRequestInfo;
}),
);
const findLatestPr = (cwd: string, branch: string) =>
Effect.gen(function* () {
const stdout = yield* gitHubCli
.execute({
cwd,
args: [
"pr",
"list",
"--head",
branch,
"--state",
"all",
"--limit",
"20",
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
],
})
.pipe(Effect.map((result) => result.stdout));
const raw = stdout.trim();
if (raw.length === 0) {
return null;
}
const parsedJson = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) =>
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
});
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
return right - left;
});
const latestOpenPr = parsed.find((pr) => pr.state === "open");
if (latestOpenPr) {
return latestOpenPr;
}
return parsed[0] ?? null;
});
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
Effect.gen(function* () {
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
@@ -149,30 +275,72 @@ export const makeGitManager = Effect.gen(function* () {
return "main";
});
const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>
const resolveCommitAndBranchSuggestion = (input: {
cwd: string;
branch: string | null;
commitMessage?: string;
/** When true, also produce a semantic feature branch name. */
includeBranch?: boolean;
}) =>
Effect.gen(function* () {
const context = yield* gitCore.prepareCommitContext(cwd);
const context = yield* gitCore.prepareCommitContext(input.cwd);
if (!context) {
return null;
}
const customCommit = parseCustomCommitMessage(input.commitMessage ?? "");
if (customCommit) {
return {
subject: customCommit.subject,
body: customCommit.body,
...(input.includeBranch
? { branch: sanitizeFeatureBranchName(customCommit.subject) }
: {}),
commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),
};
}
const generated = yield* textGeneration
.generateCommitMessage({
cwd: input.cwd,
branch: input.branch,
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
...(input.includeBranch ? { includeBranch: true } : {}),
})
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
return {
subject: generated.subject,
body: generated.body,
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
commitMessage: formatCommitMessage(generated.subject, generated.body),
};
});
const runCommitStep = (
cwd: string,
branch: string | null,
commitMessage?: string,
preResolvedSuggestion?: CommitAndBranchSuggestion,
) =>
Effect.gen(function* () {
const suggestion =
preResolvedSuggestion ??
(yield* resolveCommitAndBranchSuggestion({
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
}));
if (!suggestion) {
return { status: "skipped_no_changes" as const };
}
let generated = parseCustomCommitMessage(commitMessage ?? "");
if (!generated) {
generated = yield* textGeneration
.generateCommitMessage({
cwd,
branch,
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
})
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
}
const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
return {
status: "created" as const,
commitSha,
subject: generated.subject,
subject: suggestion.subject,
};
});
@@ -258,10 +426,10 @@ export const makeGitManager = Effect.gen(function* () {
const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
const details = yield* gitCore.statusDetails(input.cwd);
const openPr =
details.branch && details.hasUpstream
? yield* findOpenPr(input.cwd, details.branch).pipe(
Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),
const pr =
details.branch !== null
? yield* findLatestPr(input.cwd, details.branch).pipe(
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
Effect.catch(() => Effect.succeed(null)),
)
: null;
@@ -273,38 +441,92 @@ export const makeGitManager = Effect.gen(function* () {
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr,
pr,
};
});
const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
Effect.gen(function* () {
const suggestion = yield* resolveCommitAndBranchSuggestion({
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
includeBranch: true,
});
if (!suggestion) {
return yield* gitManagerError(
"runFeatureBranchStep",
"Cannot create a feature branch because there are no changes to commit.",
);
}
const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
return {
branchStep: { status: "created" as const, name: resolvedBranch },
resolvedCommitMessage: suggestion.commitMessage,
resolvedCommitSuggestion: suggestion,
};
});
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
function* (input) {
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (wantsPush && !initialStatus.branch) {
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (wantsPr && !initialStatus.branch) {
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
let commitMessageForStep = input.commitMessage;
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
if (input.featureBranch) {
const result = yield* runFeatureBranchStep(
input.cwd,
initialStatus.branch,
input.commitMessage,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
} else {
branchStep = { status: "skipped_not_requested" as const };
}
const currentBranch = branchStep.name ?? initialStatus.branch;
const commit = yield* runCommitStep(
input.cwd,
currentBranch,
commitMessageForStep,
preResolvedCommitSuggestion,
);
const push = wantsPush
? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? yield* runPrStep(input.cwd, initialStatus.branch)
? yield* runPrStep(input.cwd, currentBranch)
: { status: "skipped_not_requested" as const };
return {
action: input.action,
branch: branchStep,
commit,
push,
pr,
+28 -1
View File
@@ -3,7 +3,7 @@ import { it, assert } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect";
import { GitCommandError } from "../Errors.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitServiceLive, normalizeGitProcessResult } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
@@ -56,4 +56,31 @@ layer("GitServiceLive", (it) => {
}
}),
);
it("normalizeGitProcessResult fails when git exits without a code", () => {
try {
void normalizeGitProcessResult(
{
operation: "GitProcess.test.signal",
cwd: process.cwd(),
args: ["status"],
},
{},
{
code: null,
signal: "SIGTERM",
stdout: "",
stderr: "",
timedOut: false,
},
);
assert.fail("Expected normalizeGitProcessResult to throw.");
} catch (error) {
assert.equal(Schema.is(GitCommandError)(error), true);
if (!Schema.is(GitCommandError)(error)) {
return;
}
assert.equal(error.detail, "git status terminated by signal SIGTERM.");
}
});
});
+64 -82
View File
@@ -1,13 +1,13 @@
/**
* Git process helpers - Effect-native git execution with typed errors.
* Git process helpers - runtime-aware git execution with typed errors.
*
* Centralizes child-process git invocation for server modules. This module
* only executes git commands and reports structured failures.
*
* @module GitServiceLive
*/
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { Effect, Layer, Schema } from "effect";
import { runProcess } from "../../processRunner.ts";
import { GitCommandError } from "../Errors.ts";
import {
ExecuteGitInput,
@@ -39,37 +39,60 @@ function toGitCommandError(
});
}
const collectOutput = Effect.fn(function* <E>(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number,
): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder();
let bytes = 0;
let text = "";
export function normalizeGitProcessResult(
commandInput: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
input: Pick<ExecuteGitInput, "allowNonZeroExit">,
result: {
readonly stdout: string;
readonly stderr: string;
readonly code: number | null;
readonly signal: NodeJS.Signals | null;
readonly timedOut: boolean;
},
): ExecuteGitResult {
if (result.timedOut) {
throw new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
});
}
yield* Stream.runForEach(stream, (chunk) =>
Effect.gen(function* () {
bytes += chunk.byteLength;
if (bytes > maxOutputBytes) {
return yield* new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
});
}
text += decoder.decode(chunk, { stream: true });
}),
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
if (result.code === null) {
throw new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail:
result.signal !== null
? `${quoteGitCommand(commandInput.args)} terminated by signal ${result.signal}.`
: `${quoteGitCommand(commandInput.args)} terminated before reporting an exit code.`,
});
}
text += decoder.decode();
return text;
});
const exitCode = result.code;
if (!input.allowNonZeroExit && exitCode !== 0) {
const trimmedStderr = result.stderr.trim();
throw new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail:
trimmedStderr.length > 0
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
});
}
const makeGitService = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return {
code: exitCode,
stdout: result.stdout,
stderr: result.stderr,
} satisfies ExecuteGitResult;
}
const makeGitService = Effect.sync(() => {
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
@@ -78,62 +101,21 @@ const makeGitService = Effect.gen(function* () {
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const commandEffect = Effect.gen(function* () {
const child = yield* commandSpawner
.spawn(
ChildProcess.make("git", commandInput.args, {
cwd: commandInput.cwd,
...(input.env ? { env: input.env } : {}),
}),
)
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectOutput(commandInput, child.stdout, maxOutputBytes),
collectOutput(commandInput, child.stderr, maxOutputBytes),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
),
],
{ concurrency: "unbounded" },
);
if (!input.allowNonZeroExit && exitCode !== 0) {
const trimmedStderr = stderr.trim();
return yield* new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
return yield* Effect.tryPromise({
try: async () => {
const result = await runProcess("git", commandInput.args, {
cwd: commandInput.cwd,
detail:
trimmedStderr.length > 0
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
...(input.env ? { env: input.env } : {}),
timeoutMs,
allowNonZeroExit: true,
maxBufferBytes: maxOutputBytes,
outputMode: "error",
});
}
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
return normalizeGitProcessResult(commandInput, input, result);
},
catch: toGitCommandError(commandInput, "failed to run."),
});
return yield* commandEffect.pipe(
Effect.scoped,
Effect.timeoutOption(timeoutMs),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
}),
),
onSome: Effect.succeed,
}),
),
);
});
return {
+28 -4
View File
@@ -7,7 +7,7 @@
* @module GitCore
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { Effect, Scope } from "effect";
import type {
GitCheckoutInput,
GitCreateBranchInput,
@@ -24,7 +24,7 @@ import type {
import type { GitCommandError } from "../Errors.ts";
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
upstreamRef: string | null;
}
@@ -46,6 +46,16 @@ export interface GitRangeContext {
diffPatch: string;
}
export interface GitRenameBranchInput {
cwd: string;
oldBranch: string;
newBranch: string;
}
export interface GitRenameBranchResult {
branch: string;
}
/**
* GitCoreShape - Service API for low-level Git repository interactions.
*/
@@ -101,7 +111,7 @@ export interface GitCoreShape {
) => Effect.Effect<string | null, GitCommandError>;
/**
* List local branches and branch metadata.
* List local + remote branches and branch metadata.
*/
readonly listBranches: (
input: GitListBranchesInput,
@@ -124,6 +134,13 @@ export interface GitCoreShape {
*/
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
/**
* Rename an existing local branch.
*/
readonly renameBranch: (
input: GitRenameBranchInput,
) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
/**
* Create a local branch.
*/
@@ -132,12 +149,19 @@ export interface GitCoreShape {
/**
* Checkout an existing branch and refresh its upstream metadata in background.
*/
readonly checkoutBranch: (input: GitCheckoutInput) => Effect.Effect<void, GitCommandError>;
readonly checkoutBranch: (
input: GitCheckoutInput,
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
/**
* Initialize a repository in the provided directory.
*/
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
/**
* List local branch names (short format).
*/
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
}
/**
@@ -29,6 +29,7 @@ export interface GitManagerShape {
/**
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first.
*/
readonly runStackedAction: (
input: GitRunStackedActionInput,
@@ -8,6 +8,7 @@
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ChatAttachment } from "@t3tools/contracts";
import type { TextGenerationError } from "../Errors.ts";
@@ -16,11 +17,15 @@ export interface CommitMessageGenerationInput {
branch: string | null;
stagedSummary: string;
stagedPatch: string;
/** When true, the model also returns a semantic branch name for the change. */
includeBranch?: boolean;
}
export interface CommitMessageGenerationResult {
subject: string;
body: string;
/** Only present when `includeBranch` was set on the input. */
branch?: string | undefined;
}
export interface PrContentGenerationInput {
@@ -37,11 +42,22 @@ export interface PrContentGenerationResult {
body: string;
}
export interface BranchNameGenerationInput {
cwd: string;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
}
export interface BranchNameGenerationResult {
branch: string;
}
export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
}
/**
@@ -61,6 +77,13 @@ export interface TextGenerationShape {
readonly generatePrContent: (
input: PrContentGenerationInput,
) => Effect.Effect<PrContentGenerationResult, TextGenerationError>;
/**
* Generate a concise branch name from a user message.
*/
readonly generateBranchName: (
input: BranchNameGenerationInput,
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
}
/**
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
describe("imageMime", () => {
it("parses base64 data URL with mime type", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("parses base64 data URL with mime parameters", () => {
expect(parseBase64DataUrl("data:image/png;charset=utf-8;base64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("rejects non-base64 data URL", () => {
expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull();
});
it("rejects missing mime type", () => {
expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull();
});
it("parses base64 data URL with spaces in payload", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("does not read inherited keys from mime extension map", () => {
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
});
});
+79
View File
@@ -0,0 +1,79 @@
import Mime from "@effect/platform-node/Mime";
export const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
"image/avif": ".avif",
"image/bmp": ".bmp",
"image/gif": ".gif",
"image/heic": ".heic",
"image/heif": ".heif",
"image/jpeg": ".jpg",
"image/jpg": ".jpg",
"image/png": ".png",
"image/svg+xml": ".svg",
"image/tiff": ".tiff",
"image/webp": ".webp",
};
export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
".avif",
".bmp",
".gif",
".heic",
".heif",
".ico",
".jpeg",
".jpg",
".png",
".svg",
".tiff",
".webp",
]);
export function parseBase64DataUrl(
dataUrl: string,
): { readonly mimeType: string; readonly base64: string } | null {
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
if (!match) return null;
const headerParts = (match[1] ?? "")
.split(";")
.map((part) => part.trim())
.filter((part) => part.length > 0);
if (headerParts.length < 2) {
return null;
}
const trailingToken = headerParts.at(-1)?.toLowerCase();
if (trailingToken !== "base64") {
return null;
}
const mimeType = headerParts[0]?.toLowerCase();
const base64 = match[2]?.replace(/\s+/g, "");
if (!mimeType || !base64) return null;
return { mimeType, base64 };
}
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
const key = input.mimeType.toLowerCase();
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
? IMAGE_EXTENSION_BY_MIME_TYPE[key]
: undefined;
if (fromMime) {
return fromMime;
}
const fromMimeExtension = Mime.getExtension(input.mimeType);
if (fromMimeExtension && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension)) {
return fromMimeExtension;
}
const fileName = input.fileName?.trim() ?? "";
const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) {
return fileNameExtension;
}
return ".bin";
}
+1 -1
View File
@@ -8,7 +8,7 @@ import { OpenLive } from "./open";
import { Command } from "effect/unstable/cli";
import { version } from "../package.json" with { type: "json" };
import { ServerLive } from "./wsServer";
import { NetService } from "./config";
import { NetService } from "@t3tools/shared/Net";
const RuntimeLayer = Layer.empty.pipe(
Layer.provideMerge(CliConfig.layer),
+19 -4
View File
@@ -6,9 +6,10 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Command from "effect/unstable/cli/Command";
import { beforeEach } from "vitest";
import { NetService } from "@t3tools/shared/Net";
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
import { NetService, ServerConfig, type ServerConfigShape } from "./config";
import { ServerConfig, type ServerConfigShape } from "./config";
import { Open, type OpenShape } from "./open";
import { Server, type ServerShape } from "./wsServer";
@@ -33,6 +34,9 @@ const testLayer = Layer.mergeAll(
resolveStaticDir: Effect.undefined,
} satisfies CliConfigShape),
Layer.succeed(NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(0),
findAvailablePort,
}),
Layer.succeed(Server, {
@@ -49,10 +53,21 @@ const testLayer = Layer.mergeAll(
const runCli = (
args: ReadonlyArray<string>,
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
) =>
Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))),
) => {
const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_STATE_DIR: uniqueStateDir,
...env,
},
}),
),
),
);
};
beforeEach(() => {
vi.clearAllMocks();
+3 -1
View File
@@ -8,10 +8,10 @@
*/
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
import {
DEFAULT_PORT,
NetService,
resolveStaticDir,
ServerConfig,
type RuntimeMode,
@@ -21,6 +21,7 @@ import { fixPath, resolveStateDir } from "./os-jank";
import { Open } from "./open";
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
import { Server } from "./wsServer";
export class StartupError extends Data.TaggedError("StartupError")<{
@@ -197,6 +198,7 @@ const LayerLive = (input: CliInput) =>
Layer.empty.pipe(
Layer.provideMerge(makeServerRuntimeServicesLayer()),
Layer.provideMerge(makeServerProviderLayer()),
Layer.provideMerge(ProviderHealthLive),
Layer.provideMerge(SqlitePersistence.layerConfig),
Layer.provideMerge(ServerConfigLive(input)),
);
+326 -11
View File
@@ -1,28 +1,56 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import { launchDetached, resolveEditorLaunch } from "./open";
import {
isCommandAvailable,
launchDetached,
resolveBrowserLaunch,
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open";
import { Effect } from "effect";
import { assertSuccess } from "@effect/vitest/utils";
describe("resolveEditorLaunch", () => {
it.effect("returns cursor command for cursor editor", () =>
it.effect("returns commands for command-based editors", () =>
Effect.gen(function* () {
const launch = yield* resolveEditorLaunch(
const cursorLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "cursor" },
"darwin",
{ platform: "darwin" },
);
assert.deepEqual(launch, {
assert.deepEqual(cursorLaunch, {
command: "cursor",
args: ["/tmp/workspace"],
});
const vscodeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
{ platform: "darwin" },
);
assert.deepEqual(vscodeLaunch, {
command: "code",
args: ["/tmp/workspace"],
});
const zedLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "zed" },
{ platform: "darwin" },
);
assert.deepEqual(zedLaunch, {
command: "zed",
args: ["/tmp/workspace"],
});
}),
);
it.effect("uses --goto when cursor target includes line/column suffixes", () =>
it.effect("uses --goto when editor supports line/column suffixes", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
"darwin",
{ platform: "darwin" },
);
assert.deepEqual(lineOnly, {
command: "cursor",
@@ -31,12 +59,30 @@ describe("resolveEditorLaunch", () => {
const lineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
"darwin",
{ platform: "darwin" },
);
assert.deepEqual(lineAndColumn, {
command: "cursor",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
{ platform: "darwin" },
);
assert.deepEqual(vscodeLineAndColumn, {
command: "code",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const zedLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
{ platform: "darwin" },
);
assert.deepEqual(zedLineAndColumn, {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
});
}),
);
@@ -44,7 +90,7 @@ describe("resolveEditorLaunch", () => {
Effect.gen(function* () {
const launch1 = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
"darwin",
{ platform: "darwin" },
);
assert.deepEqual(launch1, {
command: "open",
@@ -53,7 +99,7 @@ describe("resolveEditorLaunch", () => {
const launch2 = yield* resolveEditorLaunch(
{ cwd: "C:\\workspace", editor: "file-manager" },
"win32",
{ platform: "win32" },
);
assert.deepEqual(launch2, {
command: "explorer",
@@ -62,7 +108,7 @@ describe("resolveEditorLaunch", () => {
const launch3 = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
"linux",
{ platform: "linux" },
);
assert.deepEqual(launch3, {
command: "xdg-open",
@@ -70,6 +116,112 @@ describe("resolveEditorLaunch", () => {
});
}),
);
it.effect("prefers linux editor shims in wsl-hosted mode when available", () =>
Effect.gen(function* () {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-linux-editor-"));
try {
fs.writeFileSync(path.join(dir, "code"), "#!/bin/sh\n", { mode: 0o755 });
const launch = yield* resolveEditorLaunch(
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
{
platform: "linux",
runtimeEnvironment: {
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu",
},
env: {
PATH: dir,
},
},
);
assert.deepEqual(launch, {
command: "code",
args: ["--goto", "/home/julius/project/src/open.ts:71:5"],
});
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}),
);
it.effect("falls back to windows editor executables in wsl-hosted mode", () =>
Effect.gen(function* () {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-win-editor-"));
try {
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
const launch = yield* resolveEditorLaunch(
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
{
platform: "linux",
runtimeEnvironment: {
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu",
},
env: {
PATH: dir,
},
translateWslPathToWindows: (target) =>
target.replace(
"/home/julius/project",
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
),
},
);
assert.deepEqual(launch, {
command: "code.exe",
args: [
"--goto",
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts:71:5",
],
});
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}),
);
it.effect("translates file-manager targets for wsl-hosted mode", () =>
Effect.gen(function* () {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-file-manager-"));
try {
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
const launch = yield* resolveEditorLaunch(
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "file-manager" },
{
platform: "linux",
runtimeEnvironment: {
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu",
},
env: {
PATH: dir,
},
translateWslPathToWindows: (target) =>
target.replace(
"/home/julius/project",
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
),
},
);
assert.deepEqual(launch, {
command: "explorer.exe",
args: ["\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts"],
});
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}),
);
});
describe("launchDetached", () => {
@@ -93,3 +245,166 @@ describe("launchDetached", () => {
}),
);
});
describe("isCommandAvailable", () => {
function withTempDir(run: (dir: string) => void): void {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-"));
try {
run(dir);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
it("resolves win32 commands with PATHEXT", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "code.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
});
});
it("returns false when a command is not on PATH", () => {
const env = {
PATH: "",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
});
it("does not treat bare files without executable extension as available on win32", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "npm"), "echo nope\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
});
});
it("appends PATHEXT for commands with non-executable extensions on win32", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "my.tool.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
});
});
it("uses platform-specific PATH delimiter for platform overrides", () => {
withTempDir((firstDir) => {
withTempDir((secondDir) => {
fs.writeFileSync(path.join(secondDir, "code.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: `${firstDir};${secondDir}`,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
});
});
});
});
describe("resolveAvailableEditors", () => {
it("returns only editors whose launch commands are available", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-"));
try {
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
const editors = resolveAvailableEditors({
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
});
assert.deepEqual(editors, ["cursor", "file-manager"]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("accepts windows editor executables in wsl-hosted mode", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-wsl-"));
try {
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
const editors = resolveAvailableEditors({
platform: "linux",
runtimeEnvironment: {
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu",
},
env: {
PATH: dir,
},
});
assert.deepEqual(editors, ["vscode", "file-manager"]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
describe("resolveBrowserLaunch", () => {
it("prefers wslview in wsl-hosted mode", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-"));
try {
fs.writeFileSync(path.join(dir, "wslview"), "#!/bin/sh\n", { mode: 0o755 });
const launch = resolveBrowserLaunch("http://localhost:3773", {
platform: "linux",
runtimeEnvironment: {
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu",
},
env: {
PATH: dir,
},
});
assert.deepEqual(launch, {
command: "wslview",
args: ["http://localhost:3773"],
});
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("falls back to explorer.exe in wsl-hosted mode", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-explorer-"));
try {
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
const launch = resolveBrowserLaunch("http://localhost:3773", {
platform: "linux",
runtimeEnvironment: {
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu",
},
env: {
PATH: dir,
},
});
assert.deepEqual(launch, {
command: "explorer.exe",
args: ["http://localhost:3773"],
});
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
+371 -38
View File
@@ -6,10 +6,13 @@
*
* @module Open
*/
import { spawn } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { EDITORS, type EditorId, type ServerRuntimeEnvironment } from "@t3tools/contracts";
import { ServiceMap, Schema, Effect, Layer } from "effect";
import { spawnDetachedProcess, spawnProcessSync } from "./processRunner";
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
// ==============================
// Definitions
@@ -30,10 +33,170 @@ interface EditorLaunch {
readonly args: ReadonlyArray<string>;
}
interface CommandAvailabilityOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
}
interface ResolveOpenOptions extends CommandAvailabilityOptions {
readonly runtimeEnvironment?: ServerRuntimeEnvironment;
readonly translateWslPathToWindows?: (target: string) => string;
}
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
function detectRuntimeEnvironment(options: ResolveOpenOptions): ServerRuntimeEnvironment {
return (
options.runtimeEnvironment ??
detectServerRuntimeEnvironment({
...(options.platform !== undefined ? { platform: options.platform } : {}),
...(options.env !== undefined ? { env: options.env } : {}),
})
);
}
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
return editorId === "cursor" && LINE_COLUMN_SUFFIX_PATTERN.test(target);
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
switch (platform) {
case "darwin":
return "open";
case "win32":
return "explorer";
default:
return "xdg-open";
}
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [];
for (const extension of windowsPathExtensions) {
candidates.push(`${command}${extension}`);
candidates.push(`${command}${extension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
export function isCommandAvailable(
command: string,
options: CommandAvailabilityOptions = {},
): boolean {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
if (command.includes("/") || command.includes("\\")) {
return commandCandidates.some((candidate) =>
isExecutableFile(candidate, platform, windowsPathExtensions),
);
}
const pathValue = resolvePathEnvironmentVariable(env);
if (pathValue.length === 0) return false;
const pathEntries = pathValue
.split(resolvePathDelimiter(platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of commandCandidates) {
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
return true;
}
}
}
return false;
}
export function resolveAvailableEditors(
options: ResolveOpenOptions = {},
): ReadonlyArray<EditorId> {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
const available: EditorId[] = [];
for (const editor of EDITORS) {
const launch = resolveOpenCommand(editor.id, {
platform,
env,
runtimeEnvironment,
});
if (launch.some((entry) => isCommandAvailable(entry, { platform, env }))) {
available.push(editor.id);
}
}
return available;
}
/**
@@ -62,58 +225,223 @@ export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
// Implementations
// ==============================
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 };
}
function stripLineColumnSuffix(value: string): string {
const { path } = splitPathAndPosition(value);
return path;
}
function formatPathWithPosition(input: {
readonly path: string;
readonly line?: string;
readonly column?: string;
}): string {
if (!input.line) {
return input.path;
}
return `${input.path}:${input.line}${input.column ? `:${input.column}` : ""}`;
}
function isWindowsPath(value: string): boolean {
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
}
function defaultTranslateWslPathToWindows(target: string): string {
const parsed = splitPathAndPosition(target);
if (parsed.path.length === 0 || !parsed.path.startsWith("/") || isWindowsPath(parsed.path)) {
return target;
}
const result = spawnProcessSync("wslpath", ["-w", parsed.path], {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
});
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
const detail = result.stderr.trim() || result.stdout.trim() || "wslpath failed";
throw new Error(detail);
}
const translatedPath = result.stdout.trim();
if (translatedPath.length === 0) {
throw new Error("wslpath returned an empty path");
}
return formatPathWithPosition({
path: translatedPath,
...(parsed.line ? { line: parsed.line } : {}),
...(parsed.column ? { column: parsed.column } : {}),
});
}
function resolveOpenCommand(
editorId: EditorId,
options: ResolveOpenOptions,
): ReadonlyArray<string> {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
const editorDef = EDITORS.find((editor) => editor.id === editorId);
if (!editorDef) {
return [];
}
if (editorId === "file-manager") {
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
return ["explorer.exe", "xdg-open"];
}
return [fileManagerCommandForPlatform(platform)];
}
if (!editorDef.command) {
return [];
}
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
return [editorDef.command, `${editorDef.command}.exe`];
}
return [editorDef.command];
}
export function resolveBrowserLaunch(
target: string,
options: ResolveOpenOptions = {},
): EditorLaunch | null {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
if (isCommandAvailable("wslview", { platform, env })) {
return { command: "wslview", args: [target] };
}
if (isCommandAvailable("explorer.exe", { platform, env })) {
return { command: "explorer.exe", args: [target] };
}
}
return null;
}
export const resolveEditorLaunch = Effect.fnUntraced(function* (
input: OpenInEditorInput,
platform: NodeJS.Platform = process.platform,
options: ResolveOpenOptions = {},
): Effect.fn.Return<EditorLaunch, OpenError> {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
if (!editorDef) {
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
}
const translateWslPathToWindows = options.translateWslPathToWindows ?? defaultTranslateWslPathToWindows;
if (editorDef.command) {
return shouldUseGotoFlag(editorDef.id, input.cwd)
? { command: editorDef.command, args: ["--goto", input.cwd] }
: { command: editorDef.command, args: [input.cwd] };
const candidateCommands = resolveOpenCommand(editorDef.id, {
platform,
env,
runtimeEnvironment,
});
const command =
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
candidateCommands[0];
if (!command) {
return yield* new OpenError({ message: `Editor command not found: ${editorDef.command}` });
}
const usesWindowsPath = runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command.endsWith(".exe");
const target = usesWindowsPath
? yield* Effect.try({
try: () => translateWslPathToWindows(input.cwd),
catch: (cause) =>
new OpenError({
message: "Failed to translate WSL path for Windows editor launch",
cause,
}),
})
: input.cwd;
return shouldUseGotoFlag(editorDef.id, target)
? { command, args: ["--goto", target] }
: { command, args: [target] };
}
if (editorDef.id !== "file-manager") {
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
}
switch (platform) {
case "darwin":
return { command: "open", args: [input.cwd] };
case "win32":
return { command: "explorer", args: [input.cwd] };
default:
return { command: "xdg-open", args: [input.cwd] };
const candidateCommands = resolveOpenCommand(editorDef.id, {
platform,
env,
runtimeEnvironment,
});
const command =
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
candidateCommands[0];
if (!command) {
return yield* new OpenError({ message: "Editor command not found: file-manager" });
}
let target = stripLineColumnSuffix(input.cwd);
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command === "explorer.exe") {
target = yield* Effect.try({
try: () => stripLineColumnSuffix(translateWslPathToWindows(target)),
catch: (cause) =>
new OpenError({
message: "Failed to translate WSL path for Windows file manager launch",
cause,
}),
});
}
return { command, args: [target] };
});
export const launchDetached = (launch: EditorLaunch) =>
Effect.callback<void, OpenError>((resume) => {
let child;
try {
child = spawn(launch.command, [...launch.args], {
detached: true,
stdio: "ignore",
});
} catch (error) {
return resume(
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
);
}
Effect.tryPromise({
try: async () => {
if (!isCommandAvailable(launch.command)) {
throw new OpenError({ message: `Editor command not found: ${launch.command}` });
}
const handleSpawn = () => {
child.unref();
resume(Effect.void);
};
child.once("spawn", handleSpawn);
child.once("error", (cause) =>
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
);
await spawnDetachedProcess(launch.command, [...launch.args]);
},
catch: (cause) =>
Schema.is(OpenError)(cause)
? cause
: new OpenError({ message: "failed to spawn detached process", cause }),
});
const make = Effect.gen(function* () {
@@ -123,11 +451,16 @@ const make = Effect.gen(function* () {
});
return {
openBrowser: (target) =>
Effect.tryPromise({
openBrowser: (target) => {
const launch = resolveBrowserLaunch(target);
if (launch) {
return launchDetached(launch);
}
return Effect.tryPromise({
try: () => open.default(target),
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
}),
});
},
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
} satisfies OpenShape;
});
@@ -11,6 +11,7 @@ import {
ProjectId,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
@@ -36,10 +37,12 @@ import {
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
import { ServerConfig } from "../../config.ts";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd = cwd) {
@@ -91,7 +94,7 @@ function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd
async function waitForThread(
engine: OrchestrationEngineShape,
predicate: (thread: {
latestTurnId: string | null;
latestTurn: { turnId: string } | null;
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
activities: ReadonlyArray<{ kind: string }>;
}) => boolean,
@@ -99,7 +102,7 @@ async function waitForThread(
) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<{
latestTurnId: string | null;
latestTurn: { turnId: string } | null;
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
activities: ReadonlyArray<{ kind: string }>;
}> => {
@@ -231,11 +234,13 @@ describe("CheckpointReactor", () => {
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
const layer = CheckpointReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(checkpointStoreLayer),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
runtime = ManagedRuntime.make(layer);
@@ -317,6 +322,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -332,7 +339,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-1"),
turnId: asProviderTurnId("turn-1"),
});
await waitForGitRefExists(
harness.cwd,
@@ -347,14 +354,14 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-1"),
turnId: asProviderTurnId("turn-1"),
status: "completed",
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
const thread = await waitForThread(
harness.engine,
(entry) => entry.latestTurnId === "turn-1" && entry.checkpoints.length === 1,
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(
@@ -379,6 +386,83 @@ describe("CheckpointReactor", () => {
).toBe("v2\n");
});
it("ignores auxiliary thread turn completion while primary turn is active", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: asTurnId("turn-main"),
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
harness.provider.emit({
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-main"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-main"),
});
await waitForGitRefExists(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
);
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
harness.provider.emit({
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-aux"),
turnId: asProviderTurnId("turn-aux"),
status: "completed",
});
await Effect.runPromise(Effect.sleep("40 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
expect(midThread?.checkpoints).toHaveLength(0);
harness.provider.emit({
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-main"),
status: "completed",
});
const thread = await waitForThread(
harness.engine,
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
});
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
@@ -394,6 +478,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -409,7 +495,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-missing-baseline"),
turnId: asProviderTurnId("turn-missing-baseline"),
status: "completed",
});
@@ -445,6 +531,8 @@ describe("CheckpointReactor", () => {
text: "start turn",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: new Date().toISOString(),
}),
);
@@ -481,6 +569,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-missing"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: asTurnId("turn-missing-cwd"),
lastError: null,
updatedAt: createdAt,
@@ -497,7 +587,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-missing"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
turnId: asTurnId("turn-missing-cwd"),
turnId: asProviderTurnId("turn-missing-cwd"),
status: "completed",
});
@@ -529,6 +619,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -544,7 +636,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-3"),
turnId: asProviderTurnId("turn-3"),
turnCount: 3,
status: "completed",
});
@@ -580,6 +672,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -595,7 +689,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-runtime-failure"),
turnId: asProviderTurnId("turn-runtime-failure"),
turnCount: 1,
status: "completed",
});
@@ -607,7 +701,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-after-runtime-failure"),
turnId: asProviderTurnId("turn-after-runtime-failure"),
});
await waitForGitRefExists(
@@ -634,6 +728,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -684,7 +780,7 @@ describe("CheckpointReactor", () => {
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
expect(thread.latestTurnId).toBe("turn-1");
expect(thread.latestTurn?.turnId).toBe("turn-1");
expect(thread.checkpoints).toHaveLength(1);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
@@ -713,6 +809,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -3,6 +3,7 @@ import {
EventId,
MessageId,
ProviderSessionId,
ProviderThreadId,
ThreadId,
TurnId,
type OrchestrationEvent,
@@ -36,6 +37,17 @@ function toTurnId(value: string | undefined): TurnId | null {
return value === undefined ? null : TurnId.makeUnsafe(value);
}
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
}
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
if (left === null || left === undefined || right === null || right === undefined) {
return false;
}
return left === right;
}
function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
switch (status) {
case "failed":
@@ -173,6 +185,21 @@ const make = Effect.gen(function* () {
return;
}
const projectedProviderThreadId = thread.session?.providerThreadId ?? null;
const eventProviderThreadId = toProviderThreadId(event.threadId);
if (
projectedProviderThreadId !== null &&
eventProviderThreadId !== null &&
!sameId(projectedProviderThreadId, eventProviderThreadId)
) {
return;
}
// When a primary turn is active, only that turn may produce completion checkpoints.
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
return;
}
if (thread.checkpoints.some((checkpoint) => checkpoint.turnId === turnId)) {
return;
}
@@ -25,6 +25,8 @@ import {
OrchestrationProjectionPipeline,
type OrchestrationProjectionPipelineShape,
} from "../Services/ProjectionPipeline.ts";
import { ServerConfig } from "../../config.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
@@ -37,6 +39,8 @@ async function createOrchestrationSystem() {
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(orchestrationLayer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
@@ -92,6 +96,8 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt,
}),
);
@@ -308,6 +314,8 @@ describe("OrchestrationEngine", () => {
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
),
);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
@@ -428,6 +436,8 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request" as const,
sandboxMode: "workspace-write" as const,
createdAt,
};
@@ -586,6 +596,8 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now(),
}),
),
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,10 @@
import { ApprovalRequestId, type OrchestrationEvent } from "@t3tools/contracts";
import { Effect, Layer, Option, Stream } from "effect";
import {
ApprovalRequestId,
type ChatAttachment,
type OrchestrationEvent,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
@@ -27,10 +32,17 @@ import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
import { ServerConfig } from "../../config.ts";
import {
OrchestrationProjectionPipeline,
type OrchestrationProjectionPipelineShape,
} from "../Services/ProjectionPipeline.ts";
import {
attachmentRelativePath,
parseAttachmentIdFromRelativePath,
parseThreadSegmentFromAttachmentId,
toSafeThreadAttachmentSegment,
} from "../../attachmentStore.ts";
export const ORCHESTRATION_PROJECTOR_NAMES = {
projects: "projection.projects",
@@ -48,9 +60,23 @@ type ProjectorName =
interface ProjectorDefinition {
readonly name: ProjectorName;
readonly apply: (event: OrchestrationEvent) => Effect.Effect<void, ProjectionRepositoryError>;
readonly apply: (
event: OrchestrationEvent,
attachmentSideEffects: AttachmentSideEffects,
) => Effect.Effect<void, ProjectionRepositoryError>;
}
interface AttachmentSideEffects {
readonly deletedThreadIds: Set<string>;
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
}
const materializeAttachmentsForProjection = Effect.fn(
(input: {
readonly attachments: ReadonlyArray<ChatAttachment>;
}) => Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
);
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
if (typeof payload !== "object" || payload === null) {
return null;
@@ -163,6 +189,130 @@ function retainProjectionActivitiesAfterRevert(
);
}
function collectThreadAttachmentRelativePaths(
threadId: string,
messages: ReadonlyArray<ProjectionThreadMessage>,
): Set<string> {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
return new Set();
}
const relativePaths = new Set<string>();
for (const message of messages) {
for (const attachment of message.attachments ?? []) {
if (attachment.type !== "image") {
continue;
}
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
continue;
}
relativePaths.add(attachmentRelativePath(attachment));
}
}
return relativePaths;
}
const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSideEffects) {
const serverConfig = yield* Effect.service(ServerConfig);
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
const path = yield* Effect.service(Path.Path);
const attachmentsRootDir = path.join(serverConfig.stateDir, "attachments");
yield* Effect.forEach(
sideEffects.deletedThreadIds,
(threadId) =>
Effect.gen(function* () {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
threadId,
});
return;
}
const entries = yield* fileSystem
.readDirectory(attachmentsRootDir, { recursive: false })
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
yield* Effect.forEach(
entries,
(entry) =>
Effect.gen(function* () {
const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) {
return;
}
const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);
if (!attachmentId) {
return;
}
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
return;
}
yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {
force: true,
});
}),
{ concurrency: 1 },
);
}),
{ concurrency: 1 },
);
yield* Effect.forEach(
sideEffects.prunedThreadRelativePaths.entries(),
([threadId, keptThreadRelativePaths]) => {
if (sideEffects.deletedThreadIds.has(threadId)) {
return Effect.void;
}
return Effect.gen(function* () {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
return;
}
const entries = yield* fileSystem
.readDirectory(attachmentsRootDir, { recursive: false })
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
yield* Effect.forEach(
entries,
(entry) =>
Effect.gen(function* () {
const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
if (relativePath.length === 0 || relativePath.includes("/")) {
return;
}
const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
if (!attachmentId) {
return;
}
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
return;
}
const absolutePath = path.join(attachmentsRootDir, relativePath);
const fileInfo = yield* fileSystem
.stat(absolutePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
return;
}
if (!keptThreadRelativePaths.has(relativePath)) {
yield* fileSystem.remove(absolutePath, { force: true });
}
}),
{ concurrency: 1 },
);
});
},
{ concurrency: 1 },
);
});
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const eventStore = yield* OrchestrationEventStore;
@@ -175,7 +325,11 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
const projectionTurnRepository = yield* ProjectionTurnRepository;
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
const applyProjectsProjection: ProjectorDefinition["apply"] = (event) =>
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
Effect.gen(function* () {
switch (event.type) {
case "project.created":
@@ -233,7 +387,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadsProjection: ProjectorDefinition["apply"] = (event) =>
const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.created":
@@ -272,6 +426,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
case "thread.deleted": {
attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
@@ -351,7 +506,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (event) =>
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (
event,
attachmentSideEffects,
) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.message-sent": {
@@ -367,12 +525,19 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
: existingMessage && event.payload.text.length === 0
? existingMessage.text
: event.payload.text;
const nextAttachments =
event.payload.attachments !== undefined
? yield* materializeAttachmentsForProjection({
attachments: event.payload.attachments,
})
: existingMessage?.attachments;
yield* projectionThreadMessageRepository.upsert({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
turnId: event.payload.turnId,
role: event.payload.role,
text: nextText,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
isStreaming: event.payload.streaming,
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
updatedAt: event.payload.updatedAt,
@@ -406,6 +571,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {
concurrency: 1,
}).pipe(Effect.asVoid);
attachmentSideEffects.prunedThreadRelativePaths.set(
event.payload.threadId,
collectThreadAttachmentRelativePaths(event.payload.threadId, keptRows),
);
return;
}
@@ -414,7 +583,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (event) =>
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.activity-appended":
@@ -462,7 +634,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (event) =>
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
if (event.type !== "thread.session-set") {
return;
@@ -473,13 +648,18 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
providerName: event.payload.session.providerName,
providerSessionId: event.payload.session.providerSessionId,
providerThreadId: event.payload.session.providerThreadId,
approvalPolicy: event.payload.session.approvalPolicy,
sandboxMode: event.payload.session.sandboxMode,
activeTurnId: event.payload.session.activeTurnId,
lastError: event.payload.session.lastError,
updatedAt: event.payload.session.updatedAt,
});
});
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (event) =>
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.turn-start-requested": {
@@ -712,7 +892,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (event) =>
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.activity-appended": {
@@ -835,17 +1018,35 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
];
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
sql.withTransaction(
projector.apply(event).pipe(
Effect.flatMap(() =>
projectionStateRepository.upsert({
Effect.gen(function* () {
const attachmentSideEffects: AttachmentSideEffects = {
deletedThreadIds: new Set<string>(),
prunedThreadRelativePaths: new Map<string, Set<string>>(),
};
yield* sql.withTransaction(
projector.apply(event, attachmentSideEffects).pipe(
Effect.flatMap(() =>
projectionStateRepository.upsert({
projector: projector.name,
lastAppliedSequence: event.sequence,
updatedAt: event.occurredAt,
}),
),
),
);
yield* runAttachmentSideEffects(attachmentSideEffects).pipe(
Effect.catch((cause) =>
Effect.logWarning("failed to apply projected attachment side-effects", {
projector: projector.name,
lastAppliedSequence: event.sequence,
updatedAt: event.occurredAt,
sequence: event.sequence,
eventType: event.type,
cause,
}),
),
),
);
);
});
const bootstrapProjector = (projector: ProjectorDefinition) =>
projectionStateRepository
@@ -867,6 +1068,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
concurrency: 1,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.provideService(ServerConfig, serverConfig),
Effect.asVoid,
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
@@ -878,6 +1082,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
bootstrapProjector,
{ concurrency: 1 },
).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.provideService(ServerConfig, serverConfig),
Effect.asVoid,
Effect.tap(() =>
Effect.log("orchestration projection pipeline bootstrapped").pipe(
@@ -899,6 +1106,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
OrchestrationProjectionPipeline,
makeOrchestrationProjectionPipeline,
).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ProjectionProjectRepositoryLive),
Layer.provideMerge(ProjectionThreadRepositoryLive),
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
@@ -143,6 +143,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
provider_name,
provider_session_id,
provider_thread_id,
approval_policy,
sandbox_mode,
active_turn_id,
last_error,
updated_at
@@ -153,6 +155,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'codex',
'provider-session-1',
'provider-thread-1',
'on-request',
'workspace-write',
'turn-1',
NULL,
'2026-02-24T00:00:07.000Z'
@@ -239,7 +243,14 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
model: "gpt-5-codex",
branch: null,
worktreePath: null,
latestTurnId: asTurnId("turn-1"),
latestTurn: {
turnId: asTurnId("turn-1"),
state: "completed",
requestedAt: "2026-02-24T00:00:08.000Z",
startedAt: "2026-02-24T00:00:08.000Z",
completedAt: "2026-02-24T00:00:08.000Z",
assistantMessageId: asMessageId("message-1"),
},
createdAt: "2026-02-24T00:00:02.000Z",
updatedAt: "2026-02-24T00:00:03.000Z",
deletedAt: null,
@@ -282,6 +293,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
providerName: "codex",
providerSessionId: asProviderSessionId("provider-session-1"),
providerThreadId: asProviderThreadId("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: asTurnId("turn-1"),
lastError: null,
updatedAt: "2026-02-24T00:00:07.000Z",
@@ -1,8 +1,13 @@
import {
ChatAttachment,
IsoDateTime,
MessageId,
OrchestrationCheckpointFile,
OrchestrationReadModel,
ProjectScript,
TurnId,
type OrchestrationCheckpointSummary,
type OrchestrationLatestTurn,
type OrchestrationMessage,
type OrchestrationProject,
type OrchestrationSession,
@@ -38,12 +43,13 @@ const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
}),
);
const ProjectionThreadDbRowSchema = ProjectionThread;
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
Struct.assign({
isStreaming: Schema.Number,
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
}),
);
const ProjectionThreadDbRowSchema = ProjectionThread;
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
Struct.assign({
payload: Schema.fromJsonString(Schema.Unknown),
@@ -55,6 +61,15 @@ const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
}),
);
const ProjectionLatestTurnDbRowSchema = Schema.Struct({
threadId: ProjectionThread.fields.threadId,
turnId: TurnId,
state: Schema.String,
requestedAt: IsoDateTime,
startedAt: Schema.NullOr(IsoDateTime),
completedAt: Schema.NullOr(IsoDateTime),
assistantMessageId: Schema.NullOr(MessageId),
});
const ProjectionStateDbRowSchema = ProjectionState;
const REQUIRED_SNAPSHOT_PROJECTORS = [
@@ -158,6 +173,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
turn_id AS "turnId",
role,
text,
attachments_json AS "attachments",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -196,6 +212,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
provider_name AS "providerName",
provider_session_id AS "providerSessionId",
provider_thread_id AS "providerThreadId",
approval_policy AS "approvalPolicy",
sandbox_mode AS "sandboxMode",
active_turn_id AS "activeTurnId",
last_error AS "lastError",
updated_at AS "updatedAt"
@@ -224,6 +242,25 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listLatestTurnRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionLatestTurnDbRowSchema,
execute: () =>
sql`
SELECT
thread_id AS "threadId",
turn_id AS "turnId",
state,
requested_at AS "requestedAt",
started_at AS "startedAt",
completed_at AS "completedAt",
assistant_message_id AS "assistantMessageId"
FROM projection_turns
WHERE turn_id IS NOT NULL
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
`,
});
const listProjectionStateRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionStateDbRowSchema,
@@ -248,6 +285,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
activityRows,
sessionRows,
checkpointRows,
latestTurnRows,
stateRows,
] = yield* Effect.all([
listProjectRows(undefined).pipe(
@@ -298,6 +336,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query",
"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows",
),
),
),
listProjectionStateRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -312,6 +358,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
const sessionsByThread = new Map<string, OrchestrationSession>();
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
let updatedAt: string | null = null;
@@ -332,6 +379,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
id: row.messageId,
role: row.role,
text: row.text,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
turnId: row.turnId,
streaming: row.isStreaming === 1,
createdAt: row.createdAt,
@@ -370,6 +418,34 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
checkpointsByThread.set(row.threadId, threadCheckpoints);
}
for (const row of latestTurnRows) {
updatedAt = maxIso(updatedAt, row.requestedAt);
if (row.startedAt !== null) {
updatedAt = maxIso(updatedAt, row.startedAt);
}
if (row.completedAt !== null) {
updatedAt = maxIso(updatedAt, row.completedAt);
}
if (latestTurnByThread.has(row.threadId)) {
continue;
}
latestTurnByThread.set(row.threadId, {
turnId: row.turnId,
state:
row.state === "error"
? "error"
: row.state === "interrupted"
? "interrupted"
: row.state === "completed"
? "completed"
: "running",
requestedAt: row.requestedAt,
startedAt: row.startedAt,
completedAt: row.completedAt,
assistantMessageId: row.assistantMessageId,
});
}
for (const row of sessionRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
sessionsByThread.set(row.threadId, {
@@ -378,6 +454,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
providerName: row.providerName,
providerSessionId: row.providerSessionId,
providerThreadId: row.providerThreadId,
approvalPolicy: row.approvalPolicy,
sandboxMode: row.sandboxMode,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
updatedAt: row.updatedAt,
@@ -402,7 +480,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
model: row.model,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurnId: row.latestTurnId,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
@@ -1,3 +1,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import {
ApprovalRequestId,
@@ -13,6 +17,8 @@ import {
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../../git/Errors.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
@@ -20,11 +26,14 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
@@ -56,6 +65,7 @@ describe("ProviderCommandReactor", () => {
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
const createdStateDirs = new Set<string>();
afterEach(async () => {
if (scope) {
@@ -66,21 +76,29 @@ describe("ProviderCommandReactor", () => {
await runtime.dispose();
}
runtime = null;
for (const stateDir of createdStateDirs) {
fs.rmSync(stateDir, { recursive: true, force: true });
}
createdStateDirs.clear();
});
async function createHarness() {
async function createHarness(input?: { readonly stateDir?: string }) {
const now = new Date().toISOString();
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
createdStateDirs.add(stateDir);
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
const startSession = vi.fn((_: unknown, __: unknown) =>
Effect.succeed({
sessionId: asSessionId("sess-1"),
let nextSessionIndex = 1;
const startSession = vi.fn((_: unknown, __: unknown) => {
const sessionIndex = nextSessionIndex++;
return Effect.succeed({
sessionId: asSessionId(`sess-${sessionIndex}`),
provider: "codex" as const,
status: "ready" as const,
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
threadId: ProviderThreadId.makeUnsafe(`provider-thread-${sessionIndex}`),
createdAt: now,
updatedAt: now,
}),
);
});
});
const sendTurn = vi.fn((_: unknown) =>
Effect.succeed({
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
@@ -90,6 +108,16 @@ describe("ProviderCommandReactor", () => {
const interruptTurn = vi.fn((_: unknown) => Effect.void);
const respondToRequest = vi.fn((_: unknown) => Effect.void);
const stopSession = vi.fn((_: unknown) => Effect.void);
const renameBranch = vi.fn((_: unknown) =>
Effect.succeed({
branch: "t3code/generated-name",
}),
);
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>(() =>
Effect.succeed({
branch: "generated-name",
}),
);
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: ProviderServiceShape = {
@@ -113,8 +141,15 @@ describe("ProviderCommandReactor", () => {
const layer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(Layer.succeed(ProviderService, service)),
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
Layer.provideMerge(
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
Layer.provideMerge(NodeServices.layer),
);
runtime = ManagedRuntime.make(layer);
const runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
scope = await Effect.runPromise(Scope.make("sequential"));
@@ -153,6 +188,9 @@ describe("ProviderCommandReactor", () => {
interruptTurn,
respondToRequest,
stopSession,
renameBranch,
generateBranchName,
stateDir,
};
}
@@ -171,6 +209,8 @@ describe("ProviderCommandReactor", () => {
text: "hello reactor",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
@@ -181,11 +221,422 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
model: "gpt-5-codex",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerSessionId).toBe("sess-1");
expect(thread?.session?.approvalPolicy).toBe("on-request");
expect(thread?.session?.sandboxMode).toBe("workspace-write");
});
it("generates and renames temporary worktree branch on first turn", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/89abc123",
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-worktree-rename"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-worktree-rename"),
role: "user",
text: "Fix visual bug from screenshot",
attachments: [
{
type: "image",
id: "thread-1-att-rename",
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
await waitFor(() => harness.renameBranch.mock.calls.length === 1);
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
message: "Fix visual bug from screenshot",
attachments: [
{
type: "image",
id: "thread-1-att-rename",
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
});
expect(harness.renameBranch.mock.calls[0]?.[0]).toEqual({
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
oldBranch: "t3code/89abc123",
newBranch: "t3code/generated-name",
});
await waitFor(() => {
const readModel = Effect.runSync(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return thread?.branch === "t3code/generated-name";
});
});
it("passes persisted attachment references to branch generation and turn start", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-persisted"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/abcdef12",
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-persisted-attachments"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-persisted-attachments"),
role: "user",
text: "Fix visual bug from screenshot",
attachments: [
{
type: "image",
id: "thread-1-att-persisted",
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
cwd: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
message: "Fix visual bug from screenshot",
attachments: [
{
type: "image",
id: "thread-1-att-persisted",
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
attachments: [
{
type: "image",
id: "thread-1-att-persisted",
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
});
});
it("skips worktree branch generation after the first user turn", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/1234abcd",
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-1234abcd",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-first"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-first"),
role: "user",
text: "first",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-second"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-second"),
role: "user",
text: "second",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.generateBranchName.mock.calls.length).toBe(1);
expect(harness.renameBranch.mock.calls.length).toBe(1);
});
it("skips worktree rename when branch-name generation fails", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.generateBranchName.mockImplementationOnce(() =>
Effect.fail(
new TextGenerationError({
operation: "generateBranchName",
detail: "model returned invalid payload",
}),
),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-null"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/0000abcd",
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-0000abcd",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-null-branch"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-null-branch"),
role: "user",
text: "Fix visual regression",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
await Effect.runPromise(Effect.sleep("20 millis"));
expect(harness.renameBranch.mock.calls.length).toBe(0);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.branch).toBe("t3code/0000abcd");
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-unchanged-1"),
role: "user",
text: "first",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-unchanged-2"),
role: "user",
text: "second",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls.length).toBe(1);
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts the provider session when runtime mode changes", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-runtime-mode-1"),
role: "user",
text: "first",
attachments: [],
},
approvalPolicy: "never",
sandboxMode: "danger-full-access",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-runtime-mode-2"),
role: "user",
text: "second",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.stopSession.mock.calls.length === 1);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ sessionId: asSessionId("sess-1") });
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
resumeThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
});
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
sessionId: asSessionId("sess-2"),
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerSessionId).toBe("sess-2");
expect(thread?.session?.approvalPolicy).toBe("on-request");
expect(thread?.session?.sandboxMode).toBe("workspace-write");
});
it("does not stop the active session when restart fails before rebind", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-restart-failure-1"),
role: "user",
text: "first",
attachments: [],
},
approvalPolicy: "never",
sandboxMode: "danger-full-access",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
harness.startSession.mockImplementationOnce(
(_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-restart-failure-2"),
role: "user",
text: "second",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await Effect.runPromise(Effect.sleep("30 millis"));
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(1);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerSessionId).toBe("sess-1");
expect(thread?.session?.approvalPolicy).toBe("never");
expect(thread?.session?.sandboxMode).toBe("danger-full-access");
});
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
@@ -203,6 +654,8 @@ describe("ProviderCommandReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: asTurnId("turn-1"),
lastError: null,
updatedAt: now,
@@ -242,6 +695,8 @@ describe("ProviderCommandReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: now,
@@ -284,6 +739,8 @@ describe("ProviderCommandReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: now,
@@ -3,14 +3,20 @@ import {
CommandId,
EventId,
type OrchestrationEvent,
type ProviderApprovalPolicy,
type ProviderKind,
type ProviderSandboxMode,
type OrchestrationSession,
type ThreadId,
type ProviderSession,
type ProviderThreadId,
type TurnId,
} from "@t3tools/contracts";
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
@@ -60,10 +66,43 @@ const serverCommandId = (tag: string): CommandId =>
const HANDLED_TURN_START_KEY_MAX = 10_000;
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
const WORKTREE_BRANCH_PREFIX = "t3code";
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
function isTemporaryWorktreeBranch(branch: string): boolean {
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
}
function buildGeneratedWorktreeBranchName(raw: string): string {
const normalized = raw
.trim()
.toLowerCase()
.replace(/^refs\/heads\//, "")
.replace(/['"`]/g, "");
const withoutPrefix = normalized.startsWith(`${WORKTREE_BRANCH_PREFIX}/`)
? normalized.slice(`${WORKTREE_BRANCH_PREFIX}/`.length)
: normalized;
const branchFragment = withoutPrefix
.replace(/[^a-z0-9/_-]+/g, "-")
.replace(/\/+/g, "/")
.replace(/-+/g, "-")
.replace(/^[./_-]+|[./_-]+$/g, "")
.slice(0, 64)
.replace(/[./_-]+$/g, "");
const safeFragment = branchFragment.length > 0 ? branchFragment : "update";
return `${WORKTREE_BRANCH_PREFIX}/${safeFragment}`;
}
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const git = yield* GitCore;
const textGeneration = yield* TextGeneration;
const handledTurnStartKeys = yield* Cache.make<string, true>({
capacity: HANDLED_TURN_START_KEY_MAX,
timeToLive: HANDLED_TURN_START_KEY_TTL,
@@ -128,6 +167,10 @@ const make = Effect.gen(function* () {
const ensureSessionForThread = Effect.fnUntraced(function* (
threadId: ThreadId,
createdAt: string,
options?: {
readonly approvalPolicy?: ProviderApprovalPolicy;
readonly sandboxMode?: ProviderSandboxMode;
},
) {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
@@ -135,11 +178,10 @@ const make = Effect.gen(function* () {
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
}
const existingSessionId = thread.session?.providerSessionId;
if (existingSessionId) {
return existingSessionId;
}
const desiredApprovalPolicy =
options?.approvalPolicy ?? thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY;
const desiredSandboxMode =
options?.sandboxMode ?? thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE;
const preferredProvider: ProviderKind | undefined =
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
? thread.session.providerName
@@ -149,28 +191,65 @@ const make = Effect.gen(function* () {
projects: readModel.projects,
});
const startedSession = yield* providerService.startSession(threadId, {
...(preferredProvider ? { provider: preferredProvider } : {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(thread.model ? { model: thread.model } : {}),
});
const startProviderSession = (resumeThreadId?: ProviderThreadId | null) =>
providerService.startSession(threadId, {
...(preferredProvider ? { provider: preferredProvider } : {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(thread.model ? { model: thread.model } : {}),
...(resumeThreadId ? { resumeThreadId } : {}),
approvalPolicy: desiredApprovalPolicy,
sandboxMode: desiredSandboxMode,
});
yield* setThreadSession({
threadId,
session: {
const bindSessionToThread = (session: ProviderSession) =>
setThreadSession({
threadId,
status: mapProviderSessionStatusToOrchestrationStatus(startedSession.status),
providerName: startedSession.provider,
providerSessionId: startedSession.sessionId,
providerThreadId: startedSession.threadId ?? null,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: startedSession.lastError ?? null,
updatedAt: startedSession.updatedAt,
},
createdAt,
});
session: {
threadId,
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
providerName: session.provider,
providerSessionId: session.sessionId,
providerThreadId: session.threadId ?? null,
approvalPolicy: desiredApprovalPolicy,
sandboxMode: desiredSandboxMode,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: session.lastError ?? null,
updatedAt: session.updatedAt,
},
createdAt,
});
const existingSessionId = thread.session?.providerSessionId;
if (existingSessionId) {
const approvalPolicyChanged =
options?.approvalPolicy !== undefined &&
options.approvalPolicy !== thread.session?.approvalPolicy;
const sandboxModeChanged =
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
if (!approvalPolicyChanged && !sandboxModeChanged) {
return existingSessionId;
}
const restartedSession = yield* startProviderSession(
thread.session?.providerThreadId ?? null,
);
yield* bindSessionToThread(restartedSession);
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to stop superseded provider session", {
threadId,
sessionId: existingSessionId,
cause: Cause.pretty(cause),
}),
),
);
return restartedSession.sessionId;
}
const startedSession = yield* startProviderSession();
yield* bindSessionToThread(startedSession);
return startedSession.sessionId;
});
@@ -180,13 +259,18 @@ const make = Effect.gen(function* () {
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly model?: string;
readonly effort?: string;
readonly approvalPolicy: ProviderApprovalPolicy;
readonly sandboxMode: ProviderSandboxMode;
readonly createdAt: string;
}) {
const thread = yield* resolveThread(input.threadId);
if (!thread) {
return;
}
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt);
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt, {
approvalPolicy: input.approvalPolicy,
sandboxMode: input.sandboxMode,
});
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
@@ -199,6 +283,74 @@ const make = Effect.gen(function* () {
});
});
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly branch: string | null;
readonly worktreePath: string | null;
readonly messageId: string;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
}) {
if (!input.branch || !input.worktreePath) {
return;
}
if (!isTemporaryWorktreeBranch(input.branch)) {
return;
}
const thread = yield* resolveThread(input.threadId);
if (!thread) {
return;
}
const userMessages = thread.messages.filter((message) => message.role === "user");
if (userMessages.length !== 1 || userMessages[0]?.id !== input.messageId) {
return;
}
const oldBranch = input.branch;
const cwd = input.worktreePath;
const attachments = input.attachments ?? [];
yield* textGeneration
.generateBranchName({
cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
})
.pipe(
Effect.catch((error) =>
Effect.logWarning(
"provider command reactor failed to generate worktree branch name; skipping rename",
{ threadId: input.threadId, cwd, oldBranch, reason: error.message },
),
),
Effect.flatMap((generated) => {
if (!generated) return Effect.void;
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
if (targetBranch === oldBranch) return Effect.void;
return Effect.flatMap(
git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
(renamed) =>
orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("worktree-branch-rename"),
threadId: input.threadId,
branch: renamed.branch,
worktreePath: cwd,
}),
);
}),
Effect.catchCause((cause) =>
Effect.logWarning(
"provider command reactor failed to generate or rename worktree branch",
{ threadId: input.threadId, cwd, oldBranch, cause: Cause.pretty(cause) },
),
),
);
});
const processTurnStartRequested = Effect.fnUntraced(function* (
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
) {
@@ -225,12 +377,23 @@ const make = Effect.gen(function* () {
return;
}
yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
threadId: event.payload.threadId,
branch: thread.branch,
worktreePath: thread.worktreePath,
messageId: message.id,
messageText: message.text,
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
}).pipe(Effect.forkScoped);
yield* sendTurnForThread({
threadId: event.payload.threadId,
messageText: message.text,
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.effort !== undefined ? { effort: event.payload.effort } : {}),
approvalPolicy: event.payload.approvalPolicy,
sandboxMode: event.payload.sandboxMode,
createdAt: event.payload.createdAt,
});
});
@@ -307,6 +470,8 @@ const make = Effect.gen(function* () {
providerName: thread.session?.providerName ?? null,
providerSessionId: null,
providerThreadId: null,
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
activeTurnId: null,
lastError: thread.session?.lastError ?? null,
updatedAt: now,
@@ -28,9 +28,12 @@ import {
type OrchestrationEngineShape,
} from "../Services/OrchestrationEngine.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ServerConfig } from "../../config.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
@@ -120,6 +123,8 @@ describe("ProviderRuntimeIngestion", () => {
const layer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
@@ -164,6 +169,8 @@ describe("ProviderRuntimeIngestion", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
@@ -218,6 +225,116 @@ describe("ProviderRuntimeIngestion", () => {
expect(thread.session?.lastError).toBe("turn failed");
});
it("ignores auxiliary turn completions from a different provider thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-primary"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
threadId: asProviderThreadId("provider-thread-1"),
turnId: asProviderTurnId("turn-primary"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-primary",
);
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-aux"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: asProviderThreadId("provider-thread-aux"),
turnId: asProviderTurnId("turn-aux"),
status: "completed",
});
await Effect.runPromise(Effect.sleep("40 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
expect(midThread?.session?.status).toBe("running");
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-primary"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: asProviderThreadId("provider-thread-1"),
turnId: asProviderTurnId("turn-primary"),
status: "completed",
});
await waitForThread(
harness.engine,
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
);
});
it("ignores non-active turn completion when runtime omits thread id", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-guarded"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-guarded-main"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-guarded-main",
);
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-guarded-other"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
turnId: asProviderTurnId("turn-guarded-other"),
status: "completed",
});
await Effect.runPromise(Effect.sleep("40 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
expect(midThread?.session?.status).toBe("running");
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-guarded-main"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
turnId: asProviderTurnId("turn-guarded-main"),
status: "completed",
});
await waitForThread(
harness.engine,
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
);
});
it("maps message delta/completed into finalized assistant messages", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -291,7 +408,9 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(Effect.sleep("30 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
expect(midThread?.messages.some((message) => message.id === "assistant:item-buffered")).toBe(
false,
);
@@ -306,10 +425,10 @@ describe("ProviderRuntimeIngestion", () => {
itemId: asItemId("item-buffered"),
});
const thread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some((message) => message.id === "assistant:item-buffered" && !message.streaming),
const thread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message) => message.id === "assistant:item-buffered" && !message.streaming,
),
);
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffered");
expect(message?.text).toBe("buffer me");
@@ -332,6 +451,8 @@ describe("ProviderRuntimeIngestion", () => {
attachments: [],
},
assistantDeliveryMode: "streaming",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
@@ -363,15 +484,13 @@ describe("ProviderRuntimeIngestion", () => {
delta: "hello live",
});
const liveThread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some(
(message) =>
message.id === "assistant:item-streaming-mode" &&
message.streaming &&
message.text === "hello live",
),
const liveThread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message) =>
message.id === "assistant:item-streaming-mode" &&
message.streaming &&
message.text === "hello live",
),
);
const liveMessage = liveThread.messages.find(
(entry) => entry.id === "assistant:item-streaming-mode",
@@ -388,12 +507,10 @@ describe("ProviderRuntimeIngestion", () => {
itemId: asItemId("item-streaming-mode"),
});
const finalThread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some(
(message) => message.id === "assistant:item-streaming-mode" && !message.streaming,
),
const finalThread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message) => message.id === "assistant:item-streaming-mode" && !message.streaming,
),
);
const finalMessage = finalThread.messages.find(
(entry) => entry.id === "assistant:item-streaming-mode",
@@ -442,12 +559,10 @@ describe("ProviderRuntimeIngestion", () => {
itemId: asItemId("item-buffer-spill"),
});
const thread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some(
(message) => message.id === "assistant:item-buffer-spill" && !message.streaming,
),
const thread = await waitForThread(harness.engine, (entry) =>
entry.messages.some(
(message) => message.id === "assistant:item-buffer-spill" && !message.streaming,
),
);
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffer-spill");
expect(message?.text.length).toBe(oversizedText.length);
@@ -3,6 +3,8 @@ import {
CommandId,
MessageId,
type OrchestrationEvent,
type ProviderApprovalPolicy,
type ProviderSandboxMode,
ProviderThreadId,
type ThreadId,
TurnId,
@@ -24,11 +26,14 @@ const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "on-request";
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120);
const MAX_BUFFERED_ASSISTANT_CHARS = 24_000;
const STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== "0";
type TurnStartRequestedDomainEvent = Extract<
OrchestrationEvent,
@@ -49,6 +54,17 @@ function toTurnId(value: string | undefined): TurnId | undefined {
return value === undefined ? undefined : TurnId.makeUnsafe(value);
}
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
}
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
if (left === null || left === undefined || right === null || right === undefined) {
return false;
}
return left === right;
}
function truncateDetail(value: string, limit = 180): string {
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
}
@@ -328,6 +344,62 @@ const make = Effect.gen(function* () {
if (!thread) return;
const now = event.createdAt;
const sessionProviderThreadId = thread.session?.providerThreadId ?? null;
const eventProviderThreadId = toProviderThreadId(event.threadId);
const eventTurnId = toTurnId("turnId" in event ? event.turnId : undefined);
const activeTurnId = thread.session?.activeTurnId ?? null;
const matchesThreadScope =
eventProviderThreadId === null ||
sessionProviderThreadId === null ||
sameId(eventProviderThreadId, sessionProviderThreadId);
const conflictsWithActiveTurn =
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
const shouldApplyThreadLifecycle = (() => {
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
return true;
}
switch (event.type) {
case "session.exited":
return true;
case "session.started":
case "thread.started":
if (!matchesThreadScope) {
return false;
}
// Never let auxiliary/provider-side spawned threads replace the primary thread binding.
if (
eventProviderThreadId !== null &&
sessionProviderThreadId !== null &&
!sameId(eventProviderThreadId, sessionProviderThreadId)
) {
return false;
}
return true;
case "turn.started":
if (!matchesThreadScope) {
return false;
}
return !conflictsWithActiveTurn;
case "turn.completed":
if (!matchesThreadScope) {
return false;
}
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
return false;
}
// Only the active turn may close the lifecycle state.
if (activeTurnId !== null && eventTurnId !== undefined) {
return sameId(activeTurnId, eventTurnId);
}
// Without an active turn, only accept completion when no thread mismatch signal exists.
return eventProviderThreadId === null || sessionProviderThreadId === null;
default:
return true;
}
})();
if (
event.type === "session.started" ||
@@ -336,16 +408,14 @@ const make = Effect.gen(function* () {
event.type === "turn.started" ||
event.type === "turn.completed"
) {
const activeTurnId =
event.type === "turn.started" ? (toTurnId(event.turnId) ?? null) : null;
const nextActiveTurnId = event.type === "turn.started" ? (eventTurnId ?? null) : null;
const providerThreadIdFromEvent =
event.type === "thread.started"
? ProviderThreadId.makeUnsafe(event.threadId)
: event.threadId !== undefined
? ProviderThreadId.makeUnsafe(event.threadId)
: null;
const providerThreadId =
providerThreadIdFromEvent ?? thread.session?.providerThreadId ?? null;
const providerThreadId = providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
const status =
event.type === "turn.started"
? "running"
@@ -361,22 +431,26 @@ const make = Effect.gen(function* () {
? null
: (thread.session?.lastError ?? null);
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "thread-session-set"),
threadId: thread.id,
session: {
if (shouldApplyThreadLifecycle) {
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "thread-session-set"),
threadId: thread.id,
status,
providerName: event.provider,
providerSessionId: event.sessionId,
providerThreadId,
activeTurnId,
lastError,
updatedAt: now,
},
createdAt: now,
});
session: {
threadId: thread.id,
status,
providerName: event.provider,
providerSessionId: event.sessionId,
providerThreadId,
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
activeTurnId: nextActiveTurnId,
lastError,
updatedAt: now,
},
createdAt: now,
});
}
}
if (event.type === "message.delta" && event.delta.length > 0) {
@@ -464,27 +538,38 @@ const make = Effect.gen(function* () {
}
if (event.type === "runtime.error") {
const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
? true
: matchesThreadScope &&
(activeTurnId === null ||
eventTurnId === undefined ||
sameId(activeTurnId, eventTurnId));
const providerThreadId =
event.threadId !== undefined
? ProviderThreadId.makeUnsafe(event.threadId)
: (thread.session?.providerThreadId ?? null);
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "runtime-error-session-set"),
threadId: thread.id,
session: {
if (shouldApplyRuntimeError) {
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "runtime-error-session-set"),
threadId: thread.id,
status: "error",
providerName: event.provider,
providerSessionId: event.sessionId,
providerThreadId,
activeTurnId: toTurnId(event.turnId) ?? null,
lastError: event.message,
updatedAt: now,
},
createdAt: now,
});
session: {
threadId: thread.id,
status: "error",
providerName: event.provider,
providerSessionId: event.sessionId,
providerThreadId,
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
activeTurnId: eventTurnId ?? null,
lastError: event.message,
updatedAt: now,
},
createdAt: now,
});
}
}
const activities = runtimeEventToActivities(event);
@@ -54,7 +54,7 @@ const readModel: OrchestrationReadModel = {
worktreePath: null,
createdAt: now,
updatedAt: now,
latestTurnId: null,
latestTurn: null,
messages: [],
session: null,
activities: [],
@@ -70,7 +70,7 @@ const readModel: OrchestrationReadModel = {
worktreePath: null,
createdAt: now,
updatedAt: now,
latestTurnId: null,
latestTurn: null,
messages: [],
session: null,
activities: [],
@@ -90,6 +90,8 @@ const messageSendCommand: OrchestrationCommand = {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
};
@@ -152,6 +152,8 @@ describe("decider project scripts", () => {
},
model: "gpt-5",
effort: "high",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
},
readModel,
@@ -169,5 +171,13 @@ describe("decider project scripts", () => {
return;
}
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
messageId: asMessageId("message-user-1"),
model: "gpt-5",
effort: "high",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
});
});
});
+2
View File
@@ -254,6 +254,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.model !== undefined ? { model: command.model } : {}),
...(command.effort !== undefined ? { effort: command.effort } : {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
approvalPolicy: command.approvalPolicy,
sandboxMode: command.sandboxMode,
createdAt: command.createdAt,
},
};
@@ -75,7 +75,7 @@ describe("orchestration projector", () => {
model: "gpt-5-codex",
branch: null,
worktreePath: null,
latestTurnId: null,
latestTurn: null,
createdAt: now,
updatedAt: now,
deletedAt: null,
@@ -135,6 +135,8 @@ describe("orchestration projector", () => {
payload: {
threadId: "thread-1",
messageId: "message-1",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: "2026-01-01T00:00:00.000Z",
},
}),
@@ -193,6 +195,8 @@ describe("orchestration projector", () => {
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: "turn-1",
lastError: null,
updatedAt: startedAt,
@@ -203,7 +207,7 @@ describe("orchestration projector", () => {
);
const thread = afterRunning.threads[0];
expect(thread?.latestTurnId).toBe("turn-1");
expect(thread?.latestTurn?.turnId).toBe("turn-1");
expect(thread?.session?.status).toBe("running");
});
@@ -500,7 +504,7 @@ describe("orchestration projector", () => {
thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })),
).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
expect(thread?.latestTurnId).toBe("turn-1");
expect(thread?.latestTurn?.turnId).toBe("turn-1");
});
it("does not fallback-retain messages tied to removed turn IDs", async () => {
+54 -6
View File
@@ -26,6 +26,12 @@ type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
const MAX_THREAD_MESSAGES = 2_000;
const MAX_THREAD_CHECKPOINTS = 500;
function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
if (status === "error") return "error" as const;
if (status === "missing") return "interrupted" as const;
return "completed" as const;
}
function updateThread(
threads: ReadonlyArray<OrchestrationThread>,
threadId: ThreadId,
@@ -220,7 +226,7 @@ export function projectEvent(
model: payload.model,
branch: payload.branch,
worktreePath: payload.worktreePath,
latestTurnId: null,
latestTurn: null,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
deletedAt: null,
@@ -351,7 +357,26 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
session,
latestTurnId: session.activeTurnId,
latestTurn:
session.status === "running" && session.activeTurnId !== null
? {
turnId: session.activeTurnId,
state: "running",
requestedAt:
thread.latestTurn?.turnId === session.activeTurnId
? thread.latestTurn.requestedAt
: session.updatedAt,
startedAt:
thread.latestTurn?.turnId === session.activeTurnId
? (thread.latestTurn.startedAt ?? session.updatedAt)
: session.updatedAt,
completedAt: null,
assistantMessageId:
thread.latestTurn?.turnId === session.activeTurnId
? thread.latestTurn.assistantMessageId
: null,
}
: thread.latestTurn,
updatedAt: event.occurredAt,
}),
};
@@ -396,7 +421,20 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
checkpoints,
latestTurnId: payload.turnId,
latestTurn: {
turnId: payload.turnId,
state: checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
: payload.completedAt,
startedAt:
thread.latestTurn?.turnId === payload.turnId
? (thread.latestTurn.startedAt ?? payload.completedAt)
: payload.completedAt,
completedAt: payload.completedAt,
assistantMessageId: payload.assistantMessageId,
},
updatedAt: event.occurredAt,
}),
};
@@ -422,8 +460,18 @@ export function projectEvent(
).slice(-MAX_THREAD_MESSAGES);
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
const latestTurnId =
checkpoints.length > 0 ? (checkpoints[checkpoints.length - 1]?.turnId ?? null) : null;
const latestCheckpoint = checkpoints.at(-1) ?? null;
const latestTurn =
latestCheckpoint === null
? null
: {
turnId: latestCheckpoint.turnId,
state: checkpointStatusToLatestTurnState(latestCheckpoint.status),
requestedAt: latestCheckpoint.completedAt,
startedAt: latestCheckpoint.completedAt,
completedAt: latestCheckpoint.completedAt,
assistantMessageId: latestCheckpoint.assistantMessageId,
};
return {
...nextBase,
@@ -431,7 +479,7 @@ export function projectEvent(
checkpoints,
messages,
activities,
latestTurnId,
latestTurn,
updatedAt: event.occurredAt,
}),
};
@@ -0,0 +1,106 @@
import { MessageId, ThreadId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ProjectionThreadMessageRepository } from "../Services/ProjectionThreadMessages.ts";
import { ProjectionThreadMessageRepositoryLive } from "./ProjectionThreadMessages.ts";
import { SqlitePersistenceMemory } from "./Sqlite.ts";
const layer = it.layer(
ProjectionThreadMessageRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
);
layer("ProjectionThreadMessageRepository", (it) => {
it.effect("preserves existing attachments when upsert omits attachments", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.makeUnsafe("thread-preserve-attachments");
const messageId = MessageId.makeUnsafe("message-preserve-attachments");
const createdAt = "2026-02-28T19:00:00.000Z";
const updatedAt = "2026-02-28T19:00:01.000Z";
const persistedAttachments = [
{
type: "image" as const,
id: "thread-preserve-attachments-att-1",
name: "example.png",
mimeType: "image/png",
sizeBytes: 5,
},
];
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "user",
text: "initial",
attachments: persistedAttachments,
isStreaming: false,
createdAt,
updatedAt,
});
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "user",
text: "updated",
isStreaming: false,
createdAt,
updatedAt: "2026-02-28T19:00:02.000Z",
});
const rows = yield* repository.listByThreadId({ threadId });
assert.equal(rows.length, 1);
assert.equal(rows[0]?.text, "updated");
assert.deepEqual(rows[0]?.attachments, persistedAttachments);
}),
);
it.effect("allows explicit attachment clearing with an empty array", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.makeUnsafe("thread-clear-attachments");
const messageId = MessageId.makeUnsafe("message-clear-attachments");
const createdAt = "2026-02-28T19:10:00.000Z";
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "assistant",
text: "with attachment",
attachments: [
{
type: "image",
id: "thread-clear-attachments-att-1",
name: "example.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
isStreaming: false,
createdAt,
updatedAt: "2026-02-28T19:10:01.000Z",
});
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "assistant",
text: "cleared",
attachments: [],
isStreaming: false,
createdAt,
updatedAt: "2026-02-28T19:10:02.000Z",
});
const rows = yield* repository.listByThreadId({ threadId });
assert.equal(rows.length, 1);
assert.equal(rows[0]?.text, "cleared");
assert.deepEqual(rows[0]?.attachments, []);
}),
);
});
@@ -1,6 +1,7 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Schema, Struct } from "effect";
import { ChatAttachment } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
@@ -14,6 +15,7 @@ import {
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
Struct.assign({
isStreaming: Schema.Number,
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
}),
);
@@ -22,14 +24,17 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
const upsertProjectionThreadMessageRow = SqlSchema.void({
Request: ProjectionThreadMessage,
execute: (row) =>
sql`
execute: (row) => {
const nextAttachmentsJson =
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
return sql`
INSERT INTO projection_thread_messages (
message_id,
thread_id,
turn_id,
role,
text,
attachments_json,
is_streaming,
created_at,
updated_at
@@ -40,6 +45,14 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
${row.turnId},
${row.role},
${row.text},
COALESCE(
${nextAttachmentsJson},
(
SELECT attachments_json
FROM projection_thread_messages
WHERE message_id = ${row.messageId}
)
),
${row.isStreaming ? 1 : 0},
${row.createdAt},
${row.updatedAt}
@@ -50,10 +63,15 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
turn_id = excluded.turn_id,
role = excluded.role,
text = excluded.text,
attachments_json = COALESCE(
excluded.attachments_json,
projection_thread_messages.attachments_json
),
is_streaming = excluded.is_streaming,
created_at = excluded.created_at,
updated_at = excluded.updated_at
`,
`;
},
});
const listProjectionThreadMessageRows = SqlSchema.findAll({
@@ -67,6 +85,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
turn_id AS "turnId",
role,
text,
attachments_json AS "attachments",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -97,8 +116,15 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
),
Effect.map((rows) =>
rows.map((row) => ({
...row,
messageId: row.messageId,
threadId: row.threadId,
turnId: row.turnId,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
})),
),
);
@@ -25,6 +25,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
provider_name,
provider_session_id,
provider_thread_id,
approval_policy,
sandbox_mode,
active_turn_id,
last_error,
updated_at
@@ -35,6 +37,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
${row.providerName},
${row.providerSessionId},
${row.providerThreadId},
${row.approvalPolicy},
${row.sandboxMode},
${row.activeTurnId},
${row.lastError},
${row.updatedAt}
@@ -45,6 +49,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
provider_name = excluded.provider_name,
provider_session_id = excluded.provider_session_id,
provider_thread_id = excluded.provider_thread_id,
approval_policy = excluded.approval_policy,
sandbox_mode = excluded.sandbox_mode,
active_turn_id = excluded.active_turn_id,
last_error = excluded.last_error,
updated_at = excluded.updated_at
@@ -62,6 +68,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
provider_name AS "providerName",
provider_session_id AS "providerSessionId",
provider_thread_id AS "providerThreadId",
approval_policy AS "approvalPolicy",
sandbox_mode AS "sandboxMode",
active_turn_id AS "activeTurnId",
last_error AS "lastError",
updated_at AS "updatedAt"
@@ -17,6 +17,8 @@ import Migration0002 from "./Migrations/002_OrchestrationCommandReceipts.ts";
import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
import Migration0005 from "./Migrations/005_Projections.ts";
import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts";
/**
* Migration loader with all migrations defined inline.
@@ -34,6 +36,8 @@ const loader = Migrator.fromRecord({
"3_CheckpointDiffBlobs": Migration0003,
"4_ProviderSessionRuntime": Migration0004,
"5_Projections": Migration0005,
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
"7_ProjectionThreadMessageAttachments": Migration0007,
});
/**
@@ -0,0 +1,30 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
const DEFAULT_APPROVAL_POLICY = "never";
const DEFAULT_SANDBOX_MODE = "workspace-write";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_thread_sessions
ADD COLUMN approval_policy TEXT NOT NULL DEFAULT 'never'
`;
yield* sql`
ALTER TABLE projection_thread_sessions
ADD COLUMN sandbox_mode TEXT NOT NULL DEFAULT 'workspace-write'
`;
yield* sql`
UPDATE projection_thread_sessions
SET approval_policy = ${DEFAULT_APPROVAL_POLICY}
WHERE approval_policy IS NULL
`;
yield* sql`
UPDATE projection_thread_sessions
SET sandbox_mode = ${DEFAULT_SANDBOX_MODE}
WHERE sandbox_mode IS NULL
`;
});
@@ -0,0 +1,11 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_thread_messages
ADD COLUMN attachments_json TEXT
`;
});
@@ -4,23 +4,27 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqliteClient from "./NodeSqliteClient.ts";
it.effect("runs prepared queries and returns positional values", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const layer = it.layer(SqliteClient.layerMemory());
yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
layer("NodeSqliteClient", (it) => {
it.effect("runs prepared queries and returns positional values", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const rows = yield* sql<{ readonly id: number; readonly name: string }>`
yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
const rows = yield* sql<{ readonly id: number; readonly name: string }>`
SELECT id, name FROM entries ORDER BY id
`;
assert.equal(rows.length, 2);
assert.equal(rows[0]?.name, "alpha");
assert.equal(rows[1]?.name, "beta");
assert.equal(rows.length, 2);
assert.equal(rows[0]?.name, "alpha");
assert.equal(rows[1]?.name, "beta");
const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
assert.equal(values.length, 2);
assert.equal(values[0]?.[1], "alpha");
assert.equal(values[1]?.[1], "beta");
}).pipe(Effect.provide(SqliteClient.layerMemory())),
);
const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
assert.equal(values.length, 2);
assert.equal(values[0]?.[1], "alpha");
assert.equal(values[1]?.[1], "beta");
}),
);
});
@@ -7,6 +7,7 @@
* @module ProjectionThreadMessageRepository
*/
import {
ChatAttachment,
OrchestrationMessageRole,
MessageId,
ThreadId,
@@ -24,6 +25,7 @@ export const ProjectionThreadMessage = Schema.Struct({
turnId: Schema.NullOr(TurnId),
role: OrchestrationMessageRole,
text: Schema.String,
attachments: Schema.optional(Schema.Array(ChatAttachment)),
isStreaming: Schema.Boolean,
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -9,6 +9,8 @@
import {
IsoDateTime,
OrchestrationSessionStatus,
ProviderApprovalPolicy,
ProviderSandboxMode,
ProviderSessionId,
ProviderThreadId,
ThreadId,
@@ -25,6 +27,8 @@ export const ProjectionThreadSession = Schema.Struct({
providerName: Schema.NullOr(Schema.String),
providerSessionId: Schema.NullOr(ProviderSessionId),
providerThreadId: Schema.NullOr(ProviderThreadId),
approvalPolicy: ProviderApprovalPolicy,
sandboxMode: ProviderSandboxMode,
activeTurnId: Schema.NullOr(TurnId),
lastError: Schema.NullOr(Schema.String),
updatedAt: IsoDateTime,
+17 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { runProcess } from "./processRunner";
import { runProcess, spawnDetachedProcess, spawnProcessSync } from "./processRunner";
describe("runProcess", () => {
it("fails when output exceeds max buffer in default mode", async () => {
@@ -20,4 +20,20 @@ describe("runProcess", () => {
expect(result.stdoutTruncated).toBe(true);
expect(result.stderrTruncated).toBe(false);
});
it("runs sync commands through the shared spawn strategy", () => {
const result = spawnProcessSync("node", ["-e", "process.stdout.write('ok')"], {
stdio: ["ignore", "pipe", "pipe"],
});
expect(result.error).toBeUndefined();
expect(result.status).toBe(0);
expect(result.stdout).toBe("ok");
});
it("spawns detached commands through the shared spawn strategy", async () => {
await expect(
spawnDetachedProcess(process.execPath, ["-e", "process.exit(0)"]),
).resolves.toBeUndefined();
});
});
+229 -10
View File
@@ -1,4 +1,44 @@
import { spawn } from "node:child_process";
import {
type ChildProcess as ChildProcessHandle,
type ChildProcessWithoutNullStreams,
spawn,
spawnSync,
type StdioOptions,
} from "node:child_process";
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
import { Effect, Exit, Scope } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
interface ProcessSpawnBaseOptions {
cwd?: string | undefined;
env?: NodeJS.ProcessEnv | undefined;
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
shell?: boolean | undefined;
}
interface RuntimeShellOptions {
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
shell?: boolean | string | undefined;
}
interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
stdio?: StdioOptions | undefined;
detached?: boolean | undefined;
}
interface RuntimeCommandOptions extends ChildProcess.CommandOptions {
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
}
interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
stdio?: StdioOptions | undefined;
detached?: boolean | undefined;
encoding?: BufferEncoding | undefined;
input?: string | undefined;
}
export interface ProcessRunOptions {
cwd?: string | undefined;
@@ -8,6 +48,8 @@ export interface ProcessRunOptions {
allowNonZeroExit?: boolean | undefined;
maxBufferBytes?: number | undefined;
outputMode?: "error" | "truncate" | undefined;
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
shell?: boolean | undefined;
}
export interface ProcessRunResult {
@@ -24,6 +66,127 @@ function commandLabel(command: string, args: readonly string[]): string {
return [command, ...args].join(" ");
}
function resolveRuntimeEnvironment(
runtimeEnvironment: ServerRuntimeEnvironment | undefined,
): ServerRuntimeEnvironment {
return runtimeEnvironment ?? detectServerRuntimeEnvironment();
}
function shouldUseShell(options: RuntimeShellOptions): boolean | string {
if (options.shell !== undefined) {
return options.shell;
}
return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows";
}
function toSpawnOptions(options: ProcessSpawnOptions) {
return {
cwd: options.cwd,
env: options.env,
shell: shouldUseShell(options),
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
...(options.detached !== undefined ? { detached: options.detached } : {}),
};
}
function toRuntimeCommandOptions(
options: RuntimeCommandOptions = {},
): ChildProcess.CommandOptions {
const { runtimeEnvironment: _, ...rest } = options;
return {
...rest,
shell: options.shell ?? shouldUseShell(options),
};
}
export function makeRuntimeCommand(
command: string,
args: ReadonlyArray<string>,
options: RuntimeCommandOptions = {},
): ChildProcess.StandardCommand {
return ChildProcess.make(command, [...args], toRuntimeCommandOptions(options));
}
interface ManagedChildProcess {
readonly scope: Scope.Closeable;
readonly handle: ChildProcessSpawner.ChildProcessHandle;
}
export const spawnManagedCommand = (command: ChildProcess.Command) =>
Effect.gen(function* () {
const scope = yield* Scope.make("sequential");
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const handle = yield* spawner.spawn(command).pipe(
Scope.provide(scope),
Effect.tapError(() => Scope.close(scope, Exit.void)),
);
return {
scope,
handle,
} satisfies ManagedChildProcess;
});
function spawnProcess(
command: string,
args: readonly string[],
options: ProcessSpawnOptions = {},
): ChildProcessHandle {
return spawn(command, args, toSpawnOptions(options));
}
function spawnPipedProcess(
command: string,
args: readonly string[],
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
): ChildProcessWithoutNullStreams {
return spawnProcess(command, args, {
...options,
stdio: "pipe",
}) as ChildProcessWithoutNullStreams;
}
export function spawnProcessSync(
command: string,
args: readonly string[],
options: ProcessSpawnSyncOptions = {},
) {
return spawnSync(command, args, {
cwd: options.cwd,
env: options.env,
shell: shouldUseShell(options),
encoding: options.encoding ?? "utf8",
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
...(options.detached !== undefined ? { detached: options.detached } : {}),
...(options.input !== undefined ? { input: options.input } : {}),
});
}
export function spawnDetachedProcess(
command: string,
args: readonly string[],
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
): Promise<void> {
return new Promise<void>((resolve, reject) => {
const child = spawnProcess(command, args, {
...options,
detached: true,
stdio: "ignore",
});
const handleSpawn = () => {
child.unref();
resolve();
};
child.once("spawn", handleSpawn);
child.once("error", (error) => {
reject(normalizeSpawnError(command, args, error));
});
});
}
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to run ${commandLabel(command, args)}.`);
@@ -37,11 +200,26 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
}
function isWindowsCommandNotFound(
code: number | null,
stderr: string,
runtimeEnvironment?: ServerRuntimeEnvironment,
): boolean {
if (resolveRuntimeEnvironment(runtimeEnvironment).platform !== "windows") return false;
if (code === 9009) return true;
return /is not recognized as an internal or external command/i.test(stderr);
}
function normalizeExitError(
command: string,
args: readonly string[],
result: ProcessRunResult,
runtimeEnvironment?: ServerRuntimeEnvironment,
): Error {
if (isWindowsCommandNotFound(result.code, result.stderr, runtimeEnvironment)) {
return new Error(`Command not found: ${command}`);
}
const reason = result.timedOut
? "timed out"
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
@@ -70,6 +248,42 @@ function normalizeBufferError(
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killProcessTree(
child: ChildProcessHandle,
options: {
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
signal?: NodeJS.Signals | undefined;
} = {},
): void {
const signal = options.signal ?? "SIGTERM";
if (
resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows" &&
child.pid !== undefined
) {
try {
const result = spawnProcessSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
stdio: "ignore",
shell: false,
runtimeEnvironment: options.runtimeEnvironment,
});
if (!result.error && result.status === 0) {
return;
}
if (result.error) {
throw result.error;
}
} catch {
// fallback to direct kill
}
}
child.kill(signal);
}
function appendChunkWithinLimit(
target: string,
currentBytes: number,
@@ -108,11 +322,7 @@ export async function runProcess(
const outputMode = options.outputMode ?? "error";
return new Promise<ProcessRunResult>((resolve, reject) => {
const child = spawn(command, args, {
cwd: options.cwd,
env: options.env,
stdio: "pipe",
});
const child = spawnPipedProcess(command, args, options);
let stdout = "";
let stderr = "";
@@ -126,9 +336,15 @@ export async function runProcess(
const timeoutTimer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
killProcessTree(child, {
runtimeEnvironment: options.runtimeEnvironment,
signal: "SIGTERM",
});
forceKillTimer = setTimeout(() => {
child.kill("SIGKILL");
killProcessTree(child, {
runtimeEnvironment: options.runtimeEnvironment,
signal: "SIGKILL",
});
}, 1_000);
}, timeoutMs);
@@ -143,7 +359,10 @@ export async function runProcess(
};
const fail = (error: Error): void => {
child.kill("SIGTERM");
killProcessTree(child, {
runtimeEnvironment: options.runtimeEnvironment,
signal: "SIGTERM",
});
finalize(() => {
reject(error);
});
@@ -216,7 +435,7 @@ export async function runProcess(
finalize(() => {
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
reject(normalizeExitError(command, args, result));
reject(normalizeExitError(command, args, result, options.runtimeEnvironment));
return;
}
resolve(result);
+167
View File
@@ -0,0 +1,167 @@
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
interface HttpResponse {
statusCode: number;
contentType: string | null;
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 withRouteServer(
run: (baseUrl: string) => Promise<void>,
): Promise<void> {
const server = http.createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://127.0.0.1");
if (tryHandleProjectFaviconRequest(url, res)) {
return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
});
await new Promise<void>((resolve, reject) => {
server.listen(0, "127.0.0.1", (error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
const address = server.address();
if (typeof address !== "object" || address === null) {
throw new Error("Expected server address to be an object");
}
const baseUrl = `http://127.0.0.1:${address.port}`;
try {
await run(baseUrl);
} finally {
await new Promise<void>((resolve, reject) => {
server.close((error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
}
async function request(baseUrl: string, pathname: string): Promise<HttpResponse> {
const response = await fetch(`${baseUrl}${pathname}`);
return {
statusCode: response.status,
contentType: response.headers.get("content-type"),
body: await response.text(),
};
}
describe("tryHandleProjectFaviconRequest", () => {
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("returns 400 when cwd is missing", async () => {
await withRouteServer(async (baseUrl) => {
const response = await request(baseUrl, "/api/project-favicon");
expect(response.statusCode).toBe(400);
expect(response.body).toBe("Missing cwd parameter");
});
});
it("serves a well-known favicon file from the project root", async () => {
const projectDir = makeTempDir("t3code-favicon-route-root-");
fs.writeFileSync(path.join(projectDir, "favicon.svg"), "<svg>favicon</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>favicon</svg>");
});
});
it("resolves icon href from source files when no well-known favicon exists", async () => {
const projectDir = makeTempDir("t3code-favicon-route-source-");
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
fs.writeFileSync(path.join(projectDir, "index.html"), '<link rel="icon" href="/brand/logo.svg">');
fs.writeFileSync(iconPath, "<svg>brand</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>brand</svg>");
});
});
it("resolves icon link when href appears before rel in HTML", async () => {
const projectDir = makeTempDir("t3code-favicon-route-html-order-");
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
fs.writeFileSync(path.join(projectDir, "index.html"), '<link href="/brand/logo.svg" rel="icon">');
fs.writeFileSync(iconPath, "<svg>brand-html-order</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>brand-html-order</svg>");
});
});
it("resolves object-style icon metadata when href appears before rel", async () => {
const projectDir = makeTempDir("t3code-favicon-route-obj-order-");
const iconPath = path.join(projectDir, "public", "brand", "obj.svg");
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
fs.mkdirSync(path.join(projectDir, "src"), { recursive: true });
fs.writeFileSync(
path.join(projectDir, "src", "root.tsx"),
'const links = [{ href: "/brand/obj.svg", rel: "icon" }];',
"utf8",
);
fs.writeFileSync(iconPath, "<svg>brand-obj-order</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>brand-obj-order</svg>");
});
});
it("serves a fallback favicon when no icon exists", async () => {
const projectDir = makeTempDir("t3code-favicon-route-fallback-");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toContain('data-fallback="project-favicon"');
});
});
});
+171
View File
@@ -0,0 +1,171 @@
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
const FAVICON_MIME_TYPES: Record<string, string> = {
".png": "image/png",
".jpg": "image/jpeg",
".svg": "image/svg+xml",
".ico": "image/x-icon",
};
const FALLBACK_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
// Well-known favicon paths checked in order.
const FAVICON_CANDIDATES = [
"favicon.svg",
"favicon.ico",
"favicon.png",
"public/favicon.svg",
"public/favicon.ico",
"public/favicon.png",
"app/favicon.ico",
"app/favicon.png",
"app/icon.svg",
"app/icon.png",
"app/icon.ico",
"src/favicon.ico",
"src/favicon.svg",
"src/app/favicon.ico",
"src/app/icon.svg",
"src/app/icon.png",
"assets/icon.svg",
"assets/icon.png",
"assets/logo.svg",
"assets/logo.png",
];
// Files that may contain a <link rel="icon"> or icon metadata declaration.
const ICON_SOURCE_FILES = [
"index.html",
"public/index.html",
"app/routes/__root.tsx",
"src/routes/__root.tsx",
"app/root.tsx",
"src/root.tsx",
"src/index.html",
];
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
const LINK_ICON_HTML_RE =
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
const LINK_ICON_OBJ_RE =
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
function extractIconHref(source: string): string | null {
const htmlMatch = source.match(LINK_ICON_HTML_RE);
if (htmlMatch?.[1]) return htmlMatch[1];
const objMatch = source.match(LINK_ICON_OBJ_RE);
if (objMatch?.[1]) return objMatch[1];
return null;
}
function resolveIconHref(projectCwd: string, href: string): string[] {
const clean = href.replace(/^\//, "");
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
}
function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
}
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
const ext = path.extname(filePath).toLowerCase();
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
fs.readFile(filePath, (readErr, data) => {
if (readErr) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Read error");
return;
}
res.writeHead(200, {
"Content-Type": contentType,
"Cache-Control": "public, max-age=3600",
});
res.end(data);
});
}
function serveFallbackFavicon(res: http.ServerResponse): void {
res.writeHead(200, {
"Content-Type": "image/svg+xml",
"Cache-Control": "public, max-age=3600",
});
res.end(FALLBACK_FAVICON_SVG);
}
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
if (url.pathname !== "/api/project-favicon") {
return false;
}
const projectCwd = url.searchParams.get("cwd");
if (!projectCwd) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Missing cwd parameter");
return true;
}
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
if (index >= paths.length) {
onExhausted();
return;
}
const candidate = paths[index]!;
if (!isPathWithinProject(projectCwd, candidate)) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
}
serveFaviconFile(candidate, res);
});
};
const trySourceFiles = (index: number): void => {
if (index >= ICON_SOURCE_FILES.length) {
serveFallbackFavicon(res);
return;
}
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
fs.readFile(sourceFile, "utf8", (err, content) => {
if (err) {
trySourceFiles(index + 1);
return;
}
const href = extractIconHref(content);
if (!href) {
trySourceFiles(index + 1);
return;
}
const candidates = resolveIconHref(projectCwd, href);
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
});
};
const tryCandidates = (index: number): void => {
if (index >= FAVICON_CANDIDATES.length) {
trySourceFiles(0);
return;
}
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
if (!isPathWithinProject(projectCwd, candidate)) {
tryCandidates(index + 1);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryCandidates(index + 1);
return;
}
serveFaviconFile(candidate, res);
});
};
tryCandidates(0);
return true;
}
@@ -4,7 +4,6 @@ import {
ProviderItemId,
type ProviderApprovalDecision,
type ProviderEvent,
type ProviderSendTurnInput,
ProviderSessionId,
type ProviderSession,
type ProviderSessionStartInput,
@@ -12,14 +11,20 @@ import {
ProviderTurnId,
type ProviderTurnStartResult,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { afterAll, assert, it, vi } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, Fiber, Stream } from "effect";
import { Effect, Fiber, Layer, Option, Stream } from "effect";
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
import {
CodexAppServerManager,
type CodexAppServerSendTurnInput,
} from "../../codexAppServerManager.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
@@ -44,7 +49,7 @@ class FakeCodexManager extends CodexAppServerManager {
);
public sendTurnImpl = vi.fn(
async (_input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> => ({
async (_input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> => ({
threadId: ProviderThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
}),
@@ -78,7 +83,7 @@ class FakeCodexManager extends CodexAppServerManager {
return this.startSessionImpl(input);
}
override sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
override sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
return this.sendTurnImpl(input);
}
@@ -117,8 +122,24 @@ class FakeCodexManager extends CodexAppServerManager {
}
}
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
upsert: () => Effect.void,
getProvider: () =>
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
getBinding: () => Effect.succeed(Option.none()),
getThreadId: () => Effect.succeed(Option.none()),
remove: () => Effect.void,
listSessionIds: () => Effect.succeed([]),
});
const validationManager = new FakeCodexManager();
const validationLayer = it.layer(makeCodexAdapterLive({ manager: validationManager }));
const validationLayer = it.layer(
makeCodexAdapterLive({ manager: validationManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
);
validationLayer("CodexAdapterLive validation", (it) => {
it.effect("returns validation error for non-codex provider on startSession", () =>
@@ -147,7 +168,13 @@ const sessionErrorManager = new FakeCodexManager();
sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
throw new Error("Unknown session: sess-missing");
});
const sessionErrorLayer = it.layer(makeCodexAdapterLive({ manager: sessionErrorManager }));
const sessionErrorLayer = it.layer(
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
);
sessionErrorLayer("CodexAdapterLive session errors", (it) => {
it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () =>
@@ -178,7 +205,13 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
});
const lifecycleManager = new FakeCodexManager();
const lifecycleLayer = it.layer(makeCodexAdapterLive({ manager: lifecycleManager }));
const lifecycleLayer = it.layer(
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
);
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps completed agent message items to canonical message.completed events", () =>
+82 -15
View File
@@ -17,7 +17,7 @@ import {
ProviderThreadId,
ProviderTurnId,
} from "@t3tools/contracts";
import { Effect, Layer, Queue, Schema, Stream } from "effect";
import { Effect, FileSystem, Layer, Option, Queue, Schema, Stream } from "effect";
import {
ProviderAdapterProcessError,
@@ -28,8 +28,12 @@ import {
type ProviderAdapterError,
} from "../Errors.ts";
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const PROVIDER = "codex" as const;
@@ -37,6 +41,7 @@ export interface CodexAdapterLiveOptions {
readonly manager?: CodexAppServerManager;
readonly makeManager?: () => CodexAppServerManager;
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: EventNdjsonLogger;
}
function toMessage(cause: unknown, fallback: string): string {
@@ -426,10 +431,17 @@ function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray<ProviderRuntime
const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const serverConfig = yield* Effect.service(ServerConfig);
const directory = yield* ProviderSessionDirectory;
const services = yield* Effect.services<NodeServices.NodeServices>();
const nativeEventLogger =
options?.nativeEventLogPath !== undefined
? makeEventNdjsonLogger(options.nativeEventLogPath)
: undefined;
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined);
const manager = yield* Effect.acquireRelease(
Effect.sync(() => {
@@ -439,7 +451,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
if (options?.makeManager) {
return options.makeManager();
}
return new CodexAppServerManager();
return new CodexAppServerManager(services);
}),
(manager) =>
Effect.sync(() => {
@@ -475,9 +487,48 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
};
const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>
Effect.tryPromise({
try: () => manager.sendTurn(input),
catch: (cause) => toRequestError(input.sessionId, "turn/start", cause),
Effect.gen(function* () {
const codexAttachments = yield* Effect.forEach(
input.attachments ?? [],
(attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
stateDir: serverConfig.stateDir,
attachment,
});
if (!attachmentPath) {
return yield* toRequestError(
input.sessionId,
"turn/start",
new Error(`Invalid attachment id '${attachment.id}'.`),
);
}
const bytes = yield* fileSystem
.readFile(attachmentPath)
.pipe(
Effect.mapError((cause) => toRequestError(input.sessionId, "turn/start", cause)),
);
return {
type: "image" as const,
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
};
}),
{ concurrency: 1 },
);
return yield* Effect.tryPromise({
try: () => {
const managerInput = {
sessionId: input.sessionId,
...(input.input !== undefined ? { input: input.input } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.effort !== undefined ? { effort: input.effort } : {}),
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
};
return manager.sendTurn(managerInput);
},
catch: (cause) => toRequestError(input.sessionId, "turn/start", cause),
});
});
const interruptTurn: CodexAdapterShape["interruptTurn"] = (sessionId, turnId) =>
@@ -539,13 +590,29 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
yield* Effect.acquireRelease(
Effect.sync(() => {
const listener = (event: ProviderEvent) => {
nativeEventLogger?.write({
observedAt: new Date().toISOString(),
event,
const writeNativeEvent = (event: ProviderEvent) =>
Effect.gen(function* () {
if (!nativeEventLogger) {
return;
}
const orchestrationThreadId = yield* Effect.catch(
directory
.getThreadId(event.sessionId)
.pipe(
Effect.map((threadIdOption) =>
Option.isSome(threadIdOption) ? threadIdOption.value : null,
),
),
() => Effect.succeed(null),
);
yield* nativeEventLogger.write(event, orchestrationThreadId);
});
Queue.offerAllUnsafe(runtimeEventQueue, mapToRuntimeEvents(event));
};
const listener = (event: ProviderEvent) =>
Effect.gen(function* () {
yield* writeNativeEvent(event);
yield* Queue.offerAll(runtimeEventQueue, mapToRuntimeEvents(event));
}).pipe(Effect.runPromiseWith(services));
manager.on("event", listener);
return listener;
}),
@@ -2,36 +2,165 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { ThreadId } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
function parseLogLine(line: string) {
const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
assert.notEqual(match, null);
if (!match) {
throw new Error(`invalid log line: ${line}`);
}
const observedAt = match[1];
const stream = match[2];
const payload = match[3];
if (!observedAt || !stream || payload === undefined) {
throw new Error(`invalid log line: ${line}`);
}
return {
observedAt,
stream,
payload,
};
}
describe("EventNdjsonLogger", () => {
it("writes NDJSON records to disk", () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const filePath = path.join(tempDir, "provider-native.ndjson");
it.effect("writes effect-style lines to thread-scoped files", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const basePath = path.join(tempDir, "provider-native.ndjson");
try {
const logger = makeEventNdjsonLogger(filePath);
expect(logger).toBeDefined();
if (!logger) {
return;
try {
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
assert.notEqual(logger, undefined);
if (!logger) {
return;
}
yield* logger.write(
{ threadId: "provider-thread-1", id: "evt-1" },
ThreadId.makeUnsafe("thread-1"),
);
yield* logger.write(
{ type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" },
ThreadId.makeUnsafe("thread-2"),
);
yield* logger.close();
const threadOnePath = path.join(tempDir, "thread-1.log");
const threadTwoPath = path.join(tempDir, "thread-2.log");
assert.equal(fs.existsSync(threadOnePath), true);
assert.equal(fs.existsSync(threadTwoPath), true);
const first = parseLogLine(fs.readFileSync(threadOnePath, "utf8").trim());
const second = parseLogLine(fs.readFileSync(threadTwoPath, "utf8").trim());
assert.equal(Number.isNaN(Date.parse(first.observedAt)), false);
assert.equal(first.stream, "NTIVE");
assert.equal(first.payload, '{"threadId":"provider-thread-1","id":"evt-1"}');
assert.equal(Number.isNaN(Date.parse(second.observedAt)), false);
assert.equal(second.stream, "NTIVE");
assert.equal(
second.payload,
'{"type":"turn.completed","threadId":"provider-thread-2","id":"evt-2"}',
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
logger.write({ type: "native", payload: { id: "evt-1" } });
logger.write({ type: "canonical", payload: { id: "evt-2" } });
logger.close();
it.effect(
"falls back to a global segment when orchestration thread id is missing or invalid",
() =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const basePath = path.join(tempDir, "provider-canonical.ndjson");
const raw = fs.readFileSync(filePath, "utf8").trim();
const lines = raw.split("\n");
expect(lines.length).toBe(2);
try {
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "orchestration" });
assert.notEqual(logger, undefined);
if (!logger) {
return;
}
const first = JSON.parse(lines[0] ?? "{}");
const second = JSON.parse(lines[1] ?? "{}");
expect(first).toEqual({ type: "native", payload: { id: "evt-1" } });
expect(second).toEqual({ type: "canonical", payload: { id: "evt-2" } });
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
yield* logger.write({ id: "evt-no-thread" }, null);
yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
yield* logger.close();
const globalPath = path.join(tempDir, "_global.log");
assert.equal(fs.existsSync(globalPath), true);
const lines = fs
.readFileSync(globalPath, "utf8")
.trim()
.split("\n")
.map((line) => parseLogLine(line));
assert.equal(lines.length, 2);
assert.equal(Number.isNaN(Date.parse(lines[0]?.observedAt ?? "")), false);
assert.equal(Number.isNaN(Date.parse(lines[1]?.observedAt ?? "")), false);
assert.equal(lines[0]?.stream, "CANON");
assert.equal(lines[0]?.payload, '{"id":"evt-no-thread"}');
assert.equal(lines[1]?.stream, "CANON");
assert.equal(lines[1]?.payload, '{"id":"evt-invalid-thread"}');
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("rotates per-thread files when max size is exceeded", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const basePath = path.join(tempDir, "provider-native.ndjson");
try {
const logger = yield* makeEventNdjsonLogger(basePath, {
stream: "native",
maxBytes: 120,
maxFiles: 2,
});
assert.notEqual(logger, undefined);
if (!logger) {
return;
}
for (let index = 0; index < 10; index += 1) {
yield* logger.write(
{
threadId: "provider-thread-rotate",
id: `evt-${index}`,
payload: "x".repeat(40),
},
ThreadId.makeUnsafe("thread-rotate"),
);
}
yield* logger.close();
const fileStem = "thread-rotate.log";
const matchingFiles = fs
.readdirSync(tempDir)
.filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
.toSorted();
assert.equal(
matchingFiles.some((entry) => entry === `${fileStem}.1`),
true,
);
assert.equal(
matchingFiles.some((entry) => entry === fileStem || entry === `${fileStem}.2`),
true,
);
assert.equal(
matchingFiles.some((entry) => entry === `${fileStem}.3`),
false,
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
});
@@ -1,66 +1,257 @@
/**
* Provider event NDJSON logger helper.
* Provider event logger helper.
*
* Best-effort writer for observability logs. Failures are downgraded to warnings
* so provider runtime behavior is unaffected.
* Best-effort writer for observability logs. Each record is formatted as a
* single effect-style text line in a thread-scoped file. Failures are
* downgraded to warnings so provider runtime behavior is unaffected.
*/
import fs from "node:fs";
import path from "node:path";
import { createLogger } from "../../logger.ts";
import type { ThreadId } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { Effect, Exit, Logger, Scope } from "effect";
const logger = createLogger("provider-observability");
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
const DEFAULT_MAX_FILES = 10;
const DEFAULT_BATCH_WINDOW_MS = 200;
const GLOBAL_THREAD_SEGMENT = "_global";
const LOG_SCOPE = "provider-observability";
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
export interface EventNdjsonLogger {
readonly filePath: string;
write: (record: unknown) => void;
close: () => void;
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
close: () => Effect.Effect<void>;
}
function stringifyRecord(record: unknown): string | undefined {
try {
return JSON.stringify(record);
} catch (error) {
logger.warn("failed to serialize provider event log record", { error });
return undefined;
export interface EventNdjsonLoggerOptions {
readonly stream: EventNdjsonStream;
readonly maxBytes?: number;
readonly maxFiles?: number;
readonly batchWindowMs?: number;
}
interface ThreadWriter {
writeMessage: (message: string) => Effect.Effect<void>;
close: () => Effect.Effect<void>;
}
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
}
function resolveThreadSegment(raw: string | null | undefined): string {
const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
return normalized ?? GLOBAL_THREAD_SEGMENT;
}
function formatLoggerMessage(message: unknown): string {
if (Array.isArray(message)) {
return message.map((part) => (typeof part === "string" ? part : String(part))).join(" ");
}
return typeof message === "string" ? message : String(message);
}
function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
return Logger.make(
({ date, message }) =>
`[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
);
}
function resolveStreamLabel(stream: EventNdjsonStream): string {
switch (stream) {
case "native":
return "NTIVE";
case "canonical":
case "orchestration":
default:
return "CANON";
}
}
export function makeEventNdjsonLogger(filePath: string): EventNdjsonLogger | undefined {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.appendFileSync(filePath, "", { encoding: "utf8", flag: "a" });
} catch (error) {
logger.warn("failed to create provider event log directory", { filePath, error });
return undefined;
}
function toLogMessage(event: unknown): Effect.Effect<string | undefined> {
return Effect.gen(function* () {
const serialized = yield* Effect.sync(() => {
try {
return { ok: true as const, value: JSON.stringify(event) };
} catch (error) {
return { ok: false as const, error };
}
});
try {
let broken = false;
if (!serialized.ok) {
yield* logWarning("failed to serialize provider event log record", {
error: serialized.error,
});
return undefined;
}
if (typeof serialized.value !== "string") {
return undefined;
}
return serialized.value;
});
}
function makeThreadWriter(input: {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly streamLabel: string;
}): Effect.Effect<ThreadWriter | undefined> {
return Effect.gen(function* () {
const sinkResult = yield* Effect.sync(() => {
try {
return {
ok: true as const,
sink: new RotatingFileSink({
filePath: input.filePath,
maxBytes: input.maxBytes,
maxFiles: input.maxFiles,
throwOnError: true,
}),
};
} catch (error) {
return { ok: false as const, error };
}
});
if (!sinkResult.ok) {
yield* logWarning("failed to initialize provider thread log file", {
filePath: input.filePath,
error: sinkResult.error,
});
return undefined;
}
const sink = sinkResult.sink;
const scope = yield* Scope.make();
const lineLogger = makeLineLogger(input.streamLabel);
const batchedLogger = yield* Logger.batched(lineLogger, {
window: input.batchWindowMs,
flush: (messages) =>
Effect.gen(function* () {
const flushResult = yield* Effect.sync(() => {
try {
for (const message of messages) {
sink.write(message);
}
return { ok: true as const };
} catch (error) {
return { ok: false as const, error };
}
});
if (!flushResult.ok) {
yield* logWarning("provider event log batch flush failed", {
filePath: input.filePath,
error: flushResult.error,
});
}
}),
}).pipe(Effect.provideService(Scope.Scope, scope));
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
return {
writeMessage(message: string) {
return Effect.log(message).pipe(Effect.provide(loggerLayer));
},
close() {
return Scope.close(scope, Exit.void);
},
} satisfies ThreadWriter;
});
}
export function makeEventNdjsonLogger(
filePath: string,
options: EventNdjsonLoggerOptions,
): Effect.Effect<EventNdjsonLogger | undefined> {
return Effect.gen(function* () {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
const streamLabel = resolveStreamLabel(options.stream);
const directoryReady = yield* Effect.sync(() => {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
return true;
} catch (error) {
return { ok: false as const, error };
}
});
if (directoryReady !== true) {
yield* logWarning("failed to create provider event log directory", {
filePath,
error: directoryReady.error,
});
return undefined;
}
const threadWriters = new Map<string, ThreadWriter>();
const failedSegments = new Set<string>();
const resolveThreadWriter = (threadSegment: string): Effect.Effect<ThreadWriter | undefined> =>
Effect.gen(function* () {
if (failedSegments.has(threadSegment)) {
return undefined;
}
const existing = threadWriters.get(threadSegment);
if (existing) {
return existing;
}
const writer = yield* makeThreadWriter({
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
});
if (!writer) {
failedSegments.add(threadSegment);
return undefined;
}
threadWriters.set(threadSegment, writer);
return writer;
});
return {
filePath,
write(record: unknown) {
if (broken) {
return;
}
const serialized = stringifyRecord(record);
if (!serialized) {
return;
}
try {
fs.appendFileSync(filePath, `${serialized}\n`, { encoding: "utf8", flag: "a" });
} catch (error) {
broken = true;
logger.warn("provider event log write failed", { filePath, error });
}
write(event: unknown, threadId: ThreadId | null) {
return Effect.gen(function* () {
const threadSegment = resolveThreadSegment(threadId);
const message = yield* toLogMessage(event);
if (!message) {
return;
}
const writer = yield* resolveThreadWriter(threadSegment);
if (!writer) {
return;
}
yield* writer.writeMessage(message);
});
},
close() {
// no-op for sync append logger
return Effect.gen(function* () {
for (const writer of threadWriters.values()) {
yield* writer.close();
}
threadWriters.clear();
});
},
};
} catch (error) {
logger.warn("failed to create provider event log file", { filePath, error });
return undefined;
}
} satisfies EventNdjsonLogger;
});
}
@@ -0,0 +1,176 @@
import assert from "node:assert/strict";
import { it } from "@effect/vitest";
import { Effect } from "effect";
import { checkCodexProviderStatus, parseAuthStatusFromOutput } from "./ProviderHealth";
// ── Test helpers ────────────────────────────────────────────────────
function mockRunner(
handler: (args: ReadonlyArray<string>) => {
stdout: string;
stderr: string;
code: number | null;
timedOut?: boolean;
},
) {
return (args: ReadonlyArray<string>) => Promise.resolve(handler(args));
}
function failingRunner(description: string) {
return () => Promise.reject(new Error(description));
}
// ── Tests ───────────────────────────────────────────────────────────
it.effect("returns ready when codex is installed and authenticated", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus(
mockRunner((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}),
);
it.effect("returns unavailable when codex is missing", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus(failingRunner("spawn codex ENOENT"));
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
}),
);
it.effect("returns unauthenticated when auth probe reports login required", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus(
mockRunner((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}),
);
it.effect(
"returns unauthenticated when login status output includes 'not logged in'",
() =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus(
mockRunner((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}),
);
it.effect("returns warning when login status command is unsupported", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus(
mockRunner((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
);
}),
);
it.effect("returns unavailable when codex version probe times out", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus(
mockRunner((args) => {
const joined = args.join(" ");
if (joined === "--version") {
return { stdout: "", stderr: "", code: null, timedOut: true };
}
throw new Error(`Unexpected args: ${joined}`);
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.message, "Codex CLI is installed but failed to run. Timed out while running command.");
}),
);
it("parseAuthStatusFromOutput: timed out auth check is warning", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "", stderr: "", code: null, timedOut: true });
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
assert.strictEqual(parsed.message, "Timed out while checking Codex authentication status.");
});
// ── Pure function tests ─────────────────────────────────────────────
it("parseAuthStatusFromOutput: exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("parseAuthStatusFromOutput: JSON with authenticated=false is unauthenticated", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"authenticated":false}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("parseAuthStatusFromOutput: JSON without auth marker is warning", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"ok":true}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
@@ -0,0 +1,311 @@
/**
* ProviderHealthLive - Startup-time provider health checks.
*
* Performs one-time provider readiness probes when the server starts and
* keeps the resulting snapshot in memory for `server.getConfig`.
*
* Uses the shared process runner to run CLI probes natively.
*
* @module ProviderHealthLive
*/
import type {
ServerProviderAuthStatus,
ServerProviderStatus,
ServerProviderStatusState,
} from "@t3tools/contracts";
import { Data, Effect, Layer, Result } from "effect";
import { runProcess } from "../../processRunner";
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
const DEFAULT_TIMEOUT_MS = 4_000;
const CODEX_PROVIDER = "codex" as const;
class ProviderHealthCommandError extends Data.TaggedError("ProviderHealthCommandError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
// ── Pure helpers ────────────────────────────────────────────────────
export interface CommandResult {
readonly stdout: string;
readonly stderr: string;
readonly code: number | null;
readonly timedOut?: boolean;
}
function errorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (
error &&
typeof error === "object" &&
"message" in error &&
typeof (error as { message?: unknown }).message === "string"
) {
return (error as { message: string }).message;
}
return String(error);
}
function nonEmptyTrimmed(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function isCommandMissingCause(error: unknown): boolean {
const lower = errorMessage(error).toLowerCase();
return (
lower.includes("command not found: codex") ||
lower.includes("spawn codex enoent") ||
lower.includes("enoent") ||
lower.includes("notfound")
);
}
function detailFromResult(
result: CommandResult & { readonly timedOut?: boolean },
): string | undefined {
if (result.timedOut) return "Timed out while running command.";
const stderr = nonEmptyTrimmed(result.stderr);
if (stderr) return stderr;
const stdout = nonEmptyTrimmed(result.stdout);
if (stdout) return stdout;
if (result.code === null) {
return "Command was terminated before reporting an exit code.";
}
if (result.code !== 0) {
return `Command exited with code ${result.code}.`;
}
return undefined;
}
function extractAuthBoolean(value: unknown): boolean | undefined {
if (Array.isArray(value)) {
for (const entry of value) {
const nested = extractAuthBoolean(entry);
if (nested !== undefined) return nested;
}
return undefined;
}
if (!value || typeof value !== "object") return undefined;
const record = value as Record<string, unknown>;
for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
if (typeof record[key] === "boolean") return record[key];
}
for (const key of ["auth", "status", "session", "account"] as const) {
const nested = extractAuthBoolean(record[key]);
if (nested !== undefined) return nested;
}
return undefined;
}
export function parseAuthStatusFromOutput(result: CommandResult): {
readonly status: ServerProviderStatusState;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
if (result.timedOut) {
return {
status: "warning",
authStatus: "unknown",
message: "Timed out while checking Codex authentication status.",
};
}
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
authStatus: "unknown",
message: "Codex CLI authentication status command is unavailable in this Codex version.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `codex login`") ||
lowerOutput.includes("run codex login")
) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
message:
"Could not verify Codex authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
message: detail
? `Could not verify Codex authentication status. ${detail}`
: "Could not verify Codex authentication status.",
};
}
export type RunProviderHealthCommand = (
args: ReadonlyArray<string>,
) => Promise<CommandResult>;
const defaultRunCodexCommand: RunProviderHealthCommand = async (args) => {
const result = await runProcess("codex", [...args], {
allowNonZeroExit: true,
timeoutMs: DEFAULT_TIMEOUT_MS,
maxBufferBytes: 262_144,
outputMode: "truncate",
});
return {
stdout: result.stdout,
stderr: result.stderr,
code: result.code,
timedOut: result.timedOut,
} satisfies CommandResult;
};
// ── Health check ────────────────────────────────────────────────────
export const checkCodexProviderStatus = (
runCodexCommand: RunProviderHealthCommand = defaultRunCodexCommand,
): Effect.Effect<ServerProviderStatus> =>
Effect.gen(function* () {
const checkedAt = new Date().toISOString();
// Probe 1: `codex --version` — is the CLI reachable?
const versionProbe = yield* Effect.tryPromise({
try: () => runCodexCommand(["--version"]),
catch: (error) =>
new ProviderHealthCommandError({
message: errorMessage(error),
...(error !== undefined ? { cause: error } : {}),
}),
}).pipe(Effect.result);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${errorMessage(error)}.`,
};
}
const version = versionProbe.success;
if (version.timedOut || version.code !== 0) {
const detail = detailFromResult(version);
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
};
}
// Probe 2: `codex login status` — is the user authenticated?
const authProbe = yield* Effect.tryPromise({
try: () => runCodexCommand(["login", "status"]),
catch: (error) =>
new ProviderHealthCommandError({
message: errorMessage(error),
...(error !== undefined ? { cause: error } : {}),
}),
}).pipe(Effect.result);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return {
provider: CODEX_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message:
errorMessage(error).length > 0
? `Could not verify Codex authentication status: ${errorMessage(error)}.`
: "Could not verify Codex authentication status.",
};
}
const parsed = parseAuthStatusFromOutput(authProbe.success);
return {
provider: CODEX_PROVIDER,
status: parsed.status,
available: true,
authStatus: parsed.authStatus,
checkedAt,
...(parsed.message ? { message: parsed.message } : {}),
} satisfies ServerProviderStatus;
});
// ── Layer ───────────────────────────────────────────────────────────
export const ProviderHealthLive = Layer.effect(
ProviderHealth,
Effect.gen(function* () {
const codexStatus = yield* checkCodexProviderStatus();
return {
getStatuses: Effect.succeed([codexStatus]),
} satisfies ProviderHealthShape;
}),
);
@@ -47,6 +47,7 @@ import {
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
@@ -377,6 +378,7 @@ it.effect(
[
{
provider: "codex",
cwd: "/tmp/project",
resumeThreadId: startedSession.threadId,
},
],
@@ -464,6 +466,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
[
{
provider: "codex",
cwd: "/tmp/project",
resumeThreadId: initial.threadId,
},
],
@@ -474,6 +477,38 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const initial = yield* provider.startSession(asThreadId("thread-1"), {
provider: "codex",
cwd: "/tmp/project-send-turn",
});
yield* provider.stopAll();
routing.codex.startSession.mockClear();
routing.codex.sendTurn.mockClear();
yield* provider.sendTurn({
sessionId: initial.sessionId,
input: "resume",
attachments: [],
});
assert.deepEqual(routing.codex.startSession.mock.calls, [
[
{
provider: "codex",
cwd: "/tmp/project-send-turn",
resumeThreadId: initial.threadId,
},
],
]);
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
}),
);
it.effect("stops all sessions and clears adapter runtime", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -564,7 +599,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
threadId: asProviderThreadId("thread-1"),
turnId: asTurnId("turn-1"),
status: "completed",
};
@@ -612,7 +647,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
threadId: asProviderThreadId("thread-1"),
turnId: asTurnId("turn-1"),
toolKind: "command",
title: "Command run",
@@ -624,7 +659,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
threadId: asProviderThreadId("thread-1"),
turnId: asTurnId("turn-1"),
delta: "hello",
},
@@ -634,7 +669,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
threadId: asProviderThreadId("thread-1"),
turnId: asTurnId("turn-1"),
status: "completed",
},
@@ -30,10 +30,11 @@ import {
ProviderSessionDirectory,
type ProviderSessionBinding,
} from "../Services/ProviderSessionDirectory.ts";
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
export interface ProviderServiceLiveOptions {
readonly canonicalEventLogPath?: string;
readonly canonicalEventLogger?: EventNdjsonLogger;
}
const ProviderRollbackConversationInput = Schema.Struct({
@@ -93,12 +94,27 @@ function toRuntimePayloadFromSession(session: ProviderSession): Record<string, u
};
}
function readPersistedCwd(
runtimePayload: ProviderSessionBinding["runtimePayload"],
): string | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined;
if (typeof rawCwd !== "string") return undefined;
const trimmed = rawCwd.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
Effect.gen(function* () {
const canonicalEventLogger =
options?.canonicalEventLogPath !== undefined
? makeEventNdjsonLogger(options.canonicalEventLogPath)
: undefined;
options?.canonicalEventLogger ??
(options?.canonicalEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
stream: "canonical",
})
: undefined);
const registry = yield* ProviderAdapterRegistry;
const directory = yield* ProviderSessionDirectory;
@@ -128,12 +144,20 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
canonicalizeRuntimeEventSession(event).pipe(
Effect.tap((canonicalEvent) =>
Effect.sync(() => {
canonicalEventLogger?.write({
observedAt: new Date().toISOString(),
event: canonicalEvent,
});
}),
canonicalEventLogger
? Effect.flatMap(
Effect.catch(
directory.getThreadId(canonicalEvent.sessionId).pipe(
Effect.map((threadIdOption) =>
Option.isSome(threadIdOption) ? threadIdOption.value : null,
),
),
() => Effect.succeed<ThreadId | null>(null),
),
(orchestrationThreadId) =>
canonicalEventLogger.write(canonicalEvent, orchestrationThreadId),
)
: Effect.void,
),
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
Effect.asVoid,
@@ -266,8 +290,11 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
);
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(resumeThreadId ? { resumeThreadId } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
});
@@ -26,6 +26,7 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
return Layer.mergeAll(
runtimeRepositoryLayer,
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
NodeServices.layer,
);
}
@@ -223,5 +224,5 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
}).pipe(Effect.provide(directoryLayer));
fs.rmSync(tempDir, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)));
}));
});
@@ -0,0 +1,22 @@
/**
* ProviderHealth - Provider readiness snapshot service.
*
* Owns startup-time provider health checks (install/auth reachability) and
* exposes the cached results to transport layers.
*
* @module ProviderHealth
*/
import type { ServerProviderStatus } from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
export interface ProviderHealthShape {
/**
* Read provider health statuses computed at server startup.
*/
readonly getStatuses: Effect.Effect<ReadonlyArray<ServerProviderStatus>>;
}
export class ProviderHealth extends ServiceMap.Service<ProviderHealth, ProviderHealthShape>()(
"t3/provider/Services/ProviderHealth",
) {}
@@ -0,0 +1,72 @@
import { describe, expect, it } from "vitest";
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
describe("detectServerRuntimeEnvironment", () => {
it("detects native windows mode", () => {
expect(
detectServerRuntimeEnvironment({
platform: "win32",
env: {},
osRelease: "10.0.26100",
}),
).toEqual({
platform: "windows",
pathStyle: "windows",
isWsl: false,
windowsInteropMode: "windows-native",
wslDistroName: null,
});
});
it("detects wsl-hosted mode from environment variables", () => {
expect(
detectServerRuntimeEnvironment({
platform: "linux",
env: {
WSL_DISTRO_NAME: "Ubuntu-24.04",
WSL_INTEROP: "/run/WSL/123_interop",
},
osRelease: "6.6.87.2-microsoft-standard-WSL2",
}),
).toEqual({
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu-24.04",
});
});
it("detects wsl-hosted mode from os release when env is unavailable", () => {
expect(
detectServerRuntimeEnvironment({
platform: "linux",
env: {},
osRelease: "5.15.167.4-microsoft-standard-WSL2",
}),
).toEqual({
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: null,
});
});
it("leaves non-wsl posix hosts outside the windows interop modes", () => {
expect(
detectServerRuntimeEnvironment({
platform: "darwin",
env: {},
osRelease: "24.3.0",
}),
).toEqual({
platform: "macos",
pathStyle: "posix",
isWsl: false,
windowsInteropMode: null,
wslDistroName: null,
});
});
});
+54
View File
@@ -0,0 +1,54 @@
import os from "node:os";
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
interface DetectServerRuntimeEnvironmentOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
readonly osRelease?: string;
}
function normalizePlatform(platform: NodeJS.Platform): ServerRuntimeEnvironment["platform"] {
switch (platform) {
case "win32":
return "windows";
case "darwin":
return "macos";
default:
return "linux";
}
}
function detectWsl(options: {
readonly platform: NodeJS.Platform;
readonly env: NodeJS.ProcessEnv;
readonly osRelease: string;
}): boolean {
if (options.platform !== "linux") {
return false;
}
if (options.env.WSL_DISTRO_NAME || options.env.WSL_INTEROP) {
return true;
}
return options.osRelease.toLowerCase().includes("microsoft");
}
export function detectServerRuntimeEnvironment(
options: DetectServerRuntimeEnvironmentOptions = {},
): ServerRuntimeEnvironment {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const osRelease = options.osRelease ?? os.release();
const normalizedPlatform = normalizePlatform(platform);
const isWsl = detectWsl({ platform, env, osRelease });
return {
platform: normalizedPlatform,
pathStyle: normalizedPlatform === "windows" ? "windows" : "posix",
isWsl,
windowsInteropMode: normalizedPlatform === "windows" ? "windows-native" : isWsl ? "wsl-hosted" : null,
wslDistroName: isWsl ? env.WSL_DISTRO_NAME?.trim() || null : null,
};
}
+34 -16
View File
@@ -1,7 +1,7 @@
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, Layer } from "effect";
import { Effect, FileSystem, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
@@ -23,6 +23,7 @@ import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRe
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
import { ProviderService } from "./provider/Services/ProviderService";
import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger";
import { TerminalManagerLive } from "./terminal/Layers/Manager";
import { KeybindingsLive } from "./keybindings";
@@ -37,40 +38,53 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
export function makeServerProviderLayer(): Layer.Layer<
ProviderService,
ProviderUnsupportedError,
SqlClient.SqlClient | ServerConfig
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | NodeServices.NodeServices
> {
return Effect.gen(function* () {
const { stateDir } = yield* ServerConfig;
const providerLogsDir = path.join(stateDir, "logs", "providers");
const codexAdapterLayer = makeCodexAdapterLive({
nativeEventLogPath: path.join(providerLogsDir, "provider-native.ndjson"),
const providerLogsDir = path.join(stateDir, "logs", "provider");
const providerEventLogPath = path.join(providerLogsDir, "events.log");
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "canonical",
});
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(Layer.provide(codexAdapterLayer));
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
);
return makeProviderServiceLive({
canonicalEventLogPath: path.join(providerLogsDir, "provider-canonical.ndjson"),
}).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
const codexAdapterLayer = makeCodexAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
Layer.provide(codexAdapterLayer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
return makeProviderServiceLive(
canonicalEventLogger ? { canonicalEventLogger } : undefined,
).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
}).pipe(Layer.unwrap);
}
export function makeServerRuntimeServicesLayer() {
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
const textGenerationLayer = CodexTextGenerationLive;
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
Layer.provideMerge(checkpointStoreLayer),
Layer.provideMerge(CheckpointStoreLive),
);
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
checkpointStoreLayer,
CheckpointStoreLive,
checkpointDiffQueryLayer,
);
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
@@ -78,6 +92,8 @@ export function makeServerRuntimeServicesLayer() {
);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(textGenerationLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
@@ -89,15 +105,17 @@ export function makeServerRuntimeServicesLayer() {
);
const terminalLayer = TerminalManagerLive.pipe(
Layer.provide(typeof Bun !== "undefined" ? BunPtyAdapterLive : NodePtyAdapterLive),
Layer.provide(
typeof Bun !== "undefined" && process.platform !== "win32"
? BunPtyAdapterLive
: NodePtyAdapterLive,
),
);
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
const gitManagerLayer = GitManagerLive.pipe(
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(CodexTextGenerationLive),
Layer.provideMerge(textGenerationLayer),
);
return Layer.mergeAll(
+112 -1
View File
@@ -4,6 +4,7 @@ import path from "node:path";
import {
DEFAULT_TERMINAL_ID,
type ServerRuntimeEnvironment,
type TerminalEvent,
type TerminalOpenInput,
} from "@t3tools/contracts";
@@ -16,7 +17,11 @@ import {
type PtyProcess,
type PtySpawnInput,
} from "../Services/PTY";
import { TerminalManagerRuntime } from "./Manager";
import {
resolveShellCandidates,
TerminalManagerRuntime,
validateTerminalCwdForRuntime,
} from "./Manager";
import { Effect, Encoding } from "effect";
class FakePtyProcess implements PtyProcess {
@@ -172,6 +177,7 @@ describe("TerminalManager", () => {
options: {
shellResolver?: () => string;
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
runtimeEnvironment?: ServerRuntimeEnvironment;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
maxRetainedInactiveSessions?: number;
@@ -186,6 +192,7 @@ describe("TerminalManager", () => {
ptyAdapter,
historyLineLimit,
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
...(options.runtimeEnvironment ? { runtimeEnvironment: options.runtimeEnvironment } : {}),
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
...(options.subprocessPollIntervalMs
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
@@ -394,6 +401,21 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("ignores trailing writes after terminal exit", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitExit({ exitCode: 0, signal: 0 });
await expect(manager.write({ threadId: "thread-1", data: "\r" })).resolves.toBeUndefined();
expect(process.writes).toEqual([]);
manager.dispose();
});
it("emits subprocess activity events when child-process state changes", async () => {
let hasRunningSubprocess = false;
const { manager } = makeManager(5, {
@@ -654,4 +676,93 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("resolves Windows shell candidates from runtime environment instead of host assumptions", () => {
const runtimeEnvironment: ServerRuntimeEnvironment = {
platform: "windows",
pathStyle: "windows",
isWsl: false,
windowsInteropMode: "windows-native",
wslDistroName: null,
};
const candidates = resolveShellCandidates(() => "/bin/bash -l", runtimeEnvironment);
expect(candidates.map((candidate) => candidate.shell)).toContain("cmd.exe");
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
expect(candidates.map((candidate) => candidate.shell)).not.toContain("/bin/sh");
});
it("resolves POSIX shell candidates for wsl-hosted runtime even when the requested shell is Windows-style", () => {
const runtimeEnvironment: ServerRuntimeEnvironment = {
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu",
};
const candidates = resolveShellCandidates(() => "powershell.exe", runtimeEnvironment);
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
expect(candidates.map((candidate) => candidate.shell)).toContain("/bin/bash");
expect(candidates.map((candidate) => candidate.shell)).toContain("sh");
});
it("rejects POSIX cwd values for windows-native terminal runtimes", async () => {
const runtimeEnvironment: ServerRuntimeEnvironment = {
platform: "windows",
pathStyle: "windows",
isWsl: false,
windowsInteropMode: "windows-native",
wslDistroName: null,
};
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
await expect(manager.open(openInput({ cwd: "/home/julius/project" }))).rejects.toThrow(
"Terminal cwd does not match Windows runtime path style",
);
expect(ptyAdapter.spawnInputs).toHaveLength(0);
manager.dispose();
});
it("rejects Windows cwd values for wsl-hosted terminal runtimes", async () => {
const runtimeEnvironment: ServerRuntimeEnvironment = {
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu",
};
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
await expect(manager.open(openInput({ cwd: "C:\\Users\\julius\\project" }))).rejects.toThrow(
"Terminal cwd does not match POSIX runtime path style",
);
expect(ptyAdapter.spawnInputs).toHaveLength(0);
manager.dispose();
});
it("validates cwd compatibility as a pure runtime helper", () => {
expect(
validateTerminalCwdForRuntime("/repo", {
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu",
}),
).toBeNull();
expect(
validateTerminalCwdForRuntime("\\\\wsl.localhost\\Ubuntu\\repo", {
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu",
}),
).toContain("POSIX runtime path style");
});
});
+92 -29
View File
@@ -9,12 +9,14 @@ import {
TerminalOpenInput,
TerminalResizeInput,
TerminalWriteInput,
type ServerRuntimeEnvironment,
type TerminalEvent,
type TerminalSessionSnapshot,
} from "@t3tools/contracts";
import { Effect, Encoding, Layer, Path, Schema } from "effect";
import { createLogger } from "../../logger";
import { detectServerRuntimeEnvironment } from "../../runtimeEnvironment";
import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY";
import { runProcess } from "../../processRunner";
import { ServerConfig } from "../../config";
@@ -35,6 +37,8 @@ const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
const DEFAULT_OPEN_COLS = 120;
const DEFAULT_OPEN_ROWS = 30;
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput);
const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput);
@@ -44,19 +48,22 @@ const decodeTerminalCloseInput = Schema.decodeUnknownSync(TerminalCloseInput);
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
function defaultShellResolver(): string {
if (process.platform === "win32") {
function defaultShellResolver(runtimeEnvironment: ServerRuntimeEnvironment): string {
if (runtimeEnvironment.platform === "windows") {
return process.env.ComSpec ?? "cmd.exe";
}
return process.env.SHELL ?? "bash";
}
function normalizeShellCommand(value: string | undefined): string | null {
function normalizeShellCommand(
value: string | undefined,
runtimeEnvironment: ServerRuntimeEnvironment,
): string | null {
if (!value) return null;
const trimmed = value.trim();
if (trimmed.length === 0) return null;
if (process.platform === "win32") {
if (runtimeEnvironment.platform === "windows") {
return trimmed;
}
@@ -65,10 +72,13 @@ function normalizeShellCommand(value: string | undefined): string | null {
return firstToken.replace(/^['"]|['"]$/g, "");
}
function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
function shellCandidateFromCommand(
command: string | null,
runtimeEnvironment: ServerRuntimeEnvironment,
): ShellCandidate | null {
if (!command || command.length === 0) return null;
const shellName = path.basename(command).toLowerCase();
if (process.platform !== "win32" && shellName === "zsh") {
if (runtimeEnvironment.platform !== "windows" && shellName === "zsh") {
return { shell: command, args: ["-o", "nopromptsp"] };
}
return { shell: command };
@@ -92,27 +102,36 @@ function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellC
return ordered;
}
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
export function resolveShellCandidates(
shellResolver: () => string,
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
): ShellCandidate[] {
const requested = shellCandidateFromCommand(
normalizeShellCommand(shellResolver(), runtimeEnvironment),
runtimeEnvironment,
);
if (process.platform === "win32") {
if (runtimeEnvironment.platform === "windows") {
return uniqueShellCandidates([
requested,
shellCandidateFromCommand(process.env.ComSpec ?? null),
shellCandidateFromCommand("powershell.exe"),
shellCandidateFromCommand("cmd.exe"),
shellCandidateFromCommand(process.env.ComSpec ?? null, runtimeEnvironment),
shellCandidateFromCommand("powershell.exe", runtimeEnvironment),
shellCandidateFromCommand("cmd.exe", runtimeEnvironment),
]);
}
return uniqueShellCandidates([
requested,
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
shellCandidateFromCommand("/bin/zsh"),
shellCandidateFromCommand("/bin/bash"),
shellCandidateFromCommand("/bin/sh"),
shellCandidateFromCommand("zsh"),
shellCandidateFromCommand("bash"),
shellCandidateFromCommand("sh"),
shellCandidateFromCommand(
normalizeShellCommand(process.env.SHELL, runtimeEnvironment),
runtimeEnvironment,
),
shellCandidateFromCommand("/bin/zsh", runtimeEnvironment),
shellCandidateFromCommand("/bin/bash", runtimeEnvironment),
shellCandidateFromCommand("/bin/sh", runtimeEnvironment),
shellCandidateFromCommand("zsh", runtimeEnvironment),
shellCandidateFromCommand("bash", runtimeEnvironment),
shellCandidateFromCommand("sh", runtimeEnvironment),
]);
}
@@ -178,6 +197,13 @@ async function checkWindowsSubprocessActivity(terminalPid: number): Promise<bool
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
runtimeEnvironment: {
platform: "windows",
pathStyle: "windows",
isWsl: false,
windowsInteropMode: "windows-native",
wslDistroName: null,
},
},
);
return result.code === 0;
@@ -230,14 +256,37 @@ async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolea
}
}
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return false;
function createDefaultSubprocessChecker(runtimeEnvironment: ServerRuntimeEnvironment) {
return async (terminalPid: number): Promise<boolean> => {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return false;
}
if (runtimeEnvironment.platform === "windows") {
return checkWindowsSubprocessActivity(terminalPid);
}
return checkPosixSubprocessActivity(terminalPid);
};
}
function isWindowsPath(value: string): boolean {
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
}
export function validateTerminalCwdForRuntime(
cwd: string,
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
): string | null {
if (runtimeEnvironment.pathStyle === "windows") {
if (cwd.startsWith("/")) {
return `Terminal cwd does not match Windows runtime path style: ${cwd}`;
}
return null;
}
if (process.platform === "win32") {
return checkWindowsSubprocessActivity(terminalPid);
if (isWindowsPath(cwd)) {
return `Terminal cwd does not match POSIX runtime path style: ${cwd}`;
}
return checkPosixSubprocessActivity(terminalPid);
return null;
}
function capHistory(history: string, maxLines: number): string {
@@ -316,6 +365,7 @@ interface TerminalManagerOptions {
ptyAdapter: PtyAdapterShape;
shellResolver?: () => string;
subprocessChecker?: TerminalSubprocessChecker;
runtimeEnvironment?: ServerRuntimeEnvironment;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
maxRetainedInactiveSessions?: number;
@@ -333,6 +383,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
private readonly threadLocks = new Map<string, Promise<void>>();
private readonly persistDebounceMs: number;
private readonly subprocessChecker: TerminalSubprocessChecker;
private readonly runtimeEnvironment: ServerRuntimeEnvironment;
private readonly subprocessPollIntervalMs: number;
private readonly processKillGraceMs: number;
private readonly maxRetainedInactiveSessions: number;
@@ -343,12 +394,15 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
constructor(options: TerminalManagerOptions) {
super();
this.runtimeEnvironment = options.runtimeEnvironment ?? detectServerRuntimeEnvironment();
this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals");
this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
this.ptyAdapter = options.ptyAdapter;
this.shellResolver = options.shellResolver ?? defaultShellResolver;
this.shellResolver =
options.shellResolver ?? (() => defaultShellResolver(this.runtimeEnvironment));
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
this.subprocessChecker =
options.subprocessChecker ?? createDefaultSubprocessChecker(this.runtimeEnvironment);
this.subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
@@ -438,6 +492,9 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
const input = decodeTerminalWriteInput(raw);
const session = this.requireSession(input.threadId, input.terminalId);
if (!session.process || session.status !== "running") {
if (session.status === "exited") {
return;
}
throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
@@ -586,7 +643,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
let ptyProcess: PtyProcess | null = null;
let startedShell: string | null = null;
try {
const shellCandidates = resolveShellCandidates(this.shellResolver);
const shellCandidates = resolveShellCandidates(this.shellResolver, this.runtimeEnvironment);
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
let lastSpawnError: unknown = null;
@@ -1048,6 +1105,11 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
}
private async assertValidCwd(cwd: string): Promise<void> {
const runtimePathError = validateTerminalCwdForRuntime(cwd, this.runtimeEnvironment);
if (runtimePathError) {
throw new Error(runtimePathError);
}
let stats: fs.Stats;
try {
stats = await fs.promises.stat(cwd);
@@ -1170,10 +1232,11 @@ export const TerminalManagerLive = Layer.effect(
const { stateDir } = yield* ServerConfig;
const { join } = yield* Path.Path;
const logsDir = join(stateDir, "logs", "terminals");
const runtimeEnvironment = detectServerRuntimeEnvironment();
const ptyAdapter = yield* PtyAdapter;
const runtime = yield* Effect.acquireRelease(
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter, runtimeEnvironment })),
(r) => Effect.sync(() => r.dispose()),
);
+285 -10
View File
@@ -3,7 +3,8 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { Effect, Exit, Layer, PubSub, Scope, Stream } from "effect";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
import WebSocket from "ws";
@@ -12,6 +13,7 @@ import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serve
import {
DEFAULT_TERMINAL_ID,
EDITORS,
EventId,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
@@ -23,6 +25,7 @@ import {
WS_METHODS,
type WebSocketResponse,
type ProviderRuntimeEvent,
type ServerProviderStatus,
type KeybindingsConfig,
type ResolvedKeybindingsConfig,
type WsPush,
@@ -38,14 +41,17 @@ import type {
TerminalWriteInput,
} from "@t3tools/contracts";
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager";
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
import { SqlClient } from "effect/unstable/sql";
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
import { SqlClient, SqlError } from "effect/unstable/sql";
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
import { ProviderHealth, type ProviderHealthShape } from "./provider/Services/ProviderHealth";
import { Open, type OpenShape } from "./open";
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
import type { GitCoreShape } from "./git/Services/GitCore.ts";
import { GitCore } from "./git/Services/GitCore.ts";
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
interface PendingMessages {
queue: unknown[];
@@ -66,6 +72,22 @@ const defaultOpenService: OpenShape = {
openInEditor: () => Effect.void,
};
const defaultProviderStatuses: ReadonlyArray<ServerProviderStatus> = [
{
provider: "codex",
status: "ready",
available: true,
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
},
];
const defaultProviderHealthService: ProviderHealthShape = {
getStatuses: Effect.succeed(defaultProviderStatuses),
};
const defaultRuntimeEnvironment = detectServerRuntimeEnvironment();
class MockTerminalManager implements TerminalManagerShape {
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
private readonly listeners = new Set<(event: TerminalEvent) => void>();
@@ -295,6 +317,36 @@ async function waitForPush(
return take(maxMessages);
}
async function requestPath(
port: number,
requestPath: string,
): Promise<{ statusCode: number; body: string }> {
return new Promise((resolve, reject) => {
const req = Http.request(
{
hostname: "127.0.0.1",
port,
path: requestPath,
method: "GET",
},
(res) => {
const chunks: Buffer[] = [];
res.on("data", (chunk) => {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
});
res.on("end", () => {
resolve({
statusCode: res.statusCode ?? 0,
body: Buffer.concat(chunks).toString("utf8"),
});
});
},
);
req.once("error", reject);
req.end();
});
}
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
const resolved: Array<ResolvedKeybindingsConfig[number]> = [];
for (const binding of bindings) {
@@ -308,6 +360,15 @@ function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsCon
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
const VALID_EDITOR_IDS = new Set(EDITORS.map((editor) => editor.id));
function expectAvailableEditors(value: unknown): void {
expect(Array.isArray(value)).toBe(true);
for (const editorId of value as unknown[]) {
expect(typeof editorId).toBe("string");
expect(VALID_EDITOR_IDS.has(editorId as (typeof EDITORS)[number]["id"])).toBe(true);
}
}
describe("WebSocket Server", () => {
let server: Http.Server | null = null;
@@ -323,17 +384,25 @@ describe("WebSocket Server", () => {
async function createTestServer(
options: {
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, never>;
persistenceLayer?: Layer.Layer<
SqlClient.SqlClient,
SqlError.SqlError | MigrationError | PlatformError.PlatformError
>;
cwd?: string;
autoBootstrapProjectFromCwd?: boolean;
logWebSocketEvents?: boolean;
devUrl?: string;
authToken?: string;
stateDir?: string;
staticDir?: string;
providerLayer?: Layer.Layer<ProviderService, never>;
providerHealth?: ProviderHealthShape;
open?: OpenShape;
gitManager?: GitManagerShape;
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
gitCore?: Pick<
GitCoreShape,
"listBranches" | "initRepo" | "pullCurrentBranch"
>;
terminalManager?: TerminalManagerShape;
} = {},
): Promise<Http.Server> {
@@ -345,6 +414,10 @@ describe("WebSocket Server", () => {
const scope = await Effect.runPromise(Scope.make("sequential"));
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
const providerHealthLayer = Layer.succeed(
ProviderHealth,
options.providerHealth ?? defaultProviderHealthService,
);
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
const serverConfigLayer = Layer.succeed(ServerConfig, {
mode: "web",
@@ -353,7 +426,7 @@ describe("WebSocket Server", () => {
cwd: options.cwd ?? "/test/project",
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
stateDir,
staticDir: undefined,
staticDir: options.staticDir,
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
noBrowser: true,
authToken: options.authToken,
@@ -379,8 +452,10 @@ describe("WebSocket Server", () => {
);
const dependenciesLayer = Layer.empty.pipe(
Layer.provideMerge(runtimeLayer),
Layer.provideMerge(providerHealthLayer),
Layer.provideMerge(openLayer),
Layer.provideMerge(serverConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
const runtimeServices = await Effect.runPromise(
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
@@ -437,6 +512,80 @@ describe("WebSocket Server", () => {
});
});
it("serves persisted attachments from stateDir", async () => {
const stateDir = makeTempDir("t3code-state-attachments-");
const attachmentPath = path.join(stateDir, "attachments", "thread-a", "message-a", "0.png");
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
fs.writeFileSync(attachmentPath, Buffer.from("hello-attachment"));
server = await createTestServer({ cwd: "/test/project", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const response = await fetch(`http://127.0.0.1:${port}/attachments/thread-a/message-a/0.png`);
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toContain("image/png");
const bytes = Buffer.from(await response.arrayBuffer());
expect(bytes).toEqual(Buffer.from("hello-attachment"));
});
it("serves persisted attachments for URL-encoded paths", async () => {
const stateDir = makeTempDir("t3code-state-attachments-encoded-");
const attachmentPath = path.join(
stateDir,
"attachments",
"thread%20folder",
"message%20folder",
"file%20name.png",
);
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
fs.writeFileSync(attachmentPath, Buffer.from("hello-encoded-attachment"));
server = await createTestServer({ cwd: "/test/project", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const response = await fetch(
`http://127.0.0.1:${port}/attachments/thread%20folder/message%20folder/file%20name.png`,
);
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toContain("image/png");
const bytes = Buffer.from(await response.arrayBuffer());
expect(bytes).toEqual(Buffer.from("hello-encoded-attachment"));
});
it("serves static index for root path", async () => {
const stateDir = makeTempDir("t3code-state-static-root-");
const staticDir = makeTempDir("t3code-static-root-");
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>static-root</h1>", "utf8");
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const response = await fetch(`http://127.0.0.1:${port}/`);
expect(response.status).toBe(200);
expect(await response.text()).toContain("static-root");
});
it("rejects static path traversal attempts", async () => {
const stateDir = makeTempDir("t3code-state-static-traversal-");
const staticDir = makeTempDir("t3code-static-traversal-");
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>safe</h1>", "utf8");
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const response = await requestPath(port, "/..%2f..%2fetc/passwd");
expect(response.statusCode).toBe(400);
expect(response.body).toBe("Invalid static file path");
});
it("bootstraps the cwd project on startup when enabled", async () => {
server = await createTestServer({
cwd: "/test/bootstrap-workspace",
@@ -448,23 +597,117 @@ describe("WebSocket Server", () => {
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws); // welcome
const welcome = (await waitForMessage(ws)) as WsPush; // welcome
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
expect(welcome.data).toEqual(
expect.objectContaining({
cwd: "/test/bootstrap-workspace",
projectName: "bootstrap-workspace",
bootstrapProjectId: expect.any(String),
bootstrapThreadId: expect.any(String),
}),
);
const snapshotResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getSnapshot);
expect(snapshotResponse.error).toBeUndefined();
const snapshot = snapshotResponse.result as {
projects: Array<{ workspaceRoot: string; title: string; defaultModel: string | null }>;
projects: Array<{
id: string;
workspaceRoot: string;
title: string;
defaultModel: string | null;
}>;
threads: Array<{
id: string;
projectId: string;
title: string;
model: string;
branch: string | null;
worktreePath: string | null;
}>;
};
const bootstrapProjectId = (welcome.data as { bootstrapProjectId?: string }).bootstrapProjectId;
const bootstrapThreadId = (welcome.data as { bootstrapThreadId?: string }).bootstrapThreadId;
expect(bootstrapProjectId).toBeDefined();
expect(bootstrapThreadId).toBeDefined();
expect(snapshot.projects).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: bootstrapProjectId,
workspaceRoot: "/test/bootstrap-workspace",
title: "bootstrap-workspace",
defaultModel: "gpt-5-codex",
}),
]),
);
expect(snapshot.threads).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: bootstrapThreadId,
projectId: bootstrapProjectId,
title: "New thread",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
}),
]),
);
});
it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => {
const stateDir = makeTempDir("t3code-state-bootstrap-existing-");
const persistenceLayer = makeSqlitePersistenceLive(path.join(stateDir, "state.sqlite")).pipe(
Layer.provide(NodeServices.layer),
);
const cwd = "/test/bootstrap-existing";
server = await createTestServer({
cwd,
stateDir,
persistenceLayer,
autoBootstrapProjectFromCwd: true,
});
let addr = server.address();
let port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const firstWs = await connectWs(port);
connections.push(firstWs);
const firstWelcome = (await waitForMessage(firstWs)) as WsPush;
const firstBootstrapProjectId = (firstWelcome.data as { bootstrapProjectId?: string })
.bootstrapProjectId;
const firstBootstrapThreadId = (firstWelcome.data as { bootstrapThreadId?: string })
.bootstrapThreadId;
expect(firstBootstrapProjectId).toBeDefined();
expect(firstBootstrapThreadId).toBeDefined();
firstWs.close();
await closeTestServer();
server = null;
server = await createTestServer({
cwd,
stateDir,
persistenceLayer,
autoBootstrapProjectFromCwd: true,
});
addr = server.address();
port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const secondWs = await connectWs(port);
connections.push(secondWs);
const secondWelcome = (await waitForMessage(secondWs)) as WsPush;
expect(secondWelcome.channel).toBe(WS_CHANNELS.serverWelcome);
expect(secondWelcome.data).toEqual(
expect.objectContaining({
cwd,
projectName: "bootstrap-existing",
bootstrapProjectId: firstBootstrapProjectId,
bootstrapThreadId: firstBootstrapThreadId,
}),
);
});
it("logs outbound websocket push events in dev mode", async () => {
@@ -518,7 +761,11 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
runtimeEnvironment: defaultRuntimeEnvironment,
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
});
it("bootstraps default keybindings file when missing", async () => {
@@ -541,7 +788,11 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
runtimeEnvironment: defaultRuntimeEnvironment,
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
const persistedConfig = JSON.parse(
fs.readFileSync(keybindingsPath, "utf8"),
@@ -574,7 +825,11 @@ describe("WebSocket Server", () => {
message: expect.stringContaining("expected JSON array"),
},
],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
runtimeEnvironment: defaultRuntimeEnvironment,
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
});
@@ -606,6 +861,9 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: string;
keybindings: ResolvedKeybindingsConfig;
issues: Array<{ kind: string; index?: number; message: string }>;
providers: ReadonlyArray<ServerProviderStatus>;
availableEditors: unknown;
runtimeEnvironment: unknown;
};
expect(result.cwd).toBe("/my/workspace");
expect(result.keybindingsConfigPath).toBe(keybindingsPath);
@@ -624,6 +882,9 @@ describe("WebSocket Server", () => {
expect(result.keybindings).toHaveLength(DEFAULT_RESOLVED_KEYBINDINGS.length);
expect(result.keybindings.some((entry) => entry.command === "terminal.toggle")).toBe(true);
expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true);
expect(result.providers).toEqual(defaultProviderStatuses);
expectAvailableEditors(result.availableEditors);
expect(result.runtimeEnvironment).toEqual(defaultRuntimeEnvironment);
});
it("pushes server.configUpdated issues when keybindings file changes", async () => {
@@ -651,6 +912,7 @@ describe("WebSocket Server", () => {
);
expect(malformedPush.data).toEqual({
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
providers: defaultProviderStatuses,
});
fs.writeFileSync(keybindingsPath, "[]", "utf8");
@@ -661,7 +923,7 @@ describe("WebSocket Server", () => {
Array.isArray((push.data as { issues?: unknown[] }).issues) &&
(push.data as { issues: unknown[] }).issues.length === 0,
);
expect(successPush.data).toEqual({ issues: [] });
expect(successPush.data).toEqual({ issues: [], providers: defaultProviderStatuses });
});
it("routes shell.openInEditor through the injected open service", async () => {
@@ -721,7 +983,11 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: compileKeybindings(persistedConfig),
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
runtimeEnvironment: defaultRuntimeEnvironment,
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
});
it("upserts keybinding rules and updates cached server config", async () => {
@@ -766,7 +1032,13 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: compileKeybindings(persistedConfig),
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
runtimeEnvironment: defaultRuntimeEnvironment,
});
expectAvailableEditors(
(configResponse.result as { availableEditors: unknown }).availableEditors,
);
});
it("returns error for unknown methods", async () => {
@@ -960,6 +1232,8 @@ describe("WebSocket Server", () => {
attachments: [],
},
assistantDeliveryMode: "streaming",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt,
});
expect(startTurnResponse.error).toBeUndefined();
@@ -1301,6 +1575,7 @@ describe("WebSocket Server", () => {
expect(pullResponse.result).toBeUndefined();
expect(pullResponse.error?.message).toContain("No upstream configured");
expect(pullCurrentBranch).toHaveBeenCalledWith("/repo/path");
});
it("supports git.status over websocket", async () => {
@@ -1315,7 +1590,7 @@ describe("WebSocket Server", () => {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
openPr: null,
pr: null,
};
const status = vi.fn(() => Effect.succeed(statusResult));
+342 -80
View File
@@ -6,16 +6,19 @@
*
* @module Server
*/
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import type { Duplex } from "node:stream";
import Mime from "@effect/platform-node/Mime";
import {
CommandId,
type ClientOrchestrationCommand,
type OrchestrationCommand,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
ProjectId,
ThreadId,
TerminalEvent,
WS_CHANNELS,
WS_METHODS,
@@ -24,7 +27,20 @@ import {
WsResponse,
} from "@t3tools/contracts";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import { Cause, Effect, Exit, Layer, Ref, Schema, Scope, ServiceMap, Stream, Struct } from "effect";
import {
Cause,
Effect,
Exit,
FileSystem,
Layer,
Path,
Ref,
Schema,
Scope,
ServiceMap,
Stream,
Struct,
} from "effect";
import { WebSocketServer, type WebSocket } from "ws";
import { createLogger } from "./logger";
@@ -36,26 +52,25 @@ import { OrchestrationEngineService } from "./orchestration/Services/Orchestrati
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
import { ProviderService } from "./provider/Services/ProviderService";
import { ProviderHealth } from "./provider/Services/ProviderHealth";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
import { clamp } from "effect/Number";
import { Open } from "./open";
import { Open, resolveAvailableEditors } from "./open";
import { ServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore.ts";
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",
};
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
import {
ATTACHMENTS_ROUTE_PREFIX,
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths";
import {
createAttachmentId,
resolveAttachmentPath,
resolveAttachmentPathById,
} from "./attachmentStore.ts";
import { parseBase64DataUrl } from "./imageMime.ts";
/**
* ServerShape - Service API for server lifecycle control.
@@ -67,7 +82,7 @@ export interface ServerShape {
readonly start: Effect.Effect<
http.Server,
ServerLifecycleError,
Scope.Scope | ServerRuntimeServices | ServerConfig
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
>;
/**
@@ -141,7 +156,8 @@ export type ServerCoreRuntimeServices =
| ProjectionSnapshotQuery
| CheckpointDiffQuery
| OrchestrationReactor
| ProviderService;
| ProviderService
| ProviderHealth;
export type ServerRuntimeServices =
| ServerCoreRuntimeServices
@@ -166,7 +182,7 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
export const createServer = Effect.fn(function* (): Effect.fn.Return<
http.Server,
ServerLifecycleError,
Scope.Scope | ServerRuntimeServices | ServerConfig
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
> {
const serverConfig = yield* ServerConfig;
const {
@@ -180,11 +196,16 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
logWebSocketEvents,
autoBootstrapProjectFromCwd,
} = serverConfig;
const availableEditors = resolveAvailableEditors();
const runtimeEnvironment = detectServerRuntimeEnvironment();
const gitManager = yield* GitManager;
const terminalManager = yield* TerminalManager;
const keybindingsManager = yield* Keybindings;
const providerHealth = yield* ProviderHealth;
const git = yield* GitCore;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
Effect.catch((error) =>
@@ -196,6 +217,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
),
);
const providerStatuses = yield* providerHealth.getStatuses;
const clients = yield* Ref.make(new Set<WebSocket>());
const logger = createLogger("ws");
@@ -229,59 +252,249 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
});
});
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
readonly command: ClientOrchestrationCommand;
}) {
if (input.command.type !== "thread.turn.start") {
return input.command as OrchestrationCommand;
}
const turnStartCommand = input.command;
const normalizedAttachments = yield* Effect.forEach(
turnStartCommand.message.attachments,
(attachment) =>
Effect.gen(function* () {
const parsed = parseBase64DataUrl(attachment.dataUrl);
if (!parsed || !parsed.mimeType.startsWith("image/")) {
return yield* new RouteRequestError({
message: `Invalid image attachment payload for '${attachment.name}'.`,
});
}
const bytes = Buffer.from(parsed.base64, "base64");
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
return yield* new RouteRequestError({
message: `Image attachment '${attachment.name}' is empty or too large.`,
});
}
const attachmentId = createAttachmentId(turnStartCommand.threadId);
if (!attachmentId) {
return yield* new RouteRequestError({
message: "Failed to create a safe attachment id.",
});
}
const persistedAttachment = {
type: "image" as const,
id: attachmentId,
name: attachment.name,
mimeType: parsed.mimeType.toLowerCase(),
sizeBytes: bytes.byteLength,
};
const attachmentPath = resolveAttachmentPath({
stateDir: serverConfig.stateDir,
attachment: persistedAttachment,
});
if (!attachmentPath) {
return yield* new RouteRequestError({
message: `Failed to resolve persisted path for '${attachment.name}'.`,
});
}
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
Effect.mapError(
() =>
new RouteRequestError({
message: `Failed to create attachment directory for '${attachment.name}'.`,
}),
),
);
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
Effect.mapError(
() =>
new RouteRequestError({
message: `Failed to persist attachment '${attachment.name}'.`,
}),
),
);
return persistedAttachment;
}),
{ concurrency: 1 },
);
return {
...turnStartCommand,
message: {
...turnStartCommand.message,
attachments: normalizedAttachments,
},
} satisfies OrchestrationCommand;
});
// 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.href });
res.end();
return;
}
const respond = (
statusCode: number,
headers: Record<string, string>,
body?: string | Uint8Array,
) => {
res.writeHead(statusCode, headers);
res.end(body);
};
// 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");
void Effect.runPromise(
Effect.gen(function* () {
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
if (tryHandleProjectFaviconRequest(url, res)) {
return;
}
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
});
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
if (!normalizedRelativePath) {
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
return;
}
const isIdLookup =
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
const filePath = isIdLookup
? resolveAttachmentPathById({
stateDir: serverConfig.stateDir,
attachmentId: normalizedRelativePath,
})
: resolveAttachmentRelativePath({
stateDir: serverConfig.stateDir,
relativePath: normalizedRelativePath,
});
if (!filePath) {
respond(
isIdLookup ? 404 : 400,
{ "Content-Type": "text/plain" },
isIdLookup ? "Not Found" : "Invalid attachment path",
);
return;
}
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
respond(404, { "Content-Type": "text/plain" }, "Not Found");
return;
}
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
res.writeHead(200, {
"Content-Type": contentType,
"Cache-Control": "public, max-age=31536000, immutable",
});
const streamExit = yield* Stream.runForEach(fileSystem.stream(filePath), (chunk) =>
Effect.sync(() => {
if (!res.destroyed) {
res.write(chunk);
}
}),
).pipe(Effect.exit);
if (streamExit._tag === "Failure") {
if (!res.destroyed) {
res.destroy();
}
return;
}
if (!res.writableEnded) {
res.end();
}
return;
}
// In dev mode, redirect to Vite dev server
if (devUrl) {
respond(302, { Location: devUrl.href });
return;
}
// Serve static files from the web app build
if (!staticDir) {
respond(
503,
{ "Content-Type": "text/plain" },
"No static directory configured and no dev URL set.",
);
return;
}
const staticRoot = path.resolve(staticDir);
const staticRequestPath = url.pathname === "/" ? "/index.html" : url.pathname;
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
if (
staticRelativePath.length === 0 ||
hasRawLeadingParentSegment ||
hasPathTraversalSegment ||
staticRelativePath.includes("\0")
) {
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
return;
}
const isWithinStaticRoot = (candidate: string) =>
candidate === staticRoot ||
candidate.startsWith(
staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`,
);
let filePath = path.resolve(staticRoot, staticRelativePath);
if (!isWithinStaticRoot(filePath)) {
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
return;
}
const ext = path.extname(filePath);
if (!ext) {
filePath = path.resolve(filePath, "index.html");
if (!isWithinStaticRoot(filePath)) {
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
return;
}
}
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
const indexPath = path.resolve(staticRoot, "index.html");
const indexData = yield* fileSystem
.readFile(indexPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!indexData) {
respond(404, { "Content-Type": "text/plain" }, "Not Found");
return;
}
respond(200, { "Content-Type": "text/html; charset=utf-8" }, indexData);
return;
}
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
const data = yield* fileSystem
.readFile(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!data) {
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
return;
}
respond(200, { "Content-Type": contentType }, data);
}),
).catch(() => {
if (!res.headersSent) {
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
}
});
});
@@ -331,28 +544,68 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
broadcastPush({
type: "push",
channel: WS_CHANNELS.serverConfigUpdated,
data: event,
data: {
issues: event.issues,
providers: providerStatuses,
},
}),
).pipe(Effect.forkIn(subscriptionsScope));
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
let welcomeBootstrapProjectId: ProjectId | undefined;
let welcomeBootstrapThreadId: ThreadId | undefined;
if (autoBootstrapProjectFromCwd) {
yield* Effect.gen(function* () {
const snapshot = yield* projectionReadModelQuery.getSnapshot();
const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd);
if (!existing) {
const existingProject = snapshot.projects.find(
(project) => project.workspaceRoot === cwd && project.deletedAt === null,
);
let bootstrapProjectId: ProjectId;
let bootstrapProjectDefaultModel: string;
if (!existingProject) {
const createdAt = new Date().toISOString();
const projectName = path.basename(cwd) || "project";
bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
const bootstrapProjectTitle = path.basename(cwd) || "project";
bootstrapProjectDefaultModel = "gpt-5-codex";
yield* orchestrationEngine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: ProjectId.makeUnsafe(crypto.randomUUID()),
title: projectName,
projectId: bootstrapProjectId,
title: bootstrapProjectTitle,
workspaceRoot: cwd,
defaultModel: "gpt-5-codex",
defaultModel: bootstrapProjectDefaultModel,
createdAt,
});
} else {
bootstrapProjectId = existingProject.id;
bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
}
const existingThread = snapshot.threads.find(
(thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null,
);
if (!existingThread) {
const createdAt = new Date().toISOString();
const threadId = ThreadId.makeUnsafe(crypto.randomUUID());
yield* orchestrationEngine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
threadId,
projectId: bootstrapProjectId,
title: "New thread",
model: bootstrapProjectDefaultModel,
branch: null,
worktreePath: null,
createdAt,
});
welcomeBootstrapProjectId = bootstrapProjectId;
welcomeBootstrapThreadId = threadId;
} else {
welcomeBootstrapProjectId = bootstrapProjectId;
welcomeBootstrapThreadId = existingThread.id;
}
}).pipe(
Effect.mapError(
@@ -368,7 +621,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case ORCHESTRATION_WS_METHODS.dispatchCommand: {
const { command } = request.body;
return yield* orchestrationEngine.dispatch(command);
const normalizedCommand = yield* normalizeDispatchCommand({ command });
return yield* orchestrationEngine.dispatch(normalizedCommand);
}
case ORCHESTRATION_WS_METHODS.getTurnDiff: {
@@ -446,7 +700,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.gitCheckout: {
const body = stripRequestTag(request.body);
return yield* git.checkoutBranch(body);
return yield* Effect.scoped(git.checkoutBranch(body));
}
case WS_METHODS.gitInit: {
@@ -491,6 +745,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
providers: providerStatuses,
availableEditors,
runtimeEnvironment,
};
case WS_METHODS.serverUpsertKeybinding: {
@@ -581,7 +838,12 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const welcome: WsPush = {
type: "push",
channel: WS_CHANNELS.serverWelcome,
data: { cwd, projectName },
data: {
cwd,
projectName,
...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
},
};
logOutgoingPush(welcome, 1);
ws.send(JSON.stringify(welcome));
+4 -2
View File
@@ -14,10 +14,12 @@
"importFromBarrel": "error",
"anyUnknownInErrorContext": "warning",
"instanceOfSchema": "warning",
"deterministicKeys": "warning"
"deterministicKeys": "warning",
"preferSchemaOverJson": "off",
"globalErrorInEffectFailure": "off"
}
}
]
},
"include": ["src", "tsdown.config.ts", "scripts", "integration"]
"include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"]
}
+4 -1
View File
@@ -3,10 +3,13 @@ import { defineConfig } from "tsdown";
export default defineConfig({
entry: ["src/index.ts"],
format: ["esm", "cjs"],
checks: {
legacyCjs: false,
},
outDir: "dist",
sourcemap: true,
clean: true,
noExternal: ["@t3tools/contracts"],
noExternal: (id) => id.startsWith("@t3tools/"),
inlineOnly: false,
banner: {
js: "#!/usr/bin/env node\n",
+10 -6
View File
@@ -1,19 +1,22 @@
{
"name": "@t3tools/web",
"version": "0.0.0",
"version": "0.0.0-alpha.18",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"prepare": "effect-language-service patch",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@base-ui/react": "^1.2.0",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-query": "^5.90.0",
"@tanstack/react-router": "^1.160.2",
@@ -22,14 +25,14 @@
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"effect": "catalog:",
"highlight.js": "^11.11.1",
"lexical": "^0.41.0",
"lucide-react": "^0.564.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",
"tailwind-merge": "^3.4.0"
"tailwind-merge": "^3.4.0",
"zustand": "^5.0.11"
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -40,7 +43,8 @@
"@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"
"typescript": "catalog:",
"vite": "^8.0.0-beta.12",
"vitest": "catalog:"
}
}
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import { getAppModelOptions, getSlashModelOptions, normalizeCustomModelSlugs } from "./appSettings";
describe("normalizeCustomModelSlugs", () => {
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
expect(
normalizeCustomModelSlugs([
" custom/internal-model ",
"gpt-5.3-codex",
"5.3",
"custom/internal-model",
"",
null,
]),
).toEqual(["custom/internal-model"]);
});
});
describe("getAppModelOptions", () => {
it("appends saved custom models after the built-in options", () => {
const options = getAppModelOptions(["custom/internal-model"]);
expect(options.map((option) => option.slug)).toEqual([
"gpt-5.3-codex",
"gpt-5.3-codex-spark",
"gpt-5.2-codex",
"gpt-5.2",
"custom/internal-model",
]);
});
it("keeps the currently selected custom model available even if it is no longer saved", () => {
const options = getAppModelOptions([], "custom/selected-model");
expect(options.at(-1)).toEqual({
slug: "custom/selected-model",
name: "custom/selected-model",
isCustom: true,
});
});
});
describe("getSlashModelOptions", () => {
it("includes saved custom model slugs for /model command suggestions", () => {
const options = getSlashModelOptions(["custom/internal-model"], "", "gpt-5.3-codex");
expect(options.some((option) => option.slug === "custom/internal-model")).toBe(true);
});
it("filters slash-model suggestions across built-in and custom model names", () => {
const options = getSlashModelOptions(["openai/gpt-oss-120b"], "oss", "gpt-5.3-codex");
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
});
});
+107 -5
View File
@@ -1,7 +1,11 @@
import { useCallback, useSyncExternalStore } from "react";
import { Option, Schema } from "effect";
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
const BUILT_IN_MODEL_SLUGS = new Set<string>(MODEL_OPTIONS.map((option) => option.slug));
const AppSettingsSchema = Schema.Struct({
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
@@ -14,8 +18,16 @@ const AppSettingsSchema = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.pipe(
Schema.withConstructorDefault(() => Option.some(false)),
),
customCodexModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
});
export type AppSettings = typeof AppSettingsSchema.Type;
export interface AppModelOption {
slug: string;
name: string;
isCustom: boolean;
}
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
@@ -23,6 +35,94 @@ let listeners: Array<() => void> = [];
let cachedRawSettings: string | null | undefined;
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
export function normalizeCustomModelSlugs(
models: Iterable<string | null | undefined>,
): AppSettings["customCodexModels"] {
const normalizedModels: string[] = [];
const seen = new Set<string>();
for (const candidate of models) {
const normalized = normalizeModelSlug(candidate);
if (
!normalized ||
normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
BUILT_IN_MODEL_SLUGS.has(normalized) ||
seen.has(normalized)
) {
continue;
}
seen.add(normalized);
normalizedModels.push(normalized);
if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
break;
}
}
return normalizedModels;
}
function normalizeAppSettings(settings: AppSettings): AppSettings {
return {
...settings,
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels),
};
}
export function getAppModelOptions(
customModels: readonly string[],
selectedModel?: string | null,
): AppModelOption[] {
const options: AppModelOption[] = MODEL_OPTIONS.map(({ slug, name }) => ({
slug,
name,
isCustom: false,
}));
const seen = new Set(options.map((option) => option.slug));
for (const slug of normalizeCustomModelSlugs(customModels)) {
if (seen.has(slug)) {
continue;
}
seen.add(slug);
options.push({
slug,
name: slug,
isCustom: true,
});
}
const normalizedSelectedModel = normalizeModelSlug(selectedModel);
if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
options.push({
slug: normalizedSelectedModel,
name: normalizedSelectedModel,
isCustom: true,
});
}
return options;
}
export function getSlashModelOptions(
customModels: readonly string[],
query: string,
selectedModel?: string | null,
): AppModelOption[] {
const normalizedQuery = query.trim().toLowerCase();
const options = getAppModelOptions(customModels, selectedModel);
if (!normalizedQuery) {
return options;
}
return options.filter((option) => {
const searchSlug = option.slug.toLowerCase();
const searchName = option.name.toLowerCase();
return searchSlug.includes(normalizedQuery) || searchName.includes(normalizedQuery);
});
}
function emitChange(): void {
for (const listener of listeners) {
listener();
@@ -35,7 +135,7 @@ function parsePersistedSettings(value: string | null): AppSettings {
}
try {
return Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value);
return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
} catch {
return DEFAULT_APP_SETTINGS;
}
@@ -96,10 +196,12 @@ export function useAppSettings() {
);
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
const next = Schema.decodeSync(AppSettingsSchema)({
...getAppSettingsSnapshot(),
...patch,
});
const next = normalizeAppSettings(
Schema.decodeSync(AppSettingsSchema)({
...getAppSettingsSnapshot(),
...patch,
}),
);
persistSettings(next);
emitChange();
}, []);
@@ -1,59 +1,196 @@
import { ThreadId, type GitBranch } from "@t3tools/contracts";
import type { GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
resolveDraftEnvModeAfterBranchChange,
resolveBranchToolbarValue,
} from "./BranchToolbar.logic";
const branches: GitBranch[] = [
{
name: "main",
current: true,
isDefault: true,
worktreePath: null,
},
{
name: "feature/demo",
current: false,
isDefault: false,
worktreePath: null,
},
];
describe("deriveSyncedLocalBranch", () => {
it("syncs to git current branch in local mode", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const result = deriveSyncedLocalBranch({
activeThreadId: threadId,
activeWorktreePath: null,
envMode: "local",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBe("main");
describe("resolveDraftEnvModeAfterBranchChange", () => {
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
expect(
resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: null,
currentWorktreePath: "/repo/.t3/worktrees/feature-a",
effectiveEnvMode: "worktree",
}),
).toBe("local");
});
it("does not sync when creating a new worktree", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const result = deriveSyncedLocalBranch({
activeThreadId: threadId,
activeWorktreePath: null,
envMode: "worktree",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBeNull();
it("keeps new-worktree mode when selecting a base branch before worktree creation", () => {
expect(
resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: null,
currentWorktreePath: null,
effectiveEnvMode: "worktree",
}),
).toBe("worktree");
});
it("does not sync when thread already targets a worktree path", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const result = deriveSyncedLocalBranch({
activeThreadId: threadId,
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
envMode: "local",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBeNull();
it("uses worktree mode when selecting a branch already attached to a worktree", () => {
expect(
resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: "/repo/.t3/worktrees/feature-a",
currentWorktreePath: null,
effectiveEnvMode: "local",
}),
).toBe("worktree");
});
});
describe("resolveBranchToolbarValue", () => {
it("defaults new-worktree mode to current git branch when no explicit base branch is set", () => {
expect(
resolveBranchToolbarValue({
envMode: "worktree",
activeWorktreePath: null,
activeThreadBranch: null,
currentGitBranch: "main",
}),
).toBe("main");
});
it("keeps an explicitly selected worktree base branch", () => {
expect(
resolveBranchToolbarValue({
envMode: "worktree",
activeWorktreePath: null,
activeThreadBranch: "feature/base",
currentGitBranch: "main",
}),
).toBe("feature/base");
});
it("shows the actual checked-out branch when not selecting a new worktree base", () => {
expect(
resolveBranchToolbarValue({
envMode: "local",
activeWorktreePath: null,
activeThreadBranch: "feature/base",
currentGitBranch: "main",
}),
).toBe("main");
});
});
describe("deriveLocalBranchNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
});
it("supports remote names that contain slashes", () => {
expect(deriveLocalBranchNameFromRemoteRef("my-org/upstream/feature/demo")).toBe(
"upstream/feature/demo",
);
});
it("returns the original name when ref is malformed", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/")).toBe("origin/");
expect(deriveLocalBranchNameFromRemoteRef("/feature/demo")).toBe("/feature/demo");
});
});
describe("dedupeRemoteBranchesWithLocalMatches", () => {
it("hides remote refs when the matching local branch exists", () => {
const input: GitBranch[] = [
{
name: "feature/demo",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "origin/feature/demo",
isRemote: true,
remoteName: "origin",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "origin/feature/remote-only",
isRemote: true,
remoteName: "origin",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"feature/demo",
"origin/feature/remote-only",
]);
});
it("keeps all entries when no local match exists for a remote ref", () => {
const input: GitBranch[] = [
{
name: "feature/local",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "origin/feature/remote-only",
isRemote: true,
remoteName: "origin",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"feature/local",
"origin/feature/remote-only",
]);
});
it("dedupes remote refs for remotes whose names contain slashes", () => {
const input: GitBranch[] = [
{
name: "feature/demo",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "my-org/upstream/feature/demo",
isRemote: true,
remoteName: "my-org/upstream",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"feature/demo",
]);
});
it("dedupes remote refs when git tracks with first-slash local naming", () => {
const input: GitBranch[] = [
{
name: "upstream/feature",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "my-org/upstream/feature",
isRemote: true,
remoteName: "my-org/upstream",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"upstream/feature",
]);
});
});
+83 -21
View File
@@ -1,28 +1,90 @@
import type { GitBranch, ThreadId } from "@t3tools/contracts";
import type { GitBranch } from "@t3tools/contracts";
interface DeriveSyncedLocalBranchInput {
activeThreadId: ThreadId | undefined;
export type EnvMode = "local" | "worktree";
export function resolveEffectiveEnvMode(input: {
activeWorktreePath: string | null;
hasServerThread: boolean;
draftThreadEnvMode: EnvMode | undefined;
}): EnvMode {
const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input;
return activeWorktreePath || (!hasServerThread && draftThreadEnvMode === "worktree")
? "worktree"
: "local";
}
export function resolveDraftEnvModeAfterBranchChange(input: {
nextWorktreePath: string | null;
currentWorktreePath: string | null;
effectiveEnvMode: EnvMode;
}): EnvMode {
const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
if (nextWorktreePath) {
return "worktree";
}
if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
return "worktree";
}
return "local";
}
export function resolveBranchToolbarValue(input: {
envMode: EnvMode;
activeWorktreePath: string | null;
envMode: "local" | "worktree";
activeThreadBranch: string | null;
queryBranches: ReadonlyArray<GitBranch> | undefined;
currentGitBranch: string | null;
}): string | null {
const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
if (envMode === "worktree" && !activeWorktreePath) {
return activeThreadBranch ?? currentGitBranch;
}
return currentGitBranch ?? activeThreadBranch;
}
export function deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
activeThreadBranch,
queryBranches,
}: DeriveSyncedLocalBranchInput): string | null {
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
return null;
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
const firstSeparatorIndex = branchName.indexOf("/");
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
return branchName;
}
const currentBranch = queryBranches?.find((branch) => branch.current);
if (!currentBranch || currentBranch.name === activeThreadBranch) {
return null;
}
return currentBranch.name;
return branchName.slice(firstSeparatorIndex + 1);
}
function deriveLocalBranchNameCandidatesFromRemoteRef(
branchName: string,
remoteName?: string,
): ReadonlyArray<string> {
const candidates = new Set<string>();
const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
if (firstSlashCandidate.length > 0) {
candidates.add(firstSlashCandidate);
}
if (remoteName) {
const remotePrefix = `${remoteName}/`;
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
candidates.add(branchName.slice(remotePrefix.length));
}
}
return [...candidates];
}
export function dedupeRemoteBranchesWithLocalMatches(
branches: ReadonlyArray<GitBranch>,
): ReadonlyArray<GitBranch> {
const localBranchNames = new Set(
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
);
return branches.filter((branch) => {
if (!branch.isRemote) {
return true;
}
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
branch.name,
branch.remoteName,
);
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
});
}
+87 -263
View File
@@ -1,212 +1,105 @@
import type { GitBranch, ThreadId } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import type { ThreadId } from "@t3tools/contracts";
import { useCallback } from "react";
import { newCommandId } from "../lib/utils";
import {
gitBranchesQueryOptions,
gitCheckoutMutationOptions,
gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
Combobox,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxTrigger,
} from "./ui/combobox";
import { ChevronDownIcon } from "lucide-react";
EnvMode,
resolveDraftEnvModeAfterBranchChange,
resolveEffectiveEnvMode,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { Button } from "./ui/button";
interface BranchToolbarProps {
threadId: ThreadId;
envMode: "local" | "worktree";
onEnvModeChange: (mode: "local" | "worktree") => void;
onEnvModeChange: (mode: EnvMode) => void;
envLocked: boolean;
onComposerFocusRequest?: () => void;
}
export default function BranchToolbar({
threadId,
envMode,
onEnvModeChange,
envLocked,
onComposerFocusRequest,
}: BranchToolbarProps) {
const { state, dispatch } = useStore();
const queryClient = useQueryClient();
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const activeThread = state.threads.find((thread) => thread.id === threadId);
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 serverThread = threads.find((thread) => thread.id === threadId);
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
const activeProject = projects.find((project) => project.id === activeProjectId);
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
const hasServerThread = serverThread !== undefined;
const effectiveEnvMode = resolveEffectiveEnvMode({
activeWorktreePath,
hasServerThread,
draftThreadEnvMode: draftThread?.envMode,
});
// ── Queries ───────────────────────────────────────────────────────────
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branches = branchesQuery.data?.branches ?? [];
const branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0;
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
const createBranchItemValue = canCreateBranch
? `__create_new_branch__:${trimmedBranchQuery}`
: null;
const branchPickerItems =
createBranchItemValue && !hasExactBranchMatch
? [...branchNames, createBranchItemValue]
: branchNames;
// ── Mutations ─────────────────────────────────────────────────────────
const checkoutMutation = useMutation(gitCheckoutMutationOptions({ cwd: branchCwd, queryClient }));
const createBranchMutation = useMutation(
gitCreateBranchAndCheckoutMutationOptions({ cwd: branchCwd, queryClient }),
);
// ── Effects ───────────────────────────────────────────────────────────
// Keep thread branch synced to git current branch for local threads.
const queryBranches = branchesQuery.data?.branches;
useEffect(() => {
const syncedBranch = deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
activeThreadBranch,
queryBranches,
});
if (!activeThreadId || !syncedBranch) return;
const api = readNativeApi();
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
}
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
useEffect(() => {
if (isBranchMenuOpen) return;
setBranchQuery("");
}, [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;
const api = readNativeApi();
// 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 && api) {
void api.orchestration
.dispatchCommand({
type: "thread.session.stop",
const setThreadBranch = useCallback(
(branch: string | null, worktreePath: string | null) => {
if (!activeThreadId) return;
const api = readNativeApi();
// 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 = serverThread?.session?.sessionId;
if (sessionId && worktreePath !== activeWorktreePath && api) {
void api.orchestration
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId: activeThreadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
}
if (api && hasServerThread) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
}
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
branch,
worktreePath,
});
}
if (hasServerThread) {
setThreadBranchAction(activeThreadId, branch, worktreePath);
return;
}
const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: worktreePath,
currentWorktreePath: activeWorktreePath,
effectiveEnvMode,
});
setDraftThreadContext(threadId, {
branch,
worktreePath,
envMode: nextDraftEnvMode,
});
}
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
};
},
[
activeThreadId,
serverThread?.session?.sessionId,
activeWorktreePath,
hasServerThread,
setThreadBranchAction,
setDraftThreadContext,
threadId,
effectiveEnvMode,
],
);
const selectBranch = (branch: GitBranch) => {
const api = readNativeApi();
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);
onComposerFocusRequest?.();
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);
onComposerFocusRequest?.();
return;
}
checkoutMutation.mutate(branch.name, {
onSuccess: () => {
setThreadError(null);
setThreadBranch(branch.name, activeWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
onError: (error) => {
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
setIsBranchMenuOpen(true);
},
});
};
const createBranch = (rawName: string) => {
const name = rawName.trim();
const api = readNativeApi();
if (!api || !activeThreadId || !branchCwd || !name || createBranchMutation.isPending) return;
createBranchMutation.mutate(name, {
onSuccess: () => {
setThreadError(null);
setThreadBranch(name, activeWorktreePath);
setBranchQuery("");
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
onError: (error) => {
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
},
});
};
if (!activeThread || !activeProject) return null;
if (!activeThreadId || !activeProject) return null;
return (
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
@@ -221,92 +114,23 @@ export default function BranchToolbar({
variant="ghost"
className="text-muted-foreground/70 hover:text-foreground/80"
size="xs"
onClick={() => onEnvModeChange(envMode === "local" ? "worktree" : "local")}
onClick={() => onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")}
>
{envMode === "worktree" ? "New worktree" : "Local"}
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
</Button>
)}
</div>
<Combobox
items={branchPickerItems}
autoHighlight
onOpenChange={(open) => setIsBranchMenuOpen(open)}
open={isBranchMenuOpen}
value={activeThread.branch}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={branchesQuery.isLoading}
>
<span className="max-w-[240px] truncate">
{activeThread.branch
? envMode === "worktree" && !activeWorktreePath
? `From ${activeThread.branch}`
: activeThread.branch
: "Select branch"}
</span>
<ChevronDownIcon />
</ComboboxTrigger>
<ComboboxPopup align="end" side="top" className="w-64">
<div className="border-b p-1">
<ComboboxInput
className="[&_input]:font-sans rounded-md"
inputClassName="ring-0"
placeholder="Search branches..."
showTrigger={false}
size="sm"
value={branchQuery}
onChange={(event) => setBranchQuery(event.target.value)}
/>
</div>
<ComboboxEmpty>No branches found.</ComboboxEmpty>
<ComboboxList className="max-h-56">
{(itemValue) => {
if (createBranchItemValue && itemValue === createBranchItemValue) {
return (
<ComboboxItem
hideIndicator
key={itemValue}
value={itemValue}
onClick={() => createBranch(trimmedBranchQuery)}
>
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
</ComboboxItem>
);
}
const branch = branchByName.get(itemValue);
if (!branch) return null;
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
return (
<ComboboxItem
hideIndicator
key={itemValue}
value={itemValue}
className={
itemValue === activeThread.branch ? "bg-accent text-foreground" : undefined
}
onClick={() => selectBranch(branch)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
</span>
)}
</div>
</ComboboxItem>
);
}}
</ComboboxList>
</ComboboxPopup>
</Combobox>
<BranchToolbarBranchSelector
activeProjectCwd={activeProject.cwd}
activeThreadBranch={activeThreadBranch}
activeWorktreePath={activeWorktreePath}
branchCwd={branchCwd}
effectiveEnvMode={effectiveEnvMode}
envLocked={envLocked}
onSetThreadBranch={setThreadBranch}
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
/>
</div>
);
}
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more