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
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
124 changed files with 5738 additions and 1957 deletions

No files matched your search

+4 -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
+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`.
+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);
}
+12 -9
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,
@@ -702,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;
@@ -764,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
@@ -801,7 +798,13 @@ function configureAutoUpdater(): void {
console.info("[desktop-updater] Looking for updates...");
});
autoUpdater.on("update-available", (info) => {
setUpdateState(reduceDesktopUpdateStateOnUpdateAvailable(updateState, info.version, new Date().toISOString()));
setUpdateState(
reduceDesktopUpdateStateOnUpdateAvailable(
updateState,
info.version,
new Date().toISOString(),
),
);
lastLoggedDownloadMilestone = -1;
console.info(`[desktop-updater] Update available: ${info.version}`);
});
+1 -2
View File
@@ -25,8 +25,7 @@ export function resolveDesktopRuntimeInfo(
};
}
const hostArch =
appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
const hostArch = appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
return {
hostArch,
+4 -1
View File
@@ -83,7 +83,10 @@ describe("updateMachine", () => {
},
"1.1.0",
);
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(
downloaded,
"backend shutdown timed out",
);
expect(downloaded.status).toBe("downloaded");
expect(downloaded.downloadedVersion).toBe("1.1.0");
@@ -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;
});
+5 -4
View File
@@ -6,7 +6,10 @@ import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { DEVELOPMENT_ICON_OVERRIDES, PUBLISH_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts";
import {
DEVELOPMENT_ICON_OVERRIDES,
PUBLISH_ICON_OVERRIDES,
} from "../../../scripts/lib/brand-assets.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
@@ -237,9 +240,7 @@ const publishCmd = Command.make(
Effect.gen(function* () {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(
`[cli] Failed to restore publish icon overrides: ${String(error)}`,
),
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
),
);
yield* fs.rename(backupPath, packageJsonPath);
+1 -2
View File
@@ -12,8 +12,7 @@ import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts"
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN =
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
const ATTACHMENT_ID_PATTERN = new RegExp(
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
"i",
+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());
@@ -224,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;
@@ -234,13 +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?.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,
});
@@ -265,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;
@@ -345,15 +346,16 @@ const make = Effect.gen(function* () {
});
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,
@@ -474,8 +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.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,
});
@@ -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 -1
View File
@@ -302,7 +302,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.provider !== undefined ? { provider: command.provider } : {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
...(command.providerOptions !== undefined ? { providerOptions: command.providerOptions } : {}),
...(command.providerOptions !== undefined
? { providerOptions: command.providerOptions }
: {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
runtimeMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
+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) =>
@@ -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,6 +8,9 @@
*
* @module ProviderHealthLive
*/
import * as fs from "node:fs";
import * as OS from "node:os";
import * as NodePath from "node:path";
import type {
ServerProviderAuthStatus,
ServerProviderStatus,
@@ -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,
@@ -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.
+83 -17
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 } };
@@ -1568,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);
});
@@ -1638,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();
@@ -1656,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(
@@ -1667,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,
};
+22 -14
View File
@@ -198,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);
}
@@ -330,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),
@@ -793,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) =>
@@ -832,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);
+2 -12
View File
@@ -61,23 +61,13 @@ 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"]);
});
@@ -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>
+18 -8
View File
@@ -414,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");
},
{
@@ -454,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(
@@ -697,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);
@@ -714,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,
@@ -756,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);
@@ -844,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",
+123 -11
View File
@@ -176,7 +176,7 @@ import {
VisualStudioCode,
Zed,
} from "./Icons";
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { cn, isMacPlatform, isWindowsPlatform, randomUUID } from "~/lib/utils";
import { Badge } from "./ui/badge";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { Command, CommandItem, CommandList } from "./ui/command";
@@ -216,6 +216,7 @@ import { shouldUseCompactComposerFooter } from "./composerFooterLayout";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { clamp } from "effect/Number";
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
import { estimateTimelineMessageHeight } from "./timelineHeight";
function formatMessageMeta(createdAt: string, duration: string | null): string {
@@ -407,6 +408,11 @@ type ComposerCommandItem =
type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
interface PullRequestDialogState {
initialReference: string | null;
key: number;
}
function readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
@@ -426,7 +432,7 @@ function readFileAsDataUrl(file: File): Promise<string> {
function buildTemporaryWorktreeBranchName(): string {
// Keep the 8-hex suffix shape for backend temporary-branch detection.
const token = crypto.randomUUID().slice(0, 8).toLowerCase();
const token = randomUUID().slice(0, 8).toLowerCase();
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
}
@@ -609,6 +615,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);
const clearDraftThread = useComposerDraftStore((store) => store.clearDraftThread);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const getDraftThreadByProjectId = useComposerDraftStore(
(store) => store.getDraftThreadByProjectId,
);
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
const clearProjectDraftThreadId = useComposerDraftStore(
(store) => store.clearProjectDraftThreadId,
);
const draftThread = useComposerDraftStore(
(store) => store.draftThreadsByThreadId[threadId] ?? null,
);
@@ -645,6 +659,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
Record<string, string[]>
>({});
@@ -743,12 +759,93 @@ export default function ChatView({ threadId }: ChatViewProps) {
composerDraft.interactionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE;
const isServerThread = serverThread !== undefined;
const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
const canCheckoutPullRequestIntoThread = isLocalDraftThread;
const diffOpen = rawSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const activeLatestTurn = activeThread?.latestTurn ?? null;
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = projects.find((p) => p.id === activeThread?.projectId);
const openPullRequestDialog = useCallback(
(reference?: string) => {
if (!canCheckoutPullRequestIntoThread) {
return;
}
setPullRequestDialogState({
initialReference: reference ?? null,
key: Date.now(),
});
setComposerHighlightedItemId(null);
},
[canCheckoutPullRequestIntoThread],
);
const closePullRequestDialog = useCallback(() => {
setPullRequestDialogState(null);
}, []);
const openOrReuseProjectDraftThread = useCallback(
async (input: { branch: string; worktreePath: string | null; envMode: DraftThreadEnvMode }) => {
if (!activeProject) {
throw new Error("No active project is available for this pull request.");
}
const storedDraftThread = getDraftThreadByProjectId(activeProject.id);
if (storedDraftThread) {
setDraftThreadContext(storedDraftThread.threadId, input);
setProjectDraftThreadId(activeProject.id, storedDraftThread.threadId, input);
if (storedDraftThread.threadId !== threadId) {
await navigate({
to: "/$threadId",
params: { threadId: storedDraftThread.threadId },
});
}
return;
}
const activeDraftThread = getDraftThread(threadId);
if (!isServerThread && activeDraftThread?.projectId === activeProject.id) {
setDraftThreadContext(threadId, input);
setProjectDraftThreadId(activeProject.id, threadId, input);
return;
}
clearProjectDraftThreadId(activeProject.id);
const nextThreadId = newThreadId();
setProjectDraftThreadId(activeProject.id, nextThreadId, {
createdAt: new Date().toISOString(),
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_INTERACTION_MODE,
...input,
});
await navigate({
to: "/$threadId",
params: { threadId: nextThreadId },
});
},
[
activeProject,
clearProjectDraftThreadId,
getDraftThread,
getDraftThreadByProjectId,
isServerThread,
navigate,
setDraftThreadContext,
setProjectDraftThreadId,
threadId,
],
);
const handlePreparedPullRequestThread = useCallback(
async (input: { branch: string; worktreePath: string | null }) => {
await openOrReuseProjectDraftThread({
branch: input.branch,
worktreePath: input.worktreePath,
envMode: input.worktreePath ? "worktree" : "local",
});
},
[openOrReuseProjectDraftThread],
);
useEffect(() => {
if (!activeThread?.id) return;
if (!latestTurnSettled) return;
@@ -1363,13 +1460,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
}, [activeThreadId, setTerminalOpen, terminalState.terminalOpen]);
const splitTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return;
const terminalId = `terminal-${crypto.randomUUID()}`;
const terminalId = `terminal-${randomUUID()}`;
storeSplitTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, storeSplitTerminal, hasReachedTerminalLimit]);
const createNewTerminal = useCallback(() => {
if (!activeThreadId || hasReachedTerminalLimit) return;
const terminalId = `terminal-${crypto.randomUUID()}`;
const terminalId = `terminal-${randomUUID()}`;
storeNewTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, storeNewTerminal, hasReachedTerminalLimit]);
@@ -1438,7 +1535,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const shouldCreateNewTerminal =
wantsNewTerminal && terminalState.terminalIds.length < MAX_THREAD_TERMINAL_COUNT;
const targetTerminalId = shouldCreateNewTerminal
? `terminal-${crypto.randomUUID()}`
? `terminal-${randomUUID()}`
: baseTerminalId;
setTerminalOpen(true);
@@ -1950,6 +2047,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => {
setExpandedWorkGroups({});
setPullRequestDialogState(null);
if (planSidebarOpenOnNextThreadRef.current) {
planSidebarOpenOnNextThreadRef.current = false;
setPlanSidebarOpen(true);
@@ -2331,7 +2429,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const previewUrl = URL.createObjectURL(file);
nextImages.push({
type: "image",
id: crypto.randomUUID(),
id: randomUUID(),
name: file.name || "image",
mimeType: file.type,
sizeBytes: file.size,
@@ -3688,7 +3786,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
? "Add feedback to refine the plan, or leave this blank to implement it"
: phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, or use /model"
: "Ask anything, @tag files/folders, or use / to show available commands"
}
disabled={isConnecting || isComposerApprovalState}
/>
@@ -4018,8 +4116,25 @@ export default function ChatView({ threadId }: ChatViewProps) {
onEnvModeChange={onEnvModeChange}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
/>
)}
{pullRequestDialogState ? (
<PullRequestThreadDialog
key={pullRequestDialogState.key}
open
cwd={activeProject?.cwd ?? null}
initialReference={pullRequestDialogState.initialReference}
onOpenChange={(open) => {
if (!open) {
closePullRequestDialog();
}
}}
onPrepared={handlePreparedPullRequestThread}
/>
) : null}
</div>
{/* end chat column */}
@@ -5634,10 +5749,7 @@ const ProviderModelPicker = memo(function ProviderModelPicker(props: {
}
>
<span
className={cn(
"flex min-w-0 items-center gap-2",
props.compact ? "max-w-36" : undefined,
)}
className={cn("flex min-w-0 items-center gap-2", props.compact ? "max-w-36" : undefined)}
>
<ProviderIcon aria-hidden="true" className="size-4 shrink-0 text-muted-foreground/70" />
<span className="truncate">{selectedModelLabel}</span>
@@ -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>
+3 -8
View File
@@ -106,8 +106,7 @@ const PlanSidebar = memo(function PlanSidebar({
toastManager.add({
type: "error",
title: "Could not save plan",
description:
error instanceof Error ? error.message : "An error occurred.",
description: error instanceof Error ? error.message : "An error occurred.",
});
})
.then(
@@ -199,9 +198,7 @@ const PlanSidebar = memo(function PlanSidebar({
step.status === "completed" && "bg-emerald-500/5",
)}
>
<div className="mt-0.5">
{stepStatusIcon(step.status)}
</div>
<div className="mt-0.5">{stepStatusIcon(step.status)}</div>
<p
className={cn(
"text-[13px] leading-snug",
@@ -251,9 +248,7 @@ const PlanSidebar = memo(function PlanSidebar({
{/* 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="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>
@@ -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>
);
}
+33 -1
View File
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vitest";
import { hasUnseenCompletion, resolveThreadStatusPill } from "./Sidebar.logic";
import {
hasUnseenCompletion,
resolveThreadStatusPill,
shouldClearThreadSelectionOnMouseDown,
} from "./Sidebar.logic";
function makeLatestTurn(overrides?: {
completedAt?: string | null;
@@ -30,6 +34,34 @@ describe("hasUnseenCompletion", () => {
});
});
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,
+7
View File
@@ -1,6 +1,8 @@
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"
@@ -30,6 +32,11 @@ export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
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;
+445 -251
View File
@@ -10,7 +10,7 @@ import {
TerminalIcon,
TriangleAlertIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import {
DndContext,
type DragCancelEvent,
@@ -40,7 +40,7 @@ import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
import { useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
import { isMacPlatform, newCommandId, newProjectId, newThreadId } from "../lib/utils";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
@@ -80,9 +80,10 @@ import {
SidebarSeparator,
SidebarTrigger,
} from "./ui/sidebar";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { isNonEmpty as isNonEmptyString } from "effect/String";
import { resolveThreadStatusPill } from "./Sidebar.logic";
import { resolveThreadStatusPill, shouldClearThreadSelectionOnMouseDown } from "./Sidebar.logic";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
@@ -301,6 +302,12 @@ export default function Sidebar() {
const dragInProgressRef = useRef(false);
const suppressProjectClickAfterDragRef = useRef(false);
const [desktopUpdateState, setDesktopUpdateState] = useState<DesktopUpdateState | null>(null);
const selectedThreadIds = useThreadSelectionStore((s) => s.selectedThreadIds);
const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread);
const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo);
const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
const shouldBrowseForProjectImmediately = isElectron;
const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately;
const pendingApprovalByThreadId = useMemo(() => {
@@ -628,6 +635,124 @@ export default function Sidebar() {
[],
);
/**
* Delete a single thread: stop session, close terminal, dispatch delete,
* clean up drafts/state, and optionally remove orphaned worktree.
* Callers handle thread-level confirmation; this still prompts for worktree removal.
*/
const deleteThread = useCallback(
async (
threadId: ThreadId,
opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {},
): Promise<void> => {
const api = readNativeApi();
if (!api) return;
const thread = threads.find((t) => t.id === threadId);
if (!thread) return;
const threadProject = projects.find((project) => project.id === thread.projectId);
// When bulk-deleting, exclude the other threads being deleted so
// getOrphanedWorktreePathForThread correctly detects that no surviving
// threads will reference this worktree.
const deletedIds = opts.deletedThreadIds;
const survivingThreads =
deletedIds && deletedIds.size > 0
? threads.filter((t) => t.id === threadId || !deletedIds.has(t.id))
: threads;
const orphanedWorktreePath = getOrphanedWorktreePathForThread(survivingThreads, threadId);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
));
if (thread.session && thread.session.status !== "closed") {
await api.orchestration
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
}
try {
await api.terminal.close({ threadId, deleteHistory: true });
} catch {
// Terminal may already be closed
}
const allDeletedIds = deletedIds ?? new Set<ThreadId>();
const shouldNavigateToFallback = routeThreadId === threadId;
const fallbackThreadId =
threads.find((entry) => entry.id !== threadId && !allDeletedIds.has(entry.id))?.id ?? null;
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId,
});
clearComposerDraftForThread(threadId);
clearProjectDraftThreadById(thread.projectId, thread.id);
clearTerminalState(threadId);
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
void navigate({
to: "/$threadId",
params: { threadId: fallbackThreadId },
replace: true,
});
} else {
void navigate({ to: "/", replace: true });
}
}
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
return;
}
try {
await removeWorktreeMutation.mutateAsync({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
force: true,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
console.error("Failed to remove orphaned worktree after thread deletion", {
threadId,
projectCwd: threadProject.cwd,
worktreePath: orphanedWorktreePath,
error,
});
toastManager.add({
type: "error",
title: "Thread deleted, but worktree removal failed",
description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
});
}
},
[
clearComposerDraftForThread,
clearProjectDraftThreadById,
clearTerminalState,
navigate,
projects,
removeWorktreeMutation,
routeThreadId,
threads,
],
);
const handleThreadContextMenu = useCallback(
async (threadId: ThreadId, position: { x: number; y: number }) => {
const api = readNativeApi();
@@ -684,101 +809,98 @@ export default function Sidebar() {
return;
}
}
const threadProject = projects.find((project) => project.id === thread.projectId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(threads, threadId);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
));
await deleteThread(threadId);
},
[appSettings.confirmThreadDelete, deleteThread, markThreadUnread, threads],
);
if (thread.session && thread.session.status !== "closed") {
await api.orchestration
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
}
const handleMultiSelectContextMenu = useCallback(
async (position: { x: number; y: number }) => {
const api = readNativeApi();
if (!api) return;
const ids = [...selectedThreadIds];
if (ids.length === 0) return;
const count = ids.length;
try {
await api.terminal.close({
threadId,
deleteHistory: true,
});
} catch {
// Terminal may already be closed
}
const clicked = await api.contextMenu.show(
[
{ id: "mark-unread", label: `Mark unread (${count})` },
{ id: "delete", label: `Delete (${count})`, destructive: true },
],
position,
);
const shouldNavigateToFallback = routeThreadId === threadId;
const fallbackThreadId = threads.find((entry) => entry.id !== threadId)?.id ?? null;
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId,
});
clearComposerDraftForThread(threadId);
clearProjectDraftThreadById(thread.projectId, thread.id);
clearTerminalState(threadId);
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
void navigate({
to: "/$threadId",
params: { threadId: fallbackThreadId },
replace: true,
});
} else {
void navigate({ to: "/", replace: true });
if (clicked === "mark-unread") {
for (const id of ids) {
markThreadUnread(id);
}
}
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
clearSelection();
return;
}
try {
await removeWorktreeMutation.mutateAsync({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
force: true,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
console.error("Failed to remove orphaned worktree after thread deletion", {
threadId,
projectCwd: threadProject.cwd,
worktreePath: orphanedWorktreePath,
error,
});
toastManager.add({
type: "error",
title: "Thread deleted, but worktree removal failed",
description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
});
if (clicked !== "delete") return;
if (appSettings.confirmThreadDelete) {
const confirmed = await api.dialogs.confirm(
[
`Delete ${count} thread${count === 1 ? "" : "s"}?`,
"This permanently clears conversation history for these threads.",
].join("\n"),
);
if (!confirmed) return;
}
const deletedIds = new Set<ThreadId>(ids);
for (const id of ids) {
await deleteThread(id, { deletedThreadIds: deletedIds });
}
removeFromSelection(ids);
},
[
appSettings.confirmThreadDelete,
clearComposerDraftForThread,
clearProjectDraftThreadById,
clearTerminalState,
clearSelection,
deleteThread,
markThreadUnread,
removeFromSelection,
selectedThreadIds,
],
);
const handleThreadClick = useCallback(
(event: MouseEvent, threadId: ThreadId, orderedProjectThreadIds: readonly ThreadId[]) => {
const isMac = isMacPlatform(navigator.platform);
const isModClick = isMac ? event.metaKey : event.ctrlKey;
const isShiftClick = event.shiftKey;
if (isModClick) {
event.preventDefault();
toggleThreadSelection(threadId);
return;
}
if (isShiftClick) {
event.preventDefault();
rangeSelectTo(threadId, orderedProjectThreadIds);
return;
}
// Plain click — clear selection, set anchor for future shift-clicks, and navigate
if (selectedThreadIds.size > 0) {
clearSelection();
}
setSelectionAnchor(threadId);
void navigate({
to: "/$threadId",
params: { threadId },
});
},
[
clearSelection,
navigate,
projects,
removeWorktreeMutation,
routeThreadId,
threads,
rangeSelectTo,
selectedThreadIds.size,
setSelectionAnchor,
toggleThreadSelection,
],
);
@@ -894,9 +1016,12 @@ export default function Sidebar() {
event.stopPropagation();
return;
}
if (selectedThreadIds.size > 0) {
clearSelection();
}
toggleProject(projectId);
},
[toggleProject],
[clearSelection, selectedThreadIds.size, toggleProject],
);
const handleProjectTitleKeyDown = useCallback(
@@ -913,6 +1038,12 @@ export default function Sidebar() {
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape" && selectedThreadIds.size > 0) {
event.preventDefault();
clearSelection();
return;
}
const activeThread = routeThreadId
? threads.find((thread) => thread.id === routeThreadId)
: undefined;
@@ -937,11 +1068,29 @@ export default function Sidebar() {
});
};
const onMouseDown = (event: globalThis.MouseEvent) => {
if (selectedThreadIds.size === 0) return;
const target = event.target instanceof HTMLElement ? event.target : null;
if (!shouldClearThreadSelectionOnMouseDown(target)) return;
clearSelection();
};
window.addEventListener("keydown", onWindowKeyDown);
window.addEventListener("mousedown", onMouseDown);
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
window.removeEventListener("mousedown", onMouseDown);
};
}, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, threads]);
}, [
clearSelection,
getDraftThread,
handleNewThread,
keybindings,
projects,
routeThreadId,
selectedThreadIds.size,
threads,
]);
useEffect(() => {
if (!isElectron) return;
@@ -1267,7 +1416,8 @@ export default function Sidebar() {
const projectThreads = threads
.filter((thread) => thread.projectId === project.id)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
const byDate =
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
if (byDate !== 0) return byDate;
return b.id.localeCompare(a.id);
});
@@ -1277,14 +1427,12 @@ export default function Sidebar() {
hasHiddenThreads && !isThreadListExpanded
? projectThreads.slice(0, THREAD_PREVIEW_LIMIT)
: projectThreads;
const orderedProjectThreadIds = projectThreads.map((t) => t.id);
return (
<SortableProjectItem key={project.id} projectId={project.id}>
{(dragHandleProps) => (
<Collapsible
className="group/collapsible"
open={project.expanded}
>
<Collapsible className="group/collapsible" open={project.expanded}>
<div className="group/project-header relative">
<SidebarMenuButton
size="sm"
@@ -1343,177 +1491,223 @@ export default function Sidebar() {
</div>
<CollapsibleContent keepMounted>
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
{visibleThreads.map((thread) => {
const isActive = routeThreadId === thread.id;
const threadStatus = resolveThreadStatusPill({
thread,
hasPendingApprovals: pendingApprovalByThreadId.get(thread.id) === true,
hasPendingUserInput: pendingUserInputByThreadId.get(thread.id) === true,
});
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusFromRunningIds(
selectThreadTerminalState(terminalStateByThreadId, thread.id)
.runningTerminalIds,
);
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0.5 px-1.5 py-0">
{visibleThreads.map((thread) => {
const isActive = routeThreadId === thread.id;
const isSelected = selectedThreadIds.has(thread.id);
const isHighlighted = isActive || isSelected;
const threadStatus = resolveThreadStatusPill({
thread,
hasPendingApprovals:
pendingApprovalByThreadId.get(thread.id) === true,
hasPendingUserInput:
pendingUserInputByThreadId.get(thread.id) === true,
});
const prStatus = prStatusIndicator(
prByThreadId.get(thread.id) ?? null,
);
const terminalStatus = terminalStatusFromRunningIds(
selectThreadTerminalState(terminalStateByThreadId, thread.id)
.runningTerminalIds,
);
return (
<SidebarMenuSubItem key={thread.id} className="w-full">
<SidebarMenuSubButton
render={<div role="button" tabIndex={0} />}
size="sm"
isActive={isActive}
className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
isActive
? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
return (
<SidebarMenuSubItem
key={thread.id}
className="w-full"
data-thread-item
>
<SidebarMenuSubButton
render={<div role="button" tabIndex={0} />}
size="sm"
isActive={isActive}
className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left select-none hover:bg-accent hover:text-foreground focus-visible:ring-0 ${
isSelected
? "bg-primary/15 text-foreground dark:bg-primary/10"
: isActive
? "bg-accent/85 text-foreground font-medium dark:bg-accent/55"
: "text-muted-foreground"
}`}
onClick={() => {
void navigate({
to: "/$threadId",
params: { threadId: thread.id },
}`}
onClick={(event) => {
handleThreadClick(
event,
thread.id,
orderedProjectThreadIds,
);
}}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
if (selectedThreadIds.size > 0) {
clearSelection();
}
setSelectionAnchor(thread.id);
void navigate({
to: "/$threadId",
params: { threadId: thread.id },
});
}}
onContextMenu={(event) => {
event.preventDefault();
if (
selectedThreadIds.size > 0 &&
selectedThreadIds.has(thread.id)
) {
void handleMultiSelectContextMenu({
x: event.clientX,
y: event.clientY,
});
}}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
void navigate({
to: "/$threadId",
params: { threadId: thread.id },
});
}}
onContextMenu={(event) => {
event.preventDefault();
} else {
if (selectedThreadIds.size > 0) {
clearSelection();
}
void handleThreadContextMenu(thread.id, {
x: event.clientX,
y: event.clientY,
});
}}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
{prStatus && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={prStatus.tooltip}
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
onClick={(event) => {
openPrLink(event, prStatus.url);
}}
>
<GitPullRequestIcon className="size-3" />
</button>
}
/>
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{threadStatus.label}</span>
</span>
)}
{renamingThreadId === thread.id ? (
<input
ref={(el) => {
if (el && renamingInputRef.current !== el) {
renamingInputRef.current = el;
el.focus();
el.select();
}
}}
className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
value={renamingTitle}
onChange={(e) => setRenamingTitle(e.target.value)}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter") {
e.preventDefault();
renamingCommittedRef.current = true;
void commitRename(thread.id, renamingTitle, thread.title);
} else if (e.key === "Escape") {
e.preventDefault();
renamingCommittedRef.current = true;
cancelRename();
}
}}
onBlur={() => {
if (!renamingCommittedRef.current) {
void commitRename(thread.id, renamingTitle, thread.title);
}
}}
onClick={(e) => e.stopPropagation()}
}
}}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
{prStatus && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={prStatus.tooltip}
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
onClick={(event) => {
openPrLink(event, prStatus.url);
}}
>
<GitPullRequestIcon className="size-3" />
</button>
}
/>
) : (
<span className="min-w-0 flex-1 truncate text-xs">
{thread.title}
</span>
)}
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
/>
</span>
)}
<TooltipPopup side="top">
{prStatus.tooltip}
</TooltipPopup>
</Tooltip>
)}
{threadStatus && (
<span
className={`text-[10px] ${
isActive ? "text-foreground/65" : "text-muted-foreground/40"
}`}
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
{formatRelativeTime(thread.createdAt)}
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">
{threadStatus.label}
</span>
</span>
</div>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
);
})}
)}
{renamingThreadId === thread.id ? (
<input
ref={(el) => {
if (el && renamingInputRef.current !== el) {
renamingInputRef.current = el;
el.focus();
el.select();
}
}}
className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
value={renamingTitle}
onChange={(e) => setRenamingTitle(e.target.value)}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter") {
e.preventDefault();
renamingCommittedRef.current = true;
void commitRename(
thread.id,
renamingTitle,
thread.title,
);
} else if (e.key === "Escape") {
e.preventDefault();
renamingCommittedRef.current = true;
cancelRename();
}
}}
onBlur={() => {
if (!renamingCommittedRef.current) {
void commitRename(
thread.id,
renamingTitle,
thread.title,
);
}
}}
onClick={(e) => e.stopPropagation()}
/>
) : (
<span className="min-w-0 flex-1 truncate text-xs">
{thread.title}
</span>
)}
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
/>
</span>
)}
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/65"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTime(thread.createdAt)}
</span>
</div>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
);
})}
{hasHiddenThreads && !isThreadListExpanded && (
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
onClick={() => {
expandThreadListForProject(project.id);
}}
>
<span>Show more</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
{hasHiddenThreads && isThreadListExpanded && (
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
onClick={() => {
collapseThreadListForProject(project.id);
}}
>
<span>Show less</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
</SidebarMenuSub>
{hasHiddenThreads && !isThreadListExpanded && (
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
data-thread-selection-safe
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
onClick={() => {
expandThreadListForProject(project.id);
}}
>
<span>Show more</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
{hasHiddenThreads && isThreadListExpanded && (
<SidebarMenuSubItem className="w-full">
<SidebarMenuSubButton
render={<button type="button" />}
data-thread-selection-safe
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
onClick={() => {
collapseThreadListForProject(project.id);
}}
>
<span>Show less</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
</SidebarMenuSub>
</CollapsibleContent>
</Collapsible>
)}
@@ -17,9 +17,7 @@ describe("shouldUseCompactComposerFooter", () => {
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,
);
expect(shouldUseCompactComposerFooter(COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX + 48)).toBe(false);
});
it("uses a higher breakpoint for wide action states", () => {
@@ -31,7 +31,11 @@ const baseState: DesktopUpdateState = {
describe("desktop update button state", () => {
it("shows a download action when an update is available", () => {
const state: DesktopUpdateState = { ...baseState, status: "available", availableVersion: "1.1.0" };
const state: DesktopUpdateState = {
...baseState,
status: "available",
availableVersion: "1.1.0",
};
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
expect(resolveDesktopUpdateButtonAction(state)).toBe("download");
});
+2 -1
View File
@@ -24,7 +24,8 @@ function ScrollArea({
scrollFade &&
"mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] [--fade-size:1.5rem]",
scrollbarGutter && "data-has-overflow-y:pe-2.5 data-has-overflow-x:pb-2.5",
hideScrollbars && "[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
hideScrollbars &&
"[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
)}
data-slot="scroll-area-viewport"
>
+10 -2
View File
@@ -17,7 +17,11 @@ describe("shouldHideCollapsedToastContent", () => {
describe("buildVisibleToastLayout", () => {
it("computes indices and offsets from the visible subset", () => {
const visibleToasts = [{ id: "a", height: 48 }, { id: "b", height: 72 }, { id: "c", height: 24 }];
const visibleToasts = [
{ id: "a", height: 48 },
{ id: "b", height: 72 },
{ id: "c", height: 24 },
];
const layout = buildVisibleToastLayout(visibleToasts);
@@ -37,7 +41,11 @@ describe("buildVisibleToastLayout", () => {
});
it("treats missing heights as zero", () => {
const layout = buildVisibleToastLayout([{ id: "a" }, { id: "b", height: undefined }, { id: "c", height: 30 }]);
const layout = buildVisibleToastLayout([
{ id: "a" },
{ id: "b", height: undefined },
{ id: "c", height: 30 },
]);
assert.equal(layout.frontmostHeight, 0);
assert.deepEqual(
+9 -6
View File
@@ -61,7 +61,9 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
return expandedCursor;
}
function collapsedSegmentLength(segment: { type: "text"; text: string } | { type: "mention" }): number {
function collapsedSegmentLength(
segment: { type: "text"; text: string } | { type: "mention" },
): number {
return segment.type === "mention" ? 1 : segment.text.length;
}
@@ -160,15 +162,16 @@ export function detectComposerTrigger(text: string, cursorInput: number): Compos
};
}
export function parseStandaloneComposerSlashCommand(text: string): Exclude<
ComposerSlashCommand,
"model"
> | null {
export function parseStandaloneComposerSlashCommand(
text: string,
): Exclude<ComposerSlashCommand, "model"> | null {
const match = /^\/(plan|default)\s*$/i.exec(text.trim());
if (!match) {
return null;
}
return match[1]?.toLowerCase() === "plan" ? "plan" : "default";
const command = match[1]?.toLowerCase();
if (command === "plan") return "plan";
return "default";
}
export function replaceTextRange(
+6 -4
View File
@@ -252,9 +252,9 @@ describe("composerDraftStore project draft thread mapping", () => {
store.clearProjectDraftThreadId(projectId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId).toBe(
threadId,
);
expect(
useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId,
).toBe(threadId);
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
});
@@ -380,7 +380,9 @@ describe("composerDraftStore setModel", () => {
store.setModel(threadId, "gpt-5.3-codex");
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.model).toBe("gpt-5.3-codex");
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.model).toBe(
"gpt-5.3-codex",
);
});
});
+8 -11
View File
@@ -9,11 +9,7 @@ import {
type RuntimeMode,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/shared/model";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type ChatImageAttachment,
} from "./types";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";
import { Debouncer } from "@tanstack/react-pacer";
import { create } from "zustand";
import { createJSONStorage, persist, type StateStorage } from "zustand/middleware";
@@ -495,8 +491,7 @@ function hydreatePersistedComposerImageAttachment(
attachment: PersistedComposerImageAttachment,
): File | null {
const commaIndex = attachment.dataUrl.indexOf(",");
const header =
commaIndex === -1 ? attachment.dataUrl : attachment.dataUrl.slice(0, commaIndex);
const header = commaIndex === -1 ? attachment.dataUrl : attachment.dataUrl.slice(0, commaIndex);
const payload = commaIndex === -1 ? "" : attachment.dataUrl.slice(commaIndex + 1);
if (payload.length === 0) {
return null;
@@ -605,7 +600,8 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
const nextDraftThread: DraftThreadState = {
projectId,
createdAt: options?.createdAt ?? existingThread?.createdAt ?? new Date().toISOString(),
runtimeMode: options?.runtimeMode ?? existingThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
runtimeMode:
options?.runtimeMode ?? existingThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
interactionMode:
options?.interactionMode ??
existingThread?.interactionMode ??
@@ -673,7 +669,9 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
return state;
}
const nextWorktreePath =
options.worktreePath === undefined ? existing.worktreePath : (options.worktreePath ?? null);
options.worktreePath === undefined
? existing.worktreePath
: (options.worktreePath ?? null);
const nextDraftThread: DraftThreadState = {
projectId: nextProjectId,
createdAt:
@@ -685,8 +683,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
branch: options.branch === undefined ? existing.branch : (options.branch ?? null),
worktreePath: nextWorktreePath,
envMode:
options.envMode ??
(nextWorktreePath ? "worktree" : (existing.envMode ?? "local")),
options.envMode ?? (nextWorktreePath ? "worktree" : (existing.envMode ?? "local")),
};
const isUnchanged =
nextDraftThread.projectId === existing.projectId &&
+15
View File
@@ -2,6 +2,7 @@ import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import {
gitMutationKeys,
gitPreparePullRequestThreadMutationOptions,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
} from "./gitReactQuery";
@@ -16,6 +17,12 @@ describe("gitMutationKeys", () => {
it("scopes pull keys by cwd", () => {
expect(gitMutationKeys.pull("/repo/a")).not.toEqual(gitMutationKeys.pull("/repo/b"));
});
it("scopes pull request thread preparation keys by cwd", () => {
expect(gitMutationKeys.preparePullRequestThread("/repo/a")).not.toEqual(
gitMutationKeys.preparePullRequestThread("/repo/b"),
);
});
});
describe("git mutation options", () => {
@@ -30,4 +37,12 @@ describe("git mutation options", () => {
const options = gitPullMutationOptions({ cwd: "/repo/a", queryClient });
expect(options.mutationKey).toEqual(gitMutationKeys.pull("/repo/a"));
});
it("attaches cwd-scoped mutation key for preparePullRequestThread", () => {
const options = gitPreparePullRequestThreadMutationOptions({
cwd: "/repo/a",
queryClient,
});
expect(options.mutationKey).toEqual(gitMutationKeys.preparePullRequestThread("/repo/a"));
});
});
+43
View File
@@ -18,6 +18,8 @@ export const gitMutationKeys = {
checkout: (cwd: string | null) => ["git", "mutation", "checkout", cwd] as const,
runStackedAction: (cwd: string | null) => ["git", "mutation", "run-stacked-action", cwd] as const,
pull: (cwd: string | null) => ["git", "mutation", "pull", cwd] as const,
preparePullRequestThread: (cwd: string | null) =>
["git", "mutation", "prepare-pull-request-thread", cwd] as const,
};
export function invalidateGitQueries(queryClient: QueryClient) {
@@ -56,6 +58,26 @@ export function gitBranchesQueryOptions(cwd: string | null) {
});
}
export function gitResolvePullRequestQueryOptions(input: {
cwd: string | null;
reference: string | null;
}) {
return queryOptions({
queryKey: ["git", "pull-request", input.cwd, input.reference] as const,
queryFn: async () => {
const api = ensureNativeApi();
if (!input.cwd || !input.reference) {
throw new Error("Pull request lookup is unavailable.");
}
return api.git.resolvePullRequest({ cwd: input.cwd, reference: input.reference });
},
enabled: input.cwd !== null && input.reference !== null,
staleTime: 30_000,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
}
export function gitInitMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
return mutationOptions({
mutationKey: gitMutationKeys.init(input.cwd),
@@ -168,3 +190,24 @@ export function gitRemoveWorktreeMutationOptions(input: { queryClient: QueryClie
},
});
}
export function gitPreparePullRequestThreadMutationOptions(input: {
cwd: string | null;
queryClient: QueryClient;
}) {
return mutationOptions({
mutationFn: async ({ reference, mode }: { reference: string; mode: "local" | "worktree" }) => {
const api = ensureNativeApi();
if (!input.cwd) throw new Error("Pull request thread preparation is unavailable.");
return api.git.preparePullRequestThread({
cwd: input.cwd,
reference,
mode,
});
},
mutationKey: gitMutationKeys.preparePullRequestThread(input.cwd),
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
},
});
}
+5 -2
View File
@@ -91,7 +91,9 @@ describe("buildTurnDiffTree", () => {
});
it("normalizes file paths with windows separators", () => {
const tree = buildTurnDiffTree([{ path: "apps\\web\\src\\index.ts", additions: 2, deletions: 1 }]);
const tree = buildTurnDiffTree([
{ path: "apps\\web\\src\\index.ts", additions: 2, deletions: 1 },
]);
expect(tree).toEqual([
{
@@ -157,7 +159,8 @@ describe("buildTurnDiffTree", () => {
expect(tree).toHaveLength(2);
const directoryNodes = tree.filter(
(node): node is Extract<(typeof tree)[number], { kind: "directory" }> => node.kind === "directory",
(node): node is Extract<(typeof tree)[number], { kind: "directory" }> =>
node.kind === "directory",
);
expect(directoryNodes.map((node) => node.name).toSorted()).toEqual([" a", "a"]);
expect(directoryNodes.map((node) => node.path).toSorted()).toEqual([" a", "a"]);
+13 -4
View File
@@ -1,6 +1,8 @@
import { CommandId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
import { type CxOptions, cx } from "class-variance-authority";
import { twMerge } from "tailwind-merge";
import * as Random from "effect/Random";
import * as Effect from "effect/Effect";
export function cn(...inputs: CxOptions) {
return twMerge(cx(inputs));
@@ -14,10 +16,17 @@ export function isWindowsPlatform(platform: string): boolean {
return /^win(dows)?/i.test(platform);
}
export const newCommandId = (): CommandId => CommandId.makeUnsafe(crypto.randomUUID());
export function randomUUID(): string {
if (typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return Effect.runSync(Random.nextUUIDv4);
}
export const newProjectId = (): ProjectId => ProjectId.makeUnsafe(crypto.randomUUID());
export const newCommandId = (): CommandId => CommandId.makeUnsafe(randomUUID());
export const newThreadId = (): ThreadId => ThreadId.makeUnsafe(crypto.randomUUID());
export const newProjectId = (): ProjectId => ProjectId.makeUnsafe(randomUUID());
export const newMessageId = (): MessageId => MessageId.makeUnsafe(crypto.randomUUID());
export const newThreadId = (): ThreadId => ThreadId.makeUnsafe(randomUUID());
export const newMessageId = (): MessageId => MessageId.makeUnsafe(randomUUID());
+1 -3
View File
@@ -95,9 +95,7 @@ export function derivePendingUserInputProgress(
questionIndex: number,
): PendingUserInputProgress {
const normalizedQuestionIndex =
questions.length === 0
? 0
: Math.max(0, Math.min(questionIndex, questions.length - 1));
questions.length === 0 ? 0 : Math.max(0, Math.min(questionIndex, questions.length - 1));
const activeQuestion = questions[normalizedQuestionIndex] ?? null;
const activeDraft = activeQuestion ? draftAnswers[activeQuestion.id] : undefined;
const resolvedAnswer = resolvePendingUserInputAnswer(activeDraft);
+6 -3
View File
@@ -31,9 +31,12 @@ describe("buildPlanImplementationPrompt", () => {
describe("buildCollapsedProposedPlanPreviewMarkdown", () => {
it("drops the redundant title heading and preserves the following markdown lines", () => {
expect(
buildCollapsedProposedPlanPreviewMarkdown("# Integrate RPC\n\n## Summary\n\n- step 1\n- step 2", {
maxLines: 4,
}),
buildCollapsedProposedPlanPreviewMarkdown(
"# Integrate RPC\n\n## Summary\n\n- step 1\n- step 2",
{
maxLines: 4,
},
),
).toBe("- step 1\n- step 2");
});
+2 -6
View File
@@ -5,8 +5,7 @@ export function proposedPlanTitle(planMarkdown: string): string | null {
export function stripDisplayedPlanMarkdown(planMarkdown: string): string {
const lines = planMarkdown.trimEnd().split(/\r?\n/);
const sourceLines =
lines[0] && /^\s{0,3}#{1,6}\s+/.test(lines[0]) ? lines.slice(1) : [...lines];
const sourceLines = lines[0] && /^\s{0,3}#{1,6}\s+/.test(lines[0]) ? lines.slice(1) : [...lines];
while (sourceLines[0]?.trim().length === 0) {
sourceLines.shift();
}
@@ -75,10 +74,7 @@ export function buildPlanImplementationPrompt(planMarkdown: string): string {
return `PLEASE IMPLEMENT THIS PLAN:\n${planMarkdown.trim()}`;
}
export function resolvePlanFollowUpSubmission(input: {
draftText: string;
planMarkdown: string;
}): {
export function resolvePlanFollowUpSubmission(input: { draftText: string; planMarkdown: string }): {
text: string;
interactionMode: "default" | "plan";
} {
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import { parsePullRequestReference } from "./pullRequestReference";
describe("parsePullRequestReference", () => {
it("accepts GitHub pull request URLs", () => {
expect(parsePullRequestReference("https://github.com/pingdotgg/t3code/pull/42")).toBe(
"https://github.com/pingdotgg/t3code/pull/42",
);
});
it("accepts raw numbers", () => {
expect(parsePullRequestReference("42")).toBe("42");
});
it("accepts #number references", () => {
expect(parsePullRequestReference("#42")).toBe("#42");
});
it("rejects non-pull-request input", () => {
expect(parsePullRequestReference("feature/my-branch")).toBeNull();
});
});
+22
View File
@@ -0,0 +1,22 @@
const GITHUB_PULL_REQUEST_URL_PATTERN =
/^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
const PULL_REQUEST_NUMBER_PATTERN = /^#?(\d+)$/;
export function parsePullRequestReference(input: string): string | null {
const trimmed = input.trim();
if (trimmed.length === 0) {
return null;
}
const urlMatch = GITHUB_PULL_REQUEST_URL_PATTERN.exec(trimmed);
if (urlMatch?.[1]) {
return trimmed;
}
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(trimmed);
if (numberMatch?.[1]) {
return trimmed.startsWith("#") ? trimmed : numberMatch[1];
}
return null;
}
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more