Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex e6d856b93e Add subagent work units across providers
Co-authored-by: codex <[email protected]>
2026-03-18 15:54:55 -07:00
Julius Marminge ef843d400e maybe fix codex subturns 2026-03-18 15:47:34 -07:00
Julius Marminge 654ca0da91 Backfill missing app settings defaults during decode
- add decoding defaults in `AppSettingsSchema` so older persisted settings load safely
- export shared `Schema.Literals` types for `EnvMode` and `TimestampFormat`
- add a regression test covering pre-new-key settings hydration
2026-03-18 14:17:23 -07:00
Julius Marminge aa66e08034 update adapter 2026-03-18 13:26:12 -07:00
Julius Marmingeandcodex 268d4f7cf8 Merge main and use source proposed plans in the sidebar
Co-authored-by: codex <[email protected]>
2026-03-18 13:25:17 -07:00
Utkarsh Patil 0de5742b04 fix: consume plans on implementation (#1133) 2026-03-18 13:09:57 -07:00
Julius Marminge 321251907a refactor storage 2026-03-18 11:00:07 -07:00
Julius Marminge d5c86c9af6 Merge branch 'main' into split-stack/claude-sibling 2026-03-18 10:18:13 -07:00
Utkarsh Patil b500a36a94 fix: implement button overflow (#1193) 2026-03-18 09:46:09 -07:00
Julius Marminge a75a9b427f Split Codex and Claude traits handling by model capabilities
- Add dedicated Claude traits picker with model-aware effort, thinking, and fast mode controls
- Treat Claude Ultrathink as a prompt keyword instead of session effort
- Normalize provider model options in composer flow and adapter, with tests for unsupported effort/thinking cases
2026-03-17 16:56:59 -07:00
MaskandJulius Marminge 1310045629 Give Agents access to Terminal output (#1032)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-17 15:56:51 -07:00
Seif Almotaz BellahandJulius Marminge 579a69eb77 feat: add configurable model for git text generation (#1171)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-17 15:33:36 -07:00
Guilherme Vieira 9ee8c4f543 fix(web): fix sidebar project drag clipping with variable-height items (#1176) 2026-03-17 15:31:25 -07:00
Julius Marminge 55560f5116 Use GitHub App token when checking out main in release workflow (#1175) 2026-03-17 14:55:27 -07:00
Julius Marminge f98679d217 Add Claude fast mode support across adapter and composer controls
- support `claudeAgent.fastMode` in shared/contracts, provider dispatch, and Claude adapter SDK settings
- gate fast mode to supported Claude models and restart/forward options in orchestration
- unify draft/UI fast mode state (not Codex-only) and add browser/server tests plus SDK probe
2026-03-17 14:36:35 -07:00
Julius Marminge 5c9cfcd4c3 Remove Ultrathink pill from composer header
- keep Ultrathink frame styling without extra wrapper padding toggles
- drop the inline Ultrathink badge row in ChatView
- clean up stray whitespace in ProviderService test
2026-03-17 14:11:26 -07:00
JustYanniccandClaude Opus 4.6 e6254a8451 feat: claude effort controls, ultrathink UI, and adapter robustness (#1146)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-03-17 13:23:07 -07:00
Utkarsh Patil 3710ddb611 fix: fix menu copy (#1063) 2026-03-17 10:57:31 -07:00
0x1f99d 3fce14bbcf fix(web): restore pointer cursors for sidebar actions (#894) 2026-03-17 08:46:06 -07:00
James d430a0624b Add copy workspace path button to thread action menu (#1128) 2026-03-16 22:34:24 -07:00
Julius Marminge b04132d8c8 Use provider default model in orchestration integration seed
- derive `defaultModel` from `DEFAULT_MODEL_BY_PROVIDER` using harness provider
- replace hardcoded `gpt-5-codex` in seeded project and thread setup
2026-03-16 17:36:56 -07:00
Julius Marminge b577cb5326 Fix locked-thread model selection and provider fallback
- Use thread provider as the preferred provider during command handling
- Update `ProviderModelPicker` to show direct model choices when provider is locked
- Add browser tests for locked/unlocked picker behavior and widen browser test glob
2026-03-16 17:26:50 -07:00
Julius Marminge fc9660f238 Enforce provider-model consistency for thread turn starts
- Reject turn starts that request a provider switch from the thread-bound provider
- Reject models that do not belong to the thread provider and log start failures
- Add shared `inferProviderForModel` helper and tests; reuse it in web store inference
2026-03-16 17:09:38 -07:00
Julius Marminge b403ca3183 dont provide generated orchestration ids to native providerRefs 2026-03-16 16:09:50 -07:00
Julius Marminge f34dd0a91f Schema.is 2026-03-16 15:48:28 -07:00
Julius Marminge 33791cdfe5 align branding guide lines 2026-03-16 15:41:12 -07:00
Julius Marminge fdcb05d3f6 replace ad-hoc union for contract type 2026-03-16 12:16:24 -07:00
Julius Marmingeandcodex 2121682546 Improve Claude adapter tool streaming and health checks
- Map Claude reasoning deltas, streamed tool input JSON, and tool results into runtime item/content events
- Classify Agent/read-only Claude tools for correct approval request types
- Add Claude CLI provider health checks and auth-status parsing coverage

Co-authored-by: codex <[email protected]>
2026-03-16 12:14:27 -07:00
Julius Marminge d2b00e6550 Show Claude Code in provider picker and add Cursor placeholder
- Include Claude Code in available provider options in the picker
- Add Cursor as a disabled placeholder provider with icon mapping
- Update session-logic tests to assert provider availability and ordering
2026-03-16 11:11:57 -07:00
Julius Marminge e0facb03bd fix circular import 2026-03-16 11:06:26 -07:00
Julius Marminge 73152abe81 fmt 2026-03-16 11:03:31 -07:00
Julius Marminge c5bfff1583 unify start option union 2026-03-16 10:41:05 -07:00
Julius Marminge 040011dbc7 Remove Cursor provider support across server and web
- drop `cursor` from provider/model contracts and runtime validation
- remove Cursor-specific UI options, settings, and model normalization paths
- update server/web tests and fixtures to cover Codex + Claude Code only
2026-03-16 10:35:53 -07:00
Julius Marminge 858116d836 fmt 2026-03-16 10:28:36 -07:00
Julius Marminge ff34d2c708 lock 2026-03-16 10:28:24 -07:00
Julius Marmingeandcodex 99cd1c560e Fix post-rebase provider integration
Co-authored-by: codex <[email protected]>
2026-03-16 10:24:55 -07:00
Julius Marmingeandcodex 01f01c5e6b build: sync Claude SDK lockfile on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:18:03 -07:00
Julius Marmingeandcodex de7cfba261 split: restore Claude SDK manifest and plan doc
Co-authored-by: codex <[email protected]>
2026-03-16 10:17:45 -07:00
Julius Marmingeandcodex 1da30f776e split: restore Claude provider surface on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:17:45 -07:00
Julius Marmingeandcodex 11aca1fcc6 model: restore Claude catalogs on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:12:33 -07:00
Julius Marmingeandcodex 95c50053bc contracts: restore Claude schemas on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:09:06 -07:00
Julius Marmingeandcodex da9cbcc98c test: restore Claude coverage on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:08:09 -07:00
Julius Marmingeandcodex b9ea1487b3 Restore Claude adapter on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:07:39 -07:00
Daniel StickerandJulius Marminge 765c1dc9e4 fix(desktop): backfill SSH_AUTH_SOCK from login shell on macOS (#972)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-16 09:05:37 -07:00
Utkarsh Patil e6d9a271fc fix(github): fix bug report issue template for screenshots (#1109) 2026-03-15 22:31:36 -07:00
Ivor 4b811dae61 Fixed Typos in Agents.md (#1120) 2026-03-15 16:34:09 +00:00
Etan HeymanandJulius Marminge 6d76865e74 fix: tighten node engine range for node:sqlite compat (#206) (#1096)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-14 19:22:56 -07:00
Sai Shankar 2bb71f41c3 feat(web): add scroll to bottom pill in chat view (#619) 2026-03-14 10:44:55 -07:00
Stefan Wintergerst cc2ab00074 chore: add .idea/ to .gitignore (#1077) 2026-03-14 16:03:35 +00:00
XanacasandClaude Opus 4.6 8b8e8b38e5 fix(web): unify focus ring styles across sidebar and app (#1079)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-03-14 15:51:37 +00:00
Vitor Buzinaro 46ea594f02 Actions dialog: autofocus script-name field (#912) 2026-03-14 01:05:12 +00:00
0x1f99d 790fda1a97 feat(github): add issue templates for automatic triage (#896) 2026-03-13 11:29:22 -07:00
Julius Marminge 89ffcf42eb Upgrade oxfmt and oxlint tooling versions (#1010) 2026-03-12 23:24:42 -07:00
876bbd715a Extract reusable clipboard hook and standardize media queries (#1006)
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-03-12 21:03:21 -07:00
0x1f99dandJulius Marminge ac0d1f52a0 fix(web): defer diff worker startup until diff opens (#934)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 20:47:29 -07:00
0x1f99dandJulius Marminge d0ae0adc99 fix(web): add default thread env mode setting (#892)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 20:18:20 -07:00
Jono Kemball 995a26660e chore: Upgrade marketing app to Astro 6 (#1005) 2026-03-12 20:18:03 -07:00
dpav02andClaude Opus 4.6 dfd62cfb86 fix(desktop): show dialog after "Check for Updates" menu action (#955)
Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-03-12 19:43:07 -07:00
ZortosandJulius Marminge 64dc07a8e5 Add compact Codex tool-call icons and details to the chat timeline (#988)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 19:42:59 -07:00
Jono Kemball ae4ae9973c chore: update @vitejs/plugin-react to 6.0.0 (#1002) 2026-03-12 19:30:47 -07:00
ZortosandJulius Marminge 36473f7de6 feat: replace worktree toggle with discoverable Select dropdown (#1001)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 19:26:14 -07:00
(CJ) Chukwudi Nwobodo a14debc83e fix: block image uploads during plan mode questions (#621) 2026-03-12 17:24:53 -07:00
(CJ) Chukwudi Nwobodo 71a7473a81 fix: composer @file autocomplete cursor and spacing bugs (#936) 2026-03-12 16:33:37 -07:00
WilgotMandJulius Marminge 5c03fb62c4 Add Antigravity to supported editors in Open menu (macOS, Windows, and Linux) (#841)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 23:28:32 +00:00
Hugo Blom 727c0cfcbf feat: Allow Overriding Timestamp Format in Settings (#855) 2026-03-12 15:58:51 -07:00
Noah GregoryandJulius Marminge dcd2e5c34f fix: don't restart the app on normal exists in dev runner (#986)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 13:03:55 -07:00
KiyotakaandJulius Marminge 1e276573c2 feat: add fuzzy workspace entry search (#256)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 13:00:08 -07:00
Julius Marminge db17ff3323 fix syntax errors from bad merge 2026-03-12 12:40:08 -07:00
Qiaochu Hu b496ae8395 fix: add error logging for code highlighting failures (#951) 2026-03-12 12:35:21 -07:00
Qiaochu Huandhobostay 724f54c2c1 fix: clean up timeout in PlanSidebar to prevent memory leaks (#949)
Co-authored-by: hobostay <[email protected]>
2026-03-12 12:32:00 -07:00
Qiaochu Huandhobostay b6eba3347d fix: add logging for WebSocket errors (#948)
Co-authored-by: hobostay <[email protected]>
2026-03-12 12:31:19 -07:00
Adam NajiandJulius Marminge 74c22628b3 chore: update actions/checkout and actions/github-script (#956)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 12:29:07 -07:00
0x1f99dandJulius Marminge 224acebb57 fix(web): add pointer cursor to running stop-generation button (#900)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 12:15:01 -07:00
Alex Schwartz 85c174a6ca fix: Linux icon now shows up (#807) 2026-03-12 12:09:41 -07:00
Julius Marminge 581d242925 remove triggers 2026-03-12 12:01:55 -07:00
Julius Marminge d9d0216e98 fix pr size workflow 2026-03-12 12:01:27 -07:00
Julius Marminge c52ad29b31 Fix mod+N new thread flow and terminal split limits
- ensure `chat.new` creates a fresh draft after a promoted draft thread
- enforce terminal cap per split group (4) while allowing additional terminal groups
- refine sidebar row selected/active styling via shared class-name logic and tests
2026-03-12 11:50:35 -07:00
Julius Marminge fcbf3f3c22 Fix new-thread shortcuts when terminal is focused
- move chat-wide key handling into `_chat` route-level shortcut handler
- extract reusable `useHandleNewThread` hook and `isTerminalFocused` helper
- update browser WS fixture to support `terminalOpen` RPC shape
2026-03-12 11:50:35 -07:00
Donald Silveira ab0002f99d update project removal copy (#981) 2026-03-12 11:48:23 -07:00
Noah GregoryandJulius Marminge f63cda22fa fix: improve business logic in prompt editor and fix cursor bugs in Plan mode (#867)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 11:24:10 -07:00
Noah Gregory b60a34eba4 fix: fix logo aligment regression on macOS (#960) 2026-03-12 11:13:37 -07:00
Jono Kemball ed4be2c849 fix: Fix response duration for agent to no longer always be 1ms (#866) 2026-03-12 11:12:18 -07:00
Noah Gregory 5e23e9c7c7 add Ymit24 to vouched list (#959) 2026-03-12 11:10:58 -07:00
Guilherme VieiraandJulius Marminge c3bfcc36b8 feat: add selective file staging to commit dialog (#872)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 10:50:49 -07:00
eggfriedrice a33cc8c758 fix: diff panel unclosable after retainSearchParams middleware (#937) 2026-03-12 10:44:16 -07:00
Magnus BuvarpandJulius Marminge a01d712751 fix(web): resolve preferred editor from available editors & introduce useLocalStorage helper (#662)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 10:42:17 -07:00
0x1f99d 774cff9a74 ci(github): add pull request size labels (#901) 2026-03-12 09:10:07 -07:00
Ymit24andChristian Smith e3d46b687c feat: split out components from ChatView.tsx (#860)
Co-authored-by: Christian Smith <[email protected]>
2026-03-11 19:21:22 -07:00
Theo Browne 8636ea0ec4 Add maria-rcks to the list of contributors 2026-03-11 17:16:51 -07:00
David Balderston ff6a66dcab Use live thread activities for sidebar status pills (#919) 2026-03-11 14:05:17 -07:00
maria 2ac735657e chore(release): align package versions before building artifacts (#933) 2026-03-11 14:03:49 -07:00
github-actions[bot] bbab1fc891 chore(release): prepare v0.0.10 2026-03-11 17:27:36 +00:00
Julius Marminge 82a50da8b1 revert formatting on mockServiceWorker.js 2026-03-10 18:49:04 -07:00
eggfriedrice 7ddcb239c5 feat: persist diff panel state across thread navigation (#875) 2026-03-10 18:42:39 -07:00
0x1f99d 9e4e221970 chore: added eggfriedrice24 to vouched list (#869) 2026-03-10 17:55:36 -07:00
eggfriedrice e8b0126371 fix: checkpoint diffs never resolve (shared PubSub subscription) (#595) 2026-03-10 16:54:47 -07:00
ranvier2d2andClaude Opus 4.6 90d9a2ad1f fix: map gitignore to ini for Shiki syntax highlighting (#848)
Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-03-10 16:50:18 -07:00
Julius Marminge 065ef922bd Require bun fmt for completion and clarify Electron history
- Update AGENTS.md task completion requirements to include `bun fmt`
- Add an inline note explaining why Electron uses hash history
2026-03-10 16:21:28 -07:00
7d11533490 Stabilize runtime orchestration and fix flaky CI tests (#488)
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-03-10 15:54:34 -07:00
Julius Marminge 1031a226f8 Fix cross-repo PR detection and push remote selection (#788) 2026-03-10 15:05:41 -07:00
0x1f99d ddd98876b5 fix: invalidate workspace entry cache after turn completion and revert (#796) 2026-03-10 14:42:39 -07:00
Adam Naji dfd41da2fd Fix Windows keybindings for font size: use Ctrl+ to increase (#786) 2026-03-10 14:41:02 -07:00
Utkarsh Patil b37279ca21 fix: prevent Codex overrides footer overflow with long binary paths (#707) 2026-03-10 11:46:49 -07:00
Julius Marminge 13eeb07f5f prevent squashing some know errors 2026-03-10 10:38:11 -07:00
Jono Kemball 1e9bac7f6e Sync desktop native theme with web theme setting (#800) 2026-03-10 10:23:52 -07:00
0x1f99dandJulius Marminge 1c290767f2 fix: use commit as the default git action without origin (#642)
* fix(web): avoid push and PR defaults without origin

* fmt

* object here too

---------

Co-authored-by: Julius Marminge <[email protected]>
2026-03-10 10:16:37 -07:00
0x1f99dandJulius Marminge 9becb3f40a fix(server): skip auth check when Codex CLI uses a custom model provider (#649)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-10 10:14:58 -07:00
0x1f99d 2c351726ae fix(contracts): align terminal restart input type across IPC, WS, and server (#597) 2026-03-10 09:46:24 -07:00
Weld 9e891d2e97 Display application version in sidebar and settings (#720) 2026-03-10 09:45:39 -07:00
Jono Kemball b8d07eb852 Add downloads page and shared marketing layout (#802) 2026-03-10 09:18:22 -07:00
Jason LasterandJulius Marminge 223c3dc800 chore(ci): add and apply fmt:check script (#779)
* Add  formatting conventions

* Add a fmt lint check

* rely on defaults

---------

Co-authored-by: Julius Marminge <[email protected]>
2026-03-10 00:17:18 -07:00
0x1f99dandJulius Marminge afb6e89bfd feat(web): add shift-click multi-select for sidebar threads (#651)
* feat(web): add shift-click multi-select for sidebar threads

Add support for selecting multiple threads in the sidebar via
Cmd/Ctrl+Click (toggle) and Shift+Click (range select), with
bulk context menu actions for Delete and Mark Unread.

- New threadSelectionStore (Zustand) for ephemeral selection state
  with anchor-based range selection and no-op guards
- Platform-aware modifier detection (Cmd on Mac, Ctrl elsewhere)
  matching existing isMacPlatform pattern in terminal-links
- Extracted deleteThread helper from handleThreadContextMenu for
  reuse by bulk delete, with deletedThreadIds set for correct
  fallback navigation during batch operations
- Selected threads share the active thread highlight style
- Escape key clears selection; plain click clears and navigates
- Right-click on selected thread shows bulk menu; right-click on
  unselected thread clears selection and shows single-thread menu
- 22 unit tests covering toggle, range select, clear, remove,
  and edge cases (cross-project fallback, anchor stability)

* fix(web): filter deleted threads from worktree orphan check during bulk delete

When bulk-deleting threads that share a worktree, the stale threads
closure caused getOrphanedWorktreePathForThread to see the other
threads-being-deleted as still alive, suppressing the orphaned
worktree cleanup prompt. Filter out deletedThreadIds (keeping the
current thread) so the check correctly identifies worktrees that
will have no surviving references.

* fix(web): fix shift-click range selection, distinct selection styling, and deselect on click away

* Preserve thread multi-select on safe sidebar control clicks

- avoid clearing selection on mousedown for thread items and marked safe controls
- centralize the selection-safe selector and add logic tests for clear vs preserve behavior
- simplify thread selection store typing by merging state/actions interface

---------

Co-authored-by: Julius Marminge <[email protected]>
2026-03-10 00:03:37 -07:00
Julius Marminge 9309edf4f4 rm test 2026-03-09 22:50:45 -07:00
Julius Marminge d28ced8fd7 Move PR checkout flow to dialog and drop /checkout-pr command
- Replace the inline composer PR menu with a dedicated `PullRequestThreadDialog`
- Remove `/checkout-pr` from composer slash-command parsing and tests
- Fix branch selector virtualization sizing for the checkout-PR row
2026-03-09 22:50:45 -07:00
Julius Marminge 076608021c Namespace PR worktree branch names under t3code
- Change local PR worktree branch format from `pr/<number>-<head>` to `t3code/pr-<number>/<head>`
- Update GitManager tests to assert the new branch naming convention
2026-03-09 22:50:45 -07:00
Julius Marminge fb4f9aa58e Use repo initial branch in GitCore PR fetch integration test
- Return `initialBranch` from test repo setup helper
- Replace hardcoded `main` checkout/push/assertions with detected branch name
2026-03-09 22:50:45 -07:00
Julius Marminge de21f4dcd7 Use GitHubCliLive as default test layer
- Wire `it.layer` to `GitHubCliLive` in `GitHubCli.test.ts`
- Remove redundant `Effect.provide(GitHubCliLive)` calls in individual tests
2026-03-09 22:50:45 -07:00
Julius Marminge 442bc9540e Normalize remote URL matching and migrate GitHubCli tests
- Treat remotes that only differ by trailing slash after `.git` as the same remote
- Add a GitCore regression test for trailing-slash remote reuse
- Refactor `GitHubCli` tests to `@effect/vitest` layer-based effect tests with reset cleanup
2026-03-09 22:50:45 -07:00
Julius Marminge f7570712a7 Avoid fork PR head branch collisions when creating worktrees
- create a unique local branch name for cross-repo PR worktrees (`pr/<number>-<head>`)
- fetch/set upstream against that local branch instead of overwriting local `main`
- add regression tests for fork PRs where head branch is `main`
2026-03-09 22:50:45 -07:00
Julius Marminge 2847655a1a Validate GitHub CLI JSON with Effect Schema decoders
- Replace manual JSON parsing with shared schema-based decoding helpers
- Normalize PR and repository payloads after decoding for safer typed outputs
- Improve invalid JSON error mapping with operation-specific GitHubCliError details
2026-03-09 22:50:45 -07:00
Julius Marminge 268016d872 Fix PR thread upstream tracking for fork branches
- Restore/set upstream tracking when preparing local and reused PR worktrees
- Derive fork `owner/repo` from PR URL when GitHub omits `headRepositoryNameWithOwner`
- Expand GitManager tests to cover local mode, URL-derived fork identity, and reused worktree upstream recovery
2026-03-09 22:50:45 -07:00
Julius Marminge ac3f22c274 Inline branch picker filtering and drop PR-only shortcut
- move branch filtering logic into `BranchToolbarBranchSelector`
- remove unused `filterBranchPickerItems` helper and related tests
- keep create-branch option pinned while filtering by query
2026-03-09 22:50:45 -07:00
Julius Marminge b36888e9cc Preserve fork PR upstreams when preparing local and worktree threads
- add GitCore helpers to ensure remotes, fetch remote branches, and set upstreams
- extend GitHub CLI parsing to include cross-repo PR metadata and repo clone URLs
- update GitManager flow and tests to materialize fork heads and keep tracking on fork remotes
2026-03-09 22:50:45 -07:00
Julius Marminge 9bb9023009 Handle branch selection across main and secondary worktrees
- add `resolveBranchSelectionTarget` to unify checkout cwd/worktree decisions
- reuse existing worktrees when available, including switching back to main repo
- update branch selector to use shared logic and add targeted unit tests
2026-03-09 22:50:45 -07:00
Julius Marminge f70cb5de45 Refine branch picker behavior and gate /checkout-pr by thread type
- Add shared branch picker filtering logic and tests, including PR-reference-only results
- Improve branch selector UX/perf with deferred query filtering, conditional virtualization, and status-based current branch resolution
- Only expose and handle `/checkout-pr` for local draft threads in chat and toolbar UI
2026-03-09 22:50:45 -07:00
Julius Marminge 3d3586800e Add pull-request thread setup for local and worktree modes
- Add git APIs to resolve PR refs and prepare PR thread workspaces
- Support fetching PR head refs into local branches and reusing existing worktrees
- Wire new websocket/contracts/web composer flows for PR-based thread creation
- Expand server/web/contracts tests for PR routing and branch/worktree behavior
2026-03-09 22:50:45 -07:00
Julius Marminge 767de271e9 Use Effect UUID generator as randomUUID fallback
- Replace manual UUID byte formatting fallback in `apps/web/src/lib/utils.ts`
- Use `Effect.runSync(Random.nextUUIDv4)` when `crypto.randomUUID` is unavailable
2026-03-09 22:50:23 -07:00
Hiram Chirino 9d2c2cae37 fix(web): polyfill crypto.randomUUID for non-secure HTTP contexts
Replace direct crypto.randomUUID() calls with a randomUUID() helper in
utils.ts that falls back to crypto.getRandomValues() when the browser
is not in a secure context (e.g. plain HTTP on a non-localhost address).

Signed-off-by: Hiram Chirino <[email protected]>
2026-03-09 22:50:23 -07:00
David Balderston dcccca3f7b Fix UI Overflow when Github Action is 'Commit, Create & Push PR'
Fixes: #769

* Updated wording for label from 'Commit, Create & Push PR' to 'Commit, Create & PR' to allow for it to fit within the current UI size constraints.

wording change
2026-03-09 22:27:55 -07:00
Julius Marminge 4ed89e4ba7 Treat retryable Codex errors as runtime warnings
- Map Codex `error` notifications with `willRetry: true` to `runtime.warning`
- Keep active turns/sessions running during reconnect warnings
- Add adapter and ingestion tests for retry-warning behavior
2026-03-09 17:21:03 -07:00
Satyam Bansal 99dbe4ff02 fix(web): disable add project button for empty path 2026-03-09 16:00:38 -07:00
Julius Marminge 2fc0b01c18 fmt 2026-03-09 15:20:07 -07:00
Julius Marminge 3a86b60680 Render collapsed plan preview directly as markdown
- remove deferred collapsed preview state in `ProposedPlanCard`
- always render collapsed preview with `ChatMarkdown` for simpler, consistent display
2026-03-09 15:20:07 -07:00
Julius Marminge eb7c428a2d Defer proposed plan rendering until expand in ChatView
- Keep long plan cards collapsed with lightweight preview text by default
- Render full plan markdown only after explicit expand to reduce thread open slowness
- Add tests for preview/strip helpers and browser coverage for expand behavior
2026-03-09 15:20:07 -07:00
Cursor AgentandJulius Marminge 9fb9467ed1 fix: keep suppressProjectClickAfterDragRef true on drag cancel to prevent unintended toggle
Co-authored-by: Julius Marminge <[email protected]>

Applied via @cursor push command
2026-03-09 15:08:10 -07:00
Julius Marminge e42036485f Improve project drag collision detection in sidebar
- Prefer pointer-based hit testing during project reordering
- Fall back to corner-based collision to make drop targeting more reliable
2026-03-09 15:08:10 -07:00
Julius Marminge f9c3aff294 no longer need experimental for tsconfig aliases 2026-03-09 15:08:10 -07:00
Julius Marminge 3503dbc7d5 pin vite 2026-03-09 15:08:10 -07:00
Julius Marminge b5dde6b9d8 Prevent stale click suppression after project drag cancel
- Reset post-drag click suppression when drag is canceled
- Consume only the synthetic click after drag release, then clear suppression
2026-03-09 15:08:10 -07:00
Julius Marminge a6b22ec1c9 Fix project drag clicks and sidebar collapse/scroll behavior
- prevent accidental project toggles after drag operations
- switch project rows to Collapsible for stable expand/collapse animation
- add optional hidden scrollbar mode to ScrollArea and apply it in SidebarContent
2026-03-09 15:08:10 -07:00
Julius Marminge bb49ebf6e5 Add drag-and-drop project reordering in the sidebar
- wire project list to dnd-kit sortable with vertical drag constraints
- prevent accidental expand/collapse clicks during drag gestures
- update store logic/tests and add dnd-kit dependencies
2026-03-09 15:08:10 -07:00
Levi 2f5e626029 Fix project name badge truncation in chat header
Remove the hard max-w-28 (112px) cap and shrink-0 on the project name
badge so it uses available flex space instead of aggressively truncating.
2026-03-09 14:27:29 -07:00
Julius Marminge 82c0a45ea0 Use Debouncer for composer draft persistence writes
- Replace manual timeout/pending-value debounce logic with `@tanstack/react-pacer` `Debouncer`
- Keep `removeItem`/`flush` behavior while simplifying and standardizing persistence timing
2026-03-09 14:02:29 -07:00
Julius Marminge e765051f14 Use React Pacer throttler for domain event snapshot sync
- Replace manual timeout-based domain event batching with `Throttler`
- Keep provider query invalidation batched with trailing 100ms flushes
- Cancel throttler and reset invalidation flag during EventRouter cleanup
2026-03-09 14:02:29 -07:00
Julius Marminge f5e4df5cab Use Debouncer for store state persistence
- Replace manual timeout debounce logic with `@tanstack/react-pacer`'s `Debouncer`
- Persist updates via `maybeExecute` to reduce localStorage write thrashing
- Flush pending persistence on `beforeunload` to avoid losing recent state
2026-03-09 14:02:29 -07:00
Julius Marminge 1f47cc6f4e Remove ProviderHealth onReady callback from service interface
- Drop the unused `onReady` hook from `ProviderHealthShape`
- Keep startup health status access focused on `getStatuses`
2026-03-09 14:02:29 -07:00
Tim SmartandClaude Opus 4.6 074d3af79c cleanup
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-09 14:02:29 -07:00
Chukwudi Nwobodo 6593645c80 perf: run provider health checks in background, notify clients on ready
The ProviderHealth layer blocked server startup with two sequential CLI
spawns (codex --version + codex login status), each with a 4-second
timeout, delaying startup by up to 8 seconds.

Run health checks in the background via Effect.runPromise so the layer
resolves immediately with a placeholder status. Add an onReady callback
to ProviderHealthShape so wsServer can push the resolved statuses to
connected clients once checks complete, preventing early-connecting
clients from showing "Checking..." indefinitely.
2026-03-09 14:02:29 -07:00
Chukwudi Nwobodo 296eb82c31 perf: throttle domain event processing with 100ms batch window
During active sessions, every domain event triggered a full
syncSnapshot (IPC fetch + state rebuild + React re-render cascade) and
sometimes a provider query invalidation. Events fire in rapid bursts
during AI turns.

Replace per-event processing with a throttle-first pattern: schedule a
flush on the first event, absorb subsequent events within a 100ms
window, then sync once. Provider query invalidation is batched via a
flag. Since syncSnapshot fetches the complete snapshot, no events are
lost by skipping intermediate syncs.
2026-03-09 14:02:29 -07:00
Chukwudi Nwobodo 7a377fc5e4 perf: debounce Zustand store persistence and deduplicate legacy cleanup
The useStore subscriber called persistState on every state mutation,
triggering JSON.stringify + localStorage.setItem synchronously. It also
ran 8 localStorage.removeItem calls for legacy keys on every fire.

Wrap the subscriber with a 500ms debounce so rapid state changes batch
into a single write. Move legacy key cleanup behind a one-time flag so
it runs only once per page load. Add a beforeunload handler to flush
the final state.
2026-03-09 14:02:29 -07:00
Chukwudi Nwobodo 90e0c2ab15 perf: debounce composer draft localStorage writes
Every keystroke triggered full JSON serialization of all composer drafts
(including base64 image attachments) and a synchronous localStorage
write. At normal typing speed this caused 5+ writes/sec, blocking the
main thread and creating noticeable input lag.

Wrap the Zustand persist storage with a 300ms debounce. In-memory state
updates remain immediate; only the serialization and storage write are
deferred. A beforeunload handler flushes pending writes to prevent data
loss. The removeItem method cancels any pending setItem to avoid
resurrecting cleared drafts.

Adds unit tests for the DebouncedStorage utility covering debounce
timing, rapid writes, removeItem cancellation, flush, and edge cases.
2026-03-09 14:02:29 -07:00
Cursor AgentandJulius Marminge 7a3d4d1f31 fix: stabilize onToggleRuntimeMode with useCallback to preserve memo
Co-authored-by: Julius Marminge <[email protected]>

Applied via @cursor push command
2026-03-09 11:57:27 -07:00
Julius Marminge e354e8697f Prevent compact diff sidebar from breaking chat composer layout
- Add composer footer/action data attributes for targeted width measurement
- Enforce a minimum composer width before allowing inline diff sidebar
2026-03-09 11:57:27 -07:00
Julius Marminge 993b578512 Use form clientWidth for composer compact footer checks
- Measure composer width from the form element in initial and resize paths
- Avoid relying on ResizeObserver contentRect width for compact footer layout decisions
2026-03-09 11:57:27 -07:00
Julius Marmingeandcodex ed518ef19f Fix provider picker after rebase
Co-authored-by: codex <[email protected]>
2026-03-09 11:57:27 -07:00
Julius Marminge 47117a7d85 Inline SidebarInset base classes and remove dead sidebar logic
- Replace `SIDEBAR_INSET_BASE_CLASSNAME` with an inline class string in `sidebar.tsx`
- Delete the now-unused `sidebar.logic.ts` helper and its focused unit test
2026-03-09 11:57:27 -07:00
Julius Marminge f623810903 Adapt composer footer to compact controls on narrow widths
- add shared footer layout breakpoint helper with tests
- switch chat composer footer to compact menu when width is constrained
- preserve plan sidebar toggle behavior while consolidating footer actions
2026-03-09 11:57:27 -07:00
Julius Marminge e9ffd5752b Fix plan composer layout and sidebar flex shrink behavior
- add `min-w-0` to chat/flex containers to prevent composer/sidebar overflow
- move `BranchToolbar` into the chat column so layout stays aligned with plan sidebar
- extract sidebar inset base classes to shared logic and add a regression test for `min-w-0`
2026-03-09 11:57:27 -07:00
293 changed files with 32276 additions and 7603 deletions

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
name: Bug report
description: Report broken behavior, regressions, crashes, or reliability issues.
title: "[Bug]: "
labels:
- bug
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for broken behavior, regressions, crashes, or reliability problems.
Search existing issues first and keep the report focused on one problem.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I included enough detail to reproduce or investigate the problem.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project is affected?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: Provide a minimal, deterministic repro.
placeholder: |
1. Start the app with ...
2. Open ...
3. Disconnect the network
4. Reconnect and send another prompt
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
placeholder: The thread should resume normally and accept the new message.
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual behavior
placeholder: The composer clears, no new turn starts, and the session stays in a pending state.
validations:
required: true
- type: dropdown
id: impact
attributes:
label: Impact
description: How bad is this in practice?
options:
- Blocks work completely
- Major degradation or frequent failure
- Minor bug or occasional failure
- Cosmetic issue
validations:
required: true
- type: input
id: version
attributes:
label: Version or commit
description: Release version, commit SHA, or branch name if known.
placeholder: main @ abc1234
- type: input
id: environment
attributes:
label: Environment
description: OS, browser or desktop app version, Node/Bun version, provider/model if relevant.
placeholder: macOS 15.3, Chrome 135, Bun 1.3.9, Codex app-server ...
- type: textarea
id: logs
attributes:
label: Logs or stack traces
description: Paste the most relevant output only. Redact secrets.
render: shell
- type: upload
id: attachments
attributes:
label: Screenshots, recordings, or supporting files
description: Upload screenshots, short recordings, repro archives, or log files. Redact secrets before uploading.
validations:
required: false
accept: ".png,.jpg,.jpeg,.gif,.webp,.svg,.mp4,.mov,.webm,.log,.txt,.json,.zip"
- type: textarea
id: workaround
attributes:
label: Workaround
description: If you found a temporary workaround, include it.
placeholder: Restarting the provider session clears the stuck state.
+101
View File
@@ -0,0 +1,101 @@
name: Feature request
description: Propose a scoped improvement or new capability.
title: "[Feature]: "
labels:
- enhancement
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for new capabilities or meaningful improvements to existing behavior.
This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I am describing a concrete problem or use case, not just a vague idea.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project would this change affect?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: problem
attributes:
label: Problem or use case
description: What are you trying to do? What is hard, slow, or impossible today?
placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state.
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: Describe the behavior, API, or UX you want.
placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load.
validations:
required: true
- type: textarea
id: value
attributes:
label: Why this matters
description: Who benefits, and what outcome does this unlock?
placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions.
validations:
required: true
- type: textarea
id: scope
attributes:
label: Smallest useful scope
description: What is the narrowest version of this request that would still solve your problem?
placeholder: A first pass only needs to support restoring the active session for the current thread.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: Workarounds, prior art, or other approaches you considered.
placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context.
- type: textarea
id: tradeoffs
attributes:
label: Risks or tradeoffs
description: What costs, complexity, or edge cases should be considered?
placeholder: This may require careful handling when the underlying provider session has already exited.
- type: textarea
id: references
attributes:
label: Examples or references
description: Links, screenshots, mockups, or comparable tools.
- type: checkboxes
id: contribution
attributes:
label: Contribution
options:
- label: I would be open to helping implement this.
+3
View File
@@ -19,6 +19,7 @@ github:hwanseoc
github:jamesx0416
github:jasonLaster
github:JoeEverest
github:maria-rcks
github:nmggithub
github:Noojuno
github:notkainoa
@@ -26,3 +27,5 @@ github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
+10 -7
View File
@@ -8,11 +8,11 @@ on:
jobs:
quality:
name: Lint, Typecheck, Test, Browser Test, Build
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -20,12 +20,12 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Cache Bun and Turbo
uses: actions/cache@v4
uses: actions/cache@v5
with:
path: |
~/.bun/install/cache
@@ -35,7 +35,7 @@ jobs:
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v4
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
@@ -45,6 +45,9 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Format
run: bun run fmt:check
- name: Lint
run: bun run lint
@@ -75,7 +78,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -83,7 +86,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
+75
View File
@@ -0,0 +1,75 @@
name: Issue Labels
on:
push:
branches:
- main
paths:
- .github/ISSUE_TEMPLATE/**
- .github/workflows/issue-labels.yml
workflow_dispatch:
permissions:
issues: write
jobs:
sync:
name: Sync issue labels
runs-on: ubuntu-24.04
steps:
- name: Ensure managed issue labels exist
uses: actions/github-script@v7
with:
script: |
const managedLabels = [
{
name: "bug",
color: "d73a4a",
description: "Something is broken or behaving incorrectly.",
},
{
name: "enhancement",
color: "a2eeef",
description: "Requested improvement or new capability.",
},
{
name: "needs-triage",
color: "fbca04",
description: "Issue needs maintainer review and initial categorization.",
},
];
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
+202
View File
@@ -0,0 +1,202 @@
name: PR Size
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
permissions:
contents: read
jobs:
prepare-config:
name: Prepare PR size config
runs-on: ubuntu-24.04
outputs:
labels_json: ${{ steps.config.outputs.labels_json }}
steps:
- id: config
name: Build PR size label config
uses: actions/github-script@v8
with:
result-encoding: string
script: |
const managedLabels = [
{
name: "size:XS",
color: "0e8a16",
description: "0-9 changed lines (additions + deletions).",
},
{
name: "size:S",
color: "5ebd3e",
description: "10-29 changed lines (additions + deletions).",
},
{
name: "size:M",
color: "fbca04",
description: "30-99 changed lines (additions + deletions).",
},
{
name: "size:L",
color: "fe7d37",
description: "100-499 changed lines (additions + deletions).",
},
{
name: "size:XL",
color: "d93f0b",
description: "500-999 changed lines (additions + deletions).",
},
{
name: "size:XXL",
color: "b60205",
description: "1,000+ changed lines (additions + deletions).",
},
];
core.setOutput("labels_json", JSON.stringify(managedLabels));
sync-label-definitions:
name: Sync PR size label definitions
needs: prepare-config
if: github.event_name != 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: write
steps:
- name: Ensure PR size labels exist
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
}
}
label:
name: Label PR size
needs: prepare-config
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: read
pull-requests: write
concurrency:
group: pr-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
steps:
- name: Sync PR size label
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const issueNumber = context.payload.pull_request.number;
const additions = context.payload.pull_request.additions ?? 0;
const deletions = context.payload.pull_request.deletions ?? 0;
const changedLines = additions + deletions;
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
const resolveSizeLabel = (totalChangedLines) => {
if (totalChangedLines < 10) {
return "size:XS";
}
if (totalChangedLines < 30) {
return "size:S";
}
if (totalChangedLines < 100) {
return "size:M";
}
if (totalChangedLines < 500) {
return "size:L";
}
if (totalChangedLines < 1000) {
return "size:XL";
}
return "size:XXL";
};
const nextLabelName = resolveSizeLabel(changedLines);
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
core.info(`PR #${issueNumber}: ${changedLines} changed lines -> ${nextLabelName}`);
+43 -19
View File
@@ -25,7 +25,7 @@ jobs:
targets: ${{ steps.collect.outputs.targets }}
steps:
- id: collect
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
if (context.eventName === "pull_request_target") {
@@ -85,7 +85,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Sync PR labels
uses: actions/github-script@v7
uses: actions/github-script@v8
env:
PR_NUMBER: ${{ matrix.target.number }}
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
@@ -111,7 +111,7 @@ jobs:
},
];
const managedLabelNames = managedLabels.map((label) => label.name);
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
for (const label of managedLabels) {
try {
@@ -138,13 +138,19 @@ jobs:
throw error;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
}
}
@@ -159,17 +165,35 @@ jobs:
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
const preservedLabels = currentLabels
.map((label) => label.name)
.filter((name) => !managedLabelNames.includes(name));
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
await github.rest.issues.setLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [...preservedLabels, nextLabelName],
});
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
+40 -14
View File
@@ -27,7 +27,7 @@ jobs:
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- id: release_meta
name: Resolve release version
@@ -61,7 +61,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
@@ -107,7 +107,7 @@ jobs:
arch: x64
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
@@ -118,13 +118,16 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build desktop artifact
shell: bash
env:
@@ -214,7 +217,7 @@ jobs:
fi
- name: Upload build artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release-publish/*
@@ -226,7 +229,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
@@ -236,7 +239,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
@@ -244,6 +247,9 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
@@ -256,17 +262,17 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Download all desktop artifacts
uses: actions/download-artifact@v4
uses: actions/download-artifact@v8
with:
pattern: desktop-*
merge-multiple: true
@@ -302,11 +308,31 @@ jobs:
needs: [preflight, release]
runs-on: ubuntu-24.04
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
ref: main
fetch-depth: 0
token: ${{ steps.app_token.outputs.token }}
persist-credentials: true
- id: app_bot
name: Resolve GitHub App bot identity
env:
GH_TOKEN: ${{ steps.app_token.outputs.token }}
APP_SLUG: ${{ steps.app_token.outputs.app-slug }}
run: |
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -314,7 +340,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version-file: package.json
@@ -343,8 +369,8 @@ jobs:
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git config user.name "${{ steps.app_bot.outputs.name }}"
git config user.email "${{ steps.app_bot.outputs.email }}"
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"
+2
View File
@@ -13,6 +13,8 @@ build/
.logs/
release/
.t3
.idea/
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
.vitest-*
+3 -2
View File
@@ -7,7 +7,8 @@
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js"
],
"experimentalSortPackageJson": {}
"sortPackageJson": {}
}
+7
View File
@@ -1,20 +1,24 @@
# Plan: Centralize Model Normalization in Contracts
## Summary
Move model alias/default normalization into `packages/contracts` so desktop and renderer use one shared source of truth.
## Motivation
- Removes duplicated logic between:
- `apps/desktop/src/codexAppServerManager.ts`
- `apps/renderer/src/model-logic.ts`
- Prevents behavior drift when model aliases/defaults are updated.
## Scope
- Add shared model utilities to contracts.
- Update desktop and renderer to consume shared utilities.
- Keep renderer-specific display options in renderer.
## Proposed Changes
1. Add `packages/contracts/src/model.ts` with:
- Canonical model list
- Alias map
@@ -29,14 +33,17 @@ Move model alias/default normalization into `packages/contracts` so desktop and
- Keep renderer tests focused on renderer-only behavior.
## Risks
- Desktop/renderer may currently rely on slightly different fallback behavior.
- Import graph must avoid bundling issues for Electron main/preload.
## Validation
- `bun run test`
- `bun run typecheck`
- Manual check that model selection and session start still send expected model slug.
## Done Criteria
- No duplicated alias/default map in desktop and renderer.
- Shared model utilities are contract-tested.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Strengthen Typed IPC Boundaries in Main Process
## Summary
Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers.
## Motivation
- `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`.
- Casts can hide contract breakages until runtime.
## Scope
- Desktop main process IPC registration.
- Optional shared helper for handler registration.
## Proposed Changes
1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to:
- Parse payload(s) with Zod schemas
- Standardize typed handler signatures
@@ -24,14 +28,17 @@ Replace loose payload casting in IPC handlers with strict schema parsing and typ
4. Add tests for handler parsing failure paths (invalid payloads).
## Risks
- Refactor can subtly change IPC error shape/messages.
- Helper abstraction should stay simple and not obscure control flow.
## Validation
- `bun run test`
- `bun run typecheck`
- Manual invalid payload check from renderer/devtools to confirm fast failure.
## Done Criteria
- No provider handler uses `payload as Parameters<...>`.
- All IPC entrypoints parse unknown payloads at boundary.
@@ -1,9 +1,11 @@
# Plan: Decompose CodexAppServerManager
## Summary
Split `CodexAppServerManager` into smaller modules with clear responsibilities.
## Motivation
- `apps/desktop/src/codexAppServerManager.ts` is large and mixes:
- Process lifecycle
- JSON-RPC parsing/routing
@@ -12,10 +14,12 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- This increases regression risk and slows changes.
## Scope
- Desktop provider internals only.
- Keep external behavior/API stable.
## Proposed Changes
1. Extract modules:
- `codex/processLifecycle.ts`
- `codex/jsonrpcRouter.ts`
@@ -29,13 +33,16 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- Session state transitions
## Risks
- Reordering event handling can change behavior.
- Must preserve pending request timeout/cancellation semantics.
## Validation
- Existing tests pass.
- Add module-level tests for parsing and transition logic.
## Done Criteria
- Main manager file materially smaller and orchestration-focused.
- Core protocol/state logic covered by focused tests.
+7
View File
@@ -1,9 +1,11 @@
# Plan: Split ChatView into Smaller UI/Logic Units
## Summary
Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
## Motivation
- `apps/renderer/src/components/ChatView.tsx` is large and handles:
- Session orchestration
- Send/interrupt actions
@@ -13,10 +15,12 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
- Hard to test and maintain as one component.
## Scope
- Renderer component boundaries and hooks.
- Keep visual behavior unchanged.
## Proposed Changes
1. Create hook: `apps/renderer/src/hooks/useChatSession.ts`
- `ensureSession`
- `sendTurn`
@@ -29,12 +33,15 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
4. Add focused tests for hook behavior (error handling, session reuse).
## Risks
- Refactor can break subtle UI interactions (auto-scroll, menu close, keyboard send).
## Validation
- `bun run test`
- Manual smoke: send, stream, interrupt, model switch.
## Done Criteria
- `ChatView.tsx` significantly reduced and easier to scan.
- Session logic isolated from rendering.
@@ -1,17 +1,21 @@
# Plan: Move Renderer Persisted-State Validation to Zod
## Summary
Use explicit Zod schemas for localStorage state parsing and migration.
## Motivation
- `apps/renderer/src/store.ts` has large manual sanitize functions.
- Manual type guards are verbose and easier to get wrong during schema evolution.
## Scope
- Renderer state hydration/persistence path.
- No backend/protocol changes.
## Proposed Changes
1. Add schema module: `apps/renderer/src/persistenceSchema.ts`
- Persisted payload versions (`v1`, `v2`)
- Thread/message/project schemas
@@ -23,12 +27,15 @@ Use explicit Zod schemas for localStorage state parsing and migration.
- Unknown thread/project references filtered
## Risks
- Overly strict schemas could drop valid historical data unexpectedly.
## Validation
- Unit tests for migration/hydration.
- Manual reload test with existing localStorage data.
## Done Criteria
- Store hydration logic is schema-driven.
- Migration behavior is tested and documented.
@@ -1,17 +1,21 @@
# Plan: Add Provider Log Stream Lifecycle Management
## Summary
Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely.
## Motivation
- `apps/desktop/src/providerManager.ts` opens a write stream in constructor.
- Stream lifecycle is not explicit on shutdown.
## Scope
- Desktop provider logging behavior.
- App shutdown integration.
## Proposed Changes
1. Add explicit `dispose()` on `ProviderManager`:
- Remove event listeners
- End/close log stream
@@ -20,12 +24,15 @@ Ensure `ProviderManager` logging stream is initialized, rotated/structured, and
4. Optional: per-session log files under `.logs/providers/`.
## Risks
- Improper close sequencing may lose final log lines.
## Validation
- Manual run/quit cycle to ensure no open handle warnings.
- Confirm logs flush on quit and file descriptors are not leaked.
## Done Criteria
- ProviderManager owns complete log stream lifecycle.
- Shutdown path explicitly disposes provider resources.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Add CI Workflow for Core Quality Gates
## Summary
Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-test) on pushes and PRs.
## Motivation
- Repository currently has no CI workflow files.
- Quality checks are only local/manual.
## Scope
- `.github/workflows/ci.yml`
- Bun + Turbo setup in CI.
## Proposed Changes
1. Add `ci.yml` with jobs:
- Setup Bun and Node environment
- Install deps
@@ -22,13 +26,16 @@ Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-tes
3. Configure caching for Bun/Turbo as appropriate.
## Risks
- Smoke test may be flaky in headless CI environments.
- CI runtime can grow if caching is misconfigured.
## Validation
- Verify workflow runs on a branch PR.
- Ensure failures surface clearly by job name.
## Done Criteria
- CI blocks regressions in lint/typecheck/test.
- Workflow docs added to README.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Add Pre-Commit Formatting/Lint Hooks
## Summary
Introduce pre-commit automation so formatting and basic lint checks happen before commits.
## Motivation
- Current lint failures include formatting-only issues.
- Shift-left feedback reduces noisy CI failures and cleanup churn.
## Scope
- Root tooling config and package scripts.
- No runtime code changes.
## Proposed Changes
1. Add hook tooling (e.g. Husky + lint-staged or Lefthook).
2. Configure staged-file tasks:
- `biome format --write`
@@ -20,13 +24,16 @@ Introduce pre-commit automation so formatting and basic lint checks happen befor
4. Keep checks fast to avoid developer friction.
## Risks
- Slow hooks can frustrate contributors and be bypassed.
- Need to ensure compatibility with Bun workspace setup.
## Validation
- Create sample staged changes and verify hook behavior.
- Confirm formatting fixes are applied automatically.
## Done Criteria
- Pre-commit hook installed and documented.
- Formatting-only lint failures drop significantly.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Expand Event/State Transition Test Coverage
## Summary
Add focused tests for renderer event handling and session evolution logic.
## Motivation
- Core behavior is event-driven and stateful.
- Existing renderer tests cover only a subset of timeline/model behavior.
## Scope
- `apps/renderer/src/session-logic.test.ts`
- Optional reducer tests for `apps/renderer/src/store.ts`.
## Proposed Changes
1. Add tests for `evolveSession`:
- `thread/started`
- `turn/started`
@@ -24,12 +28,15 @@ Add focused tests for renderer event handling and session evolution logic.
3. Add reducer integration tests for `APPLY_EVENT`.
## Risks
- Tests may be brittle if event payload fixtures are too coupled to implementation details.
## Validation
- `bun run test`
- Ensure new tests remain deterministic and fast.
## Done Criteria
- High-risk event transitions are covered by unit tests.
- Regressions in stream assembly/session status are caught quickly.
@@ -1,17 +1,21 @@
# Plan: Unify Process and PTY Session Abstractions in ProcessManager
## Summary
Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes.
## Motivation
- `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic.
- New execution backends/providers will multiply complexity.
## Scope
- Desktop process execution internals.
- Preserve public `ProcessManager` API.
## Proposed Changes
1. Introduce internal interface (e.g. `RuntimeSession`):
- `write(data)`
- `kill()`
@@ -24,12 +28,15 @@ Refactor `ProcessManager` to use a single runtime-session interface for child-pr
5. Add tests for both implementations.
## Risks
- PTY behavior differs by platform; abstraction must not hide required differences.
## Validation
- Existing `processManager.test.ts` passes.
- Add PTY-path tests where feasible.
## Done Criteria
- Manager no longer branches per backend in `write/kill/killAll`.
- Session backends are independently testable.
+1 -3
View File
@@ -1,5 +1,3 @@
PR 1: Service contracts + error taxonomy
Add ProviderService, CodexService, CheckpointStore as Context.Tag service defs.
Add typed Schema.TaggedError hierarchies for all 3 services (cause: Schema.optional(Schema.Defect) on each).
@@ -39,4 +37,4 @@ Remove throw-based flow entirely from provider path.
PR 10: Cleanup + deprecation removal
Remove legacy class implementations/adapters once parity is proven.
Finalize layer composition and startup graph docs.
Add architecture notes for service boundaries and error model.
Add architecture notes for service boundaries and error model.
+9
View File
@@ -1,12 +1,14 @@
# Effect Migration Plan (From Current State)
Current status summary:
- Service contracts, typed errors, and most checkpoint/persistence services exist.
- `ProviderServiceLive` is already native orchestration (not a thin adapter).
- Production server path still uses legacy `ProviderManager`/`FilesystemCheckpointStore`.
- Checkpoint flow now avoids snapshot re-sync and is write-time driven.
## PR 1: Wire Provider/Checkpoint Effect Stack Into `wsServer`
- Build one runtime layer graph for provider + checkpoint + persistence + orchestration.
- Resolve `ProviderService` from runtime in `wsServer`.
- Replace `ProviderManager` method calls in WS handlers with `ProviderService` calls.
@@ -14,12 +16,14 @@ Current status summary:
- Keep WS method/push payloads identical.
## PR 2: Runtime Composition + Startup Ownership
- Create/centralize `AppLive` composition for server startup.
- Ensure outer runtime provides Node/platform services once.
- Ensure migrations run at startup via scoped/layer startup path.
- Remove ad-hoc service initialization in request-time paths.
## PR 3: Session Lifecycle Hygiene + Checkpoint Invariants
- Add explicit checkpoint session cleanup on `stopSession` / `stopAll`.
- Remove per-session lock/cwd map leaks.
- Keep strict invariant model:
@@ -29,12 +33,14 @@ Current status summary:
- Add tests for lifecycle cleanup and invariant-failure surfaces.
## PR 4: Provider Event Stream Hardening (Without Extra Service Fragmentation)
- Keep `ProviderService` as the public event surface.
- Internally move callback fanout to Effect concurrency primitives (`Queue`/`PubSub`) for ordering/backpressure control.
- Keep API as `subscribeToEvents` unless we explicitly choose stream API later.
- Add tests for ordering and subscriber isolation under load.
## PR 5: Codex Runtime Split (Scoped Effect Core)
- Extract `CodexAppServerManager` responsibilities into Effect-native layers:
- scoped process lifecycle
- RPC request/response + pending map via `Deferred`
@@ -43,16 +49,19 @@ Current status summary:
- Preserve protocol behavior and timeout semantics.
## PR 6: Codex Protocol Decode Hardening
- Replace ad-hoc unknown parsing with runtime schema decode.
- Map decode failures to typed tagged errors with `cause` retained.
- Add regression tests for malformed/partial protocol frames.
## PR 7: Remove Legacy Provider Stack
- Remove `ProviderManager` + legacy checkpoint integration from runtime path.
- Remove `FilesystemCheckpointStore` from active server flow (keep only if explicitly needed for compatibility tooling).
- Update tests to assert only Effect service path is used.
## PR 8: Final Cleanup + Docs
- Update architecture docs with final layer graph and service boundaries.
- Document error model and recovery semantics.
- Trim dead compatibility code and stale plan references.
@@ -1,6 +1,7 @@
# ProviderService Integration Test Plan
Goal:
- Validate end-to-end `ProviderService` behavior with real layers:
- `ProviderServiceLive`
- `CheckpointServiceLive`
@@ -13,6 +14,7 @@ Goal:
## Test Harness
Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Layers/TestProviderAdapter.integration.ts`:
- Service contract: `ProviderAdapterShape<ProviderAdapterError>`.
- Internal state:
- session registry (session + cwd + threadId)
@@ -29,13 +31,15 @@ Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Lay
- `readThread`, `rollbackThread`, `stopSession`, `stopAll`.
Use real git-backed temporary workspaces in integration tests:
- initialize repo with baseline commit
- run provider turn in workspace
- assert checkpoint diffs against real git refs
## Core Integration Specs
1) `startSession` initializes checkpoint root exactly once
1. `startSession` initializes checkpoint root exactly once
- Arrange:
- start provider session in git repo.
- Assert:
@@ -43,7 +47,8 @@ Use real git-backed temporary workspaces in integration tests:
- checkpoint ref exists in git.
- second `startSession` for new session creates a new independent root.
2) Turn without filesystem change
2. Turn without filesystem change
- Arrange:
- emit normal turn events, no file mutation.
- Assert:
@@ -54,7 +59,8 @@ Use real git-backed temporary workspaces in integration tests:
- `listCheckpoints` returns root + turn 1.
- `getCheckpointDiff(0 -> 1)` returns empty/no-op diff.
3) Turn with filesystem change
3. Turn with filesystem change
- Arrange:
- mutate `README.md` during turn.
- Assert:
@@ -62,7 +68,8 @@ Use real git-backed temporary workspaces in integration tests:
- `getCheckpointDiff(0 -> 1)` contains file path and hunk.
- persisted checkpoint metadata includes non-empty `checkpointRef`.
4) Multi-turn sequencing and checkpoint monotonicity
4. Multi-turn sequencing and checkpoint monotonicity
- Arrange:
- turn 1: no file change
- turn 2: file change
@@ -72,7 +79,8 @@ Use real git-backed temporary workspaces in integration tests:
- latest checkpoint is marked current.
- diffs for adjacent turns map to expected filesystem deltas.
5) Revert to checkpoint
5. Revert to checkpoint
- Arrange:
- execute 3 turns with at least one file-changing turn.
- call `revertToCheckpoint(turnCount=1)`.
@@ -82,7 +90,8 @@ Use real git-backed temporary workspaces in integration tests:
- DB rows for turns >1 are removed.
- later refs are deleted from git.
6) Capture failure surface
6. Capture failure surface
- Arrange:
- adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails.
- Assert:
@@ -92,6 +101,7 @@ Use real git-backed temporary workspaces in integration tests:
## WebSocket Coverage (Thin Integration)
Add one ws server integration spec:
- Subscribe to `providers.event`.
- Run a deterministic provider turn through ws methods.
- Assert push stream includes:
@@ -101,10 +111,13 @@ Add one ws server integration spec:
## Proposed PR Split
PR A:
- Test adapter harness + shared integration fixtures (repo setup, runtime/layer setup).
PR B:
- Core ProviderService integration specs (cases 1-4).
PR C:
- Revert + failure-path specs (cases 5-6) + ws thin integration spec.
@@ -1,6 +1,7 @@
# Server-Authoritative Event-Sourcing Cleanup Plan
Goal:
- Move to a cleaner service architecture with:
- durable, server-authoritative event sourcing
- strict command routing/validation
@@ -85,6 +86,7 @@ CheckpointCatalog ------> SQLite
## Commit Series
### Commit 1: Split public vs system orchestration command contracts
- Create separate schemas/types:
- `ClientOrchestrationCommandSchema`
- `SystemOrchestrationCommandSchema`
@@ -100,6 +102,7 @@ CheckpointCatalog ------> SQLite
- preserve internal dispatch functionality for system commands
### Commit 2: Introduce `OrchestrationCommandRouter` + handler boundary
- Add dedicated router service to validate, authorize, and route commands.
- Move command-to-event mapping out of `orchestration/Layer.ts` into handlers.
- Add aggregate-level invariant checks before append (thread exists, project exists, etc.).
@@ -113,6 +116,7 @@ CheckpointCatalog ------> SQLite
- handler happy-path tests per command type
### Commit 3: Harden event store for idempotency + optimistic append metadata
- Add DB-level idempotency guard for `command_id` (`UNIQUE` where non-null).
- Extend append API to support idempotent replays and deterministic return of prior event on duplicate `commandId`.
- Add optional aggregate version metadata for future optimistic concurrency.
@@ -125,6 +129,7 @@ CheckpointCatalog ------> SQLite
- concurrent append behavior stays ordered and deterministic
### Commit 4: Extract provider-runtime -> orchestration bridge from `wsServer`
- Create `ProviderRuntimeIngestionService` that:
- subscribes to `ProviderService.streamEvents`
- translates runtime events into orchestration commands
@@ -139,6 +144,7 @@ CheckpointCatalog ------> SQLite
- ws integration confirms same external push behavior
### Commit 5: Make session directory durable (`ProviderSessionRegistry`)
- Replace in-memory-only `ProviderSessionDirectoryLive` with persistence-backed registry.
- Keep in-memory cache optional, but source of truth must be persistent.
- Add startup reconciliation to prune dead sessions / keep known thread mapping.
@@ -152,6 +158,7 @@ CheckpointCatalog ------> SQLite
- stale session cleanup semantics
### Commit 6: Re-key checkpoint metadata from session to thread identity
- Change checkpoint catalog primary identity from `provider_session_id` to durable `thread_id`.
- Keep `session_id` as nullable metadata only.
- Update checkpoint flows (`initialize`, `capture`, `list`, `diff`, `revert`) to use thread identity.
@@ -165,6 +172,7 @@ CheckpointCatalog ------> SQLite
- revert/diff still work after session churn
### Commit 7: Add durable projection persistence for orchestration read models
- Introduce projection tables/snapshots persisted in DB to avoid full replay dependency.
- Keep event stream as source of truth; projection rebuild stays deterministic.
- `getSnapshot` reads from projection store (memory cache optional).
@@ -177,6 +185,7 @@ CheckpointCatalog ------> SQLite
- projection rebuild from events yields same result as previous reducer semantics
### Commit 8: Narrow `ProviderService` responsibilities
- Keep `ProviderService` focused on provider RPC/session lifecycle + unified runtime stream.
- Move checkpoint-capture side effects out of provider event worker into dedicated ingestion/checkpoint pipeline service.
- Preserve adapter pluggability and provider-neutral contracts.
@@ -188,6 +197,7 @@ CheckpointCatalog ------> SQLite
- checkpoint capture still triggered by turn completion through new coordinator
### Commit 9: Look over schemas (contracts and events)
- Scan for unused schemas.
- Use effect/Schema everywhere
- Analyze which we need
@@ -196,6 +206,7 @@ CheckpointCatalog ------> SQLite
- Persistence entities
### Commit 10: Remove dead legacy path and finalize docs
- Remove unused legacy manager/store path from active architecture:
- `providerManager.ts`
- `filesystemCheckpointStore.ts` (if no longer needed by tests/tools)
@@ -210,6 +221,7 @@ CheckpointCatalog ------> SQLite
- no regressions in WS protocol behavior
## Risk Controls
- Keep WS method names and payload contracts stable throughout.
- Gate each commit with targeted integration tests before moving forward.
- Avoid broad event-type churn in one step; migrate schemas incrementally with clear compatibility windows.
+2 -1
View File
@@ -1,10 +1,11 @@
Rewrite `createServer` and `index.ts` to be Effect native.
Maybe use `effect/unstable/Socket` for the web socket server
- https://github.com/Effect-TS/effect-smol/blob/main/packages/effect/src/unstable/socket/SocketServer.ts
- https://github.com/Effect-TS/effect-smol/blob/main/packages/platform-node/test/NodeSocket.test.ts
- Migrate remaining runtime code to Effect
- `gitManager` -> `src/git`
- `terminalManager` -> `src/terminal` (Manager + PTY)
- ...
- ...
@@ -24,21 +24,25 @@
- Mark invalid/false-positive items with explicit rationale.
Exit criteria:
- Every open thread is mapped to one canonical fix item or marked invalid.
## Phase 1: Runtime Survival and Critical Event Wiring
Related bug groups solved together:
- Worker loop/fiber fatal error handling in orchestration reactors.
- WebSocket message error boundaries and unhandled rejection guards.
- Close invalid `providers.event` review findings as documented architecture mismatch (no code change expected).
Primary files:
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
- `apps/server/src/wsServer.ts`
Exit criteria:
- A single event-processing failure cannot permanently stop ingestion/reactor loops.
- WS message handling cannot produce unhandled promise rejections.
- Invalid provider-event-channel review findings are closed with architecture rationale.
@@ -46,17 +50,20 @@ Exit criteria:
## Phase 2: State Consistency and Ordering
Related bug groups solved together:
- Fire-and-forget revert completion causing consistency windows.
- Non-atomic append/projection paths and retry behavior.
- Race-sensitive thread/event association issues.
Primary files:
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
- `apps/server/src/orchestration/Layers/OrchestrationEngine.ts`
- `apps/server/src/orchestration/Layers/ProjectionPipeline.ts`
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
Exit criteria:
- Revert flow is deterministically reflected in read model updates.
- Append/project failure mode is explicit and safe under retry.
- No cross-thread misassociation under concurrent runtime events.
@@ -64,12 +71,14 @@ Exit criteria:
## Phase 3: Checkpointing Correctness Bundle
Related bug groups solved together:
- Checkpoint input normalization consistency.
- Snapshot/projector coverage mismatches.
- Checkpoint ref/workspace CWD utility duplication.
- Checkpoint diff/error handling behavior gaps.
Primary files:
- `apps/server/src/checkpointing/Layers/CheckpointStore.ts`
- `apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts`
- `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts`
@@ -77,6 +86,7 @@ Primary files:
- `apps/server/src/wsServer.ts`
Exit criteria:
- Checkpoint capture/restore/revert paths use one normalization policy.
- Required projectors are actually represented in snapshot reads.
- Shared checkpoint/ref/CWD helpers are centralized.
@@ -84,27 +94,32 @@ Exit criteria:
## Phase 4: Memory and Lifecycle Hygiene
Related bug groups solved together:
- Unbounded in-memory dedup sets/maps.
- Missing cleanup/lifecycle protections in long-lived effects/resources.
Primary files:
- `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
- `apps/server/src/config.ts`
Exit criteria:
- Long-running server memory does not grow unbounded from dedup bookkeeping.
- Resource cleanup paths are registered for interruption/shutdown.
## Phase 5: Transport, Parsing, and Platform Edge Cases
Related bug groups solved together:
- UTF-8 chunk boundary decode correctness.
- Markdown/file-link parsing edge cases.
- Shell/OS-specific PATH parsing behavior.
- Git rename parsing and small keybinding edge cases.
Primary files:
- `apps/server/src/wsServer.ts`
- `apps/server/src/git/Layers/CodexTextGeneration.ts`
- `apps/web/src/markdown-links.ts`
@@ -113,23 +128,27 @@ Primary files:
- `apps/server/src/keybindings.ts`
Exit criteria:
- Edge-case parsers are robust across valid but non-trivial inputs.
- Platform-dependent command behavior has safe fallbacks.
## Phase 6: Build and Maintainability Cleanup
Related bug groups solved together:
- Build script/runtime assumption cleanup.
- Redundant error-union declarations and utility/type duplication.
- Non-functional cleanup comments/docs markers.
Primary files:
- `apps/server/package.json`
- `apps/server/src/checkpointing/Errors.ts`
- Shared utility locations introduced during earlier phases
- `AGENTS.md` (if cleanup is still pending)
Exit criteria:
- Build path is explicit and environment-safe.
- Redundant types/utilities are removed in favor of single sources of truth.
@@ -140,6 +159,7 @@ Exit criteria:
- Resolve threads with fix references per canonical checklist item.
Exit criteria:
- Lint passes.
- Backend tests pass.
- All actionable review threads are resolved or explicitly justified.
+5 -4
View File
@@ -5,6 +5,7 @@ _Last updated: 2026-02-26_
This is the working checklist for remediation execution.
Status values:
- `TODO`: Not started
- `IN_PROGRESS`: Currently being worked
- `BLOCKED`: Waiting on decision/dependency
@@ -150,7 +151,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Area: `WebSocket robustness`
- File: `apps/web/src/wsTransport.ts:59`
- Threads: PRRT_kwDORLtfbc5whtrN
- Audit note: Transport _tag override risk exists but current callsites are constrained.
- Audit note: Transport \_tag override risk exists but current callsites are constrained.
### Phase 2
@@ -181,7 +182,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Threads: PRRT_kwDORLtfbc5whxJO
- Audit note: Message fallback retention issue is real, but prior FK-violation claim is overstated.
- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes *after* the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes _after_ the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
@@ -198,7 +199,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Severity: `Medium`
- Area: `Checkpointing correctness`
- File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:94`
- Threads: PRRT_kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv_, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))
- Threads: PRRT*kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv*, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))
- Audit note: Edge schema strategy is in place across contracts/consumers (trim/normalize via schemas and decode at boundaries); CheckpointStore remains an internal repository boundary.
- [x] `C017` `REQUIRED_SNAPSHOT_PROJECTORS` includes `pending-approvals` and `thread-turns`, but `getSnapshot` doesn't query their data. If these projectors lag behind, the returned `snapshotSequence` will be lower than what the included data actually reflects, causing clients to replay already-applied events. Consider filtering `REQUIRED_SNAPSHOT_PROJECTORS` to only include projectors whose data is actually fetched in the snapshot. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
@@ -250,7 +251,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
### Phase 5
- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after ` => ` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after `=>` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
+441
View File
@@ -0,0 +1,441 @@
# Plan: Claude Code Integration (Orchestration Architecture)
## Why this plan was rewritten
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
1. `orchestration.dispatchCommand` (client intent)
2. `OrchestrationEngine` (decide + persist + publish domain events)
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
4. `ProviderService` (adapter routing + canonical runtime stream)
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
6. `orchestration.domainEvent` (single push channel consumed by web)
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
---
## Current constraints to design around (post-Stage 1)
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
---
## Architecture target
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
Key decisions:
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
---
## Phase 1: Contracts and command shape updates
### 1.1 Provider-aware model contract
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
Expected outcomes:
1. Introduce provider-scoped model lists (Codex + Claude).
2. Add helpers that resolve model by provider.
3. Preserve backwards compatibility for existing Codex defaults.
### 1.2 Turn-start provider intent
Update `packages/contracts/src/orchestration.ts`:
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
2. Carry provider through `ThreadTurnStartRequestedPayload`.
3. Keep existing command valid when provider is omitted.
This removes the implicit “Codex unless session already exists” behavior as the only path.
### 1.3 Provider session start input for Claude runtime knobs (completed)
Update `packages/contracts/src/provider.ts`:
1. Move provider-specific start fields into typed `providerOptions`:
- `providerOptions.codex`
- `providerOptions.claudeCode`
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
3. Deprecate/remove `resumeThreadId` from the generic start contract.
4. Treat `resumeCursor` as adapter-owned opaque state.
### 1.4 Contract tests (completed)
Update/add tests in `packages/contracts/src/*.test.ts` for:
1. New command payload shape.
2. Provider-aware model resolution behavior.
3. Breaking-change expectations for removed top-level provider fields.
---
## Phase 2: Claude adapter implementation
### 2.1 Add adapter service + layer
Create:
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
### 2.1.a SDK dependency and baseline config
Add server dependency:
1. `@anthropic-ai/claude-agent-sdk`
Baseline adapter options to support from day one:
1. `cwd`
2. `model`
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
6. `resume`
7. `resumeSessionAt`
8. `includePartialMessages`
9. `canUseTool`
10. `hooks`
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
### 2.2 Claude runtime bridge
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
Required capabilities:
1. Long-lived session context per adapter session.
2. Multi-turn input queue.
3. Interrupt support.
4. Approval request/response bridge.
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
#### 2.2.a Agent SDK details to preserve
The adapter should explicitly rely on these SDK capabilities:
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
2. Multi-turn input is supported via async-iterable prompt input.
3. Tool approval decisions are provided via `canUseTool`.
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
#### 2.2.b Effect-native session lifecycle skeleton
```ts
import { query } from "@anthropic-ai/claude-agent-sdk";
import { Effect } from "effect";
const acquireSession = (input: ProviderSessionStartInput) =>
Effect.acquireRelease(
Effect.tryPromise({
try: async () => {
const claudeOptions = input.providerOptions?.claudeCode;
const resumeState = readClaudeResumeState(input.resumeCursor);
const abortController = new AbortController();
const result = query({
prompt: makePromptAsyncIterable(),
options: {
cwd: input.cwd,
model: input.model,
permissionMode: claudeOptions?.permissionMode,
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
resume: resumeState?.threadId,
resumeSessionAt: resumeState?.sessionAt,
signal: abortController.signal,
includePartialMessages: true,
canUseTool: makeCanUseTool(),
hooks: makeClaudeHooks(),
},
});
return { abortController, result };
},
catch: (cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId: "pending",
detail: "Failed to start Claude runtime session.",
cause,
}),
}),
({ abortController }) => Effect.sync(() => abortController.abort()),
);
```
#### 2.2.c AsyncIterable -> Effect Stream integration
Preferred when available in the pinned Effect version:
```ts
const sdkMessageStream = Stream.fromAsyncIterable(
session.result,
(cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
```
Portable fallback (already aligned with current server patterns):
```ts
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
let cancelled = false;
void (async () => {
try {
for await (const message of session.result) {
if (cancelled) break;
emit.single(message);
}
emit.end();
} catch (cause) {
emit.fail(
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
}
})();
return Effect.sync(() => {
cancelled = true;
});
});
```
### 2.3 Canonical event mapping
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
Initial mapping target:
1. assistant text deltas -> `content.delta`
2. final assistant text -> `item.completed` and/or `turn.completed`
3. approval requests -> `request.opened`
4. approval results -> `request.resolved`
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
6. errors -> `runtime.error`
7. plan/proposed-plan content when derivable
Implementation note:
1. Keep raw Claude message on `raw` for debugging.
2. Prefer canonical item/request kinds over provider-native enums.
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
### 2.4 Resume cursor strategy
Define Claude-owned opaque resume state, e.g.:
```ts
interface ClaudeResumeCursor {
readonly version: 1;
readonly threadId?: string;
readonly sessionAt?: string;
}
```
Rules:
1. Serialize only adapter-owned state into `resumeCursor`.
2. Parse/validate only inside Claude adapter.
3. Store updated cursor when Claude runtime yields enough data to resume safely.
4. Never overload orchestration thread id as Claude thread id.
### 2.5 Interrupt and stop semantics
Map orchestration stop/interrupt expectations onto SDK controls:
1. `interruptTurn()` -> active query interrupt.
2. `stopSession()` -> close session resources and prevent future sends.
3. `rollbackThread()` -> see Phase 4.
---
## Phase 3: Provider service and composition
### 3.1 Register Claude adapter
Update provider registry layer to include Claude:
1. add `claudeCode` -> `ClaudeAdapter`
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
### 3.2 Persist provider binding
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
Required validation:
1. Claude bindings survive restart.
2. resume cursor remains opaque and round-trips untouched.
3. stopAll + restart can recover Claude sessions when possible.
### 3.3 Provider start routing
Update `ProviderCommandReactor` / orchestration flow:
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
2. If a thread already has Claude session binding, reuse it.
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
---
## Phase 4: Checkpoint and revert strategy
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
Pick one explicit strategy:
### Option A: provider-native rewind
If SDK/runtime supports safe rewind:
1. implement in Claude adapter
2. keep `CheckpointReactor` unchanged
### Option B: session restart + state truncation shim
If no native rewind exists:
1. Claude adapter returns successful rollback by:
- stopping current Claude session
- clearing/rewriting stored Claude resume cursor to last safe resumable point
- forcing next turn to recreate session from persisted orchestration state
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
Whichever option is chosen:
1. behavior must be deterministic
2. checkpoint revert tests must pass under orchestration expectations
3. user-visible activity log should explain failures clearly when provider rollback is impossible
---
## Phase 5: Web integration
### 5.1 Provider picker and model picker
Update web state/UI:
1. allow choosing Claude as thread provider before first turn
2. show Claude model list from provider-aware model helpers
3. preserve existing Codex default behavior when provider omitted
Likely touch points:
1. `apps/web/src/store.ts`
2. `apps/web/src/components/ChatView.tsx`
3. `apps/web/src/types.ts`
4. `packages/shared/src/model.ts`
### 5.2 Settings for Claude executable/options
Add app settings if needed for:
1. Claude binary path
2. default permission mode
3. default max thinking tokens
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
### 5.3 Session rendering
No new WS channel should be needed. Claude should appear through existing:
1. thread messages
2. activities/worklog
3. approvals
4. session state
5. checkpoints/diffs
---
## Phase 6: Testing strategy
### 6.1 Contract tests
Cover:
1. provider-aware model schemas
2. provider field on turn-start command
3. provider-specific start options schema
### 6.2 Adapter layer tests
Add `ClaudeAdapter.test.ts` covering:
1. session start
2. event mapping
3. approval bridge
4. resume cursor parse/serialize
5. interrupt behavior
6. rollback behavior or explicit unsupported error path
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
### 6.3 Provider service integration tests
Extend provider integration coverage so Claude is exercised through `ProviderService`:
1. start Claude session
2. send turn
3. receive canonical runtime events
4. restart/recover using persisted binding
### 6.4 Orchestration integration tests
Add/extend integration tests around:
1. first-turn provider selection
2. Claude approval requests routed through orchestration
3. Claude runtime ingestion -> messages/activities/session updates
4. checkpoint revert behavior under Claude
5. stopAll/restart recovery
These should validate real orchestration flows, not just adapter behavior.
---
## Phase 7: Rollout order
Recommended implementation order:
1. contracts/provider-aware models
2. provider field on turn-start
3. Claude adapter skeleton + start/send/stream
4. canonical event mapping
5. provider registry/service wiring
6. orchestration recovery + checkpoint strategy
7. web provider/model picker
8. full integration tests
---
## Non-goals
1. Reintroducing provider-specific WS methods/channels.
2. Storing provider-native thread ids as orchestration ids.
3. Bypassing orchestration engine for Claude-specific UI flows.
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
@@ -3,60 +3,81 @@
## Summary
Replace timing-sensitive websocket and orchestration behavior with explicit typed runtime boundaries, ordered push delivery, and server-owned completion receipts. The cutover is broad and single-shot: no compatibility shim, no mixed old/new transport. The design must reduce flakes without baking Codex-specific lifecycle semantics into generic runtime code.
## Implementation Status
All 7 sections are implemented. CI passes (format, lint, typecheck, test, browser test, build). One deferred item remains: the shared `WsTestClient` helper from section 7 — tests use direct transport subscription and receipt-based waits instead.
### New files
| File | Purpose |
|------|---------|
| `packages/shared/src/DrainableWorker.ts` | Queue-based Effect worker with deterministic `drain` signal |
| `packages/shared/src/schemaJson.ts` | Two-phase JSON→Schema decode helpers (`decodeJsonResult`, `formatSchemaError`) |
| `apps/server/src/wsServer/pushBus.ts` | `ServerPushBus` — ordered typed push pipeline with auto-incrementing sequence |
| `apps/server/src/wsServer/readiness.ts` | `ServerReadiness` — Deferred-based barriers for startup sequencing |
| `apps/server/src/orchestration/Services/RuntimeReceiptBus.ts` | Receipt schema union: checkpoint captured, diff finalized, turn quiesced |
| `apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts` | PubSub-backed receipt bus implementation |
| `apps/server/src/watchFileWithStatPolling.ts` | Stat-polling file watcher for containers where `fs.watch` is unreliable |
| `apps/server/vitest.config.ts` | Server-specific test config (timeout bumps) |
| `apps/server/src/wsServer/pushBus.test.ts` | Push bus serialization and welcome-gating tests |
| `packages/shared/src/DrainableWorker.test.ts` | Drainable worker enqueue/drain lifecycle tests |
### Key modifications
| File | Change |
|------|--------|
| `packages/contracts/src/ws.ts` | Channel-indexed `WsPushPayloadByChannel` map, `WsPush` union schema, `WsPushSequence` |
| `apps/server/src/wsServer.ts` | Integrated `ServerPushBus` and `ServerReadiness`; welcome gated on readiness |
| `apps/server/src/keybindings.ts` | Explicit runtime with `start`/`ready`/`snapshot`; dual `fs.watch` + stat-polling watcher |
| `apps/web/src/wsTransport.ts` | Connection state machine (`connecting`→`open`→`reconnecting`→`closed`→`disposed`); two-phase decode at boundary; cached latest push by channel |
| `apps/web/src/wsNativeApi.ts` | Removed decode logic; delegates to pre-validated transport messages |
| `apps/server/src/orchestration/Layers/CheckpointReactor.ts` | Uses `DrainableWorker`; publishes completion receipts |
| `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts` | Uses `DrainableWorker` for command processing |
| `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` | Uses `DrainableWorker` for event ingestion |
| `apps/server/integration/OrchestrationEngineHarness.integration.ts` | Receipt-based waits replace polling loops |
## Key Changes
### 1. Strengthen the generic boundaries, not the Codex boundary
- Keep `ProviderRuntimeEvent` as the canonical provider event contract and `ProviderService` as the only cross-provider facade.
- Do not expose raw Codex payloads or Codex event ordering outside `CodexAdapter.ts` and `codexAppServerManager.ts`.
- Do not expand `ProviderKind` in this change. The runtime stays provider-neutral by contract, while the product remains Codex-only in concrete support.
### 1. Strengthen the generic boundaries, not the Codex boundary — DONE
- `ProviderRuntimeEvent` remains the canonical provider event contract; `ProviderService` remains the only cross-provider facade.
- Raw Codex payloads and event ordering stay isolated in `CodexAdapter.ts` and `codexAppServerManager.ts`.
- `ProviderKind` was not expanded. The runtime stays provider-neutral by contract.
### 2. Replace loose websocket envelopes with channel-indexed typed pushes
- Refactor `packages/contracts/src/ws.ts` so push messages are derived from a channel-to-schema map instead of `channel: string` plus `data: unknown`.
- Add `sequence: number` to every server push. Ordering becomes explicit and testable.
- Add structured decode diagnostics with stable machine fields: `code`, `reason`, `expected`, `actual`, `path`, optional `jsonOffset`.
- Remove runtime/test dependence on engine-specific pretty strings. Human-readable formatting remains a logging helper only.
### 2. Replace loose websocket envelopes with channel-indexed typed pushes — DONE
- `packages/contracts/src/ws.ts` now derives push messages from a `WsPushPayloadByChannel` channel-to-schema map. `WsPush` is a union schema replacing `channel: string` + `data: unknown`.
- Every server push carries `sequence: number`, auto-incremented in `ServerPushBus`.
- `packages/shared/src/schemaJson.ts` provides structured decode diagnostics via `formatSchemaError`.
- `packages/contracts/src/ws.test.ts` covers typed push envelope validation and channel/payload mismatch rejection.
### 3. Introduce explicit server readiness and a single push pipeline
- Add a `ServerPushBus` service in `apps/server` backed by one ordered queue/pubsub path. All pushes go through it: `server.welcome`, `server.configUpdated`, terminal events, orchestration domain events.
- Add a `ServerReadiness` service with explicit barriers for:
- HTTP listening
- push bus ready
- keybindings runtime ready
- terminal subscriptions ready
- orchestration subscriptions ready
- Strengthen `server.welcome` semantics: it is emitted only after connection-scoped and server-scoped readiness is complete.
- `wsServer` should never publish directly from ad hoc background streams once the bus exists.
### 3. Introduce explicit server readiness and a single push pipeline — DONE
- `apps/server/src/wsServer/pushBus.ts`: `ServerPushBus` with `publishAll` (broadcast) and `publishClient` (targeted) methods, backed by one ordered path. All pushes flow through it.
- `apps/server/src/wsServer/readiness.ts`: `ServerReadiness` with Deferred-based barriers for HTTP listening, push bus, keybindings, terminal subscriptions, and orchestration subscriptions.
- `server.welcome` is emitted only after connection-scoped and server-scoped readiness is complete.
- `wsServer.ts` no longer publishes directly from ad hoc background streams.
### 4. Turn background watchers into explicit runtimes
- Extract keybindings watching into a `KeybindingsRuntime` service with `start`, `ready`, `snapshot`, and `changes`.
- Initial config load, startup sync, cache warmup, and watcher attachment complete before `ready` resolves.
- Keep the real `fs.watch` adapter thin. Most behavior tests use a fake watch source and deterministic change stream.
### 4. Turn background watchers into explicit runtimes — DONE
- `apps/server/src/keybindings.ts` refactored as explicit `KeybindingsShape` service with `start`, `ready`, `snapshot` semantics.
- Initial config load, cache warmup, and dual watcher attachment (`fs.watch` + `watchFileWithStatPolling`) complete before `ready` resolves.
- `watchFileWithStatPolling.ts` is the thin adapter for environments where `fs.watch` is unreliable.
### 5. Replace polling-based orchestration waiting with receipts
- Add server-owned completion receipts for operations that tests currently infer by polling:
- checkpoint capture complete
- checkpoint diff finalized
- turn processing quiesced
- A receipt means append, projection, and required side effects are complete. It must not mean the provider emitted a certain event sequence.
- Update the orchestration harness and checkpoint tests to await receipts/barriers instead of polling snapshots and git refs.
### 5. Replace polling-based orchestration waiting with receipts — DONE
- `RuntimeReceiptBus` service defines three receipt types: `CheckpointBaselineCapturedReceipt`, `CheckpointDiffFinalizedReceipt` (with `status: "ready"|"missing"|"error"`), and `TurnProcessingQuiescedReceipt`.
- `CheckpointReactor`, `ProviderCommandReactor`, and `ProviderRuntimeIngestion` use `DrainableWorker` and publish receipts on completion.
- Integration harness and checkpoint tests await receipts instead of polling snapshots and git refs.
### 6. Centralize client transport state and decoding
- Refactor `apps/web/src/wsTransport.ts` into an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
- Decode and validate typed push payloads at the transport boundary, not downstream in `apps/web/src/wsNativeApi.ts`.
- Keep cached latest welcome/config behavior only if it is modeled as explicit state, not as a late-subscriber race workaround.
### 6. Centralize client transport state and decoding — DONE
- `apps/web/src/wsTransport.ts` implements an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
- Two-phase decode (JSON parse → Schema validate) happens at the transport boundary. `wsNativeApi.ts` receives pre-validated messages.
- Cached latest welcome/config modeled as explicit `latestPushByChannel` state.
### 7. Replace ad hoc test helpers with semantic test clients
- Add a shared `WsTestClient` for server/websocket tests:
- connect
- await semantic welcome
- await typed push by channel and optional predicate
- track `sequence`
- match RPC responses by id
- Add one orchestration test harness that waits on receipts/barriers instead of custom `waitForThread`, `waitForGitRef`, and arbitrary retry loops.
- Keep only a narrow set of integration tests for real filesystem/watch/socket behavior. Move behavioral assertions to deterministic unit-style harnesses.
### 7. Replace ad hoc test helpers with semantic test clients — MOSTLY DONE
- `DrainableWorker` replaces timing-sensitive `Effect.sleep` with deterministic `drain()` across reactor tests.
- Orchestration harness waits on receipts/barriers instead of `waitForThread`, `waitForGitRef`, and retry loops.
- Behavioral assertions moved to deterministic unit-style harnesses; narrow integration tests kept for real filesystem/socket behavior.
- **Deferred:** Shared `WsTestClient` helper (connect, awaitSemanticWelcome, awaitTypedPush, trackSequence, matchRpcResponseById). Tests use direct transport subscription instead.
## Provider-Coupling Guardrails
- No generic runtime API may depend on Codex-native event names, thread IDs, or request payload shapes.
- No readiness barrier may be defined as “Codex has emitted X.” Readiness is owned by the server runtime, not by provider event order.
- No readiness barrier may be defined as "Codex has emitted X." Readiness is owned by the server runtime, not by provider event order.
- No websocket channel payload may contain raw provider-native payloads unless the channel is explicitly debug/internal.
- Any provider-specific divergence must be exposed through provider capabilities from `ProviderService.getCapabilities()`, not `if provider === "codex"` branches in shared runtime code.
- Generic tests must use canonical `ProviderRuntimeEvent` fixtures. Codex-specific ordering and translation tests stay in adapter/app-server suites only.
+51
View File
@@ -3,13 +3,16 @@
Goal: Align the orchestration model to `SPEC.md` 1:1 and remove legacy persistence/application cruft.
Execution mode for this plan:
- Hard cutover only. Existing DB and migration history are disposable.
- Intermediate steps are allowed to break runtime, tests, typecheck, and lint.
- We optimize for small, reviewable work units, not continuous app operability.
- Only the final gate requires everything to run cleanly.
## 1. Freeze SPEC contract as source of truth
Work units:
- Create `.plans/spec-contract-matrix.md` with one row per requirement in `SPEC.md` sections `7.1`-`7.4`.
- Add exact SQL-level requirements per row: table, column, type, nullability, PK/unique, index, and invariants.
- Add app-level requirements per row: writer path, reader path, and owning module.
@@ -17,17 +20,22 @@ Work units:
- Identify any ambiguous spec lines and record a concrete interpretation in the matrix.
Deliverables:
- Complete matrix file with no unclassified rows.
- Single source checklist used by all later steps.
Breakage allowed:
- No code changes required yet.
Exit criteria:
- Every requirement in `7.1`-`7.4` has exactly one matrix row.
## 2. Hard cutover migrations (replace current migration set)
Work units:
- Delete the current legacy migration files and rewrite migration loader ordering.
- Create `001_orchestration_events.ts` with full envelope columns and required event indexes.
- Create `002_orchestration_command_receipts.ts` with PK + lookup indexes.
@@ -47,17 +55,22 @@ Work units:
- Ensure old tables (`projects`, `provider_checkpoints`, `provider_sessions`) are not recreated.
Deliverables:
- New 5-file migration chain.
- Updated migration loader references only new migrations.
Breakage allowed:
- Repositories/services can be temporarily broken due to removed old tables.
Exit criteria:
- Fresh DB initializes with only canonical tables plus migration bookkeeping.
## 3. Align persistence row/request schemas to DB 1:1
Work units:
- Define row schemas for each canonical table (contracts or persistence layer module).
- Define request schemas for every insert/update/query operation touching canonical tables.
- Remove or deprecate row/request schemas tied to deleted legacy tables.
@@ -65,17 +78,22 @@ Work units:
- Ensure SQL aliases map 1:1 to schema field names (no implicit shape transforms).
Deliverables:
- Canonical row/request schemas committed.
- Zero references to legacy row schemas in active code paths.
Breakage allowed:
- Runtime can still fail while query layers are being rewired.
Exit criteria:
- Every canonical table used in code has a typed row schema and typed request schema.
## 4. Rewrite event store for full persisted envelope
Work units:
- Refactor append path to write full envelope fields:
- `event_id`, `aggregate_kind`, `stream_id`, `stream_version`, `event_type`, `occurred_at`, `command_id`, `causation_event_id`, `correlation_id`, `actor_kind`, `payload_json`, `metadata_json`
- Implement stream version assignment/checking per aggregate stream.
@@ -84,16 +102,21 @@ Work units:
- Add explicit SQL ordering guarantees for replay (`ORDER BY sequence ASC`).
Deliverables:
- Event store append/replay fully aligned with canonical envelope.
Breakage allowed:
- Command dispatch flow can be partially broken until receipts/projectors are updated.
Exit criteria:
- Event store no longer depends on legacy event table shape.
## 5. Add command receipt idempotency
Work units:
- Introduce persistence access layer for `orchestration_command_receipts`.
- In command dispatch flow, check existing receipt by `commandId` before append.
- On first execution, persist accepted receipt with `resultSequence`.
@@ -102,16 +125,21 @@ Work units:
- Ensure receipt write and event append ordering is deterministic.
Deliverables:
- Dispatch path with idempotency behavior wired through receipts.
Breakage allowed:
- Snapshot/read model may still be inconsistent until projectors are fully wired.
Exit criteria:
- Duplicate command IDs no longer create duplicate events.
## 6. Build DB-backed projection pipeline
Work units:
- Create projector runner that consumes events and applies table-specific projections.
- Implement projector handlers for each projection table.
- For each handler, update target row(s) and `projection_state.last_applied_sequence` in the same transaction.
@@ -120,16 +148,21 @@ Work units:
- Add safe resume logic from projector `last_applied_sequence`.
Deliverables:
- Persistent projector pipeline writing all `projection_*` tables.
Breakage allowed:
- Web/API layer may still read old in-memory model until step 7.
Exit criteria:
- Events drive projection rows in DB; projection state advances transactionally.
## 7. Move RPC reads to projections and diff blobs
Work units:
- Implement snapshot query service reading only projection tables.
- Build thread hydration from projection rows: messages, activities, checkpoints, session.
- Compute `snapshotSequence` as the minimum required projector sequence from `projection_state`.
@@ -138,16 +171,21 @@ Work units:
- Validate replay handoff contract: snapshot sequence -> replay from `fromSequenceExclusive`.
Deliverables:
- `orchestration.getSnapshot` and `orchestration.getTurnDiff` served from DB projections/blob store.
Breakage allowed:
- Provider runtime persistence may still be partially legacy until step 8.
Exit criteria:
- No orchestration read RPC depends on legacy tables or in-memory-only state.
## 8. Migrate provider runtime persistence to canonical table
Work units:
- Create repository/service for `provider_session_runtime`.
- Update adapter/session manager to persist runtime/resume cursor in new table.
- Ensure domain-visible session state still flows through orchestration events to `projection_thread_sessions`.
@@ -155,16 +193,21 @@ Work units:
- Verify restart/resume path reads runtime state from canonical table only.
Deliverables:
- Provider runtime state entirely backed by `provider_session_runtime`.
Breakage allowed:
- Some legacy interfaces may still exist but should be disconnected.
Exit criteria:
- Runtime restore no longer reads/writes legacy provider session persistence.
## 9. Remove old cruft aggressively
Work units:
- Delete legacy repositories/services that map to removed tables.
- Remove dead migration imports and obsolete persistence service interfaces.
- Remove compatibility code paths that translate legacy row shapes.
@@ -172,16 +215,21 @@ Work units:
- Update internal docs/comments to reference canonical projection/event model only.
Deliverables:
- Legacy persistence and translation layers removed from active codebase.
Breakage allowed:
- Temporary compile failures acceptable while deletion/refactor is in progress.
Exit criteria:
- No production code path references deleted legacy tables/services.
## 10. Final verification gate (first point where green is required)
Work units:
- Add migration tests that assert canonical tables, columns, constraints, and indexes.
- Add event store tests for envelope persistence, metadata, actor kind, and replay.
- Add receipt idempotency tests for accept/reject/duplicate paths.
@@ -192,10 +240,13 @@ Work units:
- Run project lint/typecheck/tests and fix failures.
Deliverables:
- Green checks with canonical schema + persistence model in place.
Breakage allowed:
- None at end of step.
Exit criteria:
- SPEC `7.1`-`7.4` requirements satisfied and validated by tests.
+32
View File
@@ -1,6 +1,7 @@
# SPEC Contract Matrix (Sections 7.1-7.4)
Status legend:
- `required`: requirement acknowledged, no current implementation claim yet.
- `implemented`: requirement currently satisfied in code + schema.
- `to-replace`: partial/misaligned implementation exists and must be replaced.
@@ -9,6 +10,7 @@ Status legend:
## 7.1 Write-Side Persisted Tables
### W1
- Spec ref: `7.1.1 orchestration_events`
- Requirement: append-only event store with canonical envelope columns.
- SQL contract:
@@ -32,6 +34,7 @@ Status legend:
- Notes: current migration/table lacks `stream_id`, `stream_version`, `causation_event_id`, `correlation_id`, `actor_kind`, `metadata_json`.
### W2
- Spec ref: `7.1.2 orchestration_command_receipts`
- Requirement: command idempotency + ack replay receipts table.
- SQL contract:
@@ -49,6 +52,7 @@ Status legend:
- Notes: missing table and missing idempotency flow.
### W3
- Spec ref: `7.1.3 checkpoint_diff_blobs`
- Requirement: store large plaintext diffs separate from checkpoint summaries.
- SQL contract:
@@ -65,6 +69,7 @@ Status legend:
- Notes: no canonical diff blob table yet.
### W4
- Spec ref: `7.1.4 provider_session_runtime`
- Requirement: server-internal provider runtime/resume state.
- SQL contract:
@@ -86,6 +91,7 @@ Status legend:
## 7.2 Canonical Persisted Event Schema
### E1
- Spec ref: `7.2 OrchestrationPersistedEventSchema`
- Requirement: full typed persisted event envelope in shared contracts.
- SQL contract: envelope fields in W1 must map 1:1 to contracts schema.
@@ -96,6 +102,7 @@ Status legend:
- Notes: contract schema exists; DB + store mapping still incomplete.
### E2
- Spec ref: `7.2 Rules/payload discriminated by eventType`
- Requirement: `payload` validation keyed by `eventType`.
- SQL contract: `event_type` drives payload decode schema; invalid combinations rejected.
@@ -106,6 +113,7 @@ Status legend:
- Notes: decode is present but DB does not persist full envelope columns.
### E3
- Spec ref: `7.2 Rules/provider ids scope`
- Requirement: provider ids live in metadata/provider payload, not as thread identity replacement.
- SQL contract: provider fields persisted inside `metadata_json`; `stream_id` remains project/thread id.
@@ -116,6 +124,7 @@ Status legend:
- Notes: metadata plumbing is incomplete in persistence path.
### E4
- Spec ref: `7.2 Rules/streamVersion concurrency guard`
- Requirement: stream version monotonic per aggregate stream; enforced on write.
- SQL contract: `stream_version INTEGER NOT NULL` + uniqueness/invariant enforcement per stream.
@@ -128,6 +137,7 @@ Status legend:
## 7.3 Required Projected Tables (Read Models)
### P1
- Spec ref: `7.3.1 projection_projects`
- Requirement: persisted project projection table.
- SQL contract:
@@ -145,6 +155,7 @@ Status legend:
- Notes: legacy `projects` table is separate concept and should be removed from orchestration model.
### P2
- Spec ref: `7.3.2 projection_threads`
- Requirement: persisted thread projection table.
- SQL contract:
@@ -165,6 +176,7 @@ Status legend:
- Notes: missing table and projector writes.
### P3
- Spec ref: `7.3.3 projection_thread_messages`
- Requirement: persisted thread message projection table.
- SQL contract:
@@ -183,6 +195,7 @@ Status legend:
- Notes: missing table and message projection writes.
### P4
- Spec ref: `7.3.4 projection_thread_activities`
- Requirement: persisted thread activity projection table.
- SQL contract:
@@ -201,6 +214,7 @@ Status legend:
- Notes: no canonical activity projection persistence.
### P5
- Spec ref: `7.3.5 projection_thread_sessions`
- Requirement: persisted thread session projection table.
- SQL contract:
@@ -219,6 +233,7 @@ Status legend:
- Notes: current provider session table is not this domain projection.
### P6
- Spec ref: `7.3.6 projection_thread_turns`
- Requirement: persisted thread turn projection table.
- SQL contract:
@@ -237,6 +252,7 @@ Status legend:
- Notes: missing table and projection logic.
### P7
- Spec ref: `7.3.7 projection_checkpoints`
- Requirement: persisted checkpoint summary projection table.
- SQL contract:
@@ -256,6 +272,7 @@ Status legend:
- Notes: current table semantics do not match canonical checkpoint projection schema.
### P8
- Spec ref: `7.3.8 projection_pending_approvals`
- Requirement: persisted pending-approval projection table.
- SQL contract:
@@ -273,6 +290,7 @@ Status legend:
- Notes: missing table and projection logic.
### P9
- Spec ref: `7.3.9 projection_state`
- Requirement: projector progress tracking table.
- SQL contract:
@@ -286,6 +304,7 @@ Status legend:
- Notes: missing table and projector bookkeeping.
### P10
- Spec ref: `7.3 Projection consistency rules`
- Requirement: projector row updates and `projection_state` update must be atomic per event.
- SQL contract: per-projector transaction boundary covering both projection write and state update.
@@ -296,6 +315,7 @@ Status legend:
- Notes: requires transactional projection executor.
### P11
- Spec ref: `7.3 Optional debug field`
- Requirement: `lastEventSequence` on projection rows is optional and not required for correctness.
- SQL contract: optional; not required in baseline schema.
@@ -308,6 +328,7 @@ Status legend:
## 7.4 Snapshot and RPC Requirements
### R1
- Spec ref: `7.4.1`
- Requirement: `orchestration.getSnapshot` fully served from projection tables and returns `snapshotSequence`.
- SQL contract: snapshot query joins/reads only `projection_*` + `projection_state`.
@@ -318,6 +339,7 @@ Status legend:
- Notes: current in-memory read model path must be removed for SPEC compliance.
### R2
- Spec ref: `7.4.2`
- Requirement: snapshot `projects[]` source is `projection_projects`.
- SQL contract: `projects` collection assembled from `projection_projects` rows.
@@ -328,6 +350,7 @@ Status legend:
- Notes: no DB project projection reader exists yet.
### R3
- Spec ref: `7.4.3`
- Requirement: thread snapshot `checkpoints[]` source is `projection_checkpoints` with required fields.
- SQL contract: fields `turnId`, `completedAt`, `status`, `files[]`, `checkpointRef`, optional `assistantMessageId`, `checkpointTurnCount`.
@@ -338,6 +361,7 @@ Status legend:
- Notes: canonical projection table and reader not implemented.
### R4
- Spec ref: `7.4.4`
- Requirement: no `listCheckpoints` orchestration RPC; list in snapshot + full diff via `getTurnDiff` from diff blobs.
- SQL contract: `getTurnDiff` reads `checkpoint_diff_blobs` only.
@@ -348,6 +372,7 @@ Status legend:
- Notes: current checkpoint repository is not canonical source.
### R5
- Spec ref: `7.4.5`
- Requirement: client acts on `ThreadId`; server resolves provider session via `projection_thread_sessions`.
- SQL contract: session lookup by `thread_id` from projection table.
@@ -358,6 +383,7 @@ Status legend:
- Notes: remove provider-session-as-routing-key behavior.
### R6
- Spec ref: `7.4.6`
- Requirement: `snapshotSequence` derived from `projection_state` minimum over dependent projectors.
- SQL contract: `MIN(last_applied_sequence)` across required projector keys.
@@ -368,6 +394,7 @@ Status legend:
- Notes: must move from in-memory sequence to DB projection-state semantics.
### R7
- Spec ref: `7.4.7`
- Requirement: snapshot/replay handoff has no gap (`getSnapshot` -> subscribe from snapshot sequence).
- SQL contract: read consistency strategy guaranteeing no missing events between snapshot visibility and replay start.
@@ -380,22 +407,27 @@ Status legend:
## Ambiguous/Interpretation Decisions (tracked upfront)
### A1
- Topic: `orchestration_events.stream_id` vs event runtime `aggregateId` naming.
- Decision: persist canonical DB column name `stream_id`; map to runtime `aggregateId` where needed in decider/projector code.
### A2
- Topic: JSON column typing in SQLite for `payload`, `metadata`, projection payload/files, runtime cursor/payload.
- Decision: store as `TEXT` JSON with strict encode/decode schemas at boundaries.
### A3
- Topic: `snapshotSequence` dependency set for min-sequence computation.
- Decision: include all projectors used to construct snapshot payload (`projects`, `threads`, `messages`, `activities`, `sessions`, `turns`, `checkpoints`, `pending_approvals`).
### A4
- Topic: no-gap handoff mechanism in `7.4.7`.
- Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`.
## Checklist Completeness Statement
- Coverage scope: `SPEC.md` sections `7.1`, `7.2`, `7.3`, `7.4`.
- Requirement rows present: `W1-W4`, `E1-E4`, `P1-P11`, `R1-R7`.
- Unclassified rows: `0`.
+3 -3
View File
@@ -2,12 +2,12 @@
## Task Completion Requirements
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
## Project Snapshot
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
@@ -21,7 +21,7 @@ If a tradeoff is required, choose correctness and robustness over short-term con
## 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.
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
## Package Roles
+1 -1
View File
@@ -1 +1 @@
AGENTS.md
AGENTS.md
+1 -1
View File
@@ -8,7 +8,7 @@ You can still open an issue or PR, but please do so knowing there is a high chan
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
PRs are automatically labeled with a `vouch:*` trust status.
PRs are automatically labeled with a `vouch:*` trust status and a `size:*` diff size based on changed lines.
If you are an external contributor, expect `vouch:unvouched` until we explicitly add you to [.github/VOUCHED.td](.github/VOUCHED.td).
+1 -1
View File
@@ -51,7 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
- `editor.openFavorite`: open current project/worktree in the last-used editor
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
+1 -1
View File
@@ -1,6 +1,6 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
## How to use
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.9",
"version": "0.0.10",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+18 -9
View File
@@ -7,7 +7,11 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
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 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"]) },
@@ -76,12 +80,13 @@ function startApp() {
}
});
app.once("exit", () => {
app.once("exit", (code, signal) => {
if (currentApp === app) {
currentApp = null;
}
if (!shuttingDown && !expectedExits.has(app)) {
const exitedAbnormally = signal !== null || code !== 0;
if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
scheduleRestart();
}
});
@@ -148,13 +153,17 @@ function scheduleRestart() {
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;
}
const watcher = watch(
join(desktopDir, directory),
{ persistent: true },
(_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
return;
}
scheduleRestart();
});
scheduleRestart();
},
);
watchers.push(watcher);
}
-15
View File
@@ -1,15 +0,0 @@
import { readPathFromLoginShell } from "@t3tools/shared/shell";
export function fixPath(): void {
if (process.platform !== "darwin") return;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = readPathFromLoginShell(shell);
if (result) {
process.env.PATH = result;
}
} catch {
// Keep inherited PATH if shell lookup fails.
}
}
+87 -15
View File
@@ -4,21 +4,32 @@ import * as FS from "node:fs";
import * as OS from "node:os";
import * as Path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, shell } from "electron";
import {
app,
BrowserWindow,
dialog,
ipcMain,
Menu,
nativeImage,
nativeTheme,
protocol,
shell,
} from "electron";
import type { MenuItemConstructorOptions } from "electron";
import * as Effect from "effect/Effect";
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
import type {
DesktopTheme,
DesktopUpdateActionResult,
DesktopUpdateState,
} from "@t3tools/contracts";
import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
import {
getAutoUpdateDisabledReason,
shouldBroadcastDownloadProgress,
} from "./updateState";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
@@ -33,10 +44,11 @@ import {
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
fixPath();
syncShellEnvironment();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
@@ -140,6 +152,14 @@ function getSafeExternalUrl(rawUrl: unknown): string | null {
return parsedUrl.toString();
}
function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
if (rawTheme === "light" || rawTheme === "dark" || rawTheme === "system") {
return rawTheme;
}
return null;
}
function writeDesktopStreamChunk(
streamName: "stdout" | "stderr",
chunk: unknown,
@@ -515,7 +535,28 @@ function handleCheckForUpdatesMenuClick(): void {
if (!BrowserWindow.getAllWindows().length) {
mainWindow = createWindow();
}
void checkForUpdates("menu");
void checkForUpdatesFromMenu();
}
async function checkForUpdatesFromMenu(): Promise<void> {
await checkForUpdates("menu");
if (updateState.status === "up-to-date") {
void dialog.showMessageBox({
type: "info",
title: "You're up to date!",
message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
buttons: ["OK"],
});
} else if (updateState.status === "error") {
void dialog.showMessageBox({
type: "warning",
title: "Update check failed",
message: "Could not check for updates.",
detail: updateState.message ?? "An unknown error occurred. Please try again later.",
buttons: ["OK"],
});
}
}
function configureApplicationMenu(): void {
@@ -566,7 +607,21 @@ function configureApplicationMenu(): void {
],
},
{ role: "editMenu" },
{ role: "viewMenu" },
{
label: "View",
submenu: [
{ role: "reload" },
{ role: "forceReload" },
{ role: "toggleDevTools" },
{ type: "separator" },
{ role: "resetZoom" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
],
},
{ role: "windowMenu" },
{
role: "help",
@@ -585,6 +640,7 @@ function configureApplicationMenu(): void {
function resolveResourcePath(fileName: string): string | null {
const candidates = [
Path.join(__dirname, "../resources", fileName),
Path.join(__dirname, "../prod-resources", fileName),
Path.join(process.resourcesPath, "resources", fileName),
Path.join(process.resourcesPath, fileName),
];
@@ -702,7 +758,9 @@ async function checkForUpdates(reason: string): Promise<void> {
await autoUpdater.checkForUpdates();
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
setUpdateState(reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()));
setUpdateState(
reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
);
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
} finally {
updateCheckInFlight = false;
@@ -764,9 +822,7 @@ function configureAutoUpdater(): void {
updaterConfigured = true;
const githubToken =
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() ||
process.env.GH_TOKEN?.trim() ||
"";
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
if (githubToken) {
// When a token is provided, re-configure the feed with `private: true` so
// electron-updater uses the GitHub API (api.github.com) instead of the
@@ -801,7 +857,13 @@ function configureAutoUpdater(): void {
console.info("[desktop-updater] Looking for updates...");
});
autoUpdater.on("update-available", (info) => {
setUpdateState(reduceDesktopUpdateStateOnUpdateAvailable(updateState, info.version, new Date().toISOString()));
setUpdateState(
reduceDesktopUpdateStateOnUpdateAvailable(
updateState,
info.version,
new Date().toISOString(),
),
);
lastLoggedDownloadMilestone = -1;
console.info(`[desktop-updater] Update available: ${info.version}`);
});
@@ -1034,6 +1096,16 @@ function registerIpcHandlers(): void {
return showDesktopConfirmDialog(message, owner);
});
ipcMain.removeHandler(SET_THEME_CHANNEL);
ipcMain.handle(SET_THEME_CHANNEL, async (_event, rawTheme: unknown) => {
const theme = getSafeTheme(rawTheme);
if (!theme) {
return;
}
nativeTheme.themeSource = theme;
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
+2
View File
@@ -3,6 +3,7 @@ import type { DesktopBridge } from "@t3tools/contracts";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
@@ -16,6 +17,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => {
+1 -2
View File
@@ -25,8 +25,7 @@ export function resolveDesktopRuntimeInfo(
};
}
const hostArch =
appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
const hostArch = appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
return {
hostArch,
@@ -0,0 +1,85 @@
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment";
describe("syncShellEnvironment", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("preserves an inherited SSH_AUTH_SOCK value", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/login-shell.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("preserves inherited values when the login shell omits them", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("does nothing outside macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "linux",
readEnvironment,
});
expect(readEnvironment).not.toHaveBeenCalled();
expect(env.PATH).toBe("/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
});
+29
View File
@@ -0,0 +1,29 @@
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
export function syncShellEnvironment(
env: NodeJS.ProcessEnv = process.env,
options: {
platform?: NodeJS.Platform;
readEnvironment?: ShellEnvironmentReader;
} = {},
): void {
if ((options.platform ?? process.platform) !== "darwin") return;
try {
const shell = env.SHELL ?? "/bin/zsh";
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
"PATH",
"SSH_AUTH_SOCK",
]);
if (shellEnvironment.PATH) {
env.PATH = shellEnvironment.PATH;
}
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
} catch {
// Keep inherited environment if shell lookup fails.
}
}
+4 -1
View File
@@ -83,7 +83,10 @@ describe("updateMachine", () => {
},
"1.1.0",
);
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(
downloaded,
"backend shutdown timed out",
);
expect(downloaded.status).toBe("downloaded");
expect(downloaded.downloadedVersion).toBe("1.1.0");
+2 -2
View File
@@ -10,10 +10,10 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^5.7.13"
"astro": "^6.0.4"
},
"devDependencies": {
"@astrojs/check": "^0.9.4",
"@astrojs/check": "^0.9.7",
"typescript": "catalog:"
}
}
+228
View File
@@ -0,0 +1,228 @@
---
interface Props {
title?: string;
description?: string;
}
const {
title = "T3 Code",
description = "T3 Code — The best way to code with AI.",
} = Astro.props;
---
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content={description} />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>{title}</title>
</head>
<body>
<div class="page">
<nav class="nav">
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
</nav>
<main class="main">
<slot />
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
</div>
</footer>
</div>
</body>
</html>
<style is:global>
:root {
--bg: #09090b;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--border: rgba(255, 255, 255, 0.08);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
color-scheme: dark;
}
body {
background: var(--bg);
color: var(--fg);
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
opacity: 0.035;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px 256px;
z-index: 9999;
}
a {
color: inherit;
text-decoration: none;
}
img {
display: block;
max-width: 100%;
}
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
<style>
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
}
.nav-brand {
display: flex;
align-items: center;
}
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-github {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--fg-muted);
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-github:hover {
color: var(--fg);
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
}
/* ── Main content ── */
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
/* ── Footer ── */
.footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
color: var(--fg-dim);
}
.footer-links {
display: flex;
gap: 1.25rem;
}
.footer-links a {
color: var(--fg-dim);
transition: color 0.3s ease;
}
.footer-links a:hover {
color: var(--fg);
}
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem;
}
.footer {
padding: 1.25rem;
}
}
</style>
+30
View File
@@ -0,0 +1,30 @@
const REPO = "pingdotgg/t3code";
export const RELEASES_URL = `https://github.com/${REPO}/releases`;
const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
const CACHE_KEY = "t3code-latest-release";
export interface ReleaseAsset {
name: string;
browser_download_url: string;
}
export interface Release {
tag_name: string;
html_url: string;
assets: ReleaseAsset[];
}
export async function fetchLatestRelease(): Promise<Release> {
const cached = sessionStorage.getItem(CACHE_KEY);
if (cached) return JSON.parse(cached);
const data = await fetch(API_URL).then((r) => r.json());
if (data?.assets) {
sessionStorage.setItem(CACHE_KEY, JSON.stringify(data));
}
return data;
}
+271
View File
@@ -0,0 +1,271 @@
---
import Layout from "../layouts/Layout.astro";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
<h1 class="heading">Download T3 Code</h1>
<p class="subheading">
<span id="version-label">Loading latest release&hellip;</span>
<a id="changelog-link" class="changelog-link" href="#" target="_blank" rel="noopener noreferrer" style="display:none">View changelog<span aria-hidden="true"> &#8599;</span></a>
</p>
<div class="platforms" id="platforms">
<!-- macOS -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<h2 class="platform-name">macOS</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="arm64.dmg" href="#">
<span class="card-arch">Apple Silicon (arm64)</span>
<span class="card-format">.dmg</span>
</a>
<a class="download-card" data-asset="x64.dmg" href="#">
<span class="card-arch">Intel (x64)</span>
<span class="card-format">.dmg</span>
</a>
</div>
</section>
<!-- Windows -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<h2 class="platform-name">Windows</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x64.exe" href="#">
<span class="card-arch">Windows 10, 11</span>
<span class="card-format">.exe</span>
</a>
</div>
</section>
<!-- Linux -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x86_64.AppImage" href="#">
<span class="card-arch">x86_64</span>
<span class="card-format">AppImage</span>
</a>
</div>
</section>
</div>
<p class="releases-link">
Looking for older versions? Check the
<a href="https://github.com/pingdotgg/t3code/releases" target="_blank" rel="noopener noreferrer">
GitHub releases page<span aria-hidden="true"> &#8599;</span>
</a>
</p>
</Layout>
<script>
import { fetchLatestRelease, RELEASES_URL } from "../lib/releases";
async function init() {
const versionLabel = document.getElementById("version-label");
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card");
try {
const release = await fetchLatestRelease();
if (versionLabel && release.tag_name) {
versionLabel.textContent = `Latest (${release.tag_name})`;
}
const changelogLink = document.getElementById("changelog-link") as HTMLAnchorElement | null;
if (changelogLink && release.html_url) {
changelogLink.href = release.html_url;
changelogLink.style.display = "";
}
cards.forEach((card) => {
const suffix = card.dataset.asset;
if (!suffix) return;
const match = (release.assets ?? []).find((a) => a.name.endsWith(`-${suffix}`));
if (match) {
card.href = match.browser_download_url;
} else {
card.href = RELEASES_URL;
}
});
} catch {
if (versionLabel) {
versionLabel.textContent = "Could not load release info.";
}
cards.forEach((card) => {
card.href = RELEASES_URL;
});
}
}
init();
</script>
<style>
.main {
padding: 8vh 1.5rem 4rem;
}
/* ── Heading ── */
.heading {
font-weight: 500;
font-size: clamp(1.75rem, 4vw, 2.75rem);
letter-spacing: -0.035em;
line-height: 1.15;
text-align: center;
margin-bottom: 0.5rem;
opacity: 0;
animation: fade-in 1s ease-out forwards;
}
.subheading {
font-size: 0.9rem;
color: var(--fg-dim);
margin-bottom: 3.5rem;
opacity: 0;
animation: fade-in 1s ease-out 0.1s forwards;
display: flex;
align-items: center;
gap: 0.75rem;
}
.changelog-link {
color: var(--fg-muted);
font-size: 0.8rem;
text-decoration: underline;
text-decoration-color: rgba(161, 161, 170, 0.4);
text-underline-offset: 3px;
transition: color 0.3s ease, text-decoration-color 0.3s ease;
}
.changelog-link:hover {
color: var(--fg);
text-decoration-color: var(--fg);
}
/* ── Platforms ── */
.platforms {
width: 100%;
max-width: 720px;
display: flex;
flex-direction: column;
gap: 2.5rem;
opacity: 0;
animation: fade-in 1s ease-out 0.2s forwards;
}
.platform-section {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.platform-header {
display: flex;
align-items: center;
gap: 0.6rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid var(--border);
}
.platform-icon {
width: 1.15em;
height: 1.15em;
color: var(--fg-muted);
flex-shrink: 0;
}
.platform-name {
font-weight: 500;
font-size: 1.1rem;
letter-spacing: -0.01em;
}
/* ── Download cards ── */
.download-cards {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 0.5rem;
}
.download-card {
display: flex;
flex-direction: column;
gap: 0.2rem;
padding: 0.85rem 1rem;
border-radius: 10px;
border: 1px solid var(--border);
background: rgba(255, 255, 255, 0.02);
transition: background 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
}
.download-card:hover {
background: rgba(255, 255, 255, 0.06);
border-color: rgba(255, 255, 255, 0.15);
transform: translateY(-1px);
}
.download-card:active {
transform: translateY(0);
}
.card-arch {
font-weight: 600;
font-size: 0.95rem;
}
.card-format {
font-size: 0.8rem;
color: var(--fg-dim);
}
/* ── Releases link ── */
.releases-link {
margin-top: 3rem;
font-size: 0.825rem;
color: var(--fg-dim);
opacity: 0;
animation: fade-in 1s ease-out 0.35s forwards;
}
.releases-link a {
color: var(--fg-muted);
text-decoration: underline;
text-decoration-color: rgba(161, 161, 170, 0.4);
text-underline-offset: 3px;
transition: color 0.3s ease, text-decoration-color 0.3s ease;
}
.releases-link a:hover {
color: var(--fg);
text-decoration-color: var(--fg);
}
/* ── Mobile ── */
@media (max-width: 640px) {
.main {
padding: 5vh 1.25rem 4rem;
}
.platforms {
padding: 0 0.25rem;
}
.download-cards {
grid-template-columns: 1fr;
}
}
</style>
+42 -238
View File
@@ -1,75 +1,30 @@
---
import Layout from "../layouts/Layout.astro";
---
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="T3 Code — The best way to code with AI." />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>T3 Code</title>
</head>
<body>
<div class="page">
<nav class="nav">
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
</nav>
<Layout>
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<main class="main">
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<a
id="download-btn"
href="https://github.com/pingdotgg/t3code/releases"
class="hero-button"
>
<svg class="hero-button-icon hero-button-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="hero-button-icon hero-button-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<svg class="hero-button-icon hero-button-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<span id="download-label">Download now</span>
</a>
<a
id="download-btn"
href="https://github.com/pingdotgg/t3code/releases"
class="hero-button"
>
<svg class="hero-button-icon hero-button-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="hero-button-icon hero-button-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<svg class="hero-button-icon hero-button-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<span id="download-label">Download now</span>
</a>
<a href="/download" class="other-platforms">Other platforms</a>
<div class="screenshot-wrap">
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
</div>
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
</div>
</footer>
</div>
</body>
</html>
<div class="screenshot-wrap">
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
</div>
</Layout>
<script>
const REPO = "pingdotgg/t3code";
const RELEASES_URL = `https://github.com/${REPO}/releases`;
const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
import { fetchLatestRelease, RELEASES_URL, type ReleaseAsset } from "../lib/releases";
type Platform = { os: "mac" | "win" | "linux"; label: string; arch?: string };
@@ -87,10 +42,7 @@
return null;
}
function pickAsset(
assets: Array<{ name: string; browser_download_url: string }>,
platform: Platform,
): string | null {
function pickAsset(assets: ReleaseAsset[], platform: Platform): string | null {
if (platform.os === "win") {
return (
assets.find((a) => a.name.endsWith("-x64.exe"))
@@ -125,16 +77,8 @@
label.textContent = platform.label;
try {
const cached = sessionStorage.getItem("t3code-latest-release");
const data = cached
? JSON.parse(cached)
: await fetch(API_URL).then((r) => r.json());
if (!cached && data?.assets) {
sessionStorage.setItem("t3code-latest-release", JSON.stringify(data));
}
const url = pickAsset(data.assets ?? [], platform);
const release = await fetchLatestRelease();
const url = pickAsset(release.assets ?? [], platform);
if (url) {
btn.href = url;
btn.removeAttribute("target");
@@ -149,120 +93,7 @@
</script>
<style>
:root {
--bg: #09090b;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--border: rgba(255, 255, 255, 0.08);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
color-scheme: dark;
}
body {
background: var(--bg);
color: var(--fg);
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
opacity: 0.035;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px 256px;
z-index: 9999;
}
a {
color: inherit;
text-decoration: none;
}
img {
display: block;
max-width: 100%;
}
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
}
.nav-brand {
display: flex;
align-items: center;
}
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-github {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--fg-muted);
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-github:hover {
color: var(--fg);
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
}
/* ── Main content ── */
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding-top: 10vh;
}
@@ -291,7 +122,7 @@
border-radius: 999px;
font-weight: 600;
font-size: 0.9rem;
margin-bottom: 5vh;
margin-bottom: 1.25rem;
opacity: 0;
animation: fade-in 1s ease-out 0.15s forwards;
transition: transform 0.25s ease, box-shadow 0.25s ease;
@@ -325,6 +156,25 @@
display: block;
}
/* ── Other platforms link ── */
.other-platforms {
font-size: 0.825rem;
color: var(--fg-dim);
margin-bottom: 5vh;
opacity: 0;
animation: fade-in 1s ease-out 0.3s forwards;
transition: color 0.3s ease;
text-decoration: underline;
text-decoration-color: rgba(113, 113, 122, 0.4);
text-underline-offset: 3px;
}
.other-platforms:hover {
color: var(--fg-muted);
text-decoration-color: var(--fg-muted);
}
/* ── Screenshot ── */
.screenshot-wrap {
@@ -358,44 +208,6 @@
pointer-events: none;
}
/* ── Footer ── */
.footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
color: var(--fg-dim);
}
.footer-links {
display: flex;
gap: 1.25rem;
}
.footer-links a {
color: var(--fg-dim);
transition: color 0.3s ease;
}
.footer-links a:hover {
color: var(--fg);
}
/* ── Animations ── */
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes screenshot-in {
from {
opacity: 0;
@@ -410,10 +222,6 @@
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem 1.25rem;
}
.main {
padding-top: 7vh;
}
@@ -425,9 +233,5 @@
.screenshot-wrap {
width: 95vw;
}
.footer {
padding: 1.25rem;
}
}
</style>
@@ -6,6 +6,7 @@ import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
ProviderKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
@@ -205,7 +206,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: "codex";
readonly provider?: ProviderKind;
readonly realCodex?: boolean;
}
@@ -440,9 +441,7 @@ export const makeOrchestrationIntegrationHarness = (
return waitFor(
readMatchingReceipt,
(
receipt,
): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
(receipt): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
"runtime receipt",
timeoutMs,
);
@@ -10,6 +10,7 @@ import {
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderKind,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
@@ -35,7 +36,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex";
readonly provider: ProviderKind;
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -72,10 +73,9 @@ function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupt
return "completed";
}
function mapRequestType(requestKind: unknown):
| "command_execution_approval"
| "file_change_approval"
| "unknown" {
function mapRequestType(
requestKind: unknown,
): "command_execution_approval" | "file_change_approval" | "unknown" {
if (requestKind === "command") {
return "command_execution_approval";
}
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: "codex";
readonly provider: ProviderKind;
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: "codex";
readonly provider?: ProviderKind;
}
function nowIso(): string {
@@ -206,7 +206,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: "codex",
provider: ProviderKind,
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +216,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: "codex",
provider: ProviderKind,
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -239,323 +239,323 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
}>
>();
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== provider) {
return yield* new ProviderAdapterValidationError({
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== provider) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "startSession",
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
});
}
sessionCount += 1;
const threadId = input.threadId;
const createdAt = nowIso();
const session: ProviderSession = {
provider,
operation: "startSession",
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
});
}
sessionCount += 1;
const threadId = input.threadId;
const createdAt = nowIso();
const session: ProviderSession = {
provider,
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
cwd: input.cwd,
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
createdAt,
updatedAt: createdAt,
};
sessions.set(threadId, {
session,
snapshot: {
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
turns: [],
},
turnCount: 0,
queuedResponses: queuedResponsesForNextSession.splice(0),
rollbackCalls: [],
cwd: input.cwd,
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
createdAt,
updatedAt: createdAt,
};
sessions.set(threadId, {
session,
snapshot: {
threadId,
turns: [],
},
turnCount: 0,
queuedResponses: queuedResponsesForNextSession.splice(0),
rollbackCalls: [],
});
return session;
});
return session;
});
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
Effect.gen(function* () {
const state = sessions.get(input.threadId);
if (!state) {
return yield* missingSessionEffect(provider, input.threadId);
}
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
Effect.gen(function* () {
const state = sessions.get(input.threadId);
if (!state) {
return yield* missingSessionEffect(provider, input.threadId);
}
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
const response = state.queuedResponses.shift();
if (!response) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "sendTurn",
issue: `No queued turn response for thread ${input.threadId}.`,
});
}
const response = state.queuedResponses.shift();
if (!response) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "sendTurn",
issue: `No queued turn response for thread ${input.threadId}.`,
});
}
const assistantDeltas: string[] = [];
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: randomUUID(),
provider,
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
createdAt: nowIso(),
};
rawEvent.threadId = state.snapshot.threadId;
if (Object.hasOwn(rawEvent, "turnId")) {
rawEvent.turnId = turnId;
}
const assistantDeltas: string[] = [];
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: randomUUID(),
provider,
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
createdAt: nowIso(),
const runtimeEvent = normalizeFixtureEvent(rawEvent);
const runtimeType = (runtimeEvent as { type: string }).type;
if (runtimeType === "content.delta") {
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
if (typeof payload?.delta === "string") {
assistantDeltas.push(payload.delta);
}
} else if (runtimeType === "message.delta") {
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
if (typeof legacyDelta === "string") {
assistantDeltas.push(legacyDelta);
}
}
if (runtimeEvent.type === "turn.completed") {
deferredTurnCompletedEvents.push(runtimeEvent);
continue;
}
yield* emit(runtimeEvent);
}
if (response.mutateWorkspace && state.session.cwd) {
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
}
const userItem = {
type: "userMessage",
content: [{ type: "text", text: input.input }],
} as const;
const assistantText = assistantDeltas.join("");
const nextItems: Array<unknown> =
assistantText.length > 0
? [userItem, { type: "agentMessage", text: assistantText }]
: [userItem];
const nextTurn: ProviderThreadTurnSnapshot = {
id: turnId,
items: nextItems,
};
rawEvent.threadId = state.snapshot.threadId;
if (Object.hasOwn(rawEvent, "turnId")) {
rawEvent.turnId = turnId;
}
const runtimeEvent = normalizeFixtureEvent(rawEvent);
const runtimeType = (runtimeEvent as { type: string }).type;
if (runtimeType === "content.delta") {
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
if (typeof payload?.delta === "string") {
assistantDeltas.push(payload.delta);
}
} else if (runtimeType === "message.delta") {
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
if (typeof legacyDelta === "string") {
assistantDeltas.push(legacyDelta);
state.snapshot = {
threadId: state.snapshot.threadId,
turns: [...state.snapshot.turns, nextTurn],
};
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.makeUnsafe(randomUUID()),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
turnId,
payload: {
state: "completed",
},
});
} else {
for (const completedEvent of deferredTurnCompletedEvents) {
yield* emit(completedEvent);
}
}
if (runtimeEvent.type === "turn.completed") {
deferredTurnCompletedEvents.push(runtimeEvent);
continue;
}
yield* emit(runtimeEvent);
}
if (response.mutateWorkspace && state.session.cwd) {
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
}
const userItem = {
type: "userMessage",
content: [{ type: "text", text: input.input }],
} as const;
const assistantText = assistantDeltas.join("");
const nextItems: Array<unknown> =
assistantText.length > 0
? [userItem, { type: "agentMessage", text: assistantText }]
: [userItem];
const nextTurn: ProviderThreadTurnSnapshot = {
id: turnId,
items: nextItems,
};
state.snapshot = {
threadId: state.snapshot.threadId,
turns: [...state.snapshot.turns, nextTurn],
};
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.makeUnsafe(randomUUID()),
provider,
createdAt: nowIso(),
return {
threadId: state.snapshot.threadId,
turnId,
payload: {
state: "completed",
},
});
} else {
for (const completedEvent of deferredTurnCompletedEvents) {
yield* emit(completedEvent);
}
} satisfies ProviderTurnStartResult;
});
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
threadId,
turnId,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = interruptCallsBySession.get(threadId) ?? [];
existing.push(turnId);
interruptCallsBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = approvalResponsesBySession.get(threadId) ?? [];
existing.push({
threadId,
requestId,
decision,
});
approvalResponsesBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
threadId,
numTurns,
) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
return Effect.fail(
new ProviderAdapterValidationError({
provider,
operation: "rollbackThread",
issue: "numTurns must be an integer between 0 and current turn count.",
}),
);
}
return {
threadId: state.snapshot.threadId,
turnId,
} satisfies ProviderTurnStartResult;
});
return Effect.sync(() => {
state.rollbackCalls.push(numTurns);
state.snapshot = {
threadId: state.snapshot.threadId,
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
};
state.turnCount = state.snapshot.turns.length;
return state.snapshot;
});
};
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
threadId,
turnId,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = interruptCallsBySession.get(threadId) ?? [];
existing.push(turnId);
interruptCallsBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
Effect.sync(() => {
sessions.clear();
});
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = approvalResponsesBySession.get(threadId) ?? [];
existing.push({
threadId,
requestId,
decision,
});
approvalResponsesBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
threadId,
numTurns,
) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
return Effect.fail(
new ProviderAdapterValidationError({
provider,
operation: "rollbackThread",
issue: "numTurns must be an integer between 0 and current turn count.",
}),
const queueTurnResponse = (
threadId: ThreadId,
response: TestTurnResponse,
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
Effect.sync(() => sessions.get(threadId)).pipe(
Effect.flatMap((state) =>
state
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(provider, threadId)),
),
);
}
return Effect.sync(() => {
state.rollbackCalls.push(numTurns);
state.snapshot = {
threadId: state.snapshot.threadId,
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
};
state.turnCount = state.snapshot.turns.length;
return state.snapshot;
});
};
const queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
Effect.sync(() => {
sessions.clear();
});
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
const state = sessions.get(threadId);
if (!state) {
return [];
}
return [...state.rollbackCalls];
};
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const getStartCount = (): number => sessionCount;
const queueTurnResponse = (
threadId: ThreadId,
response: TestTurnResponse,
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
Effect.sync(() => sessions.get(threadId)).pipe(
Effect.flatMap((state) =>
state
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(provider, threadId)),
),
);
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
const calls = interruptCallsBySession.get(threadId);
if (!calls) {
return [];
}
return [...calls];
};
const queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
Array.from(sessions.values(), (state) => state.session.threadId);
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
const state = sessions.get(threadId);
if (!state) {
return [];
}
return [...state.rollbackCalls];
};
const getApprovalResponses = (
threadId: ThreadId,
): ReadonlyArray<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}> => {
const responses = approvalResponsesBySession.get(threadId);
if (!responses) {
return [];
}
return [...responses];
};
const getStartCount = (): number => sessionCount;
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
const calls = interruptCallsBySession.get(threadId);
if (!calls) {
return [];
}
return [...calls];
};
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
Array.from(sessions.values(), (state) => state.session.threadId);
const getApprovalResponses = (
threadId: ThreadId,
): ReadonlyArray<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}> => {
const responses = approvalResponsesBySession.get(threadId);
if (!responses) {
return [];
}
return [...responses];
};
return {
adapter,
provider,
queueTurnResponse,
queueTurnResponseForNextSession,
getStartCount,
getRollbackCalls,
getInterruptCalls,
listActiveSessionIds,
getApprovalResponses,
} satisfies TestProviderAdapterHarness;
});
return {
adapter,
provider,
queueTurnResponse,
queueTurnResponseForNextSession,
getStartCount,
getRollbackCalls,
getInterruptCalls,
listActiveSessionIds,
getApprovalResponses,
} satisfies TestProviderAdapterHarness;
});
@@ -73,7 +73,7 @@ export const codexTurnToolFixture = [
turnId: TURN_ID,
payload: {
itemType: "command_execution",
title: "Command run",
title: "Ran command",
detail: "echo integration",
},
},
@@ -85,7 +85,7 @@ export const codexTurnToolFixture = [
payload: {
itemType: "command_execution",
status: "completed",
title: "Command run",
title: "Ran command",
detail: "echo integration",
},
},
@@ -5,9 +5,11 @@ import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ProviderKind,
ThreadId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
@@ -36,7 +38,7 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = "codex";
type IntegrationProvider = ProviderKind;
function nowIso() {
return new Date().toISOString();
@@ -105,6 +107,8 @@ function withRealCodexHarness<A, E>(
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
const provider = harness.adapterHarness?.provider ?? "codex";
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
yield* harness.engine.dispatch({
type: "project.create",
@@ -112,7 +116,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModel: "gpt-5-codex",
defaultModel,
createdAt,
});
@@ -122,7 +126,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
model: "gpt-5-codex",
model: defaultModel,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -882,3 +886,420 @@ it.live(
}),
),
);
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Claude first turn.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-initial",
messageId: "msg-user-claude-initial",
text: "Use Claude",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.session.status === "ready" &&
entry.messages.some(
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
),
);
assert.equal(thread.session?.providerName, "claudeAgent");
}),
"claudeAgent",
),
);
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn before restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-1",
messageId: "msg-user-claude-recover-1",
text: "Before restart",
provider: "claudeAgent",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.adapter.stopAll();
yield* waitForSync(
() => harness.adapterHarness!.listActiveSessionIds(),
(sessionIds) => sessionIds.length === 0,
"provider stopAll",
);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn after restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-2",
messageId: "msg-user-claude-recover-2",
text: "After restart",
});
yield* waitForSync(
() => harness.adapterHarness!.getStartCount(),
(count) => count === 2,
"claude provider recovery start",
);
const recoveredThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.messages.some(
(message) => message.role === "user" && message.text === "After restart",
) &&
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
);
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeAgent",
),
);
it.live("forwards claudeAgent approval responses to the provider session", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
requestKind: "command",
detail: "Approve Claude tool call",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-approval",
messageId: "msg-user-claude-approval",
text: "Need approval",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some((activity) => activity.kind === "approval.requested"),
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
createdAt: nowIso(),
});
yield* harness.waitForPendingApproval(
"req-approval-1",
(row) => row.status === "resolved" && row.decision === "accept",
);
const approvalResponses = yield* waitForSync(
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
(responses) => responses.length === 1,
"claude provider approval response",
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
"claudeAgent",
),
);
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Long running output.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-interrupt",
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1",
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
threadId: THREAD_ID,
createdAt: nowIso(),
});
yield* harness.waitForDomainEvent(
(event) => event.type === "thread.turn-interrupt-requested",
);
const interruptCalls = yield* waitForSync(
() => harness.adapterHarness!.getInterruptCalls(THREAD_ID),
(calls) => calls.length === 1,
"claude provider interrupt call",
);
assert.equal(interruptCalls.length, 1);
}),
"claudeAgent",
),
);
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
provider: "claudeAgent",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeAgent",
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeAgent",
),
);
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.9",
"version": "0.0.10",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
@@ -22,6 +22,7 @@
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@pierre/diffs": "^1.1.0-beta.16",
@@ -44,6 +45,6 @@
"vitest": "catalog:"
},
"engines": {
"node": "^22.13 || ^23.4 || >=24.10"
"node": "^22.16 || ^23.11 || >=24.10"
}
}
+5 -4
View File
@@ -6,7 +6,10 @@ import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { DEVELOPMENT_ICON_OVERRIDES, PUBLISH_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts";
import {
DEVELOPMENT_ICON_OVERRIDES,
PUBLISH_ICON_OVERRIDES,
} from "../../../scripts/lib/brand-assets.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
@@ -237,9 +240,7 @@ const publishCmd = Command.make(
Effect.gen(function* () {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(
`[cli] Failed to restore publish icon overrides: ${String(error)}`,
),
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
),
);
yield* fs.rename(backupPath, packageJsonPath);
+1 -2
View File
@@ -12,8 +12,7 @@ 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_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",
@@ -62,6 +62,7 @@ function makeSnapshot(input: {
messages: [],
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [
{
turnId: TurnId.makeUnsafe("turn-1"),
+297 -66
View File
@@ -37,6 +37,8 @@ function createSendTurnHarness() {
planType: null,
sparkEnabled: true,
},
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
const requireSession = vi
@@ -75,6 +77,8 @@ function createThreadControlHarness() {
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
const requireSession = vi
@@ -117,6 +121,8 @@ function createPendingUserInputHarness() {
},
],
]),
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
const requireSession = vi
@@ -135,6 +141,44 @@ function createPendingUserInputHarness() {
return { manager, context, requireSession, writeMessage, emitEvent };
}
function createCollabNotificationHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
provider: "codex",
status: "running",
threadId: asThreadId("thread_1"),
runtimeMode: "full-access",
model: "gpt-5.3-codex",
activeTurnId: "turn_parent",
resumeCursor: { threadId: "provider_parent" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map<string, string>(),
collabReceiverItems: new Map<string, string>(),
nextRequestId: 1,
stopping: false,
};
const emitEvent = vi
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
.mockImplementation(() => {});
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, emitEvent, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -721,6 +765,8 @@ describe("respondToUserInput", () => {
},
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
type ApprovalRequestContext = {
session: typeof context.session;
@@ -748,89 +794,274 @@ describe("respondToUserInput", () => {
});
});
describe("collab child conversation routing", () => {
it("rewrites child notification turn ids onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/agentMessage/delta",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "msg_child_1",
delta: "working",
},
});
expect(emitEvent).toHaveBeenLastCalledWith(
expect.objectContaining({
method: "item/agentMessage/delta",
turnId: "turn_parent",
itemId: "msg_child_1",
}),
);
});
it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
updateSession.mockClear();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/started",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1" },
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/completed",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1", status: "completed" },
},
});
expect(emitEvent).not.toHaveBeenCalled();
expect(updateSession).not.toHaveBeenCalled();
});
it("rewrites child approval requests onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
(
manager as unknown as {
handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
}
).handleServerRequest(context, {
id: 42,
method: "item/commandExecution/requestApproval",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "call_child_1",
command: "bun install",
},
});
expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
expect.objectContaining({
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "item/commandExecution/requestApproval",
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
});
it("rewrites child task notifications onto the parent collab item when no child item id exists", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "codex/event/task_started",
params: {
threadId: "child_provider_1",
msg: {
type: "task_started",
turn_id: "turn_child_1",
},
},
});
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "codex/event/task_started",
turnId: "turn_parent",
itemId: "call_collab_1",
}),
);
});
});
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
it(
"keeps prior thread history when resuming with a changed runtime mode",
async () => {
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
const manager = new CodexAppServerManager();
const manager = new CodexAppServerManager();
try {
const firstSession = await manager.startSession({
threadId: asThreadId("thread-live"),
provider: "codex",
cwd: workspaceDir,
runtimeMode: "full-access",
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH
? { binaryPath: process.env.CODEX_BINARY_PATH }
: {}),
...(process.env.CODEX_HOME_PATH
? { homePath: process.env.CODEX_HOME_PATH }
: {}),
},
try {
const firstSession = await manager.startSession({
threadId: asThreadId("thread-live"),
provider: "codex",
cwd: workspaceDir,
runtimeMode: "full-access",
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
},
});
},
});
const firstTurn = await manager.sendTurn({
threadId: firstSession.threadId,
input: `Reply with exactly the word ALPHA ${randomUUID()}`,
});
const firstTurn = await manager.sendTurn({
threadId: firstSession.threadId,
input: `Reply with exactly the word ALPHA ${randomUUID()}`,
});
expect(firstTurn.threadId).toBe(firstSession.threadId);
expect(firstTurn.threadId).toBe(firstSession.threadId);
await vi.waitFor(async () => {
await vi.waitFor(
async () => {
const snapshot = await manager.readThread(firstSession.threadId);
expect(snapshot.turns.length).toBeGreaterThan(0);
}, { timeout: 120_000, interval: 1_000 });
},
{ timeout: 120_000, interval: 1_000 },
);
const firstSnapshot = await manager.readThread(firstSession.threadId);
const originalThreadId = firstSnapshot.threadId;
const originalTurnCount = firstSnapshot.turns.length;
const firstSnapshot = await manager.readThread(firstSession.threadId);
const originalThreadId = firstSnapshot.threadId;
const originalTurnCount = firstSnapshot.turns.length;
manager.stopSession(firstSession.threadId);
manager.stopSession(firstSession.threadId);
const resumedSession = await manager.startSession({
threadId: firstSession.threadId,
provider: "codex",
cwd: workspaceDir,
runtimeMode: "approval-required",
resumeCursor: firstSession.resumeCursor,
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH
? { binaryPath: process.env.CODEX_BINARY_PATH }
: {}),
...(process.env.CODEX_HOME_PATH
? { homePath: process.env.CODEX_HOME_PATH }
: {}),
},
const resumedSession = await manager.startSession({
threadId: firstSession.threadId,
provider: "codex",
cwd: workspaceDir,
runtimeMode: "approval-required",
resumeCursor: firstSession.resumeCursor,
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
},
});
},
});
expect(resumedSession.threadId).toBe(originalThreadId);
expect(resumedSession.threadId).toBe(originalThreadId);
const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
await manager.sendTurn({
threadId: resumedSession.threadId,
input: `Reply with exactly the word BETA ${randomUUID()}`,
});
await manager.sendTurn({
threadId: resumedSession.threadId,
input: `Reply with exactly the word BETA ${randomUUID()}`,
});
await vi.waitFor(async () => {
await vi.waitFor(
async () => {
const snapshot = await manager.readThread(resumedSession.threadId);
expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);
}, { timeout: 120_000, interval: 1_000 });
} finally {
manager.stopAll();
rmSync(workspaceDir, { recursive: true, force: true });
}
},
180_000,
);
},
{ timeout: 120_000, interval: 1_000 },
);
} finally {
manager.stopAll();
rmSync(workspaceDir, { recursive: true, force: true });
}
}, 180_000);
});
+117 -10
View File
@@ -70,6 +70,8 @@ interface CodexSessionContext {
pending: Map<PendingRequestKey, PendingRequest>;
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
collabReceiverTurns: Map<string, TurnId>;
collabReceiverItems: Map<string, ProviderItemId>;
nextRequestId: number;
stopping: boolean;
}
@@ -571,6 +573,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
nextRequestId: 1,
stopping: false,
};
@@ -732,6 +736,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
const context = this.requireSession(input.threadId);
context.collabReceiverTurns.clear();
context.collabReceiverItems.clear();
const turnInput: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
@@ -1121,7 +1127,18 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context: CodexSessionContext,
notification: JsonRpcNotification,
): void {
const route = this.readRouteFields(notification.params);
const rawRoute = this.readRouteFields(notification.params);
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
const childParentItemId = this.readChildParentItemId(context, notification.params);
const isChildConversation = childParentTurnId !== undefined;
const effectiveItemId = rawRoute.itemId ?? childParentItemId;
if (
isChildConversation &&
this.shouldSuppressChildConversationNotification(notification.method)
) {
return;
}
const textDelta =
notification.method === "item/agentMessage/delta"
? this.readString(notification.params, "delta")
@@ -1134,8 +1151,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: notification.method,
turnId: route.turnId,
itemId: route.itemId,
...((childParentTurnId ?? rawRoute.turnId)
? { turnId: childParentTurnId ?? rawRoute.turnId }
: {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
textDelta,
payload: notification.params,
});
@@ -1151,6 +1170,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/started") {
if (isChildConversation) {
return;
}
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
this.updateSession(context, {
status: "running",
@@ -1160,6 +1182,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/completed") {
if (isChildConversation) {
return;
}
context.collabReceiverTurns.clear();
context.collabReceiverItems.clear();
const turn = this.readObject(notification.params, "turn");
const status = this.readString(turn, "status");
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
@@ -1172,6 +1199,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "error") {
if (isChildConversation) {
return;
}
const message = this.readString(this.readObject(notification.params)?.error, "message");
const willRetry = this.readBoolean(notification.params, "willRetry");
@@ -1183,7 +1213,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
const route = this.readRouteFields(request.params);
const rawRoute = this.readRouteFields(request.params);
const childParentTurnId = this.readChildParentTurnId(context, request.params);
const childParentItemId = this.readChildParentItemId(context, request.params);
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
const effectiveItemId = rawRoute.itemId ?? childParentItemId;
const requestKind = this.requestKindForMethod(request.method);
let requestId: ApprovalRequestId | undefined;
if (requestKind) {
@@ -1199,8 +1233,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
: "item/fileChange/requestApproval",
requestKind,
threadId: context.session.threadId,
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
};
context.pendingApprovals.set(requestId, pendingRequest);
}
@@ -1211,8 +1245,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
requestId,
jsonRpcId: request.id,
threadId: context.session.threadId,
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
});
}
@@ -1223,8 +1257,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: request.method,
turnId: route.turnId,
itemId: route.itemId,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
requestId,
requestKind,
payload: request.params,
@@ -1451,6 +1485,79 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return route;
}
private readProviderConversationId(params: unknown): string | undefined {
return (
this.readString(params, "threadId") ??
this.readString(this.readObject(params, "thread"), "id") ??
this.readString(params, "conversationId")
);
}
private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined {
const providerConversationId = this.readProviderConversationId(params);
if (!providerConversationId) {
return undefined;
}
return context.collabReceiverTurns.get(providerConversationId);
}
private readChildParentItemId(
context: CodexSessionContext,
params: unknown,
): ProviderItemId | undefined {
const providerConversationId = this.readProviderConversationId(params);
if (!providerConversationId) {
return undefined;
}
return context.collabReceiverItems.get(providerConversationId);
}
private rememberCollabReceiverTurns(
context: CodexSessionContext,
params: unknown,
parentTurnId: TurnId | undefined,
): void {
if (!parentTurnId) {
return;
}
const payload = this.readObject(params);
const item = this.readObject(payload, "item") ?? payload;
const itemType = this.readString(item, "type") ?? this.readString(item, "kind");
if (itemType !== "collabAgentToolCall") {
return;
}
const parentItemId = toProviderItemId(this.readString(item, "id"));
const receiverThreadIds =
this.readArray(item, "receiverThreadIds")
?.map((value) => (typeof value === "string" ? value : null))
.filter((value): value is string => value !== null) ?? [];
for (const receiverThreadId of receiverThreadIds) {
context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
if (parentItemId) {
context.collabReceiverItems.set(receiverThreadId, parentItemId);
}
}
}
private shouldSuppressChildConversationNotification(method: string): boolean {
return (
method === "thread/started" ||
method === "thread/status/changed" ||
method === "thread/archived" ||
method === "thread/unarchived" ||
method === "thread/closed" ||
method === "thread/compacted" ||
method === "thread/name/updated" ||
method === "thread/tokenUsage/updated" ||
method === "turn/started" ||
method === "turn/completed" ||
method === "turn/aborted" ||
method === "turn/plan/updated" ||
method === "item/plan/delta"
);
}
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
const target =
key === undefined
@@ -363,8 +363,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
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 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"));
@@ -392,9 +391,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
}),
),
),
Effect.ensuring(
fs.remove(imagePath).pipe(Effect.catch(() => Effect.void)),
),
Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
);
expect(generated.branch).toBe("fix/ui-regression");
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
@@ -17,7 +18,6 @@ import {
TextGeneration,
} from "../Services/TextGeneration.ts";
const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
@@ -187,6 +187,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
outputSchemaJson,
imagePaths = [],
cleanupPaths = [],
model,
}: {
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
cwd: string;
@@ -194,6 +195,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
outputSchemaJson: S;
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
model?: string;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
@@ -212,7 +214,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
"-s",
"read-only",
"--model",
CODEX_MODEL,
model ?? DEFAULT_GIT_TEXT_GENERATION_MODEL,
"--config",
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
@@ -353,6 +355,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
cwd: input.cwd,
prompt,
outputSchemaJson,
...(input.model ? { model: input.model } : {}),
}).pipe(
Effect.map(
(generated) =>
@@ -398,6 +401,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
title: Schema.String,
body: Schema.String,
}),
...(input.model ? { model: input.model } : {}),
}).pipe(
Effect.map(
(generated) =>
@@ -449,6 +453,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
branch: Schema.String,
}),
imagePaths,
...(input.model ? { model: input.model } : {}),
});
return {
+300 -30
View File
@@ -97,7 +97,7 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
return {
status: (input) => core.status(input),
statusDetails: (cwd) => core.statusDetails(cwd),
prepareCommitContext: (cwd) => core.prepareCommitContext(cwd),
prepareCommitContext: (cwd, filePaths?) => core.prepareCommitContext(cwd, filePaths),
commit: (cwd, subject, body) => core.commit(cwd, subject, body),
pushCurrentBranch: (cwd, fallbackBranch) => core.pushCurrentBranch(cwd, fallbackBranch),
pullCurrentBranch: (cwd) => core.pullCurrentBranch(cwd),
@@ -105,6 +105,10 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
readConfigValue: (cwd, key) => core.readConfigValue(cwd, key),
listBranches: (input) => core.listBranches(input),
createWorktree: (input) => core.createWorktree(input),
fetchPullRequestBranch: (input) => core.fetchPullRequestBranch(input),
ensureRemote: (input) => core.ensureRemote(input),
fetchRemoteBranch: (input) => core.fetchRemoteBranch(input),
setBranchUpstream: (input) => core.setBranchUpstream(input),
removeWorktree: (input) => core.removeWorktree(input),
renameBranch: (input) => core.renameBranch(input),
createBranch: (input) => core.createBranch(input),
@@ -149,6 +153,13 @@ function createGitWorktree(input: Parameters<GitCoreShape["createWorktree"]>[0])
});
}
function fetchGitPullRequestBranch(input: Parameters<GitCoreShape["fetchPullRequestBranch"]>[0]) {
return Effect.gen(function* () {
const core = yield* GitCore;
return yield* core.fetchPullRequestBranch(input);
});
}
function removeGitWorktree(input: Parameters<GitCoreShape["removeWorktree"]>[0]) {
return Effect.gen(function* () {
const core = yield* GitCore;
@@ -174,7 +185,7 @@ function pullGitBranch({ cwd }: { cwd: string }) {
function initRepoWithCommit(
cwd: string,
): Effect.Effect<
void,
{ initialBranch: string },
GitCommandError | PlatformError.PlatformError,
GitCore | GitService | FileSystem.FileSystem
> {
@@ -185,6 +196,8 @@ function initRepoWithCommit(
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
yield* git(cwd, ["add", "."]);
yield* git(cwd, ["commit", "-m", "initial commit"]);
const initialBranch = yield* git(cwd, ["branch", "--show-current"]);
return { initialBranch };
});
}
@@ -247,6 +260,7 @@ it.layer(TestLayer)("git integration", (it) => {
yield* initRepoWithCommit(tmp);
const result = yield* listGitBranches({ cwd: tmp });
expect(result.isRepo).toBe(true);
expect(result.hasOriginRemote).toBe(false);
expect(result.branches.length).toBeGreaterThanOrEqual(1);
}),
);
@@ -260,6 +274,7 @@ it.layer(TestLayer)("git integration", (it) => {
const tmp = yield* makeTmpDir();
const result = yield* listGitBranches({ cwd: tmp });
expect(result.isRepo).toBe(false);
expect(result.hasOriginRemote).toBe(false);
expect(result.branches).toEqual([]);
}),
);
@@ -418,6 +433,7 @@ it.layer(TestLayer)("git integration", (it) => {
const result = yield* listGitBranches({ cwd: tmp });
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
expect(result.hasOriginRemote).toBe(true);
expect(firstRemoteIndex).toBeGreaterThan(0);
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
true,
@@ -426,7 +442,9 @@ it.layer(TestLayer)("git integration", (it) => {
true,
);
expect(
result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),
result.branches.some(
(branch) => branch.name === "feature/local-only" && !branch.isRemote,
),
).toBe(true);
expect(
result.branches.some(
@@ -689,29 +707,27 @@ 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"]);
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* 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" });
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);
}),
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", () =>
@@ -940,13 +956,7 @@ it.layer(TestLayer)("git integration", (it) => {
});
expect(renamed.branch).toBe("feature/new-name");
expect(renameArgs).toEqual([
"branch",
"-m",
"--",
"feature/old-name",
"feature/new-name",
]);
expect(renameArgs).toEqual(["branch", "-m", "--", "feature/old-name", "feature/new-name"]);
}),
);
});
@@ -1006,6 +1016,28 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("creates a worktree for an existing branch when newBranch is omitted", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* createGitBranch({ cwd: tmp, branch: "feature/existing-worktree" });
const wtPath = path.join(tmp, "wt-existing");
const result = yield* createGitWorktree({
cwd: tmp,
branch: "feature/existing-worktree",
path: wtPath,
});
expect(result.worktree.path).toBe(wtPath);
expect(result.worktree.branch).toBe("feature/existing-worktree");
const branchOutput = yield* git(wtPath, ["branch", "--show-current"]);
expect(branchOutput).toBe("feature/existing-worktree");
yield* removeGitWorktree({ cwd: tmp, path: wtPath });
}),
);
it.effect("throws when new branch name already exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1168,6 +1200,37 @@ it.layer(TestLayer)("git integration", (it) => {
);
});
describe("fetchPullRequestBranch", () => {
it.effect("fetches a GitHub pull request ref into a local branch without checkout", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(tmp);
const remoteDir = yield* makeTmpDir("git-remote-");
yield* git(remoteDir, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remoteDir]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
yield* git(tmp, ["checkout", "-b", "feature/pr-fetch"]);
yield* writeTextFile(path.join(tmp, "pr-fetch.txt"), "fetch me\n");
yield* git(tmp, ["add", "pr-fetch.txt"]);
yield* git(tmp, ["commit", "-m", "Add PR fetch branch"]);
yield* git(tmp, ["push", "-u", "origin", "feature/pr-fetch"]);
yield* git(tmp, ["push", "origin", "HEAD:refs/pull/55/head"]);
yield* git(tmp, ["checkout", initialBranch]);
yield* fetchGitPullRequestBranch({
cwd: tmp,
prNumber: 55,
branch: "feature/pr-fetch",
});
const localBranches = yield* git(tmp, ["branch", "--list", "feature/pr-fetch"]);
expect(localBranches).toContain("feature/pr-fetch");
const currentBranch = yield* git(tmp, ["branch", "--show-current"]);
expect(currentBranch).toBe(initialBranch);
}),
);
});
// ── Full flow: thread switching simulation ──
describe("full flow: thread switching (checkout toggling)", () => {
@@ -1257,6 +1320,27 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"reuses an existing remote when the target URL only differs by a trailing slash after .git",
() =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* git(tmp, ["remote", "add", "origin", "[email protected]:pingdotgg/t3code.git"]);
const remoteName = yield* core.ensureRemote({
cwd: tmp,
preferredName: "origin",
url: "[email protected]:pingdotgg/t3code.git/",
});
expect(remoteName).toBe("origin");
expect((yield* git(tmp, ["remote"])).split("\n").filter(Boolean)).toEqual(["origin"]);
}),
);
it.effect("reports status details and dirty state", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1325,6 +1409,44 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"computes ahead count against a non-origin remote-prefixed gh-merge-base candidate",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const remoteName = "fork-seed";
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", remoteName, remote]);
yield* git(source, ["push", "-u", remoteName, initialBranch]);
yield* git(source, ["checkout", "-b", "feature/non-origin-merge-base"]);
yield* git(source, [
"config",
"branch.feature/non-origin-merge-base.gh-merge-base",
`${remoteName}/${initialBranch}`,
]);
yield* writeTextFile(
path.join(source, "feature.txt"),
`ahead of ${remoteName}/${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/non-origin-merge-base");
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();
@@ -1366,6 +1488,31 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("pushes with upstream setup to the only configured non-origin remote", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* git(tmp, ["init", "--initial-branch=main"]);
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", "fork", remote]);
yield* git(tmp, ["checkout", "-b", "feature/fork-only"]);
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("fork/feature/fork-only");
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
"fork/feature/fork-only",
);
}),
);
it.effect(
"pushes with upstream setup when comparable base exists but remote branch is missing",
() =>
@@ -1402,6 +1549,90 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("prefers branch pushRemote over origin when setting upstream", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const origin = yield* makeTmpDir();
const fork = yield* makeTmpDir();
yield* git(origin, ["init", "--bare"]);
yield* git(fork, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const initialBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", origin]);
yield* git(tmp, ["remote", "add", "fork", fork]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
const featureBranch = "feature/push-remote";
yield* git(tmp, ["checkout", "-b", featureBranch]);
yield* git(tmp, ["config", `branch.${featureBranch}.pushRemote`, "fork"]);
yield* writeTextFile(path.join(tmp, "feature.txt"), "push to fork\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature commit"]);
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(`fork/${featureBranch}`);
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
`fork/${featureBranch}`,
);
expect(yield* git(tmp, ["ls-remote", "--heads", "fork", featureBranch])).toContain(
featureBranch,
);
}),
);
it.effect(
"pushes renamed PR worktree branches to their tracked upstream branch even when push.default is current",
() =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const fork = yield* makeTmpDir();
yield* git(fork, ["init", "--bare"]);
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* git(tmp, ["remote", "add", "jasonLaster", fork]);
yield* git(tmp, ["checkout", "-b", "statemachine"]);
yield* writeTextFile(path.join(tmp, "fork.txt"), "fork branch\n");
yield* git(tmp, ["add", "fork.txt"]);
yield* git(tmp, ["commit", "-m", "fork branch"]);
yield* git(tmp, ["push", "-u", "jasonLaster", "statemachine"]);
yield* git(tmp, ["checkout", initialBranch]);
yield* git(tmp, ["branch", "-D", "statemachine"]);
yield* git(tmp, [
"checkout",
"-b",
"t3code/pr-488/statemachine",
"--track",
"jasonLaster/statemachine",
]);
yield* git(tmp, ["config", "push.default", "current"]);
yield* writeTextFile(path.join(tmp, "fork.txt"), "updated fork branch\n");
yield* git(tmp, ["add", "fork.txt"]);
yield* git(tmp, ["commit", "-m", "update reviewed PR branch"]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(false);
expect(pushed.upstreamBranch).toBe("jasonLaster/statemachine");
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
"jasonLaster/statemachine",
);
expect(
yield* git(tmp, ["ls-remote", "--heads", "jasonLaster", "statemachine"]),
).toContain("statemachine");
expect(
yield* git(tmp, ["ls-remote", "--heads", "jasonLaster", "t3code/pr-488/statemachine"]),
).toBe("");
}),
);
it.effect("includes command context when worktree removal fails", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1480,6 +1711,45 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("prepareCommitContext stages only selected files when filePaths provided", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* writeTextFile(path.join(tmp, "a.txt"), "file a\n");
yield* writeTextFile(path.join(tmp, "b.txt"), "file b\n");
const context = yield* core.prepareCommitContext(tmp, ["a.txt"]);
expect(context).not.toBeNull();
expect(context!.stagedSummary).toContain("a.txt");
expect(context!.stagedSummary).not.toContain("b.txt");
yield* core.commit(tmp, "Add only a.txt", "");
// b.txt should still be untracked after commit
const statusAfter = yield* git(tmp, ["status", "--porcelain"]);
expect(statusAfter).toContain("b.txt");
expect(statusAfter).not.toContain("a.txt");
}),
);
it.effect("prepareCommitContext stages everything when filePaths is undefined", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* writeTextFile(path.join(tmp, "a.txt"), "file a\n");
yield* writeTextFile(path.join(tmp, "b.txt"), "file b\n");
const context = yield* core.prepareCommitContext(tmp);
expect(context).not.toBeNull();
expect(context!.stagedSummary).toContain("a.txt");
expect(context!.stagedSummary).toContain("b.txt");
}),
);
it.effect("pushes with upstream setup and then skips when up to date", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
+249 -30
View File
@@ -100,6 +100,38 @@ function parseRemoteNames(stdout: string): ReadonlyArray<string> {
.toSorted((a, b) => b.length - a.length);
}
function sanitizeRemoteName(value: string): string {
const sanitized = value
.trim()
.replace(/[^A-Za-z0-9._-]+/g, "-")
.replace(/^-+|-+$/g, "");
return sanitized.length > 0 ? sanitized : "fork";
}
function normalizeRemoteUrl(value: string): string {
return value
.trim()
.replace(/\/+$/g, "")
.replace(/\.git$/i, "")
.toLowerCase();
}
function parseRemoteFetchUrls(stdout: string): Map<string, string> {
const remotes = new Map<string, string>();
for (const line of stdout.split("\n")) {
const trimmed = line.trim();
if (trimmed.length === 0) continue;
const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
if (!match) continue;
const [, remoteName = "", remoteUrl = "", direction = ""] = match;
if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) {
continue;
}
remotes.set(remoteName, remoteUrl);
}
return remotes;
}
function parseRemoteRefWithRemoteNames(
branchName: string,
remoteNames: ReadonlyArray<string>,
@@ -159,9 +191,9 @@ function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
function parseDefaultBranchFromRemoteHeadRef(value: string): string | null {
function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null {
const trimmed = value.trim();
const prefix = "refs/remotes/origin/";
const prefix = `refs/remotes/${remoteName}/`;
if (!trimmed.startsWith(prefix)) {
return null;
}
@@ -385,29 +417,33 @@ const makeGitCore = Effect.gen(function* () {
yield* fetchUpstreamRef(cwd, upstream);
});
const resolveDefaultBranchName = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
const resolveDefaultBranchName = (
cwd: string,
remoteName: string,
): Effect.Effect<string | null, GitCommandError> =>
executeGit(
"GitCore.resolveDefaultBranchName",
cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
["symbolic-ref", `refs/remotes/${remoteName}/HEAD`],
{ allowNonZeroExit: true },
).pipe(
Effect.map((result) => {
if (result.code !== 0) {
return null;
}
return parseDefaultBranchFromRemoteHeadRef(result.stdout);
return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName);
}),
);
const remoteBranchExists = (
cwd: string,
remoteName: string,
branch: string,
): Effect.Effect<boolean, GitCommandError> =>
executeGit(
"GitCore.remoteBranchExists",
cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`],
["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`],
{
allowNonZeroExit: true,
},
@@ -418,6 +454,89 @@ const makeGitCore = Effect.gen(function* () {
allowNonZeroExit: true,
}).pipe(Effect.map((result) => result.code === 0));
const listRemoteNames = (cwd: string): Effect.Effect<ReadonlyArray<string>, GitCommandError> =>
runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
Effect.map((stdout) => parseRemoteNames(stdout).toReversed()),
);
const resolvePrimaryRemoteName = (cwd: string): Effect.Effect<string, GitCommandError> =>
Effect.gen(function* () {
if (yield* originRemoteExists(cwd)) {
return "origin";
}
const remotes = yield* listRemoteNames(cwd);
const [firstRemote] = remotes;
if (firstRemote) {
return firstRemote;
}
return yield* createGitCommandError(
"GitCore.resolvePrimaryRemoteName",
cwd,
["remote"],
"No git remote is configured for this repository.",
);
});
const resolvePushRemoteName = (
cwd: string,
branch: string,
): Effect.Effect<string | null, GitCommandError> =>
Effect.gen(function* () {
const branchPushRemote = yield* runGitStdout(
"GitCore.resolvePushRemoteName.branchPushRemote",
cwd,
["config", "--get", `branch.${branch}.pushRemote`],
true,
).pipe(Effect.map((stdout) => stdout.trim()));
if (branchPushRemote.length > 0) {
return branchPushRemote;
}
const pushDefaultRemote = yield* runGitStdout(
"GitCore.resolvePushRemoteName.remotePushDefault",
cwd,
["config", "--get", "remote.pushDefault"],
true,
).pipe(Effect.map((stdout) => stdout.trim()));
if (pushDefaultRemote.length > 0) {
return pushDefaultRemote;
}
return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.catch(() => Effect.succeed(null)));
});
const ensureRemote: GitCoreShape["ensureRemote"] = (input) =>
Effect.gen(function* () {
const preferredName = sanitizeRemoteName(input.preferredName);
const normalizedTargetUrl = normalizeRemoteUrl(input.url);
const remoteFetchUrls = yield* runGitStdout(
"GitCore.ensureRemote.listRemoteUrls",
input.cwd,
["remote", "-v"],
).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));
for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) {
if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) {
return remoteName;
}
}
let remoteName = preferredName;
let suffix = 1;
while (remoteFetchUrls.has(remoteName)) {
remoteName = `${preferredName}-${suffix}`;
suffix += 1;
}
yield* runGit("GitCore.ensureRemote.add", input.cwd, [
"remote",
"add",
remoteName,
input.url,
]);
return remoteName;
});
const resolveBaseBranchForNoUpstream = (
cwd: string,
branch: string,
@@ -430,7 +549,11 @@ const makeGitCore = Effect.gen(function* () {
true,
).pipe(Effect.map((stdout) => stdout.trim()));
const defaultBranch = yield* resolveDefaultBranchName(cwd);
const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe(
Effect.catch(() => Effect.succeed(null)),
);
const defaultBranch =
primaryRemoteName === null ? null : yield* resolveDefaultBranchName(cwd, primaryRemoteName);
const candidates = [
configuredBaseBranch.length > 0 ? configuredBaseBranch : null,
defaultBranch,
@@ -442,9 +565,13 @@ const makeGitCore = Effect.gen(function* () {
continue;
}
const remotePrefix =
primaryRemoteName && primaryRemoteName !== "origin" ? `${primaryRemoteName}/` : null;
const normalizedCandidate = candidate.startsWith("origin/")
? candidate.slice("origin/".length)
: candidate;
: remotePrefix && candidate.startsWith(remotePrefix)
? candidate.slice(remotePrefix.length)
: candidate;
if (normalizedCandidate.length === 0 || normalizedCandidate === branch) {
continue;
}
@@ -453,8 +580,11 @@ const makeGitCore = Effect.gen(function* () {
return normalizedCandidate;
}
if (yield* remoteBranchExists(cwd, normalizedCandidate)) {
return `origin/${normalizedCandidate}`;
if (
primaryRemoteName &&
(yield* remoteBranchExists(cwd, primaryRemoteName, normalizedCandidate))
) {
return `${primaryRemoteName}/${normalizedCandidate}`;
}
}
@@ -636,9 +766,21 @@ const makeGitCore = Effect.gen(function* () {
})),
);
const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd) =>
const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd, filePaths) =>
Effect.gen(function* () {
yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);
if (filePaths && filePaths.length > 0) {
yield* runGit("GitCore.prepareCommitContext.reset", cwd, ["reset"]).pipe(
Effect.catch(() => Effect.void),
);
yield* runGit("GitCore.prepareCommitContext.addSelected", cwd, [
"add",
"-A",
"--",
...filePaths,
]);
} else {
yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);
}
const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [
"diff",
@@ -705,17 +847,17 @@ const makeGitCore = Effect.gen(function* () {
Effect.catch(() => Effect.succeed(null)),
);
if (comparableBaseBranch) {
const hasOriginRemote = yield* originRemoteExists(cwd).pipe(
Effect.catch(() => Effect.succeed(false)),
const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(null)),
);
if (!hasOriginRemote) {
if (!publishRemoteName) {
return {
status: "skipped_up_to_date" as const,
branch,
};
}
const hasRemoteBranch = yield* remoteBranchExists(cwd, branch).pipe(
const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (hasRemoteBranch) {
@@ -728,20 +870,46 @@ const makeGitCore = Effect.gen(function* () {
}
if (!details.hasUpstream) {
const publishRemoteName = yield* resolvePushRemoteName(cwd, branch);
if (!publishRemoteName) {
return yield* createGitCommandError(
"GitCore.pushCurrentBranch",
cwd,
["push"],
"Cannot push because no git remote is configured for this repository.",
);
}
yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [
"push",
"-u",
"origin",
publishRemoteName,
branch,
]);
return {
status: "pushed" as const,
branch,
upstreamBranch: `origin/${branch}`,
upstreamBranch: `${publishRemoteName}/${branch}`,
setUpstream: true,
};
}
const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe(
Effect.catch(() => Effect.succeed(null)),
);
if (currentUpstream) {
yield* runGit("GitCore.pushCurrentBranch.pushUpstream", cwd, [
"push",
currentUpstream.remoteName,
`HEAD:${currentUpstream.upstreamBranch}`,
]);
return {
status: "pushed" as const,
branch,
upstreamBranch: currentUpstream.upstreamRef,
setUpstream: false,
};
}
yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]);
return {
status: "pushed" as const,
@@ -844,7 +1012,7 @@ const makeGitCore = Effect.gen(function* () {
if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false };
return { branches: [], isRepo: false, hasOriginRemote: false };
}
return yield* createGitCommandError(
"GitCore.listBranches",
@@ -1010,34 +1178,81 @@ const makeGitCore = Effect.gen(function* () {
const branches = [...localBranches, ...remoteBranches];
return { branches, isRepo: true };
return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") };
});
const createWorktree: GitCoreShape["createWorktree"] = (input) =>
Effect.gen(function* () {
const sanitizedBranch = input.newBranch.replace(/\//g, "-");
const targetBranch = input.newBranch ?? input.branch;
const sanitizedBranch = targetBranch.replace(/\//g, "-");
const repoName = path.basename(input.cwd);
const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
const worktreePath =
input.path ?? path.join(homeDir, ".t3", "worktrees", repoName, sanitizedBranch);
const args = input.newBranch
? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch]
: ["worktree", "add", worktreePath, input.branch];
yield* executeGit(
"GitCore.createWorktree",
input.cwd,
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
{
fallbackErrorMessage: "git worktree add failed",
},
);
yield* executeGit("GitCore.createWorktree", input.cwd, args, {
fallbackErrorMessage: "git worktree add failed",
});
return {
worktree: {
path: worktreePath,
branch: input.newBranch,
branch: targetBranch,
},
};
});
const fetchPullRequestBranch: GitCoreShape["fetchPullRequestBranch"] = (input) =>
Effect.gen(function* () {
const remoteName = yield* resolvePrimaryRemoteName(input.cwd);
yield* executeGit(
"GitCore.fetchPullRequestBranch",
input.cwd,
[
"fetch",
"--quiet",
"--no-tags",
remoteName,
`+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`,
],
{
fallbackErrorMessage: "git fetch pull request branch failed",
},
);
}).pipe(Effect.asVoid);
const fetchRemoteBranch: GitCoreShape["fetchRemoteBranch"] = (input) =>
Effect.gen(function* () {
yield* runGit("GitCore.fetchRemoteBranch.fetch", input.cwd, [
"fetch",
"--quiet",
"--no-tags",
input.remoteName,
`+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`,
]);
const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch);
const targetRef = `${input.remoteName}/${input.remoteBranch}`;
yield* runGit(
"GitCore.fetchRemoteBranch.materialize",
input.cwd,
localBranchAlreadyExists
? ["branch", "--force", input.localBranch, targetRef]
: ["branch", input.localBranch, targetRef],
);
}).pipe(Effect.asVoid);
const setBranchUpstream: GitCoreShape["setBranchUpstream"] = (input) =>
runGit("GitCore.setBranchUpstream", input.cwd, [
"branch",
"--set-upstream-to",
`${input.remoteName}/${input.remoteBranch}`,
input.branch,
]);
const removeWorktree: GitCoreShape["removeWorktree"] = (input) =>
Effect.gen(function* () {
const args = ["worktree", "remove"];
@@ -1197,6 +1412,10 @@ const makeGitCore = Effect.gen(function* () {
readConfigValue,
listBranches,
createWorktree,
fetchPullRequestBranch,
ensureRemote,
fetchRemoteBranch,
setBranchUpstream,
removeWorktree,
renameBranch,
createBranch,
@@ -0,0 +1,128 @@
import { assert, it } from "@effect/vitest";
import { Effect } from "effect";
import { afterEach, expect, vi } from "vitest";
vi.mock("../../processRunner", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../../processRunner";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { GitHubCliLive } from "./GitHubCli.ts";
const mockedRunProcess = vi.mocked(runProcess);
const layer = it.layer(GitHubCliLive);
afterEach(() => {
mockedRunProcess.mockReset();
});
layer("GitHubCliLive", (it) => {
it.effect("parses pull request view output", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: JSON.stringify({
number: 42,
title: "Add PR thread creation",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/pr-threads",
state: "OPEN",
mergedAt: null,
isCrossRepository: true,
headRepository: {
nameWithOwner: "octocat/codething-mvp",
},
headRepositoryOwner: {
login: "octocat",
},
}),
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "#42",
});
});
assert.deepStrictEqual(result, {
number: 42,
title: "Add PR thread creation",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/pr-threads",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
});
expect(mockedRunProcess).toHaveBeenCalledWith(
"gh",
[
"pr",
"view",
"#42",
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
expect.objectContaining({ cwd: "/repo" }),
);
}),
);
it.effect("reads repository clone URLs", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: JSON.stringify({
nameWithOwner: "octocat/codething-mvp",
url: "https://github.com/octocat/codething-mvp",
sshUrl: "[email protected]:octocat/codething-mvp.git",
}),
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.getRepositoryCloneUrls({
cwd: "/repo",
repository: "octocat/codething-mvp",
});
});
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/codething-mvp",
url: "https://github.com/octocat/codething-mvp",
sshUrl: "[email protected]:octocat/codething-mvp.git",
});
}),
);
it.effect("surfaces a friendly error when the pull request is not found", () =>
Effect.gen(function* () {
mockedRunProcess.mockRejectedValueOnce(
new Error(
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
),
);
const error = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "4888",
});
}).pipe(Effect.flip);
assert.equal(error.message.includes("Pull request not found"), true);
}),
);
});
+169 -67
View File
@@ -1,8 +1,14 @@
import { Effect, Layer } from "effect";
import { Effect, Layer, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { runProcess } from "../../processRunner";
import { GitHubCliError } from "../Errors.ts";
import { GitHubCli, type GitHubCliShape } from "../Services/GitHubCli.ts";
import {
GitHubCli,
type GitHubRepositoryCloneUrls,
type GitHubCliShape,
type GitHubPullRequestSummary,
} from "../Services/GitHubCli.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
@@ -30,6 +36,19 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
});
}
if (
lower.includes("could not resolve to a pullrequest") ||
lower.includes("repository.pullrequest") ||
lower.includes("no pull requests found for branch") ||
lower.includes("pull request not found")
) {
return new GitHubCliError({
operation,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
}
return new GitHubCliError({
operation,
detail: `GitHub CLI command failed: ${error.message}`,
@@ -44,59 +63,102 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
});
}
function parseOpenPullRequests(raw: string): ReadonlyArray<{
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}> {
const trimmed = raw.trim();
if (trimmed.length === 0) return [];
const parsed: unknown = JSON.parse(trimmed);
if (!Array.isArray(parsed)) {
throw new Error("GitHub CLI returned non-array JSON.");
function normalizePullRequestState(input: {
state?: string | null | undefined;
mergedAt?: string | null | undefined;
}): "open" | "closed" | "merged" {
const mergedAt = input.mergedAt;
const state = input.state;
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
return "merged";
}
const result: Array<{
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}> = [];
for (const entry of parsed) {
if (!entry || typeof entry !== "object") {
continue;
}
const record = entry as Record<string, unknown>;
const number = record.number;
const title = record.title;
const url = record.url;
const baseRefName = record.baseRefName;
const headRefName = record.headRefName;
if (
typeof number !== "number" ||
!Number.isInteger(number) ||
number <= 0 ||
typeof title !== "string" ||
typeof url !== "string" ||
typeof baseRefName !== "string" ||
typeof headRefName !== "string"
) {
continue;
}
result.push({
number,
title,
url,
baseRefName,
headRefName,
});
if (state === "CLOSED") {
return "closed";
}
return "open";
}
return result;
const RawGitHubPullRequestSchema = Schema.Struct({
number: PositiveInt,
title: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
baseRefName: TrimmedNonEmptyString,
headRefName: TrimmedNonEmptyString,
state: Schema.optional(Schema.NullOr(Schema.String)),
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
isCrossRepository: Schema.optional(Schema.Boolean),
headRepository: Schema.optional(
Schema.NullOr(
Schema.Struct({
nameWithOwner: Schema.String,
}),
),
),
headRepositoryOwner: Schema.optional(
Schema.NullOr(
Schema.Struct({
login: Schema.String,
}),
),
),
});
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
nameWithOwner: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
sshUrl: TrimmedNonEmptyString,
});
function normalizePullRequestSummary(
raw: Schema.Schema.Type<typeof RawGitHubPullRequestSchema>,
): GitHubPullRequestSummary {
const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null;
const headRepositoryOwnerLogin =
raw.headRepositoryOwner?.login ??
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
: null);
return {
number: raw.number,
title: raw.title,
url: raw.url,
baseRefName: raw.baseRefName,
headRefName: raw.headRefName,
state: normalizePullRequestState(raw),
...(typeof raw.isCrossRepository === "boolean"
? { isCrossRepository: raw.isCrossRepository }
: {}),
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
};
}
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
): GitHubRepositoryCloneUrls {
return {
nameWithOwner: raw.nameWithOwner,
url: raw.url,
sshUrl: raw.sshUrl,
};
}
function decodeGitHubJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
invalidDetail: string,
): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitHubCliError({
operation,
detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail,
cause: error,
}),
),
);
}
const makeGitHubCli = Effect.sync(() => {
@@ -119,7 +181,7 @@ const makeGitHubCli = Effect.sync(() => {
"pr",
"list",
"--head",
input.headBranch,
input.headSelector,
"--state",
"open",
"--limit",
@@ -128,21 +190,56 @@ const makeGitHubCli = Effect.sync(() => {
"number,title,url,baseRefName,headRefName",
],
}).pipe(
Effect.map((result) => result.stdout),
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
Effect.try({
try: () => parseOpenPullRequests(raw),
catch: (error: unknown) =>
new GitHubCliError({
operation: "listOpenPullRequests",
detail:
error instanceof Error
? `GitHub CLI returned invalid PR list JSON: ${error.message}`
: "GitHub CLI returned invalid PR list JSON.",
...(error !== undefined ? { cause: error } : {}),
}),
}),
raw.length === 0
? Effect.succeed([])
: decodeGitHubJson(
raw,
Schema.Array(RawGitHubPullRequestSchema),
"listOpenPullRequests",
"GitHub CLI returned invalid PR list JSON.",
),
),
Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)),
),
getPullRequest: (input) =>
execute({
cwd: input.cwd,
args: [
"pr",
"view",
input.reference,
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitHubJson(
raw,
RawGitHubPullRequestSchema,
"getPullRequest",
"GitHub CLI returned invalid pull request JSON.",
),
),
Effect.map(normalizePullRequestSummary),
),
getRepositoryCloneUrls: (input) =>
execute({
cwd: input.cwd,
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitHubJson(
raw,
RawGitHubRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitHub CLI returned invalid repository JSON.",
),
),
Effect.map(normalizeRepositoryCloneUrls),
),
createPullRequest: (input) =>
execute({
@@ -153,7 +250,7 @@ const makeGitHubCli = Effect.sync(() => {
"--base",
input.baseBranch,
"--head",
input.headBranch,
input.headSelector,
"--title",
input.title,
"--body-file",
@@ -170,6 +267,11 @@ const makeGitHubCli = Effect.sync(() => {
return trimmed.length > 0 ? trimmed : null;
}),
),
checkoutPullRequest: (input) =>
execute({
cwd: input.cwd,
args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
}).pipe(Effect.asVoid),
} satisfies GitHubCliShape;
return service;
File diff suppressed because it is too large. Load diff
+605 -64
View File
@@ -1,7 +1,12 @@
import { randomUUID } from "node:crypto";
import { realpathSync } from "node:fs";
import { Effect, FileSystem, Layer, Path } from "effect";
import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import {
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
sanitizeFeatureBranchName,
} from "@t3tools/shared/git";
import { GitManagerError } from "../Errors.ts";
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
@@ -22,6 +27,96 @@ interface PullRequestInfo extends OpenPrInfo {
updatedAt: string | null;
}
interface ResolvedPullRequest {
number: number;
title: string;
url: string;
baseBranch: string;
headBranch: string;
state: "open" | "closed" | "merged";
}
interface PullRequestHeadRemoteInfo {
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
}
interface BranchHeadContext {
localBranch: string;
headBranch: string;
headSelectors: ReadonlyArray<string>;
preferredHeadSelector: string;
remoteName: string | null;
headRepositoryNameWithOwner: string | null;
headRepositoryOwnerLogin: string | null;
isCrossRepository: boolean;
}
function parseRepositoryNameFromPullRequestUrl(url: string): string | null {
const trimmed = url.trim();
const match = /^https:\/\/github\.com\/[^/]+\/([^/]+)\/pull\/\d+(?:\/.*)?$/i.exec(trimmed);
const repositoryName = match?.[1]?.trim() ?? "";
return repositoryName.length > 0 ? repositoryName : null;
}
function resolveHeadRepositoryNameWithOwner(
pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
): string | null {
const explicitRepository = pullRequest.headRepositoryNameWithOwner?.trim() ?? "";
if (explicitRepository.length > 0) {
return explicitRepository;
}
if (!pullRequest.isCrossRepository) {
return null;
}
const ownerLogin = pullRequest.headRepositoryOwnerLogin?.trim() ?? "";
const repositoryName = parseRepositoryNameFromPullRequestUrl(pullRequest.url);
if (ownerLogin.length === 0 || !repositoryName) {
return null;
}
return `${ownerLogin}/${repositoryName}`;
}
function resolvePullRequestWorktreeLocalBranchName(
pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
): string {
if (!pullRequest.isCrossRepository) {
return pullRequest.headBranch;
}
const sanitizedHeadBranch = sanitizeBranchFragment(pullRequest.headBranch).trim();
const suffix = sanitizedHeadBranch.length > 0 ? sanitizedHeadBranch : "head";
return `t3code/pr-${pullRequest.number}/${suffix}`;
}
function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
const trimmed = url?.trim() ?? "";
if (trimmed.length === 0) {
return null;
}
const match =
/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
trimmed,
);
const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
}
function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null {
const trimmed = nameWithOwner?.trim() ?? "";
if (trimmed.length === 0) {
return null;
}
const [ownerLogin] = trimmed.split("/");
const normalizedOwnerLogin = ownerLogin?.trim() ?? "";
return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null;
}
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
if (!Array.isArray(raw)) return [];
@@ -157,6 +252,14 @@ function extractBranchFromRef(ref: string): string {
return normalized.slice(firstSlash + 1).trim();
}
function appendUnique(values: string[], next: string | null | undefined): void {
const trimmed = next?.trim() ?? "";
if (trimmed.length === 0 || values.includes(trimmed)) {
return;
}
values.push(trimmed);
}
function toStatusPr(pr: PullRequestInfo): {
number: number;
title: string;
@@ -175,72 +278,321 @@ function toStatusPr(pr: PullRequestInfo): {
};
}
function normalizePullRequestReference(reference: string): string {
const trimmed = reference.trim();
const hashNumber = /^#(\d+)$/.exec(trimmed);
return hashNumber?.[1] ?? trimmed;
}
function canonicalizeExistingPath(value: string): string {
try {
return realpathSync.native(value);
} catch {
return value;
}
}
function toResolvedPullRequest(pr: {
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
state?: "open" | "closed" | "merged";
}): ResolvedPullRequest {
return {
number: pr.number,
title: pr.title,
url: pr.url,
baseBranch: pr.baseRefName,
headBranch: pr.headRefName,
state: pr.state ?? "open",
};
}
function shouldPreferSshRemote(url: string | null): boolean {
if (!url) return false;
const trimmed = url.trim();
return trimmed.startsWith("git@") || trimmed.startsWith("ssh://");
}
function toPullRequestHeadRemoteInfo(pr: {
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
}): PullRequestHeadRemoteInfo {
return {
...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
...(pr.headRepositoryNameWithOwner !== undefined
? { headRepositoryNameWithOwner: pr.headRepositoryNameWithOwner }
: {}),
...(pr.headRepositoryOwnerLogin !== undefined
? { headRepositoryOwnerLogin: pr.headRepositoryOwnerLogin }
: {}),
};
}
export const makeGitManager = Effect.gen(function* () {
const gitCore = yield* GitCore;
const gitHubCli = yield* GitHubCli;
const textGeneration = yield* TextGeneration;
const configurePullRequestHeadUpstream = (
cwd: string,
pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
localBranch = pullRequest.headBranch,
) =>
Effect.gen(function* () {
const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
if (repositoryNameWithOwner.length === 0) {
return;
}
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url");
const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
const preferredRemoteName =
pullRequest.headRepositoryOwnerLogin?.trim() ||
repositoryNameWithOwner.split("/")[0]?.trim() ||
"fork";
const remoteName = yield* gitCore.ensureRemote({
cwd,
preferredName: preferredRemoteName,
url: remoteUrl,
});
yield* gitCore.setBranchUpstream({
cwd,
branch: localBranch,
remoteName,
remoteBranch: pullRequest.headBranch,
});
}).pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitManager.configurePullRequestHeadUpstream: failed to configure upstream for ${localBranch} -> ${pullRequest.headBranch} in ${cwd}: ${error.message}`,
).pipe(Effect.asVoid),
),
);
const materializePullRequestHeadBranch = (
cwd: string,
pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
localBranch = pullRequest.headBranch,
) =>
Effect.gen(function* () {
const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
if (repositoryNameWithOwner.length === 0) {
yield* gitCore.fetchPullRequestBranch({
cwd,
prNumber: pullRequest.number,
branch: localBranch,
});
return;
}
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url");
const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
const preferredRemoteName =
pullRequest.headRepositoryOwnerLogin?.trim() ||
repositoryNameWithOwner.split("/")[0]?.trim() ||
"fork";
const remoteName = yield* gitCore.ensureRemote({
cwd,
preferredName: preferredRemoteName,
url: remoteUrl,
});
yield* gitCore.fetchRemoteBranch({
cwd,
remoteName,
remoteBranch: pullRequest.headBranch,
localBranch,
});
yield* gitCore.setBranchUpstream({
cwd,
branch: localBranch,
remoteName,
remoteBranch: pullRequest.headBranch,
});
}).pipe(
Effect.catch(() =>
gitCore.fetchPullRequestBranch({
cwd,
prNumber: pullRequest.number,
branch: localBranch,
}),
),
);
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const findOpenPr = (cwd: string, branch: string) =>
gitHubCli
.listOpenPullRequests({
cwd,
headBranch: branch,
limit: 1,
})
.pipe(
Effect.map((prs) => {
const [first] = prs;
if (!first) {
return null;
}
const readConfigValueNullable = (cwd: string, key: string) =>
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
const resolveRemoteRepositoryContext = (cwd: string, remoteName: string | null) =>
Effect.gen(function* () {
if (!remoteName) {
return {
repositoryNameWithOwner: null,
ownerLogin: null,
};
}
const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
return {
repositoryNameWithOwner,
ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
};
});
const resolveBranchHeadContext = (
cwd: string,
details: { branch: string; upstreamRef: string | null },
) =>
Effect.gen(function* () {
const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`);
const headBranchFromUpstream = details.upstreamRef
? extractBranchFromRef(details.upstreamRef)
: "";
const headBranch =
headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch;
const [remoteRepository, originRepository] = yield* Effect.all(
[
resolveRemoteRepositoryContext(cwd, remoteName),
resolveRemoteRepositoryContext(cwd, "origin"),
],
{ concurrency: "unbounded" },
);
const isCrossRepository =
remoteRepository.repositoryNameWithOwner !== null &&
originRepository.repositoryNameWithOwner !== null
? remoteRepository.repositoryNameWithOwner.toLowerCase() !==
originRepository.repositoryNameWithOwner.toLowerCase()
: remoteName !== null &&
remoteName !== "origin" &&
remoteRepository.repositoryNameWithOwner !== null;
const ownerHeadSelector =
remoteRepository.ownerLogin && headBranch.length > 0
? `${remoteRepository.ownerLogin}:${headBranch}`
: null;
const remoteAliasHeadSelector =
remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null;
const shouldProbeRemoteOwnedSelectors =
isCrossRepository || (remoteName !== null && remoteName !== "origin");
const headSelectors: string[] = [];
if (isCrossRepository && shouldProbeRemoteOwnedSelectors) {
appendUnique(headSelectors, ownerHeadSelector);
appendUnique(
headSelectors,
remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
);
}
appendUnique(headSelectors, details.branch);
appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null);
if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) {
appendUnique(headSelectors, ownerHeadSelector);
appendUnique(
headSelectors,
remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
);
}
return {
localBranch: details.branch,
headBranch,
headSelectors,
preferredHeadSelector:
ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,
remoteName,
headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,
headRepositoryOwnerLogin: remoteRepository.ownerLogin,
isCrossRepository,
} satisfies BranchHeadContext;
});
const findOpenPr = (cwd: string, headSelectors: ReadonlyArray<string>) =>
Effect.gen(function* () {
for (const headSelector of headSelectors) {
const pullRequests = yield* gitHubCli.listOpenPullRequests({
cwd,
headSelector,
limit: 1,
});
const [firstPullRequest] = pullRequests;
if (firstPullRequest) {
return {
number: first.number,
title: first.title,
url: first.url,
baseRefName: first.baseRefName,
headRefName: first.headRefName,
number: firstPullRequest.number,
title: firstPullRequest.title,
url: firstPullRequest.url,
baseRefName: firstPullRequest.baseRefName,
headRefName: firstPullRequest.headRefName,
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),
});
return null;
});
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
const findLatestPr = (cwd: string, details: { branch: string; upstreamRef: string | null }) =>
Effect.gen(function* () {
const headContext = yield* resolveBranchHeadContext(cwd, details);
const parsedByNumber = new Map<number, PullRequestInfo>();
for (const headSelector of headContext.headSelectors) {
const stdout = yield* gitHubCli
.execute({
cwd,
args: [
"pr",
"list",
"--head",
headSelector,
"--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) {
continue;
}
const parsedJson = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) =>
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
});
for (const pr of parsePullRequestList(parsedJson)) {
parsedByNumber.set(pr.number, pr);
}
}
const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => {
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
return right - left;
@@ -253,12 +605,17 @@ export const makeGitManager = Effect.gen(function* () {
return parsed[0] ?? null;
});
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
const resolveBaseBranch = (
cwd: string,
branch: string,
upstreamRef: string | null,
headContext: Pick<BranchHeadContext, "isCrossRepository">,
) =>
Effect.gen(function* () {
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
if (configured) return configured;
if (upstreamRef) {
if (upstreamRef && !headContext.isCrossRepository) {
const upstreamBranch = extractBranchFromRef(upstreamRef);
if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
return upstreamBranch;
@@ -281,9 +638,11 @@ export const makeGitManager = Effect.gen(function* () {
commitMessage?: string;
/** When true, also produce a semantic feature branch name. */
includeBranch?: boolean;
filePaths?: readonly string[];
model?: string;
}) =>
Effect.gen(function* () {
const context = yield* gitCore.prepareCommitContext(input.cwd);
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
if (!context) {
return null;
}
@@ -307,6 +666,7 @@ export const makeGitManager = Effect.gen(function* () {
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
...(input.includeBranch ? { includeBranch: true } : {}),
...(input.model ? { model: input.model } : {}),
})
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
@@ -323,6 +683,8 @@ export const makeGitManager = Effect.gen(function* () {
branch: string | null,
commitMessage?: string,
preResolvedSuggestion?: CommitAndBranchSuggestion,
filePaths?: readonly string[],
model?: string,
) =>
Effect.gen(function* () {
const suggestion =
@@ -331,6 +693,8 @@ export const makeGitManager = Effect.gen(function* () {
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
...(model ? { model } : {}),
}));
if (!suggestion) {
return { status: "skipped_no_changes" as const };
@@ -344,7 +708,7 @@ export const makeGitManager = Effect.gen(function* () {
};
});
const runPrStep = (cwd: string, fallbackBranch: string | null) =>
const runPrStep = (cwd: string, fallbackBranch: string | null, model?: string) =>
Effect.gen(function* () {
const details = yield* gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
@@ -361,7 +725,12 @@ export const makeGitManager = Effect.gen(function* () {
);
}
const existing = yield* findOpenPr(cwd, branch);
const headContext = yield* resolveBranchHeadContext(cwd, {
branch,
upstreamRef: details.upstreamRef,
});
const existing = yield* findOpenPr(cwd, headContext.headSelectors);
if (existing) {
return {
status: "opened_existing" as const,
@@ -373,16 +742,17 @@ export const makeGitManager = Effect.gen(function* () {
};
}
const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef);
const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext);
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
const generated = yield* textGeneration.generatePrContent({
cwd,
baseBranch,
headBranch: branch,
headBranch: headContext.headBranch,
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
...(model ? { model } : {}),
});
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
@@ -397,18 +767,18 @@ export const makeGitManager = Effect.gen(function* () {
.createPullRequest({
cwd,
baseBranch,
headBranch: branch,
headSelector: headContext.preferredHeadSelector,
title: generated.title,
bodyFile,
})
.pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));
const created = yield* findOpenPr(cwd, branch);
const created = yield* findOpenPr(cwd, headContext.headSelectors);
if (!created) {
return {
status: "created" as const,
baseBranch,
headBranch: branch,
headBranch: headContext.headBranch,
title: generated.title,
};
}
@@ -428,7 +798,10 @@ export const makeGitManager = Effect.gen(function* () {
const pr =
details.branch !== null
? yield* findLatestPr(input.cwd, details.branch).pipe(
? yield* findLatestPr(input.cwd, {
branch: details.branch,
upstreamRef: details.upstreamRef,
}).pipe(
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
Effect.catch(() => Effect.succeed(null)),
)
@@ -445,13 +818,175 @@ export const makeGitManager = Effect.gen(function* () {
};
});
const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fnUntraced(
function* (input) {
const pullRequest = yield* gitHubCli
.getPullRequest({
cwd: input.cwd,
reference: normalizePullRequestReference(input.reference),
})
.pipe(Effect.map((resolved) => toResolvedPullRequest(resolved)));
return { pullRequest };
},
);
const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fnUntraced(
function* (input) {
const normalizedReference = normalizePullRequestReference(input.reference);
const rootWorktreePath = canonicalizeExistingPath(input.cwd);
const pullRequestSummary = yield* gitHubCli.getPullRequest({
cwd: input.cwd,
reference: normalizedReference,
});
const pullRequest = toResolvedPullRequest(pullRequestSummary);
if (input.mode === "local") {
yield* gitHubCli.checkoutPullRequest({
cwd: input.cwd,
reference: normalizedReference,
force: true,
});
const details = yield* gitCore.statusDetails(input.cwd);
yield* configurePullRequestHeadUpstream(
input.cwd,
{
...pullRequest,
...toPullRequestHeadRemoteInfo(pullRequestSummary),
},
details.branch ?? pullRequest.headBranch,
);
return {
pullRequest,
branch: details.branch ?? pullRequest.headBranch,
worktreePath: null,
};
}
const ensureExistingWorktreeUpstream = (worktreePath: string) =>
Effect.gen(function* () {
const details = yield* gitCore.statusDetails(worktreePath);
yield* configurePullRequestHeadUpstream(
worktreePath,
{
...pullRequest,
...toPullRequestHeadRemoteInfo(pullRequestSummary),
},
details.branch ?? pullRequest.headBranch,
);
});
const pullRequestWithRemoteInfo = {
...pullRequest,
...toPullRequestHeadRemoteInfo(pullRequestSummary),
} as const;
const localPullRequestBranch =
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
const findLocalHeadBranch = (cwd: string) =>
gitCore.listBranches({ cwd }).pipe(
Effect.map((result) => {
const localBranch = result.branches.find(
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
);
if (localBranch) {
return localBranch;
}
if (localPullRequestBranch === pullRequest.headBranch) {
return null;
}
return (
result.branches.find(
(branch) =>
!branch.isRemote &&
branch.name === pullRequest.headBranch &&
branch.worktreePath !== null &&
canonicalizeExistingPath(branch.worktreePath) !== rootWorktreePath,
) ?? null
);
}),
);
const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd);
const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath
? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
: null;
if (
existingBranchBeforeFetch?.worktreePath &&
existingBranchBeforeFetchPath !== rootWorktreePath
) {
yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath);
return {
pullRequest,
branch: localPullRequestBranch,
worktreePath: existingBranchBeforeFetch.worktreePath,
};
}
if (existingBranchBeforeFetchPath === rootWorktreePath) {
return yield* gitManagerError(
"preparePullRequestThread",
"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
);
}
yield* materializePullRequestHeadBranch(
input.cwd,
pullRequestWithRemoteInfo,
localPullRequestBranch,
);
const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd);
const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath
? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
: null;
if (
existingBranchAfterFetch?.worktreePath &&
existingBranchAfterFetchPath !== rootWorktreePath
) {
yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath);
return {
pullRequest,
branch: localPullRequestBranch,
worktreePath: existingBranchAfterFetch.worktreePath,
};
}
if (existingBranchAfterFetchPath === rootWorktreePath) {
return yield* gitManagerError(
"preparePullRequestThread",
"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
);
}
const worktree = yield* gitCore.createWorktree({
cwd: input.cwd,
branch: localPullRequestBranch,
path: null,
});
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
return {
pullRequest,
branch: worktree.worktree.branch,
worktreePath: worktree.worktree.path,
};
},
);
const runFeatureBranchStep = (
cwd: string,
branch: string | null,
commitMessage?: string,
filePaths?: readonly string[],
model?: string,
) =>
Effect.gen(function* () {
const suggestion = yield* resolveCommitAndBranchSuggestion({
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
includeBranch: true,
...(model ? { model } : {}),
});
if (!suggestion) {
return yield* gitManagerError(
@@ -499,6 +1034,8 @@ export const makeGitManager = Effect.gen(function* () {
input.cwd,
initialStatus.branch,
input.commitMessage,
input.filePaths,
input.textGenerationModel,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
@@ -514,6 +1051,8 @@ export const makeGitManager = Effect.gen(function* () {
currentBranch,
commitMessageForStep,
preResolvedCommitSuggestion,
input.filePaths,
input.textGenerationModel,
);
const push = wantsPush
@@ -521,7 +1060,7 @@ export const makeGitManager = Effect.gen(function* () {
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? yield* runPrStep(input.cwd, currentBranch)
? yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel)
: { status: "skipped_not_requested" as const };
return {
@@ -536,6 +1075,8 @@ export const makeGitManager = Effect.gen(function* () {
return {
status,
resolvePullRequest,
preparePullRequestThread,
runStackedAction,
} satisfies GitManagerShape;
});
+53
View File
@@ -56,6 +56,32 @@ export interface GitRenameBranchResult {
branch: string;
}
export interface GitFetchPullRequestBranchInput {
cwd: string;
prNumber: number;
branch: string;
}
export interface GitEnsureRemoteInput {
cwd: string;
preferredName: string;
url: string;
}
export interface GitFetchRemoteBranchInput {
cwd: string;
remoteName: string;
remoteBranch: string;
localBranch: string;
}
export interface GitSetBranchUpstreamInput {
cwd: string;
branch: string;
remoteName: string;
remoteBranch: string;
}
/**
* GitCoreShape - Service API for low-level Git repository interactions.
*/
@@ -75,6 +101,7 @@ export interface GitCoreShape {
*/
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
/**
@@ -129,6 +156,32 @@ export interface GitCoreShape {
input: GitCreateWorktreeInput,
) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>;
/**
* Materialize a GitHub pull request head as a local branch without switching checkout.
*/
readonly fetchPullRequestBranch: (
input: GitFetchPullRequestBranchInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Ensure a named remote exists for the provided URL, returning the reused or created remote name.
*/
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
/**
* Fetch a remote branch into a local branch without checkout.
*/
readonly fetchRemoteBranch: (
input: GitFetchRemoteBranchInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Set the upstream tracking branch for a local branch.
*/
readonly setBranchUpstream: (
input: GitSetBranchUpstreamInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Remove an existing worktree.
*/
+37 -2
View File
@@ -17,6 +17,16 @@ export interface GitHubPullRequestSummary {
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
readonly state?: "open" | "closed" | "merged";
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
}
export interface GitHubRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
readonly sshUrl: string;
}
/**
@@ -37,17 +47,33 @@ export interface GitHubCliShape {
*/
readonly listOpenPullRequests: (input: {
readonly cwd: string;
readonly headBranch: string;
readonly headSelector: string;
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
/**
* Resolve a pull request by URL, number, or branch-ish identifier.
*/
readonly getPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
/**
* Resolve clone URLs for a GitHub repository.
*/
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
/**
* Create a pull request from branch context and body file.
*/
readonly createPullRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
readonly headBranch: string;
readonly headSelector: string;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitHubCliError>;
@@ -58,6 +84,15 @@ export interface GitHubCliShape {
readonly getDefaultBranch: (input: {
readonly cwd: string;
}) => Effect.Effect<string | null, GitHubCliError>;
/**
* Checkout a pull request into the current repository worktree.
*/
readonly checkoutPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, GitHubCliError>;
}
/**
@@ -7,6 +7,10 @@
* @module GitManager
*/
import {
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusInput,
@@ -27,6 +31,20 @@ export interface GitManagerShape {
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
/**
* Resolve a pull request by URL/number against the current repository.
*/
readonly resolvePullRequest: (
input: GitPullRequestRefInput,
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
/**
* Prepare a new thread workspace from a pull request in local or worktree mode.
*/
readonly preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
/**
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first.
@@ -19,6 +19,8 @@ export interface CommitMessageGenerationInput {
stagedPatch: string;
/** When true, the model also returns a semantic branch name for the change. */
includeBranch?: boolean;
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
model?: string;
}
export interface CommitMessageGenerationResult {
@@ -35,6 +37,8 @@ export interface PrContentGenerationInput {
commitSummary: string;
diffSummary: string;
diffPatch: string;
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
model?: string;
}
export interface PrContentGenerationResult {
@@ -46,6 +50,8 @@ export interface BranchNameGenerationInput {
cwd: string;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
model?: string;
}
export interface BranchNameGenerationResult {
+3 -1
View File
@@ -211,7 +211,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
});
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
assert.isFalse(configState.keybindings.some((entry) => String(entry.command) === "invalid.command"));
assert.isFalse(
configState.keybindings.some((entry) => String(entry.command) === "invalid.command"),
);
assert.deepEqual(configState.issues, [
{
kind: "keybindings.invalid-entry",
+8 -34
View File
@@ -42,7 +42,6 @@ import {
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { watchFileWithStatPolling } from "./watchFileWithStatPolling";
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
"KeybindingsConfigParseError",
@@ -507,17 +506,9 @@ export interface KeybindingsShape {
readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
/**
* Subscribe to keybindings config change events.
*
* Returns a scoped subscription. Callers should subscribe in the
* current fiber (not inside a fork) to avoid missing events due to
* lazy subscription setup in `Stream.fromPubSub`.
* Stream of keybindings config change events.
*/
readonly subscribeChanges: Effect.Effect<
PubSub.Subscription<KeybindingsChangeEvent>,
never,
Scope.Scope
>;
readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;
/**
* Upsert a keybinding rule and persist the resulting configuration.
@@ -569,7 +560,7 @@ const makeKeybindings = Effect.gen(function* () {
configPath: keybindingsConfigPath,
detail: "failed to read keybindings config",
cause,
}),
}),
),
);
@@ -824,12 +815,8 @@ const makeKeybindings = Effect.gen(function* () {
),
);
const revalidateAndEmitSafely = revalidateAndEmit.pipe(
Effect.ignoreCause({ log: true }),
);
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
// fs.watch (inotify/kqueue) gives instant detection on most platforms
// but can silently miss events on Linux containers.
yield* Stream.runForEach(fs.watch(keybindingsConfigDir), (event) => {
const isTargetConfigEvent =
event.path === keybindingsConfigFile ||
@@ -839,22 +826,7 @@ const makeKeybindings = Effect.gen(function* () {
return Effect.void;
}
return revalidateAndEmitSafely;
}).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkIn(watcherScope),
Effect.asVoid,
);
// fs.watchFile (stat-based polling on libuv timers) as a reliable
// backup. Unlike an Effect.sleep loop in a forked fiber, libuv
// timers fire regardless of Effect fiber scheduling pressure.
yield* Stream.runForEach(
watchFileWithStatPolling({
filePath: keybindingsConfigPath,
pollIntervalMs: 100,
}),
() => revalidateAndEmitSafely,
).pipe(Effect.forkIn(watcherScope), Effect.asVoid);
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);
});
const start = Effect.gen(function* () {
@@ -886,7 +858,9 @@ const makeKeybindings = Effect.gen(function* () {
syncDefaultKeybindingsOnStartup,
loadConfigState: loadConfigStateFromCacheOrDisk,
getSnapshot: loadConfigStateFromCacheOrDisk,
subscribeChanges: PubSub.subscribe(changesPubSub),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
upsertKeybindingRule: (rule) =>
upsertSemaphore.withPermits(1)(
Effect.gen(function* () {
+66 -56
View File
@@ -1,8 +1,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import { FileSystem, Path, Effect } from "effect";
import {
isCommandAvailable,
@@ -10,12 +9,19 @@ import {
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open";
import { Effect } from "effect";
import { assertSuccess } from "@effect/vitest/utils";
describe("resolveEditorLaunch", () => {
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
it.effect("returns commands for command-based editors", () =>
Effect.gen(function* () {
const antigravityLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "antigravity" },
"darwin",
);
assert.deepEqual(antigravityLaunch, {
command: "agy",
args: ["/tmp/workspace"],
});
const cursorLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "cursor" },
"darwin",
@@ -117,7 +123,7 @@ describe("resolveEditorLaunch", () => {
);
});
describe("launchDetached", () => {
it.layer(NodeServices.layer)("launchDetached", (it) => {
it.effect("resolves when command can be spawned", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
@@ -139,26 +145,20 @@ 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");
it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
it.effect("resolves win32 commands with PATHEXT", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
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 = {
@@ -168,55 +168,65 @@ describe("isCommandAvailable", () => {
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");
it.effect("does not treat bare files without executable extension as available on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
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");
it.effect("appends PATHEXT for commands with non-executable extensions on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
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);
});
});
});
it.effect("uses platform-specific PATH delimiter for platform overrides", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
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");
it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
it.effect("returns installed editors for command launches", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fs.writeFileString(path.join(dir, "cursor.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
const editors = resolveAvailableEditors("win32", {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["cursor", "file-manager"]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
}),
);
});
+4 -4
View File
@@ -40,7 +40,9 @@ interface CommandAvailabilityOptions {
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
return (
(editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target)
);
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
@@ -239,9 +241,7 @@ export const launchDetached = (launch: EditorLaunch) =>
});
} catch (error) {
return resume(
Effect.fail(
new OpenError({ message: "failed to spawn detached process", cause: error }),
),
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
);
}
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -44,7 +44,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex";
readonly provider: ProviderKind;
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -70,7 +70,7 @@ function createProviderServiceHarness(
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A, never>;
const listSessions = () =>
hasSession
? Effect.succeed([
? Effect.succeed([
{
provider: providerName,
status: "ready",
@@ -235,6 +235,7 @@ describe("CheckpointReactor", () => {
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly providerSessionCwd?: string;
readonly providerName?: ProviderKind;
}) {
const cwd = createGitRepository();
tempDirs.push(cwd);
@@ -242,7 +243,7 @@ describe("CheckpointReactor", () => {
cwd,
options?.hasSession ?? true,
options?.providerSessionCwd ?? cwd,
"codex",
options?.providerName ?? "codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
@@ -353,7 +354,7 @@ describe("CheckpointReactor", () => {
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-1"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
@@ -368,7 +369,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-1"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
@@ -429,7 +430,7 @@ describe("CheckpointReactor", () => {
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-main"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-main"),
@@ -445,7 +446,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-aux"),
@@ -463,7 +464,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-main"),
@@ -477,6 +478,67 @@ describe("CheckpointReactor", () => {
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
});
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: "claudeAgent",
});
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
harness.provider.emit({
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
});
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-claude-1"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
payload: { state: "completed" },
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
const thread = await waitForThread(
harness.engine,
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
).toBe(true);
});
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
@@ -503,7 +565,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-missing-baseline"),
@@ -592,7 +654,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-missing-cwd"),
@@ -638,7 +700,7 @@ describe("CheckpointReactor", () => {
type: "checkpoint.captured",
eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-3"),
@@ -688,7 +750,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-runtime-failure"),
@@ -699,7 +761,7 @@ describe("CheckpointReactor", () => {
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-after-runtime-failure"),
@@ -792,6 +854,75 @@ describe("CheckpointReactor", () => {
).toBe(false);
});
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: "claudeAgent" });
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
status: "ready",
files: [],
checkpointTurnCount: 1,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-2"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
status: "ready",
files: [],
checkpointTurnCount: 2,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
createdAt,
}),
);
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
});
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
const harness = await createHarness();
const createdAt = new Date().toISOString();
@@ -2,6 +2,7 @@ import {
CommandId,
EventId,
MessageId,
type ProjectId,
ThreadId,
TurnId,
type OrchestrationEvent,
@@ -15,6 +16,7 @@ import {
checkpointRefForThreadTurn,
resolveThreadWorkspaceCwd,
} from "../../checkpointing/Utils.ts";
import { clearWorkspaceIndexCache } from "../../workspaceEntries.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
@@ -87,6 +89,7 @@ const make = Effect.gen(function* () {
detail: input.detail,
},
turnId: null,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
@@ -111,6 +114,7 @@ const make = Effect.gen(function* () {
detail: input.detail,
},
turnId: input.turnId,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
@@ -146,6 +150,179 @@ const make = Effect.gen(function* () {
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
// Resolves the workspace CWD for checkpoint operations, preferring the
// active provider session CWD and falling back to the thread/project config.
// Returns undefined when no CWD can be determined or the workspace is not
// a git repository.
const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
readonly preferSessionRuntime: boolean;
}): Effect.fn.Return<string | undefined> {
const fromSession = yield* resolveSessionRuntimeForThread(input.threadId);
const fromThread = resolveThreadWorkspaceCwd({
thread: input.thread,
projects: input.projects,
});
const cwd = input.preferSessionRuntime
? (Option.match(fromSession, {
onNone: () => undefined,
onSome: (runtime) => runtime.cwd,
}) ?? fromThread)
: (fromThread ??
Option.match(fromSession, {
onNone: () => undefined,
onSome: (runtime) => runtime.cwd,
}));
if (!cwd) {
return undefined;
}
if (!isGitWorkspace(cwd)) {
return undefined;
}
return cwd;
});
// Shared tail for both capture paths: creates the git checkpoint ref, diffs
// it against the previous turn, then dispatches the domain events to update
// the orchestration read model.
const captureAndDispatchCheckpoint = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly turnId: TurnId;
readonly thread: {
readonly messages: ReadonlyArray<{
readonly id: MessageId;
readonly role: string;
readonly turnId: TurnId | null;
}>;
};
readonly cwd: string;
readonly turnCount: number;
readonly status: "ready" | "missing" | "error";
readonly assistantMessageId: MessageId | undefined;
readonly createdAt: string;
}) {
const fromTurnCount = Math.max(0, input.turnCount - 1);
const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, fromTurnCount);
const targetCheckpointRef = checkpointRefForThreadTurn(input.threadId, input.turnCount);
const fromCheckpointExists = yield* checkpointStore.hasCheckpointRef({
cwd: input.cwd,
checkpointRef: fromCheckpointRef,
});
if (!fromCheckpointExists) {
yield* Effect.logWarning("checkpoint capture missing pre-turn baseline", {
threadId: input.threadId,
turnId: input.turnId,
fromTurnCount,
});
}
yield* checkpointStore.captureCheckpoint({
cwd: input.cwd,
checkpointRef: targetCheckpointRef,
});
// Invalidate the workspace entry cache so the @-mention file picker
// reflects files created or deleted during this turn.
clearWorkspaceIndexCache(input.cwd);
const files = yield* checkpointStore
.diffCheckpoints({
cwd: input.cwd,
fromCheckpointRef,
toCheckpointRef: targetCheckpointRef,
fallbackFromToHead: false,
})
.pipe(
Effect.map((diff) =>
parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
path: file.path,
kind: "modified" as const,
additions: file.additions,
deletions: file.deletions,
})),
),
Effect.tapError((error) =>
appendCaptureFailureActivity({
threadId: input.threadId,
turnId: input.turnId,
detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
createdAt: input.createdAt,
}),
),
Effect.catch((error) =>
Effect.logWarning("failed to derive checkpoint file summary", {
threadId: input.threadId,
turnId: input.turnId,
turnCount: input.turnCount,
detail: error.message,
}).pipe(Effect.as([])),
),
);
const assistantMessageId =
input.assistantMessageId ??
input.thread.messages
.toReversed()
.find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ??
MessageId.makeUnsafe(`assistant:${input.turnId}`);
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: serverCommandId("checkpoint-turn-diff-complete"),
threadId: input.threadId,
turnId: input.turnId,
completedAt: input.createdAt,
checkpointRef: targetCheckpointRef,
status: input.status,
files,
assistantMessageId,
checkpointTurnCount: input.turnCount,
createdAt: input.createdAt,
});
yield* receiptBus.publish({
type: "checkpoint.diff.finalized",
threadId: input.threadId,
turnId: input.turnId,
checkpointTurnCount: input.turnCount,
checkpointRef: targetCheckpointRef,
status: input.status,
createdAt: input.createdAt,
});
yield* receiptBus.publish({
type: "turn.processing.quiesced",
threadId: input.threadId,
turnId: input.turnId,
checkpointTurnCount: input.turnCount,
createdAt: input.createdAt,
});
yield* orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: serverCommandId("checkpoint-captured-activity"),
threadId: input.threadId,
activity: {
id: EventId.makeUnsafe(crypto.randomUUID()),
tone: "info",
kind: "checkpoint.captured",
summary: "Checkpoint captured",
payload: {
turnCount: input.turnCount,
status: input.status,
},
turnId: input.turnId,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
});
});
// Captures a real git checkpoint when a turn completes via a runtime event.
const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
) {
@@ -165,150 +342,111 @@ const make = Effect.gen(function* () {
return;
}
if (thread.checkpoints.some((checkpoint) => checkpoint.turnId === turnId)) {
// Only skip if a real (non-placeholder) checkpoint already exists for this turn.
// ProviderRuntimeIngestion may insert placeholder entries with status "missing"
// before this reactor runs; those must not prevent real git capture.
if (
thread.checkpoints.some(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
)
) {
return;
}
const sessionRuntime = yield* resolveSessionRuntimeForThread(thread.id);
const checkpointCwd =
Option.match(sessionRuntime, {
onNone: () => undefined,
onSome: (runtime) => runtime.cwd,
}) ??
resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
});
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: true,
});
if (!checkpointCwd) {
yield* Effect.logWarning("checkpoint capture skipped: no active provider session cwd", {
threadId: thread.id,
turnId,
});
return;
}
if (!isGitWorkspace(checkpointCwd)) {
yield* Effect.logDebug("checkpoint capture skipped for non-git workspace", {
threadId: thread.id,
turnId,
cwd: checkpointCwd,
});
return;
}
// If a placeholder checkpoint exists for this turn, reuse its turn count
// instead of incrementing past it.
const existingPlaceholder = thread.checkpoints.find(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
);
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const nextTurnCount = currentTurnCount + 1;
const fromTurnCount = Math.max(0, nextTurnCount - 1);
const fromCheckpointRef = checkpointRefForThreadTurn(thread.id, fromTurnCount);
const targetCheckpointRef = checkpointRefForThreadTurn(thread.id, nextTurnCount);
const nextTurnCount = existingPlaceholder
? existingPlaceholder.checkpointTurnCount
: currentTurnCount + 1;
const fromCheckpointExists = yield* checkpointStore.hasCheckpointRef({
yield* captureAndDispatchCheckpoint({
threadId: thread.id,
turnId,
thread,
cwd: checkpointCwd,
checkpointRef: fromCheckpointRef,
turnCount: nextTurnCount,
status: checkpointStatusFromRuntime(event.payload.state),
assistantMessageId: undefined,
createdAt: event.createdAt,
});
if (!fromCheckpointExists) {
yield* Effect.logWarning("checkpoint completion missing pre-turn baseline", {
threadId: thread.id,
turnId,
fromTurnCount,
});
});
// Captures a real git checkpoint when a placeholder checkpoint (status "missing")
// is detected via a domain event. This replaces the placeholder with a real
// git-ref-based checkpoint.
//
// ProviderRuntimeIngestion creates placeholder checkpoints on turn.diff.updated
// events from the Codex runtime. This handler fires when the corresponding
// domain event arrives, allowing the reactor to capture the actual filesystem
// state into a git ref and dispatch a replacement checkpoint.
const captureCheckpointFromPlaceholder = Effect.fnUntraced(function* (
event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
) {
const { threadId, turnId, checkpointTurnCount, status } = event.payload;
// Only replace placeholders; skip events from our own real captures.
if (status !== "missing") {
return;
}
yield* checkpointStore.captureCheckpoint({
cwd: checkpointCwd,
checkpointRef: targetCheckpointRef,
});
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
if (!thread) {
yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
threadId,
});
return;
}
const files = yield* checkpointStore
.diffCheckpoints({
cwd: checkpointCwd,
fromCheckpointRef,
toCheckpointRef: targetCheckpointRef,
fallbackFromToHead: false,
})
.pipe(
Effect.map((diff) =>
parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
path: file.path,
kind: "modified" as const,
additions: file.additions,
deletions: file.deletions,
})),
),
Effect.tapError((error) =>
appendCaptureFailureActivity({
threadId: thread.id,
turnId,
detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
createdAt: event.createdAt,
}),
),
Effect.catch((error) =>
Effect.logWarning("failed to derive checkpoint file summary", {
threadId: thread.id,
turnId,
turnCount: nextTurnCount,
detail: error.message,
}).pipe(Effect.as([])),
),
// If a real checkpoint already exists for this turn, skip.
if (
thread.checkpoints.some(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
)
) {
yield* Effect.logDebug(
"checkpoint capture from placeholder skipped: real checkpoint already exists",
{ threadId, turnId },
);
return;
}
const assistantMessageId =
thread.messages
.toReversed()
.find((entry) => entry.role === "assistant" && entry.turnId === turnId)?.id ??
MessageId.makeUnsafe(`assistant:${turnId}`);
const checkpointCwd = yield* resolveCheckpointCwd({
threadId,
thread,
projects: readModel.projects,
preferSessionRuntime: true,
});
if (!checkpointCwd) {
return;
}
const now = event.createdAt;
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: serverCommandId("checkpoint-turn-diff-complete"),
threadId: thread.id,
yield* captureAndDispatchCheckpoint({
threadId,
turnId,
completedAt: now,
checkpointRef: targetCheckpointRef,
status: checkpointStatusFromRuntime(event.payload.state),
files,
assistantMessageId,
checkpointTurnCount: nextTurnCount,
createdAt: now,
});
yield* receiptBus.publish({
type: "checkpoint.diff.finalized",
threadId: thread.id,
turnId,
checkpointTurnCount: nextTurnCount,
checkpointRef: targetCheckpointRef,
status: checkpointStatusFromRuntime(event.payload.state),
createdAt: now,
});
yield* receiptBus.publish({
type: "turn.processing.quiesced",
threadId: thread.id,
turnId,
checkpointTurnCount: nextTurnCount,
createdAt: now,
});
yield* orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: serverCommandId("checkpoint-captured-activity"),
threadId: thread.id,
activity: {
id: EventId.makeUnsafe(crypto.randomUUID()),
tone: "info",
kind: "checkpoint.captured",
summary: "Checkpoint captured",
payload: {
turnCount: nextTurnCount,
status: event.payload.state,
},
turnId,
createdAt: now,
},
createdAt: now,
thread,
cwd: checkpointCwd,
turnCount: checkpointTurnCount,
status: "ready",
assistantMessageId: event.payload.assistantMessageId ?? undefined,
createdAt: event.payload.completedAt,
});
});
@@ -326,24 +464,13 @@ const make = Effect.gen(function* () {
return;
}
const checkpointCwdFromThreadOrProject = resolveThreadWorkspaceCwd({
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: false,
});
const checkpointCwd =
checkpointCwdFromThreadOrProject ??
Option.match(yield* resolveSessionRuntimeForThread(thread.id), {
onNone: () => undefined,
onSome: (runtime) => runtime.cwd,
});
if (!checkpointCwd) {
yield* Effect.logWarning("checkpoint pre-turn capture skipped: no workspace cwd", {
threadId: thread.id,
turnId,
});
return;
}
if (!isGitWorkspace(checkpointCwd)) {
return;
}
@@ -396,23 +523,13 @@ const make = Effect.gen(function* () {
return;
}
const checkpointCwdFromThreadOrProject = resolveThreadWorkspaceCwd({
const checkpointCwd = yield* resolveCheckpointCwd({
threadId,
thread,
projects: readModel.projects,
preferSessionRuntime: false,
});
const checkpointCwd =
checkpointCwdFromThreadOrProject ??
Option.match(yield* resolveSessionRuntimeForThread(threadId), {
onNone: () => undefined,
onSome: (runtime) => runtime.cwd,
});
if (!checkpointCwd) {
yield* Effect.logWarning("checkpoint pre-turn capture skipped: no workspace cwd", {
threadId,
});
return;
}
if (!isGitWorkspace(checkpointCwd)) {
return;
}
@@ -526,6 +643,10 @@ const make = Effect.gen(function* () {
return;
}
// Invalidate the workspace entry cache so the @-mention file picker
// reflects the reverted filesystem state.
clearWorkspaceIndexCache(sessionRuntime.value.cwd);
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
if (rolledBackTurns > 0) {
yield* providerService.rollbackConversation({
@@ -583,6 +704,25 @@ const make = Effect.gen(function* () {
}),
),
);
return;
}
// When ProviderRuntimeIngestion creates a placeholder checkpoint (status "missing")
// from a turn.diff.updated runtime event, capture the real git checkpoint to
// replace it. The providerService.streamEvents PubSub does not reliably deliver
// turn.completed runtime events to this reactor (shared subscription), so
// reacting to the domain event is the reliable path.
if (event.type === "thread.turn-diff-completed") {
yield* captureCheckpointFromPlaceholder(event).pipe(
Effect.catch((error) =>
appendCaptureFailureActivity({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
detail: error.message,
createdAt: new Date().toISOString(),
}).pipe(Effect.catch(() => Effect.void)),
),
);
}
});
@@ -635,7 +775,8 @@ const make = Effect.gen(function* () {
if (
event.type !== "thread.turn-start-requested" &&
event.type !== "thread.message-sent" &&
event.type !== "thread.checkpoint-revert-requested"
event.type !== "thread.checkpoint-revert-requested" &&
event.type !== "thread.turn-diff-completed"
) {
return Effect.void;
}
@@ -49,13 +49,6 @@ function commandToAggregateRef(command: OrchestrationCommand): {
}
}
function formatDispatchError(error: OrchestrationDispatchError): string {
if (error instanceof Error && error.message.length > 0) {
return error.message;
}
return String(error);
}
const makeOrchestrationEngine = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const eventStore = yield* OrchestrationEventStore;
@@ -191,7 +184,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
acceptedAt: new Date().toISOString(),
resultSequence: readModel.snapshotSequence,
status: "rejected",
error: formatDispatchError(error),
error: error.message,
})
.pipe(Effect.catch(() => Effect.void));
}
@@ -229,14 +222,16 @@ const makeOrchestrationEngine = Effect.gen(function* () {
return yield* Deferred.await(result);
});
const streamDomainEvents: OrchestrationEngineShape["streamDomainEvents"] =
Stream.fromPubSub(eventPubSub);
return {
getReadModel,
readEvents,
dispatch,
streamDomainEvents,
// Each access creates a fresh PubSub subscription so that multiple
// consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)
// each independently receive all domain events.
get streamDomainEvents(): OrchestrationEngineShape["streamDomainEvents"] {
return Stream.fromPubSub(eventPubSub);
},
} satisfies OrchestrationEngineShape;
});
File diff suppressed because it is too large. Load diff
@@ -22,6 +22,10 @@ import {
type ProjectionThreadProposedPlan,
ProjectionThreadProposedPlanRepository,
} from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import {
type ProjectionThreadWorkUnit,
ProjectionThreadWorkUnitRepository,
} from "../../persistence/Services/ProjectionThreadWorkUnits.ts";
import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
import {
type ProjectionTurn,
@@ -34,6 +38,7 @@ import { ProjectionStateRepositoryLive } from "../../persistence/Layers/Projecti
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
import { ProjectionThreadWorkUnitRepositoryLive } from "../../persistence/Layers/ProjectionThreadWorkUnits.ts";
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
@@ -55,6 +60,7 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
threadMessages: "projection.thread-messages",
threadProposedPlans: "projection.thread-proposed-plans",
threadActivities: "projection.thread-activities",
threadWorkUnits: "projection.thread-work-units",
threadSessions: "projection.thread-sessions",
threadTurns: "projection.thread-turns",
checkpoints: "projection.checkpoints",
@@ -78,9 +84,8 @@ interface AttachmentSideEffects {
}
const materializeAttachmentsForProjection = Effect.fn(
(input: {
readonly attachments: ReadonlyArray<ChatAttachment>;
}) => Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
(input: { readonly attachments: ReadonlyArray<ChatAttachment> }) =>
Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
);
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
@@ -215,6 +220,28 @@ function retainProjectionProposedPlansAfterRevert(
);
}
function retainProjectionWorkUnitsAfterRevert(
workUnits: ReadonlyArray<ProjectionThreadWorkUnit>,
turns: ReadonlyArray<ProjectionTurn>,
turnCount: number,
): ReadonlyArray<ProjectionThreadWorkUnit> {
const retainedTurnIds = new Set<string>(
turns
.filter(
(turn) =>
turn.turnId !== null &&
turn.checkpointTurnCount !== null &&
turn.checkpointTurnCount <= turnCount,
)
.flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),
);
const retained = workUnits.filter((workUnit) => retainedTurnIds.has(workUnit.turnId));
const retainedIds = new Set(retained.map((workUnit) => workUnit.workUnitId));
return retained.filter(
(workUnit) => workUnit.parentWorkUnitId === null || retainedIds.has(workUnit.parentWorkUnitId),
);
}
function collectThreadAttachmentRelativePaths(
threadId: string,
messages: ReadonlyArray<ProjectionThreadMessage>,
@@ -336,7 +363,6 @@ const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSid
},
{ concurrency: 1 },
);
});
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
@@ -348,6 +374,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
const projectionThreadWorkUnitRepository = yield* ProjectionThreadWorkUnitRepository;
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
@@ -655,6 +682,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
threadId: event.payload.threadId,
turnId: event.payload.proposedPlan.turnId,
planMarkdown: event.payload.proposedPlan.planMarkdown,
implementedAt: event.payload.proposedPlan.implementedAt,
implementationThreadId: event.payload.proposedPlan.implementationThreadId,
createdAt: event.payload.proposedPlan.createdAt,
updatedAt: event.payload.proposedPlan.updatedAt,
});
@@ -705,6 +734,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
activityId: event.payload.activity.id,
threadId: event.payload.threadId,
turnId: event.payload.activity.turnId,
workUnitId: event.payload.activity.workUnitId,
tone: event.payload.activity.tone,
kind: event.payload.activity.kind,
summary: event.payload.activity.summary,
@@ -748,6 +778,64 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadWorkUnitsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.work-unit-upserted":
yield* projectionThreadWorkUnitRepository.upsert({
workUnitId: event.payload.workUnit.id,
threadId: event.payload.threadId,
turnId: event.payload.workUnit.turnId,
parentWorkUnitId: event.payload.workUnit.parentWorkUnitId,
kind: event.payload.workUnit.kind,
state: event.payload.workUnit.state,
title: event.payload.workUnit.title,
detail: event.payload.workUnit.detail,
spawnedByActivityId: event.payload.workUnit.spawnedByActivityId,
...(event.payload.workUnit.providerRefs !== undefined
? { providerRefs: event.payload.workUnit.providerRefs }
: {}),
startedAt: event.payload.workUnit.startedAt,
updatedAt: event.payload.workUnit.updatedAt,
completedAt: event.payload.workUnit.completedAt,
});
return;
case "thread.reverted": {
const existingRows = yield* projectionThreadWorkUnitRepository.listByThreadId({
threadId: event.payload.threadId,
});
if (existingRows.length === 0) {
return;
}
const existingTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
const keptRows = retainProjectionWorkUnitsAfterRevert(
existingRows,
existingTurns,
event.payload.turnCount,
);
if (keptRows.length === existingRows.length) {
return;
}
yield* projectionThreadWorkUnitRepository.deleteByThreadId({
threadId: event.payload.threadId,
});
yield* Effect.forEach(keptRows, projectionThreadWorkUnitRepository.upsert, {
concurrency: 1,
}).pipe(Effect.asVoid);
return;
}
default:
return;
}
});
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
@@ -777,6 +865,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
yield* projectionTurnRepository.replacePendingTurnStart({
threadId: event.payload.threadId,
messageId: event.payload.messageId,
sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null,
sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null,
requestedAt: event.payload.createdAt,
});
return;
@@ -806,6 +896,16 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
pendingMessageId:
existingTurn.value.pendingMessageId ??
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),
sourceProposedPlanThreadId:
existingTurn.value.sourceProposedPlanThreadId ??
(Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanThreadId
: null),
sourceProposedPlanId:
existingTurn.value.sourceProposedPlanId ??
(Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanId
: null),
startedAt:
existingTurn.value.startedAt ??
(Option.isSome(pendingTurnStart)
@@ -824,6 +924,12 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
pendingMessageId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.messageId
: null,
sourceProposedPlanThreadId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanThreadId
: null,
sourceProposedPlanId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanId
: null,
assistantMessageId: null,
state: "running",
requestedAt: Option.isSome(pendingTurnStart)
@@ -877,6 +983,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.messageId,
state: event.payload.streaming ? "running" : "completed",
requestedAt: event.payload.createdAt,
@@ -912,6 +1020,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: null,
state: "interrupted",
requestedAt: event.payload.createdAt,
@@ -956,6 +1066,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.assistantMessageId,
state: nextState,
requestedAt: event.payload.completedAt,
@@ -1110,6 +1222,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
apply: applyThreadActivitiesProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadWorkUnits,
apply: applyThreadWorkUnitsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
apply: applyThreadSessionsProjection,
@@ -1227,6 +1343,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
Layer.provideMerge(ProjectionThreadWorkUnitRepositoryLive),
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
Layer.provideMerge(ProjectionTurnRepositoryLive),
Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),
@@ -5,6 +5,7 @@ import {
ProjectId,
ThreadId,
TurnId,
WorkUnitId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
@@ -20,6 +21,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
const asWorkUnitId = (value: string): WorkUnitId => WorkUnitId.makeUnsafe(value);
const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
@@ -33,6 +35,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_state`;
yield* sql`DELETE FROM projection_thread_proposed_plans`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
@@ -108,11 +111,35 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
)
`;
yield* sql`
INSERT INTO projection_thread_proposed_plans (
plan_id,
thread_id,
turn_id,
plan_markdown,
implemented_at,
implementation_thread_id,
created_at,
updated_at
)
VALUES (
'plan-1',
'thread-1',
'turn-1',
'# Ship it',
'2026-02-24T00:00:05.500Z',
'thread-2',
'2026-02-24T00:00:05.000Z',
'2026-02-24T00:00:05.500Z'
)
`;
yield* sql`
INSERT INTO projection_thread_activities (
activity_id,
thread_id,
turn_id,
work_unit_id,
tone,
kind,
summary,
@@ -123,6 +150,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'activity-1',
'thread-1',
'turn-1',
'wu:thread-1:turn:turn-1:root',
'info',
'runtime.note',
'provider started',
@@ -131,6 +159,39 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
)
`;
yield* sql`
INSERT INTO projection_thread_work_units (
work_unit_id,
thread_id,
turn_id,
parent_work_unit_id,
kind,
state,
title,
detail,
spawned_by_activity_id,
provider_refs_json,
started_at,
updated_at,
completed_at
)
VALUES (
'wu:thread-1:turn:turn-1:root',
'thread-1',
'turn-1',
NULL,
'primary_agent',
'completed',
'Primary agent',
NULL,
NULL,
'{"providerTurnId":"provider-turn-1"}',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z'
)
`;
yield* sql`
INSERT INTO projection_thread_sessions (
thread_id,
@@ -161,6 +222,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
@@ -175,6 +238,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'thread-1',
'turn-1',
NULL,
'thread-1',
'plan-1',
'message-1',
'completed',
'2026-02-24T00:00:08.000Z',
@@ -245,6 +310,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
startedAt: "2026-02-24T00:00:08.000Z",
completedAt: "2026-02-24T00:00:08.000Z",
assistantMessageId: asMessageId("message-1"),
sourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-1"),
planId: "plan-1",
},
},
createdAt: "2026-02-24T00:00:02.000Z",
updatedAt: "2026-02-24T00:00:03.000Z",
@@ -260,7 +329,17 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
updatedAt: "2026-02-24T00:00:05.000Z",
},
],
proposedPlans: [],
proposedPlans: [
{
id: "plan-1",
turnId: asTurnId("turn-1"),
planMarkdown: "# Ship it",
implementedAt: "2026-02-24T00:00:05.500Z",
implementationThreadId: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-02-24T00:00:05.000Z",
updatedAt: "2026-02-24T00:00:05.500Z",
},
],
activities: [
{
id: asEventId("activity-1"),
@@ -269,9 +348,28 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
summary: "provider started",
payload: { stage: "start" },
turnId: asTurnId("turn-1"),
workUnitId: asWorkUnitId("wu:thread-1:turn:turn-1:root"),
createdAt: "2026-02-24T00:00:06.000Z",
},
],
workUnits: [
{
id: asWorkUnitId("wu:thread-1:turn:turn-1:root"),
turnId: asTurnId("turn-1"),
parentWorkUnitId: null,
kind: "primary_agent",
state: "completed",
title: "Primary agent",
detail: null,
spawnedByActivityId: null,
providerRefs: {
providerTurnId: "provider-turn-1",
},
startedAt: "2026-02-24T00:00:08.000Z",
updatedAt: "2026-02-24T00:00:08.000Z",
completedAt: "2026-02-24T00:00:08.000Z",
},
],
checkpoints: [
{
turnId: asTurnId("turn-1"),
@@ -4,8 +4,10 @@ import {
MessageId,
NonNegativeInt,
OrchestrationCheckpointFile,
OrchestrationProposedPlanId,
OrchestrationReadModel,
ProjectScript,
ThreadId,
TurnId,
type OrchestrationCheckpointSummary,
type OrchestrationLatestTurn,
@@ -15,6 +17,7 @@ import {
type OrchestrationSession,
type OrchestrationThread,
type OrchestrationThreadActivity,
type OrchestrationWorkUnit,
} from "@t3tools/contracts";
import { Effect, Layer, Schema, Struct } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -32,6 +35,7 @@ import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import { ProjectionThreadWorkUnit } from "../../persistence/Services/ProjectionThreadWorkUnits.ts";
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
@@ -60,6 +64,13 @@ const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
sequence: Schema.NullOr(NonNegativeInt),
}),
);
const ProjectionThreadWorkUnitDbRowSchema = ProjectionThreadWorkUnit.mapFields(
Struct.assign({
providerRefs: Schema.NullOr(
Schema.fromJsonString(ProjectionThreadWorkUnit.fields.providerRefs),
),
}),
);
const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;
const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
Struct.assign({
@@ -74,6 +85,8 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
startedAt: Schema.NullOr(IsoDateTime),
completedAt: Schema.NullOr(IsoDateTime),
assistantMessageId: Schema.NullOr(MessageId),
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
});
const ProjectionStateDbRowSchema = ProjectionState;
@@ -83,6 +96,7 @@ const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
ORCHESTRATION_PROJECTOR_NAMES.threadWorkUnits,
ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
] as const;
@@ -200,6 +214,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
plan_markdown AS "planMarkdown",
implemented_at AS "implementedAt",
implementation_thread_id AS "implementationThreadId",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_proposed_plans
@@ -216,6 +232,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
work_unit_id AS "workUnitId",
tone,
kind,
summary,
@@ -232,6 +249,30 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listThreadWorkUnitRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadWorkUnitDbRowSchema,
execute: () =>
sql`
SELECT
work_unit_id AS "workUnitId",
thread_id AS "threadId",
turn_id AS "turnId",
parent_work_unit_id AS "parentWorkUnitId",
kind,
state,
title,
detail,
spawned_by_activity_id AS "spawnedByActivityId",
provider_refs_json AS "providerRefs",
started_at AS "startedAt",
updated_at AS "updatedAt",
completed_at AS "completedAt"
FROM projection_thread_work_units
ORDER BY thread_id ASC, started_at ASC, work_unit_id ASC
`,
});
const listThreadSessionRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadSessionDbRowSchema,
@@ -284,7 +325,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
requested_at AS "requestedAt",
started_at AS "startedAt",
completed_at AS "completedAt",
assistant_message_id AS "assistantMessageId"
assistant_message_id AS "assistantMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId"
FROM projection_turns
WHERE turn_id IS NOT NULL
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
@@ -314,6 +357,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
messageRows,
proposedPlanRows,
activityRows,
workUnitRows,
sessionRows,
checkpointRows,
latestTurnRows,
@@ -359,6 +403,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadWorkUnitRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getSnapshot:listThreadWorkUnits:query",
"ProjectionSnapshotQuery.getSnapshot:listThreadWorkUnits:decodeRows",
),
),
),
listThreadSessionRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -396,6 +448,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
const workUnitsByThread = new Map<string, Array<OrchestrationWorkUnit>>();
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
const sessionsByThread = new Map<string, OrchestrationSession>();
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
@@ -435,6 +488,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
id: row.planId,
turnId: row.turnId,
planMarkdown: row.planMarkdown,
implementedAt: row.implementedAt,
implementationThreadId: row.implementationThreadId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
});
@@ -451,12 +506,33 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
workUnitId: row.workUnitId,
...(row.sequence !== null ? { sequence: row.sequence } : {}),
createdAt: row.createdAt,
});
activitiesByThread.set(row.threadId, threadActivities);
}
for (const row of workUnitRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
const threadWorkUnits = workUnitsByThread.get(row.threadId) ?? [];
threadWorkUnits.push({
id: row.workUnitId,
turnId: row.turnId,
parentWorkUnitId: row.parentWorkUnitId,
kind: row.kind,
state: row.state,
title: row.title,
detail: row.detail,
spawnedByActivityId: row.spawnedByActivityId,
...(row.providerRefs !== null ? { providerRefs: row.providerRefs } : {}),
startedAt: row.startedAt,
updatedAt: row.updatedAt,
completedAt: row.completedAt,
});
workUnitsByThread.set(row.threadId, threadWorkUnits);
}
for (const row of checkpointRows) {
updatedAt = maxIso(updatedAt, row.completedAt);
const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];
@@ -497,6 +573,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
startedAt: row.startedAt,
completedAt: row.completedAt,
assistantMessageId: row.assistantMessageId,
...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
? {
sourceProposedPlan: {
threadId: row.sourceProposedPlanThreadId,
planId: row.sourceProposedPlanId,
},
}
: {}),
});
}
@@ -540,6 +624,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
workUnits: workUnitsByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
@@ -41,7 +41,10 @@ const asApprovalRequestId = (value: string): ApprovalRequestId =>
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
async function waitFor(predicate: () => boolean | Promise<boolean>, timeoutMs = 2000): Promise<void> {
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2000,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (await predicate()) {
@@ -80,9 +83,13 @@ describe("ProviderCommandReactor", () => {
createdStateDirs.clear();
});
async function createHarness(input?: { readonly stateDir?: string }) {
async function createHarness(input?: {
readonly stateDir?: string;
readonly threadModel?: string;
}) {
const now = new Date().toISOString();
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
const threadModel = input?.threadModel ?? "gpt-5-codex";
createdStateDirs.add(stateDir);
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
let nextSessionIndex = 1;
@@ -93,7 +100,7 @@ describe("ProviderCommandReactor", () => {
typeof input === "object" &&
input !== null &&
"provider" in input &&
input.provider === "codex"
(input.provider === "codex" || input.provider === "claudeAgent")
? input.provider
: "codex";
const resumeCursor =
@@ -101,7 +108,10 @@ describe("ProviderCommandReactor", () => {
? input.resumeCursor
: undefined;
const model =
typeof input === "object" && input !== null && "model" in input && typeof input.model === "string"
typeof input === "object" &&
input !== null &&
"model" in input &&
typeof input.model === "string"
? input.model
: undefined;
const threadId =
@@ -123,7 +133,7 @@ describe("ProviderCommandReactor", () => {
: "full-access",
...(model !== undefined ? { model } : {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `cursor-${sessionIndex}` },
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
createdAt: now,
updatedAt: now,
};
@@ -222,7 +232,7 @@ describe("ProviderCommandReactor", () => {
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot: "/tmp/provider-project",
defaultModel: "gpt-5-codex",
defaultModel: threadModel,
createdAt: now,
}),
);
@@ -233,7 +243,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
model: threadModel,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -345,6 +355,106 @@ describe("ProviderCommandReactor", () => {
});
});
it("forwards claude effort options through session start and turn send", async () => {
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort"),
role: "user",
text: "hello with effort",
attachments: [],
},
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
});
it("forwards claude fast mode options through session start and turn send", async () => {
const harness = await createHarness({ threadModel: "claude-opus-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-fast-mode"),
role: "user",
text: "hello with fast mode",
attachments: [],
},
provider: "claudeAgent",
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeAgent",
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
});
});
it("forwards plan interaction mode to the provider turn request", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -383,6 +493,102 @@ describe("ProviderCommandReactor", () => {
});
});
it("rejects a first turn when requested provider conflicts with the thread model", 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-provider-first"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-first"),
role: "user",
text: "hello claude",
attachments: [],
},
provider: "claudeAgent",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession).not.toHaveBeenCalled();
expect(harness.sendTurn).not.toHaveBeenCalled();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session).toBeNull();
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
summary: "Provider turn start failed",
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
});
it("rejects a turn when the requested model belongs to a different provider", 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-model-provider-mismatch"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-model-provider-mismatch"),
role: "user",
text: "hello",
attachments: [],
},
model: "claude-sonnet-4-6",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession).not.toHaveBeenCalled();
expect(harness.sendTurn).not.toHaveBeenCalled();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("does not belong to provider 'codex'"),
},
});
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -429,6 +635,73 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts claude sessions when claude effort changes", async () => {
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort-1"),
role: "user",
text: "first claude turn",
attachments: [],
},
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "medium",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
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-claude-effort-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort-2"),
role: "user",
text: "second claude turn",
attachments: [],
},
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
provider: "claudeAgent",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
});
it("restarts the provider session when runtime mode is updated on the thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -475,7 +748,9 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return thread?.runtimeMode === "approval-required";
});
await waitFor(() => harness.startSession.mock.calls.length === 2);
@@ -501,7 +776,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
resumeCursor: { opaque: "cursor-1" },
resumeCursor: { opaque: "resume-1" },
runtimeMode: "approval-required",
});
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
@@ -514,6 +789,77 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("rejects provider changes after a thread is already bound to a session provider", 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-provider-switch-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
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-provider-switch-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-2"),
role: "user",
text: "second",
attachments: [],
},
provider: "claudeAgent",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession.mock.calls.length).toBe(1);
expect(harness.sendTurn.mock.calls.length).toBe(1);
expect(harness.stopSession.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?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerName).toBe("codex");
expect(thread?.session?.runtimeMode).toBe("approval-required");
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
});
it("does not stop the active session when restart fails before rebind", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -564,7 +910,9 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return thread?.runtimeMode === "approval-required";
});
await waitFor(() => harness.startSession.mock.calls.length === 2);
@@ -749,6 +1097,7 @@ describe("ProviderCommandReactor", () => {
requestKind: "command",
},
turnId: null,
workUnitId: null,
createdAt: now,
},
createdAt: now,
@@ -768,9 +1117,13 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
if (!thread) return false;
return thread.activities.some((activity) => activity.kind === "provider.approval.respond.failed");
return thread.activities.some(
(activity) => activity.kind === "provider.approval.respond.failed",
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
@@ -1,10 +1,11 @@
import {
type ChatAttachment,
CommandId,
DEFAULT_GIT_TEXT_GENERATION_MODEL,
EventId,
type OrchestrationEvent,
type ProviderModelOptions,
type ProviderKind,
ProviderKind,
type ProviderStartOptions,
type OrchestrationSession,
ThreadId,
@@ -17,7 +18,7 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -25,6 +26,7 @@ import {
ProviderCommandReactor,
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { inferProviderForModel } from "@t3tools/shared/model";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -74,18 +76,13 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const WORKTREE_BRANCH_PREFIX = "t3code";
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
function toErrorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
try {
return JSON.stringify(error);
} catch {
return String(error);
}
}
const sameModelOptions = (
left: ProviderModelOptions | undefined,
right: ProviderModelOptions | undefined,
): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
function isUnknownPendingApprovalRequestError(error: unknown): boolean {
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
const detail = error.detail.toLowerCase();
return (
@@ -93,7 +90,7 @@ function isUnknownPendingApprovalRequestError(error: unknown): boolean {
detail.includes("unknown pending permission request")
);
}
const message = toErrorMessage(error).toLowerCase();
const message = Cause.pretty(cause);
return (
message.includes("unknown pending approval request") ||
message.includes("unknown pending permission request")
@@ -146,6 +143,7 @@ const make = Effect.gen(function* () {
);
const threadProviderOptions = new Map<string, ProviderStartOptions>();
const threadModelOptions = new Map<string, ProviderModelOptions>();
const appendProviderFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -175,6 +173,7 @@ const make = Effect.gen(function* () {
...(input.requestId ? { requestId: input.requestId } : {}),
},
turnId: input.turnId,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
@@ -215,9 +214,30 @@ const make = Effect.gen(function* () {
}
const desiredRuntimeMode = thread.runtimeMode;
const currentProvider: ProviderKind | undefined =
thread.session?.providerName === "codex" ? thread.session.providerName : undefined;
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(
thread.session?.providerName,
)
? thread.session.providerName
: undefined;
const threadProvider: ProviderKind = currentProvider ?? inferProviderForModel(thread.model);
if (options?.provider !== undefined && options.provider !== threadProvider) {
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${options.provider}'.`,
});
}
if (
options?.model !== undefined &&
inferProviderForModel(options.model, threadProvider) !== threadProvider
) {
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Model '${options.model}' does not belong to provider '${threadProvider}' for thread '${threadId}'.`,
});
}
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
const desiredModel = options?.model ?? thread.model;
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
@@ -241,7 +261,9 @@ const make = Effect.gen(function* () {
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(desiredModel ? { model: desiredModel } : {}),
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
...(options?.providerOptions !== undefined ? { providerOptions: options.providerOptions } : {}),
...(options?.providerOptions !== undefined
? { providerOptions: options.providerOptions }
: {}),
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
runtimeMode: desiredRuntimeMode,
});
@@ -275,13 +297,23 @@ const make = Effect.gen(function* () {
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
const previousModelOptions = threadModelOptions.get(threadId);
const shouldRestartForModelOptionsChange =
currentProvider === "claudeAgent" &&
options?.modelOptions !== undefined &&
!sameModelOptions(previousModelOptions, options.modelOptions);
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
if (
!runtimeModeChanged &&
!providerChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelOptionsChange
) {
return existingSessionThreadId;
}
const resumeCursor =
providerChanged || shouldRestartForModelChange
providerChanged || shouldRestartForModelChange || shouldRestartForModelOptionsChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
yield* Effect.logInfo("provider command reactor restarting provider session", {
@@ -295,6 +327,7 @@ const make = Effect.gen(function* () {
providerChanged,
modelChanged,
shouldRestartForModelChange,
shouldRestartForModelOptionsChange,
hasResumeCursor: resumeCursor !== undefined,
});
const restartedSession = yield* startProviderSession({
@@ -334,15 +367,18 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
if (input.providerOptions !== undefined) {
threadProviderOptions.set(input.threadId, input.providerOptions);
}
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
if (input.providerOptions !== undefined) {
threadProviderOptions.set(input.threadId, input.providerOptions);
}
if (input.modelOptions !== undefined) {
threadModelOptions.set(input.threadId, input.modelOptions);
}
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
const activeSession = yield* providerService
@@ -399,6 +435,7 @@ const make = Effect.gen(function* () {
cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
})
.pipe(
Effect.catch((error) =>
@@ -483,7 +520,18 @@ const make = Effect.gen(function* () {
: {}),
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
});
}).pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
}),
),
);
});
const processTurnInterruptRequested = Effect.fnUntraced(function* (
@@ -538,19 +586,17 @@ const make = Effect.gen(function* () {
.pipe(
Effect.catchCause((cause) =>
Effect.gen(function* () {
const error = Cause.squash(cause);
const detail = toErrorMessage(error);
yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.approval.respond.failed",
summary: "Provider approval response failed",
detail,
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
if (!isUnknownPendingApprovalRequestError(error)) return;
if (!isUnknownPendingApprovalRequestError(cause)) return;
}),
),
);
@@ -584,17 +630,14 @@ const make = Effect.gen(function* () {
})
.pipe(
Effect.catchCause((cause) =>
Effect.gen(function* () {
const error = Cause.squash(cause);
yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: toErrorMessage(error),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
}),
),
);
@@ -637,8 +680,12 @@ const make = Effect.gen(function* () {
return;
}
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
const cachedModelOptions = threadModelOptions.get(event.payload.threadId);
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
...(cachedProviderOptions !== undefined ? { providerOptions: cachedProviderOptions } : {}),
...(cachedProviderOptions !== undefined
? { providerOptions: cachedProviderOptions }
: {}),
...(cachedModelOptions !== undefined ? { modelOptions: cachedModelOptions } : {}),
});
return;
}
@@ -2,7 +2,12 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { OrchestrationReadModel, ProviderRuntimeEvent } from "@t3tools/contracts";
import type {
OrchestrationReadModel,
ProviderKind,
ProviderRuntimeEvent,
ProviderSession,
} from "@t3tools/contracts";
import {
ApprovalRequestId,
CommandId,
@@ -45,7 +50,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex";
readonly provider: ProviderKind;
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -57,6 +62,7 @@ type LegacyProviderRuntimeEvent = {
function createProviderServiceHarness() {
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
const runtimeSessions: ProviderSession[] = [];
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: ProviderServiceShape = {
@@ -66,12 +72,21 @@ function createProviderServiceHarness() {
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession: () => unsupported(),
listSessions: () => Effect.succeed([]),
listSessions: () => Effect.succeed([...runtimeSessions]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
const setSession = (session: ProviderSession): void => {
const existingIndex = runtimeSessions.findIndex((entry) => entry.threadId === session.threadId);
if (existingIndex >= 0) {
runtimeSessions[existingIndex] = session;
return;
}
runtimeSessions.push(session);
};
const emit = (event: LegacyProviderRuntimeEvent): void => {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
};
@@ -79,6 +94,7 @@ function createProviderServiceHarness() {
return {
service,
emit,
setSession,
};
}
@@ -86,11 +102,12 @@ async function waitForThread(
engine: OrchestrationEngineShape,
predicate: (thread: ProviderRuntimeTestThread) => boolean,
timeoutMs = 2000,
threadId: ThreadId = asThreadId("thread-1"),
) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<ProviderRuntimeTestThread> => {
const readModel = await Effect.runPromise(engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === threadId);
if (thread && predicate(thread)) {
return thread;
}
@@ -108,6 +125,7 @@ type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number]
type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
type ProviderRuntimeTestWorkUnit = ProviderRuntimeTestThread["workUnits"][number];
type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
describe("ProviderRuntimeIngestion", () => {
@@ -150,6 +168,7 @@ describe("ProviderRuntimeIngestion", () => {
);
const layer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
@@ -205,10 +224,19 @@ describe("ProviderRuntimeIngestion", () => {
createdAt,
}),
);
provider.setSession({
provider: "codex",
status: "ready",
runtimeMode: "approval-required",
threadId: ThreadId.makeUnsafe("thread-1"),
createdAt,
updatedAt: createdAt,
});
return {
engine,
emit: provider.emit,
setProviderSession: provider.setSession,
drain,
};
}
@@ -380,7 +408,9 @@ describe("ProviderRuntimeIngestion", () => {
await harness.drain();
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?.session?.status).toBe("running");
expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle");
@@ -400,6 +430,60 @@ describe("ProviderRuntimeIngestion", () => {
);
});
it("accepts claude turn lifecycle when seeded thread id is a synthetic placeholder", async () => {
const harness = await createHarness();
const seededAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-seed-claude-placeholder"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: seededAt,
lastError: null,
},
createdAt: seededAt,
}),
);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-claude-placeholder"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-claude-placeholder",
);
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-claude-placeholder"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
status: "completed",
});
await waitForThread(
harness.engine,
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
);
});
it("ignores auxiliary turn completions from a different provider thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -621,7 +705,499 @@ describe("ProviderRuntimeIngestion", () => {
const proposedPlan = thread.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-plan-final",
);
expect(proposedPlan?.planMarkdown).toBe("## Ship plan\n\n- wire projection\n- render follow-up");
expect(proposedPlan?.planMarkdown).toBe(
"## Ship plan\n\n- wire projection\n- render follow-up",
);
});
it("marks the source proposed plan implemented only after the target turn starts", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
const targetThreadId = asThreadId("thread-implement");
const sourceTurnId = asTurnId("turn-plan-source");
const targetTurnId = asTurnId("turn-plan-implement");
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target"),
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target"),
threadId: targetThreadId,
session: {
threadId: targetThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
harness.setProviderSession({
provider: "codex",
status: "ready",
runtimeMode: "approval-required",
threadId: targetThreadId,
createdAt,
updatedAt: createdAt,
activeTurnId: targetTurnId,
});
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
payload: {
planMarkdown: "# Source plan",
},
});
const sourceThreadWithPlan = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) =>
entry.id === "plan:thread-plan:turn:turn-plan-source",
);
expect(sourcePlan).toBeDefined();
if (!sourcePlan) {
throw new Error("Expected source plan to exist.");
}
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target"),
role: "user",
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
attachments: [],
},
sourceProposedPlan: {
threadId: sourceThreadId,
planId: sourcePlan.id,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
const sourceThreadBeforeStart = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === sourcePlan.id && proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
expect(
sourceThreadBeforeStart.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementedAt: null,
implementationThreadId: null,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-plan-target-started"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: targetTurnId,
});
const sourceThreadAfterStart = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === sourcePlan.id &&
proposedPlan.implementedAt !== null &&
proposedPlan.implementationThreadId === targetThreadId,
),
2_000,
sourceThreadId,
);
expect(
sourceThreadAfterStart.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementationThreadId: "thread-implement",
});
});
it("does not mark the source proposed plan implemented for a rejected turn.started event", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
const targetThreadId = asThreadId("thread-1");
const sourceTurnId = asTurnId("turn-plan-source");
const activeTurnId = asTurnId("turn-already-running");
const staleTurnId = asTurnId("turn-stale-start");
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-guarded"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
harness.setProviderSession({
provider: "codex",
status: "running",
runtimeMode: "approval-required",
threadId: targetThreadId,
createdAt,
updatedAt: createdAt,
activeTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-already-running"),
provider: "codex",
createdAt,
threadId: targetThreadId,
turnId: activeTurnId,
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === activeTurnId,
2_000,
targetThreadId,
);
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed-guarded"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
payload: {
planMarkdown: "# Source plan",
},
});
const sourceThreadWithPlan = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) =>
entry.id === "plan:thread-plan:turn:turn-plan-source",
);
expect(sourcePlan).toBeDefined();
if (!sourcePlan) {
throw new Error("Expected source plan to exist.");
}
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-guarded"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target-guarded"),
role: "user",
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
attachments: [],
},
sourceProposedPlan: {
threadId: sourceThreadId,
planId: sourcePlan.id,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-stale-plan-implementation"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: staleTurnId,
});
await harness.drain();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const sourceThreadAfterRejectedStart = readModel.threads.find(
(entry) => entry.id === sourceThreadId,
);
expect(
sourceThreadAfterRejectedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementedAt: null,
implementationThreadId: null,
});
const targetThreadAfterRejectedStart = readModel.threads.find(
(entry) => entry.id === targetThreadId,
);
expect(targetThreadAfterRejectedStart?.session?.status).toBe("running");
expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId);
});
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
const targetThreadId = asThreadId("thread-implement");
const sourceTurnId = asTurnId("turn-plan-source");
const expectedTurnId = asTurnId("turn-plan-implement");
const replayedTurnId = asTurnId("turn-replayed");
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-unrelated"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-unrelated"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target-unrelated"),
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target-unrelated"),
threadId: targetThreadId,
session: {
threadId: targetThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed-unrelated"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
payload: {
planMarkdown: "# Source plan",
},
});
const sourceThreadWithPlan = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) =>
entry.id === "plan:thread-plan:turn:turn-plan-source",
);
expect(sourcePlan).toBeDefined();
if (!sourcePlan) {
throw new Error("Expected source plan to exist.");
}
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-unrelated"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target-unrelated"),
role: "user",
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
attachments: [],
},
sourceProposedPlan: {
threadId: sourceThreadId,
planId: sourcePlan.id,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
harness.setProviderSession({
provider: "codex",
status: "running",
runtimeMode: "approval-required",
threadId: targetThreadId,
createdAt,
updatedAt: createdAt,
activeTurnId: expectedTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-unrelated-plan-implementation"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: replayedTurnId,
});
await harness.drain();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const sourceThreadAfterUnrelatedStart = readModel.threads.find(
(entry) => entry.id === sourceThreadId,
);
expect(
sourceThreadAfterUnrelatedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementedAt: null,
implementationThreadId: null,
});
});
it("finalizes buffered proposed-plan deltas into a first-class proposed plan on turn completion", async () => {
@@ -684,7 +1260,8 @@ describe("ProviderRuntimeIngestion", () => {
),
);
const proposedPlan = thread.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-plan-buffer",
(entry: ProviderRuntimeTestProposedPlan) =>
entry.id === "plan:thread-1:turn:turn-plan-buffer",
);
expect(proposedPlan?.planMarkdown).toBe("## Buffered plan\n\n- first\n- second");
});
@@ -1092,6 +1669,50 @@ describe("ProviderRuntimeIngestion", () => {
expect(thread.session?.lastError).toBe("runtime exploded");
});
it("keeps the session running when a runtime.warning arrives during an active turn", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-warning-turn-started"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-warning"),
payload: {},
});
harness.emit({
type: "runtime.warning",
eventId: asEventId("evt-warning-runtime"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-warning"),
payload: {
message: "Reconnecting... 2/5",
detail: {
willRetry: true,
},
},
});
const thread = await waitForThread(
harness.engine,
(entry) =>
entry.session?.status === "running" &&
entry.session?.activeTurnId === "turn-warning" &&
entry.activities.some(
(activity: ProviderRuntimeTestActivity) =>
activity.id === "evt-warning-runtime" && activity.kind === "runtime.warning",
),
);
expect(thread.session?.status).toBe("running");
expect(thread.session?.activeTurnId).toBe("turn-warning");
expect(thread.session?.lastError).toBeNull();
});
it("maps session/thread lifecycle and item.started into session/activity projections", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1289,6 +1910,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
itemId: "call-collab-1",
payload: {
taskId: "turn-task-1",
taskType: "plan",
@@ -1302,9 +1924,11 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
itemId: "call-collab-1",
payload: {
taskId: "turn-task-1",
description: "Comparing the desktop rollout chunks to the app-server stream.",
summary: "Code reviewer is validating the desktop rollout chunks.",
},
});
@@ -1315,6 +1939,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
itemId: "call-collab-1",
payload: {
taskId: "turn-task-1",
status: "completed",
@@ -1367,11 +1992,44 @@ describe("ProviderRuntimeIngestion", () => {
expect(started?.kind).toBe("task.started");
expect(started?.summary).toBe("Plan task started");
expect(progress?.kind).toBe("task.progress");
expect(progressPayload?.detail).toBe(
"Comparing the desktop rollout chunks to the app-server stream.",
expect(progressPayload?.detail).toBe("Code reviewer is validating the desktop rollout chunks.");
expect(progressPayload?.summary).toBe(
"Code reviewer is validating the desktop rollout chunks.",
);
expect(completed?.kind).toBe("task.completed");
expect(completedPayload?.detail).toBe("<proposed_plan>\n# Plan title\n</proposed_plan>");
expect(started?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
expect(progress?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
expect(completed?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
expect(
thread.workUnits.find(
(entry: ProviderRuntimeTestWorkUnit) => entry.id === "wu:thread-1:turn:turn-task-1:root",
),
).toMatchObject({
id: "wu:thread-1:turn:turn-task-1:root",
turnId: "turn-task-1",
parentWorkUnitId: null,
kind: "primary_agent",
state: "running",
title: "Primary agent",
});
expect(
thread.workUnits.find(
(entry: ProviderRuntimeTestWorkUnit) =>
entry.id === "wu:thread-1:turn:turn-task-1:task:turn-task-1",
),
).toMatchObject({
id: "wu:thread-1:turn:turn-task-1:task:turn-task-1",
turnId: "turn-task-1",
parentWorkUnitId: "wu:thread-1:turn:turn-task-1:root",
kind: "delegated_agent",
state: "completed",
title: "<proposed_plan>\n# Plan title\n</proposed_plan>",
providerRefs: {
runtimeTaskId: "turn-task-1",
runtimeItemId: "call-collab-1",
},
});
expect(
thread.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-task-1",
@@ -4,9 +4,14 @@ import {
CommandId,
MessageId,
type OrchestrationEvent,
type OrchestrationProposedPlanId,
CheckpointRef,
isToolLifecycleItemType,
RuntimeTaskId,
ThreadId,
TurnId,
WorkUnitId,
type OrchestrationThread,
type OrchestrationThreadActivity,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
@@ -14,6 +19,8 @@ import { Cache, Cause, Duration, Effect, Layer, Option, Ref, Stream } from "effe
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { isGitRepository } from "../../git/isRepo.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -25,6 +32,10 @@ import {
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
const rootWorkUnitIdForTurn = (threadId: ThreadId, turnId: TurnId): WorkUnitId =>
WorkUnitId.makeUnsafe(`wu:${threadId}:turn:${turnId}:root`);
const taskWorkUnitIdForTurn = (threadId: ThreadId, turnId: TurnId, taskId: string): WorkUnitId =>
WorkUnitId.makeUnsafe(`wu:${threadId}:turn:${turnId}:task:${taskId}`);
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
@@ -173,16 +184,55 @@ function requestKindFromCanonicalRequestType(
}
}
function isToolLifecycleItemType(itemType: string): boolean {
return (
itemType === "command_execution" ||
itemType === "file_change" ||
itemType === "mcp_tool_call" ||
itemType === "dynamic_tool_call" ||
itemType === "collab_agent_tool_call" ||
itemType === "web_search" ||
itemType === "image_view"
);
function workUnitIdForRuntimeEvent(event: ProviderRuntimeEvent): WorkUnitId | null {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return null;
}
if (
event.type === "task.started" ||
event.type === "task.progress" ||
event.type === "task.completed"
) {
return taskWorkUnitIdForTurn(event.threadId, turnId, String(event.payload.taskId));
}
return rootWorkUnitIdForTurn(event.threadId, turnId);
}
function runtimeTurnStateToWorkUnitState(
state: "completed" | "failed" | "interrupted" | "cancelled",
): "completed" | "failed" | "stopped" | "cancelled" {
switch (state) {
case "failed":
return "failed";
case "interrupted":
return "stopped";
case "cancelled":
return "cancelled";
case "completed":
return "completed";
}
}
function runtimeTaskStateToWorkUnitState(
state: "completed" | "failed" | "stopped",
): "completed" | "failed" | "stopped" {
switch (state) {
case "failed":
return "failed";
case "stopped":
return "stopped";
case "completed":
return "completed";
}
}
function providerTurnWorkUnitRefs(
event: ProviderRuntimeEvent,
): NonNullable<OrchestrationThread["workUnits"][number]["providerRefs"]> | undefined {
return event.providerRefs?.providerTurnId !== undefined
? { providerTurnId: event.providerRefs.providerTurnId }
: undefined;
}
function runtimeEventToActivities(
@@ -194,6 +244,7 @@ function runtimeEventToActivities(
? { sequence: eventWithSequence.sessionSequence }
: {};
})();
const maybeWorkUnit = { workUnitId: workUnitIdForRuntimeEvent(event) };
switch (event.type) {
case "request.opened": {
if (event.payload.requestType === "tool_user_input") {
@@ -221,6 +272,7 @@ function runtimeEventToActivities(
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -245,6 +297,7 @@ function runtimeEventToActivities(
...(event.payload.decision ? { decision: event.payload.decision } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -266,6 +319,7 @@ function runtimeEventToActivities(
message: truncateDetail(message),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -284,6 +338,7 @@ function runtimeEventToActivities(
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -304,6 +359,7 @@ function runtimeEventToActivities(
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -322,6 +378,7 @@ function runtimeEventToActivities(
questions: event.payload.questions,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -340,6 +397,7 @@ function runtimeEventToActivities(
answers: event.payload.answers,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -366,6 +424,7 @@ function runtimeEventToActivities(
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -381,11 +440,13 @@ function runtimeEventToActivities(
summary: "Reasoning update",
payload: {
taskId: event.payload.taskId,
detail: truncateDetail(event.payload.description),
detail: truncateDetail(event.payload.summary ?? event.payload.description),
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -411,6 +472,7 @@ function runtimeEventToActivities(
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -434,6 +496,7 @@ function runtimeEventToActivities(
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -449,12 +512,13 @@ function runtimeEventToActivities(
createdAt: event.createdAt,
tone: "tool",
kind: "tool.completed",
summary: `${event.payload.title ?? "Tool"} complete`,
summary: event.payload.title ?? "Tool",
payload: {
itemType: event.payload.itemType,
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -476,6 +540,7 @@ function runtimeEventToActivities(
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -491,6 +556,7 @@ function runtimeEventToActivities(
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
DEFAULT_ASSISTANT_DELIVERY_MODE,
@@ -682,6 +748,8 @@ const make = Effect.gen(function* () {
threadProposedPlans: ReadonlyArray<{
id: string;
createdAt: string;
implementedAt: string | null;
implementationThreadId: ThreadId | null;
}>;
planId: string;
turnId?: TurnId;
@@ -704,6 +772,8 @@ const make = Effect.gen(function* () {
id: input.planId,
turnId: input.turnId ?? null,
planMarkdown,
implementedAt: existingPlan?.implementedAt ?? null,
implementationThreadId: existingPlan?.implementationThreadId ?? null,
createdAt: existingPlan?.createdAt ?? input.createdAt,
updatedAt: input.updatedAt,
},
@@ -717,6 +787,8 @@ const make = Effect.gen(function* () {
threadProposedPlans: ReadonlyArray<{
id: string;
createdAt: string;
implementedAt: string | null;
implementationThreadId: ThreadId | null;
}>;
planId: string;
turnId?: TurnId;
@@ -783,6 +855,147 @@ const make = Effect.gen(function* () {
).pipe(Effect.asVoid);
});
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
) {
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId,
});
if (Option.isNone(pendingTurnStart)) {
return null;
}
const sourceThreadId = pendingTurnStart.value.sourceProposedPlanThreadId;
const sourcePlanId = pendingTurnStart.value.sourceProposedPlanId;
if (sourceThreadId === null || sourcePlanId === null) {
return null;
}
return {
sourceThreadId,
sourcePlanId,
} as const;
});
const getExpectedProviderTurnIdForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const sessions = yield* providerService.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
return session?.activeTurnId;
});
const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
eventTurnId: TurnId | undefined,
) {
if (eventTurnId === undefined) {
return null;
}
const expectedTurnId = yield* getExpectedProviderTurnIdForThread(threadId);
if (!sameId(expectedTurnId, eventTurnId)) {
return null;
}
return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId);
});
const markSourceProposedPlanImplemented = Effect.fnUntraced(function* (
sourceThreadId: ThreadId,
sourcePlanId: OrchestrationProposedPlanId,
implementationThreadId: ThreadId,
implementedAt: string,
) {
const readModel = yield* orchestrationEngine.getReadModel();
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.makeUnsafe(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
),
threadId: sourceThread.id,
proposedPlan: {
...sourcePlan,
implementedAt,
implementationThreadId,
updatedAt: implementedAt,
},
createdAt: implementedAt,
});
});
const upsertWorkUnit = Effect.fnUntraced(function* (input: {
thread: OrchestrationThread;
event: ProviderRuntimeEvent;
workUnitId: WorkUnitId;
turnId: TurnId;
kind: "primary_agent" | "delegated_agent";
state: "queued" | "running" | "completed" | "failed" | "stopped" | "cancelled";
title: string;
updatedAt: string;
parentWorkUnitId?: WorkUnitId | null;
detail?: string | null;
startedAt?: string;
completedAt?: string | null;
providerRefs?: NonNullable<OrchestrationThread["workUnits"][number]["providerRefs"]>;
}) {
const existing = input.thread.workUnits.find((entry) => sameId(entry.id, input.workUnitId));
const providerRefs =
input.providerRefs !== undefined || existing?.providerRefs !== undefined
? {
...existing?.providerRefs,
...input.providerRefs,
}
: undefined;
yield* orchestrationEngine.dispatch({
type: "thread.work-unit.upsert",
commandId: providerCommandId(input.event, "thread-work-unit-upsert"),
threadId: input.thread.id,
workUnit: {
id: input.workUnitId,
turnId: input.turnId,
parentWorkUnitId: input.parentWorkUnitId ?? existing?.parentWorkUnitId ?? null,
kind: input.kind,
state: input.state,
title: input.title.trim().length > 0 ? input.title : (existing?.title ?? "Work unit"),
detail: input.detail !== undefined ? input.detail : (existing?.detail ?? null),
spawnedByActivityId: existing?.spawnedByActivityId ?? null,
...(providerRefs !== undefined ? { providerRefs } : {}),
startedAt: existing?.startedAt ?? input.startedAt ?? input.updatedAt,
updatedAt: input.updatedAt,
completedAt:
input.completedAt !== undefined ? input.completedAt : (existing?.completedAt ?? null),
},
createdAt: input.updatedAt,
});
});
const ensureRootWorkUnit = Effect.fnUntraced(function* (
thread: OrchestrationThread,
event: ProviderRuntimeEvent,
turnId: TurnId,
updatedAt: string,
) {
const providerRefs = providerTurnWorkUnitRefs(event);
yield* upsertWorkUnit({
thread,
event,
workUnitId: rootWorkUnitIdForTurn(thread.id, turnId),
turnId,
kind: "primary_agent",
state: "running",
title: "Primary agent",
updatedAt,
startedAt: updatedAt,
...(providerRefs ? { providerRefs } : {}),
});
});
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -823,6 +1036,10 @@ const make = Effect.gen(function* () {
return true;
}
})();
const acceptedTurnStartedSourcePlan =
event.type === "turn.started" && shouldApplyThreadLifecycle
? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)
: null;
if (
event.type === "session.started" ||
@@ -865,6 +1082,26 @@ const make = Effect.gen(function* () {
: (thread.session?.lastError ?? null);
if (shouldApplyThreadLifecycle) {
if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) {
yield* markSourceProposedPlanImplemented(
acceptedTurnStartedSourcePlan.sourceThreadId,
acceptedTurnStartedSourcePlan.sourcePlanId,
thread.id,
now,
).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(
"provider runtime ingestion failed to mark source proposed plan",
{
eventId: event.eventId,
eventType: event.type,
cause: Cause.pretty(cause),
},
),
),
);
}
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "thread-session-set"),
@@ -883,6 +1120,89 @@ const make = Effect.gen(function* () {
}
}
if (eventTurnId !== undefined) {
yield* ensureRootWorkUnit(thread, event, eventTurnId, now);
}
if (event.type === "turn.started" && eventTurnId !== undefined) {
const providerRefs = providerTurnWorkUnitRefs(event);
yield* upsertWorkUnit({
thread,
event,
workUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
turnId: eventTurnId,
kind: "primary_agent",
state: "running",
title: "Primary agent",
updatedAt: now,
startedAt: now,
...(providerRefs ? { providerRefs } : {}),
});
}
if (event.type === "turn.completed" && eventTurnId !== undefined) {
const providerRefs = providerTurnWorkUnitRefs(event);
yield* upsertWorkUnit({
thread,
event,
workUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
turnId: eventTurnId,
kind: "primary_agent",
state: runtimeTurnStateToWorkUnitState(runtimeTurnState(event)),
title: "Primary agent",
updatedAt: now,
completedAt: now,
...(providerRefs ? { providerRefs } : {}),
});
}
if (
(event.type === "task.started" ||
event.type === "task.progress" ||
event.type === "task.completed") &&
eventTurnId !== undefined
) {
const taskId = String(event.payload.taskId);
const workUnitId = taskWorkUnitIdForTurn(thread.id, eventTurnId, taskId);
const taskState =
event.type === "task.completed"
? runtimeTaskStateToWorkUnitState(event.payload.status)
: "running";
const taskTitle =
event.type === "task.started"
? (event.payload.description ?? event.payload.taskType ?? "Delegated task")
: event.type === "task.completed"
? (event.payload.summary ?? "Delegated task")
: (event.payload.summary ?? event.payload.description);
const taskDetail =
event.type === "task.started"
? (event.payload.description ?? null)
: event.type === "task.completed"
? (event.payload.summary ?? null)
: (event.payload.summary ?? event.payload.description);
yield* upsertWorkUnit({
thread,
event,
workUnitId,
turnId: eventTurnId,
parentWorkUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
kind: "delegated_agent",
state: taskState,
title: taskTitle,
detail: taskDetail,
updatedAt: now,
...(event.type === "task.started" ? { startedAt: now } : {}),
...(event.type === "task.completed" ? { completedAt: now } : {}),
providerRefs: {
runtimeTaskId: RuntimeTaskId.makeUnsafe(taskId),
...(event.itemId ? { runtimeItemId: event.itemId } : {}),
...(event.providerRefs?.providerTurnId !== undefined
? { providerTurnId: event.providerRefs.providerTurnId }
: {}),
},
});
}
const assistantDelta =
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
? event.payload.delta
@@ -952,10 +1272,11 @@ const make = Effect.gen(function* () {
if (assistantCompletion) {
const assistantMessageId = assistantCompletion.messageId;
const turnId = toTurnId(event.turnId);
const existingAssistantMessage = thread.messages.find((entry) => entry.id === assistantMessageId);
const existingAssistantMessage = thread.messages.find(
(entry) => entry.id === assistantMessageId,
);
const shouldApplyFallbackCompletionText =
!existingAssistantMessage ||
existingAssistantMessage.text.length === 0;
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
if (turnId) {
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
}
@@ -1063,22 +1384,34 @@ const make = Effect.gen(function* () {
if (event.type === "turn.diff.updated") {
const turnId = toTurnId(event.turnId);
if (turnId && (yield* isGitRepoForThread(thread.id))) {
const assistantMessageId = MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: providerCommandId(event, "thread-turn-diff-complete"),
threadId: thread.id,
turnId,
completedAt: now,
checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`),
status: "missing",
files: [],
assistantMessageId,
checkpointTurnCount: thread.checkpoints.length + 1,
createdAt: now,
});
// Skip if a checkpoint already exists for this turn. A real
// (non-placeholder) capture from CheckpointReactor should not
// be clobbered, and dispatching a duplicate placeholder for the
// same turnId would produce an unstable checkpointTurnCount.
if (thread.checkpoints.some((c) => c.turnId === turnId)) {
// Already tracked; no-op.
} else {
const assistantMessageId = MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
const maxTurnCount = thread.checkpoints.reduce(
(max, c) => Math.max(max, c.checkpointTurnCount),
0,
);
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: providerCommandId(event, "thread-turn-diff-complete"),
threadId: thread.id,
turnId,
completedAt: now,
checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`),
status: "missing",
files: [],
assistantMessageId,
checkpointTurnCount: maxTurnCount + 1,
createdAt: now,
});
}
}
}
@@ -1142,4 +1475,7 @@ const make = Effect.gen(function* () {
} satisfies ProviderRuntimeIngestionShape;
});
export const ProviderRuntimeIngestionLive = Layer.effect(ProviderRuntimeIngestionService, make);
export const ProviderRuntimeIngestionLive = Layer.effect(
ProviderRuntimeIngestionService,
make,
).pipe(Layer.provide(ProjectionTurnRepositoryLive));
+2
View File
@@ -13,6 +13,7 @@ import {
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,
ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema,
ThreadWorkUnitUpsertedPayload as ContractsThreadWorkUnitUpsertedPayloadSchema,
ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema,
ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema,
ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema,
@@ -37,6 +38,7 @@ export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;
export const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema;
export const ThreadWorkUnitUpsertedPayload = ContractsThreadWorkUnitUpsertedPayloadSchema;
export const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema;
export const ThreadTurnInterruptRequestedPayload =
@@ -62,6 +62,7 @@ const readModel: OrchestrationReadModel = {
session: null,
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [],
deletedAt: null,
},
@@ -81,6 +82,7 @@ const readModel: OrchestrationReadModel = {
session: null,
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [],
deletedAt: null,
},
+52 -8
View File
@@ -262,11 +262,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}
case "thread.turn.start": {
yield* requireThread({
const targetThread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const sourceProposedPlan = command.sourceProposedPlan;
const sourceThread = sourceProposedPlan
? yield* requireThread({
readModel,
command,
threadId: sourceProposedPlan.threadId,
})
: null;
const sourcePlan =
sourceProposedPlan && sourceThread
? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
: null;
if (sourceProposedPlan && !sourcePlan) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
});
}
if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
});
}
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
...withEventBase({
aggregateKind: "thread",
@@ -302,14 +326,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.provider !== undefined ? { provider: command.provider } : {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
...(command.providerOptions !== undefined ? { providerOptions: command.providerOptions } : {}),
...(command.providerOptions !== undefined
? { providerOptions: command.providerOptions }
: {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
runtimeMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
command.runtimeMode,
interactionMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
command.interactionMode,
runtimeMode: targetThread.runtimeMode,
interactionMode: targetThread.interactionMode,
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
createdAt: command.createdAt,
},
};
@@ -608,6 +631,27 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.work-unit.upsert": {
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
return {
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
type: "thread.work-unit-upserted",
payload: {
threadId: command.threadId,
workUnit: command.workUnit,
},
};
}
default: {
command satisfies never;
const fallback = command as never as { type: string };
@@ -85,6 +85,7 @@ describe("orchestration projector", () => {
messages: [],
proposedPlans: [],
activities: [],
workUnits: [],
checkpoints: [],
session: null,
},
@@ -122,6 +123,88 @@ describe("orchestration projector", () => {
).rejects.toBeDefined();
});
it("applies thread.work-unit-upserted events", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
const afterCreate = await Effect.runPromise(
projectEvent(
model,
makeEvent({
sequence: 1,
type: "thread.created",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-thread-create",
payload: {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
),
);
const next = await Effect.runPromise(
projectEvent(
afterCreate,
makeEvent({
sequence: 2,
type: "thread.work-unit-upserted",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-work-unit-upsert",
payload: {
threadId: "thread-1",
workUnit: {
id: "wu:thread-1:turn:turn-1:root",
turnId: "turn-1",
parentWorkUnitId: null,
kind: "primary_agent",
state: "running",
title: "Primary agent",
detail: null,
spawnedByActivityId: null,
providerRefs: {
providerTurnId: "provider-turn-1",
},
startedAt: now,
updatedAt: now,
completedAt: null,
},
},
}),
),
);
expect(next.threads[0]?.workUnits).toEqual([
{
id: "wu:thread-1:turn:turn-1:root",
turnId: "turn-1",
parentWorkUnitId: null,
kind: "primary_agent",
state: "running",
title: "Primary agent",
detail: null,
spawnedByActivityId: null,
providerRefs: {
providerTurnId: "provider-turn-1",
},
startedAt: now,
updatedAt: now,
completedAt: null,
},
]);
});
it("keeps projector forward-compatible for unhandled event types", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
@@ -453,6 +536,7 @@ describe("orchestration projector", () => {
summary: "Edit file started",
payload: { toolKind: "command" },
turnId: "turn-1",
workUnitId: null,
createdAt: "2026-02-23T10:00:02.750Z",
},
},
@@ -527,6 +611,7 @@ describe("orchestration projector", () => {
summary: "Edit file complete",
payload: { toolKind: "command" },
turnId: "turn-2",
workUnitId: null,
createdAt: "2026-02-23T10:00:04.750Z",
},
},
+58 -6
View File
@@ -23,6 +23,7 @@ import {
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
ThreadWorkUnitUpsertedPayload,
} from "./Schemas.ts";
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
@@ -136,6 +137,17 @@ function retainThreadProposedPlansAfterRevert(
);
}
function retainThreadWorkUnitsAfterRevert(
workUnits: ReadonlyArray<OrchestrationThread["workUnits"][number]>,
retainedTurnIds: ReadonlySet<string>,
): ReadonlyArray<OrchestrationThread["workUnits"][number]> {
const retained = workUnits.filter((workUnit) => retainedTurnIds.has(workUnit.turnId));
const retainedIds = new Set(retained.map((workUnit) => workUnit.id));
return retained.filter(
(workUnit) => workUnit.parentWorkUnitId === null || retainedIds.has(workUnit.parentWorkUnitId),
);
}
function compareThreadActivities(
left: OrchestrationThread["activities"][number],
right: OrchestrationThread["activities"][number],
@@ -262,7 +274,9 @@ export function projectEvent(
updatedAt: payload.updatedAt,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
workUnits: [],
checkpoints: [],
session: null,
},
@@ -304,12 +318,7 @@ export function projectEvent(
);
case "thread.runtime-mode-set":
return decodeForEvent(
ThreadRuntimeModeSetPayload,
event.payload,
event.type,
"payload",
).pipe(
return decodeForEvent(ThreadRuntimeModeSetPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
@@ -505,6 +514,16 @@ export function projectEvent(
"checkpoint",
);
// Do not let a placeholder (status "missing") overwrite a checkpoint
// that has already been captured with a real git ref (status "ready").
// ProviderRuntimeIngestion may fire multiple turn.diff.updated events
// per turn; without this guard later placeholders would clobber the
// real capture dispatched by CheckpointReactor.
const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);
if (existing && existing.status !== "missing" && checkpoint.status === "missing") {
return nextBase;
}
const checkpoints = [
...thread.checkpoints.filter((entry) => entry.turnId !== checkpoint.turnId),
checkpoint,
@@ -558,6 +577,7 @@ export function projectEvent(
retainedTurnIds,
).slice(-200);
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
const workUnits = retainThreadWorkUnitsAfterRevert(thread.workUnits, retainedTurnIds);
const latestCheckpoint = checkpoints.at(-1) ?? null;
const latestTurn =
@@ -579,6 +599,7 @@ export function projectEvent(
messages,
proposedPlans,
activities,
workUnits,
latestTurn,
updatedAt: event.occurredAt,
}),
@@ -616,6 +637,37 @@ export function projectEvent(
}),
);
case "thread.work-unit-upserted":
return decodeForEvent(
ThreadWorkUnitUpsertedPayload,
event.payload,
event.type,
"payload",
).pipe(
Effect.map((payload) => {
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
if (!thread) {
return nextBase;
}
const workUnits = [
...thread.workUnits.filter((entry) => entry.id !== payload.workUnit.id),
payload.workUnit,
].toSorted(
(left, right) =>
left.startedAt.localeCompare(right.startedAt) || left.id.localeCompare(right.id),
);
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
workUnits,
updatedAt: event.occurredAt,
}),
};
}),
);
default:
return Effect.succeed(nextBase);
}
@@ -38,6 +38,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
activity_id,
thread_id,
turn_id,
work_unit_id,
tone,
kind,
summary,
@@ -49,6 +50,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
${row.activityId},
${row.threadId},
${row.turnId},
${row.workUnitId},
${row.tone},
${row.kind},
${row.summary},
@@ -60,6 +62,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
DO UPDATE SET
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
work_unit_id = excluded.work_unit_id,
tone = excluded.tone,
kind = excluded.kind,
summary = excluded.summary,
@@ -78,6 +81,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
work_unit_id AS "workUnitId",
tone,
kind,
summary,
@@ -126,6 +130,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
activityId: row.activityId,
threadId: row.threadId,
turnId: row.turnId,
workUnitId: row.workUnitId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
@@ -22,6 +22,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
thread_id,
turn_id,
plan_markdown,
implemented_at,
implementation_thread_id,
created_at,
updated_at
)
@@ -30,6 +32,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
${row.threadId},
${row.turnId},
${row.planMarkdown},
${row.implementedAt},
${row.implementationThreadId},
${row.createdAt},
${row.updatedAt}
)
@@ -38,6 +42,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
plan_markdown = excluded.plan_markdown,
implemented_at = excluded.implemented_at,
implementation_thread_id = excluded.implementation_thread_id,
created_at = excluded.created_at,
updated_at = excluded.updated_at
`,
@@ -52,6 +58,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
plan_markdown AS "planMarkdown",
implemented_at AS "implementedAt",
implementation_thread_id AS "implementationThreadId",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_proposed_plans
@@ -70,9 +78,7 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
const upsert: ProjectionThreadProposedPlanRepositoryShape["upsert"] = (row) =>
upsertProjectionThreadProposedPlanRow(row).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadProposedPlanRepository.upsert:query"),
),
Effect.mapError(toPersistenceSqlError("ProjectionThreadProposedPlanRepository.upsert:query")),
);
const listByThreadId: ProjectionThreadProposedPlanRepositoryShape["listByThreadId"] = (input) =>
@@ -0,0 +1,163 @@
import { Effect, Layer, Schema, Struct } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
import {
DeleteProjectionThreadWorkUnitsInput,
ListProjectionThreadWorkUnitsInput,
ProjectionThreadWorkUnit,
ProjectionThreadWorkUnitRepository,
type ProjectionThreadWorkUnitRepositoryShape,
} from "../Services/ProjectionThreadWorkUnits.ts";
const ProjectionThreadWorkUnitDbRowSchema = ProjectionThreadWorkUnit.mapFields(
Struct.assign({
providerRefs: Schema.NullOr(
Schema.fromJsonString(ProjectionThreadWorkUnit.fields.providerRefs),
),
}),
);
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown) =>
Schema.isSchemaError(cause)
? toPersistenceDecodeError(decodeOperation)(cause)
: toPersistenceSqlError(sqlOperation)(cause);
}
const makeProjectionThreadWorkUnitRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const upsertProjectionThreadWorkUnitRow = SqlSchema.void({
Request: ProjectionThreadWorkUnit,
execute: (row) => sql`
INSERT INTO projection_thread_work_units (
work_unit_id,
thread_id,
turn_id,
parent_work_unit_id,
kind,
state,
title,
detail,
spawned_by_activity_id,
provider_refs_json,
started_at,
updated_at,
completed_at
)
VALUES (
${row.workUnitId},
${row.threadId},
${row.turnId},
${row.parentWorkUnitId},
${row.kind},
${row.state},
${row.title},
${row.detail},
${row.spawnedByActivityId},
${row.providerRefs ? JSON.stringify(row.providerRefs) : null},
${row.startedAt},
${row.updatedAt},
${row.completedAt}
)
ON CONFLICT (work_unit_id)
DO UPDATE SET
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
parent_work_unit_id = excluded.parent_work_unit_id,
kind = excluded.kind,
state = excluded.state,
title = excluded.title,
detail = excluded.detail,
spawned_by_activity_id = excluded.spawned_by_activity_id,
provider_refs_json = excluded.provider_refs_json,
started_at = excluded.started_at,
updated_at = excluded.updated_at,
completed_at = excluded.completed_at
`,
});
const listProjectionThreadWorkUnitRows = SqlSchema.findAll({
Request: ListProjectionThreadWorkUnitsInput,
Result: ProjectionThreadWorkUnitDbRowSchema,
execute: ({ threadId }) => sql`
SELECT
work_unit_id AS "workUnitId",
thread_id AS "threadId",
turn_id AS "turnId",
parent_work_unit_id AS "parentWorkUnitId",
kind,
state,
title,
detail,
spawned_by_activity_id AS "spawnedByActivityId",
provider_refs_json AS "providerRefs",
started_at AS "startedAt",
updated_at AS "updatedAt",
completed_at AS "completedAt"
FROM projection_thread_work_units
WHERE thread_id = ${threadId}
ORDER BY started_at ASC, work_unit_id ASC
`,
});
const deleteProjectionThreadWorkUnitRows = SqlSchema.void({
Request: DeleteProjectionThreadWorkUnitsInput,
execute: ({ threadId }) => sql`
DELETE FROM projection_thread_work_units
WHERE thread_id = ${threadId}
`,
});
const upsert: ProjectionThreadWorkUnitRepositoryShape["upsert"] = (row) =>
upsertProjectionThreadWorkUnitRow(row).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionThreadWorkUnitRepository.upsert:query")),
);
const listByThreadId: ProjectionThreadWorkUnitRepositoryShape["listByThreadId"] = (input) =>
listProjectionThreadWorkUnitRows(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionThreadWorkUnitRepository.listByThreadId:query",
"ProjectionThreadWorkUnitRepository.listByThreadId:decodeRows",
),
),
Effect.map((rows) =>
rows.map((row) => ({
workUnitId: row.workUnitId,
threadId: row.threadId,
turnId: row.turnId,
parentWorkUnitId: row.parentWorkUnitId,
kind: row.kind,
state: row.state,
title: row.title,
detail: row.detail,
spawnedByActivityId: row.spawnedByActivityId,
...(row.providerRefs !== null ? { providerRefs: row.providerRefs } : {}),
startedAt: row.startedAt,
updatedAt: row.updatedAt,
completedAt: row.completedAt,
})),
),
);
const deleteByThreadId: ProjectionThreadWorkUnitRepositoryShape["deleteByThreadId"] = (input) =>
deleteProjectionThreadWorkUnitRows(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadWorkUnitRepository.deleteByThreadId:query"),
),
);
return {
upsert,
listByThreadId,
deleteByThreadId,
} satisfies ProjectionThreadWorkUnitRepositoryShape;
});
export const ProjectionThreadWorkUnitRepositoryLive = Layer.effect(
ProjectionThreadWorkUnitRepository,
makeProjectionThreadWorkUnitRepository,
);
@@ -47,6 +47,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
@@ -61,6 +63,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
${row.threadId},
${row.turnId},
${row.pendingMessageId},
${row.sourceProposedPlanThreadId},
${row.sourceProposedPlanId},
${row.assistantMessageId},
${row.state},
${row.requestedAt},
@@ -74,6 +78,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
ON CONFLICT (thread_id, turn_id)
DO UPDATE SET
pending_message_id = excluded.pending_message_id,
source_proposed_plan_thread_id = excluded.source_proposed_plan_thread_id,
source_proposed_plan_id = excluded.source_proposed_plan_id,
assistant_message_id = excluded.assistant_message_id,
state = excluded.state,
requested_at = excluded.requested_at,
@@ -106,6 +112,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
@@ -120,6 +128,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
${row.threadId},
NULL,
${row.messageId},
${row.sourceProposedPlanThreadId},
${row.sourceProposedPlanId},
NULL,
'pending',
${row.requestedAt},
@@ -141,6 +151,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
pending_message_id AS "messageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
requested_at AS "requestedAt"
FROM projection_turns
WHERE thread_id = ${threadId}
@@ -162,6 +174,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
pending_message_id AS "pendingMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
assistant_message_id AS "assistantMessageId",
state,
requested_at AS "requestedAt",
@@ -193,6 +207,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
pending_message_id AS "pendingMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
assistant_message_id AS "assistantMessageId",
state,
requested_at AS "requestedAt",
@@ -25,6 +25,9 @@ import Migration0010 from "./Migrations/010_ProjectionThreadsRuntimeMode.ts";
import Migration0011 from "./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts";
import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts";
import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
import Migration0016 from "./Migrations/016_ProjectionThreadWorkUnits.ts";
import { Effect } from "effect";
/**
@@ -51,6 +54,9 @@ const loader = Migrator.fromRecord({
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
"12_ProjectionThreadsInteractionMode": Migration0012,
"13_ProjectionThreadProposedPlans": Migration0013,
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
"16_ProjectionThreadWorkUnits": Migration0016,
});
/**
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_thread_proposed_plans
ADD COLUMN implemented_at TEXT
`;
yield* sql`
ALTER TABLE projection_thread_proposed_plans
ADD COLUMN implementation_thread_id TEXT
`;
});
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_turns
ADD COLUMN source_proposed_plan_thread_id TEXT
`;
yield* sql`
ALTER TABLE projection_turns
ADD COLUMN source_proposed_plan_id TEXT
`;
});
@@ -0,0 +1,88 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_thread_activities
ADD COLUMN work_unit_id TEXT
`;
yield* sql`
CREATE TABLE IF NOT EXISTS projection_thread_work_units (
work_unit_id TEXT PRIMARY KEY,
thread_id TEXT NOT NULL,
turn_id TEXT NOT NULL,
parent_work_unit_id TEXT,
kind TEXT NOT NULL,
state TEXT NOT NULL,
title TEXT NOT NULL,
detail TEXT,
spawned_by_activity_id TEXT,
provider_refs_json TEXT,
started_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
completed_at TEXT
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_thread_work_units_thread_turn
ON projection_thread_work_units(thread_id, turn_id, started_at)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_thread_work_units_thread_parent
ON projection_thread_work_units(thread_id, parent_work_unit_id, started_at)
`;
yield* sql`
INSERT INTO projection_thread_work_units (
work_unit_id,
thread_id,
turn_id,
parent_work_unit_id,
kind,
state,
title,
detail,
spawned_by_activity_id,
provider_refs_json,
started_at,
updated_at,
completed_at
)
SELECT
'wu:' || thread_id || ':turn:' || turn_id || ':root',
thread_id,
turn_id,
NULL,
'primary_agent',
CASE state
WHEN 'completed' THEN 'completed'
WHEN 'error' THEN 'failed'
WHEN 'interrupted' THEN 'stopped'
ELSE 'running'
END,
'Primary agent',
NULL,
NULL,
NULL,
COALESCE(started_at, requested_at),
COALESCE(completed_at, started_at, requested_at),
CASE
WHEN state IN ('completed', 'error', 'interrupted') THEN COALESCE(completed_at, started_at, requested_at)
ELSE NULL
END
FROM projection_turns
WHERE turn_id IS NOT NULL
`;
yield* sql`
UPDATE projection_thread_activities
SET work_unit_id = 'wu:' || thread_id || ':turn:' || turn_id || ':root'
WHERE turn_id IS NOT NULL
AND work_unit_id IS NULL
`;
});
Loaded 100 of 293 files, more files were not shown because too many files have changed in this diff. Show more