Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex 7333863065 Merge remote-tracking branch 'origin/main' into t3code/pr-649/fix/skip-auth-check-custom-model-providers
Co-authored-by: codex <[email protected]>
2026-03-10 01:18:30 -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
BinBandit 9dc1b8153b fix(server): skip auth check when Codex CLI uses a custom model provider
When the Codex CLI is configured with a custom model_provider in
~/.codex/config.toml (e.g. Portkey, Azure OpenAI proxy), authentication
is handled via provider-specific environment variables rather than
`codex login`. The `codex login status` probe would report 'not logged
in' and t3code would treat this as a blocking error, even though the CLI
works perfectly fine.

This change reads the model_provider key from the Codex CLI config file
at startup. When a non-OpenAI provider is detected, the auth probe is
skipped and the provider health check returns ready with authStatus
'unknown' instead of erroring out.

Fixes #644
2026-03-09 20:44:39 +11: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
150 changed files with 9297 additions and 3138 deletions

No files matched your search

+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
+28
View File
@@ -0,0 +1,28 @@
# 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:nmggithub
github:Noojuno
github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
+24 -1
View File
@@ -8,7 +8,7 @@ on:
jobs:
quality:
name: Lint, Typecheck, Test, Browser Test, Build
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Checkout
@@ -45,6 +45,9 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Format
run: bun run fmt:check
- name: Lint
run: bun run lint
@@ -69,3 +72,23 @@ jobs:
run: |
test -f 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@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
+175
View File
@@ -0,0 +1,175 @@
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@v7
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@v7
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 = 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;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
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,
});
const preservedLabels = currentLabels
.map((label) => label.name)
.filter((name) => !managedLabelNames.includes(name));
await github.rest.issues.setLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [...preservedLabels, nextLabelName],
});
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
+12 -28
View File
@@ -255,6 +255,16 @@ jobs:
needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Download all desktop artifacts
uses: actions/download-artifact@v4
with:
@@ -312,33 +322,7 @@ jobs:
name: Update version strings
env:
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
run: |
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`);
'
run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
@@ -346,7 +330,7 @@ jobs:
- name: Refresh lockfile
if: steps.update_versions.outputs.changed == 'true'
run: bun install
run: bun install --lockfile-only --ignore-scripts
- name: Commit and push version bump
if: steps.update_versions.outputs.changed == 'true'
+3 -2
View File
@@ -7,7 +7,8 @@
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js"
],
"experimentalSortPackageJson": {}
"sortPackageJson": {}
}
+7
View File
@@ -1,20 +1,24 @@
# Plan: Centralize Model Normalization in Contracts
## Summary
Move model alias/default normalization into `packages/contracts` so desktop and renderer use one shared source of truth.
## Motivation
- Removes duplicated logic between:
- `apps/desktop/src/codexAppServerManager.ts`
- `apps/renderer/src/model-logic.ts`
- Prevents behavior drift when model aliases/defaults are updated.
## Scope
- Add shared model utilities to contracts.
- Update desktop and renderer to consume shared utilities.
- Keep renderer-specific display options in renderer.
## Proposed Changes
1. Add `packages/contracts/src/model.ts` with:
- Canonical model list
- Alias map
@@ -29,14 +33,17 @@ Move model alias/default normalization into `packages/contracts` so desktop and
- Keep renderer tests focused on renderer-only behavior.
## Risks
- Desktop/renderer may currently rely on slightly different fallback behavior.
- Import graph must avoid bundling issues for Electron main/preload.
## Validation
- `bun run test`
- `bun run typecheck`
- Manual check that model selection and session start still send expected model slug.
## Done Criteria
- No duplicated alias/default map in desktop and renderer.
- Shared model utilities are contract-tested.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Strengthen Typed IPC Boundaries in Main Process
## Summary
Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers.
## Motivation
- `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`.
- Casts can hide contract breakages until runtime.
## Scope
- Desktop main process IPC registration.
- Optional shared helper for handler registration.
## Proposed Changes
1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to:
- Parse payload(s) with Zod schemas
- Standardize typed handler signatures
@@ -24,14 +28,17 @@ Replace loose payload casting in IPC handlers with strict schema parsing and typ
4. Add tests for handler parsing failure paths (invalid payloads).
## Risks
- Refactor can subtly change IPC error shape/messages.
- Helper abstraction should stay simple and not obscure control flow.
## Validation
- `bun run test`
- `bun run typecheck`
- Manual invalid payload check from renderer/devtools to confirm fast failure.
## Done Criteria
- No provider handler uses `payload as Parameters<...>`.
- All IPC entrypoints parse unknown payloads at boundary.
@@ -1,9 +1,11 @@
# Plan: Decompose CodexAppServerManager
## Summary
Split `CodexAppServerManager` into smaller modules with clear responsibilities.
## Motivation
- `apps/desktop/src/codexAppServerManager.ts` is large and mixes:
- Process lifecycle
- JSON-RPC parsing/routing
@@ -12,10 +14,12 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- This increases regression risk and slows changes.
## Scope
- Desktop provider internals only.
- Keep external behavior/API stable.
## Proposed Changes
1. Extract modules:
- `codex/processLifecycle.ts`
- `codex/jsonrpcRouter.ts`
@@ -29,13 +33,16 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- Session state transitions
## Risks
- Reordering event handling can change behavior.
- Must preserve pending request timeout/cancellation semantics.
## Validation
- Existing tests pass.
- Add module-level tests for parsing and transition logic.
## Done Criteria
- Main manager file materially smaller and orchestration-focused.
- Core protocol/state logic covered by focused tests.
+7
View File
@@ -1,9 +1,11 @@
# Plan: Split ChatView into Smaller UI/Logic Units
## Summary
Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
## Motivation
- `apps/renderer/src/components/ChatView.tsx` is large and handles:
- Session orchestration
- Send/interrupt actions
@@ -13,10 +15,12 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
- Hard to test and maintain as one component.
## Scope
- Renderer component boundaries and hooks.
- Keep visual behavior unchanged.
## Proposed Changes
1. Create hook: `apps/renderer/src/hooks/useChatSession.ts`
- `ensureSession`
- `sendTurn`
@@ -29,12 +33,15 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
4. Add focused tests for hook behavior (error handling, session reuse).
## Risks
- Refactor can break subtle UI interactions (auto-scroll, menu close, keyboard send).
## Validation
- `bun run test`
- Manual smoke: send, stream, interrupt, model switch.
## Done Criteria
- `ChatView.tsx` significantly reduced and easier to scan.
- Session logic isolated from rendering.
@@ -1,17 +1,21 @@
# Plan: Move Renderer Persisted-State Validation to Zod
## Summary
Use explicit Zod schemas for localStorage state parsing and migration.
## Motivation
- `apps/renderer/src/store.ts` has large manual sanitize functions.
- Manual type guards are verbose and easier to get wrong during schema evolution.
## Scope
- Renderer state hydration/persistence path.
- No backend/protocol changes.
## Proposed Changes
1. Add schema module: `apps/renderer/src/persistenceSchema.ts`
- Persisted payload versions (`v1`, `v2`)
- Thread/message/project schemas
@@ -23,12 +27,15 @@ Use explicit Zod schemas for localStorage state parsing and migration.
- Unknown thread/project references filtered
## Risks
- Overly strict schemas could drop valid historical data unexpectedly.
## Validation
- Unit tests for migration/hydration.
- Manual reload test with existing localStorage data.
## Done Criteria
- Store hydration logic is schema-driven.
- Migration behavior is tested and documented.
@@ -1,17 +1,21 @@
# Plan: Add Provider Log Stream Lifecycle Management
## Summary
Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely.
## Motivation
- `apps/desktop/src/providerManager.ts` opens a write stream in constructor.
- Stream lifecycle is not explicit on shutdown.
## Scope
- Desktop provider logging behavior.
- App shutdown integration.
## Proposed Changes
1. Add explicit `dispose()` on `ProviderManager`:
- Remove event listeners
- End/close log stream
@@ -20,12 +24,15 @@ Ensure `ProviderManager` logging stream is initialized, rotated/structured, and
4. Optional: per-session log files under `.logs/providers/`.
## Risks
- Improper close sequencing may lose final log lines.
## Validation
- Manual run/quit cycle to ensure no open handle warnings.
- Confirm logs flush on quit and file descriptors are not leaked.
## Done Criteria
- ProviderManager owns complete log stream lifecycle.
- Shutdown path explicitly disposes provider resources.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Add CI Workflow for Core Quality Gates
## Summary
Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-test) on pushes and PRs.
## Motivation
- Repository currently has no CI workflow files.
- Quality checks are only local/manual.
## Scope
- `.github/workflows/ci.yml`
- Bun + Turbo setup in CI.
## Proposed Changes
1. Add `ci.yml` with jobs:
- Setup Bun and Node environment
- Install deps
@@ -22,13 +26,16 @@ Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-tes
3. Configure caching for Bun/Turbo as appropriate.
## Risks
- Smoke test may be flaky in headless CI environments.
- CI runtime can grow if caching is misconfigured.
## Validation
- Verify workflow runs on a branch PR.
- Ensure failures surface clearly by job name.
## Done Criteria
- CI blocks regressions in lint/typecheck/test.
- Workflow docs added to README.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Add Pre-Commit Formatting/Lint Hooks
## Summary
Introduce pre-commit automation so formatting and basic lint checks happen before commits.
## Motivation
- Current lint failures include formatting-only issues.
- Shift-left feedback reduces noisy CI failures and cleanup churn.
## Scope
- Root tooling config and package scripts.
- No runtime code changes.
## Proposed Changes
1. Add hook tooling (e.g. Husky + lint-staged or Lefthook).
2. Configure staged-file tasks:
- `biome format --write`
@@ -20,13 +24,16 @@ Introduce pre-commit automation so formatting and basic lint checks happen befor
4. Keep checks fast to avoid developer friction.
## Risks
- Slow hooks can frustrate contributors and be bypassed.
- Need to ensure compatibility with Bun workspace setup.
## Validation
- Create sample staged changes and verify hook behavior.
- Confirm formatting fixes are applied automatically.
## Done Criteria
- Pre-commit hook installed and documented.
- Formatting-only lint failures drop significantly.
+7
View File
@@ -1,17 +1,21 @@
# Plan: Expand Event/State Transition Test Coverage
## Summary
Add focused tests for renderer event handling and session evolution logic.
## Motivation
- Core behavior is event-driven and stateful.
- Existing renderer tests cover only a subset of timeline/model behavior.
## Scope
- `apps/renderer/src/session-logic.test.ts`
- Optional reducer tests for `apps/renderer/src/store.ts`.
## Proposed Changes
1. Add tests for `evolveSession`:
- `thread/started`
- `turn/started`
@@ -24,12 +28,15 @@ Add focused tests for renderer event handling and session evolution logic.
3. Add reducer integration tests for `APPLY_EVENT`.
## Risks
- Tests may be brittle if event payload fixtures are too coupled to implementation details.
## Validation
- `bun run test`
- Ensure new tests remain deterministic and fast.
## Done Criteria
- High-risk event transitions are covered by unit tests.
- Regressions in stream assembly/session status are caught quickly.
@@ -1,17 +1,21 @@
# Plan: Unify Process and PTY Session Abstractions in ProcessManager
## Summary
Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes.
## Motivation
- `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic.
- New execution backends/providers will multiply complexity.
## Scope
- Desktop process execution internals.
- Preserve public `ProcessManager` API.
## Proposed Changes
1. Introduce internal interface (e.g. `RuntimeSession`):
- `write(data)`
- `kill()`
@@ -24,12 +28,15 @@ Refactor `ProcessManager` to use a single runtime-session interface for child-pr
5. Add tests for both implementations.
## Risks
- PTY behavior differs by platform; abstraction must not hide required differences.
## Validation
- Existing `processManager.test.ts` passes.
- Add PTY-path tests where feasible.
## Done Criteria
- Manager no longer branches per backend in `write/kill/killAll`.
- Session backends are independently testable.
+1 -3
View File
@@ -1,5 +1,3 @@
PR 1: Service contracts + error taxonomy
Add ProviderService, CodexService, CheckpointStore as Context.Tag service defs.
Add typed Schema.TaggedError hierarchies for all 3 services (cause: Schema.optional(Schema.Defect) on each).
@@ -39,4 +37,4 @@ Remove throw-based flow entirely from provider path.
PR 10: Cleanup + deprecation removal
Remove legacy class implementations/adapters once parity is proven.
Finalize layer composition and startup graph docs.
Add architecture notes for service boundaries and error model.
Add architecture notes for service boundaries and error model.
+9
View File
@@ -1,12 +1,14 @@
# Effect Migration Plan (From Current State)
Current status summary:
- Service contracts, typed errors, and most checkpoint/persistence services exist.
- `ProviderServiceLive` is already native orchestration (not a thin adapter).
- Production server path still uses legacy `ProviderManager`/`FilesystemCheckpointStore`.
- Checkpoint flow now avoids snapshot re-sync and is write-time driven.
## PR 1: Wire Provider/Checkpoint Effect Stack Into `wsServer`
- Build one runtime layer graph for provider + checkpoint + persistence + orchestration.
- Resolve `ProviderService` from runtime in `wsServer`.
- Replace `ProviderManager` method calls in WS handlers with `ProviderService` calls.
@@ -14,12 +16,14 @@ Current status summary:
- Keep WS method/push payloads identical.
## PR 2: Runtime Composition + Startup Ownership
- Create/centralize `AppLive` composition for server startup.
- Ensure outer runtime provides Node/platform services once.
- Ensure migrations run at startup via scoped/layer startup path.
- Remove ad-hoc service initialization in request-time paths.
## PR 3: Session Lifecycle Hygiene + Checkpoint Invariants
- Add explicit checkpoint session cleanup on `stopSession` / `stopAll`.
- Remove per-session lock/cwd map leaks.
- Keep strict invariant model:
@@ -29,12 +33,14 @@ Current status summary:
- Add tests for lifecycle cleanup and invariant-failure surfaces.
## PR 4: Provider Event Stream Hardening (Without Extra Service Fragmentation)
- Keep `ProviderService` as the public event surface.
- Internally move callback fanout to Effect concurrency primitives (`Queue`/`PubSub`) for ordering/backpressure control.
- Keep API as `subscribeToEvents` unless we explicitly choose stream API later.
- Add tests for ordering and subscriber isolation under load.
## PR 5: Codex Runtime Split (Scoped Effect Core)
- Extract `CodexAppServerManager` responsibilities into Effect-native layers:
- scoped process lifecycle
- RPC request/response + pending map via `Deferred`
@@ -43,16 +49,19 @@ Current status summary:
- Preserve protocol behavior and timeout semantics.
## PR 6: Codex Protocol Decode Hardening
- Replace ad-hoc unknown parsing with runtime schema decode.
- Map decode failures to typed tagged errors with `cause` retained.
- Add regression tests for malformed/partial protocol frames.
## PR 7: Remove Legacy Provider Stack
- Remove `ProviderManager` + legacy checkpoint integration from runtime path.
- Remove `FilesystemCheckpointStore` from active server flow (keep only if explicitly needed for compatibility tooling).
- Update tests to assert only Effect service path is used.
## PR 8: Final Cleanup + Docs
- Update architecture docs with final layer graph and service boundaries.
- Document error model and recovery semantics.
- Trim dead compatibility code and stale plan references.
@@ -1,6 +1,7 @@
# ProviderService Integration Test Plan
Goal:
- Validate end-to-end `ProviderService` behavior with real layers:
- `ProviderServiceLive`
- `CheckpointServiceLive`
@@ -13,6 +14,7 @@ Goal:
## Test Harness
Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Layers/TestProviderAdapter.integration.ts`:
- Service contract: `ProviderAdapterShape<ProviderAdapterError>`.
- Internal state:
- session registry (session + cwd + threadId)
@@ -29,13 +31,15 @@ Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Lay
- `readThread`, `rollbackThread`, `stopSession`, `stopAll`.
Use real git-backed temporary workspaces in integration tests:
- initialize repo with baseline commit
- run provider turn in workspace
- assert checkpoint diffs against real git refs
## Core Integration Specs
1) `startSession` initializes checkpoint root exactly once
1. `startSession` initializes checkpoint root exactly once
- Arrange:
- start provider session in git repo.
- Assert:
@@ -43,7 +47,8 @@ Use real git-backed temporary workspaces in integration tests:
- checkpoint ref exists in git.
- second `startSession` for new session creates a new independent root.
2) Turn without filesystem change
2. Turn without filesystem change
- Arrange:
- emit normal turn events, no file mutation.
- Assert:
@@ -54,7 +59,8 @@ Use real git-backed temporary workspaces in integration tests:
- `listCheckpoints` returns root + turn 1.
- `getCheckpointDiff(0 -> 1)` returns empty/no-op diff.
3) Turn with filesystem change
3. Turn with filesystem change
- Arrange:
- mutate `README.md` during turn.
- Assert:
@@ -62,7 +68,8 @@ Use real git-backed temporary workspaces in integration tests:
- `getCheckpointDiff(0 -> 1)` contains file path and hunk.
- persisted checkpoint metadata includes non-empty `checkpointRef`.
4) Multi-turn sequencing and checkpoint monotonicity
4. Multi-turn sequencing and checkpoint monotonicity
- Arrange:
- turn 1: no file change
- turn 2: file change
@@ -72,7 +79,8 @@ Use real git-backed temporary workspaces in integration tests:
- latest checkpoint is marked current.
- diffs for adjacent turns map to expected filesystem deltas.
5) Revert to checkpoint
5. Revert to checkpoint
- Arrange:
- execute 3 turns with at least one file-changing turn.
- call `revertToCheckpoint(turnCount=1)`.
@@ -82,7 +90,8 @@ Use real git-backed temporary workspaces in integration tests:
- DB rows for turns >1 are removed.
- later refs are deleted from git.
6) Capture failure surface
6. Capture failure surface
- Arrange:
- adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails.
- Assert:
@@ -92,6 +101,7 @@ Use real git-backed temporary workspaces in integration tests:
## WebSocket Coverage (Thin Integration)
Add one ws server integration spec:
- Subscribe to `providers.event`.
- Run a deterministic provider turn through ws methods.
- Assert push stream includes:
@@ -101,10 +111,13 @@ Add one ws server integration spec:
## Proposed PR Split
PR A:
- Test adapter harness + shared integration fixtures (repo setup, runtime/layer setup).
PR B:
- Core ProviderService integration specs (cases 1-4).
PR C:
- Revert + failure-path specs (cases 5-6) + ws thin integration spec.
@@ -1,6 +1,7 @@
# Server-Authoritative Event-Sourcing Cleanup Plan
Goal:
- Move to a cleaner service architecture with:
- durable, server-authoritative event sourcing
- strict command routing/validation
@@ -85,6 +86,7 @@ CheckpointCatalog ------> SQLite
## Commit Series
### Commit 1: Split public vs system orchestration command contracts
- Create separate schemas/types:
- `ClientOrchestrationCommandSchema`
- `SystemOrchestrationCommandSchema`
@@ -100,6 +102,7 @@ CheckpointCatalog ------> SQLite
- preserve internal dispatch functionality for system commands
### Commit 2: Introduce `OrchestrationCommandRouter` + handler boundary
- Add dedicated router service to validate, authorize, and route commands.
- Move command-to-event mapping out of `orchestration/Layer.ts` into handlers.
- Add aggregate-level invariant checks before append (thread exists, project exists, etc.).
@@ -113,6 +116,7 @@ CheckpointCatalog ------> SQLite
- handler happy-path tests per command type
### Commit 3: Harden event store for idempotency + optimistic append metadata
- Add DB-level idempotency guard for `command_id` (`UNIQUE` where non-null).
- Extend append API to support idempotent replays and deterministic return of prior event on duplicate `commandId`.
- Add optional aggregate version metadata for future optimistic concurrency.
@@ -125,6 +129,7 @@ CheckpointCatalog ------> SQLite
- concurrent append behavior stays ordered and deterministic
### Commit 4: Extract provider-runtime -> orchestration bridge from `wsServer`
- Create `ProviderRuntimeIngestionService` that:
- subscribes to `ProviderService.streamEvents`
- translates runtime events into orchestration commands
@@ -139,6 +144,7 @@ CheckpointCatalog ------> SQLite
- ws integration confirms same external push behavior
### Commit 5: Make session directory durable (`ProviderSessionRegistry`)
- Replace in-memory-only `ProviderSessionDirectoryLive` with persistence-backed registry.
- Keep in-memory cache optional, but source of truth must be persistent.
- Add startup reconciliation to prune dead sessions / keep known thread mapping.
@@ -152,6 +158,7 @@ CheckpointCatalog ------> SQLite
- stale session cleanup semantics
### Commit 6: Re-key checkpoint metadata from session to thread identity
- Change checkpoint catalog primary identity from `provider_session_id` to durable `thread_id`.
- Keep `session_id` as nullable metadata only.
- Update checkpoint flows (`initialize`, `capture`, `list`, `diff`, `revert`) to use thread identity.
@@ -165,6 +172,7 @@ CheckpointCatalog ------> SQLite
- revert/diff still work after session churn
### Commit 7: Add durable projection persistence for orchestration read models
- Introduce projection tables/snapshots persisted in DB to avoid full replay dependency.
- Keep event stream as source of truth; projection rebuild stays deterministic.
- `getSnapshot` reads from projection store (memory cache optional).
@@ -177,6 +185,7 @@ CheckpointCatalog ------> SQLite
- projection rebuild from events yields same result as previous reducer semantics
### Commit 8: Narrow `ProviderService` responsibilities
- Keep `ProviderService` focused on provider RPC/session lifecycle + unified runtime stream.
- Move checkpoint-capture side effects out of provider event worker into dedicated ingestion/checkpoint pipeline service.
- Preserve adapter pluggability and provider-neutral contracts.
@@ -188,6 +197,7 @@ CheckpointCatalog ------> SQLite
- checkpoint capture still triggered by turn completion through new coordinator
### Commit 9: Look over schemas (contracts and events)
- Scan for unused schemas.
- Use effect/Schema everywhere
- Analyze which we need
@@ -196,6 +206,7 @@ CheckpointCatalog ------> SQLite
- Persistence entities
### Commit 10: Remove dead legacy path and finalize docs
- Remove unused legacy manager/store path from active architecture:
- `providerManager.ts`
- `filesystemCheckpointStore.ts` (if no longer needed by tests/tools)
@@ -210,6 +221,7 @@ CheckpointCatalog ------> SQLite
- no regressions in WS protocol behavior
## Risk Controls
- Keep WS method names and payload contracts stable throughout.
- Gate each commit with targeted integration tests before moving forward.
- Avoid broad event-type churn in one step; migrate schemas incrementally with clear compatibility windows.
+2 -1
View File
@@ -1,10 +1,11 @@
Rewrite `createServer` and `index.ts` to be Effect native.
Maybe use `effect/unstable/Socket` for the web socket server
- https://github.com/Effect-TS/effect-smol/blob/main/packages/effect/src/unstable/socket/SocketServer.ts
- https://github.com/Effect-TS/effect-smol/blob/main/packages/platform-node/test/NodeSocket.test.ts
- Migrate remaining runtime code to Effect
- `gitManager` -> `src/git`
- `terminalManager` -> `src/terminal` (Manager + PTY)
- ...
- ...
@@ -24,21 +24,25 @@
- Mark invalid/false-positive items with explicit rationale.
Exit criteria:
- Every open thread is mapped to one canonical fix item or marked invalid.
## Phase 1: Runtime Survival and Critical Event Wiring
Related bug groups solved together:
- Worker loop/fiber fatal error handling in orchestration reactors.
- WebSocket message error boundaries and unhandled rejection guards.
- Close invalid `providers.event` review findings as documented architecture mismatch (no code change expected).
Primary files:
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
- `apps/server/src/wsServer.ts`
Exit criteria:
- A single event-processing failure cannot permanently stop ingestion/reactor loops.
- WS message handling cannot produce unhandled promise rejections.
- Invalid provider-event-channel review findings are closed with architecture rationale.
@@ -46,17 +50,20 @@ Exit criteria:
## Phase 2: State Consistency and Ordering
Related bug groups solved together:
- Fire-and-forget revert completion causing consistency windows.
- Non-atomic append/projection paths and retry behavior.
- Race-sensitive thread/event association issues.
Primary files:
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
- `apps/server/src/orchestration/Layers/OrchestrationEngine.ts`
- `apps/server/src/orchestration/Layers/ProjectionPipeline.ts`
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
Exit criteria:
- Revert flow is deterministically reflected in read model updates.
- Append/project failure mode is explicit and safe under retry.
- No cross-thread misassociation under concurrent runtime events.
@@ -64,12 +71,14 @@ Exit criteria:
## Phase 3: Checkpointing Correctness Bundle
Related bug groups solved together:
- Checkpoint input normalization consistency.
- Snapshot/projector coverage mismatches.
- Checkpoint ref/workspace CWD utility duplication.
- Checkpoint diff/error handling behavior gaps.
Primary files:
- `apps/server/src/checkpointing/Layers/CheckpointStore.ts`
- `apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts`
- `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts`
@@ -77,6 +86,7 @@ Primary files:
- `apps/server/src/wsServer.ts`
Exit criteria:
- Checkpoint capture/restore/revert paths use one normalization policy.
- Required projectors are actually represented in snapshot reads.
- Shared checkpoint/ref/CWD helpers are centralized.
@@ -84,27 +94,32 @@ Exit criteria:
## Phase 4: Memory and Lifecycle Hygiene
Related bug groups solved together:
- Unbounded in-memory dedup sets/maps.
- Missing cleanup/lifecycle protections in long-lived effects/resources.
Primary files:
- `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
- `apps/server/src/config.ts`
Exit criteria:
- Long-running server memory does not grow unbounded from dedup bookkeeping.
- Resource cleanup paths are registered for interruption/shutdown.
## Phase 5: Transport, Parsing, and Platform Edge Cases
Related bug groups solved together:
- UTF-8 chunk boundary decode correctness.
- Markdown/file-link parsing edge cases.
- Shell/OS-specific PATH parsing behavior.
- Git rename parsing and small keybinding edge cases.
Primary files:
- `apps/server/src/wsServer.ts`
- `apps/server/src/git/Layers/CodexTextGeneration.ts`
- `apps/web/src/markdown-links.ts`
@@ -113,23 +128,27 @@ Primary files:
- `apps/server/src/keybindings.ts`
Exit criteria:
- Edge-case parsers are robust across valid but non-trivial inputs.
- Platform-dependent command behavior has safe fallbacks.
## Phase 6: Build and Maintainability Cleanup
Related bug groups solved together:
- Build script/runtime assumption cleanup.
- Redundant error-union declarations and utility/type duplication.
- Non-functional cleanup comments/docs markers.
Primary files:
- `apps/server/package.json`
- `apps/server/src/checkpointing/Errors.ts`
- Shared utility locations introduced during earlier phases
- `AGENTS.md` (if cleanup is still pending)
Exit criteria:
- Build path is explicit and environment-safe.
- Redundant types/utilities are removed in favor of single sources of truth.
@@ -140,6 +159,7 @@ Exit criteria:
- Resolve threads with fix references per canonical checklist item.
Exit criteria:
- Lint passes.
- Backend tests pass.
- All actionable review threads are resolved or explicitly justified.
+5 -4
View File
@@ -5,6 +5,7 @@ _Last updated: 2026-02-26_
This is the working checklist for remediation execution.
Status values:
- `TODO`: Not started
- `IN_PROGRESS`: Currently being worked
- `BLOCKED`: Waiting on decision/dependency
@@ -150,7 +151,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Area: `WebSocket robustness`
- File: `apps/web/src/wsTransport.ts:59`
- Threads: PRRT_kwDORLtfbc5whtrN
- Audit note: Transport _tag override risk exists but current callsites are constrained.
- Audit note: Transport \_tag override risk exists but current callsites are constrained.
### Phase 2
@@ -181,7 +182,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Threads: PRRT_kwDORLtfbc5whxJO
- Audit note: Message fallback retention issue is real, but prior FK-violation claim is overstated.
- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes *after* the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes _after_ the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
@@ -198,7 +199,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Severity: `Medium`
- Area: `Checkpointing correctness`
- File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:94`
- Threads: PRRT_kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv_, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))
- Threads: PRRT*kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv*, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))
- Audit note: Edge schema strategy is in place across contracts/consumers (trim/normalize via schemas and decode at boundaries); CheckpointStore remains an internal repository boundary.
- [x] `C017` `REQUIRED_SNAPSHOT_PROJECTORS` includes `pending-approvals` and `thread-turns`, but `getSnapshot` doesn't query their data. If these projectors lag behind, the returned `snapshotSequence` will be lower than what the included data actually reflects, causing clients to replay already-applied events. Consider filtering `REQUIRED_SNAPSHOT_PROJECTORS` to only include projectors whose data is actually fetched in the snapshot. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
@@ -250,7 +251,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
### Phase 5
- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after ` => ` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after `=>` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
+51
View File
@@ -3,13 +3,16 @@
Goal: Align the orchestration model to `SPEC.md` 1:1 and remove legacy persistence/application cruft.
Execution mode for this plan:
- Hard cutover only. Existing DB and migration history are disposable.
- Intermediate steps are allowed to break runtime, tests, typecheck, and lint.
- We optimize for small, reviewable work units, not continuous app operability.
- Only the final gate requires everything to run cleanly.
## 1. Freeze SPEC contract as source of truth
Work units:
- Create `.plans/spec-contract-matrix.md` with one row per requirement in `SPEC.md` sections `7.1`-`7.4`.
- Add exact SQL-level requirements per row: table, column, type, nullability, PK/unique, index, and invariants.
- Add app-level requirements per row: writer path, reader path, and owning module.
@@ -17,17 +20,22 @@ Work units:
- Identify any ambiguous spec lines and record a concrete interpretation in the matrix.
Deliverables:
- Complete matrix file with no unclassified rows.
- Single source checklist used by all later steps.
Breakage allowed:
- No code changes required yet.
Exit criteria:
- Every requirement in `7.1`-`7.4` has exactly one matrix row.
## 2. Hard cutover migrations (replace current migration set)
Work units:
- Delete the current legacy migration files and rewrite migration loader ordering.
- Create `001_orchestration_events.ts` with full envelope columns and required event indexes.
- Create `002_orchestration_command_receipts.ts` with PK + lookup indexes.
@@ -47,17 +55,22 @@ Work units:
- Ensure old tables (`projects`, `provider_checkpoints`, `provider_sessions`) are not recreated.
Deliverables:
- New 5-file migration chain.
- Updated migration loader references only new migrations.
Breakage allowed:
- Repositories/services can be temporarily broken due to removed old tables.
Exit criteria:
- Fresh DB initializes with only canonical tables plus migration bookkeeping.
## 3. Align persistence row/request schemas to DB 1:1
Work units:
- Define row schemas for each canonical table (contracts or persistence layer module).
- Define request schemas for every insert/update/query operation touching canonical tables.
- Remove or deprecate row/request schemas tied to deleted legacy tables.
@@ -65,17 +78,22 @@ Work units:
- Ensure SQL aliases map 1:1 to schema field names (no implicit shape transforms).
Deliverables:
- Canonical row/request schemas committed.
- Zero references to legacy row schemas in active code paths.
Breakage allowed:
- Runtime can still fail while query layers are being rewired.
Exit criteria:
- Every canonical table used in code has a typed row schema and typed request schema.
## 4. Rewrite event store for full persisted envelope
Work units:
- Refactor append path to write full envelope fields:
- `event_id`, `aggregate_kind`, `stream_id`, `stream_version`, `event_type`, `occurred_at`, `command_id`, `causation_event_id`, `correlation_id`, `actor_kind`, `payload_json`, `metadata_json`
- Implement stream version assignment/checking per aggregate stream.
@@ -84,16 +102,21 @@ Work units:
- Add explicit SQL ordering guarantees for replay (`ORDER BY sequence ASC`).
Deliverables:
- Event store append/replay fully aligned with canonical envelope.
Breakage allowed:
- Command dispatch flow can be partially broken until receipts/projectors are updated.
Exit criteria:
- Event store no longer depends on legacy event table shape.
## 5. Add command receipt idempotency
Work units:
- Introduce persistence access layer for `orchestration_command_receipts`.
- In command dispatch flow, check existing receipt by `commandId` before append.
- On first execution, persist accepted receipt with `resultSequence`.
@@ -102,16 +125,21 @@ Work units:
- Ensure receipt write and event append ordering is deterministic.
Deliverables:
- Dispatch path with idempotency behavior wired through receipts.
Breakage allowed:
- Snapshot/read model may still be inconsistent until projectors are fully wired.
Exit criteria:
- Duplicate command IDs no longer create duplicate events.
## 6. Build DB-backed projection pipeline
Work units:
- Create projector runner that consumes events and applies table-specific projections.
- Implement projector handlers for each projection table.
- For each handler, update target row(s) and `projection_state.last_applied_sequence` in the same transaction.
@@ -120,16 +148,21 @@ Work units:
- Add safe resume logic from projector `last_applied_sequence`.
Deliverables:
- Persistent projector pipeline writing all `projection_*` tables.
Breakage allowed:
- Web/API layer may still read old in-memory model until step 7.
Exit criteria:
- Events drive projection rows in DB; projection state advances transactionally.
## 7. Move RPC reads to projections and diff blobs
Work units:
- Implement snapshot query service reading only projection tables.
- Build thread hydration from projection rows: messages, activities, checkpoints, session.
- Compute `snapshotSequence` as the minimum required projector sequence from `projection_state`.
@@ -138,16 +171,21 @@ Work units:
- Validate replay handoff contract: snapshot sequence -> replay from `fromSequenceExclusive`.
Deliverables:
- `orchestration.getSnapshot` and `orchestration.getTurnDiff` served from DB projections/blob store.
Breakage allowed:
- Provider runtime persistence may still be partially legacy until step 8.
Exit criteria:
- No orchestration read RPC depends on legacy tables or in-memory-only state.
## 8. Migrate provider runtime persistence to canonical table
Work units:
- Create repository/service for `provider_session_runtime`.
- Update adapter/session manager to persist runtime/resume cursor in new table.
- Ensure domain-visible session state still flows through orchestration events to `projection_thread_sessions`.
@@ -155,16 +193,21 @@ Work units:
- Verify restart/resume path reads runtime state from canonical table only.
Deliverables:
- Provider runtime state entirely backed by `provider_session_runtime`.
Breakage allowed:
- Some legacy interfaces may still exist but should be disconnected.
Exit criteria:
- Runtime restore no longer reads/writes legacy provider session persistence.
## 9. Remove old cruft aggressively
Work units:
- Delete legacy repositories/services that map to removed tables.
- Remove dead migration imports and obsolete persistence service interfaces.
- Remove compatibility code paths that translate legacy row shapes.
@@ -172,16 +215,21 @@ Work units:
- Update internal docs/comments to reference canonical projection/event model only.
Deliverables:
- Legacy persistence and translation layers removed from active codebase.
Breakage allowed:
- Temporary compile failures acceptable while deletion/refactor is in progress.
Exit criteria:
- No production code path references deleted legacy tables/services.
## 10. Final verification gate (first point where green is required)
Work units:
- Add migration tests that assert canonical tables, columns, constraints, and indexes.
- Add event store tests for envelope persistence, metadata, actor kind, and replay.
- Add receipt idempotency tests for accept/reject/duplicate paths.
@@ -192,10 +240,13 @@ Work units:
- Run project lint/typecheck/tests and fix failures.
Deliverables:
- Green checks with canonical schema + persistence model in place.
Breakage allowed:
- None at end of step.
Exit criteria:
- SPEC `7.1`-`7.4` requirements satisfied and validated by tests.
+32
View File
@@ -1,6 +1,7 @@
# SPEC Contract Matrix (Sections 7.1-7.4)
Status legend:
- `required`: requirement acknowledged, no current implementation claim yet.
- `implemented`: requirement currently satisfied in code + schema.
- `to-replace`: partial/misaligned implementation exists and must be replaced.
@@ -9,6 +10,7 @@ Status legend:
## 7.1 Write-Side Persisted Tables
### W1
- Spec ref: `7.1.1 orchestration_events`
- Requirement: append-only event store with canonical envelope columns.
- SQL contract:
@@ -32,6 +34,7 @@ Status legend:
- Notes: current migration/table lacks `stream_id`, `stream_version`, `causation_event_id`, `correlation_id`, `actor_kind`, `metadata_json`.
### W2
- Spec ref: `7.1.2 orchestration_command_receipts`
- Requirement: command idempotency + ack replay receipts table.
- SQL contract:
@@ -49,6 +52,7 @@ Status legend:
- Notes: missing table and missing idempotency flow.
### W3
- Spec ref: `7.1.3 checkpoint_diff_blobs`
- Requirement: store large plaintext diffs separate from checkpoint summaries.
- SQL contract:
@@ -65,6 +69,7 @@ Status legend:
- Notes: no canonical diff blob table yet.
### W4
- Spec ref: `7.1.4 provider_session_runtime`
- Requirement: server-internal provider runtime/resume state.
- SQL contract:
@@ -86,6 +91,7 @@ Status legend:
## 7.2 Canonical Persisted Event Schema
### E1
- Spec ref: `7.2 OrchestrationPersistedEventSchema`
- Requirement: full typed persisted event envelope in shared contracts.
- SQL contract: envelope fields in W1 must map 1:1 to contracts schema.
@@ -96,6 +102,7 @@ Status legend:
- Notes: contract schema exists; DB + store mapping still incomplete.
### E2
- Spec ref: `7.2 Rules/payload discriminated by eventType`
- Requirement: `payload` validation keyed by `eventType`.
- SQL contract: `event_type` drives payload decode schema; invalid combinations rejected.
@@ -106,6 +113,7 @@ Status legend:
- Notes: decode is present but DB does not persist full envelope columns.
### E3
- Spec ref: `7.2 Rules/provider ids scope`
- Requirement: provider ids live in metadata/provider payload, not as thread identity replacement.
- SQL contract: provider fields persisted inside `metadata_json`; `stream_id` remains project/thread id.
@@ -116,6 +124,7 @@ Status legend:
- Notes: metadata plumbing is incomplete in persistence path.
### E4
- Spec ref: `7.2 Rules/streamVersion concurrency guard`
- Requirement: stream version monotonic per aggregate stream; enforced on write.
- SQL contract: `stream_version INTEGER NOT NULL` + uniqueness/invariant enforcement per stream.
@@ -128,6 +137,7 @@ Status legend:
## 7.3 Required Projected Tables (Read Models)
### P1
- Spec ref: `7.3.1 projection_projects`
- Requirement: persisted project projection table.
- SQL contract:
@@ -145,6 +155,7 @@ Status legend:
- Notes: legacy `projects` table is separate concept and should be removed from orchestration model.
### P2
- Spec ref: `7.3.2 projection_threads`
- Requirement: persisted thread projection table.
- SQL contract:
@@ -165,6 +176,7 @@ Status legend:
- Notes: missing table and projector writes.
### P3
- Spec ref: `7.3.3 projection_thread_messages`
- Requirement: persisted thread message projection table.
- SQL contract:
@@ -183,6 +195,7 @@ Status legend:
- Notes: missing table and message projection writes.
### P4
- Spec ref: `7.3.4 projection_thread_activities`
- Requirement: persisted thread activity projection table.
- SQL contract:
@@ -201,6 +214,7 @@ Status legend:
- Notes: no canonical activity projection persistence.
### P5
- Spec ref: `7.3.5 projection_thread_sessions`
- Requirement: persisted thread session projection table.
- SQL contract:
@@ -219,6 +233,7 @@ Status legend:
- Notes: current provider session table is not this domain projection.
### P6
- Spec ref: `7.3.6 projection_thread_turns`
- Requirement: persisted thread turn projection table.
- SQL contract:
@@ -237,6 +252,7 @@ Status legend:
- Notes: missing table and projection logic.
### P7
- Spec ref: `7.3.7 projection_checkpoints`
- Requirement: persisted checkpoint summary projection table.
- SQL contract:
@@ -256,6 +272,7 @@ Status legend:
- Notes: current table semantics do not match canonical checkpoint projection schema.
### P8
- Spec ref: `7.3.8 projection_pending_approvals`
- Requirement: persisted pending-approval projection table.
- SQL contract:
@@ -273,6 +290,7 @@ Status legend:
- Notes: missing table and projection logic.
### P9
- Spec ref: `7.3.9 projection_state`
- Requirement: projector progress tracking table.
- SQL contract:
@@ -286,6 +304,7 @@ Status legend:
- Notes: missing table and projector bookkeeping.
### P10
- Spec ref: `7.3 Projection consistency rules`
- Requirement: projector row updates and `projection_state` update must be atomic per event.
- SQL contract: per-projector transaction boundary covering both projection write and state update.
@@ -296,6 +315,7 @@ Status legend:
- Notes: requires transactional projection executor.
### P11
- Spec ref: `7.3 Optional debug field`
- Requirement: `lastEventSequence` on projection rows is optional and not required for correctness.
- SQL contract: optional; not required in baseline schema.
@@ -308,6 +328,7 @@ Status legend:
## 7.4 Snapshot and RPC Requirements
### R1
- Spec ref: `7.4.1`
- Requirement: `orchestration.getSnapshot` fully served from projection tables and returns `snapshotSequence`.
- SQL contract: snapshot query joins/reads only `projection_*` + `projection_state`.
@@ -318,6 +339,7 @@ Status legend:
- Notes: current in-memory read model path must be removed for SPEC compliance.
### R2
- Spec ref: `7.4.2`
- Requirement: snapshot `projects[]` source is `projection_projects`.
- SQL contract: `projects` collection assembled from `projection_projects` rows.
@@ -328,6 +350,7 @@ Status legend:
- Notes: no DB project projection reader exists yet.
### R3
- Spec ref: `7.4.3`
- Requirement: thread snapshot `checkpoints[]` source is `projection_checkpoints` with required fields.
- SQL contract: fields `turnId`, `completedAt`, `status`, `files[]`, `checkpointRef`, optional `assistantMessageId`, `checkpointTurnCount`.
@@ -338,6 +361,7 @@ Status legend:
- Notes: canonical projection table and reader not implemented.
### R4
- Spec ref: `7.4.4`
- Requirement: no `listCheckpoints` orchestration RPC; list in snapshot + full diff via `getTurnDiff` from diff blobs.
- SQL contract: `getTurnDiff` reads `checkpoint_diff_blobs` only.
@@ -348,6 +372,7 @@ Status legend:
- Notes: current checkpoint repository is not canonical source.
### R5
- Spec ref: `7.4.5`
- Requirement: client acts on `ThreadId`; server resolves provider session via `projection_thread_sessions`.
- SQL contract: session lookup by `thread_id` from projection table.
@@ -358,6 +383,7 @@ Status legend:
- Notes: remove provider-session-as-routing-key behavior.
### R6
- Spec ref: `7.4.6`
- Requirement: `snapshotSequence` derived from `projection_state` minimum over dependent projectors.
- SQL contract: `MIN(last_applied_sequence)` across required projector keys.
@@ -368,6 +394,7 @@ Status legend:
- Notes: must move from in-memory sequence to DB projection-state semantics.
### R7
- Spec ref: `7.4.7`
- Requirement: snapshot/replay handoff has no gap (`getSnapshot` -> subscribe from snapshot sequence).
- SQL contract: read consistency strategy guaranteeing no missing events between snapshot visibility and replay start.
@@ -380,22 +407,27 @@ Status legend:
## Ambiguous/Interpretation Decisions (tracked upfront)
### A1
- Topic: `orchestration_events.stream_id` vs event runtime `aggregateId` naming.
- Decision: persist canonical DB column name `stream_id`; map to runtime `aggregateId` where needed in decider/projector code.
### A2
- Topic: JSON column typing in SQLite for `payload`, `metadata`, projection payload/files, runtime cursor/payload.
- Decision: store as `TEXT` JSON with strict encode/decode schemas at boundaries.
### A3
- Topic: `snapshotSequence` dependency set for min-sequence computation.
- Decision: include all projectors used to construct snapshot payload (`projects`, `threads`, `messages`, `activities`, `sessions`, `turns`, `checkpoints`, `pending_approvals`).
### A4
- Topic: no-gap handoff mechanism in `7.4.7`.
- Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`.
## Checklist Completeness Statement
- Coverage scope: `SPEC.md` sections `7.1`, `7.2`, `7.3`, `7.4`.
- Requirement rows present: `W1-W4`, `E1-E4`, `P1-P11`, `R1-R7`.
- Unclassified rows: `0`.
+4
View File
@@ -8,6 +8,10 @@ You can still open an issue or PR, but please do so knowing there is a high chan
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
PRs are automatically labeled with a `vouch:*` trust status.
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.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.5",
"version": "0.0.9",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+15 -7
View File
@@ -7,7 +7,11 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
const devServerUrl = `http://localhost:${port}`;
const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];
const requiredFiles = [
"dist-electron/main.js",
"dist-electron/preload.js",
"../server/dist/index.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
@@ -148,13 +152,17 @@ function scheduleRestart() {
function startWatchers() {
for (const { directory, files } of watchedDirectories) {
const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
return;
}
const watcher = watch(
join(desktopDir, directory),
{ persistent: true },
(_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
return;
}
scheduleRestart();
});
scheduleRestart();
},
);
watchers.push(watcher);
}
+122 -25
View File
@@ -15,10 +15,7 @@ import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
import {
getAutoUpdateDisabledReason,
shouldBroadcastDownloadProgress,
} from "./updateState";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
@@ -31,6 +28,7 @@ import {
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
fixPath();
@@ -50,6 +48,8 @@ const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
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_DISPLAY_LENGTH = 12;
const LOG_DIR = Path.join(STATE_DIR, "logs");
@@ -78,7 +78,13 @@ let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
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 {
return new Date().toISOString();
@@ -112,6 +118,25 @@ function formatErrorMessage(error: unknown): string {
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 writeDesktopStreamChunk(
streamName: "stdout" | "stderr",
chunk: unknown,
@@ -574,6 +599,34 @@ function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
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 {
app.setName(APP_DISPLAY_NAME);
const commitHash = resolveAboutCommitHash();
@@ -646,7 +699,9 @@ async function checkForUpdates(reason: string): Promise<void> {
await autoUpdater.checkForUpdates();
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
setUpdateState(reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()));
setUpdateState(
reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
);
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
} finally {
updateCheckInFlight = false;
@@ -659,6 +714,7 @@ async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed
}
updateDownloadInFlight = true;
setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState));
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
console.info("[desktop-updater] Downloading update...");
try {
@@ -697,7 +753,7 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
function configureAutoUpdater(): void {
const enabled = shouldEnableAutoUpdates();
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion()),
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled,
status: enabled ? "idle" : "disabled",
});
@@ -707,9 +763,7 @@ function configureAutoUpdater(): void {
updaterConfigured = true;
const githubToken =
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() ||
process.env.GH_TOKEN?.trim() ||
"";
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
if (githubToken) {
// When a token is provided, re-configure the feed with `private: true` so
// electron-updater uses the GitHub API (api.github.com) instead of the
@@ -731,13 +785,26 @@ function configureAutoUpdater(): void {
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
autoUpdater.allowDowngrade = false;
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
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", () => {
console.info("[desktop-updater] Looking for updates...");
});
autoUpdater.on("update-available", (info) => {
setUpdateState(reduceDesktopUpdateStateOnUpdateAvailable(updateState, info.version, new Date().toISOString()));
setUpdateState(
reduceDesktopUpdateStateOnUpdateAvailable(
updateState,
info.version,
new Date().toISOString(),
),
);
lastLoggedDownloadMilestone = -1;
console.info(`[desktop-updater] Update available: ${info.version}`);
});
@@ -1033,23 +1100,13 @@ function registerIpcHandlers(): void {
ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
if (typeof rawUrl !== "string" || rawUrl.length === 0) {
return false;
}
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return false;
}
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
const externalUrl = getSafeExternalUrl(rawUrl);
if (!externalUrl) {
return false;
}
try {
await shell.openExternal(parsedUrl.toString());
await shell.openExternal(externalUrl);
return true;
} catch {
return false;
@@ -1114,7 +1171,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) => {
event.preventDefault();
window.setTitle(APP_DISPLAY_NAME);
@@ -1143,6 +1235,11 @@ function createWindow(): BrowserWindow {
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();
async function bootstrap(): Promise<void> {
+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,
} from "./updateMachine";
const runtimeInfo = {
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
} as const;
describe("updateMachine", () => {
it("clears transient errors when a check starts", () => {
const state = reduceDesktopUpdateStateOnCheckStart(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "error",
message: "network",
@@ -36,7 +42,7 @@ describe("updateMachine", () => {
it("records a check failure without exposing an action", () => {
const state = reduceDesktopUpdateStateOnCheckFailure(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "checking",
},
@@ -52,7 +58,7 @@ describe("updateMachine", () => {
it("preserves available version on download failure for retry", () => {
const state = reduceDesktopUpdateStateOnDownloadFailure(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "downloading",
availableVersion: "1.1.0",
@@ -70,14 +76,17 @@ describe("updateMachine", () => {
it("transitions to downloaded and then preserves install retry state", () => {
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "downloading",
availableVersion: "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.downloadedVersion).toBe("1.1.0");
@@ -89,7 +98,7 @@ describe("updateMachine", () => {
it("clears stale download state when no update is available", () => {
const state = reduceDesktopUpdateStateOnNoUpdate(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
status: "error",
availableVersion: "1.1.0",
@@ -111,7 +120,7 @@ describe("updateMachine", () => {
it("tracks available, download start, and progress cleanly", () => {
const available = reduceDesktopUpdateStateOnUpdateAvailable(
{
...createInitialDesktopUpdateState("1.0.0"),
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
enabled: true,
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";
export function createInitialDesktopUpdateState(currentVersion: string): DesktopUpdateState {
export function createInitialDesktopUpdateState(
currentVersion: string,
runtimeInfo: DesktopRuntimeInfo,
): DesktopUpdateState {
return {
enabled: false,
status: "disabled",
currentVersion,
hostArch: runtimeInfo.hostArch,
appArch: runtimeInfo.appArch,
runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
@@ -152,4 +158,3 @@ export function reduceDesktopUpdateStateOnInstallFailure(
canRetry: true,
};
}
+3
View File
@@ -12,6 +12,9 @@ const baseState: DesktopUpdateState = {
enabled: true,
status: "idle",
currentVersion: "1.0.0",
hostArch: "x64",
appArch: "x64",
runningUnderArm64Translation: false,
availableVersion: null,
downloadedVersion: null,
downloadPercent: null,
+1 -3
View File
@@ -77,12 +77,10 @@
const ua = navigator.userAgent;
if (/Win/i.test(ua)) return { os: "win", label: "Download for Windows" };
if (/Mac/i.test(ua)) {
const isArm =
/arm|aarch/i.test(navigator.platform ?? "") || ua.includes("ARM");
return {
os: "mac",
label: `Download for macOS`,
arch: isArm ? "arm64" : "x64",
arch: "arm64",
};
}
if (/Linux/i.test(ua)) return { os: "linux", label: "Download for Linux" };
@@ -72,10 +72,9 @@ function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupt
return "completed";
}
function mapRequestType(requestKind: unknown):
| "command_execution_approval"
| "file_change_approval"
| "unknown" {
function mapRequestType(
requestKind: unknown,
): "command_execution_approval" | "file_change_approval" | "unknown" {
if (requestKind === "command") {
return "command_execution_approval";
}
@@ -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) =>
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== provider) {
return yield* new ProviderAdapterValidationError({
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== provider) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "startSession",
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
});
}
sessionCount += 1;
const threadId = input.threadId;
const createdAt = nowIso();
const session: ProviderSession = {
provider,
operation: "startSession",
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
});
}
sessionCount += 1;
const threadId = input.threadId;
const createdAt = nowIso();
const session: ProviderSession = {
provider,
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
cwd: input.cwd,
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
createdAt,
updatedAt: createdAt,
};
sessions.set(threadId, {
session,
snapshot: {
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
turns: [],
},
turnCount: 0,
queuedResponses: queuedResponsesForNextSession.splice(0),
rollbackCalls: [],
cwd: input.cwd,
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
createdAt,
updatedAt: createdAt,
};
sessions.set(threadId, {
session,
snapshot: {
threadId,
turns: [],
},
turnCount: 0,
queuedResponses: queuedResponsesForNextSession.splice(0),
rollbackCalls: [],
});
return session;
});
return session;
});
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
Effect.gen(function* () {
const state = sessions.get(input.threadId);
if (!state) {
return yield* missingSessionEffect(provider, input.threadId);
}
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
Effect.gen(function* () {
const state = sessions.get(input.threadId);
if (!state) {
return yield* missingSessionEffect(provider, input.threadId);
}
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
const response = state.queuedResponses.shift();
if (!response) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "sendTurn",
issue: `No queued turn response for thread ${input.threadId}.`,
});
}
const response = state.queuedResponses.shift();
if (!response) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "sendTurn",
issue: `No queued turn response for thread ${input.threadId}.`,
});
}
const assistantDeltas: string[] = [];
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: randomUUID(),
provider,
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
createdAt: nowIso(),
};
rawEvent.threadId = state.snapshot.threadId;
if (Object.hasOwn(rawEvent, "turnId")) {
rawEvent.turnId = turnId;
}
const assistantDeltas: string[] = [];
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: randomUUID(),
provider,
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
createdAt: nowIso(),
const runtimeEvent = normalizeFixtureEvent(rawEvent);
const runtimeType = (runtimeEvent as { type: string }).type;
if (runtimeType === "content.delta") {
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
if (typeof payload?.delta === "string") {
assistantDeltas.push(payload.delta);
}
} else if (runtimeType === "message.delta") {
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
if (typeof legacyDelta === "string") {
assistantDeltas.push(legacyDelta);
}
}
if (runtimeEvent.type === "turn.completed") {
deferredTurnCompletedEvents.push(runtimeEvent);
continue;
}
yield* emit(runtimeEvent);
}
if (response.mutateWorkspace && state.session.cwd) {
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
}
const userItem = {
type: "userMessage",
content: [{ type: "text", text: input.input }],
} as const;
const assistantText = assistantDeltas.join("");
const nextItems: Array<unknown> =
assistantText.length > 0
? [userItem, { type: "agentMessage", text: assistantText }]
: [userItem];
const nextTurn: ProviderThreadTurnSnapshot = {
id: turnId,
items: nextItems,
};
rawEvent.threadId = state.snapshot.threadId;
if (Object.hasOwn(rawEvent, "turnId")) {
rawEvent.turnId = turnId;
}
const runtimeEvent = normalizeFixtureEvent(rawEvent);
const runtimeType = (runtimeEvent as { type: string }).type;
if (runtimeType === "content.delta") {
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
if (typeof payload?.delta === "string") {
assistantDeltas.push(payload.delta);
}
} else if (runtimeType === "message.delta") {
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
if (typeof legacyDelta === "string") {
assistantDeltas.push(legacyDelta);
state.snapshot = {
threadId: state.snapshot.threadId,
turns: [...state.snapshot.turns, nextTurn],
};
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.makeUnsafe(randomUUID()),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
turnId,
payload: {
state: "completed",
},
});
} else {
for (const completedEvent of deferredTurnCompletedEvents) {
yield* emit(completedEvent);
}
}
if (runtimeEvent.type === "turn.completed") {
deferredTurnCompletedEvents.push(runtimeEvent);
continue;
}
yield* emit(runtimeEvent);
}
if (response.mutateWorkspace && state.session.cwd) {
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
}
const userItem = {
type: "userMessage",
content: [{ type: "text", text: input.input }],
} as const;
const assistantText = assistantDeltas.join("");
const nextItems: Array<unknown> =
assistantText.length > 0
? [userItem, { type: "agentMessage", text: assistantText }]
: [userItem];
const nextTurn: ProviderThreadTurnSnapshot = {
id: turnId,
items: nextItems,
};
state.snapshot = {
threadId: state.snapshot.threadId,
turns: [...state.snapshot.turns, nextTurn],
};
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.makeUnsafe(randomUUID()),
provider,
createdAt: nowIso(),
return {
threadId: state.snapshot.threadId,
turnId,
payload: {
state: "completed",
},
});
} else {
for (const completedEvent of deferredTurnCompletedEvents) {
yield* emit(completedEvent);
}
} satisfies ProviderTurnStartResult;
});
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
threadId,
turnId,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = interruptCallsBySession.get(threadId) ?? [];
existing.push(turnId);
interruptCallsBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = approvalResponsesBySession.get(threadId) ?? [];
existing.push({
threadId,
requestId,
decision,
});
approvalResponsesBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
threadId,
numTurns,
) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
return Effect.fail(
new ProviderAdapterValidationError({
provider,
operation: "rollbackThread",
issue: "numTurns must be an integer between 0 and current turn count.",
}),
);
}
return {
threadId: state.snapshot.threadId,
turnId,
} satisfies ProviderTurnStartResult;
});
return Effect.sync(() => {
state.rollbackCalls.push(numTurns);
state.snapshot = {
threadId: state.snapshot.threadId,
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
};
state.turnCount = state.snapshot.turns.length;
return state.snapshot;
});
};
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
threadId,
turnId,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = interruptCallsBySession.get(threadId) ?? [];
existing.push(turnId);
interruptCallsBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
Effect.sync(() => {
sessions.clear();
});
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = approvalResponsesBySession.get(threadId) ?? [];
existing.push({
threadId,
requestId,
decision,
});
approvalResponsesBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
threadId,
numTurns,
) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
return Effect.fail(
new ProviderAdapterValidationError({
provider,
operation: "rollbackThread",
issue: "numTurns must be an integer between 0 and current turn count.",
}),
const queueTurnResponse = (
threadId: ThreadId,
response: TestTurnResponse,
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
Effect.sync(() => sessions.get(threadId)).pipe(
Effect.flatMap((state) =>
state
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(provider, threadId)),
),
);
}
return Effect.sync(() => {
state.rollbackCalls.push(numTurns);
state.snapshot = {
threadId: state.snapshot.threadId,
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
};
state.turnCount = state.snapshot.turns.length;
return state.snapshot;
});
};
const queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
Effect.sync(() => {
sessions.clear();
});
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
const state = sessions.get(threadId);
if (!state) {
return [];
}
return [...state.rollbackCalls];
};
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const getStartCount = (): number => sessionCount;
const queueTurnResponse = (
threadId: ThreadId,
response: TestTurnResponse,
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
Effect.sync(() => sessions.get(threadId)).pipe(
Effect.flatMap((state) =>
state
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(provider, threadId)),
),
);
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
const calls = interruptCallsBySession.get(threadId);
if (!calls) {
return [];
}
return [...calls];
};
const queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
Array.from(sessions.values(), (state) => state.session.threadId);
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
const state = sessions.get(threadId);
if (!state) {
return [];
}
return [...state.rollbackCalls];
};
const getApprovalResponses = (
threadId: ThreadId,
): ReadonlyArray<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}> => {
const responses = approvalResponsesBySession.get(threadId);
if (!responses) {
return [];
}
return [...responses];
};
const getStartCount = (): number => sessionCount;
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
const calls = interruptCallsBySession.get(threadId);
if (!calls) {
return [];
}
return [...calls];
};
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
Array.from(sessions.values(), (state) => state.session.threadId);
const getApprovalResponses = (
threadId: ThreadId,
): ReadonlyArray<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}> => {
const responses = approvalResponsesBySession.get(threadId);
if (!responses) {
return [];
}
return [...responses];
};
return {
adapter,
provider,
queueTurnResponse,
queueTurnResponseForNextSession,
getStartCount,
getRollbackCalls,
getInterruptCalls,
listActiveSessionIds,
getApprovalResponses,
} satisfies TestProviderAdapterHarness;
});
return {
adapter,
provider,
queueTurnResponse,
queueTurnResponseForNextSession,
getStartCount,
getRollbackCalls,
getInterruptCalls,
listActiveSessionIds,
getApprovalResponses,
} satisfies TestProviderAdapterHarness;
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.5",
"version": "0.0.9",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
+7 -4
View File
@@ -6,7 +6,10 @@ import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { DEVELOPMENT_ICON_OVERRIDES, PUBLISH_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts";
import {
DEVELOPMENT_ICON_OVERRIDES,
PUBLISH_ICON_OVERRIDES,
} from "../../../scripts/lib/brand-assets.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
@@ -132,6 +135,7 @@ const buildCmd = Command.make(
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun tsdown`,
);
@@ -226,6 +230,7 @@ const publishCmd = Command.make(
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
}),
);
@@ -235,9 +240,7 @@ const publishCmd = Command.make(
Effect.gen(function* () {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(
`[cli] Failed to restore publish icon overrides: ${String(error)}`,
),
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
),
);
yield* fs.rename(backupPath, packageJsonPath);
+1 -2
View File
@@ -12,8 +12,7 @@ import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts"
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN =
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
const ATTACHMENT_ID_PATTERN = new RegExp(
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
"i",
+60 -66
View File
@@ -749,88 +749,82 @@ describe("respondToUserInput", () => {
});
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
it(
"keeps prior thread history when resuming with a changed runtime mode",
async () => {
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
const manager = new CodexAppServerManager();
const manager = new CodexAppServerManager();
try {
const firstSession = await manager.startSession({
threadId: asThreadId("thread-live"),
provider: "codex",
cwd: workspaceDir,
runtimeMode: "full-access",
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH
? { binaryPath: process.env.CODEX_BINARY_PATH }
: {}),
...(process.env.CODEX_HOME_PATH
? { homePath: process.env.CODEX_HOME_PATH }
: {}),
},
try {
const firstSession = await manager.startSession({
threadId: asThreadId("thread-live"),
provider: "codex",
cwd: workspaceDir,
runtimeMode: "full-access",
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
},
});
},
});
const firstTurn = await manager.sendTurn({
threadId: firstSession.threadId,
input: `Reply with exactly the word ALPHA ${randomUUID()}`,
});
const firstTurn = await manager.sendTurn({
threadId: firstSession.threadId,
input: `Reply with exactly the word ALPHA ${randomUUID()}`,
});
expect(firstTurn.threadId).toBe(firstSession.threadId);
expect(firstTurn.threadId).toBe(firstSession.threadId);
await vi.waitFor(async () => {
await vi.waitFor(
async () => {
const snapshot = await manager.readThread(firstSession.threadId);
expect(snapshot.turns.length).toBeGreaterThan(0);
}, { timeout: 120_000, interval: 1_000 });
},
{ timeout: 120_000, interval: 1_000 },
);
const firstSnapshot = await manager.readThread(firstSession.threadId);
const originalThreadId = firstSnapshot.threadId;
const originalTurnCount = firstSnapshot.turns.length;
const firstSnapshot = await manager.readThread(firstSession.threadId);
const originalThreadId = firstSnapshot.threadId;
const originalTurnCount = firstSnapshot.turns.length;
manager.stopSession(firstSession.threadId);
manager.stopSession(firstSession.threadId);
const resumedSession = await manager.startSession({
threadId: firstSession.threadId,
provider: "codex",
cwd: workspaceDir,
runtimeMode: "approval-required",
resumeCursor: firstSession.resumeCursor,
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH
? { binaryPath: process.env.CODEX_BINARY_PATH }
: {}),
...(process.env.CODEX_HOME_PATH
? { homePath: process.env.CODEX_HOME_PATH }
: {}),
},
const resumedSession = await manager.startSession({
threadId: firstSession.threadId,
provider: "codex",
cwd: workspaceDir,
runtimeMode: "approval-required",
resumeCursor: firstSession.resumeCursor,
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
},
});
},
});
expect(resumedSession.threadId).toBe(originalThreadId);
expect(resumedSession.threadId).toBe(originalThreadId);
const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
await manager.sendTurn({
threadId: resumedSession.threadId,
input: `Reply with exactly the word BETA ${randomUUID()}`,
});
await manager.sendTurn({
threadId: resumedSession.threadId,
input: `Reply with exactly the word BETA ${randomUUID()}`,
});
await vi.waitFor(async () => {
await vi.waitFor(
async () => {
const snapshot = await manager.readThread(resumedSession.threadId);
expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);
}, { timeout: 120_000, interval: 1_000 });
} finally {
manager.stopAll();
rmSync(workspaceDir, { recursive: true, force: true });
}
},
180_000,
);
},
{ timeout: 120_000, interval: 1_000 },
);
} finally {
manager.stopAll();
rmSync(workspaceDir, { recursive: true, force: true });
}
}, 180_000);
});
@@ -363,8 +363,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const attachmentId =
`thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello"));
@@ -392,9 +391,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
}),
),
),
Effect.ensuring(
fs.remove(imagePath).pipe(Effect.catch(() => Effect.void)),
),
Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
);
expect(generated.branch).toBe("fix/ui-regression");
+110 -29
View File
@@ -105,6 +105,10 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
readConfigValue: (cwd, key) => core.readConfigValue(cwd, key),
listBranches: (input) => core.listBranches(input),
createWorktree: (input) => core.createWorktree(input),
fetchPullRequestBranch: (input) => core.fetchPullRequestBranch(input),
ensureRemote: (input) => core.ensureRemote(input),
fetchRemoteBranch: (input) => core.fetchRemoteBranch(input),
setBranchUpstream: (input) => core.setBranchUpstream(input),
removeWorktree: (input) => core.removeWorktree(input),
renameBranch: (input) => core.renameBranch(input),
createBranch: (input) => core.createBranch(input),
@@ -149,6 +153,13 @@ function createGitWorktree(input: Parameters<GitCoreShape["createWorktree"]>[0])
});
}
function fetchGitPullRequestBranch(input: Parameters<GitCoreShape["fetchPullRequestBranch"]>[0]) {
return Effect.gen(function* () {
const core = yield* GitCore;
return yield* core.fetchPullRequestBranch(input);
});
}
function removeGitWorktree(input: Parameters<GitCoreShape["removeWorktree"]>[0]) {
return Effect.gen(function* () {
const core = yield* GitCore;
@@ -174,7 +185,7 @@ function pullGitBranch({ cwd }: { cwd: string }) {
function initRepoWithCommit(
cwd: string,
): Effect.Effect<
void,
{ initialBranch: string },
GitCommandError | PlatformError.PlatformError,
GitCore | GitService | FileSystem.FileSystem
> {
@@ -185,6 +196,8 @@ function initRepoWithCommit(
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
yield* git(cwd, ["add", "."]);
yield* git(cwd, ["commit", "-m", "initial commit"]);
const initialBranch = yield* git(cwd, ["branch", "--show-current"]);
return { initialBranch };
});
}
@@ -426,7 +439,9 @@ it.layer(TestLayer)("git integration", (it) => {
true,
);
expect(
result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),
result.branches.some(
(branch) => branch.name === "feature/local-only" && !branch.isRemote,
),
).toBe(true);
expect(
result.branches.some(
@@ -689,29 +704,27 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"does not silently checkout a local branch when a remote ref no longer exists",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
it.effect("does not silently checkout a local branch when a remote ref no longer exists", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: source, branch: "feature" });
yield* createGitBranch({ cwd: source, branch: "feature" });
const checkoutResult = yield* Effect.result(
checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
);
expect(checkoutResult._tag).toBe("Failure");
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
}),
const checkoutResult = yield* Effect.result(
checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
);
expect(checkoutResult._tag).toBe("Failure");
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
}),
);
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
@@ -940,13 +953,7 @@ it.layer(TestLayer)("git integration", (it) => {
});
expect(renamed.branch).toBe("feature/new-name");
expect(renameArgs).toEqual([
"branch",
"-m",
"--",
"feature/old-name",
"feature/new-name",
]);
expect(renameArgs).toEqual(["branch", "-m", "--", "feature/old-name", "feature/new-name"]);
}),
);
});
@@ -1006,6 +1013,28 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("creates a worktree for an existing branch when newBranch is omitted", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* createGitBranch({ cwd: tmp, branch: "feature/existing-worktree" });
const wtPath = path.join(tmp, "wt-existing");
const result = yield* createGitWorktree({
cwd: tmp,
branch: "feature/existing-worktree",
path: wtPath,
});
expect(result.worktree.path).toBe(wtPath);
expect(result.worktree.branch).toBe("feature/existing-worktree");
const branchOutput = yield* git(wtPath, ["branch", "--show-current"]);
expect(branchOutput).toBe("feature/existing-worktree");
yield* removeGitWorktree({ cwd: tmp, path: wtPath });
}),
);
it.effect("throws when new branch name already exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1168,6 +1197,37 @@ it.layer(TestLayer)("git integration", (it) => {
);
});
describe("fetchPullRequestBranch", () => {
it.effect("fetches a GitHub pull request ref into a local branch without checkout", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(tmp);
const remoteDir = yield* makeTmpDir("git-remote-");
yield* git(remoteDir, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remoteDir]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
yield* git(tmp, ["checkout", "-b", "feature/pr-fetch"]);
yield* writeTextFile(path.join(tmp, "pr-fetch.txt"), "fetch me\n");
yield* git(tmp, ["add", "pr-fetch.txt"]);
yield* git(tmp, ["commit", "-m", "Add PR fetch branch"]);
yield* git(tmp, ["push", "-u", "origin", "feature/pr-fetch"]);
yield* git(tmp, ["push", "origin", "HEAD:refs/pull/55/head"]);
yield* git(tmp, ["checkout", initialBranch]);
yield* fetchGitPullRequestBranch({
cwd: tmp,
prNumber: 55,
branch: "feature/pr-fetch",
});
const localBranches = yield* git(tmp, ["branch", "--list", "feature/pr-fetch"]);
expect(localBranches).toContain("feature/pr-fetch");
const currentBranch = yield* git(tmp, ["branch", "--show-current"]);
expect(currentBranch).toBe(initialBranch);
}),
);
});
// ── Full flow: thread switching simulation ──
describe("full flow: thread switching (checkout toggling)", () => {
@@ -1257,6 +1317,27 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"reuses an existing remote when the target URL only differs by a trailing slash after .git",
() =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* git(tmp, ["remote", "add", "origin", "[email protected]:pingdotgg/t3code.git"]);
const remoteName = yield* core.ensureRemote({
cwd: tmp,
preferredName: "origin",
url: "[email protected]:pingdotgg/t3code.git/",
});
expect(remoteName).toBe("origin");
expect((yield* git(tmp, ["remote"])).split("\n").filter(Boolean)).toEqual(["origin"]);
}),
);
it.effect("reports status details and dirty state", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
+148 -10
View File
@@ -100,6 +100,38 @@ function parseRemoteNames(stdout: string): ReadonlyArray<string> {
.toSorted((a, b) => b.length - a.length);
}
function sanitizeRemoteName(value: string): string {
const sanitized = value
.trim()
.replace(/[^A-Za-z0-9._-]+/g, "-")
.replace(/^-+|-+$/g, "");
return sanitized.length > 0 ? sanitized : "fork";
}
function normalizeRemoteUrl(value: string): string {
return value
.trim()
.replace(/\/+$/g, "")
.replace(/\.git$/i, "")
.toLowerCase();
}
function parseRemoteFetchUrls(stdout: string): Map<string, string> {
const remotes = new Map<string, string>();
for (const line of stdout.split("\n")) {
const trimmed = line.trim();
if (trimmed.length === 0) continue;
const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
if (!match) continue;
const [, remoteName = "", remoteUrl = "", direction = ""] = match;
if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) {
continue;
}
remotes.set(remoteName, remoteUrl);
}
return remotes;
}
function parseRemoteRefWithRemoteNames(
branchName: string,
remoteNames: ReadonlyArray<string>,
@@ -418,6 +450,61 @@ const makeGitCore = Effect.gen(function* () {
allowNonZeroExit: true,
}).pipe(Effect.map((result) => result.code === 0));
const listRemoteNames = (cwd: string): Effect.Effect<ReadonlyArray<string>, GitCommandError> =>
runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
Effect.map((stdout) => parseRemoteNames(stdout).toReversed()),
);
const resolvePrimaryRemoteName = (cwd: string): Effect.Effect<string, GitCommandError> =>
Effect.gen(function* () {
if (yield* originRemoteExists(cwd)) {
return "origin";
}
const remotes = yield* listRemoteNames(cwd);
const [firstRemote] = remotes;
if (firstRemote) {
return firstRemote;
}
return yield* createGitCommandError(
"GitCore.resolvePrimaryRemoteName",
cwd,
["remote"],
"No git remote is configured for this repository.",
);
});
const ensureRemote: GitCoreShape["ensureRemote"] = (input) =>
Effect.gen(function* () {
const preferredName = sanitizeRemoteName(input.preferredName);
const normalizedTargetUrl = normalizeRemoteUrl(input.url);
const remoteFetchUrls = yield* runGitStdout(
"GitCore.ensureRemote.listRemoteUrls",
input.cwd,
["remote", "-v"],
).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));
for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) {
if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) {
return remoteName;
}
}
let remoteName = preferredName;
let suffix = 1;
while (remoteFetchUrls.has(remoteName)) {
remoteName = `${preferredName}-${suffix}`;
suffix += 1;
}
yield* runGit("GitCore.ensureRemote.add", input.cwd, [
"remote",
"add",
remoteName,
input.url,
]);
return remoteName;
});
const resolveBaseBranchForNoUpstream = (
cwd: string,
branch: string,
@@ -1015,29 +1102,76 @@ const makeGitCore = Effect.gen(function* () {
const createWorktree: GitCoreShape["createWorktree"] = (input) =>
Effect.gen(function* () {
const sanitizedBranch = input.newBranch.replace(/\//g, "-");
const targetBranch = input.newBranch ?? input.branch;
const sanitizedBranch = targetBranch.replace(/\//g, "-");
const repoName = path.basename(input.cwd);
const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
const worktreePath =
input.path ?? path.join(homeDir, ".t3", "worktrees", repoName, sanitizedBranch);
const args = input.newBranch
? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch]
: ["worktree", "add", worktreePath, input.branch];
yield* executeGit(
"GitCore.createWorktree",
input.cwd,
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
{
fallbackErrorMessage: "git worktree add failed",
},
);
yield* executeGit("GitCore.createWorktree", input.cwd, args, {
fallbackErrorMessage: "git worktree add failed",
});
return {
worktree: {
path: worktreePath,
branch: input.newBranch,
branch: targetBranch,
},
};
});
const fetchPullRequestBranch: GitCoreShape["fetchPullRequestBranch"] = (input) =>
Effect.gen(function* () {
const remoteName = yield* resolvePrimaryRemoteName(input.cwd);
yield* executeGit(
"GitCore.fetchPullRequestBranch",
input.cwd,
[
"fetch",
"--quiet",
"--no-tags",
remoteName,
`+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`,
],
{
fallbackErrorMessage: "git fetch pull request branch failed",
},
);
}).pipe(Effect.asVoid);
const fetchRemoteBranch: GitCoreShape["fetchRemoteBranch"] = (input) =>
Effect.gen(function* () {
yield* runGit("GitCore.fetchRemoteBranch.fetch", input.cwd, [
"fetch",
"--quiet",
"--no-tags",
input.remoteName,
`+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`,
]);
const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch);
const targetRef = `${input.remoteName}/${input.remoteBranch}`;
yield* runGit(
"GitCore.fetchRemoteBranch.materialize",
input.cwd,
localBranchAlreadyExists
? ["branch", "--force", input.localBranch, targetRef]
: ["branch", input.localBranch, targetRef],
);
}).pipe(Effect.asVoid);
const setBranchUpstream: GitCoreShape["setBranchUpstream"] = (input) =>
runGit("GitCore.setBranchUpstream", input.cwd, [
"branch",
"--set-upstream-to",
`${input.remoteName}/${input.remoteBranch}`,
input.branch,
]);
const removeWorktree: GitCoreShape["removeWorktree"] = (input) =>
Effect.gen(function* () {
const args = ["worktree", "remove"];
@@ -1197,6 +1331,10 @@ const makeGitCore = Effect.gen(function* () {
readConfigValue,
listBranches,
createWorktree,
fetchPullRequestBranch,
ensureRemote,
fetchRemoteBranch,
setBranchUpstream,
removeWorktree,
renameBranch,
createBranch,
@@ -0,0 +1,128 @@
import { assert, it } from "@effect/vitest";
import { Effect } from "effect";
import { afterEach, expect, vi } from "vitest";
vi.mock("../../processRunner", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../../processRunner";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { GitHubCliLive } from "./GitHubCli.ts";
const mockedRunProcess = vi.mocked(runProcess);
const layer = it.layer(GitHubCliLive);
afterEach(() => {
mockedRunProcess.mockReset();
});
layer("GitHubCliLive", (it) => {
it.effect("parses pull request view output", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: JSON.stringify({
number: 42,
title: "Add PR thread creation",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/pr-threads",
state: "OPEN",
mergedAt: null,
isCrossRepository: true,
headRepository: {
nameWithOwner: "octocat/codething-mvp",
},
headRepositoryOwner: {
login: "octocat",
},
}),
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "#42",
});
});
assert.deepStrictEqual(result, {
number: 42,
title: "Add PR thread creation",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/pr-threads",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
});
expect(mockedRunProcess).toHaveBeenCalledWith(
"gh",
[
"pr",
"view",
"#42",
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
expect.objectContaining({ cwd: "/repo" }),
);
}),
);
it.effect("reads repository clone URLs", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: JSON.stringify({
nameWithOwner: "octocat/codething-mvp",
url: "https://github.com/octocat/codething-mvp",
sshUrl: "[email protected]:octocat/codething-mvp.git",
}),
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.getRepositoryCloneUrls({
cwd: "/repo",
repository: "octocat/codething-mvp",
});
});
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/codething-mvp",
url: "https://github.com/octocat/codething-mvp",
sshUrl: "[email protected]:octocat/codething-mvp.git",
});
}),
);
it.effect("surfaces a friendly error when the pull request is not found", () =>
Effect.gen(function* () {
mockedRunProcess.mockRejectedValueOnce(
new Error(
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
),
);
const error = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "4888",
});
}).pipe(Effect.flip);
assert.equal(error.message.includes("Pull request not found"), true);
}),
);
});
+167 -65
View File
@@ -1,8 +1,14 @@
import { Effect, Layer } from "effect";
import { Effect, Layer, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { runProcess } from "../../processRunner";
import { GitHubCliError } from "../Errors.ts";
import { GitHubCli, type GitHubCliShape } from "../Services/GitHubCli.ts";
import {
GitHubCli,
type GitHubRepositoryCloneUrls,
type GitHubCliShape,
type GitHubPullRequestSummary,
} from "../Services/GitHubCli.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
@@ -30,6 +36,19 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
});
}
if (
lower.includes("could not resolve to a pullrequest") ||
lower.includes("repository.pullrequest") ||
lower.includes("no pull requests found for branch") ||
lower.includes("pull request not found")
) {
return new GitHubCliError({
operation,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
}
return new GitHubCliError({
operation,
detail: `GitHub CLI command failed: ${error.message}`,
@@ -44,59 +63,102 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
});
}
function parseOpenPullRequests(raw: string): ReadonlyArray<{
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}> {
const trimmed = raw.trim();
if (trimmed.length === 0) return [];
const parsed: unknown = JSON.parse(trimmed);
if (!Array.isArray(parsed)) {
throw new Error("GitHub CLI returned non-array JSON.");
function normalizePullRequestState(input: {
state?: string | null | undefined;
mergedAt?: string | null | undefined;
}): "open" | "closed" | "merged" {
const mergedAt = input.mergedAt;
const state = input.state;
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
return "merged";
}
const result: Array<{
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}> = [];
for (const entry of parsed) {
if (!entry || typeof entry !== "object") {
continue;
}
const record = entry as Record<string, unknown>;
const number = record.number;
const title = record.title;
const url = record.url;
const baseRefName = record.baseRefName;
const headRefName = record.headRefName;
if (
typeof number !== "number" ||
!Number.isInteger(number) ||
number <= 0 ||
typeof title !== "string" ||
typeof url !== "string" ||
typeof baseRefName !== "string" ||
typeof headRefName !== "string"
) {
continue;
}
result.push({
number,
title,
url,
baseRefName,
headRefName,
});
if (state === "CLOSED") {
return "closed";
}
return "open";
}
return result;
const RawGitHubPullRequestSchema = Schema.Struct({
number: PositiveInt,
title: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
baseRefName: TrimmedNonEmptyString,
headRefName: TrimmedNonEmptyString,
state: Schema.optional(Schema.NullOr(Schema.String)),
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
isCrossRepository: Schema.optional(Schema.Boolean),
headRepository: Schema.optional(
Schema.NullOr(
Schema.Struct({
nameWithOwner: Schema.String,
}),
),
),
headRepositoryOwner: Schema.optional(
Schema.NullOr(
Schema.Struct({
login: Schema.String,
}),
),
),
});
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
nameWithOwner: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
sshUrl: TrimmedNonEmptyString,
});
function normalizePullRequestSummary(
raw: Schema.Schema.Type<typeof RawGitHubPullRequestSchema>,
): GitHubPullRequestSummary {
const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null;
const headRepositoryOwnerLogin =
raw.headRepositoryOwner?.login ??
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
: null);
return {
number: raw.number,
title: raw.title,
url: raw.url,
baseRefName: raw.baseRefName,
headRefName: raw.headRefName,
state: normalizePullRequestState(raw),
...(typeof raw.isCrossRepository === "boolean"
? { isCrossRepository: raw.isCrossRepository }
: {}),
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
};
}
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
): GitHubRepositoryCloneUrls {
return {
nameWithOwner: raw.nameWithOwner,
url: raw.url,
sshUrl: raw.sshUrl,
};
}
function decodeGitHubJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
invalidDetail: string,
): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitHubCliError({
operation,
detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail,
cause: error,
}),
),
);
}
const makeGitHubCli = Effect.sync(() => {
@@ -128,21 +190,56 @@ const makeGitHubCli = Effect.sync(() => {
"number,title,url,baseRefName,headRefName",
],
}).pipe(
Effect.map((result) => result.stdout),
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
Effect.try({
try: () => parseOpenPullRequests(raw),
catch: (error: unknown) =>
new GitHubCliError({
operation: "listOpenPullRequests",
detail:
error instanceof Error
? `GitHub CLI returned invalid PR list JSON: ${error.message}`
: "GitHub CLI returned invalid PR list JSON.",
...(error !== undefined ? { cause: error } : {}),
}),
}),
raw.length === 0
? Effect.succeed([])
: decodeGitHubJson(
raw,
Schema.Array(RawGitHubPullRequestSchema),
"listOpenPullRequests",
"GitHub CLI returned invalid PR list JSON.",
),
),
Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)),
),
getPullRequest: (input) =>
execute({
cwd: input.cwd,
args: [
"pr",
"view",
input.reference,
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitHubJson(
raw,
RawGitHubPullRequestSchema,
"getPullRequest",
"GitHub CLI returned invalid pull request JSON.",
),
),
Effect.map(normalizePullRequestSummary),
),
getRepositoryCloneUrls: (input) =>
execute({
cwd: input.cwd,
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitHubJson(
raw,
RawGitHubRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitHub CLI returned invalid repository JSON.",
),
),
Effect.map(normalizeRepositoryCloneUrls),
),
createPullRequest: (input) =>
execute({
@@ -170,6 +267,11 @@ const makeGitHubCli = Effect.sync(() => {
return trimmed.length > 0 ? trimmed : null;
}),
),
checkoutPullRequest: (input) =>
execute({
cwd: input.cwd,
args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
}).pipe(Effect.asVoid),
} satisfies GitHubCliShape;
return service;
+701 -8
View File
@@ -1,5 +1,6 @@
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
@@ -23,6 +24,18 @@ interface FakeGhScenario {
prListSequence?: string[];
createdPrUrl?: string;
defaultBranch?: string;
pullRequest?: {
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
state?: "open" | "closed" | "merged";
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
};
repositoryCloneUrls?: Record<string, { url: string; sshUrl: string }>;
failWith?: GitHubCliError;
}
@@ -51,6 +64,31 @@ interface FakeGitTextGeneration {
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
}
type FakePullRequest = NonNullable<FakeGhScenario["pullRequest"]>;
function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
const result = spawnSync("git", args, {
cwd,
encoding: "utf8",
});
if (result.status === 0) {
return;
}
throw new GitHubCliError({
operation: "execute",
detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
});
}
function isGitHubCliError(error: unknown): error is GitHubCliError {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
(error as { _tag?: unknown })._tag === "GitHubCliError"
);
}
function makeTempDir(
prefix: string,
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
@@ -82,7 +120,11 @@ function runGit(
function initRepo(
cwd: string,
): Effect.Effect<void, PlatformError.PlatformError | GitCommandError, FileSystem.FileSystem | Scope.Scope | GitService> {
): Effect.Effect<
void,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitService
> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* runGit(cwd, ["init", "--initial-branch=main"]);
@@ -112,9 +154,7 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
Effect.succeed({
subject: "Implement stacked git actions",
body: "",
...(input.includeBranch
? { branch: "feature/implement-stacked-git-actions" }
: {}),
...(input.includeBranch ? { branch: "feature/implement-stacked-git-actions" } : {}),
}),
generatePrContent: () =>
Effect.succeed({
@@ -203,8 +243,33 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}
if (args[0] === "pr" && args[1] === "view") {
const pullRequest: FakePullRequest = scenario.pullRequest ?? {
number: 101,
title: "Pull request",
url: "https://github.com/pingdotgg/codething-mvp/pull/101",
baseRefName: "main",
headRefName: "feature/pull-request",
state: "open",
};
return Effect.succeed({
stdout: "",
stdout:
JSON.stringify({
...pullRequest,
...(pullRequest.headRepositoryNameWithOwner
? {
headRepository: {
nameWithOwner: pullRequest.headRepositoryNameWithOwner,
},
}
: {}),
...(pullRequest.headRepositoryOwnerLogin
? {
headRepositoryOwner: {
login: pullRequest.headRepositoryOwnerLogin,
},
}
: {}),
}) + "\n",
stderr: "",
code: 0,
signal: null,
@@ -212,7 +277,71 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
});
}
if (args[0] === "pr" && args[1] === "checkout") {
return Effect.try({
try: () => {
const headBranch = scenario.pullRequest?.headRefName;
if (headBranch) {
const existingBranch = spawnSync(
"git",
["show-ref", "--verify", "--quiet", `refs/heads/${headBranch}`],
{
cwd: input.cwd,
encoding: "utf8",
},
);
if (existingBranch.status === 0) {
runGitSyncForFakeGh(input.cwd, ["checkout", headBranch]);
} else {
runGitSyncForFakeGh(input.cwd, ["checkout", "-b", headBranch]);
}
}
return {
stdout: "",
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
},
catch: (error) =>
isGitHubCliError(error)
? error
: new GitHubCliError({
operation: "execute",
detail:
error instanceof Error
? `Failed to simulate gh checkout: ${error.message}`
: "Failed to simulate gh checkout.",
}),
});
}
if (args[0] === "repo" && args[1] === "view") {
const repository = args[2];
if (typeof repository === "string" && args.includes("nameWithOwner,url,sshUrl")) {
const cloneUrls = scenario.repositoryCloneUrls?.[repository];
if (!cloneUrls) {
return Effect.fail(
new GitHubCliError({
operation: "execute",
detail: `Unexpected repository lookup: ${repository}`,
}),
);
}
return Effect.succeed({
stdout:
JSON.stringify({
nameWithOwner: repository,
url: cloneUrls.url,
sshUrl: cloneUrls.sshUrl,
}) + "\n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
}
return Effect.succeed({
stdout: `${scenario.defaultBranch ?? "main"}\n`,
stderr: "",
@@ -279,6 +408,27 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
return value.length > 0 ? value : null;
}),
),
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) => JSON.parse(result.stdout) as GitHubPullRequestSummary)),
getRepositoryCloneUrls: (input) =>
execute({
cwd: input.cwd,
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
checkoutPullRequest: (input) =>
execute({
cwd: input.cwd,
args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
}).pipe(Effect.asVoid),
},
ghCalls,
};
@@ -296,6 +446,17 @@ function runStackedAction(
return manager.runStackedAction(input);
}
function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) {
return manager.resolvePullRequest(input);
}
function preparePullRequestThread(
manager: GitManagerShape,
input: { cwd: string; reference: string; mode: "local" | "worktree" },
) {
return manager.preparePullRequestThread(input);
}
function makeManager(input?: {
ghScenario?: FakeGhScenario;
textGeneration?: Partial<FakeGitTextGeneration>;
@@ -556,9 +717,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
return {
subject: "Implement stacked git actions",
body: "",
...(input.includeBranch
? { branch: "feature/implement-stacked-git-actions" }
: {}),
...(input.includeBranch ? { branch: "feature/implement-stacked-git-actions" } : {}),
};
}),
},
@@ -924,4 +1083,538 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(errorMessage).toContain("gh auth login");
}),
);
it.effect("resolves pull requests from #number references", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 42,
title: "Resolve PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/resolve-pr",
state: "open",
},
},
});
const result = yield* resolvePullRequest(manager, {
cwd: repoDir,
reference: "#42",
});
expect(result.pullRequest).toEqual({
number: 42,
title: "Resolve PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseBranch: "main",
headBranch: "feature/resolve-pr",
state: "open",
});
expect(ghCalls.some((call) => call.startsWith("pr view 42 "))).toBe(true);
}),
);
it.effect("prepares pull request threads in local mode by checking out the PR branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local"]);
fs.writeFileSync(path.join(repoDir, "local.txt"), "local\n");
yield* runGit(repoDir, ["add", "local.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local PR branch"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 64,
title: "Local PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/64",
baseRefName: "main",
headRefName: "feature/pr-local",
state: "open",
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "#64",
mode: "local",
});
expect(result.branch).toBe("feature/pr-local");
expect(result.worktreePath).toBeNull();
const branch = (yield* runGit(repoDir, ["branch", "--show-current"])).stdout.trim();
expect(branch).toBe("feature/pr-local");
expect(ghCalls).toContain("pr checkout 64 --force");
}),
);
it.effect("prepares pull request threads in worktree mode on the PR head branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-worktree"]);
fs.writeFileSync(path.join(repoDir, "worktree.txt"), "worktree\n");
yield* runGit(repoDir, ["add", "worktree.txt"]);
yield* runGit(repoDir, ["commit", "-m", "PR worktree branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-worktree"]);
yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/77/head"]);
yield* runGit(repoDir, ["checkout", "main"]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 77,
title: "Worktree PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/77",
baseRefName: "main",
headRefName: "feature/pr-worktree",
state: "open",
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "77",
mode: "worktree",
});
expect(result.branch).toBe("feature/pr-worktree");
expect(result.worktreePath).not.toBeNull();
expect(fs.existsSync(result.worktreePath as string)).toBe(true);
const worktreeBranch = (yield* runGit(result.worktreePath as string, [
"branch",
"--show-current",
])).stdout.trim();
expect(worktreeBranch).toBe("feature/pr-worktree");
}),
);
it.effect("preserves fork upstream tracking when preparing a worktree PR thread", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-fork"]);
fs.writeFileSync(path.join(repoDir, "fork.txt"), "fork\n");
yield* runGit(repoDir, ["add", "fork.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Fork PR branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-fork"]);
yield* runGit(repoDir, ["checkout", "main"]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 81,
title: "Fork PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/81",
baseRefName: "main",
headRefName: "feature/pr-fork",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
},
repositoryCloneUrls: {
"octocat/codething-mvp": {
url: forkDir,
sshUrl: forkDir,
},
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "81",
mode: "worktree",
});
expect(result.worktreePath).not.toBeNull();
const upstreamRef = (yield* runGit(result.worktreePath as string, [
"rev-parse",
"--abbrev-ref",
"@{upstream}",
])).stdout.trim();
expect(upstreamRef).toBe("fork-seed/feature/pr-fork");
expect(upstreamRef.startsWith("origin/")).toBe(false);
expect(
(yield* runGit(result.worktreePath as string, [
"config",
"--get",
"remote.fork-seed.url",
])).stdout.trim(),
).toBe(forkDir);
}),
);
it.effect("preserves fork upstream tracking when preparing a local PR thread", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-fork"]);
fs.writeFileSync(path.join(repoDir, "local-fork.txt"), "local fork\n");
yield* runGit(repoDir, ["add", "local-fork.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local fork PR branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-local-fork"]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-fork"]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 82,
title: "Local Fork PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/82",
baseRefName: "main",
headRefName: "feature/pr-local-fork",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
},
repositoryCloneUrls: {
"octocat/codething-mvp": {
url: forkDir,
sshUrl: forkDir,
},
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "82",
mode: "local",
});
expect(result.worktreePath).toBeNull();
expect(result.branch).toBe("feature/pr-local-fork");
expect(
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
).toBe("fork-seed/feature/pr-local-fork");
}),
);
it.effect("derives fork repository identity from PR URL when GitHub omits nameWithOwner", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "binbandit-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "fix/git-action-default-without-origin"]);
fs.writeFileSync(path.join(repoDir, "derived-fork.txt"), "derived fork\n");
yield* runGit(repoDir, ["add", "derived-fork.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Derived fork PR branch"]);
yield* runGit(repoDir, [
"push",
"-u",
"binbandit-seed",
"fix/git-action-default-without-origin",
]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "fix/git-action-default-without-origin"]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 642,
title: "fix: use commit as the default git action without origin",
url: "https://github.com/pingdotgg/t3code/pull/642",
baseRefName: "main",
headRefName: "fix/git-action-default-without-origin",
state: "open",
isCrossRepository: true,
headRepositoryOwnerLogin: "binbandit",
},
repositoryCloneUrls: {
"binbandit/t3code": {
url: forkDir,
sshUrl: forkDir,
},
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "642",
mode: "local",
});
expect(result.branch).toBe("fix/git-action-default-without-origin");
expect(result.worktreePath).toBeNull();
expect(
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
).toBe("binbandit-seed/fix/git-action-default-without-origin");
}),
);
it.effect("reuses an existing dedicated worktree for the PR head branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-existing-worktree"]);
fs.writeFileSync(path.join(repoDir, "existing.txt"), "existing\n");
yield* runGit(repoDir, ["add", "existing.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Existing worktree branch"]);
yield* runGit(repoDir, ["checkout", "main"]);
const worktreePath = path.join(repoDir, "..", `pr-existing-${Date.now()}`);
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 78,
title: "Existing worktree PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/78",
baseRefName: "main",
headRefName: "feature/pr-existing-worktree",
state: "open",
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "78",
mode: "worktree",
});
expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe(
fs.realpathSync.native(worktreePath),
);
expect(result.branch).toBe("feature/pr-existing-worktree");
}),
);
it.effect(
"does not block fork PR worktree prep when the fork head branch collides with root main",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);
fs.writeFileSync(path.join(repoDir, "fork-main.txt"), "fork main\n");
yield* runGit(repoDir, ["add", "fork-main.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Fork main branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);
yield* runGit(repoDir, ["checkout", "main"]);
const mainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 91,
title: "Fork main PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/91",
baseRefName: "main",
headRefName: "main",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
},
repositoryCloneUrls: {
"octocat/codething-mvp": {
url: forkDir,
sshUrl: forkDir,
},
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "91",
mode: "worktree",
});
expect(result.branch).toBe("t3code/pr-91/main");
expect(result.worktreePath).not.toBeNull();
expect((yield* runGit(repoDir, ["branch", "--show-current"])).stdout.trim()).toBe("main");
expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(mainBefore);
expect(
(yield* runGit(result.worktreePath as string, [
"branch",
"--show-current",
])).stdout.trim(),
).toBe("t3code/pr-91/main");
}),
);
it.effect(
"does not overwrite an existing local main branch when preparing a fork PR worktree",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);
fs.writeFileSync(path.join(repoDir, "fork-main-second.txt"), "fork main second\n");
yield* runGit(repoDir, ["add", "fork-main-second.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);
yield* runGit(repoDir, ["checkout", "main"]);
const localMainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();
yield* runGit(repoDir, ["checkout", "-b", "feature/root-branch"]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 92,
title: "Fork main overwrite PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/92",
baseRefName: "main",
headRefName: "main",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
},
repositoryCloneUrls: {
"octocat/codething-mvp": {
url: forkDir,
sshUrl: forkDir,
},
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "92",
mode: "worktree",
});
expect(result.branch).toBe("t3code/pr-92/main");
expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(localMainBefore);
expect(
(yield* runGit(result.worktreePath as string, [
"rev-parse",
"--abbrev-ref",
"@{upstream}",
])).stdout.trim(),
).toBe("fork-seed/main");
}),
);
it.effect("reuses an existing PR worktree and restores fork upstream tracking", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-reused-fork"]);
fs.writeFileSync(path.join(repoDir, "reused-fork.txt"), "reused fork\n");
yield* runGit(repoDir, ["add", "reused-fork.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Reused fork PR branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-reused-fork"]);
yield* runGit(repoDir, ["checkout", "main"]);
const worktreePath = path.join(repoDir, "..", `pr-reused-fork-${Date.now()}`);
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-reused-fork"]);
yield* runGit(worktreePath, ["branch", "--unset-upstream"], true);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 83,
title: "Reused Fork PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/83",
baseRefName: "main",
headRefName: "feature/pr-reused-fork",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
},
repositoryCloneUrls: {
"octocat/codething-mvp": {
url: forkDir,
sshUrl: forkDir,
},
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "83",
mode: "worktree",
});
expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe(
fs.realpathSync.native(worktreePath),
);
expect(
(yield* runGit(worktreePath, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
).toBe("fork-seed/feature/pr-reused-fork");
}),
);
it.effect("rejects worktree prep when the PR head branch is checked out in the main repo", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-root-only"]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 79,
title: "Root-only PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/79",
baseRefName: "main",
headRefName: "feature/pr-root-only",
state: "open",
},
},
});
const errorMessage = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "79",
mode: "worktree",
}).pipe(
Effect.flip,
Effect.map((error) => error.message),
);
expect(errorMessage).toContain("already checked out in the main repo");
}),
);
});
+367 -1
View File
@@ -1,7 +1,12 @@
import { randomUUID } from "node:crypto";
import { realpathSync } from "node:fs";
import { Effect, FileSystem, Layer, Path } from "effect";
import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import {
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
sanitizeFeatureBranchName,
} from "@t3tools/shared/git";
import { GitManagerError } from "../Errors.ts";
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
@@ -22,6 +27,61 @@ interface PullRequestInfo extends OpenPrInfo {
updatedAt: string | null;
}
interface ResolvedPullRequest {
number: number;
title: string;
url: string;
baseBranch: string;
headBranch: string;
state: "open" | "closed" | "merged";
}
interface PullRequestHeadRemoteInfo {
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
}
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 parsePullRequestList(raw: unknown): PullRequestInfo[] {
if (!Array.isArray(raw)) return [];
@@ -175,10 +235,160 @@ function toStatusPr(pr: PullRequestInfo): {
};
}
function normalizePullRequestReference(reference: string): string {
const trimmed = reference.trim();
const hashNumber = /^#(\d+)$/.exec(trimmed);
return hashNumber?.[1] ?? trimmed;
}
function canonicalizeExistingPath(value: string): string {
try {
return realpathSync.native(value);
} catch {
return value;
}
}
function toResolvedPullRequest(pr: {
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
state?: "open" | "closed" | "merged";
}): ResolvedPullRequest {
return {
number: pr.number,
title: pr.title,
url: pr.url,
baseBranch: pr.baseRefName,
headBranch: pr.headRefName,
state: pr.state ?? "open",
};
}
function shouldPreferSshRemote(url: string | null): boolean {
if (!url) return false;
const trimmed = url.trim();
return trimmed.startsWith("git@") || trimmed.startsWith("ssh://");
}
function toPullRequestHeadRemoteInfo(pr: {
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
}): PullRequestHeadRemoteInfo {
return {
...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
...(pr.headRepositoryNameWithOwner !== undefined
? { headRepositoryNameWithOwner: pr.headRepositoryNameWithOwner }
: {}),
...(pr.headRepositoryOwnerLogin !== undefined
? { headRepositoryOwnerLogin: pr.headRepositoryOwnerLogin }
: {}),
};
}
export const makeGitManager = Effect.gen(function* () {
const gitCore = yield* GitCore;
const gitHubCli = yield* GitHubCli;
const textGeneration = yield* TextGeneration;
const configurePullRequestHeadUpstream = (
cwd: string,
pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
localBranch = pullRequest.headBranch,
) =>
Effect.gen(function* () {
const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
if (repositoryNameWithOwner.length === 0) {
return;
}
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url");
const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
const preferredRemoteName =
pullRequest.headRepositoryOwnerLogin?.trim() ||
repositoryNameWithOwner.split("/")[0]?.trim() ||
"fork";
const remoteName = yield* gitCore.ensureRemote({
cwd,
preferredName: preferredRemoteName,
url: remoteUrl,
});
yield* gitCore.setBranchUpstream({
cwd,
branch: localBranch,
remoteName,
remoteBranch: pullRequest.headBranch,
});
}).pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitManager.configurePullRequestHeadUpstream: failed to configure upstream for ${localBranch} -> ${pullRequest.headBranch} in ${cwd}: ${error.message}`,
).pipe(Effect.asVoid),
),
);
const materializePullRequestHeadBranch = (
cwd: string,
pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
localBranch = pullRequest.headBranch,
) =>
Effect.gen(function* () {
const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
if (repositoryNameWithOwner.length === 0) {
yield* gitCore.fetchPullRequestBranch({
cwd,
prNumber: pullRequest.number,
branch: localBranch,
});
return;
}
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url");
const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;
const preferredRemoteName =
pullRequest.headRepositoryOwnerLogin?.trim() ||
repositoryNameWithOwner.split("/")[0]?.trim() ||
"fork";
const remoteName = yield* gitCore.ensureRemote({
cwd,
preferredName: preferredRemoteName,
url: remoteUrl,
});
yield* gitCore.fetchRemoteBranch({
cwd,
remoteName,
remoteBranch: pullRequest.headBranch,
localBranch,
});
yield* gitCore.setBranchUpstream({
cwd,
branch: localBranch,
remoteName,
remoteBranch: pullRequest.headBranch,
});
}).pipe(
Effect.catch(() =>
gitCore.fetchPullRequestBranch({
cwd,
prNumber: pullRequest.number,
branch: localBranch,
}),
),
);
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -445,6 +655,160 @@ export const makeGitManager = Effect.gen(function* () {
};
});
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) =>
Effect.gen(function* () {
const suggestion = yield* resolveCommitAndBranchSuggestion({
@@ -536,6 +900,8 @@ export const makeGitManager = Effect.gen(function* () {
return {
status,
resolvePullRequest,
preparePullRequestThread,
runStackedAction,
} satisfies GitManagerShape;
});
+52
View File
@@ -56,6 +56,32 @@ export interface GitRenameBranchResult {
branch: string;
}
export interface GitFetchPullRequestBranchInput {
cwd: string;
prNumber: number;
branch: string;
}
export interface GitEnsureRemoteInput {
cwd: string;
preferredName: string;
url: string;
}
export interface GitFetchRemoteBranchInput {
cwd: string;
remoteName: string;
remoteBranch: string;
localBranch: string;
}
export interface GitSetBranchUpstreamInput {
cwd: string;
branch: string;
remoteName: string;
remoteBranch: string;
}
/**
* GitCoreShape - Service API for low-level Git repository interactions.
*/
@@ -129,6 +155,32 @@ export interface GitCoreShape {
input: GitCreateWorktreeInput,
) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>;
/**
* Materialize a GitHub pull request head as a local branch without switching checkout.
*/
readonly fetchPullRequestBranch: (
input: GitFetchPullRequestBranchInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Ensure a named remote exists for the provided URL, returning the reused or created remote name.
*/
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
/**
* Fetch a remote branch into a local branch without checkout.
*/
readonly fetchRemoteBranch: (
input: GitFetchRemoteBranchInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Set the upstream tracking branch for a local branch.
*/
readonly setBranchUpstream: (
input: GitSetBranchUpstreamInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Remove an existing worktree.
*/
+35
View File
@@ -17,6 +17,16 @@ export interface GitHubPullRequestSummary {
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
readonly state?: "open" | "closed" | "merged";
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
}
export interface GitHubRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
readonly sshUrl: string;
}
/**
@@ -41,6 +51,22 @@ export interface GitHubCliShape {
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
/**
* Resolve a pull request by URL, number, or branch-ish identifier.
*/
readonly getPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
/**
* Resolve clone URLs for a GitHub repository.
*/
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
/**
* Create a pull request from branch context and body file.
*/
@@ -58,6 +84,15 @@ export interface GitHubCliShape {
readonly getDefaultBranch: (input: {
readonly cwd: string;
}) => Effect.Effect<string | null, GitHubCliError>;
/**
* Checkout a pull request into the current repository worktree.
*/
readonly checkoutPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, GitHubCliError>;
}
/**
@@ -7,6 +7,10 @@
* @module GitManager
*/
import {
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusInput,
@@ -27,6 +31,20 @@ export interface GitManagerShape {
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
/**
* Resolve a pull request by URL/number against the current repository.
*/
readonly resolvePullRequest: (
input: GitPullRequestRefInput,
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
/**
* Prepare a new thread workspace from a pull request in local or worktree mode.
*/
readonly preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
/**
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first.
+3 -1
View File
@@ -211,7 +211,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
});
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
assert.isFalse(configState.keybindings.some((entry) => String(entry.command) === "invalid.command"));
assert.isFalse(
configState.keybindings.some((entry) => String(entry.command) === "invalid.command"),
);
assert.deepEqual(configState.issues, [
{
kind: "keybindings.invalid-entry",
+4 -4
View File
@@ -40,7 +40,9 @@ interface CommandAvailabilityOptions {
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
return (
(editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target)
);
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
@@ -239,9 +241,7 @@ export const launchDetached = (launch: EditorLaunch) =>
});
} catch (error) {
return resume(
Effect.fail(
new OpenError({ message: "failed to spawn detached process", cause: error }),
),
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
);
}
@@ -69,7 +69,7 @@ function createProviderServiceHarness(
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A, never>;
const listSessions = () =>
hasSession
? Effect.succeed([
? Effect.succeed([
{
provider: providerName,
status: "ready",
@@ -350,7 +350,7 @@ describe("CheckpointReactor", () => {
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-1"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
@@ -365,7 +365,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-1"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
@@ -426,7 +426,7 @@ describe("CheckpointReactor", () => {
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-main"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-main"),
@@ -442,7 +442,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-aux"),
@@ -460,7 +460,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-main"),
@@ -500,7 +500,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-missing-baseline"),
@@ -589,7 +589,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-missing-cwd"),
@@ -635,7 +635,7 @@ describe("CheckpointReactor", () => {
type: "checkpoint.captured",
eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-3"),
@@ -685,7 +685,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-runtime-failure"),
@@ -696,7 +696,7 @@ describe("CheckpointReactor", () => {
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-after-runtime-failure"),
@@ -115,9 +115,7 @@ const make = Effect.gen(function* () {
const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
threadId: ThreadId,
): Effect.fn.Return<
Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>
> {
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
@@ -133,9 +131,7 @@ const make = Effect.gen(function* () {
};
if (thread) {
const projectedSession = sessions.find(
(session) => session.threadId === thread.id,
);
const projectedSession = sessions.find((session) => session.threadId === thread.id);
const fromProjected = findSessionWithCwd(projectedSession);
if (Option.isSome(fromProjected)) {
return fromProjected;
@@ -306,9 +302,7 @@ const make = Effect.gen(function* () {
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find(
(entry) => entry.id === event.threadId,
);
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
@@ -54,9 +54,7 @@ const runWithProjectionPipelineLayer = <A, E>(
(runtime) => Effect.promise(() => runtime.dispose()),
);
const projectionLayer = it.layer(
makeProjectionPipelineTestLayer(process.cwd()),
);
const projectionLayer = it.layer(makeProjectionPipelineTestLayer(process.cwd()));
projectionLayer("OrchestrationProjectionPipeline", (it) => {
it.effect("bootstraps all projection states and writes projection rows", () =>
@@ -450,153 +448,149 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect(
"overwrites stored attachment references when a message updates attachments",
() =>
Effect.sync(() =>
fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-overwrite-")),
).pipe(
Effect.flatMap((stateDir) =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
const later = new Date(Date.now() + 1_000).toISOString();
it.effect("overwrites stored attachment references when a message updates attachments", () =>
Effect.sync(() =>
fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-overwrite-")),
).pipe(
Effect.flatMap((stateDir) =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
const later = new Date(Date.now() + 1_000).toISOString();
yield* eventStore.append({
type: "project.created",
eventId: EventId.makeUnsafe("evt-overwrite-1"),
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-overwrite"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-overwrite-1"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-overwrite-1"),
metadata: {},
payload: {
projectId: ProjectId.makeUnsafe("project-overwrite"),
title: "Project Overwrite",
workspaceRoot: "/tmp/project-overwrite",
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "project.created",
eventId: EventId.makeUnsafe("evt-overwrite-1"),
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-overwrite"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-overwrite-1"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-overwrite-1"),
metadata: {},
payload: {
projectId: ProjectId.makeUnsafe("project-overwrite"),
title: "Project Overwrite",
workspaceRoot: "/tmp/project-overwrite",
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.created",
eventId: EventId.makeUnsafe("evt-overwrite-2"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-overwrite"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-overwrite-2"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-overwrite-2"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-overwrite"),
projectId: ProjectId.makeUnsafe("project-overwrite"),
title: "Thread Overwrite",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.created",
eventId: EventId.makeUnsafe("evt-overwrite-2"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-overwrite"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-overwrite-2"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-overwrite-2"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-overwrite"),
projectId: ProjectId.makeUnsafe("project-overwrite"),
title: "Thread Overwrite",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-overwrite-3"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-overwrite"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-overwrite-3"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-overwrite-3"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-overwrite"),
messageId: MessageId.makeUnsafe("message-overwrite"),
role: "user",
text: "first image",
attachments: [
{
type: "image",
id: "thread-overwrite-att-1",
name: "file.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
turnId: null,
streaming: false,
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-overwrite-3"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-overwrite"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-overwrite-3"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-overwrite-3"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-overwrite"),
messageId: MessageId.makeUnsafe("message-overwrite"),
role: "user",
text: "first image",
attachments: [
{
type: "image",
id: "thread-overwrite-att-1",
name: "file.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
turnId: null,
streaming: false,
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-overwrite-4"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-overwrite"),
occurredAt: later,
commandId: CommandId.makeUnsafe("cmd-overwrite-4"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-overwrite-4"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-overwrite"),
messageId: MessageId.makeUnsafe("message-overwrite"),
role: "user",
text: "",
attachments: [
{
type: "image",
id: "thread-overwrite-att-2",
name: "file.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
turnId: null,
streaming: false,
createdAt: now,
updatedAt: later,
},
});
yield* eventStore.append({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-overwrite-4"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-overwrite"),
occurredAt: later,
commandId: CommandId.makeUnsafe("cmd-overwrite-4"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-overwrite-4"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-overwrite"),
messageId: MessageId.makeUnsafe("message-overwrite"),
role: "user",
text: "",
attachments: [
{
type: "image",
id: "thread-overwrite-att-2",
name: "file.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
turnId: null,
streaming: false,
createdAt: now,
updatedAt: later,
},
});
yield* projectionPipeline.bootstrap;
yield* projectionPipeline.bootstrap;
const rows = yield* sql<{
readonly attachmentsJson: string | null;
}>`
const rows = yield* sql<{
readonly attachmentsJson: string | null;
}>`
SELECT attachments_json AS "attachmentsJson"
FROM projection_thread_messages
WHERE message_id = 'message-overwrite'
`;
assert.equal(rows.length, 1);
assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [
{
type: "image",
id: "thread-overwrite-att-2",
name: "file.png",
mimeType: "image/png",
sizeBytes: 5,
},
]);
}).pipe(
(effect) => runWithProjectionPipelineLayer(stateDir, effect),
Effect.ensuring(
Effect.sync(() => fs.rmSync(stateDir, { recursive: true, force: true })),
),
),
assert.equal(rows.length, 1);
assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [
{
type: "image",
id: "thread-overwrite-att-2",
name: "file.png",
mimeType: "image/png",
sizeBytes: 5,
},
]);
}).pipe(
(effect) => runWithProjectionPipelineLayer(stateDir, effect),
Effect.ensuring(Effect.sync(() => fs.rmSync(stateDir, { recursive: true, force: true }))),
),
),
),
);
it.effect("does not persist attachment files when projector transaction rolls back", () =>
@@ -711,11 +705,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
`;
assert.equal(rows[0]?.count ?? 0, 0);
const attachmentPath = path.join(
stateDir,
"attachments",
"thread-rollback-att-1.png",
);
const attachmentPath = path.join(stateDir, "attachments", "thread-rollback-att-1.png");
assert.equal(fs.existsSync(attachmentPath), false);
yield* sql`DROP TRIGGER IF EXISTS fail_thread_messages_projection_state_update`;
}).pipe(
@@ -747,189 +737,189 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "project.created",
eventId: EventId.makeUnsafe("evt-revert-files-1"),
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-revert-files"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-1"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-1"),
metadata: {},
payload: {
projectId: ProjectId.makeUnsafe("project-revert-files"),
title: "Project Revert Files",
workspaceRoot: "/tmp/project-revert-files",
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.makeUnsafe("evt-revert-files-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-2"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-2"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.makeUnsafe("project-revert-files"),
title: "Thread Revert Files",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.makeUnsafe("evt-revert-files-3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-3"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-3"),
metadata: {},
payload: {
threadId,
turnId: TurnId.makeUnsafe("turn-keep"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert-files/turn/1"),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("message-keep"),
completedAt: now,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-revert-files-4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-4"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-4"),
metadata: {},
payload: {
threadId,
messageId: MessageId.makeUnsafe("message-keep"),
role: "assistant",
text: "Keep",
attachments: [
{
type: "image",
id: keepAttachmentId,
name: "keep.png",
mimeType: "image/png",
sizeBytes: 5,
type: "project.created",
eventId: EventId.makeUnsafe("evt-revert-files-1"),
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-revert-files"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-1"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-1"),
metadata: {},
payload: {
projectId: ProjectId.makeUnsafe("project-revert-files"),
title: "Project Revert Files",
workspaceRoot: "/tmp/project-revert-files",
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
],
turnId: TurnId.makeUnsafe("turn-keep"),
streaming: false,
createdAt: now,
updatedAt: now,
},
});
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.makeUnsafe("evt-revert-files-5"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-5"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-5"),
metadata: {},
payload: {
threadId,
turnId: TurnId.makeUnsafe("turn-remove"),
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert-files/turn/2"),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("message-remove"),
completedAt: now,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-revert-files-6"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-6"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-6"),
metadata: {},
payload: {
threadId,
messageId: MessageId.makeUnsafe("message-remove"),
role: "assistant",
text: "Remove",
attachments: [
{
type: "image",
id: removeAttachmentId,
name: "remove.png",
mimeType: "image/png",
sizeBytes: 5,
yield* appendAndProject({
type: "thread.created",
eventId: EventId.makeUnsafe("evt-revert-files-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-2"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-2"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.makeUnsafe("project-revert-files"),
title: "Thread Revert Files",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
],
turnId: TurnId.makeUnsafe("turn-remove"),
streaming: false,
createdAt: now,
updatedAt: now,
},
});
});
const keepPath = path.join(
stateDir,
"attachments",
`${keepAttachmentId}.png`,
);
const removePath = path.join(
stateDir,
"attachments",
`${removeAttachmentId}.png`,
);
fs.mkdirSync(path.join(stateDir, "attachments"), { recursive: true });
fs.writeFileSync(keepPath, Buffer.from("keep"));
fs.writeFileSync(removePath, Buffer.from("remove"));
const otherThreadPath = path.join(stateDir, "attachments", `${otherThreadAttachmentId}.png`);
fs.writeFileSync(otherThreadPath, Buffer.from("other"));
assert.equal(fs.existsSync(keepPath), true);
assert.equal(fs.existsSync(removePath), true);
assert.equal(fs.existsSync(otherThreadPath), true);
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.makeUnsafe("evt-revert-files-3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-3"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-3"),
metadata: {},
payload: {
threadId,
turnId: TurnId.makeUnsafe("turn-keep"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe(
"refs/t3/checkpoints/thread-revert-files/turn/1",
),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("message-keep"),
completedAt: now,
},
});
yield* appendAndProject({
type: "thread.reverted",
eventId: EventId.makeUnsafe("evt-revert-files-7"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-7"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-7"),
metadata: {},
payload: {
threadId,
turnCount: 1,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-revert-files-4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-4"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-4"),
metadata: {},
payload: {
threadId,
messageId: MessageId.makeUnsafe("message-keep"),
role: "assistant",
text: "Keep",
attachments: [
{
type: "image",
id: keepAttachmentId,
name: "keep.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
turnId: TurnId.makeUnsafe("turn-keep"),
streaming: false,
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.makeUnsafe("evt-revert-files-5"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-5"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-5"),
metadata: {},
payload: {
threadId,
turnId: TurnId.makeUnsafe("turn-remove"),
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.makeUnsafe(
"refs/t3/checkpoints/thread-revert-files/turn/2",
),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("message-remove"),
completedAt: now,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-revert-files-6"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-6"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-6"),
metadata: {},
payload: {
threadId,
messageId: MessageId.makeUnsafe("message-remove"),
role: "assistant",
text: "Remove",
attachments: [
{
type: "image",
id: removeAttachmentId,
name: "remove.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
turnId: TurnId.makeUnsafe("turn-remove"),
streaming: false,
createdAt: now,
updatedAt: now,
},
});
const keepPath = path.join(stateDir, "attachments", `${keepAttachmentId}.png`);
const removePath = path.join(stateDir, "attachments", `${removeAttachmentId}.png`);
fs.mkdirSync(path.join(stateDir, "attachments"), { recursive: true });
fs.writeFileSync(keepPath, Buffer.from("keep"));
fs.writeFileSync(removePath, Buffer.from("remove"));
const otherThreadPath = path.join(
stateDir,
"attachments",
`${otherThreadAttachmentId}.png`,
);
fs.writeFileSync(otherThreadPath, Buffer.from("other"));
assert.equal(fs.existsSync(keepPath), true);
assert.equal(fs.existsSync(removePath), true);
assert.equal(fs.existsSync(otherThreadPath), true);
yield* appendAndProject({
type: "thread.reverted",
eventId: EventId.makeUnsafe("evt-revert-files-7"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-revert-files-7"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-revert-files-7"),
metadata: {},
payload: {
threadId,
turnCount: 1,
},
});
assert.equal(fs.existsSync(keepPath), true);
assert.equal(fs.existsSync(removePath), false);
@@ -962,107 +952,107 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "project.created",
eventId: EventId.makeUnsafe("evt-delete-files-1"),
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-delete-files"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-delete-files-1"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-delete-files-1"),
metadata: {},
payload: {
projectId: ProjectId.makeUnsafe("project-delete-files"),
title: "Project Delete Files",
workspaceRoot: "/tmp/project-delete-files",
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.makeUnsafe("evt-delete-files-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-delete-files-2"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-delete-files-2"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.makeUnsafe("project-delete-files"),
title: "Thread Delete Files",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-delete-files-3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-delete-files-3"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-delete-files-3"),
metadata: {},
payload: {
threadId,
messageId: MessageId.makeUnsafe("message-delete-files"),
role: "user",
text: "Delete",
attachments: [
{
type: "image",
id: attachmentId,
name: "delete.png",
mimeType: "image/png",
sizeBytes: 5,
type: "project.created",
eventId: EventId.makeUnsafe("evt-delete-files-1"),
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-delete-files"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-delete-files-1"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-delete-files-1"),
metadata: {},
payload: {
projectId: ProjectId.makeUnsafe("project-delete-files"),
title: "Project Delete Files",
workspaceRoot: "/tmp/project-delete-files",
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
],
turnId: null,
streaming: false,
createdAt: now,
updatedAt: now,
},
});
});
const threadAttachmentPath = path.join(stateDir, "attachments", `${attachmentId}.png`);
const otherThreadAttachmentPath = path.join(
stateDir,
"attachments",
`${otherThreadAttachmentId}.png`,
);
fs.mkdirSync(path.join(stateDir, "attachments"), { recursive: true });
fs.writeFileSync(threadAttachmentPath, Buffer.from("delete"));
fs.writeFileSync(otherThreadAttachmentPath, Buffer.from("other-thread"));
assert.equal(fs.existsSync(threadAttachmentPath), true);
assert.equal(fs.existsSync(otherThreadAttachmentPath), true);
yield* appendAndProject({
type: "thread.created",
eventId: EventId.makeUnsafe("evt-delete-files-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-delete-files-2"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-delete-files-2"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.makeUnsafe("project-delete-files"),
title: "Thread Delete Files",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* appendAndProject({
type: "thread.deleted",
eventId: EventId.makeUnsafe("evt-delete-files-4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-delete-files-4"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-delete-files-4"),
metadata: {},
payload: {
threadId,
deletedAt: now,
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-delete-files-3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-delete-files-3"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-delete-files-3"),
metadata: {},
payload: {
threadId,
messageId: MessageId.makeUnsafe("message-delete-files"),
role: "user",
text: "Delete",
attachments: [
{
type: "image",
id: attachmentId,
name: "delete.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
turnId: null,
streaming: false,
createdAt: now,
updatedAt: now,
},
});
const threadAttachmentPath = path.join(stateDir, "attachments", `${attachmentId}.png`);
const otherThreadAttachmentPath = path.join(
stateDir,
"attachments",
`${otherThreadAttachmentId}.png`,
);
fs.mkdirSync(path.join(stateDir, "attachments"), { recursive: true });
fs.writeFileSync(threadAttachmentPath, Buffer.from("delete"));
fs.writeFileSync(otherThreadAttachmentPath, Buffer.from("other-thread"));
assert.equal(fs.existsSync(threadAttachmentPath), true);
assert.equal(fs.existsSync(otherThreadAttachmentPath), true);
yield* appendAndProject({
type: "thread.deleted",
eventId: EventId.makeUnsafe("evt-delete-files-4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-delete-files-4"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-delete-files-4"),
metadata: {},
payload: {
threadId,
deletedAt: now,
},
});
assert.equal(fs.existsSync(threadAttachmentPath), false);
assert.equal(fs.existsSync(otherThreadAttachmentPath), true);
@@ -1075,7 +1065,9 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
);
it.effect("ignores unsafe thread ids for attachment cleanup paths", () =>
Effect.sync(() => fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-unsafe-"))).pipe(
Effect.sync(() =>
fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-unsafe-")),
).pipe(
Effect.flatMap((stateDir) =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -78,9 +78,8 @@ interface AttachmentSideEffects {
}
const materializeAttachmentsForProjection = Effect.fn(
(input: {
readonly attachments: ReadonlyArray<ChatAttachment>;
}) => Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
(input: { readonly attachments: ReadonlyArray<ChatAttachment> }) =>
Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
);
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
@@ -336,7 +335,6 @@ const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSid
},
{ concurrency: 1 },
);
});
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
@@ -1,11 +1,4 @@
import {
CheckpointRef,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -41,7 +41,10 @@ const asApprovalRequestId = (value: string): ApprovalRequestId =>
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
async function waitFor(predicate: () => boolean | Promise<boolean>, timeoutMs = 2000): Promise<void> {
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2000,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (await predicate()) {
@@ -101,7 +104,10 @@ describe("ProviderCommandReactor", () => {
? input.resumeCursor
: undefined;
const model =
typeof input === "object" && input !== null && "model" in input && typeof input.model === "string"
typeof input === "object" &&
input !== null &&
"model" in input &&
typeof input.model === "string"
? input.model
: undefined;
const threadId =
@@ -474,7 +480,9 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return thread?.runtimeMode === "approval-required";
});
await waitFor(() => harness.startSession.mock.calls.length === 2);
@@ -563,7 +571,9 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return thread?.runtimeMode === "approval-required";
});
await waitFor(() => harness.startSession.mock.calls.length === 2);
@@ -767,9 +777,13 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
if (!thread) return false;
return thread.activities.some((activity) => activity.kind === "provider.approval.respond.failed");
return thread.activities.some(
(activity) => activity.kind === "provider.approval.respond.failed",
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
@@ -5,7 +5,6 @@ import {
type OrchestrationEvent,
type ProviderModelOptions,
type ProviderKind,
type ProviderServiceTier,
type ProviderStartOptions,
type OrchestrationSession,
ThreadId,
@@ -205,7 +204,6 @@ const make = Effect.gen(function* () {
readonly provider?: ProviderKind;
readonly model?: string;
readonly modelOptions?: ProviderModelOptions;
readonly serviceTier?: ProviderServiceTier | null;
readonly providerOptions?: ProviderStartOptions;
},
) {
@@ -226,9 +224,9 @@ const make = Effect.gen(function* () {
});
const resolveActiveSession = (threadId: ThreadId) =>
providerService.listSessions().pipe(
Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)),
);
providerService
.listSessions()
.pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));
const startProviderSession = (input?: {
readonly resumeCursor?: unknown;
@@ -236,14 +234,15 @@ const make = Effect.gen(function* () {
}) =>
providerService.startSession(threadId, {
threadId,
...(input?.provider ?? preferredProvider
...((input?.provider ?? preferredProvider)
? { provider: input?.provider ?? preferredProvider }
: {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(desiredModel ? { model: desiredModel } : {}),
...(options?.serviceTier !== undefined ? { serviceTier: options.serviceTier } : {}),
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
...(options?.providerOptions !== undefined ? { providerOptions: options.providerOptions } : {}),
...(options?.providerOptions !== undefined
? { providerOptions: options.providerOptions }
: {}),
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
runtimeMode: desiredRuntimeMode,
});
@@ -268,16 +267,15 @@ const make = Effect.gen(function* () {
thread.session && thread.session.status !== "stopped" ? thread.id : null;
if (existingSessionThreadId) {
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
const providerChanged = options?.provider !== undefined && options.provider !== currentProvider;
const providerChanged =
options?.provider !== undefined && options.provider !== currentProvider;
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const modelChanged =
options?.model !== undefined && options.model !== activeSession?.model;
const shouldRestartForModelChange =
modelChanged && sessionModelSwitch === "restart-session";
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
return existingSessionThreadId;
@@ -328,7 +326,6 @@ const make = Effect.gen(function* () {
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly provider?: ProviderKind;
readonly model?: string;
readonly serviceTier?: ProviderServiceTier | null;
readonly modelOptions?: ProviderModelOptions;
readonly providerOptions?: ProviderStartOptions;
readonly interactionMode?: "default" | "plan";
@@ -344,28 +341,27 @@ const make = Effect.gen(function* () {
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
const activeSession = yield* providerService.listSessions().pipe(
Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),
);
const activeSession = yield* providerService
.listSessions()
.pipe(
Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),
);
const sessionModelSwitch =
activeSession === undefined
? "in-session"
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
const modelForTurn =
sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
const modelForTurn = sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
yield* providerService.sendTurn({
threadId: input.threadId,
...(normalizedInput ? { input: normalizedInput } : {}),
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
});
@@ -480,9 +476,12 @@ const make = Effect.gen(function* () {
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.serviceTier !== undefined ? { serviceTier: event.payload.serviceTier } : {}),
...(event.payload.modelOptions !== undefined ? { modelOptions: event.payload.modelOptions } : {}),
...(event.payload.providerOptions !== undefined ? { providerOptions: event.payload.providerOptions } : {}),
...(event.payload.modelOptions !== undefined
? { modelOptions: event.payload.modelOptions }
: {}),
...(event.payload.providerOptions !== undefined
? { providerOptions: event.payload.providerOptions }
: {}),
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
});
@@ -639,9 +638,13 @@ const make = Effect.gen(function* () {
return;
}
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
...(cachedProviderOptions !== undefined ? { providerOptions: cachedProviderOptions } : {}),
});
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedProviderOptions !== undefined
? { providerOptions: cachedProviderOptions }
: undefined,
);
return;
}
case "thread.turn-start-requested":
@@ -379,7 +379,9 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(Effect.sleep("40 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
expect(midThread?.session?.status).toBe("running");
expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle");
@@ -620,7 +622,9 @@ describe("ProviderRuntimeIngestion", () => {
const proposedPlan = thread.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-plan-final",
);
expect(proposedPlan?.planMarkdown).toBe("## Ship plan\n\n- wire projection\n- render follow-up");
expect(proposedPlan?.planMarkdown).toBe(
"## Ship plan\n\n- wire projection\n- render follow-up",
);
});
it("finalizes buffered proposed-plan deltas into a first-class proposed plan on turn completion", async () => {
@@ -683,7 +687,8 @@ describe("ProviderRuntimeIngestion", () => {
),
);
const proposedPlan = thread.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-plan-buffer",
(entry: ProviderRuntimeTestProposedPlan) =>
entry.id === "plan:thread-1:turn:turn-plan-buffer",
);
expect(proposedPlan?.planMarkdown).toBe("## Buffered plan\n\n- first\n- second");
});
@@ -1091,6 +1096,50 @@ describe("ProviderRuntimeIngestion", () => {
expect(thread.session?.lastError).toBe("runtime exploded");
});
it("keeps the session running when a runtime.warning arrives during an active turn", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-warning-turn-started"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-warning"),
payload: {},
});
harness.emit({
type: "runtime.warning",
eventId: asEventId("evt-warning-runtime"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-warning"),
payload: {
message: "Reconnecting... 2/5",
detail: {
willRetry: true,
},
},
});
const thread = await waitForThread(
harness.engine,
(entry) =>
entry.session?.status === "running" &&
entry.session?.activeTurnId === "turn-warning" &&
entry.activities.some(
(activity: ProviderRuntimeTestActivity) =>
activity.id === "evt-warning-runtime" && activity.kind === "runtime.warning",
),
);
expect(thread.session?.status).toBe("running");
expect(thread.session?.activeTurnId).toBe("turn-warning");
expect(thread.session?.lastError).toBeNull();
});
it("maps session/thread lifecycle and item.started into session/activity projections", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -210,9 +210,9 @@ function runtimeEventToActivities(
? "Command approval requested"
: requestKind === "file-read"
? "File-read approval requested"
: requestKind === "file-change"
? "File-change approval requested"
: "Approval requested",
: requestKind === "file-change"
? "File-change approval requested"
: "Approval requested",
payload: {
requestId: toApprovalRequestId(event.requestId),
...(requestKind ? { requestKind } : {}),
@@ -298,7 +298,9 @@ function runtimeEventToActivities(
summary: "Plan updated",
payload: {
plan: event.payload.plan,
...(event.payload.explanation !== undefined ? { explanation: event.payload.explanation } : {}),
...(event.payload.explanation !== undefined
? { explanation: event.payload.explanation }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -358,7 +360,9 @@ function runtimeEventToActivities(
payload: {
taskId: event.payload.taskId,
...(event.payload.taskType ? { taskType: event.payload.taskType } : {}),
...(event.payload.description ? { detail: truncateDetail(event.payload.description) } : {}),
...(event.payload.description
? { detail: truncateDetail(event.payload.description) }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -525,11 +529,7 @@ const make = Effect.gen(function* () {
return isGitRepository(workspaceCwd);
});
const rememberAssistantMessageId = (
threadId: ThreadId,
turnId: TurnId,
messageId: MessageId,
) =>
const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(
Effect.flatMap((existingIds) =>
Cache.set(
@@ -547,11 +547,7 @@ const make = Effect.gen(function* () {
),
);
const forgetAssistantMessageId = (
threadId: ThreadId,
turnId: TurnId,
messageId: MessageId,
) =>
const forgetAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(
Effect.flatMap((existingIds) =>
Option.match(existingIds, {
@@ -616,7 +612,8 @@ const make = Effect.gen(function* () {
const existing = Option.getOrUndefined(existingEntry);
return Cache.set(bufferedProposedPlanById, planId, {
text: `${existing?.text ?? ""}${delta}`,
createdAt: existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt,
createdAt:
existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt,
});
}),
);
@@ -633,7 +630,8 @@ const make = Effect.gen(function* () {
const clearBufferedProposedPlan = (planId: string) =>
Cache.invalidate(bufferedProposedPlanById, planId);
const clearAssistantMessageState = (messageId: MessageId) => clearBufferedAssistantText(messageId);
const clearAssistantMessageState = (messageId: MessageId) =>
clearBufferedAssistantText(messageId);
const finalizeAssistantMessage = (input: {
event: ProviderRuntimeEvent;
@@ -862,8 +860,8 @@ const make = Effect.gen(function* () {
: event.type === "turn.completed" && runtimeTurnState(event) === "failed"
? (runtimeTurnErrorMessage(event) ?? thread.session?.lastError ?? "Turn failed")
: status === "ready"
? null
: (thread.session?.lastError ?? null);
? null
: (thread.session?.lastError ?? null);
if (shouldApplyThreadLifecycle) {
yield* orchestrationEngine.dispatch({
@@ -935,7 +933,9 @@ const make = Effect.gen(function* () {
const assistantCompletion =
event.type === "item.completed" && event.payload.itemType === "assistant_message"
? {
messageId: MessageId.makeUnsafe(`assistant:${event.itemId ?? event.turnId ?? event.eventId}`),
messageId: MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
),
fallbackText: event.payload.detail,
}
: undefined;
@@ -951,10 +951,11 @@ const make = Effect.gen(function* () {
if (assistantCompletion) {
const assistantMessageId = assistantCompletion.messageId;
const turnId = toTurnId(event.turnId);
const existingAssistantMessage = thread.messages.find((entry) => entry.id === assistantMessageId);
const existingAssistantMessage = thread.messages.find(
(entry) => entry.id === assistantMessageId,
);
const shouldApplyFallbackCompletionText =
!existingAssistantMessage ||
existingAssistantMessage.text.length === 0;
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
if (turnId) {
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
}
@@ -1029,9 +1030,7 @@ const make = Effect.gen(function* () {
const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
? true
: activeTurnId === null ||
eventTurnId === undefined ||
sameId(activeTurnId, eventTurnId);
: activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId);
if (shouldApplyRuntimeError) {
yield* orchestrationEngine.dispatch({
+3 -2
View File
@@ -301,9 +301,10 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
messageId: command.message.messageId,
...(command.provider !== undefined ? { provider: command.provider } : {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.serviceTier !== undefined ? { serviceTier: command.serviceTier } : {}),
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
...(command.providerOptions !== undefined ? { providerOptions: command.providerOptions } : {}),
...(command.providerOptions !== undefined
? { providerOptions: command.providerOptions }
: {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
runtimeMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
+1 -6
View File
@@ -304,12 +304,7 @@ export function projectEvent(
);
case "thread.runtime-mode-set":
return decodeForEvent(
ThreadRuntimeModeSetPayload,
event.payload,
event.type,
"payload",
).pipe(
return decodeForEvent(ThreadRuntimeModeSetPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
@@ -70,9 +70,7 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
const upsert: ProjectionThreadProposedPlanRepositoryShape["upsert"] = (row) =>
upsertProjectionThreadProposedPlanRow(row).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadProposedPlanRepository.upsert:query"),
),
Effect.mapError(toPersistenceSqlError("ProjectionThreadProposedPlanRepository.upsert:query")),
);
const listByThreadId: ProjectionThreadProposedPlanRepositoryShape["listByThreadId"] = (input) =>
+9 -5
View File
@@ -20,9 +20,7 @@ function makeTempDir(prefix: string): string {
return dir;
}
async function withRouteServer(
run: (baseUrl: string) => Promise<void>,
): Promise<void> {
async function withRouteServer(run: (baseUrl: string) => Promise<void>): Promise<void> {
const server = http.createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://127.0.0.1");
if (tryHandleProjectFaviconRequest(url, res)) {
@@ -104,7 +102,10 @@ describe("tryHandleProjectFaviconRequest", () => {
const projectDir = makeTempDir("t3code-favicon-route-source-");
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
fs.writeFileSync(path.join(projectDir, "index.html"), '<link rel="icon" href="/brand/logo.svg">');
fs.writeFileSync(
path.join(projectDir, "index.html"),
'<link rel="icon" href="/brand/logo.svg">',
);
fs.writeFileSync(iconPath, "<svg>brand</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
@@ -120,7 +121,10 @@ describe("tryHandleProjectFaviconRequest", () => {
const projectDir = makeTempDir("t3code-favicon-route-html-order-");
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
fs.writeFileSync(path.join(projectDir, "index.html"), '<link href="/brand/logo.svg" rel="icon">');
fs.writeFileSync(
path.join(projectDir, "index.html"),
'<link href="/brand/logo.svg" rel="icon">',
);
fs.writeFileSync(iconPath, "<svg>brand-html-order</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
@@ -407,6 +407,42 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}),
);
it.effect("maps retryable Codex error notifications to runtime.warning", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
id: asEventId("evt-retryable-error"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "error",
turnId: asTurnId("turn-1"),
payload: {
error: {
message: "Reconnecting... 2/5",
},
willRetry: true,
},
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "runtime.warning");
if (firstEvent.value.type !== "runtime.warning") {
return;
}
assert.equal(firstEvent.value.turnId, "turn-1");
assert.equal(firstEvent.value.payload.message, "Reconnecting... 2/5");
}),
);
it.effect("preserves request type when mapping serverRequest/resolved", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
@@ -403,7 +403,9 @@ function asRuntimeTaskId(taskId: string): RuntimeTaskId {
return RuntimeTaskId.makeUnsafe(taskId);
}
function codexEventMessage(payload: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
function codexEventMessage(
payload: Record<string, unknown> | undefined,
): Record<string, unknown> | undefined {
return asObject(payload?.msg);
}
@@ -1037,7 +1039,9 @@ function mapToRuntimeEvents(
type: "content.delta",
payload: {
streamKind:
asNumber(msg?.summary_index) !== undefined ? "reasoning_summary_text" : "reasoning_text",
asNumber(msg?.summary_index) !== undefined
? "reasoning_summary_text"
: "reasoning_text",
delta,
...(asNumber(msg?.summary_index) !== undefined
? { summaryIndex: asNumber(msg?.summary_index) }
@@ -1192,13 +1196,14 @@ function mapToRuntimeEvents(
if (event.method === "error") {
const message =
asString(asObject(payload?.error)?.message) ?? event.message ?? "Provider runtime error";
const willRetry = payload?.willRetry === true;
return [
{
type: "runtime.error",
type: willRetry ? "runtime.warning" : "runtime.error",
...runtimeEventBase(event, canonicalThreadId),
payload: {
message,
class: "provider_error",
...(!willRetry ? { class: "provider_error" as const } : {}),
...(event.payload !== undefined ? { detail: event.payload } : {}),
},
},
@@ -1313,9 +1318,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
detail: toMessage(cause, "Failed to start Codex adapter session."),
cause,
}),
}).pipe(
Effect.map((session) => session),
);
}).pipe(Effect.map((session) => session));
};
const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>
@@ -1354,7 +1357,6 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
threadId: input.threadId,
...(input.input !== undefined ? { input: input.input } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions?.codex?.reasoningEffort !== undefined
? { effort: input.modelOptions.codex.reasoningEffort }
: {}),
@@ -29,10 +29,7 @@ const fakeCodexAdapter: CodexAdapterShape = {
const layer = it.layer(
Layer.mergeAll(
Layer.provide(
ProviderAdapterRegistryLive,
Layer.succeed(CodexAdapter, fakeCodexAdapter),
),
Layer.provide(ProviderAdapterRegistryLive, Layer.succeed(CodexAdapter, fakeCodexAdapter)),
NodeServices.layer,
),
);
@@ -23,10 +23,7 @@ export interface ProviderAdapterRegistryLiveOptions {
const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
Effect.gen(function* () {
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter];
const adapters = options?.adapters !== undefined ? options.adapters : [yield* CodexAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
@@ -1,10 +1,19 @@
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { it } from "@effect/vitest";
import { Effect, Layer, Sink, Stream } from "effect";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { afterEach, beforeEach, describe } from "vitest";
import { checkCodexProviderStatus, parseAuthStatusFromOutput } from "./ProviderHealth";
import {
checkCodexProviderStatus,
hasCustomModelProvider,
parseAuthStatusFromOutput,
readCodexConfigModelProvider,
} from "./ProviderHealth";
// ── Test helpers ────────────────────────────────────────────────────
@@ -53,88 +62,99 @@ function failingSpawnerLayer(description: string) {
);
}
// ── Tests ───────────────────────────────────────────────────────────
/**
* Create a temporary CODEX_HOME with an optional config.toml content.
* Returns a cleanup function that restores the original env var.
*/
function withTempCodexHome(configContent?: string): { tmpDir: string; cleanup: () => void } {
const originalCodexHome = process.env.CODEX_HOME;
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-test-codex-"));
process.env.CODEX_HOME = tmpDir;
if (configContent !== undefined) {
fs.writeFileSync(path.join(tmpDir, "config.toml"), configContent);
}
return {
tmpDir,
cleanup: () => {
if (originalCodexHome !== undefined) {
process.env.CODEX_HOME = originalCodexHome;
} else {
delete process.env.CODEX_HOME;
}
fs.rmSync(tmpDir, { recursive: true, force: true });
},
};
}
it.effect("returns ready when codex is installed and authenticated", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
// ── checkCodexProviderStatus tests ──────────────────────────────────
//
// These tests control CODEX_HOME to ensure the custom-provider detection
// in hasCustomModelProvider() does not interfere with the auth-probe
// path being tested.
describe("checkCodexProviderStatus", () => {
let cleanup: () => void;
// Point CODEX_HOME at an empty tmp dir (no config.toml) so the
// default code path (OpenAI provider, auth probe runs) is exercised.
beforeEach(() => {
({ cleanup } = withTempCodexHome());
});
afterEach(() => cleanup());
it.effect("returns ready when codex is installed and authenticated", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
),
);
);
it.effect("returns unavailable when codex is missing", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
it.effect("returns unavailable when codex is missing", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
it.effect("returns unavailable when codex is below the minimum supported version", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
it.effect("returns unavailable when codex is below the minimum supported version", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
),
);
);
it.effect("returns unauthenticated when auth probe reports login required", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect(
"returns unauthenticated when login status output includes 'not logged in'",
() =>
it.effect("returns unauthenticated when auth probe reports login required", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
@@ -145,6 +165,137 @@ it.effect(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect(
"returns unauthenticated when login status output includes 'not logged in'",
() =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when login status command is unsupported", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── Custom model provider: checkCodexProviderStatus integration ─────
describe("checkCodexProviderStatus with custom model provider", () => {
let cleanup: () => void;
beforeEach(() => {
({ cleanup } = withTempCodexHome(
['model_provider = "portkey"', "", "[model_providers.portkey]", 'base_url = "https://api.portkey.ai/v1"', 'env_key = "PORTKEY_API_KEY"'].join(
"\n",
),
));
});
afterEach(() => cleanup());
it.effect(
"skips auth probe and returns ready when a custom model provider is configured",
() =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Using a custom Codex model provider; OpenAI login check skipped.",
);
}).pipe(
Effect.provide(
// The spawner only handles --version; if the test attempts
// "login status" the throw proves the auth probe was NOT skipped.
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
throw new Error(`Auth probe should have been skipped but got args: ${joined}`);
}),
),
),
);
it.effect(
"still reports error when codex CLI is missing even with custom provider",
() =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
});
describe("checkCodexProviderStatus with openai model provider", () => {
let cleanup: () => void;
beforeEach(() => {
({ cleanup } = withTempCodexHome('model_provider = "openai"\n'));
});
afterEach(() => cleanup());
it.effect("still runs auth probe when model_provider is openai", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
// The auth probe runs and sees "not logged in" → error
assert.strictEqual(status.status, "error");
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -156,57 +307,153 @@ it.effect(
}),
),
),
);
);
});
it.effect("returns warning when login status command is unsupported", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
// ── parseAuthStatusFromOutput pure tests ────────────────────────────
describe("parseAuthStatusFromOutput", () => {
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with authenticated=false is unauthenticated", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"authenticated":false}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"ok":true}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
// ── readCodexConfigModelProvider tests ───────────────────────────────
describe("readCodexConfigModelProvider", () => {
let cleanup: () => void;
let tmpDir: string;
beforeEach(() => {
({ tmpDir, cleanup } = withTempCodexHome());
});
afterEach(() => cleanup());
it("returns undefined when config file does not exist", () => {
assert.strictEqual(readCodexConfigModelProvider(), undefined);
});
it("returns undefined when config has no model_provider key", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model = "gpt-5-codex"\n');
assert.strictEqual(readCodexConfigModelProvider(), undefined);
});
it("returns the provider when model_provider is set at top level", () => {
fs.writeFileSync(
path.join(tmpDir, "config.toml"),
'model = "gpt-5-codex"\nmodel_provider = "portkey"\n',
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
// ── Pure function tests ─────────────────────────────────────────────
it("parseAuthStatusFromOutput: exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("parseAuthStatusFromOutput: JSON with authenticated=false is unauthenticated", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"authenticated":false}]\n',
stderr: "",
code: 0,
assert.strictEqual(readCodexConfigModelProvider(), "portkey");
});
it("returns openai when model_provider is openai", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "openai"\n');
assert.strictEqual(readCodexConfigModelProvider(), "openai");
});
it("ignores model_provider inside section headers", () => {
fs.writeFileSync(
path.join(tmpDir, "config.toml"),
[
'model = "gpt-5-codex"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'model_provider = "should-be-ignored"',
"",
].join("\n"),
);
assert.strictEqual(readCodexConfigModelProvider(), undefined);
});
it("handles comments and whitespace", () => {
fs.writeFileSync(
path.join(tmpDir, "config.toml"),
[
"# This is a comment",
"",
' model_provider = "azure" ',
"",
"[profiles.deep-review]",
'model = "gpt-5-pro"',
].join("\n"),
);
assert.strictEqual(readCodexConfigModelProvider(), "azure");
});
it("handles single-quoted values in TOML", () => {
fs.writeFileSync(
path.join(tmpDir, "config.toml"),
"model_provider = 'mistral'\n",
);
assert.strictEqual(readCodexConfigModelProvider(), "mistral");
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("parseAuthStatusFromOutput: JSON without auth marker is warning", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"ok":true}]\n',
stderr: "",
code: 0,
// ── hasCustomModelProvider tests ─────────────────────────────────────
describe("hasCustomModelProvider", () => {
let cleanup: () => void;
let tmpDir: string;
beforeEach(() => {
({ tmpDir, cleanup } = withTempCodexHome());
});
afterEach(() => cleanup());
it("returns false when no config file exists", () => {
assert.strictEqual(hasCustomModelProvider(), false);
});
it("returns false when model_provider is not set", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model = "gpt-5-codex"\n');
assert.strictEqual(hasCustomModelProvider(), false);
});
it("returns false when model_provider is openai", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "openai"\n');
assert.strictEqual(hasCustomModelProvider(), false);
});
it("returns true when model_provider is portkey", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "portkey"\n');
assert.strictEqual(hasCustomModelProvider(), true);
});
it("returns true when model_provider is azure", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "azure"\n');
assert.strictEqual(hasCustomModelProvider(), true);
});
it("returns true when model_provider is ollama", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "ollama"\n');
assert.strictEqual(hasCustomModelProvider(), true);
});
it("returns true when model_provider is a custom proxy", () => {
fs.writeFileSync(path.join(tmpDir, "config.toml"), 'model_provider = "my-company-proxy"\n');
assert.strictEqual(hasCustomModelProvider(), true);
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
@@ -8,12 +8,15 @@
*
* @module ProviderHealthLive
*/
import * as fs from "node:fs";
import * as OS from "node:os";
import * as NodePath from "node:path";
import type {
ServerProviderAuthStatus,
ServerProviderStatus,
ServerProviderStatusState,
} from "@t3tools/contracts";
import { Effect, Layer, Option, Result, Stream } from "effect";
import { Array, Effect, Fiber, Layer, Option, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
@@ -167,6 +170,70 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
};
}
// ── Codex CLI config detection ──────────────────────────────────────
/**
* Providers that use OpenAI-native authentication via `codex login`.
* When the configured `model_provider` is one of these, the `codex login
* status` probe still runs. For any other provider value the auth probe
* is skipped because authentication is handled externally (e.g. via
* environment variables like `PORTKEY_API_KEY` or `AZURE_API_KEY`).
*/
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
/**
* Read the `model_provider` value from the Codex CLI config file.
*
* Looks for the file at `$CODEX_HOME/config.toml` (falls back to
* `~/.codex/config.toml`). Uses a simple line-by-line scan rather than
* a full TOML parser to avoid adding a dependency for a single key.
*
* Returns `undefined` when the file does not exist or does not set
* `model_provider`.
*/
export function readCodexConfigModelProvider(): string | undefined {
const codexHome = process.env.CODEX_HOME || NodePath.join(OS.homedir(), ".codex");
const configPath = NodePath.join(codexHome, "config.toml");
let content: string;
try {
content = fs.readFileSync(configPath, "utf8");
} catch {
return undefined;
}
// We need to find `model_provider = "..."` at the top level of the
// TOML file (i.e. before any `[section]` header). Lines inside
// `[profiles.*]`, `[model_providers.*]`, etc. are ignored.
let inTopLevel = true;
for (const line of content.split("\n")) {
const trimmed = line.trim();
// Skip comments and empty lines.
if (!trimmed || trimmed.startsWith("#")) continue;
// Detect section headers — once we leave the top level, stop.
if (trimmed.startsWith("[")) {
inTopLevel = false;
continue;
}
if (!inTopLevel) continue;
const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);
if (match) return match[1];
}
return undefined;
}
/**
* Returns `true` when the Codex CLI is configured with a custom
* (non-OpenAI) model provider, meaning `codex login` auth is not
* required because authentication is handled through provider-specific
* environment variables.
*/
export function hasCustomModelProvider(): boolean {
const provider = readCodexConfigModelProvider();
return provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider);
}
// ── Effect-native command execution ─────────────────────────────────
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
@@ -265,6 +332,22 @@ export const checkCodexProviderStatus: Effect.Effect<
}
// Probe 2: `codex login status` — is the user authenticated?
//
// Custom model providers (e.g. Portkey, Azure OpenAI proxy) handle
// authentication through their own environment variables, so `codex
// login status` will report "not logged in" even when the CLI works
// fine. Skip the auth probe entirely for non-OpenAI providers.
if (hasCustomModelProvider()) {
return {
provider: CODEX_PROVIDER,
status: "ready" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message: "Using a custom Codex model provider; OpenAI login check skipped.",
} satisfies ServerProviderStatus;
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
@@ -312,9 +395,13 @@ export const checkCodexProviderStatus: Effect.Effect<
export const ProviderHealthLive = Layer.effect(
ProviderHealth,
Effect.gen(function* () {
const codexStatus = yield* checkCodexProviderStatus;
const codexStatusFiber = yield* checkCodexProviderStatus.pipe(
Effect.map(Array.of),
Effect.forkScoped,
);
return {
getStatuses: Effect.succeed([codexStatus]),
getStatuses: Fiber.join(codexStatusFiber),
} satisfies ProviderHealthShape;
}),
);
@@ -635,7 +635,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn");
}
}
}),
);
});
@@ -141,9 +141,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
Effect.succeed(event).pipe(
Effect.tap((canonicalEvent) =>
canonicalEventLogger
? canonicalEventLogger.write(canonicalEvent, null)
: Effect.void,
canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
),
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
Effect.asVoid,
@@ -193,7 +191,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
if (hasActiveSession) {
const activeSessions = yield* adapter.listSessions();
const existing = activeSessions.find((session) => session.threadId === input.binding.threadId);
const existing = activeSessions.find(
(session) => session.threadId === input.binding.threadId,
);
if (existing) {
yield* upsertSessionBinding(existing, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
@@ -292,7 +292,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
yield* upsertSessionBinding(session, threadId, {
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
...(input.providerOptions !== undefined
? { providerOptions: input.providerOptions }
: {}),
});
yield* analytics.record("provider.session.started", {
provider: session.provider,
@@ -425,23 +427,23 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const listSessions: ProviderServiceShape["listSessions"] = () =>
Effect.gen(function* () {
const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) => adapter.listSessions());
const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
);
const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
const persistedBindings = yield* directory
.listThreadIds()
.pipe(
Effect.flatMap((threadIds) =>
Effect.forEach(
threadIds,
(threadId) =>
directory.getBinding(threadId).pipe(
Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>()),
),
{ concurrency: "unbounded" },
),
const persistedBindings = yield* directory.listThreadIds().pipe(
Effect.flatMap((threadIds) =>
Effect.forEach(
threadIds,
(threadId) =>
directory
.getBinding(threadId)
.pipe(Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>())),
{ concurrency: "unbounded" },
),
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
);
),
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
);
const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
for (const bindingOption of persistedBindings) {
const binding = Option.getOrUndefined(bindingOption);
@@ -2,10 +2,7 @@ import { type ProviderKind, type ThreadId } from "@t3tools/contracts";
import { Effect, Layer, Option } from "effect";
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
import {
ProviderSessionDirectoryPersistenceError,
ProviderValidationError,
} from "../Errors.ts";
import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts";
import {
ProviderSessionDirectory,
type ProviderRuntimeBinding,
@@ -138,7 +135,9 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
const remove: ProviderSessionDirectoryShape["remove"] = (threadId) =>
repository
.deleteByThreadId({ threadId })
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.remove:deleteByThreadId")));
.pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.remove:deleteByThreadId")),
);
const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () =>
repository.list().pipe(
@@ -66,10 +66,7 @@ export interface ProviderAdapterShape<TError> {
/**
* Interrupt an active turn.
*/
readonly interruptTurn: (
threadId: ThreadId,
turnId?: TurnId,
) => Effect.Effect<void, TError>;
readonly interruptTurn: (threadId: ThreadId, turnId?: TurnId) => Effect.Effect<void, TError>;
/**
* Respond to an interactive approval request.
@@ -107,9 +104,7 @@ export interface ProviderAdapterShape<TError> {
/**
* Read a provider thread snapshot.
*/
readonly readThread: (
threadId: ThreadId,
) => Effect.Effect<ProviderThreadSnapshot, TError>;
readonly readThread: (threadId: ThreadId) => Effect.Effect<ProviderThreadSnapshot, TError>;
/**
* Roll back a provider thread by N turns.
+84 -20
View File
@@ -1236,21 +1236,19 @@ describe("WebSocket Server", () => {
return event.type === "thread.session-set";
});
emitRuntimeEvent(
{
type: "content.delta",
eventId: asEventId("evt-ws-runtime-message-delta"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
turnId: asTurnId("turn-1"),
itemId: asProviderItemId("item-1"),
payload: {
streamKind: "assistant_text",
delta: "hello from runtime",
},
} as unknown as ProviderRuntimeEvent,
);
emitRuntimeEvent({
type: "content.delta",
eventId: asEventId("evt-ws-runtime-message-delta"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
turnId: asTurnId("turn-1"),
itemId: asProviderItemId("item-1"),
payload: {
streamKind: "assistant_text",
delta: "hello from runtime",
},
} as unknown as ProviderRuntimeEvent);
const domainPush = await waitForPush(ws, ORCHESTRATION_WS_CHANNELS.domainEvent, (push) => {
const event = push.data as { type?: string; payload?: { messageId?: string; text?: string } };
@@ -1333,9 +1331,7 @@ describe("WebSocket Server", () => {
};
terminalManager.emitEvent(manualEvent);
const push = (await waitForMessage(ws)) as WsPush;
expect(push.type).toBe("push");
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
const push = await waitForPush(ws, WS_CHANNELS.terminalEvent);
expect((push.data as TerminalEvent).type).toBe("output");
});
@@ -1570,7 +1566,9 @@ describe("WebSocket Server", () => {
});
expect(response.result).toBeUndefined();
expect(response.error?.message).toContain("Workspace file path must stay within the project root.");
expect(response.error?.message).toContain(
"Workspace file path must stay within the project root.",
);
expect(fs.existsSync(path.join(workspace, "..", "escape.md"))).toBe(false);
});
@@ -1640,7 +1638,14 @@ describe("WebSocket Server", () => {
const status = vi.fn(() => Effect.succeed(statusResult));
const runStackedAction = vi.fn(() => Effect.void as any);
const gitManager: GitManagerShape = { status, runStackedAction };
const resolvePullRequest = vi.fn(() => Effect.void as any);
const preparePullRequestThread = vi.fn(() => Effect.void as any);
const gitManager: GitManagerShape = {
status,
resolvePullRequest,
preparePullRequestThread,
runStackedAction,
};
server = await createTestServer({ cwd: "/test", gitManager });
const addr = server.address();
@@ -1658,6 +1663,63 @@ describe("WebSocket Server", () => {
expect(status).toHaveBeenCalledWith({ cwd: "/test" });
});
it("supports git pull request routing over websocket", async () => {
const resolvePullRequestResult = {
pullRequest: {
number: 42,
title: "PR thread flow",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseBranch: "main",
headBranch: "feature/pr-threads",
state: "open" as const,
},
};
const preparePullRequestThreadResult = {
...resolvePullRequestResult,
branch: "feature/pr-threads",
worktreePath: "/tmp/pr-threads",
};
const gitManager: GitManagerShape = {
status: vi.fn(() => Effect.void as any),
resolvePullRequest: vi.fn(() => Effect.succeed(resolvePullRequestResult)),
preparePullRequestThread: vi.fn(() => Effect.succeed(preparePullRequestThreadResult)),
runStackedAction: vi.fn(() => Effect.void as any),
};
server = await createTestServer({ cwd: "/test", gitManager });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const resolveResponse = await sendRequest(ws, WS_METHODS.gitResolvePullRequest, {
cwd: "/test",
reference: "#42",
});
expect(resolveResponse.error).toBeUndefined();
expect(resolveResponse.result).toEqual(resolvePullRequestResult);
const prepareResponse = await sendRequest(ws, WS_METHODS.gitPreparePullRequestThread, {
cwd: "/test",
reference: "42",
mode: "worktree",
});
expect(prepareResponse.error).toBeUndefined();
expect(prepareResponse.result).toEqual(preparePullRequestThreadResult);
expect(gitManager.resolvePullRequest).toHaveBeenCalledWith({
cwd: "/test",
reference: "#42",
});
expect(gitManager.preparePullRequestThread).toHaveBeenCalledWith({
cwd: "/test",
reference: "42",
mode: "worktree",
});
});
it("returns errors from git.runStackedAction", async () => {
const runStackedAction = vi.fn(() =>
Effect.fail(
@@ -1669,6 +1731,8 @@ describe("WebSocket Server", () => {
);
const gitManager: GitManagerShape = {
status: vi.fn(() => Effect.void as any),
resolvePullRequest: vi.fn(() => Effect.void as any),
preparePullRequestThread: vi.fn(() => Effect.void as any),
runStackedAction,
};
+42 -18
View File
@@ -26,6 +26,7 @@ import {
WebSocketRequest,
WsPush,
WsResponse,
ServerProviderStatus,
} from "@t3tools/contracts";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import {
@@ -197,8 +198,7 @@ function stripRequestTag<T extends { _tag: string }>(body: T) {
function messageFromCause(cause: Cause.Cause<unknown>): string {
const squashed = Cause.squash(cause);
const message =
squashed instanceof Error ? squashed.message.trim() : String(squashed).trim();
const message = squashed instanceof Error ? squashed.message.trim() : String(squashed).trim();
return message.length > 0 ? message : Cause.pretty(cause);
}
@@ -268,8 +268,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
),
);
const providerStatuses = yield* providerHealth.getStatuses;
const clients = yield* Ref.make(new Set<WebSocket>());
const logger = createLogger("ws");
@@ -331,10 +329,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
} satisfies OrchestrationCommand;
}
if (
input.command.type === "project.meta.update" &&
input.command.workspaceRoot !== undefined
) {
if (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) {
return {
...input.command,
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
@@ -617,6 +612,23 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const subscriptionsScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
// Push updated provider statuses to connected clients once background health checks finish.
let providers: ReadonlyArray<ServerProviderStatus> = [];
yield* providerHealth.getStatuses.pipe(
Effect.flatMap((statuses) => {
providers = statuses;
return broadcastPush({
type: "push",
channel: WS_CHANNELS.serverConfigUpdated,
data: {
issues: [],
providers: statuses,
},
});
}),
Effect.forkIn(subscriptionsScope),
);
yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) =>
broadcastPush({
type: "push",
@@ -631,7 +643,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
channel: WS_CHANNELS.serverConfigUpdated,
data: {
issues: event.issues,
providers: providerStatuses,
providers,
},
}),
).pipe(Effect.forkIn(subscriptionsScope));
@@ -777,14 +789,16 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
relativePath: body.relativePath,
path,
});
yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new RouteRequestError({
message: `Failed to prepare workspace path: ${String(cause)}`,
}),
),
);
yield* fileSystem
.makeDirectory(path.dirname(target.absolutePath), { recursive: true })
.pipe(
Effect.mapError(
(cause) =>
new RouteRequestError({
message: `Failed to prepare workspace path: ${String(cause)}`,
}),
),
);
yield* fileSystem.writeFileString(target.absolutePath, body.contents).pipe(
Effect.mapError(
(cause) =>
@@ -816,6 +830,16 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
return yield* gitManager.runStackedAction(body);
}
case WS_METHODS.gitResolvePullRequest: {
const body = stripRequestTag(request.body);
return yield* gitManager.resolvePullRequest(body);
}
case WS_METHODS.gitPreparePullRequestThread: {
const body = stripRequestTag(request.body);
return yield* gitManager.preparePullRequestThread(body);
}
case WS_METHODS.gitListBranches: {
const body = stripRequestTag(request.body);
return yield* git.listBranches(body);
@@ -883,7 +907,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
providers: providerStatuses,
providers,
availableEditors,
};
+5 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.5",
"version": "0.0.9",
"private": true,
"type": "module",
"scripts": {
@@ -15,6 +15,10 @@
},
"dependencies": {
"@base-ui/react": "^1.2.0",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
+2 -33
View File
@@ -4,8 +4,6 @@ import {
getAppModelOptions,
getSlashModelOptions,
normalizeCustomModelSlugs,
resolveAppServiceTier,
shouldShowFastTierIcon,
resolveAppModelSelection,
} from "./appSettings";
@@ -63,43 +61,14 @@ describe("resolveAppModelSelection", () => {
describe("getSlashModelOptions", () => {
it("includes saved custom model slugs for /model command suggestions", () => {
const options = getSlashModelOptions(
"codex",
["custom/internal-model"],
"",
"gpt-5.3-codex",
);
const options = getSlashModelOptions("codex", ["custom/internal-model"], "", "gpt-5.3-codex");
expect(options.some((option) => option.slug === "custom/internal-model")).toBe(true);
});
it("filters slash-model suggestions across built-in and custom model names", () => {
const options = getSlashModelOptions(
"codex",
["openai/gpt-oss-120b"],
"oss",
"gpt-5.3-codex",
);
const options = getSlashModelOptions("codex", ["openai/gpt-oss-120b"], "oss", "gpt-5.3-codex");
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
});
});
describe("resolveAppServiceTier", () => {
it("maps automatic to no override", () => {
expect(resolveAppServiceTier("auto")).toBeNull();
});
it("preserves explicit service tier overrides", () => {
expect(resolveAppServiceTier("fast")).toBe("fast");
expect(resolveAppServiceTier("flex")).toBe("flex");
});
});
describe("shouldShowFastTierIcon", () => {
it("shows the fast-tier icon only for gpt-5.4 on fast tier", () => {
expect(shouldShowFastTierIcon("gpt-5.4", "fast")).toBe(true);
expect(shouldShowFastTierIcon("gpt-5.4", "auto")).toBe(false);
expect(shouldShowFastTierIcon("gpt-5.3-codex", "fast")).toBe(false);
});
});
+1 -38
View File
@@ -1,31 +1,11 @@
import { useCallback, useSyncExternalStore } from "react";
import { Option, Schema } from "effect";
import { type ProviderKind, type ProviderServiceTier } from "@t3tools/contracts";
import { type ProviderKind } from "@t3tools/contracts";
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
export const APP_SERVICE_TIER_OPTIONS = [
{
value: "auto",
label: "Automatic",
description: "Use Codex defaults without forcing a service tier.",
},
{
value: "fast",
label: "Fast",
description: "Request the fast service tier when the model supports it.",
},
{
value: "flex",
label: "Flex",
description: "Request the flex service tier when the model supports it.",
},
] as const;
export type AppServiceTier = (typeof APP_SERVICE_TIER_OPTIONS)[number]["value"];
const AppServiceTierSchema = Schema.Literals(["auto", "fast", "flex"]);
const MODELS_WITH_FAST_SUPPORT = new Set(["gpt-5.4"]);
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
};
@@ -41,7 +21,6 @@ const AppSettingsSchema = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.pipe(
Schema.withConstructorDefault(() => Option.some(false)),
),
codexServiceTier: AppServiceTierSchema.pipe(Schema.withConstructorDefault(() => Option.some("auto"))),
customCodexModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
@@ -53,22 +32,6 @@ export interface AppModelOption {
isCustom: boolean;
}
export function resolveAppServiceTier(serviceTier: AppServiceTier): ProviderServiceTier | null {
return serviceTier === "auto" ? null : serviceTier;
}
export function shouldShowFastTierIcon(
model: string | null | undefined,
serviceTier: AppServiceTier,
): boolean {
const normalizedModel = normalizeModelSlug(model);
return (
resolveAppServiceTier(serviceTier) === "fast" &&
normalizedModel !== null &&
MODELS_WITH_FAST_SUPPORT.has(normalizedModel)
);
}
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
let listeners: Array<() => void> = [];
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
resolveBranchSelectionTarget,
resolveDraftEnvModeAfterBranchChange,
resolveBranchToolbarValue,
} from "./BranchToolbar.logic";
@@ -194,3 +195,73 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
]);
});
});
describe("resolveBranchSelectionTarget", () => {
it("reuses an existing secondary worktree for the selected branch", () => {
expect(
resolveBranchSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
branch: {
isDefault: false,
worktreePath: "/repo/.t3/worktrees/feature-b",
},
}),
).toEqual({
checkoutCwd: "/repo/.t3/worktrees/feature-b",
nextWorktreePath: "/repo/.t3/worktrees/feature-b",
reuseExistingWorktree: true,
});
});
it("switches back to the main repo when the branch already lives there", () => {
expect(
resolveBranchSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
branch: {
isDefault: true,
worktreePath: "/repo",
},
}),
).toEqual({
checkoutCwd: "/repo",
nextWorktreePath: null,
reuseExistingWorktree: true,
});
});
it("checks out the default branch in the main repo when leaving a secondary worktree", () => {
expect(
resolveBranchSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
branch: {
isDefault: true,
worktreePath: null,
},
}),
).toEqual({
checkoutCwd: "/repo",
nextWorktreePath: null,
reuseExistingWorktree: false,
});
});
it("keeps checkout in the current worktree for non-default branches", () => {
expect(
resolveBranchSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
branch: {
isDefault: false,
worktreePath: null,
},
}),
).toEqual({
checkoutCwd: "/repo/.t3/worktrees/feature-a",
nextWorktreePath: "/repo/.t3/worktrees/feature-a",
reuseExistingWorktree: false,
});
});
});
@@ -88,3 +88,32 @@ export function dedupeRemoteBranchesWithLocalMatches(
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
});
}
export function resolveBranchSelectionTarget(input: {
activeProjectCwd: string;
activeWorktreePath: string | null;
branch: Pick<GitBranch, "isDefault" | "worktreePath">;
}): {
checkoutCwd: string;
nextWorktreePath: string | null;
reuseExistingWorktree: boolean;
} {
const { activeProjectCwd, activeWorktreePath, branch } = input;
if (branch.worktreePath) {
return {
checkoutCwd: branch.worktreePath,
nextWorktreePath: branch.worktreePath === activeProjectCwd ? null : branch.worktreePath,
reuseExistingWorktree: true,
};
}
const nextWorktreePath =
activeWorktreePath !== null && branch.isDefault ? null : activeWorktreePath;
return {
checkoutCwd: nextWorktreePath ?? activeProjectCwd,
nextWorktreePath,
reuseExistingWorktree: false,
};
}
@@ -17,6 +17,7 @@ interface BranchToolbarProps {
threadId: ThreadId;
onEnvModeChange: (mode: EnvMode) => void;
envLocked: boolean;
onCheckoutPullRequestRequest?: (reference: string) => void;
onComposerFocusRequest?: () => void;
}
@@ -24,6 +25,7 @@ export default function BranchToolbar({
threadId,
onEnvModeChange,
envLocked,
onCheckoutPullRequestRequest,
onComposerFocusRequest,
}: BranchToolbarProps) {
const threads = useStore((store) => store.threads);
@@ -128,6 +130,7 @@ export default function BranchToolbar({
effectiveEnvMode={effectiveEnvMode}
envLocked={envLocked}
onSetThreadBranch={setThreadBranch}
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
/>
</div>
@@ -3,7 +3,9 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { ChevronDownIcon } from "lucide-react";
import {
type CSSProperties,
useCallback,
useDeferredValue,
useEffect,
useMemo,
useOptimistic,
@@ -12,12 +14,19 @@ import {
useTransition,
} from "react";
import { gitBranchesQueryOptions, gitQueryKeys, invalidateGitQueries } from "../lib/gitReactQuery";
import {
gitBranchesQueryOptions,
gitQueryKeys,
gitStatusQueryOptions,
invalidateGitQueries,
} from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { parsePullRequestReference } from "../pullRequestReference";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
EnvMode,
resolveBranchSelectionTarget,
resolveBranchToolbarValue,
} from "./BranchToolbar.logic";
import { Button } from "./ui/button";
@@ -40,6 +49,7 @@ interface BranchToolbarBranchSelectorProps {
effectiveEnvMode: EnvMode;
envLocked: boolean;
onSetThreadBranch: (branch: string | null, worktreePath: string | null) => void;
onCheckoutPullRequestRequest?: (reference: string) => void;
onComposerFocusRequest?: () => void;
}
@@ -70,18 +80,22 @@ export function BranchToolbarBranchSelector({
effectiveEnvMode,
envLocked,
onSetThreadBranch,
onCheckoutPullRequestRequest,
onComposerFocusRequest,
}: BranchToolbarBranchSelectorProps) {
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd));
const branches = useMemo(
() => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
[branchesQuery.data?.branches],
);
const currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
const currentGitBranch =
branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
const canonicalActiveBranch = resolveBranchToolbarValue({
envMode: effectiveEnvMode,
activeWorktreePath,
@@ -94,34 +108,44 @@ export function BranchToolbarBranchSelector({
[branches],
);
const trimmedBranchQuery = branchQuery.trim();
const normalizedBranchQuery = trimmedBranchQuery.toLowerCase();
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
const prReference = parsePullRequestReference(trimmedBranchQuery);
const isSelectingWorktreeBase =
effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
const checkoutPullRequestItemValue =
prReference && onCheckoutPullRequestRequest ? `__checkout_pull_request__:${prReference}` : null;
const canCreateBranch = !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
const createBranchItemValue = canCreateBranch
? `__create_new_branch__:${trimmedBranchQuery}`
: null;
const branchPickerItems = useMemo(
() =>
createBranchItemValue && !hasExactBranchMatch
? [...branchNames, createBranchItemValue]
: branchNames,
[branchNames, createBranchItemValue, hasExactBranchMatch],
);
const branchPickerItems = useMemo(() => {
const items = [...branchNames];
if (createBranchItemValue && !hasExactBranchMatch) {
items.push(createBranchItemValue);
}
if (checkoutPullRequestItemValue) {
items.unshift(checkoutPullRequestItemValue);
}
return items;
}, [branchNames, checkoutPullRequestItemValue, createBranchItemValue, hasExactBranchMatch]);
const filteredBranchPickerItems = useMemo(
() =>
normalizedBranchQuery.length === 0
normalizedDeferredBranchQuery.length === 0
? branchPickerItems
: branchPickerItems.filter((itemValue) => {
if (createBranchItemValue && itemValue === createBranchItemValue) return true;
return itemValue.toLowerCase().includes(normalizedBranchQuery);
return itemValue.toLowerCase().includes(normalizedDeferredBranchQuery);
}),
[branchPickerItems, createBranchItemValue, normalizedBranchQuery],
[branchPickerItems, createBranchItemValue, normalizedDeferredBranchQuery],
);
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
canonicalActiveBranch,
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
);
const [isBranchActionPending, startBranchActionTransition] = useTransition();
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
@@ -135,17 +159,22 @@ export function BranchToolbarBranchSelector({
if (!api || !branchCwd || isBranchActionPending) return;
// In new-worktree mode, selecting a branch sets the base branch.
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
if (isSelectingWorktreeBase) {
onSetThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
const selectionTarget = resolveBranchSelectionTarget({
activeProjectCwd,
activeWorktreePath,
branch,
});
// If the branch already lives in a worktree, point the thread there.
if (branch.worktreePath) {
const isMainWorktree = branch.worktreePath === activeProjectCwd;
onSetThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
if (selectionTarget.reuseExistingWorktree) {
onSetThreadBranch(branch.name, selectionTarget.nextWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
@@ -161,7 +190,7 @@ export function BranchToolbarBranchSelector({
runBranchAction(async () => {
setOptimisticBranch(selectedBranchName);
try {
await api.git.checkout({ cwd: branchCwd, branch: branch.name });
await api.git.checkout({ cwd: selectionTarget.checkoutCwd, branch: branch.name });
await invalidateGitQueries(queryClient);
} catch (error) {
toastManager.add({
@@ -181,7 +210,7 @@ export function BranchToolbarBranchSelector({
}
setOptimisticBranch(nextBranchName);
onSetThreadBranch(nextBranchName, activeWorktreePath);
onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
});
};
@@ -258,10 +287,11 @@ export function BranchToolbarBranchSelector({
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
const branchListVirtualizer = useVirtualizer({
count: filteredBranchPickerItems.length,
estimateSize: () => 28,
estimateSize: (index) =>
filteredBranchPickerItems[index] === checkoutPullRequestItemValue ? 44 : 28,
getScrollElement: () => branchListScrollElementRef.current,
overscan: 12,
enabled: isBranchMenuOpen,
enabled: isBranchMenuOpen && shouldVirtualizeBranchList,
initialRect: {
height: 224,
width: 0,
@@ -280,11 +310,16 @@ export function BranchToolbarBranchSelector({
);
useEffect(() => {
if (!isBranchMenuOpen) return;
if (!isBranchMenuOpen || !shouldVirtualizeBranchList) return;
queueMicrotask(() => {
branchListVirtualizer.measure();
});
}, [branchListVirtualizer, filteredBranchPickerItems.length, isBranchMenuOpen]);
}, [
branchListVirtualizer,
filteredBranchPickerItems.length,
isBranchMenuOpen,
shouldVirtualizeBranchList,
]);
const triggerLabel = getBranchTriggerLabel({
activeWorktreePath,
@@ -292,12 +327,84 @@ export function BranchToolbarBranchSelector({
resolvedActiveBranch,
});
function renderPickerItem(itemValue: string, index: number, style?: CSSProperties) {
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
return (
<ComboboxItem
hideIndicator
key={itemValue}
index={index}
value={itemValue}
style={style}
onClick={() => {
if (!prReference || !onCheckoutPullRequestRequest) {
return;
}
setIsBranchMenuOpen(false);
setBranchQuery("");
onComposerFocusRequest?.();
onCheckoutPullRequestRequest(prReference);
}}
>
<div className="flex min-w-0 flex-col items-start py-1">
<span className="truncate font-medium">Checkout Pull Request</span>
<span className="truncate text-muted-foreground text-xs">{prReference}</span>
</div>
</ComboboxItem>
);
}
if (createBranchItemValue && itemValue === createBranchItemValue) {
return (
<ComboboxItem
hideIndicator
key={itemValue}
index={index}
value={itemValue}
style={style}
onClick={() => createBranch(trimmedBranchQuery)}
>
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
</ComboboxItem>
);
}
const branch = branchByName.get(itemValue);
if (!branch) return null;
const hasSecondaryWorktree = branch.worktreePath && branch.worktreePath !== activeProjectCwd;
const badge = branch.current
? "current"
: hasSecondaryWorktree
? "worktree"
: branch.isRemote
? "remote"
: branch.isDefault
? "default"
: null;
return (
<ComboboxItem
hideIndicator
key={itemValue}
index={index}
value={itemValue}
className={itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined}
style={style}
onClick={() => selectBranch(branch)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
</div>
</ComboboxItem>
);
}
return (
<Combobox
items={branchPickerItems}
filteredItems={filteredBranchPickerItems}
autoHighlight
virtualized
virtualized={shouldVirtualizeBranchList}
onItemHighlighted={(_value, eventDetails) => {
if (!isBranchMenuOpen || eventDetails.index < 0) return;
branchListVirtualizer.scrollToIndex(eventDetails.index, { align: "auto" });
@@ -309,12 +416,12 @@ export function BranchToolbarBranchSelector({
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={branchesQuery.isLoading || isBranchActionPending}
disabled={(branchesQuery.isLoading && branches.length === 0) || isBranchActionPending}
>
<span className="max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon />
</ComboboxTrigger>
<ComboboxPopup align="end" side="top" className="w-64">
<ComboboxPopup align="end" side="top" className="w-80">
<div className="border-b p-1">
<ComboboxInput
className="[&_input]:font-sans rounded-md"
@@ -329,78 +436,28 @@ export function BranchToolbarBranchSelector({
<ComboboxEmpty>No branches found.</ComboboxEmpty>
<ComboboxList ref={setBranchListRef} className="max-h-56">
<div
className="relative"
style={{
height: `${branchListVirtualizer.getTotalSize()}px`,
}}
>
{virtualBranchRows.map((virtualRow) => {
const itemValue = filteredBranchPickerItems[virtualRow.index];
if (!itemValue) return null;
if (createBranchItemValue && itemValue === createBranchItemValue) {
return (
<ComboboxItem
hideIndicator
key={itemValue}
index={virtualRow.index}
value={itemValue}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
transform: `translateY(${virtualRow.start}px)`,
}}
onClick={() => createBranch(trimmedBranchQuery)}
>
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
</ComboboxItem>
);
}
const branch = branchByName.get(itemValue);
if (!branch) return null;
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProjectCwd;
const badge = branch.current
? "current"
: hasSecondaryWorktree
? "worktree"
: branch.isRemote
? "remote"
: branch.isDefault
? "default"
: null;
return (
<ComboboxItem
hideIndicator
key={itemValue}
index={virtualRow.index}
value={itemValue}
className={
itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
transform: `translateY(${virtualRow.start}px)`,
}}
onClick={() => selectBranch(branch)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{badge && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
)}
</div>
</ComboboxItem>
);
})}
</div>
{shouldVirtualizeBranchList ? (
<div
className="relative"
style={{
height: `${branchListVirtualizer.getTotalSize()}px`,
}}
>
{virtualBranchRows.map((virtualRow) => {
const itemValue = filteredBranchPickerItems[virtualRow.index];
if (!itemValue) return null;
return renderPickerItem(itemValue, virtualRow.index, {
position: "absolute",
top: 0,
left: 0,
width: "100%",
transform: `translateY(${virtualRow.start}px)`,
});
})}
</div>
) : (
filteredBranchPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index))
)}
</ComboboxList>
</ComboboxPopup>
</Combobox>
+110 -8
View File
@@ -256,6 +256,61 @@ function createDraftOnlySnapshot(): OrchestrationReadModel {
};
}
function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-plan-target" as MessageId,
targetText: "plan thread",
});
const planMarkdown = [
"# Ship plan mode follow-up",
"",
"- Step 1: capture the thread-open trace",
"- Step 2: identify the main-thread bottleneck",
"- Step 3: keep collapsed cards cheap",
"- Step 4: render the full markdown only on demand",
"- Step 5: preserve export and save actions",
"- Step 6: add regression coverage",
"- Step 7: verify route transitions stay responsive",
"- Step 8: confirm no server-side work changed",
"- Step 9: confirm short plans still render normally",
"- Step 10: confirm long plans stay collapsed by default",
"- Step 11: confirm preview text is still useful",
"- Step 12: confirm plan follow-up flow still works",
"- Step 13: confirm timeline virtualization still behaves",
"- Step 14: confirm theme styling still looks correct",
"- Step 15: confirm save dialog behavior is unchanged",
"- Step 16: confirm download behavior is unchanged",
"- Step 17: confirm code fences do not parse until expand",
"- Step 18: confirm preview truncation ends cleanly",
"- Step 19: confirm markdown links still open in editor after expand",
"- Step 20: confirm deep hidden detail only appears after expand",
"",
"```ts",
"export const hiddenPlanImplementationDetail = 'deep hidden detail only after expand';",
"```",
].join("\n");
return {
...snapshot,
threads: snapshot.threads.map((thread) =>
thread.id === THREAD_ID
? Object.assign({}, thread, {
proposedPlans: [
{
id: "plan-browser-test",
turnId: null,
planMarkdown,
createdAt: isoAt(1_000),
updatedAt: isoAt(1_001),
},
],
updatedAt: isoAt(1_001),
})
: thread,
),
};
}
function resolveWsRpc(tag: string): unknown {
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
return fixture.snapshot;
@@ -359,9 +414,9 @@ async function setViewport(viewport: ViewportSpec): Promise<void> {
async function waitForProductionStyles(): Promise<void> {
await vi.waitFor(
() => {
expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).not.toBe(
"",
);
expect(
getComputedStyle(document.documentElement).getPropertyValue("--background").trim(),
).not.toBe("");
expect(getComputedStyle(document.body).marginTop).toBe("0px");
},
{
@@ -399,7 +454,9 @@ async function waitForComposerEditor(): Promise<HTMLElement> {
);
}
async function waitForInteractionModeButton(expectedLabel: "Chat" | "Plan"): Promise<HTMLButtonElement> {
async function waitForInteractionModeButton(
expectedLabel: "Chat" | "Plan",
): Promise<HTMLButtonElement> {
return waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
@@ -642,7 +699,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
const measurements: Array<UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }> = [];
const measurements: Array<
UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }
> = [];
for (const viewport of TEXT_VIEWPORT_MATRIX) {
await mounted.setViewport(viewport);
@@ -659,7 +718,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
measurements.push({ ...measurement, viewport, estimatedHeightPx });
}
expect(new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx))).size).toBeGreaterThanOrEqual(3);
expect(
new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx)))
.size,
).toBeGreaterThanOrEqual(3);
const byMeasuredWidth = measurements.toSorted(
(left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx,
@@ -701,7 +763,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
{ timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx },
);
const measuredDeltaPx = mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;
const measuredDeltaPx =
mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;
const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx;
expect(measuredDeltaPx).toBeGreaterThan(0);
expect(estimatedDeltaPx).toBeGreaterThan(0);
@@ -789,7 +852,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
await vi.waitFor(
() => {
const openRequest = wsRequests.find((request) => request._tag === WS_METHODS.shellOpenInEditor);
const openRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.shellOpenInEditor,
);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.shellOpenInEditor,
cwd: "/repo/project",
@@ -867,4 +932,41 @@ describe("ChatView timeline estimator parity (full app)", () => {
await mounted.cleanup();
}
});
it("keeps long proposed plans lightweight until the user expands them", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotWithLongProposedPlan(),
});
try {
await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "Expand plan",
) as HTMLButtonElement | null,
"Unable to find Expand plan button.",
);
expect(document.body.textContent).not.toContain("deep hidden detail only after expand");
const expandButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "Expand plan",
) as HTMLButtonElement | null,
"Unable to find Expand plan button.",
);
expandButton.click();
await vi.waitFor(
() => {
expect(document.body.textContent).toContain("deep hidden detail only after expand");
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
});
File diff suppressed because it is too large. Load diff
@@ -1,7 +1,4 @@
import {
LexicalComposer,
type InitialConfigType,
} from "@lexical/react/LexicalComposer";
import { LexicalComposer, type InitialConfigType } from "@lexical/react/LexicalComposer";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
@@ -331,12 +328,11 @@ function $setSelectionAtComposerOffset(nextOffset: number): void {
const composerLength = $getComposerRootLength();
const boundedOffset = Math.max(0, Math.min(nextOffset, composerLength));
const remainingRef = { value: boundedOffset };
const point =
findSelectionPointAtOffset(root, remainingRef) ?? {
key: root.getKey(),
offset: root.getChildren().length,
type: "element" as const,
};
const point = findSelectionPointAtOffset(root, remainingRef) ?? {
key: root.getKey(),
offset: root.getChildren().length,
type: "element" as const,
};
const selection = $createRangeSelection();
selection.anchor.set(point.key, point.offset, point.type);
selection.focus.set(point.key, point.offset, point.type);
@@ -724,7 +720,10 @@ function ComposerPromptEditorInner({
editorState.read(() => {
const nextValue = $getRoot().getTextContent();
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
const nextCursor = clampCursor(nextValue, $readSelectionOffsetFromEditorState(fallbackCursor));
const nextCursor = clampCursor(
nextValue,
$readSelectionOffsetFromEditorState(fallbackCursor),
);
const previousSnapshot = snapshotRef.current;
if (previousSnapshot.value === nextValue && previousSnapshot.cursor === nextCursor) {
return;
@@ -771,41 +770,42 @@ function ComposerPromptEditorInner({
);
}
export const ComposerPromptEditor = forwardRef<ComposerPromptEditorHandle, ComposerPromptEditorProps>(
function ComposerPromptEditor(
{ value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
ref,
) {
const initialValueRef = useRef(value);
const initialConfig = useMemo<InitialConfigType>(
() => ({
namespace: "t3tools-composer-editor",
editable: true,
nodes: [ComposerMentionNode],
editorState: () => {
$setComposerEditorPrompt(initialValueRef.current);
},
onError: (error) => {
throw error;
},
}),
[],
);
export const ComposerPromptEditor = forwardRef<
ComposerPromptEditorHandle,
ComposerPromptEditorProps
>(function ComposerPromptEditor(
{ value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
ref,
) {
const initialValueRef = useRef(value);
const initialConfig = useMemo<InitialConfigType>(
() => ({
namespace: "t3tools-composer-editor",
editable: true,
nodes: [ComposerMentionNode],
editorState: () => {
$setComposerEditorPrompt(initialValueRef.current);
},
onError: (error) => {
throw error;
},
}),
[],
);
return (
<LexicalComposer key={COMPOSER_EDITOR_HMR_KEY} initialConfig={initialConfig}>
<ComposerPromptEditorInner
value={value}
cursor={cursor}
disabled={disabled}
placeholder={placeholder}
onChange={onChange}
onPaste={onPaste}
editorRef={ref}
{...(onCommandKeyDown ? { onCommandKeyDown } : {})}
{...(className ? { className } : {})}
/>
</LexicalComposer>
);
},
);
return (
<LexicalComposer key={COMPOSER_EDITOR_HMR_KEY} initialConfig={initialConfig}>
<ComposerPromptEditorInner
value={value}
cursor={cursor}
disabled={disabled}
placeholder={placeholder}
onChange={onChange}
onPaste={onPaste}
editorRef={ref}
{...(onCommandKeyDown ? { onCommandKeyDown } : {})}
{...(className ? { className } : {})}
/>
</LexicalComposer>
);
});
+8 -1
View File
@@ -4,7 +4,14 @@ import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ThreadId, type TurnId } from "@t3tools/contracts";
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
import { type WheelEvent as ReactWheelEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
type WheelEvent as ReactWheelEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
@@ -344,7 +344,7 @@ describe("when: working tree has local changes", () => {
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
label: "Commit, push & create PR",
label: "Commit, push & PR",
});
});
@@ -440,7 +440,7 @@ describe("when: working tree has local changes and branch is behind upstream", (
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
label: "Commit, push & create PR",
label: "Commit, push & PR",
});
});
@@ -577,10 +577,7 @@ describe("when: branch has no upstream configured", () => {
});
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
const items = buildMenuItems(
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
false,
);
const items = buildMenuItems(status({ hasUpstream: false, pr: null, aheadCount: 0 }), false);
assert.deepEqual(items, [
{
id: "commit",
@@ -627,10 +624,7 @@ describe("when: branch has no upstream configured", () => {
});
it("buildMenuItems enables create PR when no upstream and commits are ahead", () => {
const items = buildMenuItems(
status({ hasUpstream: false, pr: null, aheadCount: 2 }),
false,
);
const items = buildMenuItems(status({ hasUpstream: false, pr: null, aheadCount: 2 }), false);
assert.deepEqual(items, [
{
id: "commit",
@@ -123,12 +123,7 @@ export function buildMenuItems(
const canCommit = !isBusy && hasChanges;
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
const canCreatePr =
!isBusy &&
hasBranch &&
!hasChanges &&
!hasOpenPr &&
gitStatus.aheadCount > 0 &&
!isBehind;
!isBusy && hasBranch && !hasChanges && !hasOpenPr && gitStatus.aheadCount > 0 && !isBehind;
const canOpenPr = !isBusy && hasOpenPr;
return [
@@ -206,7 +201,7 @@ export function resolveQuickAction(
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
}
return {
label: "Commit, push & create PR",
label: "Commit, push & PR",
disabled: false,
kind: "run_action",
action: "commit_push_pr",
+17 -11
View File
@@ -255,7 +255,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
}) => {
const actionStatus = statusOverride ?? gitStatusForActions;
const actionBranch = actionStatus?.branch ?? null;
const actionIsDefaultBranch = isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);
const actionIsDefaultBranch =
isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);
const includesCommit =
!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
if (
@@ -331,7 +332,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
stopProgressUpdates();
const resultToast = summarizeGitResult(result);
const existingOpenPrUrl = actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
const existingOpenPrUrl =
actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
const prUrl = result.pr.url ?? existingOpenPrUrl;
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
const shouldOfferOpenPrCta =
@@ -374,12 +376,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
},
}
: shouldOfferOpenPrCta
? {
actionProps: {
children: "View PR",
onClick: () => {
const api = readNativeApi();
if (!api) return;
? {
actionProps: {
children: "View PR",
onClick: () => {
const api = readNativeApi();
if (!api) return;
closeResultToast();
void api.shell.openExternal(prUrl);
},
@@ -424,7 +426,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const continuePendingDefaultBranchAction = useCallback(() => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } =
pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
action,
@@ -453,7 +456,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } =
pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
checkoutNewBranchAndRunAction({
action,
@@ -725,7 +729,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
<span className="text-muted-foreground">Branch</span>
<span className="flex items-center justify-between gap-2">
<span className="font-medium">{gitStatusForActions?.branch ?? "(detached HEAD)"}</span>
<span className="font-medium">
{gitStatusForActions?.branch ?? "(detached HEAD)"}
</span>
{isDefaultBranch && (
<span className="text-right text-warning text-xs">Warning: default branch</span>
)}
+13 -52
View File
@@ -74,10 +74,7 @@ export const VisualStudioCode: Icon = (props) => {
filterUnits="userSpaceOnUse"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feColorMatrix
in="SourceAlpha"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
/>
<feColorMatrix in="SourceAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" />
<feOffset />
<feGaussianBlur stdDeviation="4.167" />
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
@@ -94,10 +91,7 @@ export const VisualStudioCode: Icon = (props) => {
filterUnits="userSpaceOnUse"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feColorMatrix
in="SourceAlpha"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
/>
<feColorMatrix in="SourceAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" />
<feOffset />
<feGaussianBlur stdDeviation="4.167" />
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
@@ -185,28 +179,16 @@ export const Gemini: Icon = (props) => (
<ellipse cx="19.5" cy="148.5" fill="#F6C013" rx="68.5" ry="72.5" />
</g>
<g filter="url(#gemini__e)">
<path
fill="#FA4340"
d="M194 10.5C172 82.5 65.5 134.333 22.5 135L144-66l50 76.5Z"
/>
<path fill="#FA4340" d="M194 10.5C172 82.5 65.5 134.333 22.5 135L144-66l50 76.5Z" />
</g>
<g filter="url(#gemini__f)">
<path
fill="#FA4340"
d="M190.5-12.5C168.5 59.5 62 111.333 19 112L140.5-89l50 76.5Z"
/>
<path fill="#FA4340" d="M190.5-12.5C168.5 59.5 62 111.333 19 112L140.5-89l50 76.5Z" />
</g>
<g filter="url(#gemini__g)">
<path
fill="#14BB69"
d="M194.5 279.5C172.5 207.5 66 155.667 23 155l121.5 201 50-76.5Z"
/>
<path fill="#14BB69" d="M194.5 279.5C172.5 207.5 66 155.667 23 155l121.5 201 50-76.5Z" />
</g>
<g filter="url(#gemini__h)">
<path
fill="#14BB69"
d="M196.5 320.5C174.5 248.5 68 196.667 25 196l121.5 201 50-76.5Z"
/>
<path fill="#14BB69" d="M196.5 320.5C174.5 248.5 68 196.667 25 196l121.5 201 50-76.5Z" />
</g>
</g>
<defs>
@@ -221,10 +203,7 @@ export const Gemini: Icon = (props) => (
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
<feGaussianBlur
result="effect1_foregroundBlur_69_17998"
stdDeviation="18"
/>
<feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="18" />
</filter>
<filter
id="gemini__c"
@@ -237,10 +216,7 @@ export const Gemini: Icon = (props) => (
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
<feGaussianBlur
result="effect1_foregroundBlur_69_17998"
stdDeviation="32"
/>
<feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" />
</filter>
<filter
id="gemini__d"
@@ -253,10 +229,7 @@ export const Gemini: Icon = (props) => (
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
<feGaussianBlur
result="effect1_foregroundBlur_69_17998"
stdDeviation="32"
/>
<feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" />
</filter>
<filter
id="gemini__e"
@@ -269,10 +242,7 @@ export const Gemini: Icon = (props) => (
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
<feGaussianBlur
result="effect1_foregroundBlur_69_17998"
stdDeviation="32"
/>
<feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" />
</filter>
<filter
id="gemini__f"
@@ -285,10 +255,7 @@ export const Gemini: Icon = (props) => (
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
<feGaussianBlur
result="effect1_foregroundBlur_69_17998"
stdDeviation="32"
/>
<feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" />
</filter>
<filter
id="gemini__g"
@@ -301,10 +268,7 @@ export const Gemini: Icon = (props) => (
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
<feGaussianBlur
result="effect1_foregroundBlur_69_17998"
stdDeviation="32"
/>
<feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" />
</filter>
<filter
id="gemini__h"
@@ -317,10 +281,7 @@ export const Gemini: Icon = (props) => (
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
<feGaussianBlur
result="effect1_foregroundBlur_69_17998"
stdDeviation="32"
/>
<feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" />
</filter>
</defs>
</svg>
+264
View File
@@ -0,0 +1,264 @@
import { memo, useState, useCallback } from "react";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { ScrollArea } from "./ui/scroll-area";
import ChatMarkdown from "./ChatMarkdown";
import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
EllipsisIcon,
LoaderIcon,
PanelRightCloseIcon,
} from "lucide-react";
import { cn } from "~/lib/utils";
import { formatTimestamp } from "../session-logic";
import type { ActivePlanState } from "../session-logic";
import type { LatestProposedPlanState } from "../session-logic";
import {
proposedPlanTitle,
buildProposedPlanMarkdownFilename,
normalizePlanMarkdownForExport,
downloadPlanAsTextFile,
stripDisplayedPlanMarkdown,
} from "../proposedPlan";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
import { readNativeApi } from "~/nativeApi";
import { toastManager } from "./ui/toast";
function stepStatusIcon(status: string): React.ReactNode {
if (status === "completed") {
return (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-emerald-500/15 text-emerald-500">
<CheckIcon className="size-3" />
</span>
);
}
if (status === "inProgress") {
return (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-blue-500/15 text-blue-400">
<LoaderIcon className="size-3 animate-spin" />
</span>
);
}
return (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full border border-border/60 bg-muted/30">
<span className="size-1.5 rounded-full bg-muted-foreground/30" />
</span>
);
}
interface PlanSidebarProps {
activePlan: ActivePlanState | null;
activeProposedPlan: LatestProposedPlanState | null;
markdownCwd: string | undefined;
workspaceRoot: string | undefined;
onClose: () => void;
}
const PlanSidebar = memo(function PlanSidebar({
activePlan,
activeProposedPlan,
markdownCwd,
workspaceRoot,
onClose,
}: PlanSidebarProps) {
const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false);
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
const [copied, setCopied] = useState(false);
const planMarkdown = activeProposedPlan?.planMarkdown ?? null;
const displayedPlanMarkdown = planMarkdown ? stripDisplayedPlanMarkdown(planMarkdown) : null;
const planTitle = planMarkdown ? proposedPlanTitle(planMarkdown) : null;
const handleCopyPlan = useCallback(() => {
if (!planMarkdown) return;
void navigator.clipboard.writeText(planMarkdown);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}, [planMarkdown]);
const handleDownload = useCallback(() => {
if (!planMarkdown) return;
const filename = buildProposedPlanMarkdownFilename(planMarkdown);
downloadPlanAsTextFile(filename, normalizePlanMarkdownForExport(planMarkdown));
}, [planMarkdown]);
const handleSaveToWorkspace = useCallback(() => {
const api = readNativeApi();
if (!api || !workspaceRoot || !planMarkdown) return;
const filename = buildProposedPlanMarkdownFilename(planMarkdown);
setIsSavingToWorkspace(true);
void api.projects
.writeFile({
cwd: workspaceRoot,
relativePath: filename,
contents: normalizePlanMarkdownForExport(planMarkdown),
})
.then((result) => {
toastManager.add({
type: "success",
title: "Plan saved",
description: result.relativePath,
});
})
.catch((error) => {
toastManager.add({
type: "error",
title: "Could not save plan",
description: error instanceof Error ? error.message : "An error occurred.",
});
})
.then(
() => setIsSavingToWorkspace(false),
() => setIsSavingToWorkspace(false),
);
}, [planMarkdown, workspaceRoot]);
return (
<div className="flex h-full w-[340px] shrink-0 flex-col border-l border-border/70 bg-card/50">
{/* Header */}
<div className="flex h-12 shrink-0 items-center justify-between border-b border-border/60 px-3">
<div className="flex items-center gap-2">
<Badge
variant="secondary"
className="rounded-md bg-blue-500/10 px-1.5 py-0 text-[10px] font-semibold tracking-wide text-blue-400 uppercase"
>
Plan
</Badge>
{activePlan ? (
<span className="text-[11px] text-muted-foreground/60">
{formatTimestamp(activePlan.createdAt)}
</span>
) : null}
</div>
<div className="flex items-center gap-1">
{planMarkdown ? (
<Menu>
<MenuTrigger
render={
<Button
size="icon-xs"
variant="ghost"
className="text-muted-foreground/50 hover:text-foreground/70"
aria-label="Plan actions"
/>
}
>
<EllipsisIcon className="size-3.5" />
</MenuTrigger>
<MenuPopup align="end">
<MenuItem onClick={handleCopyPlan}>
{copied ? "Copied!" : "Copy to clipboard"}
</MenuItem>
<MenuItem onClick={handleDownload}>Download as markdown</MenuItem>
<MenuItem
onClick={handleSaveToWorkspace}
disabled={!workspaceRoot || isSavingToWorkspace}
>
Save to workspace
</MenuItem>
</MenuPopup>
</Menu>
) : null}
<Button
size="icon-xs"
variant="ghost"
onClick={onClose}
aria-label="Close plan sidebar"
className="text-muted-foreground/50 hover:text-foreground/70"
>
<PanelRightCloseIcon className="size-3.5" />
</Button>
</div>
</div>
{/* Content */}
<ScrollArea className="min-h-0 flex-1">
<div className="p-3 space-y-4">
{/* Explanation */}
{activePlan?.explanation ? (
<p className="text-[13px] leading-relaxed text-muted-foreground/80">
{activePlan.explanation}
</p>
) : null}
{/* Plan Steps */}
{activePlan && activePlan.steps.length > 0 ? (
<div className="space-y-1">
<p className="mb-2 text-[10px] font-semibold tracking-widest text-muted-foreground/40 uppercase">
Steps
</p>
{activePlan.steps.map((step) => (
<div
key={`${step.status}:${step.step}`}
className={cn(
"flex items-start gap-2.5 rounded-lg px-2.5 py-2 transition-colors duration-200",
step.status === "inProgress" && "bg-blue-500/5",
step.status === "completed" && "bg-emerald-500/5",
)}
>
<div className="mt-0.5">{stepStatusIcon(step.status)}</div>
<p
className={cn(
"text-[13px] leading-snug",
step.status === "completed"
? "text-muted-foreground/50 line-through decoration-muted-foreground/20"
: step.status === "inProgress"
? "text-foreground/90"
: "text-muted-foreground/70",
)}
>
{step.step}
</p>
</div>
))}
</div>
) : null}
{/* Proposed Plan Markdown */}
{planMarkdown ? (
<div className="space-y-2">
<button
type="button"
className="group flex w-full items-center gap-1.5 text-left"
onClick={() => setProposedPlanExpanded((v) => !v)}
>
{proposedPlanExpanded ? (
<ChevronDownIcon className="size-3 shrink-0 text-muted-foreground/40 transition-transform" />
) : (
<ChevronRightIcon className="size-3 shrink-0 text-muted-foreground/40 transition-transform" />
)}
<span className="text-[10px] font-semibold tracking-widest text-muted-foreground/40 uppercase group-hover:text-muted-foreground/60">
{planTitle ?? "Full Plan"}
</span>
</button>
{proposedPlanExpanded ? (
<div className="rounded-lg border border-border/50 bg-background/50 p-3">
<ChatMarkdown
text={displayedPlanMarkdown ?? ""}
cwd={markdownCwd}
isStreaming={false}
/>
</div>
) : null}
</div>
) : null}
{/* Empty state */}
{!activePlan && !planMarkdown ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-[13px] text-muted-foreground/40">No active plan yet.</p>
<p className="mt-1 text-[11px] text-muted-foreground/30">
Plans will appear here when generated.
</p>
</div>
) : null}
</div>
</ScrollArea>
</div>
);
});
export default PlanSidebar;
export type { PlanSidebarProps };
@@ -14,7 +14,7 @@ import {
SettingsIcon,
WrenchIcon,
} from "lucide-react";
import React, { type FormEvent, type KeyboardEvent, useMemo, useState } from "react";
import React, { type FormEvent, type KeyboardEvent, useCallback, useMemo, useState } from "react";
import {
keybindingValueForCommand,
@@ -27,6 +27,15 @@ import {
} from "~/projectScripts";
import { shortcutLabelForCommand } from "~/keybindings";
import { isMacPlatform } from "~/lib/utils";
import {
AlertDialog,
AlertDialogClose,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogPopup,
AlertDialogTitle,
} from "./ui/alert-dialog";
import { Button } from "./ui/button";
import {
Dialog,
@@ -84,6 +93,7 @@ interface ProjectScriptsControlProps {
onRunScript: (script: ProjectScript) => void;
onAddScript: (input: NewProjectScriptInput) => Promise<void> | void;
onUpdateScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void> | void;
onDeleteScript: (scriptId: string) => Promise<void> | void;
}
function normalizeShortcutKeyToken(key: string): string | null {
@@ -144,6 +154,7 @@ export default function ProjectScriptsControl({
onRunScript,
onAddScript,
onUpdateScript,
onDeleteScript,
}: ProjectScriptsControlProps) {
const addScriptFormId = React.useId();
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
@@ -155,6 +166,7 @@ export default function ProjectScriptsControl({
const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
const [keybinding, setKeybinding] = useState("");
const [validationError, setValidationError] = useState<string | null>(null);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const primaryScript = useMemo(() => {
if (preferredScriptId) {
@@ -247,6 +259,13 @@ export default function ProjectScriptsControl({
setDialogOpen(true);
};
const confirmDeleteScript = useCallback(() => {
if (!editingScriptId) return;
setDeleteConfirmOpen(false);
setDialogOpen(false);
void onDeleteScript(editingScriptId);
}, [editingScriptId, onDeleteScript]);
return (
<>
{primaryScript ? (
@@ -440,6 +459,16 @@ export default function ProjectScriptsControl({
</form>
</DialogPanel>
<DialogFooter>
{isEditing && (
<Button
type="button"
variant="destructive-outline"
className="mr-auto"
onClick={() => setDeleteConfirmOpen(true)}
>
Delete
</Button>
)}
<Button
type="button"
variant="outline"
@@ -455,6 +484,21 @@ export default function ProjectScriptsControl({
</DialogFooter>
</DialogPopup>
</Dialog>
<AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Delete action "{name}"?</AlertDialogTitle>
<AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button variant="destructive" onClick={confirmDeleteScript}>
Delete action
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
</>
);
}
@@ -0,0 +1,283 @@
import type { GitResolvePullRequestResult } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
gitPreparePullRequestThreadMutationOptions,
gitResolvePullRequestQueryOptions,
} from "~/lib/gitReactQuery";
import { cn } from "~/lib/utils";
import { parsePullRequestReference } from "~/pullRequestReference";
import { Button } from "./ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "./ui/dialog";
import { Input } from "./ui/input";
import { Spinner } from "./ui/spinner";
interface PullRequestThreadDialogProps {
open: boolean;
cwd: string | null;
initialReference: string | null;
onOpenChange: (open: boolean) => void;
onPrepared: (input: { branch: string; worktreePath: string | null }) => Promise<void> | void;
}
export function PullRequestThreadDialog({
open,
cwd,
initialReference,
onOpenChange,
onPrepared,
}: PullRequestThreadDialogProps) {
const queryClient = useQueryClient();
const referenceInputRef = useRef<HTMLInputElement>(null);
const [reference, setReference] = useState(initialReference ?? "");
const [referenceDirty, setReferenceDirty] = useState(false);
const [preparingMode, setPreparingMode] = useState<"local" | "worktree" | null>(null);
const [debouncedReference, referenceDebouncer] = useDebouncedValue(
reference,
{ wait: 450 },
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
useEffect(() => {
if (!open) return;
setReference(initialReference ?? "");
setReferenceDirty(false);
setPreparingMode(null);
}, [initialReference, open]);
useEffect(() => {
if (!open) return;
const frame = window.requestAnimationFrame(() => {
referenceInputRef.current?.focus();
referenceInputRef.current?.select();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [open]);
const parsedReference = parsePullRequestReference(reference);
const parsedDebouncedReference = parsePullRequestReference(debouncedReference);
const resolvePullRequestQuery = useQuery(
gitResolvePullRequestQueryOptions({
cwd,
reference: open ? parsedDebouncedReference : null,
}),
);
const cachedPullRequest = useMemo(() => {
if (!cwd || !parsedReference) {
return null;
}
const cached = queryClient.getQueryData<GitResolvePullRequestResult>([
"git",
"pull-request",
cwd,
parsedReference,
]);
return cached?.pullRequest ?? null;
}, [cwd, parsedReference, queryClient]);
const preparePullRequestThreadMutation = useMutation(
gitPreparePullRequestThreadMutationOptions({ cwd, queryClient }),
);
const liveResolvedPullRequest =
parsedReference !== null && parsedReference === parsedDebouncedReference
? (resolvePullRequestQuery.data?.pullRequest ?? null)
: null;
const resolvedPullRequest = liveResolvedPullRequest ?? cachedPullRequest;
const isResolving =
open &&
parsedReference !== null &&
resolvedPullRequest === null &&
(referenceDebouncer.state.isPending ||
parsedReference !== parsedDebouncedReference ||
resolvePullRequestQuery.isPending ||
resolvePullRequestQuery.isFetching);
const statusTone = useMemo(() => {
switch (resolvedPullRequest?.state) {
case "merged":
return "text-violet-600 dark:text-violet-300/90";
case "closed":
return "text-zinc-500 dark:text-zinc-400/80";
case "open":
return "text-emerald-600 dark:text-emerald-300/90";
default:
return "text-muted-foreground";
}
}, [resolvedPullRequest?.state]);
const handleConfirm = useCallback(
async (mode: "local" | "worktree") => {
if (!parsedReference) {
setReferenceDirty(true);
return;
}
if (!parsedReference || !resolvedPullRequest || !cwd) {
return;
}
setPreparingMode(mode);
try {
const result = await preparePullRequestThreadMutation.mutateAsync({
reference: parsedReference,
mode,
});
await onPrepared({
branch: result.branch,
worktreePath: result.worktreePath,
});
onOpenChange(false);
} finally {
setPreparingMode(null);
}
},
[
cwd,
onOpenChange,
onPrepared,
parsedReference,
preparePullRequestThreadMutation,
resolvedPullRequest,
],
);
const validationMessage = !referenceDirty
? null
: reference.trim().length === 0
? "Paste a GitHub pull request URL or enter 123 / #123."
: parsedReference === null
? "Use a GitHub pull request URL, 123, or #123."
: null;
const errorMessage =
validationMessage ??
(resolvedPullRequest === null && resolvePullRequestQuery.isError
? resolvePullRequestQuery.error instanceof Error
? resolvePullRequestQuery.error.message
: "Failed to resolve pull request."
: preparePullRequestThreadMutation.error instanceof Error
? preparePullRequestThreadMutation.error.message
: preparePullRequestThreadMutation.error
? "Failed to prepare pull request thread."
: null);
return (
<Dialog
open={open}
onOpenChange={(nextOpen) => {
if (!preparePullRequestThreadMutation.isPending) {
onOpenChange(nextOpen);
}
}}
>
<DialogPopup className="max-w-xl">
<DialogHeader>
<DialogTitle>Checkout Pull Request</DialogTitle>
<DialogDescription>
Resolve a GitHub pull request, then create the draft thread in the main repo or in a
dedicated worktree.
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-4">
<label className="grid gap-1.5">
<span className="text-xs font-medium text-foreground">Pull request</span>
<Input
ref={referenceInputRef}
placeholder="https://github.com/owner/repo/pull/42 or #42"
value={reference}
onChange={(event) => {
setReferenceDirty(true);
setReference(event.target.value);
}}
onKeyDown={(event) => {
if (event.key !== "Enter") {
return;
}
event.preventDefault();
if (!isResolving && !preparePullRequestThreadMutation.isPending) {
void handleConfirm("local");
}
}}
/>
</label>
{resolvedPullRequest ? (
<div className="rounded-xl border border-border/70 bg-muted/24 p-3">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="truncate font-medium text-sm">{resolvedPullRequest.title}</p>
<p className="truncate text-muted-foreground text-xs">
#{resolvedPullRequest.number} · {resolvedPullRequest.headBranch} to{" "}
{resolvedPullRequest.baseBranch}
</p>
</div>
<span className={cn("shrink-0 text-xs capitalize", statusTone)}>
{resolvedPullRequest.state}
</span>
</div>
</div>
) : null}
{isResolving ? (
<div className="flex items-center gap-2 text-muted-foreground text-xs">
<Spinner className="size-3.5" />
Resolving pull request...
</div>
) : null}
{errorMessage ? <p className="text-destructive text-xs">{errorMessage}</p> : null}
</DialogPanel>
<DialogFooter>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onOpenChange(false)}
disabled={preparePullRequestThreadMutation.isPending}
>
Cancel
</Button>
<Button
type="button"
size="sm"
variant="outline"
onClick={() => {
void handleConfirm("local");
}}
disabled={
!cwd ||
!resolvedPullRequest ||
isResolving ||
preparePullRequestThreadMutation.isPending
}
>
{preparingMode === "local" ? "Preparing local..." : "Local"}
</Button>
<Button
type="button"
size="sm"
onClick={() => {
void handleConfirm("worktree");
}}
disabled={
!cwd ||
!resolvedPullRequest ||
isResolving ||
preparePullRequestThreadMutation.isPending
}
>
{preparingMode === "worktree" ? "Preparing worktree..." : "Worktree"}
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
@@ -0,0 +1,156 @@
import { describe, expect, it } from "vitest";
import {
hasUnseenCompletion,
resolveThreadStatusPill,
shouldClearThreadSelectionOnMouseDown,
} from "./Sidebar.logic";
function makeLatestTurn(overrides?: {
completedAt?: string | null;
startedAt?: string | null;
}): Parameters<typeof hasUnseenCompletion>[0]["latestTurn"] {
return {
turnId: "turn-1" as never,
state: "completed",
assistantMessageId: null,
requestedAt: "2026-03-09T10:00:00.000Z",
startedAt: overrides?.startedAt ?? "2026-03-09T10:00:00.000Z",
completedAt: overrides?.completedAt ?? "2026-03-09T10:05:00.000Z",
};
}
describe("hasUnseenCompletion", () => {
it("returns true when a thread completed after its last visit", () => {
expect(
hasUnseenCompletion({
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: "2026-03-09T10:04:00.000Z",
proposedPlans: [],
session: null,
}),
).toBe(true);
});
});
describe("shouldClearThreadSelectionOnMouseDown", () => {
it("preserves selection for thread items", () => {
const child = {
closest: (selector: string) =>
selector.includes("[data-thread-item]") ? ({} as Element) : null,
} as unknown as HTMLElement;
expect(shouldClearThreadSelectionOnMouseDown(child)).toBe(false);
});
it("preserves selection for thread list toggle controls", () => {
const selectionSafe = {
closest: (selector: string) =>
selector.includes("[data-thread-selection-safe]") ? ({} as Element) : null,
} as unknown as HTMLElement;
expect(shouldClearThreadSelectionOnMouseDown(selectionSafe)).toBe(false);
});
it("clears selection for unrelated sidebar clicks", () => {
const unrelated = {
closest: () => null,
} as unknown as HTMLElement;
expect(shouldClearThreadSelectionOnMouseDown(unrelated)).toBe(true);
});
});
describe("resolveThreadStatusPill", () => {
const baseThread = {
interactionMode: "plan" as const,
latestTurn: null,
lastVisitedAt: undefined,
proposedPlans: [],
session: {
provider: "codex" as const,
status: "running" as const,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:00:00.000Z",
orchestrationStatus: "running" as const,
},
};
it("shows pending approval before all other statuses", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: true,
hasPendingUserInput: true,
}),
).toMatchObject({ label: "Pending Approval", pulse: false });
});
it("shows awaiting input when plan mode is blocked on user answers", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: true,
}),
).toMatchObject({ label: "Awaiting Input", pulse: false });
});
it("falls back to working when the thread is actively running without blockers", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Working", pulse: true });
});
it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
latestTurn: makeLatestTurn(),
proposedPlans: [
{
id: "plan-1" as never,
turnId: "turn-1" as never,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
planMarkdown: "# Plan",
},
],
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Plan Ready", pulse: false });
});
it("shows completed when there is an unseen completion and no active blocker", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: "2026-03-09T10:04:00.000Z",
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Completed", pulse: false });
});
});
+107
View File
@@ -0,0 +1,107 @@
import type { Thread } from "../types";
import { findLatestProposedPlan, isLatestTurnSettled } from "../session-logic";
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export interface ThreadStatusPill {
label:
| "Working"
| "Connecting"
| "Completed"
| "Pending Approval"
| "Awaiting Input"
| "Plan Ready";
colorClass: string;
dotClass: string;
pulse: boolean;
}
type ThreadStatusInput = Pick<
Thread,
"interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session"
>;
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
if (!thread.latestTurn?.completedAt) return false;
const completedAt = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(completedAt)) return false;
if (!thread.lastVisitedAt) return true;
const lastVisitedAt = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAt)) return true;
return completedAt > lastVisitedAt;
}
export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
if (target === null) return true;
return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
}
export function resolveThreadStatusPill(input: {
thread: ThreadStatusInput;
hasPendingApprovals: boolean;
hasPendingUserInput: boolean;
}): ThreadStatusPill | null {
const { hasPendingApprovals, hasPendingUserInput, thread } = input;
if (hasPendingApprovals) {
return {
label: "Pending Approval",
colorClass: "text-amber-600 dark:text-amber-300/90",
dotClass: "bg-amber-500 dark:bg-amber-300/90",
pulse: false,
};
}
if (hasPendingUserInput) {
return {
label: "Awaiting Input",
colorClass: "text-indigo-600 dark:text-indigo-300/90",
dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
pulse: false,
};
}
if (thread.session?.status === "running") {
return {
label: "Working",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (thread.session?.status === "connecting") {
return {
label: "Connecting",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
const hasPlanReadyPrompt =
!hasPendingUserInput &&
thread.interactionMode === "plan" &&
isLatestTurnSettled(thread.latestTurn, thread.session) &&
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null) !== null;
if (hasPlanReadyPrompt) {
return {
label: "Plan Ready",
colorClass: "text-violet-600 dark:text-violet-300/90",
dotClass: "bg-violet-500 dark:bg-violet-300/90",
pulse: false,
};
}
if (hasUnseenCompletion(thread)) {
return {
label: "Completed",
colorClass: "text-emerald-600 dark:text-emerald-300/90",
dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
pulse: false,
};
}
return null;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import {
COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX,
COMPOSER_FOOTER_WIDE_ACTIONS_COMPACT_BREAKPOINT_PX,
shouldUseCompactComposerFooter,
} from "./composerFooterLayout";
describe("shouldUseCompactComposerFooter", () => {
it("stays expanded without a measured width", () => {
expect(shouldUseCompactComposerFooter(null)).toBe(false);
});
it("switches to compact mode below the breakpoint", () => {
expect(shouldUseCompactComposerFooter(COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX - 1)).toBe(true);
});
it("stays expanded at and above the breakpoint", () => {
expect(shouldUseCompactComposerFooter(COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX)).toBe(false);
expect(shouldUseCompactComposerFooter(COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX + 48)).toBe(false);
});
it("uses a higher breakpoint for wide action states", () => {
expect(
shouldUseCompactComposerFooter(COMPOSER_FOOTER_WIDE_ACTIONS_COMPACT_BREAKPOINT_PX - 1, {
hasWideActions: true,
}),
).toBe(true);
expect(
shouldUseCompactComposerFooter(COMPOSER_FOOTER_WIDE_ACTIONS_COMPACT_BREAKPOINT_PX, {
hasWideActions: true,
}),
).toBe(false);
});
});
@@ -0,0 +1,12 @@
export const COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX = 620;
export const COMPOSER_FOOTER_WIDE_ACTIONS_COMPACT_BREAKPOINT_PX = 720;
export function shouldUseCompactComposerFooter(
width: number | null,
options?: { hasWideActions?: boolean },
): boolean {
const breakpoint = options?.hasWideActions
? COMPOSER_FOOTER_WIDE_ACTIONS_COMPACT_BREAKPOINT_PX
: COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX;
return width !== null && width < breakpoint;
}
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more