Compare commits

..
Author SHA1 Message Date
Julius Marminge 11091bf337 Refactor allowed host parsing for origin validation
- validate allowed hosts with `Schema.Trim` + `Schema.check`
- normalize hosts via lowercase decode step
- simplify CSV decode/encode by removing Effect-wrapped transforms
2026-03-17 12:54:25 -07:00
Julius Marminge 49dda48a4f Verify WebSocket origins and enforce allowed host checks
- Add `--allowed-hosts` / `T3CODE_ALLOWED_HOSTS` config parsing and validation
- Reject HTTP and WebSocket requests from disallowed hosts with 403
- Enforce production WebSocket origin matching (including proxy headers), with dev-url bypass
- Expand CLI and server tests for host filtering and origin verification
2026-03-17 12:49:38 -07: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
Julius Marminge 24122b1762 Stabilize toast stacking offsets to prevent hover flicker
- derive toast indices and Y offsets from the filtered visible toasts
- pass frontmost height and per-toast layout vars to the viewport/item styles
- add unit tests for visible toast layout calculations and height normalization
2026-03-09 10:01:46 -07:00
Julius Marminge 081a6dacdb Remove fast-tier icons from model selection UI
- delete `shouldShowFastTierIcon` and its test
- remove Zap icon badges from slash model commands and provider model picker
- simplify related ChatView props and memo dependencies
2026-03-09 09:47:21 -07:00
Julius Marminge 9fdb45be1e Remove service tier setting from Codex flow and contracts
- Drop `serviceTier` from orchestration/provider contracts and server dispatch paths
- Remove service-tier app setting/UI and related resolver logic
- Keep fast badge behavior tied to explicit fast-mode boolean
2026-03-09 09:47:21 -07:00
Julius Marminge b946f00f1a Show Plan Ready status pill for settled plan threads
- add "Plan Ready" sidebar status when a plan-mode turn is settled with a proposed plan
- update sidebar logic tests to cover the new status and expanded thread inputs
2026-03-09 09:46:33 -07:00
Julius Marminge b030f69a83 Show Awaiting Input status in sidebar and extract status logic
- add `Sidebar.logic.ts` to centralize thread status pill resolution
- show `Awaiting Input` when plan mode is blocked on user responses
- add unit tests for unseen completion and status-priority behavior
- prevent plan collapse/expand clicks from triggering chat scroll anchoring
2026-03-09 09:46:33 -07:00
Julius Marminge b0e1b3368e Show toast when immediate project add fails
- Use a toast error for add-project failures during immediate folder browse
- Keep inline add-project error state for non-immediate flows
- Include `shouldBrowseForProjectImmediately` in callback dependencies
2026-03-09 09:31:39 -07:00
Julius Marminge ce7b24bfb1 Inline Electron project picker check in Sidebar
- Replace `shouldOpenProjectFolderPickerImmediately` with direct `isElectron` usage
- Remove obsolete `Sidebar.logic.ts` and its tests
2026-03-09 09:31:39 -07:00
Julius Marminge 5c286cab8b Open project folder picker immediately in Electron
- remove mobile-width gating from sidebar project picker behavior
- simplify picker logic/tests to depend only on Electron runtime
2026-03-09 09:31:39 -07:00
Julius Marminge 75ca0d4fa4 Open folder picker immediately on desktop Electron
- add `shouldOpenProjectFolderPickerImmediately` to centralize Sidebar behavior
- trigger folder browse directly when adding a project in desktop Electron
- keep manual path entry for mobile layouts and non-Electron, with tests for all cases
2026-03-09 09:31:39 -07:00
0x1f99d 8282b11fb5 refactor(contracts): remove unused OrchestrationPersistedEvent schema (#601) 2026-03-09 08:29:49 -07:00
github-actions[bot] 45744cc789 chore(release): prepare v0.0.9 2026-03-09 11:17:07 +00:00
Sai Shankar 4b6a0c433c fix(web): fix native scrollbar being intercepted by sidebar rail on windows and linux (#618)
the rail's 16px hit area at z-20 sits right where the native os scrollbar
lives when the sidebar is in offcanvas mode and collapsed. this causes clicks
and drags on the scrollbar to toggle the sidebar instead on windows and linux.

scoping pointer-events-none to [data-collapsible=offcanvas][data-state=collapsed]
fixes the interception without affecting icon mode where the rail needs to stay
clickable.
2026-03-09 04:03:13 -07:00
Theo Browne 304a14de7d Fix users who installed intel builds on arm macs (#641) 2026-03-09 04:01:23 -07:00
Theo Browne c585128bbe ARM ALWAYS FUCK YOU INTEL 2026-03-09 01:20:14 -07:00
Theo Browne acd92f9b06 include sourcemaps 2026-03-09 01:12:55 -07:00
0x1f99d 4088b7ac3c fix(desktop): use filesystem-friendly userData directory name (#607)
Electron derives the userData path from productName in package.json,
which produces directories with spaces and parentheses on all platforms
(e.g. ~/.config/T3 Code (Alpha) on Linux). This is hostile to shell
usage and violates Linux XDG naming conventions.

Override the userData path via app.setPath() before the ready event to
use a clean lowercase name (t3code). If the legacy directory already
exists it is used as-is so existing users keep their Chromium profile
data (localStorage, cookies, sessions, cache).

This follows the same pattern VS Code uses — keeping productName for
display purposes while explicitly setting the data directory path.

Closes #578
2026-03-08 22:02:15 -07:00
0x1f99d 8e8904a159 refactor(web): remove redundant double parse of diff route search params (#598)
`rawSearch` is already the output of `parseDiffRouteSearch` via the
`useSearch` select transform. The `useMemo` at line 760 re-parsed it
through the same function with an unsafe `as Record<string, unknown>`
cast, producing an identical result. Use `rawSearch` directly instead.
2026-03-08 21:55:09 -07:00
0x1f99d 16f3490aee fix(ci): handle draft PR conversions in pr-vouch (#611) 2026-03-08 21:53:26 -07:00
Jono Kemball 651084e8c0 fix: fix external link opening in desktop (#599)
fixes #434
2026-03-08 21:43:35 -07:00
Theo Browne 812bb99f5c Add Noojuno to vouched 2026-03-08 21:43:17 -07:00
Jason Laster 5bc79807ec Add an encyclopedia of common terms (#613) 2026-03-08 21:40:44 -07:00
github-actions[bot] 8fe21d7583 chore(release): prepare v0.0.8 2026-03-09 03:43:56 +00:00
0x1f99d 412331aa61 fix(web): add missing v7 key to legacy localStorage cleanup list (#594)
When the persisted state key was bumped from v7 to v8 in 689dda59,
the v7 key was not added to LEGACY_PERSISTED_STATE_KEYS. Users who
ran the app during the ~3-week v7 window retain a stale
`t3code:renderer-state:v7` entry in localStorage that is never
cleaned up.
2026-03-08 20:39:41 -07:00
Theo Browne cd1c3df89c Add PR vouch workflow with trust-status labels (#602)
* Add PR vouch workflow and trust-status labeling

- Add `.github/workflows/pr-vouch.yml` to label PRs as trusted, unvouched, or denounced
- Add `.github/VOUCHED.td` trust-list file for external contributors
- Document automatic `vouch:*` labels and contributor expectations in `CONTRIBUTING.md`

* Add vouch entries for trusted GitHub contributors

- Append 16 GitHub accounts to `.github/VOUCHED.td`
- Update trusted-voucher list used for PR labeling workflows
2026-03-08 20:36:37 -07:00
0x1f99d 3738373aa5 fix(server): use waitForPush in terminal event broadcast test to prevent flaky failure (#606)
The terminal RPC test used raw waitForMessage to receive the expected
terminal.event push, but a server.configUpdated push from the
keybindings file watcher can arrive first depending on OS timing.
Replace with the existing waitForPush helper that filters by channel.
2026-03-08 20:36:03 -07:00
Theo Browne 9b9006fed5 Fix release finalize lockfile refresh (#608)
* Add checkout and Node setup to release updater publish job

- Ensure the updater publish job checks out the target ref
- Initialize Node using the repository's package.json version file before downloading artifacts

* Fix release finalize lockfile refresh
2026-03-08 20:30:01 -07:00
Theo Browne 42234b8f7c fix: plan mode ui overhaul (#596)
* new plan mode started

* review comments

* more fixes
2026-03-08 20:12:31 -07:00
Theo Browne 39f65703e7 Add checkout and Node setup to updater publish workflow job (#605)
- Ensure the updater publish job checks out the target ref
- Initialize Node using the repository's package.json version file before downloading artifacts
2026-03-08 20:00:15 -07:00
(CJ) Chukwudi Nwobodo b7f954a904 Fix ChildProcess.spawn failing on Windows for .cmd shims (#495)
* fix(scripts): enable shell mode on Windows for .cmd shim resolution

On Windows, tools like `bun`, `npm`, `turbo`, and `bunx` are installed
as `.cmd` shims. Node's `child_process.spawn` cannot resolve these
without `shell: true`, causing `PlatformError: NotFound` on fresh
builds where there is no Turbo cache.

Add `shell: process.platform === "win32"` to all ChildProcess.make
calls in cli.ts, dev-runner.ts, and build-desktop-artifact.ts.

Closes #474

* docs: add comments explaining Windows shell spawn requirement

* docs: add shell spawn comments to remaining call sites
2026-03-08 18:58:25 -07:00
0x1f99d a20815ece6 fix(web): align sidebar logo with macOS traffic light buttons (#586)
Adjust the Electron sidebar header to properly center the T3 wordmark
with the native window controls. The logo was sitting ~2px too low and
~8px too close to the traffic lights.

- Reduce wordmark container top margin from mt-2 (8px) to mt-1.5 (6px)
- Increase Electron header left padding from 82px to 90px for proper
  traffic light clearance
- Match the desktop update button margin to stay aligned

Closes #564
2026-03-08 18:56:29 -07:00
Mubin Ansari 1c43bad705 Add delete option for project actions (#223)
Adds a delete button to the action edit dialog with a confirmation
alert. Fixes pingdotgg/t3code#208.
2026-03-08 18:51:55 -07:00
(CJ) Chukwudi Nwobodo 18b6590d2e feat(desktop): add spellcheck suggestions to context menu (#500)
Wire up Electron's context-menu event on webContents to surface
dictionary suggestions for misspelled words. Standard edit actions
(Cut, Copy, Paste, Select All) appear in all context menus.

Related to #473
2026-03-08 18:36:52 -07:00
Theo Browne d62ffa7560 pr changes pt2 2026-03-08 18:27:04 -07:00
0x1f99d 59e2944fb7 fix(web): add dismiss button to thread error banner (#588)
The thread error banner had no way to be dismissed. Users hitting
unrecoverable errors (e.g. missing gh CLI during PR creation) were
stuck with a persistent error banner and no way to clear it.

Add a dismiss (X) button to ThreadErrorBanner using the existing
AlertAction component, wired to clear the thread error via
setThreadError(id, null).

Closes #496
2026-03-08 18:24:56 -07:00
Theo Browne 17942787aa fix: settings in sidebar, better add project flow (#584)
* improvements

* sidebar ui pt2

* back flow

* fix back flow
2026-03-08 18:21:31 -07:00
Theo Browne 5815ba24e2 Add pull request template with contribution notice and review checklist (#582)
* Add PR template with contribution notice and review checklist

- Add `.github/pull_request_template.md`
- Set expectations that external PRs may not be reviewed or merged
- Require clear change rationale plus UI before/after media when applicable

* Add contribution policy notice and link detailed guidelines

- add CONTRIBUTING.md with clear expectations for external PRs
- update README to direct would-be contributors to CONTRIBUTING.md first
2026-03-08 18:20:05 -07:00
Noah Gregory 5de8e9d1ae fix: properly emit update metadata for intel macs (#446)
* fix: properly emit update metadata for intel macs

* refactor: fix broken parsing of quoted values
2026-03-08 18:03:18 -07:00
Aditya Vardhan Sharma 96e1e3db5e feat(marketing): add platform detection for download button (#558) 2026-03-08 17:45:40 -07:00
github-actions[bot] 5dd36bc5ad chore(release): prepare v0.0.5 2026-03-08 23:52:20 +00:00
Patrick BauerandPatrickBauer 6271b989bc fix(web): use wss:// when page is served over HTTPS (#391)
When T3 Code web mode is accessed via HTTPS (e.g. through a reverse proxy
or Tailscale Serve), the WebSocket connection must use wss:// instead of
ws://. Browsers block mixed content — an insecure ws:// connection
initiated from an HTTPS page.

Fix: derive the WebSocket protocol from window.location.protocol.

Co-authored-by: PatrickBauer <[email protected]>
2026-03-08 16:30:25 -07:00
James 57aa6bf16c fix: avoid duplicating streamed assistant completion text (#465) 2026-03-08 16:29:34 -07:00
Kainoa Newton 40a7f4b4b1 Rename Open PR action label to View PR (#467)
- Update GitActionsControl quick/menu action text for existing pull requests
- Align unavailable-state copy and tests with the new label
2026-03-08 16:27:39 -07:00
Kainoa Newton cba0f23a9e Remove extra dot from working indicator (#481)
- Drop the redundant static bullet before the working status text in `MessagesTimeline`
- Keep the animated dots indicator as the sole working-state visual cue
2026-03-08 16:27:03 -07:00
(CJ) Chukwudi Nwobodo a7ec0179fb Fix codex binary path setting having no effect (#493)
* refactor(contracts): export ProviderStartOptions schema

* feat(contracts): add providerOptions to ThreadTurnStartCommand

* feat(web): send codex binary/home path settings to server

* feat(server): thread providerOptions through to session startup

* fix(contracts): define ProviderStartOptions inline to avoid circular dep

The import from provider.ts caused a ReferenceError at runtime because
of module initialization order in the bundled output.

* fix(server): preserve providerOptions across runtime mode changes and session recovery

Runtime mode toggles and server restarts silently dropped the custom
codex binary/home path, falling back to the default binary. Cache
providerOptions per thread in ProviderCommandReactor and persist it in
the session binding's runtimePayload so recovery can restore it.

Closes #486
2026-03-08 15:55:49 -07:00
Jason Laster c97c6b7836 Enforce minimum Codex CLI version (≥0.37.0) before starting sessions (#404)
Add a pre-flight version check that runs `codex --version` and blocks
session startup with a clear upgrade message when the installed CLI is
below v0.37.0. The check runs both synchronously at session start
(codexAppServerManager) and during provider health probes
(ProviderHealth), so users get fast feedback in the UI.

Introduces `codexCliVersion.ts` with semver parsing, comparison, and
formatting helpers shared by both call sites.
2026-03-07 13:12:11 -08:00
github-actions[bot] 59b0527c38 chore(release): prepare v0.0.4-alpha.1 2026-03-07 12:19:51 +00:00
Theo Browne b74c7a79ab Handle prerelease tags in GitHub release publishing (#344)
* Handle prerelease tags when publishing GitHub releases

- Derive `is_prerelease` and `make_latest` from the version format in preflight
- Mark suffixed versions (for example `1.2.3-alpha.1`) as prereleases
- Keep only plain `X.Y.Z` releases marked as latest
- Document prerelease/latest behavior in `docs/release.md`

* Force desktop auto-updates to stable latest channel

- set Electron updater channel to `latest`
- disable prerelease and downgrade updates regardless of app version
2026-03-07 04:05:36 -08:00
github-actions[bot] f772720d8c chore(release): prepare v0.0.4 2026-03-07 10:38:31 +00:00
Hwanseo ChoiandCopilot 0763a35fbc Fix bun run dev:desktop from not terminating properly on SIGINT/SIGTERM/SIGHUP (#305)
* fix: handle turbo shutdown in dev runner

* refactor: rely on effect child process shutdown

* refactor: inline turbo shutdown timeout

* add back sigint sigterm sighup handling

* refactor: tighten turbo signal forwarding

* refactor: inline dev runner errors

* fix: use detached false instead of manual signal forwarding

Effect defaults to detached: true on non-Windows, putting turbo in a
new process group where terminal signals (Ctrl+C) never reach it.
Setting detached: false keeps turbo in the same group, eliminating
the need for ~130 lines of manual signal forwarding.

* Update scripts/dev-runner.ts

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Copilot <[email protected]>
2026-03-07 02:20:17 -08:00
Guilherme Barros e1c33dcd33 Fix Fish shell PATH detection and clean up lint warnings (#323)
* Fix Fish shell PATH detection for Codex

* refactor(provider): resolve lint warnings in provider layers

* refactor(terminal): simplify thread lock release initialization

* test(git): simplify fetch release callback initialization
2026-03-07 02:14:30 -08:00
Ahmed R.andAhmed R 0a902790ca Fix crash when rendering code blocks with unsupported languages (#266 & #210) (#279)
The app crashed when displaying code blocks with language identifiers
not bundled in Shiki (e.g. "env" from .env file edits). The language
string was cast to SupportedLanguages without validation, causing
resolveLanguage to throw an unhandled error that killed the thread.

Three layers of defense added:
- getHighlighterPromise falls back to "text" when Shiki rejects
- codeToHtml call wrapped in try/catch with "text" fallback
- CodeHighlightErrorBoundary prevents component tree crashes

Closes #266

Co-authored-by: Ahmed R <[email protected]>
2026-03-07 02:12:54 -08:00
Theo Browne 0837c8b639 fix: everything AICodeKing reported (#320)
* Guard non-git projects and improve send and diff UX

- Skip checkpoint capture/revert and turn diff ingestion for non-git workspaces
- Normalize project workspace roots and return clearer request/error messages
- Show "No Git" state in chat/diff UI and enrich work log with commands/files
- Track send start time so working status shows elapsed duration consistently

* Format active working timer in concise h/m/s units

- add `formatWorkingTimer` for human-friendly durations in ChatView
- show active "Working for" time as `0s`, `1m 5s`, or `2h 3m` instead of ms

* more cleanup

* Fix active work timing and use temp git workspaces in tests

- derive active work start from unsettled turn state instead of always latest turn
- update chat view to use shared deriveActiveWorkStartedAt helper
- make server/ws tests create temporary workspace roots with .git for project creation
2026-03-07 02:06:55 -08:00
JoeEverest 5a90b6be9c #221: Fix missing list markers in chat markdown (#224)
Tailwind v4 Preflight resets list-style to none on ul/ol elements.
Restore disc/decimal markers and add nested list style variants
(circle, square, lower-alpha, lower-roman) for visual distinction.
2026-03-06 17:51:44 -08:00
github-actions[bot] 42675571c9 chore(release): prepare v0.0.3 2026-03-07 00:57:40 +00:00
Theo Browne e9f00f65ca Update README command and support link
- switch quickstart command from `npx t3@alpha` to `npx t3`
- fix wording in desktop app sentence
- replace "Discord link coming soon" with invite link
2026-03-06 16:56:10 -08:00
Julius Marminge 04b95e37c5 Change CLI package publish tag from alpha to latest 2026-03-06 16:27:42 -08:00
github-actions[bot] 5820e1b6ff chore(release): prepare v0.0.2 2026-03-07 00:17:26 +00:00
Theo Browne 8c904ffe34 Add production favicon set for marketing page (#196)
- add 16x16, 32x32, and Apple touch icon assets
- update `index.astro` head links to reference size-specific favicons
2026-03-06 15:53:32 -08:00
Theo Browne 9fa9cb4b31 Soften chat composer focus border color (#188)
- Reduce focused composer border intensity using `focus-within:border-ring/45`
- Keeps drag-over styling behavior unchanged
2026-03-06 15:53:12 -08:00
github-actions[bot] 24599aaeed chore(release): prepare v0.0.0-alpha.22 2026-03-06 23:08:37 +00:00
Theo Browne f403b23e9a Add Shift+Tab shortcut to toggle composer plan mode (#186)
- add Shift+Tab keyboard handling in composer to switch chat/plan modes
- refactor mode toggle into shared callback used by hotkey and button
- add browser test to verify toggling only works when composer is focused
2026-03-06 14:55:24 -08:00
Theo BrowneandClaude Opus 4.6 39c71a0394 Redesign marketing site with Astro (#187)
* marketing site

* redesign 1

* more

* Redesign marketing site: port to Astro, minimal dark homepage

Replace the React/Vite marketing site with a single static Astro page.
Dark theme matching the app aesthetic, featuring the production glossy
T3 icon, app screenshot, and a clean minimal layout.

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

* Fix GitHub link to pingdotgg/t3code

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

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-03-06 14:45:41 -08:00
d249e628ee Stage production icons for desktop builds and publish (#168)
* Stage production icons for desktop builds and publish

- add shared brand asset paths and a Windows .ico asset
- stage Linux/Windows icons in desktop artifact builds
- override and restore publish favicon during server CLI publish

* 'blip'

* Fix PR review issues for publish icon staging

* Refactor brand assets and harden Windows desktop build setup

* Apply remaining server orchestration updates

* Fix production mac icon asset

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

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
2026-03-06 13:54:31 -08:00
Yash SinghandTheo Browne 40fcb6bdf8 fix: restrict spark to non-plus users & fast mode gpt5.4 (#180)
* fix: restrict spark to non-plus users & fast mode gpt5.4

* nit

* tests

* tests

---------

Co-authored-by: Theo Browne <[email protected]>
2026-03-06 13:48:37 -08:00
Julius Marminge d58ff5de26 Streamline composer behavior during pending approvals
- Treat pending approvals as a dedicated composer state
- Disable prompt input and hide command menu/image chips while approval is active
- Move approval decision buttons into footer actions and simplify the header panel
2026-03-06 09:03:16 -08:00
Julius Marmingeandcodex e28ad18106 Inline pending approvals in composer header
Co-authored-by: codex <[email protected]>
2026-03-06 09:03:16 -08:00
github-actions[bot] 525411101d chore(release): prepare v0.0.0-alpha.21 2026-03-06 08:08:47 +00:00
Julius Marminge 0f208447ed Prefer base HTML icon for .html files
- Override `.html` language mapping to use the generic HTML icon
- Add test coverage asserting `index.html` resolves to `file_type_html.svg`
2026-03-05 23:52:26 -08:00
Theo Browne 71e0573459 @alpha 2026-03-05 23:48:17 -08:00
Julius Marminge c63ea8d25b Use project cwd when opening draft threads without worktree
- Pass resolved `openInCwd` from ChatView into OpenInPicker
- Fall back to project `cwd` when draft thread has no `worktreePath`
- Add browser test covering Open action for draft-only snapshot
2026-03-05 23:44:26 -08:00
Julius Marminge b9e529e0b5 Preserve draft terminal state during snapshot cleanup
- add `collectActiveTerminalThreadIds` to keep non-deleted server threads plus local draft threads
- use helper in root event router before orphan terminal state removal
- add unit tests for retained and deleted thread behavior
2026-03-05 23:41:23 -08:00
Julius Marminge 0f702fcd62 server heartbeat 2026-03-05 23:40:49 -08:00
Julius Marmingeandcodex 13f2f9bc58 Fix ProviderService telemetry payload fields after rebase
Co-authored-by: codex <[email protected]>
2026-03-05 23:40:49 -08:00
Julius Marminge 91cf202177 Scope telemetry flush loop to service lifecycle
- Replace detached flush worker with scoped fiber in `AnalyticsService`
- Ensure periodic analytics flushing is tied to layer lifetime/cleanup
2026-03-05 23:40:49 -08:00
Julius Marminge d21a8d597b rm 2026-03-05 23:40:49 -08:00
Julius Marminge 14022f1d00 Refactor analytics flush test to use Effect NodeServices
- Wrap test in `it.layer(NodeServices.layer)` for Node service provisioning
- Replace manual temp dir setup/cleanup with scoped `FileSystem.makeTempDirectoryScoped`
- Keep multi-batch flush assertions while simplifying test runtime wiring
2026-03-05 23:40:49 -08:00
Julius Marminge 28c62f3efd Add test for analytics flush across multiple batches
- Verify `flush` drains 45 buffered events with batch size 20
- Assert three `/batch` POSTs are sent and event indexes 0-44 are delivered
2026-03-05 23:40:49 -08:00
Julius Marminge 268bb4bfa3 simplify layers 2026-03-05 23:40:49 -08:00
Julius Marminge 477b4f9d0e Wire telemetry in main and store anonymous ID in state dir
- move `AnalyticsServiceLayerLive` from CLI runtime setup into `main` server layer
- persist telemetry `anonymous-id` under configured `stateDir` instead of home directory
- add `FetchHttpClient.layer` to `main.test.ts` test layer wiring
2026-03-05 23:40:49 -08:00
Julius Marminge d5d88270f0 fallback 2026-03-05 23:40:49 -08:00
Julius Marminge 373725f96e record some machine info 2026-03-05 23:40:49 -08:00
Julius Marminge fcb1a50ee4 adjust 2026-03-05 23:40:49 -08:00
Julius Marminge ec3778bbf4 Add anonymous PostHog telemetry for provider lifecycle events
- introduce `AnalyticsService` with buffered PostHog batch flush
- add hashed telemetry identifier from Codex account id or anonymous local id
- record provider session/turn lifecycle events and flush on stop-all
- wire telemetry layer into server runtime and update tests with no-op analytics
2026-03-05 23:40:49 -08:00
Theo Browne 8c5b8d3b72 readme and shit 2026-03-05 23:07:59 -08:00
Julius Marminge 010ba70561 Fix plan follow-up mode switching and submission text
- Extract follow-up submission resolution into `resolvePlanFollowUpSubmission`
- Send implementation prompt in default mode when follow-up text is empty
- Keep composer mode toggle synced when starting same-thread implementation turns
- Add tests for follow-up submission behavior
2026-03-05 23:00:41 -08:00
Julius Marminge 6ee057e25b rm test 2026-03-05 23:00:41 -08:00
Julius Marminge 551aebc604 Add default collaboration mode preset for Codex turn starts
- Send `collaborationMode` for both `default` and `plan` interactions
- Add default-mode developer instructions and preserve plan-mode behavior
- Update server/web tests for default collaboration mode and model constant usage
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 9de85ea16e fix: preserve custom model picker selections
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 10dde452f9 fix: address core review findings
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 116c8c5e8e rm some aliases 2026-03-05 23:00:41 -08:00
Julius Marminge f8886e874d rm task lifecycle events from ui 2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 2435a9cd58 chore: move cursor acp probe artifacts to cursor stack
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 78d53062d1 refactor: move cursor provider surface out of core\n\nCo-authored-by: codex <[email protected]> 2026-03-05 23:00:41 -08:00
Julius Marminge 697d71d57d sync lock 2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex d74b086aaf split: move Claude SDK and plan doc to sibling stack
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 6496aedc92 split: move Claude provider surface to sibling stack
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex e972fad300 model: move Claude catalogs out of core
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 1bd4d6d953 contracts: move Claude schemas out of core
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge e9655d43d5 Show unavailable providers as coming-soon placeholders
- Keep Claude Code and Cursor in provider list as disabled options
- Remove unused Claude agent SDK dependency from server
- Delete stale plan-mode deep-dive doc
2026-03-05 23:00:41 -08:00
Julius Marminge f0a7ddaf80 sync lock 2026-03-05 23:00:41 -08:00
Julius Marminge ed6c12c709 rm tmp 2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex a1b75fe17f test: move Claude coverage out of core PR
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 2e5e75699e Remove Claude adapter from stack base
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex be308beacc Remove Cursor adapter from stack base
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 2589176c82 Add GPT-5.4 to Codex model options
- include `gpt-5.4` in Codex app model option coverage
- only keep truly custom Cursor models in the custom model option list
2026-03-05 23:00:41 -08:00
Julius Marminge adfd99bdec Plumb Codex model options through orchestration and composer
- Replace ad-hoc `effort` handling with provider `modelOptions` across decider/reactor/adapters
- Map Codex `reasoningEffort` and `fastMode` to turn/session params (`effort`, `serviceTier`)
- Persist runtime/interaction/model selections from composer and sync them before sending turns
- Move model normalization/helpers into `@t3tools/shared/model` with updated contracts/tests
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 1683ee7b11 Fix post-rebase typecheck regressions
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge e6575c4149 Prune internal contract exports and remove checkpoint RPC schemas
- Stop exporting internal-only schema constants/types across contracts modules
- Remove unused provider checkpoint list/revert/diff RPC contract schemas
- Keep public contract surface focused on externally consumed types
2026-03-05 23:00:41 -08:00
Julius Marminge ae7283e021 style 2026-03-05 23:00:41 -08:00
Julius Marminge 640a2cca9f Persist proposed plans as first-class thread projection data
- Add `thread.proposed-plan-upserted` orchestration flow from ingestion through decider/projector
- Store proposed plans in a dedicated projection table and include them in snapshot queries
- Update provider runtime/web handling and tests to use proposed plans instead of assistant message wrappers
2026-03-05 23:00:41 -08:00
Julius Marminge 12edc3455c Add plan interaction mode and user-input request handling
- Wire Codex plan mode through turn start, including collaboration settings
- Track and answer pending `requestUserInput` prompts instead of auto-empty responses
- Persist/project thread `interactionMode` (schema, migration, queries) and update tests/contracts
2026-03-05 23:00:41 -08:00
Julius Marminge 26f631b638 Migrate provider runtime/session flow to thread-scoped IDs
- Replace provider session-id centric plumbing with thread-id based runtime handling across server orchestration and provider layers
- Update persistence repositories/migrations and contracts for threadless runtime semantics
- Refresh integration/unit tests and web session/store types to match the new runtime model
2026-03-05 23:00:41 -08:00
Julius Marminge 981cf40561 Improve session restart handling and server logging
- add structured lifecycle logs for Codex thread open/resume and provider session restarts
- introduce persistent server file logging layer and tighten WebSocket server startup/finalizer ordering
- preserve env-based boolean overrides in dev runner and stop forcing WS event logging in dev
- enrich provider session listing from persisted bindings and fix Claude rate-limit/task-id event mapping
- update orchestration and dev-runner tests for runtime-mode restart and env-flag behavior
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 689dda59e9 Persist thread runtime mode and handle mode-switch session restarts
- Add `thread.runtime-mode.set` -> `thread.runtime-mode-set` flow in decider/reactors/projectors
- Persist runtime mode on thread/session projections with new DB migrations
- Update provider and Codex integration tests to verify thread continuity across mode changes

Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 0a67f9dd39 Clarify Cursor plan-mode semantics and ACP extension mapping
- Define Cursor operating mode as binary `default | plan`
- Document mapping for `cursor/ask_question`, `cursor/create_plan`, and `cursor/update_todos`
- Update capability and fallback guidance based on docs plus probe evidence
2026-03-05 23:00:41 -08:00
Julius Marminge df6bb188d4 Rewrite plan-mode deep dive as implementation blueprint
- Reframe doc into a provider-agnostic implementation plan for Codex, Claude, and Cursor
- Define canonical mode, plan, and structured user-input models plus capability-driven UI behavior
- Add concrete orchestration, adapter, frontend, and test work items for rollout
2026-03-05 23:00:41 -08:00
Julius Marminge 03053d9ee0 Add runtime mode tracking across provider orchestration pipeline
- extend provider and orchestration contracts for runtime mode-aware events
- persist runtime mode fields in projection thread session storage and migration 006
- update adapters, reactors, projections, websocket/web session logic, and tests
- add plan mode deep dive docs and probe artifacts for ACP behavior
2026-03-05 23:00:41 -08:00
Julius Marminge 9c4d7a83e2 Handle session.state.changed in provider runtime ingestion
- Map runtime session state transitions to orchestration session status
- Persist error reasons from `session.state.changed` error events
- Add coverage for waiting/error/stopped/ready transition handling
2026-03-05 23:00:41 -08:00
Julius Marminge 7425a3c4b3 Support provider custom models and fix runtime event mapping
- add per-provider custom model settings/options in web settings and chat picker
- preserve Codex request type on `serverRequest/resolved` events
- validate empty Cursor prompts before turn start and keep tool-call item types consistent
- add tests for new adapter and model-settings behavior
- add PR event review checklist document
2026-03-05 23:00:41 -08:00
Julius Marminge 344e04b623 Inject native event loggers into provider adapters
- allow Claude/Cursor adapters to accept an injected native event logger
- make native event writes effectful/non-blocking so logging cannot break message handling
- update adapter tests to assert native observability events via in-memory loggers
- fix runtime session ID conversion when resolving canonical event thread IDs
2026-03-05 23:00:41 -08:00
Julius Marminge 7b71e234e0 Normalize runtime events and tighten orchestration approval flow
- migrate fixtures/tests/adapters to canonical provider runtime event payloads
- route checkpoint capture off `turn.completed` only and drop legacy `checkpoint.captured` path
- stop faking approval resolution when provider reports stale/unknown pending requests
2026-03-05 23:00:41 -08:00
Julius Marminge 77f67d1766 Handle stale approval responses and cover Cursor resume IDs
- Catch provider approval response failures and emit `provider.approval.respond.failed`
- Auto-resolve approvals when provider reports unknown pending request IDs
- Add tests for Cursor ACP resume via `resumeCursor.acpSessionId` and legacy `sessionId`
2026-03-05 23:00:41 -08:00
Julius Marminge 1c2ed75937 Normalize approval request kinds and persist draft provider state
- map canonical approval request types to `requestKind` across ingestion and web pending approvals
- auto-approve Cursor permission requests when approval policy is `never`
- persist per-thread composer provider selection in draft store and use it in ChatView
- disable Cursor traits picker while model selection is locked
2026-03-05 23:00:41 -08:00
Julius Marminge 17e6cad479 Respect provider model-switch limits and canonical runtime events
- Add provider capability plumbing for `sessionModelSwitch` and use it in session/turn routing
- Keep Cursor sessions stable when in-session model switching is unsupported
- Ingest canonical runtime events (`content.delta`, `item.*`, `request.*`) with legacy-shape compatibility
2026-03-05 23:00:41 -08:00
Julius Marminge feff86638e Fix effort and provider handling in thread turn start
- Only include `effort` in start command when a value is selected
- Persist effort selection via composer draft state and hide picker when unavailable
- Add optional `provider` to `ClientThreadTurnStartCommand`
- Simplify thread model fallback selection in `ChatView`
2026-03-05 23:00:41 -08:00
Julius Marminge ad28eaa86f Scope composer draft reasoning effort to Codex options
- Switch draft store types to `CodexReasoningEffort`
- Validate and default effort using Codex-specific option/default constants
2026-03-05 23:00:41 -08:00
Julius Marminge d36bbc177d Unify provider runtime events and add Cursor adapter layer
- migrate Claude/Codex/registry adapters to canonical runtime event types and payload shapes
- add Cursor layer adapter plus tests and wire it through server layers
- update provider contracts/runtime schemas and related adapter tests
2026-03-05 23:00:41 -08:00
Julius Marminge aeddb57594 Scope reasoning effort defaults and options by provider
- Replace global reasoning constants with provider-scoped effort options/defaults
- Update ChatView to use Codex-specific reasoning effort types and default lookup
- Expand model contract tests for provider-specific reasoning effort behavior
2026-03-05 23:00:41 -08:00
Julius Marminge f2253269dd Introduce v2 provider runtime event schema and validation tests
- Restructure runtime events around a shared base plus typed payloads
- Add runtime-branded IDs and new event types (plan, item, request, user-input)
- Remove legacy canonical event names from docs and add schema decode/rejection tests
2026-03-05 23:00:41 -08:00
Julius Marminge d08cecf126 Document Cursor ACP mapping in canonical runtime event spec
- Add Cursor ACP raw source types to `RuntimeEventRaw.source`
- Define canonical mappings for ACP lifecycle, updates, permissions, and errors
- Expand cross-provider equivalence table to include Cursor ACP and renumber sections
2026-03-05 23:00:41 -08:00
Julius Marminge afad39d125 Revise Cursor provider plan for ACP JSON-RPC integration
- Switch plan from `agent -p` stream-json to `agent acp` JSON-RPC transport
- Document ACP session, permission, event-mapping, and interrupt/recovery behavior
- Update implementation phases, tests, and delivery checklist for ACP-first design
2026-03-05 23:00:41 -08:00
Julius Marminge f97916f371 Add Cursor ACP probe script and captured session logs
- add `scripts/cursor-acp-probe.mjs` to run ACP protocol probing scenarios
- update `package.json` scripts for probe execution
- include generated probe summaries/transcripts under `.tmp/acp-probe/`
2026-03-05 23:00:41 -08:00
Julius Marminge 86e204439e Add Cursor provider support across backend, contracts, and UI
- Accept `cursor` as a first-class provider in orchestration, persistence, and session directory flows
- Update model/provider inference and normalization to handle Cursor model aliases
- Revamp chat provider/model picker with Cursor-specific trait controls and add coverage in tests
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 04a931fc79 Add Cursor CLI stream event schemas and decoding tests
- define `CursorAdapter` service contract and Cursor stream-json schema types
- add `CursorCliStreamEvent` decoding tests for system/thinking/tool/result/retry events
- add implementation plan for Cursor provider integration

Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 75354bbd96 Track runtime event sequence and order thread activities by sequence
- add per-session `sessionSequence` on provider runtime events and persist activity `sequence`
- migrate `projection_thread_activities` with nullable `sequence` column + index
- sort server/web activity projections by sequence fallback to timestamp/id
- allow provider sessions/turns to start before a real threadId is emitted
2026-03-05 23:00:41 -08:00
Julius Marminge 6a10e97a97 Align Claude permissions and provider-specific reasoning effort
- Default Claude sessions to bypass permissions when approval policy is `never`, while preserving explicit `permissionMode`
- Hide/send reasoning effort only for providers that support it in ChatView
- Add coverage for Claude permission-mode derivation and precedence, and update runtime event model docs
2026-03-05 23:00:41 -08:00
Julius Marminge 1542b00db2 Stabilize Claude turn event ordering and native event logging
- Preserve active turn state when `session.started`/`thread.started` arrive mid-turn
- Emit `message.delta` from assistant text when stream deltas are missing, then complete the message
- Add Claude native SDK NDJSON observability logging and wire its log path in server layers
- Expand ingestion/adapter tests to cover mid-turn lifecycle and delta fallback behavior
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex f79f8bac80 Fix ProviderService sendTurn recovery expectation after rebase
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 92f1a4aa3c Ignore stale resume cursors and Claude placeholder thread IDs
- Do not pass `resumeCursor` when restarting a session after changing providers
- Treat synthetic Claude thread IDs (`claude-thread-*`) as unscoped during runtime ingestion
- Add tests covering provider-switch restart behavior and Claude turn lifecycle acceptance
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 11f929c397 Align orchestration integration tests with latestTurn metadata
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 0616338911 Fix Claude resume cursor to only persist valid session UUIDs
- Stop synthesizing `resume` from generated thread IDs
- Persist resume session ID from query messages when available
- Validate resume/sessionId values as UUIDs before reuse
- Add tests for valid UUID resume passthrough and no synthesized resume
2026-03-05 23:00:41 -08:00
Julius Marminge 58427d565d Refactor ClaudeCodeAdapter session flow and stream handling
- Replace manual prompt async iterator with `Stream.fromQueue(...).toAsyncIterable`
- Use `Ref` for shared session context in tool approval callbacks
- Simplify timestamp/ID generation and close sessions via queue shutdown
2026-03-05 23:00:41 -08:00
Julius Marminge 9b3dbada17 Integrate Claude agent SDK into server provider adapter
- add `@anthropic-ai/claude-agent-sdk` dependency for `apps/server`
- replace placeholder Claude adapter with live session/query/event handling
- add comprehensive adapter tests for runtime events, approvals, resume, rollback, and model overrides
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 4797f99cf8 Include all provider models in /model slash command
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 50f35351a2 Fix Claude model fallback in web store sync
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex c7460bde16 Update Claude model catalog to latest 4.6/4.5 gen
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 2c110e8ce2 Show provider logos in composer model trigger
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 5707a6ee1d Use grouped provider/model select in chat composer
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 291411a45e Inline Claude adapter behavior into live layer
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 87abc22f39 unnecessary catch 2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 441582dbb8 Use typed errors for unavailable Claude runtime path
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 1b1ede92ba Make Claude runtime boundary Effect-native
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 4ec7ae33c5 Add Claude integration coverage across orchestration flows
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex 317fcc659b Add Claude checkpoint and revert reactor coverage
Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex ff7e084a33 Enable Claude provider selection in chat composer
Add provider-aware model options and include provider in turn-start dispatch.

Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex c590beb4e3 Support provider-aware session selection in reactor
Add restart semantics when requested provider changes and cover with tests.

Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marmingeandcodex e9ced44ac6 Wire Claude adapter into registry and server provider layer
Add provider-service routing coverage for explicit claudeCode sessions.

Co-authored-by: codex <[email protected]>
2026-03-05 23:00:41 -08:00
Julius Marminge 802cd127d1 Add Claude Code adapter live layer with error mapping tests
- introduce `ClaudeCodeAdapter` service and live layer wiring
- map runtime/session/request failures into provider adapter error types
- add coverage for validation, session-not-found mapping, lifecycle forwarding, and event passthrough
2026-03-05 23:00:41 -08:00
Julius Marminge 931c56b2d0 revised plan 2026-03-05 23:00:41 -08:00
Julius Marminge 484662b2d4 redo contracts a bit 2026-03-05 23:00:41 -08:00
Julius Marminge 2cd04f08c1 Add provider-specific model resolution and defaults
- Add per-provider model options, defaults, and slug aliases
- Add provider-aware model normalization/resolution helpers
- Preserve Codex-only constants/functions for backward compatibility
- Extend tests to cover Claude aliases and provider-specific fallback behavior
2026-03-05 23:00:41 -08:00
Theo Browne 4916dad78e license 2026-03-05 22:58:18 -08:00
333 changed files with 23659 additions and 12422 deletions

No files matched your search

-20
View File
@@ -1,20 +0,0 @@
---
name: btca-cli
description: btca is a cli for getting information from other git repositories by querying them with natural language. Spawns an external subagent to explore external codebases (i.e. a github repo) and answer questions about them. Great when integrating complex libraries, frameworks, or tools.
---
btca is a cli for asking questions about various folders, primarily git repositories. It's built to give you the exact information you need without bloating your context window. btca uses agents under the hood to answer your question, so prompt it the way you would prompt a tool similar to yourself.
For example, assuming you have a resource named `codex`, you can ask questions like:
```bash
btca ask -r codex -q "What is the return format for Codex App Server responses? Are there any edge cases worth knowing?"
```
Your prompt may include specific names for resources to use, if they do then you should try those first. If you need to check available resources, you can use the `btca resources` command.
New resources can be created if the ones you need do not yet exist.
```bash
btca add -n svelte-dev https://github.com/sveltejs/svelte.dev
```
@@ -1,3 +0,0 @@
interface:
display_name: "BTCA CLI"
short_description: "Help with BTCA CLI setup and usage workflows"
+143
View File
@@ -0,0 +1,143 @@
# Architecture
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ wsTransport (state machine) │
│ Typed push decode at boundary │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ServerPushBus (ordered pushes) │
│ ServerReadiness (startup gate) │
│ OrchestrationEngine │
│ ProviderService │
│ CheckpointReactor │
│ RuntimeReceiptBus │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
## Components
- **Browser app**: The React app renders session state, owns the client-side WebSocket transport, and treats typed push events as the boundary between server runtime details and UI state.
- **Server**: `apps/server` is the main coordinator. It serves the web app, accepts WebSocket requests, waits for startup readiness before welcoming clients, and sends all outbound pushes through a single ordered push path.
- **Provider runtime**: `codex app-server` does the actual provider/session work. The server talks to it over JSON-RPC on stdio and translates those runtime events into the app's orchestration model.
- **Background workers**: Long-running async flows such as runtime ingestion, command reaction, and checkpoint processing run as queue-backed workers. This keeps work ordered, reduces timing races, and gives tests a deterministic way to wait for the system to go idle.
- **Runtime signals**: The server emits lightweight typed receipts when important async milestones finish, such as checkpoint capture, diff finalization, or a turn becoming fully quiescent. Tests and orchestration code wait on these signals instead of polling internal state.
## Event Lifecycle
### Startup and client connect
```mermaid
sequenceDiagram
participant Browser
participant Transport as WsTransport
participant Server as wsServer
participant Layers as serverLayers
participant Ready as ServerReadiness
participant Push as ServerPushBus
Browser->>Transport: Load app and open WebSocket
Transport->>Server: Connect
Server->>Layers: Start runtime services
Server->>Ready: Wait for startup barriers
Ready-->>Server: Ready
Server->>Push: Publish server.welcome
Push-->>Transport: Ordered welcome push
Transport-->>Browser: Hydrate initial state
```
1. The browser boots [`WsTransport`][1] and registers typed listeners in [`wsNativeApi`][2].
2. The server accepts the connection in [`wsServer`][3] and brings up the runtime graph defined in [`serverLayers`][7].
3. [`ServerReadiness`][4] waits until the key startup barriers are complete.
4. Once the server is ready, [`wsServer`][3] sends `server.welcome` from the contracts in [`ws.ts`][6] through [`ServerPushBus`][5].
5. The browser receives that ordered push through [`WsTransport`][1], and [`wsNativeApi`][2] uses it to seed local client state.
### User turn flow
```mermaid
sequenceDiagram
participant Browser
participant Transport as WsTransport
participant Server as wsServer
participant Provider as ProviderService
participant Codex as codex app-server
participant Ingest as ProviderRuntimeIngestion
participant Engine as OrchestrationEngine
participant Push as ServerPushBus
Browser->>Transport: Send user action
Transport->>Server: Typed WebSocket request
Server->>Provider: Route request
Provider->>Codex: JSON-RPC over stdio
Codex-->>Ingest: Provider runtime events
Ingest->>Engine: Normalize into orchestration events
Engine-->>Server: Domain events
Server->>Push: Publish orchestration.domainEvent
Push-->>Browser: Typed push
```
1. A user action in the browser becomes a typed request through [`WsTransport`][1] and the browser API layer in [`nativeApi`][12].
2. [`wsServer`][3] decodes that request using the shared WebSocket contracts in [`ws.ts`][6] and routes it to the right service.
3. [`ProviderService`][8] starts or resumes a session and talks to `codex app-server` over JSON-RPC on stdio.
4. Provider-native events are pulled back into the server by [`ProviderRuntimeIngestion`][9], which converts them into orchestration events.
5. [`OrchestrationEngine`][10] persists those events, updates the read model, and exposes them as domain events.
6. [`wsServer`][3] pushes those updates to the browser through [`ServerPushBus`][5] on channels defined in [`orchestration.ts`][11].
### Async completion flow
```mermaid
sequenceDiagram
participant Server as wsServer
participant Worker as Queue-backed workers
participant Cmd as ProviderCommandReactor
participant Checkpoint as CheckpointReactor
participant Receipt as RuntimeReceiptBus
participant Push as ServerPushBus
participant Browser
Server->>Worker: Enqueue follow-up work
Worker->>Cmd: Process provider commands
Worker->>Checkpoint: Process checkpoint tasks
Checkpoint->>Receipt: Publish completion receipt
Cmd-->>Server: Produce orchestration changes
Checkpoint-->>Server: Produce orchestration changes
Server->>Push: Publish resulting state updates
Push-->>Browser: User-visible push
```
1. Some work continues after the initial request returns, especially in [`ProviderRuntimeIngestion`][9], [`ProviderCommandReactor`][13], and [`CheckpointReactor`][14].
2. These flows run as queue-backed workers using [`DrainableWorker`][16], which helps keep side effects ordered and test synchronization deterministic.
3. When a milestone completes, the server emits a typed receipt on [`RuntimeReceiptBus`][15], such as checkpoint completion or turn quiescence.
4. Tests and orchestration code wait on those receipts instead of polling git state, projections, or timers.
5. Any user-visible state changes produced by that async work still go back through [`wsServer`][3] and [`ServerPushBus`][5].
[1]: ../apps/web/src/wsTransport.ts
[2]: ../apps/web/src/wsNativeApi.ts
[3]: ../apps/server/src/wsServer.ts
[4]: ../apps/server/src/wsServer/readiness.ts
[5]: ../apps/server/src/wsServer/pushBus.ts
[6]: ../packages/contracts/src/ws.ts
[7]: ../apps/server/src/serverLayers.ts
[8]: ../apps/server/src/provider/Layers/ProviderService.ts
[9]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
[10]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
[11]: ../packages/contracts/src/orchestration.ts
[12]: ../apps/web/src/nativeApi.ts
[13]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
[14]: ../apps/server/src/orchestration/Layers/CheckpointReactor.ts
[15]: ../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts
[16]: ../packages/shared/src/DrainableWorker.ts
+6
View File
@@ -0,0 +1,6 @@
# CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
+5
View File
@@ -0,0 +1,5 @@
# Codex prerequisites
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
+180
View File
@@ -0,0 +1,180 @@
# Encyclopedia
This is a living glossary for T3 Code. It explains what common terms mean in this codebase.
## Table of contents
- [Project and workspace](#project-and-workspace)
- [Thread timeline](#thread-timeline)
- [Orchestration](#orchestration)
- [Provider runtime](#provider-runtime)
- [Checkpointing](#checkpointing)
## Concepts
### Project and workspace
#### Project
The top-level workspace record in the app. In [the orchestration contracts][1], a project has a `workspaceRoot`, a title, and one or more threads. See [workspace-layout.md][2].
#### Workspace root
The root filesystem path for a project. In [the orchestration model][1], it is the base directory for branches and optional worktrees. See [workspace-layout.md][2].
#### Worktree
A Git worktree used as an isolated workspace for a thread. If a thread has a `worktreePath` in [the contracts][1], it runs there instead of in the main working tree. Git operations live in [GitCore.ts][3].
### Thread timeline
#### Thread
The main durable unit of conversation and workspace history. In [the orchestration contracts][1], a thread holds messages, activities, checkpoints, and session-related state. See [projector.ts][4].
#### Turn
A single user-to-assistant work cycle inside a thread. It starts with user input and ends when follow-up work like checkpointing settles. See [the contracts][1], [ProviderRuntimeIngestion.ts][5], and [CheckpointReactor.ts][6].
#### Activity
A user-visible log item attached to a thread. In [the contracts][1], activities cover important non-message events like approvals, tool actions, and failures. They are projected into thread state in [projector.ts][4].
### Orchestration
Orchestration is the server-side domain layer that turns runtime activity into stable app state. The main entry point is [OrchestrationEngine.ts][7], with core logic in [decider.ts][8] and [projector.ts][4].
#### Aggregate
The domain object a command or event belongs to. In [the contracts][1], that is usually `project` or `thread`. See [decider.ts][8].
#### Command
A typed request to change domain state. In [the contracts][1], commands are validated in [commandInvariants.ts][9] and turned into events by [decider.ts][8].
Examples include `thread.create`, `thread.turn.start`, and `thread.checkpoint.revert`.
#### Domain Event
A persisted fact that something already happened. In [the contracts][1], events are the source of truth, and [projector.ts][4] shows how they are applied.
Examples include `thread.created`, `thread.message-sent`, and `thread.turn-diff-completed`.
#### Decider
The pure orchestration logic that turns commands plus current state into events. The core implementation is in [decider.ts][8], with preconditions in [commandInvariants.ts][9].
#### Projection
A read-optimized view derived from events. See [projector.ts][4], [ProjectionPipeline.ts][11], and [ProjectionSnapshotQuery.ts][10].
#### Projector
The logic that applies domain events to the read model or projection tables. See [projector.ts][4] and [ProjectionPipeline.ts][11].
#### Read model
The current materialized view of orchestration state. In [the contracts][1], it holds projects, threads, messages, activities, checkpoints, and session state. See [ProjectionSnapshotQuery.ts][10] and [OrchestrationEngine.ts][7].
#### Reactor
A side-effecting service that handles follow-up work after events or runtime signals. Examples include [CheckpointReactor.ts][6], [ProviderCommandReactor.ts][12], and [ProviderRuntimeIngestion.ts][5].
#### Receipt
A lightweight typed runtime signal emitted when an async milestone completes. See [RuntimeReceiptBus.ts][13].
Examples include `checkpoint.baseline.captured`, `checkpoint.diff.finalized`, and `turn.processing.quiesced`, which are emitted by flows such as [CheckpointReactor.ts][6].
#### Quiesced
"Quiesced" means a turn has gone quiet and stable. In [the receipt schema][13], it means the follow-up work has settled, including work in [CheckpointReactor.ts][6].
### Provider runtime
The live backend agent implementation and its event stream. The main service is [ProviderService.ts][14], the adapter contract is [ProviderAdapter.ts][15], and the overview is in [provider-architecture.md][16].
#### Provider
The backend agent runtime that actually performs work. See [ProviderService.ts][14], [ProviderAdapter.ts][15], and [CodexAdapter.ts][17].
#### Session
The live provider-backed runtime attached to a thread. Session shape is in [the orchestration contracts][1], and lifecycle is managed in [ProviderService.ts][14].
#### Runtime mode
The safety/access mode for a thread or session. In [the contracts][1], the main values are `approval-required` and `full-access`. See [runtime-modes.md][18].
#### Interaction mode
The agent interaction style for a thread. In [the contracts][1], the main values are `default` and `plan`. See [runtime-modes.md][18].
#### Assistant delivery mode
Controls how assistant text reaches the thread timeline. In [the contracts][1], `streaming` updates incrementally and `buffered` delivers a completed result. See [ProviderService.ts][14].
#### Snapshot
A point-in-time view of state. The word is used in multiple layers, including orchestration, provider, and checkpointing. See [ProjectionSnapshotQuery.ts][10], [ProviderAdapter.ts][15], and [CheckpointStore.ts][19].
### Checkpointing
Checkpointing captures workspace state over time so the app can diff turns and restore earlier points. The main pieces are [CheckpointStore.ts][19], [CheckpointDiffQuery.ts][20], and [CheckpointReactor.ts][6].
#### Checkpoint
A saved snapshot of a thread workspace at a particular turn. In practice it is a hidden Git ref in [CheckpointStore.ts][19] plus a projected summary from [ProjectionCheckpoints.ts][21]. Capture and lifecycle work happen in [CheckpointReactor.ts][6].
#### Checkpoint ref
The durable identifier for a filesystem checkpoint, stored as a Git ref. It is typed in [the contracts][1], constructed in [Utils.ts][22], and used by [CheckpointStore.ts][19].
#### Checkpoint baseline
The starting checkpoint for diffing a thread timeline. This flow is surfaced through [RuntimeReceiptBus.ts][13], coordinated in [CheckpointReactor.ts][6], and supported by [Utils.ts][22].
#### Checkpoint diff
The patch difference between two checkpoints. Query logic lives in [CheckpointDiffQuery.ts][20], diff parsing lives in [Diffs.ts][23], and finalization is coordinated by [CheckpointReactor.ts][6].
#### Turn diff
The file patch and changed-file summary for one turn. It is usually computed in [CheckpointDiffQuery.ts][20], represented in [the contracts][1], and recorded into thread state by [projector.ts][4].
## Practical Shortcuts
- If you see `requested`, think "intent recorded".
- If you see `completed`, think "result applied".
- If you see `receipt`, think "async milestone signal".
- If you see `checkpoint`, think "workspace snapshot for diff/restore".
- If you see `quiesced`, think "all relevant follow-up work has gone idle".
## Related Docs
- [architecture.md][24]
- [provider-architecture.md][16]
- [runtime-modes.md][18]
- [workspace-layout.md][2]
[1]: ../packages/contracts/src/orchestration.ts
[2]: ./workspace-layout.md
[3]: ../apps/server/src/git/Layers/GitCore.ts
[4]: ../apps/server/src/orchestration/projector.ts
[5]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
[6]: ../apps/server/src/orchestration/Layers/CheckpointReactor.ts
[7]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
[8]: ../apps/server/src/orchestration/decider.ts
[9]: ../apps/server/src/orchestration/commandInvariants.ts
[10]: ../apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
[11]: ../apps/server/src/orchestration/Layers/ProjectionPipeline.ts
[12]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
[13]: ../apps/server/src/orchestration/Services/RuntimeReceiptBus.ts
[14]: ../apps/server/src/provider/Layers/ProviderService.ts
[15]: ../apps/server/src/provider/Services/ProviderAdapter.ts
[16]: ./provider-architecture.md
[17]: ../apps/server/src/provider/Layers/CodexAdapter.ts
[18]: ./runtime-modes.md
[19]: ../apps/server/src/checkpointing/Services/CheckpointStore.ts
[20]: ../apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts
[21]: ../apps/server/src/persistence/Services/ProjectionCheckpoints.ts
[22]: ../apps/server/src/checkpointing/Utils.ts
[23]: ../apps/server/src/checkpointing/Diffs.ts
[24]: ./architecture.md
+30
View File
@@ -0,0 +1,30 @@
# Provider architecture
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: typed envelopes with `channel`, `sequence` (monotonic per connection), and channel-specific `data`
Push channels: `server.welcome`, `server.configUpdated`, `terminal.event`, `orchestration.domainEvent`. Payloads are schema-validated at the transport boundary (`wsTransport.ts`). Decode failures produce structured `WsDecodeDiagnostic` with `code`, `reason`, and path info.
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
## Client transport
`wsTransport.ts` manages connection state: `connecting` → `open` → `reconnecting` → `closed` → `disposed`. Outbound requests are queued while disconnected and flushed on reconnect. Inbound pushes are decoded and validated at the boundary, then cached per channel. Subscribers can opt into `replayLatest` to receive the last push on subscribe.
## Server-side orchestration layers
Provider runtime events flow through queue-based workers:
1. **ProviderRuntimeIngestion** — consumes provider runtime streams, emits orchestration commands
2. **ProviderCommandReactor** — reacts to orchestration intent events, dispatches provider calls
3. **CheckpointReactor** — captures git checkpoints on turn start/complete, publishes runtime receipts
All three use `DrainableWorker` internally and expose `drain()` for deterministic test synchronization.
+22
View File
@@ -0,0 +1,22 @@
# Quick start
```bash
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
bun run build
bun run start
# Build a shareable macOS .dmg (arm64 by default)
bun run dist:desktop:dmg
# Or from any project directory after publishing:
npx t3
```
+6
View File
@@ -0,0 +1,6 @@
# Runtime modes
T3 Code has a global runtime mode switch in the chat toolbar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
+42
View File
@@ -0,0 +1,42 @@
# Scripts
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
## Desktop `.dmg` packaging notes
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
## Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5733`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
+7
View File
@@ -0,0 +1,7 @@
# Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
- `/packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`, `@t3tools/shared/DrainableWorker`) — no barrel index.
+108
View File
@@ -0,0 +1,108 @@
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, stack traces, or screenshots
description: Paste the most relevant output only. Redact secrets.
render: shell
- 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.
+31
View File
@@ -0,0 +1,31 @@
# Trust list for this repository.
#
# External contributors listed here are treated as trusted by the vouch
# workflow. Collaborators with write access are automatically trusted and
# do not need to be duplicated in this file.
#
# Syntax:
# github:username
# -github:username reason for denouncement
#
# Keep entries sorted alphabetically.
github:adityavardhansharma
github:binbandit
github:chuks-qua
github:cursoragent
github:gbarros-dev
github:github-actions[bot]
github:hwanseoc
github:jamesx0416
github:jasonLaster
github:JoeEverest
github:maria-rcks
github:nmggithub
github:Noojuno
github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
+33
View File
@@ -0,0 +1,33 @@
<!--
⚠️ READ BEFORE OPENING ⚠️
We are not actively accepting contributions right now.
You can still open a PR, but please do so knowing there is a high chance
we may close it without merging it, or never review it.
- Small, focused PRs are strongly preferred. Bug fixes are most likely to be merged.
- New features will most likely just annoy us.
- 1,000+ line PRs with a bunch of new features will probably get you banned from the repo.
-->
## What Changed
<!-- Describe the change clearly and keep scope tight. -->
## Why
<!-- Explain the problem being solved and why this approach is the right one. -->
## UI Changes
<!-- If this PR changes UI, include clear before/after screenshots.
If the change involves motion or interaction, include a short video.
Delete this section if not applicable. -->
## Checklist
- [ ] This PR is small and focused
- [ ] I explained what changed and why
- [ ] I included before/after screenshots for any UI changes
- [ ] I included a video for animation/interaction changes
+28 -5
View File
@@ -8,11 +8,11 @@ on:
jobs: jobs:
quality: quality:
name: Lint, Typecheck, Test, Browser Test, Build name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404 runs-on: blacksmith-4vcpu-ubuntu-2404
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v6
- name: Setup Bun - name: Setup Bun
uses: oven-sh/setup-bun@v2 uses: oven-sh/setup-bun@v2
@@ -20,12 +20,12 @@ jobs:
bun-version-file: package.json bun-version-file: package.json
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v6
with: with:
node-version-file: package.json node-version-file: package.json
- name: Cache Bun and Turbo - name: Cache Bun and Turbo
uses: actions/cache@v4 uses: actions/cache@v5
with: with:
path: | path: |
~/.bun/install/cache ~/.bun/install/cache
@@ -35,7 +35,7 @@ jobs:
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}- ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers - name: Cache Playwright browsers
uses: actions/cache@v4 uses: actions/cache@v5
with: with:
path: ~/.cache/ms-playwright path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }} key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
@@ -45,6 +45,9 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install --frozen-lockfile
- name: Format
run: bun run fmt:check
- name: Lint - name: Lint
run: bun run lint run: bun run lint
@@ -69,3 +72,23 @@ jobs:
run: | run: |
test -f apps/desktop/dist-electron/preload.js test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
release_smoke:
name: Release Smoke
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+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}`);
+199
View File
@@ -0,0 +1,199 @@
name: PR Vouch
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
issue_comment:
types: [created]
push:
branches:
- main
paths:
- .github/VOUCHED.td
- .github/workflows/pr-vouch.yml
permissions:
contents: read
issues: write
pull-requests: write
jobs:
collect-targets:
name: Collect PR targets
runs-on: ubuntu-24.04
outputs:
targets: ${{ steps.collect.outputs.targets }}
steps:
- id: collect
uses: actions/github-script@v8
with:
script: |
if (context.eventName === "pull_request_target") {
const pr = context.payload.pull_request;
core.setOutput("targets", JSON.stringify([{ number: pr.number, user: pr.user.login }]));
return;
}
if (context.eventName === "issue_comment") {
const issue = context.payload.issue;
const body = context.payload.comment?.body ?? "";
if (!issue?.pull_request || !body.includes("/recheck-vouch")) {
core.setOutput("targets", "[]");
return;
}
core.setOutput(
"targets",
JSON.stringify([{ number: issue.number, user: issue.user.login }]),
);
return;
}
const pulls = await github.paginate(github.rest.pulls.list, {
owner: context.repo.owner,
repo: context.repo.repo,
state: "open",
per_page: 100,
});
const targets = pulls.map((pull) => ({
number: pull.number,
user: pull.user.login,
}));
core.setOutput("targets", JSON.stringify(targets));
label:
name: Label PR ${{ matrix.target.number }}
needs: collect-targets
if: ${{ needs.collect-targets.outputs.targets != '[]' }}
runs-on: ubuntu-24.04
concurrency:
group: pr-vouch-${{ matrix.target.number }}
cancel-in-progress: true
strategy:
fail-fast: false
matrix:
target: ${{ fromJson(needs.collect-targets.outputs.targets) }}
steps:
- id: vouch
name: Check PR author trust
uses: mitchellh/vouch/action/check-user@v1
with:
user: ${{ matrix.target.user }}
allow-fail: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Sync PR labels
uses: actions/github-script@v8
env:
PR_NUMBER: ${{ matrix.target.number }}
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
with:
script: |
const issueNumber = Number(process.env.PR_NUMBER);
const status = process.env.VOUCH_STATUS;
const managedLabels = [
{
name: "vouch:trusted",
color: "1f883d",
description: "PR author is trusted by repo permissions or the VOUCHED list.",
},
{
name: "vouch:unvouched",
color: "fbca04",
description: "PR author is not yet trusted in the VOUCHED list.",
},
{
name: "vouch:denounced",
color: "d1242f",
description: "PR author is explicitly blocked by the VOUCHED list.",
},
];
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
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;
}
}
}
}
const nextLabelName =
status === "denounced"
? "vouch:denounced"
: ["bot", "collaborator", "vouched"].includes(status)
? "vouch:trusted"
: "vouch:unvouched";
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}: ${status} -> ${nextLabelName}`);
+47 -40
View File
@@ -22,10 +22,12 @@ jobs:
outputs: outputs:
version: ${{ steps.release_meta.outputs.version }} version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }} tag: ${{ steps.release_meta.outputs.tag }}
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
make_latest: ${{ steps.release_meta.outputs.make_latest }}
ref: ${{ github.sha }} ref: ${{ github.sha }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v6
- id: release_meta - id: release_meta
name: Resolve release version name: Resolve release version
@@ -45,6 +47,13 @@ jobs:
echo "version=$version" >> "$GITHUB_OUTPUT" echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT" echo "tag=v$version" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
- name: Setup Bun - name: Setup Bun
uses: oven-sh/setup-bun@v2 uses: oven-sh/setup-bun@v2
@@ -52,7 +61,7 @@ jobs:
bun-version-file: package.json bun-version-file: package.json
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v6
with: with:
node-version-file: package.json node-version-file: package.json
@@ -98,7 +107,7 @@ jobs:
arch: x64 arch: x64
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v6
with: with:
ref: ${{ needs.preflight.outputs.ref }} ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0 fetch-depth: 0
@@ -109,13 +118,16 @@ jobs:
bun-version-file: package.json bun-version-file: package.json
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v6
with: with:
node-version-file: package.json node-version-file: package.json
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile 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 - name: Build desktop artifact
shell: bash shell: bash
env: env:
@@ -205,7 +217,7 @@ jobs:
fi fi
- name: Upload build artifacts - name: Upload build artifacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v7
with: with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }} name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release-publish/* path: release-publish/*
@@ -217,7 +229,7 @@ jobs:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v6
with: with:
ref: ${{ needs.preflight.outputs.ref }} ref: ${{ needs.preflight.outputs.ref }}
@@ -227,7 +239,7 @@ jobs:
bun-version-file: package.json bun-version-file: package.json
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v6
with: with:
node-version-file: package.json node-version-file: package.json
registry-url: https://registry.npmjs.org registry-url: https://registry.npmjs.org
@@ -235,24 +247,44 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile 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 - name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3 run: bun run build --filter=@t3tools/web --filter=t3
- name: Publish CLI package - name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
release: release:
name: Publish GitHub Release name: Publish GitHub Release
needs: [preflight, build, publish_cli] needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Download all desktop artifacts - name: Download all desktop artifacts
uses: actions/download-artifact@v4 uses: actions/download-artifact@v8
with: with:
pattern: desktop-* pattern: desktop-*
merge-multiple: true merge-multiple: true
path: release-assets path: release-assets
- name: Merge macOS updater manifests
run: |
node scripts/merge-mac-update-manifests.ts \
release-assets/latest-mac.yml \
release-assets/latest-mac-x64.yml
rm -f release-assets/latest-mac-x64.yml
- name: Publish release - name: Publish release
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
with: with:
@@ -260,7 +292,8 @@ jobs:
target_commitish: ${{ needs.preflight.outputs.ref }} target_commitish: ${{ needs.preflight.outputs.ref }}
name: T3 Code v${{ needs.preflight.outputs.version }} name: T3 Code v${{ needs.preflight.outputs.version }}
generate_release_notes: true generate_release_notes: true
make_latest: true prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
files: | files: |
release-assets/*.dmg release-assets/*.dmg
release-assets/*.zip release-assets/*.zip
@@ -276,7 +309,7 @@ jobs:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v6
with: with:
ref: main ref: main
fetch-depth: 0 fetch-depth: 0
@@ -287,7 +320,7 @@ jobs:
bun-version-file: package.json bun-version-file: package.json
- name: Setup Node - name: Setup Node
uses: actions/setup-node@v4 uses: actions/setup-node@v6
with: with:
node-version-file: package.json node-version-file: package.json
@@ -295,33 +328,7 @@ jobs:
name: Update version strings name: Update version strings
env: env:
RELEASE_VERSION: ${{ needs.preflight.outputs.version }} RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
run: | run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
node --input-type=module -e '
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
const files = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
];
let changed = false;
for (const file of files) {
const packageJson = JSON.parse(readFileSync(file, "utf8"));
if (packageJson.version !== process.env.RELEASE_VERSION) {
packageJson.version = process.env.RELEASE_VERSION;
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
changed = true;
}
}
if (!changed) {
console.log("All package.json versions already match release version.");
}
appendFileSync(process.env.GITHUB_OUTPUT, `changed=${changed}\n`);
'
- name: Format package.json files - name: Format package.json files
if: steps.update_versions.outputs.changed == 'true' if: steps.update_versions.outputs.changed == 'true'
@@ -329,7 +336,7 @@ jobs:
- name: Refresh lockfile - name: Refresh lockfile
if: steps.update_versions.outputs.changed == 'true' if: steps.update_versions.outputs.changed == 'true'
run: bun install run: bun install --lockfile-only --ignore-scripts
- name: Commit and push version bump - name: Commit and push version bump
if: steps.update_versions.outputs.changed == 'true' if: steps.update_versions.outputs.changed == 'true'
+1
View File
@@ -5,6 +5,7 @@ node_modules
*.log *.log
*.tsbuildinfo *.tsbuildinfo
apps/*/dist apps/*/dist
.astro
packages/*/dist packages/*/dist
.env .env
.env.local .env.local
+3
View File
@@ -0,0 +1,3 @@
[tools]
node = "24.13.1"
bun = "1.3.9"
+3 -2
View File
@@ -7,7 +7,8 @@
"node_modules", "node_modules",
"bun.lock", "bun.lock",
"*.tsbuildinfo", "*.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 # Plan: Centralize Model Normalization in Contracts
## Summary ## Summary
Move model alias/default normalization into `packages/contracts` so desktop and renderer use one shared source of truth. Move model alias/default normalization into `packages/contracts` so desktop and renderer use one shared source of truth.
## Motivation ## Motivation
- Removes duplicated logic between: - Removes duplicated logic between:
- `apps/desktop/src/codexAppServerManager.ts` - `apps/desktop/src/codexAppServerManager.ts`
- `apps/renderer/src/model-logic.ts` - `apps/renderer/src/model-logic.ts`
- Prevents behavior drift when model aliases/defaults are updated. - Prevents behavior drift when model aliases/defaults are updated.
## Scope ## Scope
- Add shared model utilities to contracts. - Add shared model utilities to contracts.
- Update desktop and renderer to consume shared utilities. - Update desktop and renderer to consume shared utilities.
- Keep renderer-specific display options in renderer. - Keep renderer-specific display options in renderer.
## Proposed Changes ## Proposed Changes
1. Add `packages/contracts/src/model.ts` with: 1. Add `packages/contracts/src/model.ts` with:
- Canonical model list - Canonical model list
- Alias map - 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. - Keep renderer tests focused on renderer-only behavior.
## Risks ## Risks
- Desktop/renderer may currently rely on slightly different fallback behavior. - Desktop/renderer may currently rely on slightly different fallback behavior.
- Import graph must avoid bundling issues for Electron main/preload. - Import graph must avoid bundling issues for Electron main/preload.
## Validation ## Validation
- `bun run test` - `bun run test`
- `bun run typecheck` - `bun run typecheck`
- Manual check that model selection and session start still send expected model slug. - Manual check that model selection and session start still send expected model slug.
## Done Criteria ## Done Criteria
- No duplicated alias/default map in desktop and renderer. - No duplicated alias/default map in desktop and renderer.
- Shared model utilities are contract-tested. - Shared model utilities are contract-tested.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Strengthen Typed IPC Boundaries in Main Process # Plan: Strengthen Typed IPC Boundaries in Main Process
## Summary ## Summary
Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers. Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers.
## Motivation ## Motivation
- `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`. - `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`.
- Casts can hide contract breakages until runtime. - Casts can hide contract breakages until runtime.
## Scope ## Scope
- Desktop main process IPC registration. - Desktop main process IPC registration.
- Optional shared helper for handler registration. - Optional shared helper for handler registration.
## Proposed Changes ## Proposed Changes
1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to: 1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to:
- Parse payload(s) with Zod schemas - Parse payload(s) with Zod schemas
- Standardize typed handler signatures - 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). 4. Add tests for handler parsing failure paths (invalid payloads).
## Risks ## Risks
- Refactor can subtly change IPC error shape/messages. - Refactor can subtly change IPC error shape/messages.
- Helper abstraction should stay simple and not obscure control flow. - Helper abstraction should stay simple and not obscure control flow.
## Validation ## Validation
- `bun run test` - `bun run test`
- `bun run typecheck` - `bun run typecheck`
- Manual invalid payload check from renderer/devtools to confirm fast failure. - Manual invalid payload check from renderer/devtools to confirm fast failure.
## Done Criteria ## Done Criteria
- No provider handler uses `payload as Parameters<...>`. - No provider handler uses `payload as Parameters<...>`.
- All IPC entrypoints parse unknown payloads at boundary. - All IPC entrypoints parse unknown payloads at boundary.
@@ -1,9 +1,11 @@
# Plan: Decompose CodexAppServerManager # Plan: Decompose CodexAppServerManager
## Summary ## Summary
Split `CodexAppServerManager` into smaller modules with clear responsibilities. Split `CodexAppServerManager` into smaller modules with clear responsibilities.
## Motivation ## Motivation
- `apps/desktop/src/codexAppServerManager.ts` is large and mixes: - `apps/desktop/src/codexAppServerManager.ts` is large and mixes:
- Process lifecycle - Process lifecycle
- JSON-RPC parsing/routing - JSON-RPC parsing/routing
@@ -12,10 +14,12 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- This increases regression risk and slows changes. - This increases regression risk and slows changes.
## Scope ## Scope
- Desktop provider internals only. - Desktop provider internals only.
- Keep external behavior/API stable. - Keep external behavior/API stable.
## Proposed Changes ## Proposed Changes
1. Extract modules: 1. Extract modules:
- `codex/processLifecycle.ts` - `codex/processLifecycle.ts`
- `codex/jsonrpcRouter.ts` - `codex/jsonrpcRouter.ts`
@@ -29,13 +33,16 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- Session state transitions - Session state transitions
## Risks ## Risks
- Reordering event handling can change behavior. - Reordering event handling can change behavior.
- Must preserve pending request timeout/cancellation semantics. - Must preserve pending request timeout/cancellation semantics.
## Validation ## Validation
- Existing tests pass. - Existing tests pass.
- Add module-level tests for parsing and transition logic. - Add module-level tests for parsing and transition logic.
## Done Criteria ## Done Criteria
- Main manager file materially smaller and orchestration-focused. - Main manager file materially smaller and orchestration-focused.
- Core protocol/state logic covered by focused tests. - Core protocol/state logic covered by focused tests.
+7
View File
@@ -1,9 +1,11 @@
# Plan: Split ChatView into Smaller UI/Logic Units # Plan: Split ChatView into Smaller UI/Logic Units
## Summary ## Summary
Refactor `ChatView.tsx` into composable pieces with isolated responsibilities. Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
## Motivation ## Motivation
- `apps/renderer/src/components/ChatView.tsx` is large and handles: - `apps/renderer/src/components/ChatView.tsx` is large and handles:
- Session orchestration - Session orchestration
- Send/interrupt actions - Send/interrupt actions
@@ -13,10 +15,12 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
- Hard to test and maintain as one component. - Hard to test and maintain as one component.
## Scope ## Scope
- Renderer component boundaries and hooks. - Renderer component boundaries and hooks.
- Keep visual behavior unchanged. - Keep visual behavior unchanged.
## Proposed Changes ## Proposed Changes
1. Create hook: `apps/renderer/src/hooks/useChatSession.ts` 1. Create hook: `apps/renderer/src/hooks/useChatSession.ts`
- `ensureSession` - `ensureSession`
- `sendTurn` - `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). 4. Add focused tests for hook behavior (error handling, session reuse).
## Risks ## Risks
- Refactor can break subtle UI interactions (auto-scroll, menu close, keyboard send). - Refactor can break subtle UI interactions (auto-scroll, menu close, keyboard send).
## Validation ## Validation
- `bun run test` - `bun run test`
- Manual smoke: send, stream, interrupt, model switch. - Manual smoke: send, stream, interrupt, model switch.
## Done Criteria ## Done Criteria
- `ChatView.tsx` significantly reduced and easier to scan. - `ChatView.tsx` significantly reduced and easier to scan.
- Session logic isolated from rendering. - Session logic isolated from rendering.
@@ -1,17 +1,21 @@
# Plan: Move Renderer Persisted-State Validation to Zod # Plan: Move Renderer Persisted-State Validation to Zod
## Summary ## Summary
Use explicit Zod schemas for localStorage state parsing and migration. Use explicit Zod schemas for localStorage state parsing and migration.
## Motivation ## Motivation
- `apps/renderer/src/store.ts` has large manual sanitize functions. - `apps/renderer/src/store.ts` has large manual sanitize functions.
- Manual type guards are verbose and easier to get wrong during schema evolution. - Manual type guards are verbose and easier to get wrong during schema evolution.
## Scope ## Scope
- Renderer state hydration/persistence path. - Renderer state hydration/persistence path.
- No backend/protocol changes. - No backend/protocol changes.
## Proposed Changes ## Proposed Changes
1. Add schema module: `apps/renderer/src/persistenceSchema.ts` 1. Add schema module: `apps/renderer/src/persistenceSchema.ts`
- Persisted payload versions (`v1`, `v2`) - Persisted payload versions (`v1`, `v2`)
- Thread/message/project schemas - Thread/message/project schemas
@@ -23,12 +27,15 @@ Use explicit Zod schemas for localStorage state parsing and migration.
- Unknown thread/project references filtered - Unknown thread/project references filtered
## Risks ## Risks
- Overly strict schemas could drop valid historical data unexpectedly. - Overly strict schemas could drop valid historical data unexpectedly.
## Validation ## Validation
- Unit tests for migration/hydration. - Unit tests for migration/hydration.
- Manual reload test with existing localStorage data. - Manual reload test with existing localStorage data.
## Done Criteria ## Done Criteria
- Store hydration logic is schema-driven. - Store hydration logic is schema-driven.
- Migration behavior is tested and documented. - Migration behavior is tested and documented.
@@ -1,17 +1,21 @@
# Plan: Add Provider Log Stream Lifecycle Management # Plan: Add Provider Log Stream Lifecycle Management
## Summary ## Summary
Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely. Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely.
## Motivation ## Motivation
- `apps/desktop/src/providerManager.ts` opens a write stream in constructor. - `apps/desktop/src/providerManager.ts` opens a write stream in constructor.
- Stream lifecycle is not explicit on shutdown. - Stream lifecycle is not explicit on shutdown.
## Scope ## Scope
- Desktop provider logging behavior. - Desktop provider logging behavior.
- App shutdown integration. - App shutdown integration.
## Proposed Changes ## Proposed Changes
1. Add explicit `dispose()` on `ProviderManager`: 1. Add explicit `dispose()` on `ProviderManager`:
- Remove event listeners - Remove event listeners
- End/close log stream - 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/`. 4. Optional: per-session log files under `.logs/providers/`.
## Risks ## Risks
- Improper close sequencing may lose final log lines. - Improper close sequencing may lose final log lines.
## Validation ## Validation
- Manual run/quit cycle to ensure no open handle warnings. - Manual run/quit cycle to ensure no open handle warnings.
- Confirm logs flush on quit and file descriptors are not leaked. - Confirm logs flush on quit and file descriptors are not leaked.
## Done Criteria ## Done Criteria
- ProviderManager owns complete log stream lifecycle. - ProviderManager owns complete log stream lifecycle.
- Shutdown path explicitly disposes provider resources. - Shutdown path explicitly disposes provider resources.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Add CI Workflow for Core Quality Gates # Plan: Add CI Workflow for Core Quality Gates
## Summary ## Summary
Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-test) on pushes and PRs. Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-test) on pushes and PRs.
## Motivation ## Motivation
- Repository currently has no CI workflow files. - Repository currently has no CI workflow files.
- Quality checks are only local/manual. - Quality checks are only local/manual.
## Scope ## Scope
- `.github/workflows/ci.yml` - `.github/workflows/ci.yml`
- Bun + Turbo setup in CI. - Bun + Turbo setup in CI.
## Proposed Changes ## Proposed Changes
1. Add `ci.yml` with jobs: 1. Add `ci.yml` with jobs:
- Setup Bun and Node environment - Setup Bun and Node environment
- Install deps - 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. 3. Configure caching for Bun/Turbo as appropriate.
## Risks ## Risks
- Smoke test may be flaky in headless CI environments. - Smoke test may be flaky in headless CI environments.
- CI runtime can grow if caching is misconfigured. - CI runtime can grow if caching is misconfigured.
## Validation ## Validation
- Verify workflow runs on a branch PR. - Verify workflow runs on a branch PR.
- Ensure failures surface clearly by job name. - Ensure failures surface clearly by job name.
## Done Criteria ## Done Criteria
- CI blocks regressions in lint/typecheck/test. - CI blocks regressions in lint/typecheck/test.
- Workflow docs added to README. - Workflow docs added to README.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Add Pre-Commit Formatting/Lint Hooks # Plan: Add Pre-Commit Formatting/Lint Hooks
## Summary ## Summary
Introduce pre-commit automation so formatting and basic lint checks happen before commits. Introduce pre-commit automation so formatting and basic lint checks happen before commits.
## Motivation ## Motivation
- Current lint failures include formatting-only issues. - Current lint failures include formatting-only issues.
- Shift-left feedback reduces noisy CI failures and cleanup churn. - Shift-left feedback reduces noisy CI failures and cleanup churn.
## Scope ## Scope
- Root tooling config and package scripts. - Root tooling config and package scripts.
- No runtime code changes. - No runtime code changes.
## Proposed Changes ## Proposed Changes
1. Add hook tooling (e.g. Husky + lint-staged or Lefthook). 1. Add hook tooling (e.g. Husky + lint-staged or Lefthook).
2. Configure staged-file tasks: 2. Configure staged-file tasks:
- `biome format --write` - `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. 4. Keep checks fast to avoid developer friction.
## Risks ## Risks
- Slow hooks can frustrate contributors and be bypassed. - Slow hooks can frustrate contributors and be bypassed.
- Need to ensure compatibility with Bun workspace setup. - Need to ensure compatibility with Bun workspace setup.
## Validation ## Validation
- Create sample staged changes and verify hook behavior. - Create sample staged changes and verify hook behavior.
- Confirm formatting fixes are applied automatically. - Confirm formatting fixes are applied automatically.
## Done Criteria ## Done Criteria
- Pre-commit hook installed and documented. - Pre-commit hook installed and documented.
- Formatting-only lint failures drop significantly. - Formatting-only lint failures drop significantly.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Expand Event/State Transition Test Coverage # Plan: Expand Event/State Transition Test Coverage
## Summary ## Summary
Add focused tests for renderer event handling and session evolution logic. Add focused tests for renderer event handling and session evolution logic.
## Motivation ## Motivation
- Core behavior is event-driven and stateful. - Core behavior is event-driven and stateful.
- Existing renderer tests cover only a subset of timeline/model behavior. - Existing renderer tests cover only a subset of timeline/model behavior.
## Scope ## Scope
- `apps/renderer/src/session-logic.test.ts` - `apps/renderer/src/session-logic.test.ts`
- Optional reducer tests for `apps/renderer/src/store.ts`. - Optional reducer tests for `apps/renderer/src/store.ts`.
## Proposed Changes ## Proposed Changes
1. Add tests for `evolveSession`: 1. Add tests for `evolveSession`:
- `thread/started` - `thread/started`
- `turn/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`. 3. Add reducer integration tests for `APPLY_EVENT`.
## Risks ## Risks
- Tests may be brittle if event payload fixtures are too coupled to implementation details. - Tests may be brittle if event payload fixtures are too coupled to implementation details.
## Validation ## Validation
- `bun run test` - `bun run test`
- Ensure new tests remain deterministic and fast. - Ensure new tests remain deterministic and fast.
## Done Criteria ## Done Criteria
- High-risk event transitions are covered by unit tests. - High-risk event transitions are covered by unit tests.
- Regressions in stream assembly/session status are caught quickly. - Regressions in stream assembly/session status are caught quickly.
@@ -1,17 +1,21 @@
# Plan: Unify Process and PTY Session Abstractions in ProcessManager # Plan: Unify Process and PTY Session Abstractions in ProcessManager
## Summary ## Summary
Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes. Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes.
## Motivation ## Motivation
- `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic. - `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic.
- New execution backends/providers will multiply complexity. - New execution backends/providers will multiply complexity.
## Scope ## Scope
- Desktop process execution internals. - Desktop process execution internals.
- Preserve public `ProcessManager` API. - Preserve public `ProcessManager` API.
## Proposed Changes ## Proposed Changes
1. Introduce internal interface (e.g. `RuntimeSession`): 1. Introduce internal interface (e.g. `RuntimeSession`):
- `write(data)` - `write(data)`
- `kill()` - `kill()`
@@ -24,12 +28,15 @@ Refactor `ProcessManager` to use a single runtime-session interface for child-pr
5. Add tests for both implementations. 5. Add tests for both implementations.
## Risks ## Risks
- PTY behavior differs by platform; abstraction must not hide required differences. - PTY behavior differs by platform; abstraction must not hide required differences.
## Validation ## Validation
- Existing `processManager.test.ts` passes. - Existing `processManager.test.ts` passes.
- Add PTY-path tests where feasible. - Add PTY-path tests where feasible.
## Done Criteria ## Done Criteria
- Manager no longer branches per backend in `write/kill/killAll`. - Manager no longer branches per backend in `write/kill/killAll`.
- Session backends are independently testable. - Session backends are independently testable.
+1 -3
View File
@@ -1,5 +1,3 @@
PR 1: Service contracts + error taxonomy PR 1: Service contracts + error taxonomy
Add ProviderService, CodexService, CheckpointStore as Context.Tag service defs. 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). 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 PR 10: Cleanup + deprecation removal
Remove legacy class implementations/adapters once parity is proven. Remove legacy class implementations/adapters once parity is proven.
Finalize layer composition and startup graph docs. 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) # Effect Migration Plan (From Current State)
Current status summary: Current status summary:
- Service contracts, typed errors, and most checkpoint/persistence services exist. - Service contracts, typed errors, and most checkpoint/persistence services exist.
- `ProviderServiceLive` is already native orchestration (not a thin adapter). - `ProviderServiceLive` is already native orchestration (not a thin adapter).
- Production server path still uses legacy `ProviderManager`/`FilesystemCheckpointStore`. - Production server path still uses legacy `ProviderManager`/`FilesystemCheckpointStore`.
- Checkpoint flow now avoids snapshot re-sync and is write-time driven. - Checkpoint flow now avoids snapshot re-sync and is write-time driven.
## PR 1: Wire Provider/Checkpoint Effect Stack Into `wsServer` ## PR 1: Wire Provider/Checkpoint Effect Stack Into `wsServer`
- Build one runtime layer graph for provider + checkpoint + persistence + orchestration. - Build one runtime layer graph for provider + checkpoint + persistence + orchestration.
- Resolve `ProviderService` from runtime in `wsServer`. - Resolve `ProviderService` from runtime in `wsServer`.
- Replace `ProviderManager` method calls in WS handlers with `ProviderService` calls. - Replace `ProviderManager` method calls in WS handlers with `ProviderService` calls.
@@ -14,12 +16,14 @@ Current status summary:
- Keep WS method/push payloads identical. - Keep WS method/push payloads identical.
## PR 2: Runtime Composition + Startup Ownership ## PR 2: Runtime Composition + Startup Ownership
- Create/centralize `AppLive` composition for server startup. - Create/centralize `AppLive` composition for server startup.
- Ensure outer runtime provides Node/platform services once. - Ensure outer runtime provides Node/platform services once.
- Ensure migrations run at startup via scoped/layer startup path. - Ensure migrations run at startup via scoped/layer startup path.
- Remove ad-hoc service initialization in request-time paths. - Remove ad-hoc service initialization in request-time paths.
## PR 3: Session Lifecycle Hygiene + Checkpoint Invariants ## PR 3: Session Lifecycle Hygiene + Checkpoint Invariants
- Add explicit checkpoint session cleanup on `stopSession` / `stopAll`. - Add explicit checkpoint session cleanup on `stopSession` / `stopAll`.
- Remove per-session lock/cwd map leaks. - Remove per-session lock/cwd map leaks.
- Keep strict invariant model: - Keep strict invariant model:
@@ -29,12 +33,14 @@ Current status summary:
- Add tests for lifecycle cleanup and invariant-failure surfaces. - Add tests for lifecycle cleanup and invariant-failure surfaces.
## PR 4: Provider Event Stream Hardening (Without Extra Service Fragmentation) ## PR 4: Provider Event Stream Hardening (Without Extra Service Fragmentation)
- Keep `ProviderService` as the public event surface. - Keep `ProviderService` as the public event surface.
- Internally move callback fanout to Effect concurrency primitives (`Queue`/`PubSub`) for ordering/backpressure control. - 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. - Keep API as `subscribeToEvents` unless we explicitly choose stream API later.
- Add tests for ordering and subscriber isolation under load. - Add tests for ordering and subscriber isolation under load.
## PR 5: Codex Runtime Split (Scoped Effect Core) ## PR 5: Codex Runtime Split (Scoped Effect Core)
- Extract `CodexAppServerManager` responsibilities into Effect-native layers: - Extract `CodexAppServerManager` responsibilities into Effect-native layers:
- scoped process lifecycle - scoped process lifecycle
- RPC request/response + pending map via `Deferred` - RPC request/response + pending map via `Deferred`
@@ -43,16 +49,19 @@ Current status summary:
- Preserve protocol behavior and timeout semantics. - Preserve protocol behavior and timeout semantics.
## PR 6: Codex Protocol Decode Hardening ## PR 6: Codex Protocol Decode Hardening
- Replace ad-hoc unknown parsing with runtime schema decode. - Replace ad-hoc unknown parsing with runtime schema decode.
- Map decode failures to typed tagged errors with `cause` retained. - Map decode failures to typed tagged errors with `cause` retained.
- Add regression tests for malformed/partial protocol frames. - Add regression tests for malformed/partial protocol frames.
## PR 7: Remove Legacy Provider Stack ## PR 7: Remove Legacy Provider Stack
- Remove `ProviderManager` + legacy checkpoint integration from runtime path. - Remove `ProviderManager` + legacy checkpoint integration from runtime path.
- Remove `FilesystemCheckpointStore` from active server flow (keep only if explicitly needed for compatibility tooling). - Remove `FilesystemCheckpointStore` from active server flow (keep only if explicitly needed for compatibility tooling).
- Update tests to assert only Effect service path is used. - Update tests to assert only Effect service path is used.
## PR 8: Final Cleanup + Docs ## PR 8: Final Cleanup + Docs
- Update architecture docs with final layer graph and service boundaries. - Update architecture docs with final layer graph and service boundaries.
- Document error model and recovery semantics. - Document error model and recovery semantics.
- Trim dead compatibility code and stale plan references. - Trim dead compatibility code and stale plan references.
@@ -1,6 +1,7 @@
# ProviderService Integration Test Plan # ProviderService Integration Test Plan
Goal: Goal:
- Validate end-to-end `ProviderService` behavior with real layers: - Validate end-to-end `ProviderService` behavior with real layers:
- `ProviderServiceLive` - `ProviderServiceLive`
- `CheckpointServiceLive` - `CheckpointServiceLive`
@@ -13,6 +14,7 @@ Goal:
## Test Harness ## Test Harness
Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Layers/TestProviderAdapter.integration.ts`: Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Layers/TestProviderAdapter.integration.ts`:
- Service contract: `ProviderAdapterShape<ProviderAdapterError>`. - Service contract: `ProviderAdapterShape<ProviderAdapterError>`.
- Internal state: - Internal state:
- session registry (session + cwd + threadId) - session registry (session + cwd + threadId)
@@ -29,13 +31,15 @@ Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Lay
- `readThread`, `rollbackThread`, `stopSession`, `stopAll`. - `readThread`, `rollbackThread`, `stopSession`, `stopAll`.
Use real git-backed temporary workspaces in integration tests: Use real git-backed temporary workspaces in integration tests:
- initialize repo with baseline commit - initialize repo with baseline commit
- run provider turn in workspace - run provider turn in workspace
- assert checkpoint diffs against real git refs - assert checkpoint diffs against real git refs
## Core Integration Specs ## Core Integration Specs
1) `startSession` initializes checkpoint root exactly once 1. `startSession` initializes checkpoint root exactly once
- Arrange: - Arrange:
- start provider session in git repo. - start provider session in git repo.
- Assert: - Assert:
@@ -43,7 +47,8 @@ Use real git-backed temporary workspaces in integration tests:
- checkpoint ref exists in git. - checkpoint ref exists in git.
- second `startSession` for new session creates a new independent root. - second `startSession` for new session creates a new independent root.
2) Turn without filesystem change 2. Turn without filesystem change
- Arrange: - Arrange:
- emit normal turn events, no file mutation. - emit normal turn events, no file mutation.
- Assert: - Assert:
@@ -54,7 +59,8 @@ Use real git-backed temporary workspaces in integration tests:
- `listCheckpoints` returns root + turn 1. - `listCheckpoints` returns root + turn 1.
- `getCheckpointDiff(0 -> 1)` returns empty/no-op diff. - `getCheckpointDiff(0 -> 1)` returns empty/no-op diff.
3) Turn with filesystem change 3. Turn with filesystem change
- Arrange: - Arrange:
- mutate `README.md` during turn. - mutate `README.md` during turn.
- Assert: - Assert:
@@ -62,7 +68,8 @@ Use real git-backed temporary workspaces in integration tests:
- `getCheckpointDiff(0 -> 1)` contains file path and hunk. - `getCheckpointDiff(0 -> 1)` contains file path and hunk.
- persisted checkpoint metadata includes non-empty `checkpointRef`. - persisted checkpoint metadata includes non-empty `checkpointRef`.
4) Multi-turn sequencing and checkpoint monotonicity 4. Multi-turn sequencing and checkpoint monotonicity
- Arrange: - Arrange:
- turn 1: no file change - turn 1: no file change
- turn 2: file change - turn 2: file change
@@ -72,7 +79,8 @@ Use real git-backed temporary workspaces in integration tests:
- latest checkpoint is marked current. - latest checkpoint is marked current.
- diffs for adjacent turns map to expected filesystem deltas. - diffs for adjacent turns map to expected filesystem deltas.
5) Revert to checkpoint 5. Revert to checkpoint
- Arrange: - Arrange:
- execute 3 turns with at least one file-changing turn. - execute 3 turns with at least one file-changing turn.
- call `revertToCheckpoint(turnCount=1)`. - call `revertToCheckpoint(turnCount=1)`.
@@ -82,7 +90,8 @@ Use real git-backed temporary workspaces in integration tests:
- DB rows for turns >1 are removed. - DB rows for turns >1 are removed.
- later refs are deleted from git. - later refs are deleted from git.
6) Capture failure surface 6. Capture failure surface
- Arrange: - Arrange:
- adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails. - adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails.
- Assert: - Assert:
@@ -92,6 +101,7 @@ Use real git-backed temporary workspaces in integration tests:
## WebSocket Coverage (Thin Integration) ## WebSocket Coverage (Thin Integration)
Add one ws server integration spec: Add one ws server integration spec:
- Subscribe to `providers.event`. - Subscribe to `providers.event`.
- Run a deterministic provider turn through ws methods. - Run a deterministic provider turn through ws methods.
- Assert push stream includes: - Assert push stream includes:
@@ -101,10 +111,13 @@ Add one ws server integration spec:
## Proposed PR Split ## Proposed PR Split
PR A: PR A:
- Test adapter harness + shared integration fixtures (repo setup, runtime/layer setup). - Test adapter harness + shared integration fixtures (repo setup, runtime/layer setup).
PR B: PR B:
- Core ProviderService integration specs (cases 1-4). - Core ProviderService integration specs (cases 1-4).
PR C: PR C:
- Revert + failure-path specs (cases 5-6) + ws thin integration spec. - Revert + failure-path specs (cases 5-6) + ws thin integration spec.
@@ -1,6 +1,7 @@
# Server-Authoritative Event-Sourcing Cleanup Plan # Server-Authoritative Event-Sourcing Cleanup Plan
Goal: Goal:
- Move to a cleaner service architecture with: - Move to a cleaner service architecture with:
- durable, server-authoritative event sourcing - durable, server-authoritative event sourcing
- strict command routing/validation - strict command routing/validation
@@ -85,6 +86,7 @@ CheckpointCatalog ------> SQLite
## Commit Series ## Commit Series
### Commit 1: Split public vs system orchestration command contracts ### Commit 1: Split public vs system orchestration command contracts
- Create separate schemas/types: - Create separate schemas/types:
- `ClientOrchestrationCommandSchema` - `ClientOrchestrationCommandSchema`
- `SystemOrchestrationCommandSchema` - `SystemOrchestrationCommandSchema`
@@ -100,6 +102,7 @@ CheckpointCatalog ------> SQLite
- preserve internal dispatch functionality for system commands - preserve internal dispatch functionality for system commands
### Commit 2: Introduce `OrchestrationCommandRouter` + handler boundary ### Commit 2: Introduce `OrchestrationCommandRouter` + handler boundary
- Add dedicated router service to validate, authorize, and route commands. - Add dedicated router service to validate, authorize, and route commands.
- Move command-to-event mapping out of `orchestration/Layer.ts` into handlers. - Move command-to-event mapping out of `orchestration/Layer.ts` into handlers.
- Add aggregate-level invariant checks before append (thread exists, project exists, etc.). - 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 - handler happy-path tests per command type
### Commit 3: Harden event store for idempotency + optimistic append metadata ### Commit 3: Harden event store for idempotency + optimistic append metadata
- Add DB-level idempotency guard for `command_id` (`UNIQUE` where non-null). - 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`. - 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. - Add optional aggregate version metadata for future optimistic concurrency.
@@ -125,6 +129,7 @@ CheckpointCatalog ------> SQLite
- concurrent append behavior stays ordered and deterministic - concurrent append behavior stays ordered and deterministic
### Commit 4: Extract provider-runtime -> orchestration bridge from `wsServer` ### Commit 4: Extract provider-runtime -> orchestration bridge from `wsServer`
- Create `ProviderRuntimeIngestionService` that: - Create `ProviderRuntimeIngestionService` that:
- subscribes to `ProviderService.streamEvents` - subscribes to `ProviderService.streamEvents`
- translates runtime events into orchestration commands - translates runtime events into orchestration commands
@@ -139,6 +144,7 @@ CheckpointCatalog ------> SQLite
- ws integration confirms same external push behavior - ws integration confirms same external push behavior
### Commit 5: Make session directory durable (`ProviderSessionRegistry`) ### Commit 5: Make session directory durable (`ProviderSessionRegistry`)
- Replace in-memory-only `ProviderSessionDirectoryLive` with persistence-backed registry. - Replace in-memory-only `ProviderSessionDirectoryLive` with persistence-backed registry.
- Keep in-memory cache optional, but source of truth must be persistent. - Keep in-memory cache optional, but source of truth must be persistent.
- Add startup reconciliation to prune dead sessions / keep known thread mapping. - Add startup reconciliation to prune dead sessions / keep known thread mapping.
@@ -152,6 +158,7 @@ CheckpointCatalog ------> SQLite
- stale session cleanup semantics - stale session cleanup semantics
### Commit 6: Re-key checkpoint metadata from session to thread identity ### Commit 6: Re-key checkpoint metadata from session to thread identity
- Change checkpoint catalog primary identity from `provider_session_id` to durable `thread_id`. - Change checkpoint catalog primary identity from `provider_session_id` to durable `thread_id`.
- Keep `session_id` as nullable metadata only. - Keep `session_id` as nullable metadata only.
- Update checkpoint flows (`initialize`, `capture`, `list`, `diff`, `revert`) to use thread identity. - 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 - revert/diff still work after session churn
### Commit 7: Add durable projection persistence for orchestration read models ### Commit 7: Add durable projection persistence for orchestration read models
- Introduce projection tables/snapshots persisted in DB to avoid full replay dependency. - Introduce projection tables/snapshots persisted in DB to avoid full replay dependency.
- Keep event stream as source of truth; projection rebuild stays deterministic. - Keep event stream as source of truth; projection rebuild stays deterministic.
- `getSnapshot` reads from projection store (memory cache optional). - `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 - projection rebuild from events yields same result as previous reducer semantics
### Commit 8: Narrow `ProviderService` responsibilities ### Commit 8: Narrow `ProviderService` responsibilities
- Keep `ProviderService` focused on provider RPC/session lifecycle + unified runtime stream. - 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. - Move checkpoint-capture side effects out of provider event worker into dedicated ingestion/checkpoint pipeline service.
- Preserve adapter pluggability and provider-neutral contracts. - Preserve adapter pluggability and provider-neutral contracts.
@@ -188,6 +197,7 @@ CheckpointCatalog ------> SQLite
- checkpoint capture still triggered by turn completion through new coordinator - checkpoint capture still triggered by turn completion through new coordinator
### Commit 9: Look over schemas (contracts and events) ### Commit 9: Look over schemas (contracts and events)
- Scan for unused schemas. - Scan for unused schemas.
- Use effect/Schema everywhere - Use effect/Schema everywhere
- Analyze which we need - Analyze which we need
@@ -196,6 +206,7 @@ CheckpointCatalog ------> SQLite
- Persistence entities - Persistence entities
### Commit 10: Remove dead legacy path and finalize docs ### Commit 10: Remove dead legacy path and finalize docs
- Remove unused legacy manager/store path from active architecture: - Remove unused legacy manager/store path from active architecture:
- `providerManager.ts` - `providerManager.ts`
- `filesystemCheckpointStore.ts` (if no longer needed by tests/tools) - `filesystemCheckpointStore.ts` (if no longer needed by tests/tools)
@@ -210,6 +221,7 @@ CheckpointCatalog ------> SQLite
- no regressions in WS protocol behavior - no regressions in WS protocol behavior
## Risk Controls ## Risk Controls
- Keep WS method names and payload contracts stable throughout. - Keep WS method names and payload contracts stable throughout.
- Gate each commit with targeted integration tests before moving forward. - 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. - 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. Rewrite `createServer` and `index.ts` to be Effect native.
Maybe use `effect/unstable/Socket` for the web socket server 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/effect/src/unstable/socket/SocketServer.ts
- https://github.com/Effect-TS/effect-smol/blob/main/packages/platform-node/test/NodeSocket.test.ts - https://github.com/Effect-TS/effect-smol/blob/main/packages/platform-node/test/NodeSocket.test.ts
- Migrate remaining runtime code to Effect - Migrate remaining runtime code to Effect
- `gitManager` -> `src/git` - `gitManager` -> `src/git`
- `terminalManager` -> `src/terminal` (Manager + PTY) - `terminalManager` -> `src/terminal` (Manager + PTY)
- ... - ...
@@ -24,21 +24,25 @@
- Mark invalid/false-positive items with explicit rationale. - Mark invalid/false-positive items with explicit rationale.
Exit criteria: Exit criteria:
- Every open thread is mapped to one canonical fix item or marked invalid. - Every open thread is mapped to one canonical fix item or marked invalid.
## Phase 1: Runtime Survival and Critical Event Wiring ## Phase 1: Runtime Survival and Critical Event Wiring
Related bug groups solved together: Related bug groups solved together:
- Worker loop/fiber fatal error handling in orchestration reactors. - Worker loop/fiber fatal error handling in orchestration reactors.
- WebSocket message error boundaries and unhandled rejection guards. - WebSocket message error boundaries and unhandled rejection guards.
- Close invalid `providers.event` review findings as documented architecture mismatch (no code change expected). - Close invalid `providers.event` review findings as documented architecture mismatch (no code change expected).
Primary files: Primary files:
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` - `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts` - `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
- `apps/server/src/wsServer.ts` - `apps/server/src/wsServer.ts`
Exit criteria: Exit criteria:
- A single event-processing failure cannot permanently stop ingestion/reactor loops. - A single event-processing failure cannot permanently stop ingestion/reactor loops.
- WS message handling cannot produce unhandled promise rejections. - WS message handling cannot produce unhandled promise rejections.
- Invalid provider-event-channel review findings are closed with architecture rationale. - Invalid provider-event-channel review findings are closed with architecture rationale.
@@ -46,17 +50,20 @@ Exit criteria:
## Phase 2: State Consistency and Ordering ## Phase 2: State Consistency and Ordering
Related bug groups solved together: Related bug groups solved together:
- Fire-and-forget revert completion causing consistency windows. - Fire-and-forget revert completion causing consistency windows.
- Non-atomic append/projection paths and retry behavior. - Non-atomic append/projection paths and retry behavior.
- Race-sensitive thread/event association issues. - Race-sensitive thread/event association issues.
Primary files: Primary files:
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts` - `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
- `apps/server/src/orchestration/Layers/OrchestrationEngine.ts` - `apps/server/src/orchestration/Layers/OrchestrationEngine.ts`
- `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` - `apps/server/src/orchestration/Layers/ProjectionPipeline.ts`
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` - `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
Exit criteria: Exit criteria:
- Revert flow is deterministically reflected in read model updates. - Revert flow is deterministically reflected in read model updates.
- Append/project failure mode is explicit and safe under retry. - Append/project failure mode is explicit and safe under retry.
- No cross-thread misassociation under concurrent runtime events. - No cross-thread misassociation under concurrent runtime events.
@@ -64,12 +71,14 @@ Exit criteria:
## Phase 3: Checkpointing Correctness Bundle ## Phase 3: Checkpointing Correctness Bundle
Related bug groups solved together: Related bug groups solved together:
- Checkpoint input normalization consistency. - Checkpoint input normalization consistency.
- Snapshot/projector coverage mismatches. - Snapshot/projector coverage mismatches.
- Checkpoint ref/workspace CWD utility duplication. - Checkpoint ref/workspace CWD utility duplication.
- Checkpoint diff/error handling behavior gaps. - Checkpoint diff/error handling behavior gaps.
Primary files: Primary files:
- `apps/server/src/checkpointing/Layers/CheckpointStore.ts` - `apps/server/src/checkpointing/Layers/CheckpointStore.ts`
- `apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts` - `apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts`
- `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts` - `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts`
@@ -77,6 +86,7 @@ Primary files:
- `apps/server/src/wsServer.ts` - `apps/server/src/wsServer.ts`
Exit criteria: Exit criteria:
- Checkpoint capture/restore/revert paths use one normalization policy. - Checkpoint capture/restore/revert paths use one normalization policy.
- Required projectors are actually represented in snapshot reads. - Required projectors are actually represented in snapshot reads.
- Shared checkpoint/ref/CWD helpers are centralized. - Shared checkpoint/ref/CWD helpers are centralized.
@@ -84,27 +94,32 @@ Exit criteria:
## Phase 4: Memory and Lifecycle Hygiene ## Phase 4: Memory and Lifecycle Hygiene
Related bug groups solved together: Related bug groups solved together:
- Unbounded in-memory dedup sets/maps. - Unbounded in-memory dedup sets/maps.
- Missing cleanup/lifecycle protections in long-lived effects/resources. - Missing cleanup/lifecycle protections in long-lived effects/resources.
Primary files: Primary files:
- `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts` - `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` - `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
- `apps/server/src/config.ts` - `apps/server/src/config.ts`
Exit criteria: Exit criteria:
- Long-running server memory does not grow unbounded from dedup bookkeeping. - Long-running server memory does not grow unbounded from dedup bookkeeping.
- Resource cleanup paths are registered for interruption/shutdown. - Resource cleanup paths are registered for interruption/shutdown.
## Phase 5: Transport, Parsing, and Platform Edge Cases ## Phase 5: Transport, Parsing, and Platform Edge Cases
Related bug groups solved together: Related bug groups solved together:
- UTF-8 chunk boundary decode correctness. - UTF-8 chunk boundary decode correctness.
- Markdown/file-link parsing edge cases. - Markdown/file-link parsing edge cases.
- Shell/OS-specific PATH parsing behavior. - Shell/OS-specific PATH parsing behavior.
- Git rename parsing and small keybinding edge cases. - Git rename parsing and small keybinding edge cases.
Primary files: Primary files:
- `apps/server/src/wsServer.ts` - `apps/server/src/wsServer.ts`
- `apps/server/src/git/Layers/CodexTextGeneration.ts` - `apps/server/src/git/Layers/CodexTextGeneration.ts`
- `apps/web/src/markdown-links.ts` - `apps/web/src/markdown-links.ts`
@@ -113,23 +128,27 @@ Primary files:
- `apps/server/src/keybindings.ts` - `apps/server/src/keybindings.ts`
Exit criteria: Exit criteria:
- Edge-case parsers are robust across valid but non-trivial inputs. - Edge-case parsers are robust across valid but non-trivial inputs.
- Platform-dependent command behavior has safe fallbacks. - Platform-dependent command behavior has safe fallbacks.
## Phase 6: Build and Maintainability Cleanup ## Phase 6: Build and Maintainability Cleanup
Related bug groups solved together: Related bug groups solved together:
- Build script/runtime assumption cleanup. - Build script/runtime assumption cleanup.
- Redundant error-union declarations and utility/type duplication. - Redundant error-union declarations and utility/type duplication.
- Non-functional cleanup comments/docs markers. - Non-functional cleanup comments/docs markers.
Primary files: Primary files:
- `apps/server/package.json` - `apps/server/package.json`
- `apps/server/src/checkpointing/Errors.ts` - `apps/server/src/checkpointing/Errors.ts`
- Shared utility locations introduced during earlier phases - Shared utility locations introduced during earlier phases
- `AGENTS.md` (if cleanup is still pending) - `AGENTS.md` (if cleanup is still pending)
Exit criteria: Exit criteria:
- Build path is explicit and environment-safe. - Build path is explicit and environment-safe.
- Redundant types/utilities are removed in favor of single sources of truth. - 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. - Resolve threads with fix references per canonical checklist item.
Exit criteria: Exit criteria:
- Lint passes. - Lint passes.
- Backend tests pass. - Backend tests pass.
- All actionable review threads are resolved or explicitly justified. - 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. This is the working checklist for remediation execution.
Status values: Status values:
- `TODO`: Not started - `TODO`: Not started
- `IN_PROGRESS`: Currently being worked - `IN_PROGRESS`: Currently being worked
- `BLOCKED`: Waiting on decision/dependency - `BLOCKED`: Waiting on decision/dependency
@@ -150,7 +151,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Area: `WebSocket robustness` - Area: `WebSocket robustness`
- File: `apps/web/src/wsTransport.ts:59` - File: `apps/web/src/wsTransport.ts:59`
- Threads: PRRT_kwDORLtfbc5whtrN - 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 ### Phase 2
@@ -181,7 +182,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Threads: PRRT_kwDORLtfbc5whxJO - Threads: PRRT_kwDORLtfbc5whxJO
- Audit note: Message fallback retention issue is real, but prior FK-violation claim is overstated. - 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` - Status: `DONE`
- Verdict: `valid` - Verdict: `valid`
- Severity: `Medium` - Severity: `Medium`
@@ -198,7 +199,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Severity: `Medium` - Severity: `Medium`
- Area: `Checkpointing correctness` - Area: `Checkpointing correctness`
- File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:94` - 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. - 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> - [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 ### 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` - Status: `TODO`
- Verdict: `valid` - Verdict: `valid`
- Severity: `Medium` - Severity: `Medium`
@@ -0,0 +1,109 @@
# Plan: Provider-Neutral Runtime Determinism and Flake Elimination
## 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 — 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 — 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 — 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 — 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 — 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 — 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 — 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 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.
- Keep UI/provider-specific knobs such as Codex-only options scoped to provider UX code. Do not pull them into generic transport or orchestration state.
## Test Plan
- Contracts:
- schema tests for typed push envelopes and structured decode diagnostics
- ordering tests for `sequence`
- Server:
- readiness tests proving `server.welcome` cannot precede runtime readiness
- push bus tests proving terminal/config/orchestration pushes are serialized and typed
- keybindings runtime tests with fake watch source plus one real watcher integration test
- Orchestration:
- receipt tests proving checkpoint refs and projections are complete before completion signals resolve
- replacement of polling-based checkpoint/integration waits with receipt-based waits
- Web:
- transport tests for invalid JSON, invalid envelope, invalid payload, reconnect queue flushing, cached semantic state
- Validation gate:
- `bun run lint`
- `bun run typecheck`
- `mise exec -- bun run test`
- repeated full-suite run after cutover to confirm flake removal
## Assumptions and Defaults
- This remains a single-provider product during the cutover, but the runtime contracts must stay provider-neutral.
- No backward-compatibility layer is required for old websocket push envelopes.
- The goal is deterministic runtime behavior first; reducing retries and sleeps in tests is a consequence, not the primary mechanism.
- If a completion signal cannot be expressed provider-neutrally, it does not belong in the shared runtime layer and must stay adapter-local.
-327
View File
@@ -1,327 +0,0 @@
# Plan: Cursor ACP (`agent acp`) Provider Integration
## Goal
Add Cursor as a first-class provider in T3 Code using ACP (`agent acp`) over JSON-RPC 2.0 stdio, with robust session lifecycle handling and canonical `ProviderRuntimeEvent` projection.
---
## 1) Exploration Findings (from live ACP probes)
### 1.1 Core invocation and transport
1. Binary is `agent` on PATH (`2026.02.27-e7d2ef6` observed).
2. ACP server command is `agent acp`.
3. Transport is newline-delimited JSON-RPC 2.0 over stdio.
4. Messages:
- client -> server: requests and responses to server-initiated requests
- server -> client: responses, notifications (`session/update`), and server requests (`session/request_permission`)
### 1.2 Handshake and session calls observed
1. `initialize` returns:
- `protocolVersion`
- `agentCapabilities` (`loadSession`, `mcpCapabilities`, `promptCapabilities`)
- `authMethods` (includes `cursor_login`)
2. `authenticate { methodId: "cursor_login" }` returns `{}` when logged in.
3. `session/new` returns:
- `sessionId`
- `modes` (`agent`, `plan`, `ask`)
4. `session/load` works and requires `sessionId`, `cwd`, `mcpServers`.
5. `session/prompt` returns terminal response `{ stopReason: "end_turn" | "cancelled" }`.
Important sequence note:
1. ACP currently allows `session/new` even without explicit `initialize`/`authenticate` when local auth already exists.
2. For adapter consistency and forward compatibility, we should still send `initialize` and `authenticate` during startup.
### 1.3 `session/update` event families observed
Observed `params.update.sessionUpdate` values:
1. `available_commands_update`
2. `agent_thought_chunk`
3. `agent_message_chunk`
4. `tool_call`
5. `tool_call_update`
Observed payload behavior:
1. `agent_*_chunk` provides `content: { type: "text", text: string }`.
2. `tool_call` may be emitted multiple times for same `toolCallId`:
- initial generic form (`title: "Terminal"`, `rawInput: {}`)
- enriched form (`title: "\`pwd\`"`, `rawInput: { command: "pwd" }`)
3. `tool_call_update` statuses observed:
- `in_progress`
- `completed`
4. `tool_call_update` on completion may include `rawOutput`:
- terminal: `{ exitCode, stdout, stderr }`
- search/find: `{ totalFiles, truncated }`
### 1.4 Permission flow observed
1. ACP server sends `session/request_permission` (JSON-RPC request with `id`).
2. Request shape includes:
- `params.sessionId`
- `params.toolCall`
- `params.options` (`allow-once`, `allow-always`, `reject-once`)
3. Client must respond on same `id` with:
- `{ outcome: { outcome: "selected", optionId: "<one-option-id>" } }`
4. Reject path still results in tool lifecycle completion events (`tool_call_update status: completed`), typically without `rawOutput`.
### 1.5 Error and capability quirks
1. `session/cancel` currently returns:
- JSON-RPC error `-32601` Method not found
2. Error shape examples:
- unknown auth method: `-32602`
- `session/load` missing/invalid params: `-32602`
- `session/prompt` unknown session: `-32603` with details
3. Parallel prompts on same session are effectively single-flight:
- second prompt can cause first to complete with `stopReason: "cancelled"`.
4. `session/new` accepts a `model` field (no explicit echo in response).
Probe artifacts:
1. `.tmp/acp-probe/*/transcript.ndjson`
2. `.tmp/acp-probe/*/summary.json`
3. `scripts/cursor-acp-probe.mjs`
---
## 2) Integration Constraints for T3
1. T3 adapter contract still requires:
- `startSession`, `sendTurn`, `interruptTurn`, `respondToRequest`, `readThread`, `rollbackThread`, `stopSession`, `listSessions`, `hasSession`, `stopAll`, `streamEvents`.
2. Orchestration consumes canonical `ProviderRuntimeEvent` only.
3. `ProviderCommandReactor` provider precedence fix remains required (respect explicit provider on turn start).
4. ACP now supports external permission decisions, so Cursor can participate in T3 approval UX via adapter-managed request/response plumbing.
---
## 3) Proposed Architecture
### 3.1 New server components
1. `apps/server/src/provider/Services/CursorAdapter.ts` (service contract/tag + ACP event schemas).
2. `apps/server/src/provider/Layers/CursorAdapter.ts` (single implementation unit; owns ACP process lifecycle, JSON-RPC routing, runtime projection).
3. No manager indirection; keep logic in layer implementation.
### 3.2 Session model
1. One long-lived ACP child process per T3 Cursor provider session.
2. Track:
- `providerSessionId` (T3 synthetic ID)
- `acpSessionId` (from `session/new` or restored via `session/load`)
- `cwd`, `model`, in-flight turn state
- pending permission requests by JSON-RPC request id
3. Resume support:
- persist `acpSessionId` in provider resume metadata and call `session/load` on reattach.
### 3.3 Command strategy
1. `startSession`:
- spawn `agent acp`
- `initialize`
- `authenticate(cursor_login)` (best-effort, typed failure handling)
- `session/new` or `session/load`
2. `sendTurn`:
- send `session/prompt { sessionId, prompt: [...] }`
- consume streaming `session/update` notifications until terminal prompt response
3. `interruptTurn`:
- no native `session/cancel` today; implement fallback:
- terminate ACP process + restart + `session/load` for subsequent turns
- mark in-flight turn as interrupted/failed in canonical events
4. `respondToRequest`:
- map T3 approval decision -> ACP `optionId`
- reply to exact JSON-RPC request id from `session/request_permission`
### 3.4 Effect-first implementation style (required)
1. Keep logic inside `CursorAdapterLive`.
2. Use Effect primitives:
- `Queue` + `Stream.fromQueue` for event fan-out
- `Ref` / `Ref.Synchronized` for session/process/request state
- scoped fibers for stdout/stderr read loops
3. Typed JSON decode at boundary:
- request/response envelopes
- `session/update` union schema
- permission-request schema
4. Keep adapter errors in typed error algebra with explicit mapping at process/protocol boundaries.
---
## 4) Canonical Event Mapping Plan (ACP -> ProviderRuntimeEvent)
1. `session/update: agent_message_chunk`
- emit `message.delta` for assistant stream
2. prompt terminal response (`session/prompt` result `stopReason: end_turn`)
- emit `message.completed` + `turn.completed`
3. `session/update: agent_thought_chunk`
- initial mapping: emit thinking activity (or ignore if we keep current canonical surface minimal)
4. `session/update: tool_call`
- first-seen `toolCallId` emits `tool.started`
- subsequent `tool_call` for same ID treated as metadata update (no duplicate started event)
5. `session/update: tool_call_update`
- `in_progress`: optional progress activity
- `completed`: emit `tool.completed` with summarized `rawOutput` when present
6. `session/request_permission`
- emit `approval.requested` with mapped options
- when client decision sent, emit `approval.resolved`
7. protocol/process error
- emit `runtime.error`
- fail active turn/session as appropriate
Synthetic IDs:
1. `turnId`: T3-generated UUID per `sendTurn`.
2. `itemId`:
- assistant stream: `${turnId}:assistant`
- tools: `${turnId}:${toolCallId}`
---
## 5) Approval, Resume, and Rollback Behavior
### 5.1 Approvals
1. Cursor ACP permission requests are externally controllable; implement full `respondToRequest` path in v1.
2. Decision mapping:
- allow once -> `allow-once`
- allow always -> `allow-always`
- reject -> `reject-once`
### 5.2 Resume
1. `session/load` is available and should be first-class for adapter restart/reconnect.
2. Must send required params: `sessionId`, `cwd`, `mcpServers`.
### 5.3 Rollback / thread read
1. ACP currently has no observed rollback API.
2. Plan for v1:
- `readThread`: adapter-maintained snapshot projection
- `rollbackThread`: explicit unsupported error
3. Product guard:
- disable checkpoint revert for Cursor threads in UI until rollback exists.
---
## 6) Required Contract and Runtime Changes
### 6.1 Contracts
1. Add `cursor` to `ProviderKind`.
2. Add Cursor provider start options (`providerOptions.cursor`), ACP-oriented:
- optional `binaryPath`
- optional auth/mode knobs if needed later
3. Extend model options for Cursor list and traits mapping.
4. Add schemas for ACP-native event union in Cursor adapter service file.
### 6.2 Server orchestration and registry
1. Register `CursorAdapter` in provider registry and server layer wiring.
2. Update provider-kind persistence decoding for `cursor`.
3. Fix `ProviderCommandReactor` precedence to honor explicit provider in turn-start command.
### 6.3 Web
1. Cursor in provider picker and model picker (already partially done).
2. Trait controls map to concrete Cursor model identifiers.
3. Surface unsupported rollback behavior in UX.
---
## 7) Implementation Phases
### Phase A: ACP process and protocol skeleton
1. Implement ACP process lifecycle in `CursorAdapterLive`.
2. Implement JSON-RPC request/response multiplexer.
3. Implement `initialize`/`authenticate`/`session/new|load` flow.
4. Wire `streamEvents` from ACP notifications.
### Phase B: Runtime projection and approvals
1. Map `session/update` variants to canonical runtime events.
2. Implement permission-request bridging to `respondToRequest`.
3. Implement dedupe for repeated `tool_call` on same `toolCallId`.
### Phase C: Turn control and interruption
1. Implement single in-flight prompt protection per session.
2. Implement interruption fallback (process restart + reload) because `session/cancel` unavailable.
3. Ensure clean state recovery on ACP process crash.
### Phase D: Orchestration + UX polish
1. Provider routing precedence fix.
2. Cursor-specific UX notes for unsupported rollback.
3. End-to-end smoke and event log validation.
---
## 8) Test Plan
Follow project rule: backend external-service integrations tested via layered fakes, not by mocking core business logic.
### 8.1 Unit tests (`CursorAdapter`)
1. JSON-RPC envelope parsing:
- response matching by id
- server request handling (`session/request_permission`)
- notification decode (`session/update`)
2. Event projection:
- `agent_message_chunk` / `agent_thought_chunk`
- `tool_call` + `tool_call_update` dedupe/lifecycle
- permission request -> approval events
3. Error mapping:
- unknown session
- method-not-found (`session/cancel`)
- invalid params
### 8.2 Provider service/routing tests
1. Registry resolves `cursor`.
2. Session directory persistence reads/writes `cursor`.
3. ProviderService fan-out ordering with Cursor ACP events.
### 8.3 Orchestration tests
1. `thread.turn.start` with `provider: cursor` routes to Cursor adapter.
2. approval response command maps to ACP permission response.
3. checkpoint revert on Cursor thread returns controlled unsupported failure.
### 8.4 Optional live smoke
1. Env-gated ACP smoke:
- start session
- run prompt
- observe deltas + completion
- exercise permission request path with one tool call
---
## 9) Operational Notes
1. Keep one in-flight turn per ACP session.
2. Keep per-session ACP process logs/NDJSON artifacts for debugging.
3. Treat `session/cancel` as unsupported until Cursor ships it; avoid relying on it.
4. Preserve resume metadata (`acpSessionId`) for crash recovery.
---
## 10) Open Questions
1. Should we call `authenticate` always, or only after auth-required errors?
2. Should model selection be passed at `session/new` only, or can/should we support model switching mid-session if ACP adds API?
3. For interruption UX, do we expose “hard interrupt” semantics (process restart) explicitly?
---
## 11) Delivery Checklist
1. Plan/documentation switched from headless `agent -p` to ACP `agent acp`.
2. Contracts updated (`ProviderKind`, Cursor options, model/trait mapping).
3. Cursor ACP adapter layer implemented and registered.
4. Provider precedence fixed in orchestration router.
5. Approval response path wired through ACP permission requests.
6. Tests added for protocol decode, projection, approval flow, and routing.
7. Lint + tests green.
+51
View File
@@ -3,13 +3,16 @@
Goal: Align the orchestration model to `SPEC.md` 1:1 and remove legacy persistence/application cruft. Goal: Align the orchestration model to `SPEC.md` 1:1 and remove legacy persistence/application cruft.
Execution mode for this plan: Execution mode for this plan:
- Hard cutover only. Existing DB and migration history are disposable. - Hard cutover only. Existing DB and migration history are disposable.
- Intermediate steps are allowed to break runtime, tests, typecheck, and lint. - Intermediate steps are allowed to break runtime, tests, typecheck, and lint.
- We optimize for small, reviewable work units, not continuous app operability. - We optimize for small, reviewable work units, not continuous app operability.
- Only the final gate requires everything to run cleanly. - Only the final gate requires everything to run cleanly.
## 1. Freeze SPEC contract as source of truth ## 1. Freeze SPEC contract as source of truth
Work units: Work units:
- Create `.plans/spec-contract-matrix.md` with one row per requirement in `SPEC.md` sections `7.1`-`7.4`. - 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 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. - 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. - Identify any ambiguous spec lines and record a concrete interpretation in the matrix.
Deliverables: Deliverables:
- Complete matrix file with no unclassified rows. - Complete matrix file with no unclassified rows.
- Single source checklist used by all later steps. - Single source checklist used by all later steps.
Breakage allowed: Breakage allowed:
- No code changes required yet. - No code changes required yet.
Exit criteria: Exit criteria:
- Every requirement in `7.1`-`7.4` has exactly one matrix row. - Every requirement in `7.1`-`7.4` has exactly one matrix row.
## 2. Hard cutover migrations (replace current migration set) ## 2. Hard cutover migrations (replace current migration set)
Work units: Work units:
- Delete the current legacy migration files and rewrite migration loader ordering. - 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 `001_orchestration_events.ts` with full envelope columns and required event indexes.
- Create `002_orchestration_command_receipts.ts` with PK + lookup 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. - Ensure old tables (`projects`, `provider_checkpoints`, `provider_sessions`) are not recreated.
Deliverables: Deliverables:
- New 5-file migration chain. - New 5-file migration chain.
- Updated migration loader references only new migrations. - Updated migration loader references only new migrations.
Breakage allowed: Breakage allowed:
- Repositories/services can be temporarily broken due to removed old tables. - Repositories/services can be temporarily broken due to removed old tables.
Exit criteria: Exit criteria:
- Fresh DB initializes with only canonical tables plus migration bookkeeping. - Fresh DB initializes with only canonical tables plus migration bookkeeping.
## 3. Align persistence row/request schemas to DB 1:1 ## 3. Align persistence row/request schemas to DB 1:1
Work units: Work units:
- Define row schemas for each canonical table (contracts or persistence layer module). - Define row schemas for each canonical table (contracts or persistence layer module).
- Define request schemas for every insert/update/query operation touching canonical tables. - Define request schemas for every insert/update/query operation touching canonical tables.
- Remove or deprecate row/request schemas tied to deleted legacy 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). - Ensure SQL aliases map 1:1 to schema field names (no implicit shape transforms).
Deliverables: Deliverables:
- Canonical row/request schemas committed. - Canonical row/request schemas committed.
- Zero references to legacy row schemas in active code paths. - Zero references to legacy row schemas in active code paths.
Breakage allowed: Breakage allowed:
- Runtime can still fail while query layers are being rewired. - Runtime can still fail while query layers are being rewired.
Exit criteria: Exit criteria:
- Every canonical table used in code has a typed row schema and typed request schema. - Every canonical table used in code has a typed row schema and typed request schema.
## 4. Rewrite event store for full persisted envelope ## 4. Rewrite event store for full persisted envelope
Work units: Work units:
- Refactor append path to write full envelope fields: - 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` - `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. - 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`). - Add explicit SQL ordering guarantees for replay (`ORDER BY sequence ASC`).
Deliverables: Deliverables:
- Event store append/replay fully aligned with canonical envelope. - Event store append/replay fully aligned with canonical envelope.
Breakage allowed: Breakage allowed:
- Command dispatch flow can be partially broken until receipts/projectors are updated. - Command dispatch flow can be partially broken until receipts/projectors are updated.
Exit criteria: Exit criteria:
- Event store no longer depends on legacy event table shape. - Event store no longer depends on legacy event table shape.
## 5. Add command receipt idempotency ## 5. Add command receipt idempotency
Work units: Work units:
- Introduce persistence access layer for `orchestration_command_receipts`. - Introduce persistence access layer for `orchestration_command_receipts`.
- In command dispatch flow, check existing receipt by `commandId` before append. - In command dispatch flow, check existing receipt by `commandId` before append.
- On first execution, persist accepted receipt with `resultSequence`. - On first execution, persist accepted receipt with `resultSequence`.
@@ -102,16 +125,21 @@ Work units:
- Ensure receipt write and event append ordering is deterministic. - Ensure receipt write and event append ordering is deterministic.
Deliverables: Deliverables:
- Dispatch path with idempotency behavior wired through receipts. - Dispatch path with idempotency behavior wired through receipts.
Breakage allowed: Breakage allowed:
- Snapshot/read model may still be inconsistent until projectors are fully wired. - Snapshot/read model may still be inconsistent until projectors are fully wired.
Exit criteria: Exit criteria:
- Duplicate command IDs no longer create duplicate events. - Duplicate command IDs no longer create duplicate events.
## 6. Build DB-backed projection pipeline ## 6. Build DB-backed projection pipeline
Work units: Work units:
- Create projector runner that consumes events and applies table-specific projections. - Create projector runner that consumes events and applies table-specific projections.
- Implement projector handlers for each projection table. - Implement projector handlers for each projection table.
- For each handler, update target row(s) and `projection_state.last_applied_sequence` in the same transaction. - 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`. - Add safe resume logic from projector `last_applied_sequence`.
Deliverables: Deliverables:
- Persistent projector pipeline writing all `projection_*` tables. - Persistent projector pipeline writing all `projection_*` tables.
Breakage allowed: Breakage allowed:
- Web/API layer may still read old in-memory model until step 7. - Web/API layer may still read old in-memory model until step 7.
Exit criteria: Exit criteria:
- Events drive projection rows in DB; projection state advances transactionally. - Events drive projection rows in DB; projection state advances transactionally.
## 7. Move RPC reads to projections and diff blobs ## 7. Move RPC reads to projections and diff blobs
Work units: Work units:
- Implement snapshot query service reading only projection tables. - Implement snapshot query service reading only projection tables.
- Build thread hydration from projection rows: messages, activities, checkpoints, session. - Build thread hydration from projection rows: messages, activities, checkpoints, session.
- Compute `snapshotSequence` as the minimum required projector sequence from `projection_state`. - 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`. - Validate replay handoff contract: snapshot sequence -> replay from `fromSequenceExclusive`.
Deliverables: Deliverables:
- `orchestration.getSnapshot` and `orchestration.getTurnDiff` served from DB projections/blob store. - `orchestration.getSnapshot` and `orchestration.getTurnDiff` served from DB projections/blob store.
Breakage allowed: Breakage allowed:
- Provider runtime persistence may still be partially legacy until step 8. - Provider runtime persistence may still be partially legacy until step 8.
Exit criteria: Exit criteria:
- No orchestration read RPC depends on legacy tables or in-memory-only state. - No orchestration read RPC depends on legacy tables or in-memory-only state.
## 8. Migrate provider runtime persistence to canonical table ## 8. Migrate provider runtime persistence to canonical table
Work units: Work units:
- Create repository/service for `provider_session_runtime`. - Create repository/service for `provider_session_runtime`.
- Update adapter/session manager to persist runtime/resume cursor in new table. - 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`. - 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. - Verify restart/resume path reads runtime state from canonical table only.
Deliverables: Deliverables:
- Provider runtime state entirely backed by `provider_session_runtime`. - Provider runtime state entirely backed by `provider_session_runtime`.
Breakage allowed: Breakage allowed:
- Some legacy interfaces may still exist but should be disconnected. - Some legacy interfaces may still exist but should be disconnected.
Exit criteria: Exit criteria:
- Runtime restore no longer reads/writes legacy provider session persistence. - Runtime restore no longer reads/writes legacy provider session persistence.
## 9. Remove old cruft aggressively ## 9. Remove old cruft aggressively
Work units: Work units:
- Delete legacy repositories/services that map to removed tables. - Delete legacy repositories/services that map to removed tables.
- Remove dead migration imports and obsolete persistence service interfaces. - Remove dead migration imports and obsolete persistence service interfaces.
- Remove compatibility code paths that translate legacy row shapes. - 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. - Update internal docs/comments to reference canonical projection/event model only.
Deliverables: Deliverables:
- Legacy persistence and translation layers removed from active codebase. - Legacy persistence and translation layers removed from active codebase.
Breakage allowed: Breakage allowed:
- Temporary compile failures acceptable while deletion/refactor is in progress. - Temporary compile failures acceptable while deletion/refactor is in progress.
Exit criteria: Exit criteria:
- No production code path references deleted legacy tables/services. - No production code path references deleted legacy tables/services.
## 10. Final verification gate (first point where green is required) ## 10. Final verification gate (first point where green is required)
Work units: Work units:
- Add migration tests that assert canonical tables, columns, constraints, and indexes. - Add migration tests that assert canonical tables, columns, constraints, and indexes.
- Add event store tests for envelope persistence, metadata, actor kind, and replay. - Add event store tests for envelope persistence, metadata, actor kind, and replay.
- Add receipt idempotency tests for accept/reject/duplicate paths. - Add receipt idempotency tests for accept/reject/duplicate paths.
@@ -192,10 +240,13 @@ Work units:
- Run project lint/typecheck/tests and fix failures. - Run project lint/typecheck/tests and fix failures.
Deliverables: Deliverables:
- Green checks with canonical schema + persistence model in place. - Green checks with canonical schema + persistence model in place.
Breakage allowed: Breakage allowed:
- None at end of step. - None at end of step.
Exit criteria: Exit criteria:
- SPEC `7.1`-`7.4` requirements satisfied and validated by tests. - 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) # SPEC Contract Matrix (Sections 7.1-7.4)
Status legend: Status legend:
- `required`: requirement acknowledged, no current implementation claim yet. - `required`: requirement acknowledged, no current implementation claim yet.
- `implemented`: requirement currently satisfied in code + schema. - `implemented`: requirement currently satisfied in code + schema.
- `to-replace`: partial/misaligned implementation exists and must be replaced. - `to-replace`: partial/misaligned implementation exists and must be replaced.
@@ -9,6 +10,7 @@ Status legend:
## 7.1 Write-Side Persisted Tables ## 7.1 Write-Side Persisted Tables
### W1 ### W1
- Spec ref: `7.1.1 orchestration_events` - Spec ref: `7.1.1 orchestration_events`
- Requirement: append-only event store with canonical envelope columns. - Requirement: append-only event store with canonical envelope columns.
- SQL contract: - 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`. - Notes: current migration/table lacks `stream_id`, `stream_version`, `causation_event_id`, `correlation_id`, `actor_kind`, `metadata_json`.
### W2 ### W2
- Spec ref: `7.1.2 orchestration_command_receipts` - Spec ref: `7.1.2 orchestration_command_receipts`
- Requirement: command idempotency + ack replay receipts table. - Requirement: command idempotency + ack replay receipts table.
- SQL contract: - SQL contract:
@@ -49,6 +52,7 @@ Status legend:
- Notes: missing table and missing idempotency flow. - Notes: missing table and missing idempotency flow.
### W3 ### W3
- Spec ref: `7.1.3 checkpoint_diff_blobs` - Spec ref: `7.1.3 checkpoint_diff_blobs`
- Requirement: store large plaintext diffs separate from checkpoint summaries. - Requirement: store large plaintext diffs separate from checkpoint summaries.
- SQL contract: - SQL contract:
@@ -65,6 +69,7 @@ Status legend:
- Notes: no canonical diff blob table yet. - Notes: no canonical diff blob table yet.
### W4 ### W4
- Spec ref: `7.1.4 provider_session_runtime` - Spec ref: `7.1.4 provider_session_runtime`
- Requirement: server-internal provider runtime/resume state. - Requirement: server-internal provider runtime/resume state.
- SQL contract: - SQL contract:
@@ -86,6 +91,7 @@ Status legend:
## 7.2 Canonical Persisted Event Schema ## 7.2 Canonical Persisted Event Schema
### E1 ### E1
- Spec ref: `7.2 OrchestrationPersistedEventSchema` - Spec ref: `7.2 OrchestrationPersistedEventSchema`
- Requirement: full typed persisted event envelope in shared contracts. - Requirement: full typed persisted event envelope in shared contracts.
- SQL contract: envelope fields in W1 must map 1:1 to contracts schema. - 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. - Notes: contract schema exists; DB + store mapping still incomplete.
### E2 ### E2
- Spec ref: `7.2 Rules/payload discriminated by eventType` - Spec ref: `7.2 Rules/payload discriminated by eventType`
- Requirement: `payload` validation keyed by `eventType`. - Requirement: `payload` validation keyed by `eventType`.
- SQL contract: `event_type` drives payload decode schema; invalid combinations rejected. - 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. - Notes: decode is present but DB does not persist full envelope columns.
### E3 ### E3
- Spec ref: `7.2 Rules/provider ids scope` - Spec ref: `7.2 Rules/provider ids scope`
- Requirement: provider ids live in metadata/provider payload, not as thread identity replacement. - 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. - 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. - Notes: metadata plumbing is incomplete in persistence path.
### E4 ### E4
- Spec ref: `7.2 Rules/streamVersion concurrency guard` - Spec ref: `7.2 Rules/streamVersion concurrency guard`
- Requirement: stream version monotonic per aggregate stream; enforced on write. - Requirement: stream version monotonic per aggregate stream; enforced on write.
- SQL contract: `stream_version INTEGER NOT NULL` + uniqueness/invariant enforcement per stream. - 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) ## 7.3 Required Projected Tables (Read Models)
### P1 ### P1
- Spec ref: `7.3.1 projection_projects` - Spec ref: `7.3.1 projection_projects`
- Requirement: persisted project projection table. - Requirement: persisted project projection table.
- SQL contract: - SQL contract:
@@ -145,6 +155,7 @@ Status legend:
- Notes: legacy `projects` table is separate concept and should be removed from orchestration model. - Notes: legacy `projects` table is separate concept and should be removed from orchestration model.
### P2 ### P2
- Spec ref: `7.3.2 projection_threads` - Spec ref: `7.3.2 projection_threads`
- Requirement: persisted thread projection table. - Requirement: persisted thread projection table.
- SQL contract: - SQL contract:
@@ -165,6 +176,7 @@ Status legend:
- Notes: missing table and projector writes. - Notes: missing table and projector writes.
### P3 ### P3
- Spec ref: `7.3.3 projection_thread_messages` - Spec ref: `7.3.3 projection_thread_messages`
- Requirement: persisted thread message projection table. - Requirement: persisted thread message projection table.
- SQL contract: - SQL contract:
@@ -183,6 +195,7 @@ Status legend:
- Notes: missing table and message projection writes. - Notes: missing table and message projection writes.
### P4 ### P4
- Spec ref: `7.3.4 projection_thread_activities` - Spec ref: `7.3.4 projection_thread_activities`
- Requirement: persisted thread activity projection table. - Requirement: persisted thread activity projection table.
- SQL contract: - SQL contract:
@@ -201,6 +214,7 @@ Status legend:
- Notes: no canonical activity projection persistence. - Notes: no canonical activity projection persistence.
### P5 ### P5
- Spec ref: `7.3.5 projection_thread_sessions` - Spec ref: `7.3.5 projection_thread_sessions`
- Requirement: persisted thread session projection table. - Requirement: persisted thread session projection table.
- SQL contract: - SQL contract:
@@ -219,6 +233,7 @@ Status legend:
- Notes: current provider session table is not this domain projection. - Notes: current provider session table is not this domain projection.
### P6 ### P6
- Spec ref: `7.3.6 projection_thread_turns` - Spec ref: `7.3.6 projection_thread_turns`
- Requirement: persisted thread turn projection table. - Requirement: persisted thread turn projection table.
- SQL contract: - SQL contract:
@@ -237,6 +252,7 @@ Status legend:
- Notes: missing table and projection logic. - Notes: missing table and projection logic.
### P7 ### P7
- Spec ref: `7.3.7 projection_checkpoints` - Spec ref: `7.3.7 projection_checkpoints`
- Requirement: persisted checkpoint summary projection table. - Requirement: persisted checkpoint summary projection table.
- SQL contract: - SQL contract:
@@ -256,6 +272,7 @@ Status legend:
- Notes: current table semantics do not match canonical checkpoint projection schema. - Notes: current table semantics do not match canonical checkpoint projection schema.
### P8 ### P8
- Spec ref: `7.3.8 projection_pending_approvals` - Spec ref: `7.3.8 projection_pending_approvals`
- Requirement: persisted pending-approval projection table. - Requirement: persisted pending-approval projection table.
- SQL contract: - SQL contract:
@@ -273,6 +290,7 @@ Status legend:
- Notes: missing table and projection logic. - Notes: missing table and projection logic.
### P9 ### P9
- Spec ref: `7.3.9 projection_state` - Spec ref: `7.3.9 projection_state`
- Requirement: projector progress tracking table. - Requirement: projector progress tracking table.
- SQL contract: - SQL contract:
@@ -286,6 +304,7 @@ Status legend:
- Notes: missing table and projector bookkeeping. - Notes: missing table and projector bookkeeping.
### P10 ### P10
- Spec ref: `7.3 Projection consistency rules` - Spec ref: `7.3 Projection consistency rules`
- Requirement: projector row updates and `projection_state` update must be atomic per event. - 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. - SQL contract: per-projector transaction boundary covering both projection write and state update.
@@ -296,6 +315,7 @@ Status legend:
- Notes: requires transactional projection executor. - Notes: requires transactional projection executor.
### P11 ### P11
- Spec ref: `7.3 Optional debug field` - Spec ref: `7.3 Optional debug field`
- Requirement: `lastEventSequence` on projection rows is optional and not required for correctness. - Requirement: `lastEventSequence` on projection rows is optional and not required for correctness.
- SQL contract: optional; not required in baseline schema. - SQL contract: optional; not required in baseline schema.
@@ -308,6 +328,7 @@ Status legend:
## 7.4 Snapshot and RPC Requirements ## 7.4 Snapshot and RPC Requirements
### R1 ### R1
- Spec ref: `7.4.1` - Spec ref: `7.4.1`
- Requirement: `orchestration.getSnapshot` fully served from projection tables and returns `snapshotSequence`. - Requirement: `orchestration.getSnapshot` fully served from projection tables and returns `snapshotSequence`.
- SQL contract: snapshot query joins/reads only `projection_*` + `projection_state`. - 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. - Notes: current in-memory read model path must be removed for SPEC compliance.
### R2 ### R2
- Spec ref: `7.4.2` - Spec ref: `7.4.2`
- Requirement: snapshot `projects[]` source is `projection_projects`. - Requirement: snapshot `projects[]` source is `projection_projects`.
- SQL contract: `projects` collection assembled from `projection_projects` rows. - SQL contract: `projects` collection assembled from `projection_projects` rows.
@@ -328,6 +350,7 @@ Status legend:
- Notes: no DB project projection reader exists yet. - Notes: no DB project projection reader exists yet.
### R3 ### R3
- Spec ref: `7.4.3` - Spec ref: `7.4.3`
- Requirement: thread snapshot `checkpoints[]` source is `projection_checkpoints` with required fields. - Requirement: thread snapshot `checkpoints[]` source is `projection_checkpoints` with required fields.
- SQL contract: fields `turnId`, `completedAt`, `status`, `files[]`, `checkpointRef`, optional `assistantMessageId`, `checkpointTurnCount`. - 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. - Notes: canonical projection table and reader not implemented.
### R4 ### R4
- Spec ref: `7.4.4` - Spec ref: `7.4.4`
- Requirement: no `listCheckpoints` orchestration RPC; list in snapshot + full diff via `getTurnDiff` from diff blobs. - Requirement: no `listCheckpoints` orchestration RPC; list in snapshot + full diff via `getTurnDiff` from diff blobs.
- SQL contract: `getTurnDiff` reads `checkpoint_diff_blobs` only. - SQL contract: `getTurnDiff` reads `checkpoint_diff_blobs` only.
@@ -348,6 +372,7 @@ Status legend:
- Notes: current checkpoint repository is not canonical source. - Notes: current checkpoint repository is not canonical source.
### R5 ### R5
- Spec ref: `7.4.5` - Spec ref: `7.4.5`
- Requirement: client acts on `ThreadId`; server resolves provider session via `projection_thread_sessions`. - Requirement: client acts on `ThreadId`; server resolves provider session via `projection_thread_sessions`.
- SQL contract: session lookup by `thread_id` from projection table. - SQL contract: session lookup by `thread_id` from projection table.
@@ -358,6 +383,7 @@ Status legend:
- Notes: remove provider-session-as-routing-key behavior. - Notes: remove provider-session-as-routing-key behavior.
### R6 ### R6
- Spec ref: `7.4.6` - Spec ref: `7.4.6`
- Requirement: `snapshotSequence` derived from `projection_state` minimum over dependent projectors. - Requirement: `snapshotSequence` derived from `projection_state` minimum over dependent projectors.
- SQL contract: `MIN(last_applied_sequence)` across required projector keys. - 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. - Notes: must move from in-memory sequence to DB projection-state semantics.
### R7 ### R7
- Spec ref: `7.4.7` - Spec ref: `7.4.7`
- Requirement: snapshot/replay handoff has no gap (`getSnapshot` -> subscribe from snapshot sequence). - 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. - 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) ## Ambiguous/Interpretation Decisions (tracked upfront)
### A1 ### A1
- Topic: `orchestration_events.stream_id` vs event runtime `aggregateId` naming. - 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. - Decision: persist canonical DB column name `stream_id`; map to runtime `aggregateId` where needed in decider/projector code.
### A2 ### A2
- Topic: JSON column typing in SQLite for `payload`, `metadata`, projection payload/files, runtime cursor/payload. - 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. - Decision: store as `TEXT` JSON with strict encode/decode schemas at boundaries.
### A3 ### A3
- Topic: `snapshotSequence` dependency set for min-sequence computation. - 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`). - Decision: include all projectors used to construct snapshot payload (`projects`, `threads`, `messages`, `activities`, `sessions`, `turns`, `checkpoints`, `pending_approvals`).
### A4 ### A4
- Topic: no-gap handoff mechanism in `7.4.7`. - Topic: no-gap handoff mechanism in `7.4.7`.
- Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`. - Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`.
## Checklist Completeness Statement ## Checklist Completeness Statement
- Coverage scope: `SPEC.md` sections `7.1`, `7.2`, `7.3`, `7.4`. - Coverage scope: `SPEC.md` sections `7.1`, `7.2`, `7.3`, `7.4`.
- Requirement rows present: `W1-W4`, `E1-E4`, `P1-P11`, `R1-R7`. - Requirement rows present: `W1-W4`, `E1-E4`, `P1-P11`, `R1-R7`.
- Unclassified rows: `0`. - Unclassified rows: `0`.
+1 -1
View File
@@ -2,7 +2,7 @@
## Task Completion Requirements ## 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). - NEVER run `bun test`. Always use `bun run test` (runs Vitest).
## Project Snapshot ## Project Snapshot
+1 -1
View File
@@ -1 +1 @@
AGENTS.md AGENTS.md
+65
View File
@@ -0,0 +1,65 @@
# Contributing
## Read This First
We are not actively accepting contributions right now.
You can still open an issue or PR, but please do so knowing there is a high chance we close it, defer it forever, or never look at it.
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 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).
## What We Are Most Likely To Accept
Small, focused bug fixes.
Small reliability fixes.
Small performance improvements.
Tightly scoped maintenance work that clearly improves the project without changing its direction.
## What We Are Least Likely To Accept
Large PRs.
Drive-by feature work.
Opinionated rewrites.
Anything that expands product scope without us asking for it first.
If you open a 1,000+ line PR full of new features, we will probably close it quickly and remember that you ignored the clearly written instructions.
## If You Still Want To Open A PR
Keep it small.
Explain exactly what changed.
Explain exactly why the change should exist.
Do not mix unrelated fixes together.
If the PR makes anything resembling a UI change, include clear before/after images.
If the change depends on motion, timing, transitions, or interaction details, include a short video.
If we have to guess what changed, we are much less likely to review it.
## Issues First
If you are thinking about a non-trivial change, open an issue first.
That still does not mean we will want the PR, but it gives you a chance to avoid wasting your time.
## Be Realistic
Opening a PR does not create an obligation on our side.
We may close it. We may ignore it. We may ask you to shrink it. We may reimplement the idea ourselves later.
If you are fine with that, proceed.
+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.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused 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.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 - `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`) - `script.{id}.run`: run a project script by id (for example `script.test.run`)
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 T3 Tools Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+11 -119
View File
@@ -2,135 +2,27 @@
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-first, with Claude Code support coming soon.
Run `npx t3` in any project directory to launch the web interface. ## How to use
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
## Architecture > [!WARNING]
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
## Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## Codex prerequisites
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
## Quick start
```bash ```bash
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
bun run build
bun run start
# Build a shareable macOS .dmg (arm64 by default)
bun run dist:desktop:dmg
# Or from any project directory after publishing:
npx t3 npx t3
``` ```
## Scripts You can also just install the desktop app. It's cooler.
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode. Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
### Desktop `.dmg` packaging notes ## Some notes
- Default build is unsigned/not notarized for local sharing. We are very very early in this project. Expect bugs.
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
### Running multiple dev instances We are not accepting contributions yet.
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together. ## If you REALLY want to contribute still.... read this first
- Default ports: server `3773`, web `5733` Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset. Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
## Runtime modes
T3 Code has a global runtime mode switch in the chat toolbar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
## Provider architecture
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
## CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
-12
View File
@@ -2,24 +2,12 @@
## Small things ## Small things
- [ ] Plan mode
- [ ] Submitting new messages should scroll to bottom - [ ] Submitting new messages should scroll to bottom
- [ ] 1 click copy in codeblocks
- [x] Pasting/adding images to submit with prompts
- [ ] Only show last 10 threads for a given project - [ ] Only show last 10 threads for a given project
- [ ] Thread archiving - [ ] Thread archiving
- [x] Selecting folder should instantly create project
- [ ] New projects should go on top - [ ] New projects should go on top
- [ ] Projects should be sorted by latest thread update - [ ] Projects should be sorted by latest thread update
- [x] "Response" bar should ONLY appear on work completed
- [x] "Response" bar should ONLY appear above the FINAL message in a series
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
- [x] Insta focus input on new thread creation
- [x] Disable "streaming" (wait until whole paragraph/step finishes before showing it
- [x] Making new thread should auto-focus input box
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
## Bigger things ## Bigger things
- [ ] Queueing messages - [ ] Queueing messages
- [x] External runners (i.e. running the cli on a mac mini)
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@t3tools/desktop", "name": "@t3tools/desktop",
"version": "0.0.0-alpha.20", "version": "0.0.10",
"private": true, "private": true,
"main": "dist-electron/main.js", "main": "dist-electron/main.js",
"scripts": { "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 port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
const devServerUrl = `http://localhost:${port}`; 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 = [ const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) }, { directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["index.mjs"]) }, { 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) { if (currentApp === app) {
currentApp = null; currentApp = null;
} }
if (!shuttingDown && !expectedExits.has(app)) { const exitedAbnormally = signal !== null || code !== 0;
if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
scheduleRestart(); scheduleRestart();
} }
}); });
@@ -148,13 +153,17 @@ function scheduleRestart() {
function startWatchers() { function startWatchers() {
for (const { directory, files } of watchedDirectories) { for (const { directory, files } of watchedDirectories) {
const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => { const watcher = watch(
if (typeof filename !== "string" || !files.has(filename)) { join(desktopDir, directory),
return; { persistent: true },
} (_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
return;
}
scheduleRestart(); scheduleRestart();
}); },
);
watchers.push(watcher); watchers.push(watcher);
} }
+2 -5
View File
@@ -1,14 +1,11 @@
import * as ChildProcess from "node:child_process"; import { readPathFromLoginShell } from "@t3tools/shared/shell";
export function fixPath(): void { export function fixPath(): void {
if (process.platform !== "darwin") return; if (process.platform !== "darwin") return;
try { try {
const shell = process.env.SHELL ?? "/bin/zsh"; const shell = process.env.SHELL ?? "/bin/zsh";
const result = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], { const result = readPathFromLoginShell(shell);
encoding: "utf8",
timeout: 5000,
});
if (result) { if (result) {
process.env.PATH = result; process.env.PATH = result;
} }
+201 -30
View File
@@ -4,10 +4,24 @@ import * as FS from "node:fs";
import * as OS from "node:os"; import * as OS from "node:os";
import * as Path from "node:path"; 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 type { MenuItemConstructorOptions } from "electron";
import * as Effect from "effect/Effect"; 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 { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts"; import type { ContextMenuItem } from "@t3tools/contracts";
@@ -15,10 +29,7 @@ import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging"; import { RotatingFileSink } from "@t3tools/shared/logging";
import { showDesktopConfirmDialog } from "./confirmDialog"; import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath"; import { fixPath } from "./fixPath";
import { import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
getAutoUpdateDisabledReason,
shouldBroadcastDownloadProgress,
} from "./updateState";
import { import {
createInitialDesktopUpdateState, createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure, reduceDesktopUpdateStateOnCheckFailure,
@@ -31,11 +42,13 @@ import {
reduceDesktopUpdateStateOnNoUpdate, reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable, reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine"; } from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
fixPath(); fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder"; const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm"; const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu"; const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external"; const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action"; const MENU_ACTION_CHANNEL = "desktop:menu-action";
@@ -50,6 +63,8 @@ const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL); const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)"; const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code"; const APP_USER_MODEL_ID = "com.t3tools.t3code";
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i; const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
const COMMIT_HASH_DISPLAY_LENGTH = 12; const COMMIT_HASH_DISPLAY_LENGTH = 12;
const LOG_DIR = Path.join(STATE_DIR, "logs"); const LOG_DIR = Path.join(STATE_DIR, "logs");
@@ -58,6 +73,8 @@ const LOG_FILE_MAX_FILES = 10;
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex"); const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000; const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000; const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
const DESKTOP_UPDATE_CHANNEL = "latest";
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"]; type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
@@ -76,7 +93,13 @@ let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null; let restoreStdIoCapture: (() => void) | null = null;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined; let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const initialUpdateState = (): DesktopUpdateState => createInitialDesktopUpdateState(app.getVersion()); const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
platform: process.platform,
processArch: process.arch,
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
function logTimestamp(): string { function logTimestamp(): string {
return new Date().toISOString(); return new Date().toISOString();
@@ -110,6 +133,33 @@ function formatErrorMessage(error: unknown): string {
return String(error); return String(error);
} }
function getSafeExternalUrl(rawUrl: unknown): string | null {
if (typeof rawUrl !== "string" || rawUrl.length === 0) {
return null;
}
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return null;
}
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
return null;
}
return parsedUrl.toString();
}
function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
if (rawTheme === "light" || rawTheme === "dark" || rawTheme === "system") {
return rawTheme;
}
return null;
}
function writeDesktopStreamChunk( function writeDesktopStreamChunk(
streamName: "stdout" | "stderr", streamName: "stdout" | "stderr",
chunk: unknown, chunk: unknown,
@@ -485,7 +535,28 @@ function handleCheckForUpdatesMenuClick(): void {
if (!BrowserWindow.getAllWindows().length) { if (!BrowserWindow.getAllWindows().length) {
mainWindow = createWindow(); 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 { function configureApplicationMenu(): void {
@@ -536,7 +607,21 @@ function configureApplicationMenu(): void {
], ],
}, },
{ role: "editMenu" }, { 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: "windowMenu" },
{ {
role: "help", role: "help",
@@ -555,6 +640,7 @@ function configureApplicationMenu(): void {
function resolveResourcePath(fileName: string): string | null { function resolveResourcePath(fileName: string): string | null {
const candidates = [ const candidates = [
Path.join(__dirname, "../resources", fileName), Path.join(__dirname, "../resources", fileName),
Path.join(__dirname, "../prod-resources", fileName),
Path.join(process.resourcesPath, "resources", fileName), Path.join(process.resourcesPath, "resources", fileName),
Path.join(process.resourcesPath, fileName), Path.join(process.resourcesPath, fileName),
]; ];
@@ -572,6 +658,34 @@ function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
return resolveResourcePath(`icon.${ext}`); return resolveResourcePath(`icon.${ext}`);
} }
/**
* Resolve the Electron userData directory path.
*
* Electron derives the default userData path from `productName` in
* package.json, which currently produces directories with spaces and
* parentheses (e.g. `~/.config/T3 Code (Alpha)` on Linux). This is
* unfriendly for shell usage and violates Linux naming conventions.
*
* We override it to a clean lowercase name (`t3code`). If the legacy
* directory already exists we keep using it so existing users don't
* lose their Chromium profile data (localStorage, cookies, sessions).
*/
function resolveUserDataPath(): string {
const appDataBase =
process.platform === "win32"
? process.env.APPDATA || Path.join(OS.homedir(), "AppData", "Roaming")
: process.platform === "darwin"
? Path.join(OS.homedir(), "Library", "Application Support")
: process.env.XDG_CONFIG_HOME || Path.join(OS.homedir(), ".config");
const legacyPath = Path.join(appDataBase, LEGACY_USER_DATA_DIR_NAME);
if (FS.existsSync(legacyPath)) {
return legacyPath;
}
return Path.join(appDataBase, USER_DATA_DIR_NAME);
}
function configureAppIdentity(): void { function configureAppIdentity(): void {
app.setName(APP_DISPLAY_NAME); app.setName(APP_DISPLAY_NAME);
const commitHash = resolveAboutCommitHash(); const commitHash = resolveAboutCommitHash();
@@ -644,7 +758,9 @@ async function checkForUpdates(reason: string): Promise<void> {
await autoUpdater.checkForUpdates(); await autoUpdater.checkForUpdates();
} catch (error: unknown) { } catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error); 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}`); console.error(`[desktop-updater] Failed to check for updates: ${message}`);
} finally { } finally {
updateCheckInFlight = false; updateCheckInFlight = false;
@@ -657,6 +773,7 @@ async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed
} }
updateDownloadInFlight = true; updateDownloadInFlight = true;
setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState)); setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState));
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
console.info("[desktop-updater] Downloading update..."); console.info("[desktop-updater] Downloading update...");
try { try {
@@ -695,7 +812,7 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
function configureAutoUpdater(): void { function configureAutoUpdater(): void {
const enabled = shouldEnableAutoUpdates(); const enabled = shouldEnableAutoUpdates();
setUpdateState({ setUpdateState({
...createInitialDesktopUpdateState(app.getVersion()), ...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled, enabled,
status: enabled ? "idle" : "disabled", status: enabled ? "idle" : "disabled",
}); });
@@ -705,9 +822,7 @@ function configureAutoUpdater(): void {
updaterConfigured = true; updaterConfigured = true;
const githubToken = const githubToken =
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
process.env.GH_TOKEN?.trim() ||
"";
if (githubToken) { if (githubToken) {
// When a token is provided, re-configure the feed with `private: true` so // 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 // electron-updater uses the GitHub API (api.github.com) instead of the
@@ -725,14 +840,30 @@ function configureAutoUpdater(): void {
autoUpdater.autoDownload = false; autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false; autoUpdater.autoInstallOnAppQuit = false;
autoUpdater.allowPrerelease = app.getVersion().includes("-"); // Keep alpha branding, but force all installs onto the stable update track.
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
autoUpdater.allowDowngrade = false;
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
let lastLoggedDownloadMilestone = -1; let lastLoggedDownloadMilestone = -1;
if (isArm64HostRunningIntelBuild(desktopRuntimeInfo)) {
console.info(
"[desktop-updater] Apple Silicon host detected while running Intel build; updates will switch to arm64 packages.",
);
}
autoUpdater.on("checking-for-update", () => { autoUpdater.on("checking-for-update", () => {
console.info("[desktop-updater] Looking for updates..."); console.info("[desktop-updater] Looking for updates...");
}); });
autoUpdater.on("update-available", (info) => { autoUpdater.on("update-available", (info) => {
setUpdateState(reduceDesktopUpdateStateOnUpdateAvailable(updateState, info.version, new Date().toISOString())); setUpdateState(
reduceDesktopUpdateStateOnUpdateAvailable(
updateState,
info.version,
new Date().toISOString(),
),
);
lastLoggedDownloadMilestone = -1; lastLoggedDownloadMilestone = -1;
console.info(`[desktop-updater] Update available: ${info.version}`); console.info(`[desktop-updater] Update available: ${info.version}`);
}); });
@@ -965,6 +1096,16 @@ function registerIpcHandlers(): void {
return showDesktopConfirmDialog(message, owner); 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.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle( ipcMain.handle(
CONTEXT_MENU_CHANNEL, CONTEXT_MENU_CHANNEL,
@@ -1028,23 +1169,13 @@ function registerIpcHandlers(): void {
ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL); ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => { ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
if (typeof rawUrl !== "string" || rawUrl.length === 0) { const externalUrl = getSafeExternalUrl(rawUrl);
return false; if (!externalUrl) {
}
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return false;
}
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
return false; return false;
} }
try { try {
await shell.openExternal(parsedUrl.toString()); await shell.openExternal(externalUrl);
return true; return true;
} catch { } catch {
return false; return false;
@@ -1109,7 +1240,42 @@ function createWindow(): BrowserWindow {
}, },
}); });
window.webContents.setWindowOpenHandler(() => ({ action: "deny" })); window.webContents.on("context-menu", (event, params) => {
event.preventDefault();
const menuTemplate: MenuItemConstructorOptions[] = [];
if (params.misspelledWord) {
for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
menuTemplate.push({
label: suggestion,
click: () => window.webContents.replaceMisspelling(suggestion),
});
}
if (params.dictionarySuggestions.length === 0) {
menuTemplate.push({ label: "No suggestions", enabled: false });
}
menuTemplate.push({ type: "separator" });
}
menuTemplate.push(
{ role: "cut", enabled: params.editFlags.canCut },
{ role: "copy", enabled: params.editFlags.canCopy },
{ role: "paste", enabled: params.editFlags.canPaste },
{ role: "selectAll", enabled: params.editFlags.canSelectAll },
);
Menu.buildFromTemplate(menuTemplate).popup({ window });
});
window.webContents.setWindowOpenHandler(({ url }) => {
const externalUrl = getSafeExternalUrl(url);
if (externalUrl) {
void shell.openExternal(externalUrl);
}
return { action: "deny" };
});
window.on("page-title-updated", (event) => { window.on("page-title-updated", (event) => {
event.preventDefault(); event.preventDefault();
window.setTitle(APP_DISPLAY_NAME); window.setTitle(APP_DISPLAY_NAME);
@@ -1138,6 +1304,11 @@ function createWindow(): BrowserWindow {
return window; return window;
} }
// Override Electron's userData path before the `ready` event so that
// Chromium session data uses a filesystem-friendly directory name.
// Must be called synchronously at the top level — before `app.whenReady()`.
app.setPath("userData", resolveUserDataPath());
configureAppIdentity(); configureAppIdentity();
async function bootstrap(): Promise<void> { async function bootstrap(): Promise<void> {
+2
View File
@@ -3,6 +3,7 @@ import type { DesktopBridge } from "@t3tools/contracts";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder"; const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm"; const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu"; const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external"; const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action"; const MENU_ACTION_CHANNEL = "desktop:menu-action";
@@ -16,6 +17,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl, getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL), pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message), 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), showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url), openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => { onMenuAction: (listener) => {
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
describe("resolveDesktopRuntimeInfo", () => {
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "darwin",
processArch: "x64",
runningUnderArm64Translation: true,
});
expect(runtimeInfo).toEqual({
hostArch: "arm64",
appArch: "x64",
runningUnderArm64Translation: true,
});
expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(true);
});
it("detects native Apple Silicon builds", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "darwin",
processArch: "arm64",
runningUnderArm64Translation: false,
});
expect(runtimeInfo).toEqual({
hostArch: "arm64",
appArch: "arm64",
runningUnderArm64Translation: false,
});
expect(isArm64HostRunningIntelBuild(runtimeInfo)).toBe(false);
});
it("passes through non-mac builds without translation", () => {
const runtimeInfo = resolveDesktopRuntimeInfo({
platform: "linux",
processArch: "x64",
runningUnderArm64Translation: true,
});
expect(runtimeInfo).toEqual({
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
});
});
});
+39
View File
@@ -0,0 +1,39 @@
import type { DesktopRuntimeArch, DesktopRuntimeInfo } from "@t3tools/contracts";
interface ResolveDesktopRuntimeInfoInput {
readonly platform: NodeJS.Platform;
readonly processArch: string;
readonly runningUnderArm64Translation: boolean;
}
function normalizeDesktopArch(arch: string): DesktopRuntimeArch {
if (arch === "arm64") return "arm64";
if (arch === "x64") return "x64";
return "other";
}
export function resolveDesktopRuntimeInfo(
input: ResolveDesktopRuntimeInfoInput,
): DesktopRuntimeInfo {
const appArch = normalizeDesktopArch(input.processArch);
if (input.platform !== "darwin") {
return {
hostArch: appArch,
appArch,
runningUnderArm64Translation: false,
};
}
const hostArch = appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
return {
hostArch,
appArch,
runningUnderArm64Translation: input.runningUnderArm64Translation,
};
}
export function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
}
+16 -7
View File
@@ -13,11 +13,17 @@ import {
reduceDesktopUpdateStateOnUpdateAvailable, reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine"; } from "./updateMachine";
const runtimeInfo = {
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
} as const;
describe("updateMachine", () => { describe("updateMachine", () => {
it("clears transient errors when a check starts", () => { it("clears transient errors when a check starts", () => {
const state = reduceDesktopUpdateStateOnCheckStart( const state = reduceDesktopUpdateStateOnCheckStart(
{ {
...createInitialDesktopUpdateState("1.0.0"), ...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true, enabled: true,
status: "error", status: "error",
message: "network", message: "network",
@@ -36,7 +42,7 @@ describe("updateMachine", () => {
it("records a check failure without exposing an action", () => { it("records a check failure without exposing an action", () => {
const state = reduceDesktopUpdateStateOnCheckFailure( const state = reduceDesktopUpdateStateOnCheckFailure(
{ {
...createInitialDesktopUpdateState("1.0.0"), ...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true, enabled: true,
status: "checking", status: "checking",
}, },
@@ -52,7 +58,7 @@ describe("updateMachine", () => {
it("preserves available version on download failure for retry", () => { it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure( const state = reduceDesktopUpdateStateOnDownloadFailure(
{ {
...createInitialDesktopUpdateState("1.0.0"), ...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true, enabled: true,
status: "downloading", status: "downloading",
availableVersion: "1.1.0", availableVersion: "1.1.0",
@@ -70,14 +76,17 @@ describe("updateMachine", () => {
it("transitions to downloaded and then preserves install retry state", () => { it("transitions to downloaded and then preserves install retry state", () => {
const downloaded = reduceDesktopUpdateStateOnDownloadComplete( const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
{ {
...createInitialDesktopUpdateState("1.0.0"), ...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true, enabled: true,
status: "downloading", status: "downloading",
availableVersion: "1.1.0", availableVersion: "1.1.0",
}, },
"1.1.0", "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.status).toBe("downloaded");
expect(downloaded.downloadedVersion).toBe("1.1.0"); expect(downloaded.downloadedVersion).toBe("1.1.0");
@@ -89,7 +98,7 @@ describe("updateMachine", () => {
it("clears stale download state when no update is available", () => { it("clears stale download state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate( const state = reduceDesktopUpdateStateOnNoUpdate(
{ {
...createInitialDesktopUpdateState("1.0.0"), ...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true, enabled: true,
status: "error", status: "error",
availableVersion: "1.1.0", availableVersion: "1.1.0",
@@ -111,7 +120,7 @@ describe("updateMachine", () => {
it("tracks available, download start, and progress cleanly", () => { it("tracks available, download start, and progress cleanly", () => {
const available = reduceDesktopUpdateStateOnUpdateAvailable( const available = reduceDesktopUpdateStateOnUpdateAvailable(
{ {
...createInitialDesktopUpdateState("1.0.0"), ...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true, enabled: true,
status: "checking", status: "checking",
}, },
+8 -3
View File
@@ -1,12 +1,18 @@
import type { DesktopUpdateState } from "@t3tools/contracts"; import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState"; import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
export function createInitialDesktopUpdateState(currentVersion: string): DesktopUpdateState { export function createInitialDesktopUpdateState(
currentVersion: string,
runtimeInfo: DesktopRuntimeInfo,
): DesktopUpdateState {
return { return {
enabled: false, enabled: false,
status: "disabled", status: "disabled",
currentVersion, currentVersion,
hostArch: runtimeInfo.hostArch,
appArch: runtimeInfo.appArch,
runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
availableVersion: null, availableVersion: null,
downloadedVersion: null, downloadedVersion: null,
downloadPercent: null, downloadPercent: null,
@@ -152,4 +158,3 @@ export function reduceDesktopUpdateStateOnInstallFailure(
canRetry: true, canRetry: true,
}; };
} }
+3
View File
@@ -12,6 +12,9 @@ const baseState: DesktopUpdateState = {
enabled: true, enabled: true,
status: "idle", status: "idle",
currentVersion: "1.0.0", currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
availableVersion: null, availableVersion: null,
downloadedVersion: null, downloadedVersion: null,
downloadPercent: null, downloadPercent: null,
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from "astro/config";
export default defineConfig({
server: {
port: Number(process.env.PORT ?? 4173),
},
});
+19
View File
@@ -0,0 +1,19 @@
{
"name": "@t3tools/marketing",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"typecheck": "astro check"
},
"dependencies": {
"astro": "^6.0.4"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
"typescript": "catalog:"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 414 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 662 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 652 KiB

+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>
+237
View File
@@ -0,0 +1,237 @@
---
import Layout from "../layouts/Layout.astro";
---
<Layout>
<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 href="/download" class="other-platforms">Other platforms</a>
<div class="screenshot-wrap">
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
</div>
</Layout>
<script>
import { fetchLatestRelease, RELEASES_URL, type ReleaseAsset } from "../lib/releases";
type Platform = { os: "mac" | "win" | "linux"; label: string; arch?: string };
function detectPlatform(): Platform | null {
const ua = navigator.userAgent;
if (/Win/i.test(ua)) return { os: "win", label: "Download for Windows" };
if (/Mac/i.test(ua)) {
return {
os: "mac",
label: `Download for macOS`,
arch: "arm64",
};
}
if (/Linux/i.test(ua)) return { os: "linux", label: "Download for Linux" };
return null;
}
function pickAsset(assets: ReleaseAsset[], platform: Platform): string | null {
if (platform.os === "win") {
return (
assets.find((a) => a.name.endsWith("-x64.exe"))
?.browser_download_url ?? null
);
}
if (platform.os === "mac") {
const preferred = assets.find((a) =>
a.name.endsWith(`-${platform.arch}.dmg`),
);
const fallback = assets.find((a) => a.name.endsWith(".dmg"));
return (preferred ?? fallback)?.browser_download_url ?? null;
}
if (platform.os === "linux") {
return (
assets.find((a) => a.name.endsWith(".AppImage"))
?.browser_download_url ?? null
);
}
return null;
}
async function init() {
const btn = document.getElementById("download-btn") as HTMLAnchorElement | null;
const label = document.getElementById("download-label");
if (!btn || !label) return;
const platform = detectPlatform();
if (!platform) return;
document.documentElement.dataset.platform = platform.os;
label.textContent = platform.label;
try {
const release = await fetchLatestRelease();
const url = pickAsset(release.assets ?? [], platform);
if (url) {
btn.href = url;
btn.removeAttribute("target");
btn.removeAttribute("rel");
}
} catch {
btn.href = RELEASES_URL;
}
}
init();
</script>
<style>
.main {
padding-top: 10vh;
}
/* ── Tagline ── */
.tagline {
font-weight: 500;
font-size: clamp(2rem, 5vw, 3.5rem);
letter-spacing: -0.035em;
line-height: 1.15;
text-align: center;
margin: 0 0 6vh;
opacity: 0;
animation: fade-in 1s ease-out forwards;
}
/* ── Hero button ── */
.hero-button {
display: inline-flex;
align-items: center;
gap: 0.55rem;
background: #fafafa;
color: #09090b;
padding: 0.75rem 2rem;
border-radius: 999px;
font-weight: 600;
font-size: 0.9rem;
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;
}
.hero-button:hover {
transform: scale(1.03);
box-shadow: 0 0 24px rgba(255, 255, 255, 0.08);
}
.hero-button:active {
transform: scale(0.98);
}
.hero-button-icon {
display: none;
width: 1em;
height: 1em;
flex-shrink: 0;
}
:global([data-platform="mac"]) .hero-button-icon--apple {
display: block;
}
:global([data-platform="win"]) .hero-button-icon--windows {
display: block;
}
:global([data-platform="linux"]) .hero-button-icon--linux {
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 {
margin: 0 auto;
width: min(95vw, 1400px);
opacity: 0;
transform: scale(0.98);
animation: screenshot-in 1s ease-out 0.15s forwards;
}
.screenshot {
width: 100%;
display: block;
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.06);
mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
-webkit-mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
}
.screenshot-wrap::after {
content: "";
display: block;
width: 100%;
height: 120px;
background: inherit;
margin-top: -1px;
opacity: 0.04;
transform: scaleY(-1);
mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
-webkit-mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
pointer-events: none;
}
@keyframes screenshot-in {
from {
opacity: 0;
transform: scale(0.98);
}
to {
opacity: 1;
transform: scale(1);
}
}
/* ── Mobile ── */
@media (max-width: 640px) {
.main {
padding-top: 7vh;
}
.tagline {
margin-bottom: 4vh;
}
.screenshot-wrap {
width: 95vw;
}
}
</style>
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "astro/tsconfigs/strict"
}
@@ -15,6 +15,7 @@ import {
Layer, Layer,
ManagedRuntime, ManagedRuntime,
Option, Option,
Ref,
Schedule, Schedule,
Schema, Schema,
Scope, Scope,
@@ -40,10 +41,12 @@ import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts"; import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts"; import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
import { ProviderService } from "../src/provider/Services/ProviderService.ts"; import { ProviderService } from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts"; import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts"; import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts"; import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts"; import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts"; import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts"; import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts"; import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
@@ -53,6 +56,10 @@ import {
} from "../src/orchestration/Services/OrchestrationEngine.ts"; } from "../src/orchestration/Services/OrchestrationEngine.ts";
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts"; import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts"; import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
import {
RuntimeReceiptBus,
type OrchestrationRuntimeReceipt,
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import { import {
makeTestProviderAdapterHarness, makeTestProviderAdapterHarness,
@@ -113,7 +120,7 @@ function waitFor<A, E>(
read: Effect.Effect<A, E>, read: Effect.Effect<A, E>,
predicate: (value: A) => boolean, predicate: (value: A) => boolean,
description: string, description: string,
timeoutMs = 3000, timeoutMs = 10_000,
): Effect.Effect<A, never> { ): Effect.Effect<A, never> {
const RETRY_SIGNAL = "wait_for_retry"; const RETRY_SIGNAL = "wait_for_retry";
const retryIntervalMs = 10; const retryIntervalMs = 10;
@@ -152,7 +159,7 @@ export interface OrchestrationIntegrationHarness {
readonly rootDir: string; readonly rootDir: string;
readonly workspaceDir: string; readonly workspaceDir: string;
readonly dbPath: string; readonly dbPath: string;
readonly adapterHarness: TestProviderAdapterHarness; readonly adapterHarness: TestProviderAdapterHarness | null;
readonly engine: OrchestrationEngineShape; readonly engine: OrchestrationEngineShape;
readonly snapshotQuery: ProjectionSnapshotQuery["Service"]; readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
readonly providerService: ProviderService["Service"]; readonly providerService: ProviderService["Service"];
@@ -184,11 +191,21 @@ export interface OrchestrationIntegrationHarness {
}, },
never never
>; >;
readonly waitForReceipt: {
(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeoutMs?: number,
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeoutMs?: number,
): Effect.Effect<Receipt, never>;
};
readonly dispose: Effect.Effect<void, never>; readonly dispose: Effect.Effect<void, never>;
} }
interface MakeOrchestrationIntegrationHarnessOptions { interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: "codex" | "claudeCode"; readonly provider?: "codex";
readonly realCodex?: boolean; readonly realCodex?: boolean;
} }
@@ -252,10 +269,12 @@ export const makeOrchestrationIntegrationHarness = (
? makeProviderServiceLive().pipe( ? makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer), Layer.provide(providerSessionDirectoryLayer),
Layer.provide(realCodexRegistry), Layer.provide(realCodexRegistry),
Layer.provide(AnalyticsService.layerTest),
) )
: makeProviderServiceLive().pipe( : makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer), Layer.provide(providerSessionDirectoryLayer),
Layer.provide(fakeRegistry!), Layer.provide(fakeRegistry!),
Layer.provide(AnalyticsService.layerTest),
); );
const runtimeServicesLayer = Layer.mergeAll( const runtimeServicesLayer = Layer.mergeAll(
@@ -265,6 +284,7 @@ export const makeOrchestrationIntegrationHarness = (
ProjectionPendingApprovalRepositoryLive, ProjectionPendingApprovalRepositoryLive,
CheckpointStoreLive, CheckpointStoreLive,
providerLayer, providerLayer,
RuntimeReceiptBusLive,
); );
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe( const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer), Layer.provideMerge(runtimeServicesLayer),
@@ -319,11 +339,18 @@ export const makeOrchestrationIntegrationHarness = (
"load ProjectionPendingApprovalRepository service", "load ProjectionPendingApprovalRepository service",
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)), () => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
).pipe(Effect.orDie); ).pipe(Effect.orDie);
const runtimeReceiptBus = yield* tryRuntimePromise("load RuntimeReceiptBus service", () =>
runtime.runPromise(Effect.service(RuntimeReceiptBus)),
).pipe(Effect.orDie);
const scope = yield* Scope.make("sequential"); const scope = yield* Scope.make("sequential");
yield* tryRuntimePromise("start OrchestrationReactor", () => yield* tryRuntimePromise("start OrchestrationReactor", () =>
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))), runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
).pipe(Effect.orDie); ).pipe(Effect.orDie);
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* sleep(10); yield* sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = ( const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
@@ -395,6 +422,30 @@ export const makeOrchestrationIntegrationHarness = (
never never
>; >;
function waitForReceipt(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeoutMs?: number,
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
function waitForReceipt<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeoutMs?: number,
): Effect.Effect<Receipt, never>;
function waitForReceipt(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeoutMs?: number,
) {
const readMatchingReceipt = Ref.get(receiptHistory).pipe(
Effect.map((history) => history.find(predicate)),
);
return waitFor(
readMatchingReceipt,
(receipt): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
"runtime receipt",
timeoutMs,
);
}
let disposed = false; let disposed = false;
const dispose = Effect.gen(function* () { const dispose = Effect.gen(function* () {
if (disposed) { if (disposed) {
@@ -403,19 +454,14 @@ export const makeOrchestrationIntegrationHarness = (
disposed = true; disposed = true;
const shutdown = Effect.gen(function* () { const shutdown = Effect.gen(function* () {
const stopAllExit = yield* Effect.exit(
Effect.promise(() => runtime.runPromise(providerService.stopAll())),
);
const closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void)); const closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void));
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose())); const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
const failureCause = Exit.isFailure(stopAllExit) const failureCause = Exit.isFailure(closeScopeExit)
? stopAllExit.cause ? closeScopeExit.cause
: Exit.isFailure(closeScopeExit) : Exit.isFailure(disposeRuntimeExit)
? closeScopeExit.cause ? disposeRuntimeExit.cause
: Exit.isFailure(disposeRuntimeExit) : null;
? disposeRuntimeExit.cause
: null;
if (failureCause) { if (failureCause) {
return yield* Effect.failCause(failureCause); return yield* Effect.failCause(failureCause);
@@ -435,7 +481,7 @@ export const makeOrchestrationIntegrationHarness = (
rootDir, rootDir,
workspaceDir, workspaceDir,
dbPath, dbPath,
adapterHarness: adapterHarness as TestProviderAdapterHarness, adapterHarness,
engine, engine,
snapshotQuery, snapshotQuery,
providerService, providerService,
@@ -445,6 +491,7 @@ export const makeOrchestrationIntegrationHarness = (
waitForThread, waitForThread,
waitForDomainEvent, waitForDomainEvent,
waitForPendingApproval, waitForPendingApproval,
waitForReceipt,
dispose, dispose,
} satisfies OrchestrationIntegrationHarness; } satisfies OrchestrationIntegrationHarness;
}); });
@@ -35,7 +35,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = { export type FixtureProviderRuntimeEvent = {
readonly type: string; readonly type: string;
readonly eventId: EventId; readonly eventId: EventId;
readonly provider: "codex" | "claudeCode" | "cursor"; readonly provider: "codex";
readonly createdAt: string; readonly createdAt: string;
readonly threadId: string; readonly threadId: string;
readonly turnId?: string | undefined; readonly turnId?: string | undefined;
@@ -72,10 +72,9 @@ function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupt
return "completed"; return "completed";
} }
function mapRequestType(requestKind: unknown): function mapRequestType(
| "command_execution_approval" requestKind: unknown,
| "file_change_approval" ): "command_execution_approval" | "file_change_approval" | "unknown" {
| "unknown" {
if (requestKind === "command") { if (requestKind === "command") {
return "command_execution_approval"; return "command_execution_approval";
} }
@@ -178,7 +177,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness { export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>; readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: "codex" | "claudeCode"; readonly provider: "codex";
readonly queueTurnResponse: ( readonly queueTurnResponse: (
threadId: ThreadId, threadId: ThreadId,
response: TestTurnResponse, response: TestTurnResponse,
@@ -198,7 +197,7 @@ export interface TestProviderAdapterHarness {
} }
interface MakeTestProviderAdapterHarnessOptions { interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: "codex" | "claudeCode"; readonly provider?: "codex";
} }
function nowIso(): string { function nowIso(): string {
@@ -206,7 +205,7 @@ function nowIso(): string {
} }
function sessionNotFound( function sessionNotFound(
provider: "codex" | "claudeCode", provider: "codex",
threadId: ThreadId, threadId: ThreadId,
): ProviderAdapterSessionNotFoundError { ): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({ return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +215,7 @@ function sessionNotFound(
} }
function missingSessionEffect( function missingSessionEffect(
provider: "codex" | "claudeCode", provider: "codex",
threadId: ThreadId, threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> { ): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId)); return Effect.fail(sessionNotFound(provider, threadId));
@@ -239,323 +238,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) => const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () { Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== provider) { if (input.provider !== undefined && input.provider !== provider) {
return yield* new ProviderAdapterValidationError({ 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, provider,
operation: "startSession", status: "ready",
issue: `Expected provider '${provider}' but received '${input.provider}'.`, runtimeMode: input.runtimeMode,
});
}
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: {
threadId, threadId,
turns: [], cwd: input.cwd,
}, resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
turnCount: 0, createdAt,
queuedResponses: queuedResponsesForNextSession.splice(0), updatedAt: createdAt,
rollbackCalls: [], };
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) => state.turnCount += 1;
Effect.gen(function* () { const turnCount = state.turnCount;
const state = sessions.get(input.threadId); const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
if (!state) {
return yield* missingSessionEffect(provider, input.threadId);
}
state.turnCount += 1; const response = state.queuedResponses.shift();
const turnCount = state.turnCount; if (!response) {
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`); return yield* new ProviderAdapterValidationError({
provider,
operation: "sendTurn",
issue: `No queued turn response for thread ${input.threadId}.`,
});
}
const response = state.queuedResponses.shift(); const assistantDeltas: string[] = [];
if (!response) { const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
return yield* new ProviderAdapterValidationError({ for (const fixtureEvent of response.events) {
provider, const rawEvent: Record<string, unknown> = {
operation: "sendTurn", ...(fixtureEvent as Record<string, unknown>),
issue: `No queued turn response for thread ${input.threadId}.`, 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 runtimeEvent = normalizeFixtureEvent(rawEvent);
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = []; const runtimeType = (runtimeEvent as { type: string }).type;
for (const fixtureEvent of response.events) { if (runtimeType === "content.delta") {
const rawEvent: Record<string, unknown> = { const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
...(fixtureEvent as Record<string, unknown>), if (typeof payload?.delta === "string") {
eventId: randomUUID(), assistantDeltas.push(payload.delta);
provider, }
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)), } else if (runtimeType === "message.delta") {
createdAt: nowIso(), 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); state.snapshot = {
const runtimeType = (runtimeEvent as { type: string }).type; threadId: state.snapshot.threadId,
if (runtimeType === "content.delta") { turns: [...state.snapshot.turns, nextTurn],
const payload = runtimeEvent.payload as { delta?: unknown } | undefined; };
if (typeof payload?.delta === "string") {
assistantDeltas.push(payload.delta); if (deferredTurnCompletedEvents.length === 0) {
} yield* emit({
} else if (runtimeType === "message.delta") { type: "turn.completed",
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta; eventId: EventId.makeUnsafe(randomUUID()),
if (typeof legacyDelta === "string") { provider,
assistantDeltas.push(legacyDelta); 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); return {
}
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(),
threadId: state.snapshot.threadId, threadId: state.snapshot.threadId,
turnId, turnId,
payload: { } satisfies ProviderTurnStartResult;
state: "completed", });
},
}); const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
} else { threadId,
for (const completedEvent of deferredTurnCompletedEvents) { turnId,
yield* emit(completedEvent); ) =>
} 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 { return Effect.sync(() => {
threadId: state.snapshot.threadId, state.rollbackCalls.push(numTurns);
turnId, state.snapshot = {
} satisfies ProviderTurnStartResult; 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"] = ( const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
threadId, Effect.sync(() => {
turnId, sessions.clear();
) => });
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"] = ( const adapter: ProviderAdapterShape<ProviderAdapterError> = {
threadId, provider,
requestId, capabilities: {
decision, sessionModelSwitch: "in-session",
) => },
sessions.has(threadId) startSession,
? Effect.sync(() => { sendTurn,
const existing = approvalResponsesBySession.get(threadId) ?? []; interruptTurn,
existing.push({ respondToRequest,
threadId, respondToUserInput,
requestId, stopSession,
decision, listSessions,
}); hasSession,
approvalResponsesBySession.set(threadId, existing); readThread,
}) rollbackThread,
: missingSessionEffect(provider, threadId); stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = ( const queueTurnResponse = (
threadId, threadId: ThreadId,
_requestId, response: TestTurnResponse,
_answers, ): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId)); Effect.sync(() => sessions.get(threadId)).pipe(
Effect.flatMap((state) =>
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) => state
Effect.sync(() => { ? Effect.sync(() => {
sessions.delete(threadId); state.queuedResponses.push(response);
}); })
: Effect.fail(sessionNotFound(provider, 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 Effect.sync(() => { const queueTurnResponseForNextSession = (
state.rollbackCalls.push(numTurns); response: TestTurnResponse,
state.snapshot = { ): Effect.Effect<void, never> =>
threadId: state.snapshot.threadId, Effect.sync(() => {
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns), queuedResponsesForNextSession.push(response);
}; });
state.turnCount = state.snapshot.turns.length;
return state.snapshot;
});
};
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () => const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
Effect.sync(() => { const state = sessions.get(threadId);
sessions.clear(); if (!state) {
}); return [];
}
return [...state.rollbackCalls];
};
const adapter: ProviderAdapterShape<ProviderAdapterError> = { const getStartCount = (): number => sessionCount;
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const queueTurnResponse = ( const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
threadId: ThreadId, const calls = interruptCallsBySession.get(threadId);
response: TestTurnResponse, if (!calls) {
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> => return [];
Effect.sync(() => sessions.get(threadId)).pipe( }
Effect.flatMap((state) => return [...calls];
state };
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(provider, threadId)),
),
);
const queueTurnResponseForNextSession = ( const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
response: TestTurnResponse, Array.from(sessions.values(), (state) => state.session.threadId);
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => { const getApprovalResponses = (
const state = sessions.get(threadId); threadId: ThreadId,
if (!state) { ): ReadonlyArray<{
return []; readonly threadId: ThreadId;
} readonly requestId: ApprovalRequestId;
return [...state.rollbackCalls]; readonly decision: ProviderApprovalDecision;
}; }> => {
const responses = approvalResponsesBySession.get(threadId);
if (!responses) {
return [];
}
return [...responses];
};
const getStartCount = (): number => sessionCount; return {
adapter,
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => { provider,
const calls = interruptCallsBySession.get(threadId); queueTurnResponse,
if (!calls) { queueTurnResponseForNextSession,
return []; getStartCount,
} getRollbackCalls,
return [...calls]; getInterruptCalls,
}; listActiveSessionIds,
getApprovalResponses,
const listActiveSessionIds = (): ReadonlyArray<ThreadId> => } satisfies TestProviderAdapterHarness;
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;
});
@@ -73,7 +73,7 @@ export const codexTurnToolFixture = [
turnId: TURN_ID, turnId: TURN_ID,
payload: { payload: {
itemType: "command_execution", itemType: "command_execution",
title: "Command run", title: "Ran command",
detail: "echo integration", detail: "echo integration",
}, },
}, },
@@ -85,7 +85,7 @@ export const codexTurnToolFixture = [
payload: { payload: {
itemType: "command_execution", itemType: "command_execution",
status: "completed", status: "completed",
title: "Command run", title: "Ran command",
detail: "echo integration", detail: "echo integration",
}, },
}, },
@@ -21,6 +21,10 @@ import {
type OrchestrationIntegrationHarness, type OrchestrationIntegrationHarness,
} from "./OrchestrationEngineHarness.integration.ts"; } from "./OrchestrationEngineHarness.integration.ts";
import { checkpointRefForThreadTurn } from "../src/checkpointing/Utils.ts"; import { checkpointRefForThreadTurn } from "../src/checkpointing/Utils.ts";
import type {
CheckpointDiffFinalizedReceipt,
TurnProcessingQuiescedReceipt,
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
@@ -32,7 +36,7 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1"); const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_TURN_ID = "fixture-turn"; const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1"); const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = "codex" | "claudeCode"; type IntegrationProvider = "codex";
function nowIso() { function nowIso() {
return new Date().toISOString(); return new Date().toISOString();
@@ -180,13 +184,29 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
], ],
}; };
yield* harness.adapterHarness.queueTurnResponseForNextSession(turnResponse); yield* harness.adapterHarness!.queueTurnResponseForNextSession(turnResponse);
yield* startTurn({ yield* startTurn({
harness, harness,
commandId: "cmd-turn-start-single", commandId: "cmd-turn-start-single",
messageId: "msg-user-single", messageId: "msg-user-single",
text: "Say hello", text: "Say hello",
}); });
const finalizedReceipt = yield* harness.waitForReceipt(
(receipt): receipt is CheckpointDiffFinalizedReceipt =>
receipt.type === "checkpoint.diff.finalized" &&
receipt.threadId === THREAD_ID &&
receipt.checkpointTurnCount === 1,
);
if (finalizedReceipt.type !== "checkpoint.diff.finalized") {
throw new Error("Expected checkpoint.diff.finalized receipt.");
}
assert.equal(finalizedReceipt.status, "ready");
yield* harness.waitForReceipt(
(receipt): receipt is TurnProcessingQuiescedReceipt =>
receipt.type === "turn.processing.quiesced" &&
receipt.threadId === THREAD_ID &&
receipt.checkpointTurnCount === 1,
);
const thread = yield* harness.waitForThread( const thread = yield* harness.waitForThread(
THREAD_ID, THREAD_ID,
@@ -208,8 +228,6 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
assert.equal(checkpointRows[0]?.status, "ready"); assert.equal(checkpointRows[0]?.status, "ready");
assert.deepEqual(checkpointRows[0]?.files, []); assert.deepEqual(checkpointRows[0]?.files, []);
yield* harness.waitForDomainEvent((event) => event.type === "thread.turn-diff-completed");
const ref0 = checkpointRefForThreadTurn(THREAD_ID, 0); const ref0 = checkpointRefForThreadTurn(THREAD_ID, 0);
const ref1 = checkpointRefForThreadTurn(THREAD_ID, 1); const ref1 = checkpointRefForThreadTurn(THREAD_ID, 1);
assert.equal(gitRefExists(harness.workspaceDir, ref0), true); assert.equal(gitRefExists(harness.workspaceDir, ref0), true);
@@ -314,7 +332,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
Effect.gen(function* () { Effect.gen(function* () {
yield* seedProjectAndThread(harness); yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({ yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [ events: [
{ {
type: "turn.started", type: "turn.started",
@@ -367,13 +385,19 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
messageId: "msg-user-multi-1", messageId: "msg-user-multi-1",
text: "Make first edit", text: "Make first edit",
}); });
yield* harness.waitForReceipt(
(receipt): receipt is CheckpointDiffFinalizedReceipt =>
receipt.type === "checkpoint.diff.finalized" &&
receipt.threadId === THREAD_ID &&
receipt.checkpointTurnCount === 1,
);
yield* harness.waitForThread( yield* harness.waitForThread(
THREAD_ID, THREAD_ID,
(entry) => entry.checkpoints.length === 1 && entry.session?.threadId === "thread-1", (entry) => entry.checkpoints.length === 1 && entry.session?.threadId === "thread-1",
); );
yield* harness.adapterHarness.queueTurnResponse(THREAD_ID, { yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [ events: [
{ {
type: "turn.started", type: "turn.started",
@@ -408,6 +432,22 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
messageId: "msg-user-multi-2", messageId: "msg-user-multi-2",
text: "Make second edit", text: "Make second edit",
}); });
const secondReceipt = yield* harness.waitForReceipt(
(receipt): receipt is CheckpointDiffFinalizedReceipt =>
receipt.type === "checkpoint.diff.finalized" &&
receipt.threadId === THREAD_ID &&
receipt.checkpointTurnCount === 2,
);
if (secondReceipt.type !== "checkpoint.diff.finalized") {
throw new Error("Expected checkpoint.diff.finalized receipt.");
}
assert.equal(secondReceipt.status, "ready");
yield* harness.waitForReceipt(
(receipt): receipt is TurnProcessingQuiescedReceipt =>
receipt.type === "turn.processing.quiesced" &&
receipt.threadId === THREAD_ID &&
receipt.checkpointTurnCount === 2,
);
const secondTurnThread = yield* harness.waitForThread( const secondTurnThread = yield* harness.waitForThread(
THREAD_ID, THREAD_ID,
@@ -473,7 +513,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
Effect.gen(function* () { Effect.gen(function* () {
yield* seedProjectAndThread(harness); yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({ yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [ events: [
{ {
type: "turn.started", type: "turn.started",
@@ -538,7 +578,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
assert.equal(resolvedRow.decision, "accept"); assert.equal(resolvedRow.decision, "accept");
const approvalResponses = yield* waitForSync( const approvalResponses = yield* waitForSync(
() => harness.adapterHarness.getApprovalResponses(THREAD_ID), () => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
(responses) => responses.length === 1, (responses) => responses.length === 1,
"provider approval response", "provider approval response",
); );
@@ -554,7 +594,7 @@ it.live("records failed turn runtime state and checkpoint status as error", () =
Effect.gen(function* () { Effect.gen(function* () {
yield* seedProjectAndThread(harness); yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({ yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [ events: [
{ {
type: "turn.started", type: "turn.started",
@@ -633,7 +673,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
Effect.gen(function* () { Effect.gen(function* () {
yield* seedProjectAndThread(harness); yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({ yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [ events: [
{ {
type: "turn.started", type: "turn.started",
@@ -691,7 +731,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
(entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1, (entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1,
); );
yield* harness.adapterHarness.queueTurnResponse(THREAD_ID, { yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [ events: [
{ {
type: "turn.started", type: "turn.started",
@@ -796,7 +836,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)), gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false, false,
); );
assert.deepEqual(harness.adapterHarness.getRollbackCalls(THREAD_ID), [1]); assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({ const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
threadId: THREAD_ID, threadId: THREAD_ID,
@@ -842,416 +882,3 @@ it.live(
}), }),
), ),
); );
it.live("starts a claudeCode 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", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeCode"),
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", "claudeCode"),
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: "claudeCode",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeCode" &&
entry.session.status === "ready" &&
entry.messages.some(
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
),
);
assert.equal(thread.session?.providerName, "claudeCode");
}),
"claudeCode",
),
);
it.live("recovers claudeCode 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", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeCode"),
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", "claudeCode"),
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: "claudeCode",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.providerService.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", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeCode"),
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", "claudeCode"),
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 === "claudeCode" &&
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, "claudeCode");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeCode",
),
);
it.live("forwards claudeCode 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", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeCode"),
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", "claudeCode"),
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: "claudeCode",
});
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");
}),
"claudeCode",
),
);
it.live("forwards thread.turn.interrupt to claudeCode 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", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeCode"),
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", "claudeCode"),
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: "claudeCode",
});
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);
}),
"claudeCode",
),
);
it.live("reverts claudeCode 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", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeCode"),
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", "claudeCode"),
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: "claudeCode",
});
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", "claudeCode"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeCode"),
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", "claudeCode"),
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 === "claudeCode",
);
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]);
}),
"claudeCode",
),
);
@@ -12,6 +12,7 @@ import {
ProviderService, ProviderService,
type ProviderServiceShape, type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts"; } from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts"; import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts"; import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
@@ -59,6 +60,7 @@ const makeIntegrationFixture = Effect.gen(function* () {
const shared = Layer.mergeAll( const shared = Layer.mergeAll(
directoryLayer, directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry), Layer.succeed(ProviderAdapterRegistry, registry),
AnalyticsService.layerTest,
).pipe(Layer.provide(SqlitePersistenceMemory)); ).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared)); const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "t3", "name": "t3",
"version": "0.0.0-alpha.20", "version": "0.0.10",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/pingdotgg/t3code", "url": "https://github.com/pingdotgg/t3code",
+100 -6
View File
@@ -6,6 +6,10 @@ import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
import { Command, Flag } from "effect/unstable/cli"; import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
DEVELOPMENT_ICON_OVERRIDES,
PUBLISH_ICON_OVERRIDES,
} from "../../../scripts/lib/brand-assets.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts"; import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import rootPackageJson from "../../../package.json" with { type: "json" }; import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" }; import serverPackageJson from "../package.json" with { type: "json" };
@@ -31,6 +35,84 @@ const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Comm
} }
}); });
interface PublishIconBackup {
readonly targetPath: string;
readonly backupPath: string;
}
const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
repoRoot: string,
serverDir: string,
) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const backups: PublishIconBackup[] = [];
for (const override of PUBLISH_ICON_OVERRIDES) {
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
const targetPath = path.join(serverDir, override.targetRelativePath);
const backupPath = `${targetPath}.publish-bak`;
if (!(yield* fs.exists(sourcePath))) {
return yield* new CliError({
message: `Missing publish icon source: ${sourcePath}`,
});
}
if (!(yield* fs.exists(targetPath))) {
return yield* new CliError({
message: `Missing publish icon target: ${targetPath}. Run the build subcommand first.`,
});
}
yield* fs.copyFile(targetPath, backupPath);
yield* fs.copyFile(sourcePath, targetPath);
backups.push({ targetPath, backupPath });
}
yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
return backups as ReadonlyArray<PublishIconBackup>;
});
const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
backups: ReadonlyArray<PublishIconBackup>,
) {
const fs = yield* FileSystem.FileSystem;
for (const backup of backups) {
if (!(yield* fs.exists(backup.backupPath))) {
continue;
}
yield* fs.rename(backup.backupPath, backup.targetPath);
}
});
const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
repoRoot: string,
serverDir: string,
) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
for (const override of DEVELOPMENT_ICON_OVERRIDES) {
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
const targetPath = path.join(serverDir, override.targetRelativePath);
if (!(yield* fs.exists(sourcePath))) {
return yield* new CliError({
message: `Missing development icon source: ${sourcePath}`,
});
}
if (!(yield* fs.exists(targetPath))) {
return yield* new CliError({
message: `Missing development icon target: ${targetPath}. Build web first.`,
});
}
yield* fs.copyFile(sourcePath, targetPath);
}
yield* Effect.log("[cli] Applied development icon overrides to dist/client");
});
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// build subcommand // build subcommand
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -53,6 +135,8 @@ const buildCmd = Command.make(
cwd: serverDir, cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore", stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit", stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun tsdown`, })`bun tsdown`,
); );
@@ -61,6 +145,7 @@ const buildCmd = Command.make(
if (yield* fs.exists(webDist)) { if (yield* fs.exists(webDist)) {
yield* fs.copy(webDist, clientTarget); yield* fs.copy(webDist, clientTarget);
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
yield* Effect.log("[cli] Bundled web app into dist/client"); yield* Effect.log("[cli] Bundled web app into dist/client");
} else { } else {
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle."); yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
@@ -104,10 +189,8 @@ const publishCmd = Command.make(
yield* Effect.acquireUseRelease( yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts // Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
Effect.gen(function* () { Effect.gen(function* () {
const original = yield* fs.readFileString(packageJsonPath); // Resolve catalog dependencies before any file mutations. If this throws,
yield* fs.writeFileString(backupPath, original); // acquire fails and no release hook runs, so filesystem must still be untouched.
// Build package.json for publish
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version); const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg = { const pkg = {
name: serverPackageJson.name, name: serverPackageJson.name,
@@ -120,15 +203,19 @@ const publishCmd = Command.make(
dependencies: serverPackageJson.dependencies as Record<string, unknown>, dependencies: serverPackageJson.dependencies as Record<string, unknown>,
}; };
// Resolve catalog: entries in production dependencies
pkg.dependencies = resolveCatalogDependencies( pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies, pkg.dependencies,
rootPackageJson.workspaces.catalog, rootPackageJson.workspaces.catalog,
"apps/server dependencies", "apps/server dependencies",
); );
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`); yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* Effect.log("[cli] Resolved package.json for publish"); yield* Effect.log("[cli] Resolved package.json for publish");
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
}), }),
// Use: npm publish // Use: npm publish
() => () =>
@@ -143,12 +230,19 @@ const publishCmd = Command.make(
cwd: serverDir, cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore", stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit", stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
}), }),
); );
}), }),
// Release: restore // Release: restore
() => (resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
Effect.gen(function* () { Effect.gen(function* () {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
),
);
yield* fs.rename(backupPath, packageJsonPath); yield* fs.rename(backupPath, packageJsonPath);
if (config.verbose) yield* Effect.log("[cli] Restored original package.json"); if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
}), }),
-66
View File
@@ -1,66 +0,0 @@
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import path from "node:path";
import { Effect, FileSystem, Layer, Logger, ServiceMap } from "effect";
import { makeEventNdjsonLogger } from "../src/provider/Layers/EventNdjsonLogger.ts";
class LogDir extends ServiceMap.Service<LogDir, string>()("t3/scripts/logger-scope-repro/LogDir") {}
const main = Effect.gen(function* () {
const logdir = yield* LogDir;
const providerLogPath = path.join(logdir, "provider");
yield* Effect.logInfo(`providerLogPath=${providerLogPath}`);
const providerLogger = yield* makeEventNdjsonLogger(providerLogPath, {
stream: "native",
batchWindowMs: 10,
});
yield* Effect.logInfo("before provider write");
if (providerLogger) {
yield* providerLogger.write(
{
kind: "probe",
message: "provider-only event",
},
"thread-123" as never,
);
}
yield* Effect.logInfo("after provider write");
yield* Effect.sleep("50 millis");
if (providerLogger) {
yield* providerLogger.close();
}
yield* Effect.logInfo("after provider close");
const fs = yield* FileSystem.FileSystem;
const logContents = yield* fs
.readDirectory(logdir, { recursive: true })
.pipe(
Effect.flatMap((entries) =>
Effect.all(entries.map((entry) => fs.readFileString(path.join(logdir, entry)))),
),
);
yield* Effect.logInfo(`logContents=${logContents}`);
});
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const logdir = path.join(process.cwd(), "logtest");
yield* fs.makeDirectory(logdir);
const fileLogger = yield* Logger.formatSimple.pipe(
Logger.toFile(path.join(logdir, "global.log")),
);
const dualLogger = Logger.layer([fileLogger, Logger.consolePretty()]);
const mainLayer = Layer.mergeAll(dualLogger, Layer.succeed(LogDir, logdir));
yield* main.pipe(Effect.provide(mainLayer));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
+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_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80; const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*"; const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN = 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}";
"[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( const ATTACHMENT_ID_PATTERN = new RegExp(
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`, `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
"i", "i",
+331 -73
View File
@@ -7,11 +7,14 @@ import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
import { import {
buildCodexInitializeParams, buildCodexInitializeParams,
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
CodexAppServerManager, CodexAppServerManager,
classifyCodexStderrLine, classifyCodexStderrLine,
isRecoverableThreadResumeError, isRecoverableThreadResumeError,
normalizeCodexModelSlug, normalizeCodexModelSlug,
readCodexAccountSnapshot,
resolveCodexModelForAccount,
} from "./codexAppServerManager"; } from "./codexAppServerManager";
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value); const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
@@ -20,14 +23,20 @@ function createSendTurnHarness() {
const manager = new CodexAppServerManager(); const manager = new CodexAppServerManager();
const context = { const context = {
session: { session: {
sessionId: "sess_1",
provider: "codex", provider: "codex",
status: "ready", status: "ready",
threadId: "thread_1", threadId: "thread_1",
runtimeMode: "full-access",
model: "gpt-5.3-codex",
resumeCursor: { threadId: "thread_1" }, resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z", createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z", updatedAt: "2026-02-10T00:00:00.000Z",
}, },
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
}; };
const requireSession = vi const requireSession = vi
@@ -57,10 +66,11 @@ function createThreadControlHarness() {
const manager = new CodexAppServerManager(); const manager = new CodexAppServerManager();
const context = { const context = {
session: { session: {
sessionId: "sess_1",
provider: "codex", provider: "codex",
status: "ready", status: "ready",
threadId: "thread_1", threadId: "thread_1",
runtimeMode: "full-access",
model: "gpt-5.3-codex",
resumeCursor: { threadId: "thread_1" }, resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z", createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z", updatedAt: "2026-02-10T00:00:00.000Z",
@@ -88,10 +98,11 @@ function createPendingUserInputHarness() {
const manager = new CodexAppServerManager(); const manager = new CodexAppServerManager();
const context = { const context = {
session: { session: {
sessionId: "sess_1",
provider: "codex", provider: "codex",
status: "ready", status: "ready",
threadId: "thread_1", threadId: "thread_1",
runtimeMode: "full-access",
model: "gpt-5.3-codex",
resumeCursor: { threadId: "thread_1" }, resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z", createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z", updatedAt: "2026-02-10T00:00:00.000Z",
@@ -194,6 +205,70 @@ describe("isRecoverableThreadResumeError", () => {
}); });
}); });
describe("readCodexAccountSnapshot", () => {
it("disables spark for chatgpt plus accounts", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
planType: "plus",
}),
).toEqual({
type: "chatgpt",
planType: "plus",
sparkEnabled: false,
});
});
it("keeps spark enabled for chatgpt pro accounts", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
planType: "pro",
}),
).toEqual({
type: "chatgpt",
planType: "pro",
sparkEnabled: true,
});
});
it("keeps spark enabled for api key accounts", () => {
expect(
readCodexAccountSnapshot({
type: "apiKey",
}),
).toEqual({
type: "apiKey",
planType: null,
sparkEnabled: true,
});
});
});
describe("resolveCodexModelForAccount", () => {
it("falls back from spark to default for unsupported chatgpt plans", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "chatgpt",
planType: "plus",
sparkEnabled: false,
}),
).toBe("gpt-5.3-codex");
});
it("keeps spark for supported plans", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "chatgpt",
planType: "pro",
sparkEnabled: true,
}),
).toBe("gpt-5.3-codex-spark");
});
});
describe("startSession", () => { describe("startSession", () => {
it("enables Codex experimental api capabilities during initialize", () => { it("enables Codex experimental api capabilities during initialize", () => {
expect(buildCodexInitializeParams()).toEqual({ expect(buildCodexInitializeParams()).toEqual({
@@ -241,6 +316,59 @@ describe("startSession", () => {
manager.stopAll(); manager.stopAll();
} }
}); });
it("fails fast with an upgrade message when codex is below the minimum supported version", async () => {
const manager = new CodexAppServerManager();
const events: Array<{ method: string; kind: string; message?: string }> = [];
manager.on("event", (event) => {
events.push({
method: event.method,
kind: event.kind,
...(event.message ? { message: event.message } : {}),
});
});
const versionCheck = vi
.spyOn(
manager as unknown as {
assertSupportedCodexCliVersion: (input: {
binaryPath: string;
cwd: string;
homePath?: string;
}) => void;
},
"assertSupportedCodexCliVersion",
)
.mockImplementation(() => {
throw new Error(
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
);
});
try {
await expect(
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow(
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
);
expect(versionCheck).toHaveBeenCalledTimes(1);
expect(events).toEqual([
{
method: "session/startFailed",
kind: "error",
message:
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
},
]);
} finally {
versionCheck.mockRestore();
manager.stopAll();
}
});
}); });
describe("sendTurn", () => { describe("sendTurn", () => {
@@ -258,8 +386,8 @@ describe("sendTurn", () => {
}, },
], ],
model: "gpt-5.3", model: "gpt-5.3",
effort: "high",
serviceTier: "fast", serviceTier: "fast",
effort: "high",
}); });
expect(result).toEqual({ expect(result).toEqual({
@@ -282,8 +410,8 @@ describe("sendTurn", () => {
}, },
], ],
model: "gpt-5.3-codex", model: "gpt-5.3-codex",
effort: "high",
serviceTier: "fast", serviceTier: "fast",
effort: "high",
}); });
expect(updateSession).toHaveBeenCalledWith(context, { expect(updateSession).toHaveBeenCalledWith(context, {
status: "running", status: "running",
@@ -313,6 +441,7 @@ describe("sendTurn", () => {
url: "data:image/png;base64,BBBB", url: "data:image/png;base64,BBBB",
}, },
], ],
model: "gpt-5.3-codex",
}); });
}); });
@@ -346,6 +475,67 @@ describe("sendTurn", () => {
}); });
}); });
it("passes Codex default mode as a collaboration preset on turn/start", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
await manager.sendTurn({
threadId: asThreadId("thread_1"),
input: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
interactionMode: "default",
});
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "text",
text: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
text_elements: [],
},
],
model: "gpt-5.3-codex",
collaborationMode: {
mode: "default",
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
},
},
});
});
it("keeps the session model when interaction mode is set without an explicit model", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
context.session.model = "gpt-5.2-codex";
await manager.sendTurn({
threadId: asThreadId("thread_1"),
input: "Plan this with my current session model",
interactionMode: "plan",
});
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "text",
text: "Plan this with my current session model",
text_elements: [],
},
],
model: "gpt-5.2-codex",
collaborationMode: {
mode: "plan",
settings: {
model: "gpt-5.2-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
},
},
});
});
it("rejects empty turn input", async () => { it("rejects empty turn input", async () => {
const { manager } = createSendTurnHarness(); const { manager } = createSendTurnHarness();
@@ -454,8 +644,8 @@ describe("respondToUserInput", () => {
asThreadId("thread_1"), asThreadId("thread_1"),
ApprovalRequestId.makeUnsafe("req-user-input-1"), ApprovalRequestId.makeUnsafe("req-user-input-1"),
{ {
scope: "All request methods", scope: "All request methods",
compat: "Keep current envelope", compat: "Keep current envelope",
}, },
); );
@@ -482,91 +672,159 @@ describe("respondToUserInput", () => {
}), }),
); );
}); });
it("preserves explicit empty multi-select answers", async () => {
const { manager, context, requireSession, writeMessage, emitEvent } =
createPendingUserInputHarness();
await manager.respondToUserInput(
asThreadId("thread_1"),
ApprovalRequestId.makeUnsafe("req-user-input-1"),
{
scope: [],
},
);
expect(requireSession).toHaveBeenCalledWith("thread_1");
expect(writeMessage).toHaveBeenCalledWith(context, {
id: 42,
result: {
answers: {
scope: { answers: [] },
},
},
});
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "item/tool/requestUserInput/answered",
payload: {
requestId: "req-user-input-1",
answers: {
scope: { answers: [] },
},
},
}),
);
});
it("tracks file-read approval requests with the correct method", () => {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: asThreadId("thread_1"),
resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
};
type ApprovalRequestContext = {
session: typeof context.session;
pendingApprovals: typeof context.pendingApprovals;
pendingUserInputs: typeof context.pendingUserInputs;
};
(
manager as unknown as {
handleServerRequest: (
context: ApprovalRequestContext,
request: Record<string, unknown>,
) => void;
}
).handleServerRequest(context, {
jsonrpc: "2.0",
id: 42,
method: "item/fileRead/requestApproval",
params: {},
});
const request = Array.from(context.pendingApprovals.values())[0];
expect(request?.requestKind).toBe("file-read");
expect(request?.method).toBe("item/fileRead/requestApproval");
});
}); });
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => { describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
it( it("keeps prior thread history when resuming with a changed runtime mode", async () => {
"keeps prior thread history when resuming with a changed runtime mode", const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
async () => { writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
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 { try {
const firstSession = await manager.startSession({ const firstSession = await manager.startSession({
threadId: asThreadId("thread-live"), threadId: asThreadId("thread-live"),
provider: "codex", provider: "codex",
cwd: workspaceDir, cwd: workspaceDir,
runtimeMode: "full-access", runtimeMode: "full-access",
providerOptions: { providerOptions: {
codex: { codex: {
...(process.env.CODEX_BINARY_PATH ...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
? { binaryPath: process.env.CODEX_BINARY_PATH } ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
: {}),
...(process.env.CODEX_HOME_PATH
? { homePath: process.env.CODEX_HOME_PATH }
: {}),
},
}, },
}); },
});
const firstTurn = await manager.sendTurn({ const firstTurn = await manager.sendTurn({
threadId: firstSession.threadId, threadId: firstSession.threadId,
input: `Reply with exactly the word ALPHA ${randomUUID()}`, 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); const snapshot = await manager.readThread(firstSession.threadId);
expect(snapshot.turns.length).toBeGreaterThan(0); 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 firstSnapshot = await manager.readThread(firstSession.threadId);
const originalThreadId = firstSnapshot.threadId; const originalThreadId = firstSnapshot.threadId;
const originalTurnCount = firstSnapshot.turns.length; const originalTurnCount = firstSnapshot.turns.length;
manager.stopSession(firstSession.threadId); manager.stopSession(firstSession.threadId);
const resumedSession = await manager.startSession({ const resumedSession = await manager.startSession({
threadId: firstSession.threadId, threadId: firstSession.threadId,
provider: "codex", provider: "codex",
cwd: workspaceDir, cwd: workspaceDir,
runtimeMode: "approval-required", runtimeMode: "approval-required",
resumeCursor: firstSession.resumeCursor, resumeCursor: firstSession.resumeCursor,
providerOptions: { providerOptions: {
codex: { codex: {
...(process.env.CODEX_BINARY_PATH ...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
? { binaryPath: process.env.CODEX_BINARY_PATH } ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_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); const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId); expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount); expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
await manager.sendTurn({ await manager.sendTurn({
threadId: resumedSession.threadId, threadId: resumedSession.threadId,
input: `Reply with exactly the word BETA ${randomUUID()}`, input: `Reply with exactly the word BETA ${randomUUID()}`,
}); });
await vi.waitFor(async () => { await vi.waitFor(
async () => {
const snapshot = await manager.readThread(resumedSession.threadId); const snapshot = await manager.readThread(resumedSession.threadId);
expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount); expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);
}, { timeout: 120_000, interval: 1_000 }); },
} finally { { timeout: 120_000, interval: 1_000 },
manager.stopAll(); );
rmSync(workspaceDir, { recursive: true, force: true }); } finally {
} manager.stopAll();
}, rmSync(workspaceDir, { recursive: true, force: true });
180_000, }
); }, 180_000);
}); });
+206 -21
View File
@@ -22,6 +22,12 @@ import {
import { normalizeModelSlug } from "@t3tools/shared/model"; import { normalizeModelSlug } from "@t3tools/shared/model";
import { Effect, ServiceMap } from "effect"; import { Effect, ServiceMap } from "effect";
import {
formatCodexCliUpgradeMessage,
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "./provider/codexCliVersion";
type PendingRequestKey = string; type PendingRequestKey = string;
interface PendingRequest { interface PendingRequest {
@@ -34,7 +40,10 @@ interface PendingRequest {
interface PendingApprovalRequest { interface PendingApprovalRequest {
requestId: ApprovalRequestId; requestId: ApprovalRequestId;
jsonRpcId: string | number; jsonRpcId: string | number;
method: "item/commandExecution/requestApproval" | "item/fileChange/requestApproval"; method:
| "item/commandExecution/requestApproval"
| "item/fileChange/requestApproval"
| "item/fileRead/requestApproval";
requestKind: ProviderRequestKind; requestKind: ProviderRequestKind;
threadId: ThreadId; threadId: ThreadId;
turnId?: TurnId; turnId?: TurnId;
@@ -55,6 +64,7 @@ interface CodexUserInputAnswer {
interface CodexSessionContext { interface CodexSessionContext {
session: ProviderSession; session: ProviderSession;
account: CodexAccountSnapshot;
child: ChildProcessWithoutNullStreams; child: ChildProcessWithoutNullStreams;
output: readline.Interface; output: readline.Interface;
pending: Map<PendingRequestKey, PendingRequest>; pending: Map<PendingRequestKey, PendingRequest>;
@@ -86,13 +96,30 @@ interface JsonRpcNotification {
params?: unknown; params?: unknown;
} }
type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export interface CodexAppServerSendTurnInput { export interface CodexAppServerSendTurnInput {
readonly threadId: ThreadId; readonly threadId: ThreadId;
readonly input?: string; readonly input?: string;
readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>; readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>;
readonly model?: string; readonly model?: string;
readonly serviceTier?: string | null;
readonly effort?: string; readonly effort?: string;
readonly serviceTier?: string;
readonly interactionMode?: ProviderInteractionMode; readonly interactionMode?: ProviderInteractionMode;
} }
@@ -117,6 +144,8 @@ export interface CodexThreadSnapshot {
turns: CodexThreadTurnSnapshot[]; turns: CodexThreadTurnSnapshot[];
} }
const CODEX_VERSION_CHECK_TIMEOUT_MS = 4_000;
const ANSI_ESCAPE_CHAR = String.fromCharCode(27); const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g"); const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
const CODEX_STDERR_LOG_REGEX = const CODEX_STDERR_LOG_REGEX =
@@ -132,6 +161,50 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"unknown thread", "unknown thread",
"does not exist", "does not exist",
]; ];
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: true,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: true,
};
}
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational) export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions. You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
@@ -254,6 +327,19 @@ Do not ask "should I proceed?" in the final output. The user can easily switch o
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec. Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
</collaboration_mode>`; </collaboration_mode>`;
export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
Your active mode changes only when new developer instructions with a different \`<collaboration_mode>...</collaboration_mode>\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
## request_user_input availability
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
</collaboration_mode>`;
function mapCodexRuntimeMode(runtimeMode: RuntimeMode): { function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
readonly approvalPolicy: "on-request" | "never"; readonly approvalPolicy: "on-request" | "never";
readonly sandbox: "workspace-write" | "danger-full-access"; readonly sandbox: "workspace-write" | "danger-full-access";
@@ -271,6 +357,17 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
}; };
} }
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
/** /**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe` * On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the * wrapper, leaving the actual command running. Use `taskkill /T` to kill the
@@ -323,7 +420,7 @@ function buildCodexCollaborationMode(input: {
readonly effort?: string; readonly effort?: string;
}): }):
| { | {
mode: "plan"; mode: "default" | "plan";
settings: { settings: {
model: string; model: string;
reasoning_effort: string; reasoning_effort: string;
@@ -331,16 +428,19 @@ function buildCodexCollaborationMode(input: {
}; };
} }
| undefined { | undefined {
if (input.interactionMode !== "plan") { if (input.interactionMode === undefined) {
return undefined; return undefined;
} }
const model = normalizeCodexModelSlug(input.model) ?? "gpt-5.3-codex"; const model = normalizeCodexModelSlug(input.model) ?? "gpt-5.3-codex";
return { return {
mode: "plan", mode: input.interactionMode,
settings: { settings: {
model, model,
reasoning_effort: input.effort ?? "medium", reasoning_effort: input.effort ?? "medium",
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, developer_instructions:
input.interactionMode === "plan"
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
}, },
}; };
} }
@@ -352,18 +452,14 @@ function toCodexUserInputAnswer(value: unknown): CodexUserInputAnswer {
if (Array.isArray(value)) { if (Array.isArray(value)) {
const answers = value.filter((entry): entry is string => typeof entry === "string"); const answers = value.filter((entry): entry is string => typeof entry === "string");
if (answers.length > 0) { return { answers };
return { answers };
}
} }
if (value && typeof value === "object") { if (value && typeof value === "object") {
const maybeAnswers = (value as { answers?: unknown }).answers; const maybeAnswers = (value as { answers?: unknown }).answers;
if (Array.isArray(maybeAnswers)) { if (Array.isArray(maybeAnswers)) {
const answers = maybeAnswers.filter((entry): entry is string => typeof entry === "string"); const answers = maybeAnswers.filter((entry): entry is string => typeof entry === "string");
if (answers.length > 0) { return { answers };
return { answers };
}
} }
} }
@@ -447,6 +543,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const codexOptions = readCodexProviderOptions(input); const codexOptions = readCodexProviderOptions(input);
const codexBinaryPath = codexOptions.binaryPath ?? "codex"; const codexBinaryPath = codexOptions.binaryPath ?? "codex";
const codexHomePath = codexOptions.homePath; const codexHomePath = codexOptions.homePath;
this.assertSupportedCodexCliVersion({
binaryPath: codexBinaryPath,
cwd: resolvedCwd,
...(codexHomePath ? { homePath: codexHomePath } : {}),
});
const child = spawn(codexBinaryPath, ["app-server"], { const child = spawn(codexBinaryPath, ["app-server"], {
cwd: resolvedCwd, cwd: resolvedCwd,
env: { env: {
@@ -460,6 +561,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context = { context = {
session, session,
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
child, child,
output, output,
pending: new Map(), pending: new Map(),
@@ -477,12 +583,33 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
await this.sendRequest(context, "initialize", buildCodexInitializeParams()); await this.sendRequest(context, "initialize", buildCodexInitializeParams());
this.writeMessage(context, { method: "initialized" }); this.writeMessage(context, { method: "initialized" });
try {
const modelListResponse = await this.sendRequest(context, "model/list", {});
console.log("codex model/list response", modelListResponse);
} catch (error) {
console.log("codex model/list failed", error);
}
try {
const accountReadResponse = await this.sendRequest(context, "account/read", {});
console.log("codex account/read response", accountReadResponse);
context.account = readCodexAccountSnapshot(accountReadResponse);
console.log("codex subscription status", {
type: context.account.type,
planType: context.account.planType,
sparkEnabled: context.account.sparkEnabled,
});
} catch (error) {
console.log("codex account/read failed", error);
}
const normalizedModel = normalizeCodexModelSlug(input.model); const normalizedModel = resolveCodexModelForAccount(
normalizeCodexModelSlug(input.model),
context.account,
);
const sessionOverrides = { const sessionOverrides = {
model: normalizedModel ?? null, model: normalizedModel ?? null,
cwd: input.cwd ?? null,
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}), ...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
cwd: input.cwd ?? null,
...mapCodexRuntimeMode(input.runtimeMode ?? "full-access"), ...mapCodexRuntimeMode(input.runtimeMode ?? "full-access"),
}; };
@@ -642,10 +769,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string } { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>; >;
model?: string; model?: string;
serviceTier?: string | null;
effort?: string; effort?: string;
serviceTier?: string;
collaborationMode?: { collaborationMode?: {
mode: "plan"; mode: "default" | "plan";
settings: { settings: {
model: string; model: string;
reasoning_effort: string; reasoning_effort: string;
@@ -656,16 +783,19 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: providerThreadId, threadId: providerThreadId,
input: turnInput, input: turnInput,
}; };
const normalizedModel = normalizeCodexModelSlug(input.model ?? context.session.model); const normalizedModel = resolveCodexModelForAccount(
normalizeCodexModelSlug(input.model ?? context.session.model),
context.account,
);
if (normalizedModel) { if (normalizedModel) {
turnStartParams.model = normalizedModel; turnStartParams.model = normalizedModel;
} }
if (input.serviceTier !== undefined) {
turnStartParams.serviceTier = input.serviceTier;
}
if (input.effort) { if (input.effort) {
turnStartParams.effort = input.effort; turnStartParams.effort = input.effort;
} }
if (input.serviceTier) {
turnStartParams.serviceTier = input.serviceTier;
}
const collaborationMode = buildCodexCollaborationMode({ const collaborationMode = buildCodexCollaborationMode({
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}), ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
...(normalizedModel !== undefined ? { model: normalizedModel } : {}), ...(normalizedModel !== undefined ? { model: normalizedModel } : {}),
@@ -1064,7 +1194,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
method: method:
requestKind === "command" requestKind === "command"
? "item/commandExecution/requestApproval" ? "item/commandExecution/requestApproval"
: "item/fileChange/requestApproval", : requestKind === "file-read"
? "item/fileRead/requestApproval"
: "item/fileChange/requestApproval",
requestKind, requestKind,
threadId: context.session.threadId, threadId: context.session.threadId,
...(route.turnId ? { turnId: route.turnId } : {}), ...(route.turnId ? { turnId: route.turnId } : {}),
@@ -1201,6 +1333,14 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
this.emit("event", event); this.emit("event", event);
} }
private assertSupportedCodexCliVersion(input: {
readonly binaryPath: string;
readonly cwd: string;
readonly homePath?: string;
}): void {
assertSupportedCodexCliVersion(input);
}
private updateSession(context: CodexSessionContext, updates: Partial<ProviderSession>): void { private updateSession(context: CodexSessionContext, updates: Partial<ProviderSession>): void {
context.session = { context.session = {
...context.session, ...context.session,
@@ -1381,6 +1521,51 @@ function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
}; };
} }
function assertSupportedCodexCliVersion(input: {
readonly binaryPath: string;
readonly cwd: string;
readonly homePath?: string;
}): void {
const result = spawnSync(input.binaryPath, ["--version"], {
cwd: input.cwd,
env: {
...process.env,
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
},
encoding: "utf8",
shell: process.platform === "win32",
stdio: ["ignore", "pipe", "pipe"],
timeout: CODEX_VERSION_CHECK_TIMEOUT_MS,
maxBuffer: 1024 * 1024,
});
if (result.error) {
const lower = result.error.message.toLowerCase();
if (
lower.includes("enoent") ||
lower.includes("command not found") ||
lower.includes("not found")
) {
throw new Error(`Codex CLI (${input.binaryPath}) is not installed or not executable.`);
}
throw new Error(
`Failed to execute Codex CLI version check: ${result.error.message || String(result.error)}`,
);
}
const stdout = result.stdout ?? "";
const stderr = result.stderr ?? "";
if (result.status !== 0) {
const detail = stderr.trim() || stdout.trim() || `Command exited with code ${result.status}.`;
throw new Error(`Codex CLI version check failed. ${detail}`);
}
const parsedVersion = parseCodexCliVersion(`${stdout}\n${stderr}`);
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
throw new Error(formatCodexCliUpgradeMessage(parsedVersion));
}
}
function readResumeCursorThreadId(resumeCursor: unknown): string | undefined { function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
if (!resumeCursor || typeof resumeCursor !== "object" || Array.isArray(resumeCursor)) { if (!resumeCursor || typeof resumeCursor !== "object" || Array.isArray(resumeCursor)) {
return undefined; return undefined;
+2
View File
@@ -26,6 +26,7 @@ export interface ServerConfigShape {
readonly devUrl: URL | undefined; readonly devUrl: URL | undefined;
readonly noBrowser: boolean; readonly noBrowser: boolean;
readonly authToken: string | undefined; readonly authToken: string | undefined;
readonly allowedHosts: readonly string[];
readonly autoBootstrapProjectFromCwd: boolean; readonly autoBootstrapProjectFromCwd: boolean;
readonly logWebSocketEvents: boolean; readonly logWebSocketEvents: boolean;
} }
@@ -50,6 +51,7 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
port: 0, port: 0,
host: undefined, host: undefined,
authToken: undefined, authToken: undefined,
allowedHosts: [],
keybindingsConfigPath: path.join(statedir, "keybindings.json"), keybindingsConfigPath: path.join(statedir, "keybindings.json"),
staticDir: undefined, staticDir: undefined,
devUrl: undefined, devUrl: undefined,
@@ -363,8 +363,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () { Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem; const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path; const path = yield* Path.Path;
const attachmentId = const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
`thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`); const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true }); yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello")); yield* fs.writeFile(imagePath, Buffer.from("hello"));
@@ -392,9 +391,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
}), }),
), ),
), ),
Effect.ensuring( Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
fs.remove(imagePath).pipe(Effect.catch(() => Effect.void)),
),
); );
expect(generated.branch).toBe("fix/ui-regression"); expect(generated.branch).toBe("fix/ui-regression");
+301 -31
View File
@@ -97,7 +97,7 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
return { return {
status: (input) => core.status(input), status: (input) => core.status(input),
statusDetails: (cwd) => core.statusDetails(cwd), 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), commit: (cwd, subject, body) => core.commit(cwd, subject, body),
pushCurrentBranch: (cwd, fallbackBranch) => core.pushCurrentBranch(cwd, fallbackBranch), pushCurrentBranch: (cwd, fallbackBranch) => core.pushCurrentBranch(cwd, fallbackBranch),
pullCurrentBranch: (cwd) => core.pullCurrentBranch(cwd), pullCurrentBranch: (cwd) => core.pullCurrentBranch(cwd),
@@ -105,6 +105,10 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
readConfigValue: (cwd, key) => core.readConfigValue(cwd, key), readConfigValue: (cwd, key) => core.readConfigValue(cwd, key),
listBranches: (input) => core.listBranches(input), listBranches: (input) => core.listBranches(input),
createWorktree: (input) => core.createWorktree(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), removeWorktree: (input) => core.removeWorktree(input),
renameBranch: (input) => core.renameBranch(input), renameBranch: (input) => core.renameBranch(input),
createBranch: (input) => core.createBranch(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]) { function removeGitWorktree(input: Parameters<GitCoreShape["removeWorktree"]>[0]) {
return Effect.gen(function* () { return Effect.gen(function* () {
const core = yield* GitCore; const core = yield* GitCore;
@@ -174,7 +185,7 @@ function pullGitBranch({ cwd }: { cwd: string }) {
function initRepoWithCommit( function initRepoWithCommit(
cwd: string, cwd: string,
): Effect.Effect< ): Effect.Effect<
void, { initialBranch: string },
GitCommandError | PlatformError.PlatformError, GitCommandError | PlatformError.PlatformError,
GitCore | GitService | FileSystem.FileSystem GitCore | GitService | FileSystem.FileSystem
> { > {
@@ -185,6 +196,8 @@ function initRepoWithCommit(
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n"); yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
yield* git(cwd, ["add", "."]); yield* git(cwd, ["add", "."]);
yield* git(cwd, ["commit", "-m", "initial commit"]); 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); yield* initRepoWithCommit(tmp);
const result = yield* listGitBranches({ cwd: tmp }); const result = yield* listGitBranches({ cwd: tmp });
expect(result.isRepo).toBe(true); expect(result.isRepo).toBe(true);
expect(result.hasOriginRemote).toBe(false);
expect(result.branches.length).toBeGreaterThanOrEqual(1); expect(result.branches.length).toBeGreaterThanOrEqual(1);
}), }),
); );
@@ -260,6 +274,7 @@ it.layer(TestLayer)("git integration", (it) => {
const tmp = yield* makeTmpDir(); const tmp = yield* makeTmpDir();
const result = yield* listGitBranches({ cwd: tmp }); const result = yield* listGitBranches({ cwd: tmp });
expect(result.isRepo).toBe(false); expect(result.isRepo).toBe(false);
expect(result.hasOriginRemote).toBe(false);
expect(result.branches).toEqual([]); expect(result.branches).toEqual([]);
}), }),
); );
@@ -418,6 +433,7 @@ it.layer(TestLayer)("git integration", (it) => {
const result = yield* listGitBranches({ cwd: tmp }); const result = yield* listGitBranches({ cwd: tmp });
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote); const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
expect(result.hasOriginRemote).toBe(true);
expect(firstRemoteIndex).toBeGreaterThan(0); expect(firstRemoteIndex).toBeGreaterThan(0);
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe( expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
true, true,
@@ -426,7 +442,9 @@ it.layer(TestLayer)("git integration", (it) => {
true, true,
); );
expect( 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); ).toBe(true);
expect( expect(
result.branches.some( result.branches.some(
@@ -654,7 +672,7 @@ it.layer(TestLayer)("git integration", (it) => {
const realGitService = yield* GitService; const realGitService = yield* GitService;
let fetchStarted = false; let fetchStarted = false;
let releaseFetch: () => void = () => undefined; let releaseFetch!: () => void;
const waitForReleasePromise = new Promise<void>((resolve) => { const waitForReleasePromise = new Promise<void>((resolve) => {
releaseFetch = resolve; releaseFetch = resolve;
}); });
@@ -689,29 +707,27 @@ it.layer(TestLayer)("git integration", (it) => {
}), }),
); );
it.effect( it.effect("does not silently checkout a local branch when a remote ref no longer exists", () =>
"does not silently checkout a local branch when a remote ref no longer exists", Effect.gen(function* () {
() => const remote = yield* makeTmpDir();
Effect.gen(function* () { const source = yield* makeTmpDir();
const remote = yield* makeTmpDir(); yield* git(remote, ["init", "--bare"]);
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source); yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find( const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current, (branch) => branch.current,
)!.name; )!.name;
yield* git(source, ["remote", "add", "origin", remote]); yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]); yield* git(source, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: source, branch: "feature" }); yield* createGitBranch({ cwd: source, branch: "feature" });
const checkoutResult = yield* Effect.result( const checkoutResult = yield* Effect.result(
checkoutGitBranch({ cwd: source, branch: "origin/feature" }), checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
); );
expect(checkoutResult._tag).toBe("Failure"); expect(checkoutResult._tag).toBe("Failure");
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch); expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
}), }),
); );
it.effect("checks out a remote tracking branch when remote name contains slashes", () => 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(renamed.branch).toBe("feature/new-name");
expect(renameArgs).toEqual([ expect(renameArgs).toEqual(["branch", "-m", "--", "feature/old-name", "feature/new-name"]);
"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", () => it.effect("throws when new branch name already exists", () =>
Effect.gen(function* () { Effect.gen(function* () {
const tmp = yield* makeTmpDir(); 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 ── // ── Full flow: thread switching simulation ──
describe("full flow: thread switching (checkout toggling)", () => { 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", () => it.effect("reports status details and dirty state", () =>
Effect.gen(function* () { Effect.gen(function* () {
const tmp = yield* makeTmpDir(); 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", () => it.effect("skips push when no upstream is configured and branch is not ahead of base", () =>
Effect.gen(function* () { Effect.gen(function* () {
const tmp = yield* makeTmpDir(); 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( it.effect(
"pushes with upstream setup when comparable base exists but remote branch is missing", "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", () => it.effect("includes command context when worktree removal fails", () =>
Effect.gen(function* () { Effect.gen(function* () {
const tmp = yield* makeTmpDir(); 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", () => it.effect("pushes with upstream setup and then skips when up to date", () =>
Effect.gen(function* () { Effect.gen(function* () {
const tmp = yield* makeTmpDir(); const tmp = yield* makeTmpDir();
+251 -32
View File
@@ -100,6 +100,38 @@ function parseRemoteNames(stdout: string): ReadonlyArray<string> {
.toSorted((a, b) => b.length - a.length); .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( function parseRemoteRefWithRemoteNames(
branchName: string, branchName: string,
remoteNames: ReadonlyArray<string>, remoteNames: ReadonlyArray<string>,
@@ -159,9 +191,9 @@ function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`; return `git ${args.join(" ")}`;
} }
function parseDefaultBranchFromRemoteHeadRef(value: string): string | null { function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null {
const trimmed = value.trim(); const trimmed = value.trim();
const prefix = "refs/remotes/origin/"; const prefix = `refs/remotes/${remoteName}/`;
if (!trimmed.startsWith(prefix)) { if (!trimmed.startsWith(prefix)) {
return null; return null;
} }
@@ -385,29 +417,33 @@ const makeGitCore = Effect.gen(function* () {
yield* fetchUpstreamRef(cwd, upstream); 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( executeGit(
"GitCore.resolveDefaultBranchName", "GitCore.resolveDefaultBranchName",
cwd, cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"], ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`],
{ allowNonZeroExit: true }, { allowNonZeroExit: true },
).pipe( ).pipe(
Effect.map((result) => { Effect.map((result) => {
if (result.code !== 0) { if (result.code !== 0) {
return null; return null;
} }
return parseDefaultBranchFromRemoteHeadRef(result.stdout); return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName);
}), }),
); );
const remoteBranchExists = ( const remoteBranchExists = (
cwd: string, cwd: string,
remoteName: string,
branch: string, branch: string,
): Effect.Effect<boolean, GitCommandError> => ): Effect.Effect<boolean, GitCommandError> =>
executeGit( executeGit(
"GitCore.remoteBranchExists", "GitCore.remoteBranchExists",
cwd, cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`], ["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`],
{ {
allowNonZeroExit: true, allowNonZeroExit: true,
}, },
@@ -418,6 +454,89 @@ const makeGitCore = Effect.gen(function* () {
allowNonZeroExit: true, allowNonZeroExit: true,
}).pipe(Effect.map((result) => result.code === 0)); }).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 = ( const resolveBaseBranchForNoUpstream = (
cwd: string, cwd: string,
branch: string, branch: string,
@@ -430,7 +549,11 @@ const makeGitCore = Effect.gen(function* () {
true, true,
).pipe(Effect.map((stdout) => stdout.trim())); ).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 = [ const candidates = [
configuredBaseBranch.length > 0 ? configuredBaseBranch : null, configuredBaseBranch.length > 0 ? configuredBaseBranch : null,
defaultBranch, defaultBranch,
@@ -442,9 +565,13 @@ const makeGitCore = Effect.gen(function* () {
continue; continue;
} }
const remotePrefix =
primaryRemoteName && primaryRemoteName !== "origin" ? `${primaryRemoteName}/` : null;
const normalizedCandidate = candidate.startsWith("origin/") const normalizedCandidate = candidate.startsWith("origin/")
? candidate.slice("origin/".length) ? candidate.slice("origin/".length)
: candidate; : remotePrefix && candidate.startsWith(remotePrefix)
? candidate.slice(remotePrefix.length)
: candidate;
if (normalizedCandidate.length === 0 || normalizedCandidate === branch) { if (normalizedCandidate.length === 0 || normalizedCandidate === branch) {
continue; continue;
} }
@@ -453,8 +580,11 @@ const makeGitCore = Effect.gen(function* () {
return normalizedCandidate; return normalizedCandidate;
} }
if (yield* remoteBranchExists(cwd, normalizedCandidate)) { if (
return `origin/${normalizedCandidate}`; primaryRemoteName &&
(yield* remoteBranchExists(cwd, primaryRemoteName, normalizedCandidate))
) {
return `${primaryRemoteName}/${normalizedCandidate}`;
} }
} }
@@ -524,7 +654,7 @@ const makeGitCore = Effect.gen(function* () {
const statusDetails: GitCoreShape["statusDetails"] = (cwd) => const statusDetails: GitCoreShape["statusDetails"] = (cwd) =>
Effect.gen(function* () { Effect.gen(function* () {
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.catch(() => Effect.void)); yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all( const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
[ [
@@ -636,9 +766,21 @@ const makeGitCore = Effect.gen(function* () {
})), })),
); );
const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd) => const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd, filePaths) =>
Effect.gen(function* () { 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, [ const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [
"diff", "diff",
@@ -705,17 +847,17 @@ const makeGitCore = Effect.gen(function* () {
Effect.catch(() => Effect.succeed(null)), Effect.catch(() => Effect.succeed(null)),
); );
if (comparableBaseBranch) { if (comparableBaseBranch) {
const hasOriginRemote = yield* originRemoteExists(cwd).pipe( const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(false)), Effect.catch(() => Effect.succeed(null)),
); );
if (!hasOriginRemote) { if (!publishRemoteName) {
return { return {
status: "skipped_up_to_date" as const, status: "skipped_up_to_date" as const,
branch, branch,
}; };
} }
const hasRemoteBranch = yield* remoteBranchExists(cwd, branch).pipe( const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe(
Effect.catch(() => Effect.succeed(false)), Effect.catch(() => Effect.succeed(false)),
); );
if (hasRemoteBranch) { if (hasRemoteBranch) {
@@ -728,20 +870,46 @@ const makeGitCore = Effect.gen(function* () {
} }
if (!details.hasUpstream) { 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, [ yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [
"push", "push",
"-u", "-u",
"origin", publishRemoteName,
branch, branch,
]); ]);
return { return {
status: "pushed" as const, status: "pushed" as const,
branch, branch,
upstreamBranch: `origin/${branch}`, upstreamBranch: `${publishRemoteName}/${branch}`,
setUpstream: true, 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"]); yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]);
return { return {
status: "pushed" as const, status: "pushed" as const,
@@ -844,7 +1012,7 @@ const makeGitCore = Effect.gen(function* () {
if (localBranchResult.code !== 0) { if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim(); const stderr = localBranchResult.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) { if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false }; return { branches: [], isRepo: false, hasOriginRemote: false };
} }
return yield* createGitCommandError( return yield* createGitCommandError(
"GitCore.listBranches", "GitCore.listBranches",
@@ -1010,34 +1178,81 @@ const makeGitCore = Effect.gen(function* () {
const branches = [...localBranches, ...remoteBranches]; const branches = [...localBranches, ...remoteBranches];
return { branches, isRepo: true }; return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") };
}); });
const createWorktree: GitCoreShape["createWorktree"] = (input) => const createWorktree: GitCoreShape["createWorktree"] = (input) =>
Effect.gen(function* () { 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 repoName = path.basename(input.cwd);
const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp"; const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
const worktreePath = const worktreePath =
input.path ?? path.join(homeDir, ".t3", "worktrees", repoName, sanitizedBranch); 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( yield* executeGit("GitCore.createWorktree", input.cwd, args, {
"GitCore.createWorktree", fallbackErrorMessage: "git worktree add failed",
input.cwd, });
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
{
fallbackErrorMessage: "git worktree add failed",
},
);
return { return {
worktree: { worktree: {
path: worktreePath, 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) => const removeWorktree: GitCoreShape["removeWorktree"] = (input) =>
Effect.gen(function* () { Effect.gen(function* () {
const args = ["worktree", "remove"]; const args = ["worktree", "remove"];
@@ -1162,7 +1377,7 @@ const makeGitCore = Effect.gen(function* () {
// Refresh upstream refs in the background so checkout remains responsive. // Refresh upstream refs in the background so checkout remains responsive.
yield* Effect.forkScoped( yield* Effect.forkScoped(
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)), refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })),
); );
}); });
@@ -1197,6 +1412,10 @@ const makeGitCore = Effect.gen(function* () {
readConfigValue, readConfigValue,
listBranches, listBranches,
createWorktree, createWorktree,
fetchPullRequestBranch,
ensureRemote,
fetchRemoteBranch,
setBranchUpstream,
removeWorktree, removeWorktree,
renameBranch, renameBranch,
createBranch, 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 { runProcess } from "../../processRunner";
import { GitHubCliError } from "../Errors.ts"; 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; 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({ return new GitHubCliError({
operation, operation,
detail: `GitHub CLI command failed: ${error.message}`, detail: `GitHub CLI command failed: ${error.message}`,
@@ -44,59 +63,102 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
}); });
} }
function parseOpenPullRequests(raw: string): ReadonlyArray<{ function normalizePullRequestState(input: {
number: number; state?: string | null | undefined;
title: string; mergedAt?: string | null | undefined;
url: string; }): "open" | "closed" | "merged" {
baseRefName: string; const mergedAt = input.mergedAt;
headRefName: string; const state = input.state;
}> { if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
const trimmed = raw.trim(); return "merged";
if (trimmed.length === 0) return [];
const parsed: unknown = JSON.parse(trimmed);
if (!Array.isArray(parsed)) {
throw new Error("GitHub CLI returned non-array JSON.");
} }
if (state === "CLOSED") {
const result: Array<{ return "closed";
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,
});
} }
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(() => { const makeGitHubCli = Effect.sync(() => {
@@ -119,7 +181,7 @@ const makeGitHubCli = Effect.sync(() => {
"pr", "pr",
"list", "list",
"--head", "--head",
input.headBranch, input.headSelector,
"--state", "--state",
"open", "open",
"--limit", "--limit",
@@ -128,21 +190,56 @@ const makeGitHubCli = Effect.sync(() => {
"number,title,url,baseRefName,headRefName", "number,title,url,baseRefName,headRefName",
], ],
}).pipe( }).pipe(
Effect.map((result) => result.stdout), Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) => Effect.flatMap((raw) =>
Effect.try({ raw.length === 0
try: () => parseOpenPullRequests(raw), ? Effect.succeed([])
catch: (error: unknown) => : decodeGitHubJson(
new GitHubCliError({ raw,
operation: "listOpenPullRequests", Schema.Array(RawGitHubPullRequestSchema),
detail: "listOpenPullRequests",
error instanceof Error "GitHub CLI returned invalid PR list JSON.",
? `GitHub CLI returned invalid PR list JSON: ${error.message}` ),
: "GitHub CLI returned invalid PR list JSON.",
...(error !== undefined ? { cause: error } : {}),
}),
}),
), ),
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) => createPullRequest: (input) =>
execute({ execute({
@@ -153,7 +250,7 @@ const makeGitHubCli = Effect.sync(() => {
"--base", "--base",
input.baseBranch, input.baseBranch,
"--head", "--head",
input.headBranch, input.headSelector,
"--title", "--title",
input.title, input.title,
"--body-file", "--body-file",
@@ -170,6 +267,11 @@ const makeGitHubCli = Effect.sync(() => {
return trimmed.length > 0 ? trimmed : null; 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; } satisfies GitHubCliShape;
return service; return service;
File diff suppressed because it is too large. Load diff
+594 -62
View File
@@ -1,7 +1,12 @@
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { realpathSync } from "node:fs";
import { Effect, FileSystem, Layer, Path } from "effect"; 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 { GitManagerError } from "../Errors.ts";
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts"; import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
@@ -22,6 +27,96 @@ interface PullRequestInfo extends OpenPrInfo {
updatedAt: string | null; 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[] { function parsePullRequestList(raw: unknown): PullRequestInfo[] {
if (!Array.isArray(raw)) return []; if (!Array.isArray(raw)) return [];
@@ -157,6 +252,14 @@ function extractBranchFromRef(ref: string): string {
return normalized.slice(firstSlash + 1).trim(); 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): { function toStatusPr(pr: PullRequestInfo): {
number: number; number: number;
title: string; 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* () { export const makeGitManager = Effect.gen(function* () {
const gitCore = yield* GitCore; const gitCore = yield* GitCore;
const gitHubCli = yield* GitHubCli; const gitHubCli = yield* GitHubCli;
const textGeneration = yield* TextGeneration; 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 fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path; const path = yield* Path.Path;
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp"; const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const findOpenPr = (cwd: string, branch: string) => const readConfigValueNullable = (cwd: string, key: string) =>
gitHubCli gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
.listOpenPullRequests({
cwd, const resolveRemoteRepositoryContext = (cwd: string, remoteName: string | null) =>
headBranch: branch, Effect.gen(function* () {
limit: 1, if (!remoteName) {
}) return {
.pipe( repositoryNameWithOwner: null,
Effect.map((prs) => { ownerLogin: null,
const [first] = prs; };
if (!first) { }
return 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 { return {
number: first.number, number: firstPullRequest.number,
title: first.title, title: firstPullRequest.title,
url: first.url, url: firstPullRequest.url,
baseRefName: first.baseRefName, baseRefName: firstPullRequest.baseRefName,
headRefName: first.headRefName, headRefName: firstPullRequest.headRefName,
state: "open", state: "open",
updatedAt: null, updatedAt: null,
} satisfies PullRequestInfo; } 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({ return null;
try: () => JSON.parse(raw) as unknown, });
catch: (cause) =>
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
});
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => { const 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 left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0; const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
return right - left; return right - left;
@@ -253,12 +605,17 @@ export const makeGitManager = Effect.gen(function* () {
return parsed[0] ?? null; 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* () { Effect.gen(function* () {
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`); const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
if (configured) return configured; if (configured) return configured;
if (upstreamRef) { if (upstreamRef && !headContext.isCrossRepository) {
const upstreamBranch = extractBranchFromRef(upstreamRef); const upstreamBranch = extractBranchFromRef(upstreamRef);
if (upstreamBranch.length > 0 && upstreamBranch !== branch) { if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
return upstreamBranch; return upstreamBranch;
@@ -281,9 +638,10 @@ export const makeGitManager = Effect.gen(function* () {
commitMessage?: string; commitMessage?: string;
/** When true, also produce a semantic feature branch name. */ /** When true, also produce a semantic feature branch name. */
includeBranch?: boolean; includeBranch?: boolean;
filePaths?: readonly string[];
}) => }) =>
Effect.gen(function* () { Effect.gen(function* () {
const context = yield* gitCore.prepareCommitContext(input.cwd); const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
if (!context) { if (!context) {
return null; return null;
} }
@@ -323,6 +681,7 @@ export const makeGitManager = Effect.gen(function* () {
branch: string | null, branch: string | null,
commitMessage?: string, commitMessage?: string,
preResolvedSuggestion?: CommitAndBranchSuggestion, preResolvedSuggestion?: CommitAndBranchSuggestion,
filePaths?: readonly string[],
) => ) =>
Effect.gen(function* () { Effect.gen(function* () {
const suggestion = const suggestion =
@@ -331,6 +690,7 @@ export const makeGitManager = Effect.gen(function* () {
cwd, cwd,
branch, branch,
...(commitMessage ? { commitMessage } : {}), ...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
})); }));
if (!suggestion) { if (!suggestion) {
return { status: "skipped_no_changes" as const }; return { status: "skipped_no_changes" as const };
@@ -361,7 +721,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) { if (existing) {
return { return {
status: "opened_existing" as const, status: "opened_existing" as const,
@@ -373,13 +738,13 @@ 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 rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
const generated = yield* textGeneration.generatePrContent({ const generated = yield* textGeneration.generatePrContent({
cwd, cwd,
baseBranch, baseBranch,
headBranch: branch, headBranch: headContext.headBranch,
commitSummary: limitContext(rangeContext.commitSummary, 20_000), commitSummary: limitContext(rangeContext.commitSummary, 20_000),
diffSummary: limitContext(rangeContext.diffSummary, 20_000), diffSummary: limitContext(rangeContext.diffSummary, 20_000),
diffPatch: limitContext(rangeContext.diffPatch, 60_000), diffPatch: limitContext(rangeContext.diffPatch, 60_000),
@@ -397,18 +762,18 @@ export const makeGitManager = Effect.gen(function* () {
.createPullRequest({ .createPullRequest({
cwd, cwd,
baseBranch, baseBranch,
headBranch: branch, headSelector: headContext.preferredHeadSelector,
title: generated.title, title: generated.title,
bodyFile, bodyFile,
}) })
.pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void)))); .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) { if (!created) {
return { return {
status: "created" as const, status: "created" as const,
baseBranch, baseBranch,
headBranch: branch, headBranch: headContext.headBranch,
title: generated.title, title: generated.title,
}; };
} }
@@ -428,7 +793,10 @@ export const makeGitManager = Effect.gen(function* () {
const pr = const pr =
details.branch !== null 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.map((latest) => (latest ? toStatusPr(latest) : null)),
Effect.catch(() => Effect.succeed(null)), Effect.catch(() => Effect.succeed(null)),
) )
@@ -445,12 +813,172 @@ 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[],
) =>
Effect.gen(function* () { Effect.gen(function* () {
const suggestion = yield* resolveCommitAndBranchSuggestion({ const suggestion = yield* resolveCommitAndBranchSuggestion({
cwd, cwd,
branch, branch,
...(commitMessage ? { commitMessage } : {}), ...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
includeBranch: true, includeBranch: true,
}); });
if (!suggestion) { if (!suggestion) {
@@ -499,6 +1027,7 @@ export const makeGitManager = Effect.gen(function* () {
input.cwd, input.cwd,
initialStatus.branch, initialStatus.branch,
input.commitMessage, input.commitMessage,
input.filePaths,
); );
branchStep = result.branchStep; branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage; commitMessageForStep = result.resolvedCommitMessage;
@@ -514,6 +1043,7 @@ export const makeGitManager = Effect.gen(function* () {
currentBranch, currentBranch,
commitMessageForStep, commitMessageForStep,
preResolvedCommitSuggestion, preResolvedCommitSuggestion,
input.filePaths,
); );
const push = wantsPush const push = wantsPush
@@ -536,6 +1066,8 @@ export const makeGitManager = Effect.gen(function* () {
return { return {
status, status,
resolvePullRequest,
preparePullRequestThread,
runStackedAction, runStackedAction,
} satisfies GitManagerShape; } satisfies GitManagerShape;
}); });
+53
View File
@@ -56,6 +56,32 @@ export interface GitRenameBranchResult {
branch: string; 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. * GitCoreShape - Service API for low-level Git repository interactions.
*/ */
@@ -75,6 +101,7 @@ export interface GitCoreShape {
*/ */
readonly prepareCommitContext: ( readonly prepareCommitContext: (
cwd: string, cwd: string,
filePaths?: readonly string[],
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>; ) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
/** /**
@@ -129,6 +156,32 @@ export interface GitCoreShape {
input: GitCreateWorktreeInput, input: GitCreateWorktreeInput,
) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>; ) => 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. * Remove an existing worktree.
*/ */
+37 -2
View File
@@ -17,6 +17,16 @@ export interface GitHubPullRequestSummary {
readonly url: string; readonly url: string;
readonly baseRefName: string; readonly baseRefName: string;
readonly headRefName: 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 listOpenPullRequests: (input: {
readonly cwd: string; readonly cwd: string;
readonly headBranch: string; readonly headSelector: string;
readonly limit?: number; readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>; }) => 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. * Create a pull request from branch context and body file.
*/ */
readonly createPullRequest: (input: { readonly createPullRequest: (input: {
readonly cwd: string; readonly cwd: string;
readonly baseBranch: string; readonly baseBranch: string;
readonly headBranch: string; readonly headSelector: string;
readonly title: string; readonly title: string;
readonly bodyFile: string; readonly bodyFile: string;
}) => Effect.Effect<void, GitHubCliError>; }) => Effect.Effect<void, GitHubCliError>;
@@ -58,6 +84,15 @@ export interface GitHubCliShape {
readonly getDefaultBranch: (input: { readonly getDefaultBranch: (input: {
readonly cwd: string; readonly cwd: string;
}) => Effect.Effect<string | null, GitHubCliError>; }) => 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 * @module GitManager
*/ */
import { import {
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
GitResolvePullRequestResult,
GitRunStackedActionInput, GitRunStackedActionInput,
GitRunStackedActionResult, GitRunStackedActionResult,
GitStatusInput, GitStatusInput,
@@ -27,6 +31,20 @@ export interface GitManagerShape {
input: GitStatusInput, input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>; ) => 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`). * Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first. * When `featureBranch` is set, creates and checks out a feature branch first.
+6
View File
@@ -0,0 +1,6 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
+2
View File
@@ -9,6 +9,7 @@ import { Command } from "effect/unstable/cli";
import { version } from "../package.json" with { type: "json" }; import { version } from "../package.json" with { type: "json" };
import { ServerLive } from "./wsServer"; import { ServerLive } from "./wsServer";
import { NetService } from "@t3tools/shared/Net"; import { NetService } from "@t3tools/shared/Net";
import { FetchHttpClient } from "effect/unstable/http";
const RuntimeLayer = Layer.empty.pipe( const RuntimeLayer = Layer.empty.pipe(
Layer.provideMerge(CliConfig.layer), Layer.provideMerge(CliConfig.layer),
@@ -16,6 +17,7 @@ const RuntimeLayer = Layer.empty.pipe(
Layer.provideMerge(OpenLive), Layer.provideMerge(OpenLive),
Layer.provideMerge(NetService.layer), Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer), Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(FetchHttpClient.layer),
); );
Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain); Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain);
+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.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, [ assert.deepEqual(configState.issues, [
{ {
kind: "keybindings.invalid-entry", kind: "keybindings.invalid-entry",
+98 -41
View File
@@ -22,7 +22,9 @@ import {
Array, Array,
Cache, Cache,
Cause, Cause,
Deferred,
Effect, Effect,
Exit,
FileSystem, FileSystem,
Path, Path,
Layer, Layer,
@@ -33,7 +35,9 @@ import {
SchemaGetter, SchemaGetter,
SchemaIssue, SchemaIssue,
SchemaTransformation, SchemaTransformation,
Ref,
ServiceMap, ServiceMap,
Scope,
Stream, Stream,
} from "effect"; } from "effect";
import * as Semaphore from "effect/Semaphore"; import * as Semaphore from "effect/Semaphore";
@@ -422,6 +426,7 @@ export interface KeybindingsConfigState {
} }
export interface KeybindingsChangeEvent { export interface KeybindingsChangeEvent {
readonly keybindings: ResolvedKeybindingsConfig;
readonly issues: readonly ServerConfigIssue[]; readonly issues: readonly ServerConfigIssue[];
} }
@@ -468,6 +473,22 @@ function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): Resolve
* KeybindingsShape - Service API for keybinding configuration operations. * KeybindingsShape - Service API for keybinding configuration operations.
*/ */
export interface KeybindingsShape { export interface KeybindingsShape {
/**
* Start the keybindings runtime and attach file watching.
*
* Safe to call multiple times. The first successful call establishes the
* runtime; later calls await the same startup.
*/
readonly start: Effect.Effect<void, KeybindingsConfigError>;
/**
* Await keybindings runtime readiness.
*
* Readiness means the config directory exists, the watcher is attached, the
* startup sync has completed, and the current snapshot has been loaded.
*/
readonly ready: Effect.Effect<void, KeybindingsConfigError>;
/** /**
* Ensure the on-disk keybindings file exists and includes all default * Ensure the on-disk keybindings file exists and includes all default
* commands so newly-added defaults are backfilled on startup. * commands so newly-added defaults are backfilled on startup.
@@ -480,9 +501,14 @@ export interface KeybindingsShape {
readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>; readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
/** /**
* Stream keybindings config change events. * Read the latest keybindings snapshot from cache/disk.
*/ */
readonly changes: Stream.Stream<KeybindingsChangeEvent>; readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
/**
* Stream of keybindings config change events.
*/
readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;
/** /**
* Upsert a keybinding rule and persist the resulting configuration. * Upsert a keybinding rule and persist the resulting configuration.
@@ -509,9 +535,12 @@ const makeKeybindings = Effect.gen(function* () {
const upsertSemaphore = yield* Semaphore.make(1); const upsertSemaphore = yield* Semaphore.make(1);
const resolvedConfigCacheKey = "resolved" as const; const resolvedConfigCacheKey = "resolved" as const;
const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>(); const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();
const startedRef = yield* Ref.make(false);
const emitChange = (issues: readonly ServerConfigIssue[]) => const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();
PubSub.publish(changesPubSub, { issues }).pipe(Effect.asVoid); const watcherScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
const emitChange = (configState: KeybindingsConfigState) =>
PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);
const readConfigExists = fs.exists(keybindingsConfigPath).pipe( const readConfigExists = fs.exists(keybindingsConfigPath).pipe(
Effect.mapError( Effect.mapError(
@@ -676,43 +705,10 @@ const makeKeybindings = Effect.gen(function* () {
Effect.gen(function* () { Effect.gen(function* () {
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
const configState = yield* loadConfigStateFromCacheOrDisk; const configState = yield* loadConfigStateFromCacheOrDisk;
yield* emitChange(configState.issues); yield* emitChange(configState);
}), }),
); );
const keybindingsConfigDir = path.dirname(keybindingsConfigPath);
const keybindingsConfigFile = path.basename(keybindingsConfigPath);
const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);
yield* fs
.makeDirectory(keybindingsConfigDir, { recursive: true })
.pipe(Effect.orElseSucceed(() => undefined));
yield* Stream.runForEach(fs.watch(keybindingsConfigDir), (event) => {
const isTargetConfigEvent =
event.path === keybindingsConfigFile ||
event.path === keybindingsConfigPath ||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved;
if (!isTargetConfigEvent) {
return Effect.void;
}
return revalidateAndEmit.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to revalidate keybindings config after file update", {
path: keybindingsConfigPath,
detail: error.detail,
cause: error.cause,
}),
),
);
}).pipe(
Effect.catch((cause) =>
Effect.logWarning("keybindings config watcher stopped unexpectedly", {
path: keybindingsConfigPath,
cause,
}),
),
Effect.forkScoped,
);
const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)( const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
Effect.gen(function* () { Effect.gen(function* () {
const configExists = yield* readConfigExists; const configExists = yield* readConfigExists;
@@ -803,10 +799,68 @@ const makeKeybindings = Effect.gen(function* () {
}), }),
); );
const startWatcher = Effect.gen(function* () {
const keybindingsConfigDir = path.dirname(keybindingsConfigPath);
const keybindingsConfigFile = path.basename(keybindingsConfigPath);
const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);
yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new KeybindingsConfigError({
configPath: keybindingsConfigPath,
detail: "failed to prepare keybindings config directory",
cause,
}),
),
);
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
yield* Stream.runForEach(fs.watch(keybindingsConfigDir), (event) => {
const isTargetConfigEvent =
event.path === keybindingsConfigFile ||
event.path === keybindingsConfigPath ||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved;
if (!isTargetConfigEvent) {
return Effect.void;
}
return revalidateAndEmitSafely;
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);
});
const start = Effect.gen(function* () {
const alreadyStarted = yield* Ref.get(startedRef);
if (alreadyStarted) {
return yield* Deferred.await(startedDeferred);
}
yield* Ref.set(startedRef, true);
const startup = Effect.gen(function* () {
yield* startWatcher;
yield* syncDefaultKeybindingsOnStartup;
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
yield* loadConfigStateFromCacheOrDisk;
});
const startupExit = yield* Effect.exit(startup);
if (startupExit._tag === "Failure") {
yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
return yield* Effect.failCause(startupExit.cause);
}
yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
});
return { return {
start,
ready: Deferred.await(startedDeferred),
syncDefaultKeybindingsOnStartup, syncDefaultKeybindingsOnStartup,
loadConfigState: loadConfigStateFromCacheOrDisk, loadConfigState: loadConfigStateFromCacheOrDisk,
changes: Stream.fromPubSub(changesPubSub), getSnapshot: loadConfigStateFromCacheOrDisk,
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
upsertKeybindingRule: (rule) => upsertKeybindingRule: (rule) =>
upsertSemaphore.withPermits(1)( upsertSemaphore.withPermits(1)(
Effect.gen(function* () { Effect.gen(function* () {
@@ -833,7 +887,10 @@ const makeKeybindings = Effect.gen(function* () {
keybindings: nextResolved, keybindings: nextResolved,
issues: [], issues: [],
}); });
yield* emitChange([]); yield* emitChange({
keybindings: nextResolved,
issues: [],
});
return nextResolved; return nextResolved;
}), }),
), ),
Loaded 100 of 333 files, more files were not shown because too many files have changed in this diff. Show more