Compare commits

..
Author SHA1 Message Date
Ben Davis bb538d76c5 Optimize thread navigation render work 2026-05-06 16:08:27 -07:00
Ben Davis 357211864c Remove sidebar footer separator 2026-05-06 15:24:46 -07:00
Ben Davis 4e4f44f286 fix 2026-05-06 02:29:21 -07:00
Ben Davis 90c0d7d95a Ignore stale theme loads after preference changes
- Add preference equality guard in theme hook
- Prevent outdated async theme loads from overriding newer selections
2026-05-06 02:21:19 -07:00
Ben Davis 2b7dcd0295 Persist fallback theme and reuse destructive color
- Reset stored theme preference when the requested VS Code theme cannot be loaded
- Reuse the resolved destructive color for both destructive and destructive-foreground mapping
2026-05-06 02:08:03 -07:00
Ben Davis 169e16803d Add VS Code theme discovery and app theming
- Discover editor themes from desktop installs
- Map theme colors into shared app and syntax tokens
- Wire theme state through desktop, web, and settings
2026-05-06 02:01:32 -07:00
Ben Davis 0dc0cc76be Add VS Code theme integration plan
- Document discovery, mapping, and persistence strategy
- Outline desktop bridge, settings UI, and rollout phases
2026-05-06 01:09:14 -07:00
Julius MarmingeandJulius Marminge 499f1463d5 Split server CLI into focused submodules (#2545)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-05 23:02:05 -07:00
a2ff50dbba Add process and trace diagnostics views (#2532)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-05-06 04:22:50 +00:00
Minigamer42 166bce0389 Feature/intellij editors (#2475) 2026-05-06 04:12:52 +00:00
1498335e39 Optimize MessagesTimeline work row stability (#2527)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-05 20:57:33 -07:00
Julius MarmingeandJulius Marminge 25c9d267ac Stabilize git workspace and terminal tests (#2540)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-05 20:31:44 -07:00
536dcad19e Reduce timeline row rerenders (#2498)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-05 20:26:38 -07:00
Julius Marmingeandcodex 0e38870647 Add keybindings settings editor (#2533)
Co-authored-by: codex <[email protected]>
2026-05-06 00:08:52 +00:00
9b604bcae1 provider update advisories (#2312)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-05-05 15:59:51 -07:00
t3-code[bot] 35721d9a08 chore(release): prepare v0.0.22 2026-05-05 01:09:49 +00:00
shivamandJulius Marminge f4c9418d40 Add collapsible file diffs + @pierre/diffs version update. (#2502)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-04 17:06:07 -07:00
PeterandPeter van der Heijden 02dd47ea31 Fix repeated effect-language-service prepare hooks during bun install (#2497)
Co-authored-by: Peter van der Heijden <[email protected]>
2026-05-04 22:56:59 +00:00
legsandJulius Marminge aca0fa4e5b reduce startup time by ~47% and memory usage by up to 150-300MB (#2204)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-04 13:56:01 -07:00
Julius Marminge 0576820755 Prevent focus-ring clipping in AnimatedHeight (#2503) 2026-05-04 20:50:30 +00:00
Anirudh Vempati cb3211c8f3 README: Add OpenCode to first mention of supported agents (#2436) 2026-05-04 20:17:47 +00:00
Julius MarmingeandJulius Marminge 826965978b bitubicket base brnach (#2500)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-04 10:02:25 -07:00
623e471a02 Fix markdown highlight render stability (#2479)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-04 09:38:17 -07:00
91a03e0747 feat(source-control): add Bitbucket & Azure Devops providers (#2473)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-05-04 00:59:58 -07:00
Julius Marminge d501ebe877 fix version test (#2490) 2026-05-04 05:27:18 +00:00
Julius Marmingeandcodex 3772fa127c feat: Hosted Frontend, Tailscale Integration & SSH Lancher (#2361)
Co-authored-by: codex <[email protected]>
2026-05-03 22:19:15 -07:00
92e340d80c feat(web): collapse mobile composer by default (#1263)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-03 19:48:10 -07:00
d7969264de Add remote repository publish and discovery support (#2482)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-05-03 18:05:46 -07:00
Illia Panasenko f7748a0d65 feat: add "hide whitespace changes" option for diffs (#2389) 2026-05-03 11:47:37 -07:00
Julius MarmingeandJulius Marminge 0ce7e56e43 feat(scm): Gitlab (#2462)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-02 18:59:47 -07:00
Julius MarmingeandJulius Marminge 350d76ee14 [codex] Align GitHub source control adapter errors (#2476)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-02 16:59:03 -07:00
6d7fe2eeb7 Introduce pluggable VCS driver foundation (#2435)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-05-02 16:08:17 -07:00
Julius MarmingeandJulius Marminge 460d9c3eb9 Refactor provider settings to declarative metadata (#2452)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-02 14:14:34 -07:00
Ishan cb8015a34d fix(claude-agent): opt into claude_code system prompt preset (#2472) 2026-05-02 12:38:42 -07:00
Saikrishna Ambeti 8f50ca8e2c fix(web): show friendly error for invalid pairing token (#2222) 2026-05-02 12:23:26 -07:00
Julius MarmingeandJulius Marminge 4ceabac764 Fix dialog footer button clipping in Git actions dialog (#2458)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-01 23:57:44 -07:00
Julius MarmingeandJulius Marminge 7a3f21e7ca [codex] fix Discord release version flag (#2449)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-01 18:39:41 +00:00
Julius MarmingeandJulius Marminge 17b43960e8 Add structured Discord webhook logging for release notifications (#2431)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-01 03:53:47 +00:00
Julius MarmingeandJulius Marminge e5c7ac5a8c Optimize release workflow job execution (#2430)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 20:08:11 -07:00
a480f07241 Add Discord release announcements (#2429)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 19:13:05 -07:00
Adam Mansfield 1eb6fcea84 fix: opencode is not on PATH on Windows (#2183) 2026-04-30 18:15:45 -07:00
4ef361da73 fix(mobile): enable touch scrolling in file picker modal (#2420)
Co-authored-by: Claude Haiku 4.5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 18:12:48 -07:00
Noah Gregory c07ac592d8 fix: bump electron version to v40.9.3 and add it to our trusted dependencies (#2427) 2026-04-30 17:34:21 -07:00
d649ccf715 fix(web): respect iOS safe areas across mobile chrome & other mobile layout fixes (#2392)
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 16:26:36 -07:00
shivam f54f4385e5 Narrow the right sidebar and update task panel and diff panel (#2409) 2026-04-30 15:33:06 -07:00
Julius Marminge e25ce07cc2 Add new GitHub users to VOUCHED.td (#2425) 2026-04-30 18:58:31 +00:00
532a1d891d fix(web): make thread archive button always visible on mobile (#2423)
Co-authored-by: Claude Sonnet 4.7 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 18:46:05 +00:00
9e2f7129e3 fix(web): make new thread button always visible on mobile (#2419)
Co-authored-by: Claude Haiku 4.5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 18:18:12 +00:00
a4298f1ceb fix(web): hide mobile sidebar after thread selection or creation (#1293)
Co-authored-by: Murat Aslan <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 11:10:37 -07:00
kp 86c94b4852 fix(web): allow closing diff panel in non-git projects (#2413) 2026-04-30 04:36:05 +00:00
Guilherme Vieira 69d9a659a3 fix(git): hide stale merged/closed PRs on the default branch (#1966) 2026-04-29 21:29:48 -07:00
9acf46a76d fix(web): prevent iOS Safari auto-zoom on input focus (#1652)
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-29 18:03:40 -07:00
Bas Milius 44b39fe2ec fix(server): key AskUserQuestion answers by question text (#2404) 2026-04-29 17:44:44 -07:00
Julius Marmingeandcodex 02903f2db8 [codex] fix terminal dimension validation (#2411)
Co-authored-by: codex <[email protected]>
2026-04-30 00:09:00 +00:00
Julius Marmingeandcodex 22b7d8c524 [codex] Fix visited timestamp under clock skew (#2408)
Co-authored-by: codex <[email protected]>
2026-04-29 17:07:21 -07:00
pomp fe2fde5172 Add OpenCode to README (#2154) 2026-04-29 23:49:49 +00:00
zurielbm 7da6522fb8 fix: updated UI "add project" icon to match the command pallete icon (#2176) 2026-04-29 23:48:08 +00:00
08e6d4cfbf feat: Multi-Provider support (#2277)
Co-authored-by: Claude Opus 4.7 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-29 16:13:55 -07:00
Josh Meads 35822884d1 Stop OpenCode refresh from leaking serve processes
OpenCode can leave the long-lived serve child in the spawned process group after the wrapper exits. Provider refresh owns only a scoped inventory probe, so cleanup targets that local process group when the refresh scope closes.

Constraint: Keep active OpenCode thread sessions scoped to their own session lifecycle.
Rejected: Disable provider refresh | would hide model and auth state changes.
Confidence: high
Scope-risk: narrow
Tested: bun run test src/provider/Layers/OpenCodeProvider.test.ts src/provider/Layers/OpenCodeAdapter.test.ts
Tested: bun fmt
Tested: bun lint
Tested: bun typecheck
Tested: bun run build:desktop
2026-04-29 11:02:16 -07:00
Julius Marminge dbebc387dd Ignore stale WebSocket lifecycle events after reconnect (#2372) 2026-04-27 09:50:19 -07:00
494 changed files with 58354 additions and 17427 deletions

No files matched your search

+3
View File
@@ -30,3 +30,6 @@ github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
+67 -7
View File
@@ -30,7 +30,7 @@ jobs:
check_changes:
name: Check for changes since last nightly
if: github.event_name == 'schedule'
runs-on: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
outputs:
has_changes: ${{ steps.check.outputs.has_changes }}
steps:
@@ -376,13 +376,16 @@ jobs:
registry-url: https://registry.npmjs.org
- name: Install dependencies
run: bun install --frozen-lockfile
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build web package
run: bun --filter=@t3tools/web run build
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
run: bun --filter=t3 run build
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
@@ -391,7 +394,7 @@ jobs:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- id: app_token
@@ -418,7 +421,7 @@ jobs:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
@@ -552,7 +555,7 @@ jobs:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- id: update_versions
name: Update version strings
@@ -562,7 +565,7 @@ jobs:
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
run: bunx oxfmt@0.40.0 apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
- name: Refresh lockfile
if: steps.update_versions.outputs.changed == 'true'
@@ -585,3 +588,60 @@ jobs:
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG"
git push origin HEAD:main
announce_discord:
name: Announce release on Discord
if: |
always() && !cancelled() &&
needs.preflight.result == 'success' &&
needs.release.result == 'success' &&
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
needs: [preflight, release, finalize]
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- name: Announce prerelease on Discord
if: needs.preflight.outputs.is_prerelease == 'true'
continue-on-error: true
env:
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_NIGHTLY_ROLE_ID }}
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
run: |
node scripts/notify-discord-release.ts prerelease \
--role-id "$DISCORD_MENTION_ROLE_ID" \
--release-name "${{ needs.preflight.outputs.release_name }}" \
--release-version "${{ needs.preflight.outputs.version }}" \
--tag "${{ needs.preflight.outputs.tag }}" \
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
- name: Announce latest release on Discord
if: needs.preflight.outputs.make_latest == 'true'
continue-on-error: true
env:
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_LATEST_ROLE_ID }}
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
run: |
node scripts/notify-discord-release.ts latest \
--role-id "$DISCORD_MENTION_ROLE_ID" \
--release-name "${{ needs.preflight.outputs.release_name }}" \
--release-version "${{ needs.preflight.outputs.version }}" \
--tag "${{ needs.preflight.outputs.tag }}" \
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
@@ -0,0 +1,216 @@
# Version Control Phase 1: VCS Driver Foundation
## Goal
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
## Scope
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
- Add server services under `apps/server/src/vcs`:
- `Services/VcsDriver.ts`
- `Services/VcsRepositoryResolver.ts`
- `Services/VcsProcess.ts`
- `Layers/GitVcsDriver.ts`
- `errors.ts`
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
## Non-Goals
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
- No T3 Review implementation yet.
- No broad UI redesign.
## Driver Model
Use provider-neutral nouns in new APIs:
- `VcsDriver`: local repository mechanics.
- `RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
- `WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
- `ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
- `RefName`: branch, bookmark, tag, or provider-specific ref.
The initial driver capabilities should be explicit:
```ts
export interface VcsDriverCapabilities {
readonly kind: "git" | "jj" | "sapling" | "unknown";
readonly supportsWorktrees: boolean;
readonly supportsBookmarks: boolean;
readonly supportsAtomicSnapshot: boolean;
readonly supportsPushDefaultRemote: boolean;
}
```
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
- `detectRepository(cwd)`
- `status(cwd, options)`
- `listRefs(cwd, query/pagination)`
- `checkoutRef(cwd, ref)`
- `createRef(cwd, ref, from?)`
- `createWorkspace(cwd, ref, path?)`
- `removeWorkspace(path)`
- `prepareChangeContext(cwd, filePaths?)`
- `createChange(cwd, message, options)`
- `push(cwd, target?)`
- `rangeContext(cwd, base, head)`
- `listWorkspaceFiles(cwd, options)`
## Effect Process Layer
Create a small reusable `VcsProcess` service instead of using `runProcess`.
Requirements:
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
- Support scoped acquisition/release for long-running commands and interruption.
- Support bounded stdout/stderr collection with truncation markers.
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
- Support stdin.
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
- Stream output lines to progress callbacks as Effects.
- Return a typed `ProcessOutput` value for successful execution.
- Fail with typed errors, not generic thrown exceptions.
Errors should be schema-backed tagged classes, for example:
- `VcsProcessSpawnError`
- `VcsProcessExitError`
- `VcsProcessTimeoutError`
- `VcsOutputDecodeError`
- `VcsRepositoryDetectionError`
- `VcsUnsupportedOperationError`
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
## Git Driver Rewrite
Rewrite Git support against `VcsProcess`.
Carry forward current behavior from:
- `apps/server/src/git/Layers/GitCore.ts`
- `apps/server/src/git/Layers/GitCore.test.ts`
- current Git status/branch/worktree contracts
But split the implementation into smaller modules:
- command execution and hardening config
- repository detection
- status parsing
- branch/ref parsing
- worktree operations
- commit/range context generation
- push/pull operations
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
## Freshness and Local Caching
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
Treat these as live/local:
- repository detection for the active cwd
- working copy dirty state
- staged/unstaged/untracked file summaries
- current branch/bookmark/change name
- local branch/bookmark lists
- local worktree/workspace lists
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
Treat these as cached or explicit-refresh only:
- remote tracking branch refreshes
- ahead/behind counts that require network fetches
- default branch discovery from a remote provider
- remote branch lists beyond locally known refs
The VCS driver should expose freshness metadata with status results:
```ts
export interface VcsFreshness {
readonly source: "live-local" | "cached-local" | "cached-remote" | "explicit-remote";
readonly observedAt: string;
readonly expiresAt?: string;
}
```
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
Use Effect `Cache` for repository identity and expensive local metadata:
- key by resolved repository root plus VCS kind
- invalidate on cwd/root changes and workspace mutation operations
- use short TTLs for local status caches when filesystem events are unavailable
- never hide command failures behind stale values unless the caller explicitly accepts stale data
## Cutover Policy
Prefer direct migration and deletion over compatibility wrappers.
Rules:
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
- No new feature work may depend on transitional modules.
Expected transitional candidates:
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
## Tests
Add integration-style tests with real temporary Git repositories for the new Git driver:
- non-repository detection
- status for clean/dirty/untracked/staged states
- branch/ref list with pagination
- checkout/create branch
- worktree create/remove
- commit context generation with file filters
- commit creation with hook progress events
- push behavior against a local bare remote
- status polling does not perform remote network refresh by default
- concurrent duplicate status requests are coalesced
- bounded output/truncation
- timeout/interruption
- typed error shape for command failure and missing executable
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
## Migration Steps
1. Add `vcs` contracts and tagged errors.
2. Add `VcsProcess` and unit tests around process execution semantics.
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
4. Implement `GitVcsDriver` with real Git command integration tests.
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
6. Move commit/range/push callers to the VCS service directly.
7. Delete migrated `GitCore` internals and tests as each caller group moves.
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
## Acceptance Criteria
- Current Git branch/status/worktree/commit behavior remains intact.
- New Git implementation does not depend on `processRunner.ts`.
- New errors are typed and inspectable by tests.
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Background status refresh is local-only by default and cannot hit provider rate limits.
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
@@ -0,0 +1,268 @@
# Version Control Phase 2: Source Control Provider Foundation
## Goal
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
## Scope
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
- Add server services under `apps/server/src/sourceControl`:
- `Services/SourceControlProvider.ts`
- `Services/SourceControlProviderRegistry.ts`
- `Services/SourceControlProcess.ts`
- `Layers/GitHubSourceControlProvider.ts`
- `errors.ts`
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
## Non-Goals
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
- No in-app review UI yet.
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
## Provider Model
Use provider-neutral names:
- `SourceControlProvider`: hosted repository and change-request mechanics.
- `ChangeRequest`: GitHub pull request, GitLab merge request, Azure pull request.
- `ChangeRequestThread`: review or discussion thread.
- `ChangeRequestComment`: top-level or inline comment.
- `ProviderRepository`: owner/project/repo identity plus clone URLs.
Core provider operations:
- `detectRemote(remoteUrl)`
- `checkAuth(cwd)`
- `getRepository(cwd | remoteUrl)`
- `getDefaultTargetRef(repository)`
- `listChangeRequests(repository, filters)`
- `getChangeRequest(repository, reference)`
- `createChangeRequest(repository, input)`
- `checkoutChangeRequest(cwd, changeRequest, options)`
- `getCloneUrls(repository)`
Review-facing operations should be designed now, even if unimplemented:
- `listReviewThreads(changeRequest)`
- `createReviewComment(changeRequest, input)`
- `replyToReviewThread(thread, input)`
- `resolveReviewThread(thread)`
- `submitReview(changeRequest, input)`
Each operation should be guarded by capabilities:
```ts
export interface SourceControlProviderCapabilities {
readonly kind: "github" | "gitlab" | "azure-devops" | "unknown";
readonly supportsCreateChangeRequest: boolean;
readonly supportsCheckoutChangeRequest: boolean;
readonly supportsReviewThreads: boolean;
readonly supportsInlineComments: boolean;
readonly supportsDraftChangeRequests: boolean;
}
```
## Provider Registry
Add a registry that resolves a provider from repository remotes and explicit user input.
Rules:
- Detection should be pure where possible and testable without spawning CLIs.
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
## Rate Limits and Provider Caching
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
Default behavior:
- Pure URL/remote parsing is always live because it is local.
- Provider detection from local remotes is live-local.
- Authentication checks are cached.
- Repository metadata is cached.
- Default branch metadata is cached.
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
- Create/update operations invalidate affected cache keys immediately after success.
The provider API should make freshness explicit:
```ts
export interface SourceControlFreshness {
readonly source: "live-local" | "cached-provider" | "live-provider";
readonly observedAt: string;
readonly expiresAt?: string;
readonly stale?: boolean;
}
export type ProviderRefreshPolicy =
| "cache-first"
| "stale-while-revalidate"
| "force-refresh"
| "local-only";
```
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
Use Effect `Cache` for provider data:
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
Provider drivers should surface rate-limit signals when available:
- remaining quota
- reset time
- retry-after duration
- whether the limit is primary, secondary/abuse, or unknown
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
Avoid rate-limit footguns:
- no provider calls from render loops or fast status polling
- no listing all PRs/MRs across all repos to infer one branch state
- no silent GitHub fallback for unknown providers
- no unbounded cache cardinality for branch names or free-form search queries
- no per-thread duplicate provider refresh when multiple views observe the same repository
## GitHub Provider Rewrite
Rewrite GitHub support as `GitHubSourceControlProvider`.
Carry forward behavior from:
- `apps/server/src/git/Layers/GitHubCli.ts`
- `apps/server/src/git/Layers/GitHubCli.test.ts`
- `apps/server/src/git/githubPullRequests.ts`
- GitHub-specific `GitManager` PR paths
Implementation requirements:
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
- Keep stdout/stderr bounded.
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
## GitManager Cutover
Refactor `GitManager` so it coordinates three independent services:
- `VcsDriver` for local repository mechanics.
- `SourceControlProviderRegistry` for hosted provider selection.
- `TextGeneration` for message/body generation.
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
The Commit + PR flow should become:
1. Resolve VCS repository and local status.
2. Resolve source-control provider from remotes.
3. Generate commit content through the existing text generation service.
4. Create local change through `VcsDriver`.
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
6. Generate change-request title/body.
7. Create the change request through `SourceControlProvider`.
## Cutover Policy
This phase should aggressively remove old GitHub-specific internals.
Rules:
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
## GitLab and Azure Readiness
Use the triaged references as implementation inputs, not merge targets:
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
The abstraction should let Phase 3 add:
- `GitLabSourceControlProvider` using `glab`.
- `AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
No provider should need to edit GitHub code to join the registry.
## T3 Review Design Constraint
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
That means contracts should include stable IDs and enough metadata for:
- file-level diffs
- inline review threads
- resolved/unresolved state
- top-level discussion comments
- pending review submission
- provider URL back-links
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
## Tests
Add tests at three levels:
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
Required cases:
- GitHub PR URL, number, and branch-ish references.
- GitLab MR URL/reference parsing.
- Azure DevOps PR URL parsing for same-repo URLs.
- unknown provider returns unsupported-operation errors.
- missing CLI and auth failures produce distinct typed errors.
- invalid CLI JSON fails at decode boundary with useful context.
## Migration Steps
1. Add `sourceControl` contracts and provider-neutral schemas.
2. Add shared remote/reference parser helpers and tests.
3. Add `SourceControlProcess` and provider errors.
4. Add provider registry with GitHub-only registration.
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
## Acceptance Criteria
- Existing GitHub Commit + PR and PR checkout flows still work.
- `GitManager` no longer imports or depends on `GitHubCli`.
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
- Unknown/unsupported providers fail explicitly and visibly.
- GitHub command execution does not depend on `processRunner.ts`.
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
- Rate-limit responses become typed errors with retry/reset metadata where available.
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
+2
View File
@@ -10,3 +10,5 @@
8. `08-precommit-format-and-lint.md`
9. `09-event-state-test-expansion.md`
10. `10-unify-process-session-abstraction.md`
19. `19-version-control-phase-1-vcs-driver-foundation.md`
20. `20-version-control-phase-2-source-control-provider-foundation.md`
+5 -4
View File
@@ -1,15 +1,16 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
## Installation
> [!WARNING]
> T3 Code currently supports Codex and Claude.
> T3 Code currently supports Codex, Claude, and OpenCode.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
> - Claude: install Claude Code and run `claude auth login`
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
### Run without installing
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.21",
"version": "0.0.22",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -17,8 +17,9 @@
"dependencies": {
"@effect/platform-node": "catalog:",
"effect": "catalog:",
"electron": "40.6.0",
"electron-updater": "^6.6.2"
"electron": "40.9.3",
"electron-updater": "^6.6.2",
"jsonc-parser": "^3.3.1"
},
"devDependencies": {
"@t3tools/client-runtime": "workspace:*",
@@ -52,8 +52,11 @@ const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
@@ -61,6 +64,7 @@ const clientSettings: ClientSettings = {
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
themePreference: { mode: "system" },
};
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
+55 -7
View File
@@ -30,6 +30,7 @@ import type {
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
DesktopUpdateState,
DesktopWindowThemeColors,
} from "@t3tools/contracts";
import { autoUpdater } from "electron-updater";
@@ -84,12 +85,21 @@ import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runti
import { resolveDesktopAppBranding } from "./appBranding.ts";
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
import {
discoverEditorColorThemes,
getEditorThemePreferences,
loadEditorColorTheme,
} from "./vscodeThemeDiscovery.ts";
syncShellEnvironment();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const DISCOVER_COLOR_THEMES_CHANNEL = "desktop:discover-color-themes";
const LOAD_COLOR_THEME_CHANNEL = "desktop:load-color-theme";
const GET_EDITOR_THEME_PREFERENCES_CHANNEL = "desktop:get-editor-theme-preferences";
const SET_WINDOW_THEME_COLORS_CHANNEL = "desktop:set-window-theme-colors";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
@@ -118,14 +128,14 @@ const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
const CLIENT_SETTINGS_PATH = Path.join(STATE_DIR, "client-settings.json");
const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments.json");
const DESKTOP_SCHEME = "t3";
let windowThemeColors: DesktopWindowThemeColors | null = null;
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
// Dev-only SSH launcher override. Set this to an absolute path on the SSH host
// for a built server entry, for example:
// "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs"
const DEV_REMOTE_T3_SERVER_ENTRY_PATH =
process.env.T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH?.trim() ??
"/Users/julius/Developer/t3code/apps/server/dist/bin.mjs";
process.env.T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH?.trim() ?? "";
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
isDevelopment,
appVersion: app.getVersion(),
@@ -499,6 +509,20 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
return null;
}
function getSafeWindowThemeColors(rawInput: unknown): DesktopWindowThemeColors | null {
if (typeof rawInput !== "object" || rawInput === null || Array.isArray(rawInput)) return null;
const input = rawInput as Record<string, unknown>;
if (typeof input.backgroundColor !== "string" || input.backgroundColor.trim().length === 0) {
return null;
}
return {
backgroundColor: input.backgroundColor,
titleBarColor: typeof input.titleBarColor === "string" ? input.titleBarColor : undefined,
titleBarSymbolColor:
typeof input.titleBarSymbolColor === "string" ? input.titleBarSymbolColor : undefined,
};
}
async function waitForBackendHttpReady(
baseUrl: string,
options?: Parameters<typeof waitForHttpReady>[1],
@@ -1819,6 +1843,26 @@ function registerIpcHandlers(): void {
nativeTheme.themeSource = theme;
});
ipcMain.removeHandler(DISCOVER_COLOR_THEMES_CHANNEL);
ipcMain.handle(DISCOVER_COLOR_THEMES_CHANNEL, async () => discoverEditorColorThemes());
ipcMain.removeHandler(LOAD_COLOR_THEME_CHANNEL);
ipcMain.handle(LOAD_COLOR_THEME_CHANNEL, async (_event, rawThemeId: unknown) => {
if (typeof rawThemeId !== "string") return null;
return loadEditorColorTheme(rawThemeId);
});
ipcMain.removeHandler(GET_EDITOR_THEME_PREFERENCES_CHANNEL);
ipcMain.handle(GET_EDITOR_THEME_PREFERENCES_CHANNEL, async () => getEditorThemePreferences());
ipcMain.removeHandler(SET_WINDOW_THEME_COLORS_CHANNEL);
ipcMain.handle(SET_WINDOW_THEME_COLORS_CHANNEL, async (_event, rawInput: unknown) => {
const input = getSafeWindowThemeColors(rawInput);
if (!input) return;
windowThemeColors = input;
syncAllWindowAppearance();
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
@@ -1990,7 +2034,9 @@ function getIconOption(): { icon: string } | Record<string, never> {
}
function getInitialWindowBackgroundColor(): string {
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
return (
windowThemeColors?.backgroundColor ?? (nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff")
);
}
function getWindowTitleBarOptions(): WindowTitleBarOptions {
@@ -2004,11 +2050,13 @@ function getWindowTitleBarOptions(): WindowTitleBarOptions {
return {
titleBarStyle: "hidden",
titleBarOverlay: {
color: TITLEBAR_COLOR,
color: windowThemeColors?.titleBarColor ?? TITLEBAR_COLOR,
height: TITLEBAR_HEIGHT,
symbolColor: nativeTheme.shouldUseDarkColors
? TITLEBAR_DARK_SYMBOL_COLOR
: TITLEBAR_LIGHT_SYMBOL_COLOR,
symbolColor:
windowThemeColors?.titleBarSymbolColor ??
(nativeTheme.shouldUseDarkColors
? TITLEBAR_DARK_SYMBOL_COLOR
: TITLEBAR_LIGHT_SYMBOL_COLOR),
},
};
}
+29 -2
View File
@@ -4,6 +4,10 @@ import type { DesktopBridge } from "@t3tools/contracts";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const DISCOVER_COLOR_THEMES_CHANNEL = "desktop:discover-color-themes";
const LOAD_COLOR_THEME_CHANNEL = "desktop:load-color-theme";
const GET_EDITOR_THEME_PREFERENCES_CHANNEL = "desktop:get-editor-theme-preferences";
const SET_WINDOW_THEME_COLORS_CHANNEL = "desktop:set-window-theme-colors";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
@@ -35,6 +39,23 @@ const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
typeof result === "object" &&
result !== null &&
"type" in result &&
result.type === SSH_PASSWORD_PROMPT_CANCELLED_RESULT
) {
const message =
"message" in result && typeof result.message === "string"
? result.message
: "SSH authentication cancelled.";
throw new Error(message);
}
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
}
contextBridge.exposeInMainWorld("desktopBridge", {
getAppBranding: () => {
@@ -63,8 +84,10 @@ contextBridge.exposeInMainWorld("desktopBridge", {
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
discoverSshHosts: () => ipcRenderer.invoke(DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: (target, options) =>
ipcRenderer.invoke(ENSURE_SSH_ENVIRONMENT_CHANNEL, target, options),
ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult(
await ipcRenderer.invoke(ENSURE_SSH_ENVIRONMENT_CHANNEL, target, options),
),
disconnectSshEnvironment: (target) =>
ipcRenderer.invoke(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, target),
fetchSshEnvironmentDescriptor: (httpBaseUrl) =>
@@ -95,7 +118,11 @@ contextBridge.exposeInMainWorld("desktopBridge", {
getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL),
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
discoverColorThemes: () => ipcRenderer.invoke(DISCOVER_COLOR_THEMES_CHANNEL),
loadColorTheme: (themeId) => ipcRenderer.invoke(LOAD_COLOR_THEME_CHANNEL, themeId),
getEditorThemePreferences: () => ipcRenderer.invoke(GET_EDITOR_THEME_PREFERENCES_CHANNEL),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
setWindowThemeColors: (input) => ipcRenderer.invoke(SET_WINDOW_THEME_COLORS_CHANNEL, input),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => {
+2 -2
View File
@@ -171,7 +171,7 @@ describe("resolveDesktopCoreAdvertisedEndpoints", () => {
},
{
id: "manual:http://desktop.example.test:3773",
label: "Custom HTTPS",
label: "Custom endpoint",
provider: {
id: "manual",
label: "Manual",
@@ -187,7 +187,7 @@ describe("resolveDesktopCoreAdvertisedEndpoints", () => {
},
source: "user",
status: "unknown",
description: "User-configured HTTPS endpoint for this desktop backend.",
description: "User-configured endpoint for this desktop backend.",
},
]);
});
+6 -5
View File
@@ -165,17 +165,18 @@ export function resolveDesktopCoreAdvertisedEndpoints(
for (const customEndpointUrl of input.customHttpsEndpointUrls ?? []) {
try {
const isHttpsEndpoint = isHttpsEndpointUrl(customEndpointUrl);
endpoints.push(
createManualEndpoint({
id: `manual:${customEndpointUrl}`,
label: "Custom HTTPS",
label: isHttpsEndpoint ? "Custom HTTPS" : "Custom endpoint",
httpBaseUrl: customEndpointUrl,
reachability: "public",
...(isHttpsEndpointUrl(customEndpointUrl)
? ({ hostedHttpsCompatibility: "compatible" } as const)
: {}),
...(isHttpsEndpoint ? ({ hostedHttpsCompatibility: "compatible" } as const) : {}),
status: "unknown",
description: "User-configured HTTPS endpoint for this desktop backend.",
description: isHttpsEndpoint
? "User-configured HTTPS endpoint for this desktop backend."
: "User-configured endpoint for this desktop backend.",
}),
);
} catch {
+13 -1
View File
@@ -4,7 +4,9 @@ import * as Path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { discoverDesktopSshHosts } from "./sshEnvironment.ts";
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
import { discoverDesktopSshHosts, isSshPasswordPromptCancellation } from "./sshEnvironment.ts";
const tempDirectories: string[] = [];
@@ -21,6 +23,16 @@ function makeTempHomeDir(): string {
}
describe("sshEnvironment", () => {
it("treats password prompt timeouts as cancellable authentication prompts", () => {
expect(
isSshPasswordPromptCancellation(
new SshPasswordPromptError({
message: "SSH authentication timed out for devbox.",
}),
),
).toBe(true);
});
it("wires desktop host discovery through the ssh package runtime", async () => {
const homeDir = makeTempHomeDir();
const sshDir = Path.join(homeDir, ".ssh");
+48 -7
View File
@@ -38,6 +38,7 @@ const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
interface DesktopSshEnvironmentManagerOptions {
readonly passwordProvider?: (request: SshPasswordRequest) => Promise<string | null>;
@@ -202,6 +203,14 @@ interface PendingSshPasswordPrompt {
readonly timeout: ReturnType<typeof setTimeout>;
}
export function isSshPasswordPromptCancellation(error: unknown): error is SshPasswordPromptError {
const message = error instanceof SshPasswordPromptError ? error.message.toLowerCase() : "";
return (
error instanceof SshPasswordPromptError &&
(message.includes("cancelled") || message.includes("timed out"))
);
}
/**
* Wires the SSH environment manager to Electron IPC, owning the renderer-facing
* password prompt state so `main.ts` only needs to register, cancel, and dispose.
@@ -244,9 +253,19 @@ export class DesktopSshEnvironmentBridge {
"issuePairingToken" in rawOptions &&
(rawOptions as { issuePairingToken?: unknown }).issuePairingToken === true;
return await this.manager.ensureEnvironment(target, {
issuePairingToken,
});
try {
return await this.manager.ensureEnvironment(target, {
issuePairingToken,
});
} catch (error) {
if (isSshPasswordPromptCancellation(error)) {
return {
type: SSH_PASSWORD_PROMPT_CANCELLED_RESULT,
message: error.message,
};
}
throw error;
}
});
ipcMain.removeHandler(DISCONNECT_SSH_ENVIRONMENT_CHANNEL);
@@ -361,6 +380,11 @@ export class DesktopSshEnvironmentBridge {
};
return await new Promise<string | null>((resolve, reject) => {
const rejectPrompt = (error: Error) => {
clearTimeout(timeout);
this.pendingPrompts.delete(request.requestId);
reject(error);
};
const timeout = setTimeout(() => {
this.pendingPrompts.delete(request.requestId);
reject(new Error(`SSH authentication timed out for ${input.destination}.`));
@@ -369,11 +393,28 @@ export class DesktopSshEnvironmentBridge {
this.pendingPrompts.set(request.requestId, { resolve, reject, timeout });
window.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, request);
if (window.isMinimized()) {
window.restore();
try {
if (window.isDestroyed()) {
throw new Error("T3 Code window is not available for SSH authentication.");
}
window.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, request);
if (window.isDestroyed()) {
throw new Error("T3 Code window is not available for SSH authentication.");
}
if (window.isMinimized()) {
window.restore();
}
if (window.isDestroyed()) {
throw new Error("T3 Code window is not available for SSH authentication.");
}
window.focus();
} catch (error) {
rejectPrompt(
error instanceof Error
? error
: new Error("T3 Code window is not available for SSH authentication."),
);
}
window.focus();
});
}
}
@@ -1,10 +0,0 @@
#!/bin/sh
# Invoked by ssh via SSH_ASKPASS when T3 Code re-runs ssh with a cached password
# from the renderer's in-app prompt. We never expose a native dialog here — if
# T3_SSH_AUTH_SECRET is missing, that's a caller bug and we fail loudly.
if [ "${T3_SSH_AUTH_SECRET+x}" = "x" ]; then
printf "%s\n" "$T3_SSH_AUTH_SECRET"
exit 0
fi
printf 'T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.\n' >&2
exit 1
@@ -1,2 +0,0 @@
@echo off
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0ssh-askpass.ps1" %*
@@ -1,10 +0,0 @@
# Invoked by ssh via SSH_ASKPASS (through ssh-askpass.cmd) when T3 Code re-runs
# ssh with a cached password from the renderer's in-app prompt. We never expose
# a native dialog here — if T3_SSH_AUTH_SECRET is missing, that's a caller bug
# and we fail loudly.
if ($null -ne $env:T3_SSH_AUTH_SECRET) {
[Console]::Out.WriteLine($env:T3_SSH_AUTH_SECRET)
exit 0
}
[Console]::Error.WriteLine("T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.")
exit 1
@@ -1,34 +0,0 @@
set -eu
STATE_KEY="$1"
STATE_DIR="$HOME/.t3/ssh-launch/$STATE_KEY"
SERVER_HOME="$STATE_DIR/server-home"
PORT_FILE="$STATE_DIR/port"
PID_FILE="$STATE_DIR/pid"
LOG_FILE="$STATE_DIR/server.log"
RUNNER_FILE="$STATE_DIR/run-t3.sh"
mkdir -p "$STATE_DIR" "$SERVER_HOME"
cat >"$RUNNER_FILE" <<'SH'
@@T3_RUNNER_SCRIPT@@
SH
chmod 700 "$RUNNER_FILE"
pick_port() {
node - "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@" <<'NODE'
@@T3_PICK_PORT_SCRIPT@@
NODE
}
REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
REMOTE_PORT="$(cat "$PORT_FILE" 2>/dev/null || true)"
if [ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then
:
else
REMOTE_PORT="$(pick_port)" || true
if [ -z "$REMOTE_PORT" ]; then
printf 'Failed to find an available port on the remote host. Ensure node is available on PATH.\n' >&2
exit 1
fi
nohup env T3CODE_NO_BROWSER=1 "$RUNNER_FILE" serve --host 127.0.0.1 --port "$REMOTE_PORT" --base-dir "$SERVER_HOME" >>"$LOG_FILE" 2>&1 < /dev/null &
REMOTE_PID="$!"
printf '%s\n' "$REMOTE_PID" >"$PID_FILE"
printf '%s\n' "$REMOTE_PORT" >"$PORT_FILE"
fi
printf '{"remotePort":%s}\n' "$REMOTE_PORT"
@@ -1,10 +0,0 @@
set -eu
STATE_DIR="$HOME/.t3/ssh-launch/@@T3_STATE_KEY@@"
SERVER_HOME="$STATE_DIR/server-home"
RUNNER_FILE="$STATE_DIR/run-t3.sh"
mkdir -p "$STATE_DIR" "$SERVER_HOME"
cat >"$RUNNER_FILE" <<'SH'
@@T3_RUNNER_SCRIPT@@
SH
chmod 700 "$RUNNER_FILE"
"$RUNNER_FILE" auth pairing create --base-dir "$SERVER_HOME" --json
@@ -1,31 +0,0 @@
const fs = require("node:fs");
const net = require("node:net");
const filePath = process.argv[2] ?? "";
const defaultPort = Number.parseInt(process.argv[3] ?? "", 10);
const scanWindow = Number.parseInt(process.argv[4] ?? "", 10);
const raw = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8").trim() : "";
const preferred = Number.parseInt(raw, 10);
const start = Number.isInteger(preferred) ? preferred : defaultPort;
const end = start + scanWindow;
function tryPort(port) {
return new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.once("error", () => resolve(false));
server.listen(port, "127.0.0.1", () => {
server.close((error) => resolve(error ? false : port));
});
});
}
(async () => {
for (let port = start; port < end; port += 1) {
const available = await tryPort(port);
if (available) {
process.stdout.write(String(port));
return;
}
}
process.exit(1);
})().catch(() => process.exit(1));
@@ -1,13 +0,0 @@
#!/bin/sh
set -eu
if command -v t3 >/dev/null 2>&1; then
exec t3 "$@"
fi
if command -v npx >/dev/null 2>&1; then
exec npx --yes @@T3_PACKAGE_SPEC@@ "$@"
fi
if command -v npm >/dev/null 2>&1; then
exec npm exec --yes @@T3_PACKAGE_SPEC@@ -- "$@"
fi
printf 'Remote host is missing the t3 CLI and could not install @@T3_PACKAGE_SPEC@@ because npx and npm are unavailable on PATH.\n' >&2
exit 1
@@ -0,0 +1,104 @@
import * as FS from "node:fs";
import * as OS from "node:os";
import * as Path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
discoverEditorColorThemes,
getEditorThemePreferences,
loadEditorColorTheme,
resolveEditorRoots,
} from "./vscodeThemeDiscovery.ts";
let tempDir = "";
function writeJson(filePath: string, value: unknown) {
FS.mkdirSync(Path.dirname(filePath), { recursive: true });
FS.writeFileSync(filePath, JSON.stringify(value, null, 2));
}
describe("vscodeThemeDiscovery", () => {
beforeEach(() => {
tempDir = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-vscode-themes-"));
});
afterEach(() => {
FS.rmSync(tempDir, { recursive: true, force: true });
});
it("discovers contributed themes and ignores unsafe paths", () => {
const roots = resolveEditorRoots({ platform: "darwin", homedir: tempDir });
const vscodeRoot = roots.find((root) => root.source === "vscode");
expect(vscodeRoot).toBeDefined();
if (!vscodeRoot) return;
const extensionDir = Path.join(vscodeRoot.extensionsPath, "github.github-vscode-theme");
writeJson(Path.join(extensionDir, "package.json"), {
publisher: "GitHub",
displayName: "GitHub Theme",
contributes: {
themes: [
{ label: "GitHub Dark Default", uiTheme: "vs-dark", path: "./themes/dark.json" },
{ label: "Escaped", uiTheme: "vs", path: "../escaped.json" },
],
},
});
writeJson(Path.join(extensionDir, "themes", "dark.json"), {
colors: { "editor.background": "#0d1117" },
});
expect(discoverEditorColorThemes(roots)).toMatchObject([
{
source: "vscode",
label: "GitHub Dark Default",
kind: "dark",
publisher: "GitHub",
},
]);
});
it("loads JSONC settings overrides into the resolved app theme", () => {
const roots = resolveEditorRoots({ platform: "darwin", homedir: tempDir });
const vscodeRoot = roots.find((root) => root.source === "vscode");
expect(vscodeRoot).toBeDefined();
if (!vscodeRoot) return;
const extensionDir = Path.join(vscodeRoot.extensionsPath, "github.github-vscode-theme");
writeJson(Path.join(extensionDir, "package.json"), {
contributes: {
themes: [{ label: "GitHub Dark Default", uiTheme: "vs-dark", path: "./themes/dark.json" }],
},
});
writeJson(Path.join(extensionDir, "themes", "dark.json"), {
semanticHighlighting: true,
colors: {
"editor.background": "#0d1117",
"editor.foreground": "#e6edf3",
},
tokenColors: [],
});
FS.mkdirSync(Path.dirname(vscodeRoot.settingsPath), { recursive: true });
FS.writeFileSync(
vscodeRoot.settingsPath,
`{
"workbench.colorTheme": "GitHub Dark Default",
"workbench.colorCustomizations": {
"button.background": "#238636",
"[GitHub Dark Default]": {
"sideBar.background": "#010409"
}
}
}`,
);
const preferences = getEditorThemePreferences(roots);
expect(preferences[0]?.colorTheme).toBe("GitHub Dark Default");
const themeId = discoverEditorColorThemes(roots)[0]?.id;
expect(themeId).toBeTruthy();
const resolved = themeId ? loadEditorColorTheme(themeId, roots) : null;
expect(resolved?.colors["button.background"]).toBe("#238636");
expect(resolved?.colors["sideBar.background"]).toBe("#010409");
expect(resolved?.appVariables["--primary"]).toBe("#238636");
});
});
+284
View File
@@ -0,0 +1,284 @@
import * as FS from "node:fs";
import * as OS from "node:os";
import * as Path from "node:path";
import { parse as parseJsonc } from "jsonc-parser";
import type {
DiscoveredColorTheme,
EditorThemePreference,
EditorThemeSource,
ResolvedColorTheme,
ThemeKind,
} from "@t3tools/contracts";
import {
mapVscodeColorsToAppVariables,
normalizeCssColor,
normalizeThemeColors,
} from "@t3tools/shared/themeMapping";
interface EditorRoot {
readonly source: EditorThemeSource;
readonly extensionsPath: string;
readonly settingsPath: string;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function kindFromUiTheme(uiTheme: unknown): ThemeKind {
if (uiTheme === "hc-light") return "high-contrast-light";
if (uiTheme === "hc-black") return "high-contrast-dark";
if (uiTheme === "vs") return "light";
return "dark";
}
function readJsonOrJsoncFile(filePath: string): unknown | null {
try {
return parseJsonc(FS.readFileSync(filePath, "utf8"));
} catch {
return null;
}
}
function safeResolveChild(root: string, relativePath: string): string | null {
const resolved = Path.resolve(root, relativePath);
const normalizedRoot = Path.resolve(root);
if (resolved === normalizedRoot || resolved.startsWith(`${normalizedRoot}${Path.sep}`)) {
return resolved;
}
return null;
}
export function resolveEditorRoots(input: {
readonly platform: NodeJS.Platform;
readonly homedir: string;
readonly appData?: string;
}): readonly EditorRoot[] {
const home = input.homedir;
if (input.platform === "win32") {
const appData = input.appData ?? Path.join(home, "AppData", "Roaming");
return [
{
source: "vscode",
extensionsPath: Path.join(home, ".vscode", "extensions"),
settingsPath: Path.join(appData, "Code", "User", "settings.json"),
},
{
source: "vscode-insiders",
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
settingsPath: Path.join(appData, "Code - Insiders", "User", "settings.json"),
},
{
source: "cursor",
extensionsPath: Path.join(home, ".cursor", "extensions"),
settingsPath: Path.join(appData, "Cursor", "User", "settings.json"),
},
];
}
if (input.platform === "darwin") {
return [
{
source: "vscode",
extensionsPath: Path.join(home, ".vscode", "extensions"),
settingsPath: Path.join(
home,
"Library",
"Application Support",
"Code",
"User",
"settings.json",
),
},
{
source: "vscode-insiders",
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
settingsPath: Path.join(
home,
"Library",
"Application Support",
"Code - Insiders",
"User",
"settings.json",
),
},
{
source: "cursor",
extensionsPath: Path.join(home, ".cursor", "extensions"),
settingsPath: Path.join(
home,
"Library",
"Application Support",
"Cursor",
"User",
"settings.json",
),
},
];
}
return [
{
source: "vscode",
extensionsPath: Path.join(home, ".vscode", "extensions"),
settingsPath: Path.join(home, ".config", "Code", "User", "settings.json"),
},
{
source: "vscode-insiders",
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
settingsPath: Path.join(home, ".config", "Code - Insiders", "User", "settings.json"),
},
{
source: "cursor",
extensionsPath: Path.join(home, ".cursor", "extensions"),
settingsPath: Path.join(home, ".config", "Cursor", "User", "settings.json"),
},
];
}
function resolveDefaultEditorRoots() {
const input: { platform: NodeJS.Platform; homedir: string; appData?: string } = {
platform: process.platform,
homedir: OS.homedir(),
};
if (process.env.APPDATA) input.appData = process.env.APPDATA;
return resolveEditorRoots(input);
}
function readEditorSettings(settingsPath: string): Record<string, unknown> {
const parsed = readJsonOrJsoncFile(settingsPath);
return isObject(parsed) ? parsed : {};
}
export function getEditorThemePreferences(
roots = resolveDefaultEditorRoots(),
): readonly EditorThemePreference[] {
return roots.map((root) => {
const settings = readEditorSettings(root.settingsPath);
const customizations = settings["workbench.colorCustomizations"];
return {
source: root.source,
colorTheme:
typeof settings["workbench.colorTheme"] === "string"
? settings["workbench.colorTheme"]
: null,
preferredLightColorTheme:
typeof settings["workbench.preferredLightColorTheme"] === "string"
? settings["workbench.preferredLightColorTheme"]
: null,
preferredDarkColorTheme:
typeof settings["workbench.preferredDarkColorTheme"] === "string"
? settings["workbench.preferredDarkColorTheme"]
: null,
autoDetectColorScheme: settings["window.autoDetectColorScheme"] === true,
workbenchColorCustomizations: isObject(customizations) ? customizations : {},
editorTokenColorCustomizations: settings["editor.tokenColorCustomizations"],
};
});
}
export function discoverEditorColorThemes(
roots = resolveDefaultEditorRoots(),
): readonly DiscoveredColorTheme[] {
const themes: DiscoveredColorTheme[] = [];
for (const root of roots) {
if (!FS.existsSync(root.extensionsPath)) continue;
for (const entry of FS.readdirSync(root.extensionsPath, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const extensionDir = Path.join(root.extensionsPath, entry.name);
const packagePath = Path.join(extensionDir, "package.json");
const packageJson = readJsonOrJsoncFile(packagePath);
if (!isObject(packageJson)) continue;
const contributes = packageJson.contributes;
const contributedThemes = isObject(contributes) ? contributes.themes : null;
if (!Array.isArray(contributedThemes)) continue;
for (const theme of contributedThemes) {
if (!isObject(theme) || typeof theme.label !== "string" || typeof theme.path !== "string") {
continue;
}
const themePath = safeResolveChild(extensionDir, theme.path);
if (!themePath || !FS.existsSync(themePath)) continue;
themes.push({
id: `${root.source}:${entry.name}:${theme.label}`,
source: root.source,
extensionId: entry.name,
extensionDisplayName:
typeof packageJson.displayName === "string" ? packageJson.displayName : undefined,
label: theme.label,
kind: kindFromUiTheme(theme.uiTheme),
themePath,
packagePath,
publisher: typeof packageJson.publisher === "string" ? packageJson.publisher : undefined,
});
}
}
}
return themes.toSorted((a, b) => a.label.localeCompare(b.label));
}
function mergeWorkbenchOverrides(input: {
readonly themeLabel: string;
readonly themeColors: Record<string, string>;
readonly customizations: Record<string, unknown>;
}) {
const next = { ...input.themeColors };
for (const [key, rawValue] of Object.entries(input.customizations)) {
if (key.startsWith("[") && key.endsWith("]")) continue;
const color = normalizeCssColor(rawValue);
if (color) next[key] = color;
}
const scoped = input.customizations[`[${input.themeLabel}]`];
if (isObject(scoped)) {
for (const [key, rawValue] of Object.entries(scoped)) {
const color = normalizeCssColor(rawValue);
if (color) next[key] = color;
}
}
return next;
}
export function loadEditorColorTheme(
themeId: string,
roots = resolveDefaultEditorRoots(),
): ResolvedColorTheme | null {
const themes = discoverEditorColorThemes(roots);
const theme = themes.find((entry) => entry.id === themeId);
if (!theme) return null;
const rawTheme = readJsonOrJsoncFile(theme.themePath);
if (!isObject(rawTheme)) return null;
const preferences = getEditorThemePreferences(roots);
const preference = preferences.find((entry) => entry.source === theme.source);
const colors = mergeWorkbenchOverrides({
themeLabel: theme.label,
themeColors: normalizeThemeColors(rawTheme.colors),
customizations: preference?.workbenchColorCustomizations ?? {},
});
return {
id: theme.id,
label: theme.label,
source: theme.source,
kind: theme.kind,
colors,
tokenColors: rawTheme.tokenColors ?? [],
semanticHighlighting:
typeof rawTheme.semanticHighlighting === "boolean"
? rawTheme.semanticHighlighting
: undefined,
semanticTokenColors: rawTheme.semanticTokenColors,
appVariables: mapVscodeColorsToAppVariables({ kind: theme.kind, colors }),
};
}
-1
View File
@@ -13,7 +13,6 @@ export default defineConfig([
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
copy: [{ from: "src/sshScripts/*", to: "dist-electron/sshScripts" }],
},
{
...shared,
@@ -3,7 +3,8 @@ import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
ProviderKind,
CodexSettings,
ProviderDriverKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
@@ -24,10 +25,7 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
@@ -36,13 +34,16 @@ import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/
import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
@@ -73,6 +74,11 @@ import {
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -214,7 +220,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: ProviderDriverKind;
readonly realCodex?: boolean;
}
@@ -225,7 +231,7 @@ export const makeOrchestrationIntegrationHarness = (
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const provider = options?.provider ?? "codex";
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const useRealCodex = options?.realCodex === true;
const adapterHarness = useRealCodex
? null
@@ -233,13 +239,10 @@ export const makeOrchestrationIntegrationHarness = (
provider,
});
const fakeRegistry = adapterHarness
? Layer.succeed(ProviderAdapterRegistry, {
getByProvider: (resolvedProvider) =>
resolvedProvider === adapterHarness.provider
? Effect.succeed(adapterHarness.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
listProviders: () => Effect.succeed([adapterHarness.provider]),
} as typeof ProviderAdapterRegistry.Service)
? Layer.succeed(
ProviderAdapterRegistry,
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
)
: null;
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-orchestration-integration-",
@@ -264,34 +267,33 @@ export const makeOrchestrationIntegrationHarness = (
const realCodexRegistry = Layer.effect(
ProviderAdapterRegistry,
Effect.gen(function* () {
const codexAdapter = yield* CodexAdapter;
return {
getByProvider: (resolvedProvider) =>
resolvedProvider === "codex"
? Effect.succeed(codexAdapter)
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
listProviders: () => Effect.succeed(["codex"] as const),
} as typeof ProviderAdapterRegistry.Service;
const codexSettings = Schema.decodeSync(CodexSettings)({});
const codexAdapter = yield* makeCodexAdapter(codexSettings);
return makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: codexAdapter,
});
}),
).pipe(
Layer.provide(makeCodexAdapterLive()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);
const providerLayer = useRealCodex
? makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(realCodexRegistry),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
)
: makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(fakeRegistry!),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
const runtimeServicesLayer = Layer.mergeAll(
projectionSnapshotQueryLayer,
@@ -307,31 +309,31 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(serverSettingsLayer),
);
const gitCoreLayer = Layer.succeed(GitCore, {
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
Effect.succeed({ branch: input.newBranch }),
} as unknown as GitCoreShape);
});
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: "update" }),
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
} as unknown as TextGenerationShape);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(gitWorkflowLayer),
Layer.provideMerge(textGenerationLayer),
Layer.provideMerge(serverSettingsLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(
Layer.succeed(GitStatusBroadcaster, {
Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: true,
branch: "main",
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -342,11 +344,12 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(VcsDriverRegistry.layer),
Layer.provide(NodeServices.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(VcsProcess.layer),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
@@ -10,7 +10,7 @@ import {
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderKind,
ProviderDriverKind,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
@@ -36,7 +36,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: ProviderDriverKind;
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: ProviderKind;
readonly provider: ProviderDriverKind;
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: ProviderDriverKind;
}
function nowIso(): string {
@@ -206,7 +206,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: ProviderKind,
provider: ProviderDriverKind,
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +216,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: ProviderKind,
provider: ProviderDriverKind,
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -224,7 +224,7 @@ function missingSessionEffect(
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
Effect.gen(function* () {
const provider = options?.provider ?? "codex";
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 0;
const sessions = new Map<ThreadId, SessionState>();
@@ -257,6 +257,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
const session: ProviderSession = {
provider,
...(input.providerInstanceId !== undefined
? { providerInstanceId: input.providerInstanceId }
: {}),
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
@@ -1,7 +1,7 @@
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts";
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
const PROVIDER = "codex" as const;
const PROVIDER = ProviderDriverKind.make("codex");
const SESSION_ID = "fixture-session";
const THREAD_ID = "fixture-thread";
const TURN_ID = "fixture-turn";
@@ -4,14 +4,17 @@ import path from "node:path";
import {
ApprovalRequestId,
CommandId,
defaultInstanceIdForDriver,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_MODEL,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ProviderKind,
ProviderDriverKind,
ThreadId,
ModelSelection,
ProviderInstanceId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Option, Schema } from "effect";
@@ -39,7 +42,9 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.make("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = ProviderKind;
type IntegrationProvider = ProviderDriverKind;
const CODEX_PROVIDER = ProviderDriverKind.make("codex");
const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent");
function nowIso() {
return new Date().toISOString();
@@ -74,7 +79,11 @@ function waitForSync<A>(
});
}
function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {
function runtimeBase(
eventId: string,
createdAt: string,
provider: IntegrationProvider = CODEX_PROVIDER,
) {
return {
eventId: asEventId(eventId),
provider,
@@ -84,7 +93,7 @@ function runtimeBase(eventId: string, createdAt: string, provider: IntegrationPr
function withHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
provider: IntegrationProvider = "codex",
provider: IntegrationProvider = CODEX_PROVIDER,
) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness({ provider }),
@@ -97,7 +106,7 @@ function withRealCodexHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
makeOrchestrationIntegrationHarness({ provider: CODEX_PROVIDER, realCodex: true }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
@@ -106,8 +115,9 @@ function withRealCodexHarness<A, E>(
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
const provider = harness.adapterHarness?.provider ?? "codex";
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
const provider = harness.adapterHarness?.provider ?? CODEX_PROVIDER;
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;
const instanceId = defaultInstanceIdForDriver(provider);
yield* harness.engine.dispatch({
type: "project.create",
@@ -116,7 +126,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider,
instanceId,
model: defaultModel,
},
createdAt,
@@ -129,7 +139,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider,
instanceId,
model: defaultModel,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -265,7 +275,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.3-codex",
},
createdAt,
@@ -278,7 +288,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.3-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -496,6 +506,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
fallbackFromToHead: false,
ignoreWhitespace: false,
});
assert.equal(incrementalDiff.includes("README.md"), true);
@@ -504,6 +515,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
fallbackFromToHead: false,
ignoreWhitespace: false,
});
assert.equal(fullDiff.includes("README.md"), true);
@@ -912,20 +924,32 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-start-1",
"2026-02-24T10:10:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-start-2",
"2026-02-24T10:10:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Claude first turn.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-start-3",
"2026-02-24T10:10:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -939,7 +963,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
messageId: "msg-user-claude-initial",
text: "Use Claude",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
@@ -955,7 +979,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
);
assert.equal(thread.session?.providerName, "claudeAgent");
}),
"claudeAgent",
CLAUDE_AGENT_PROVIDER,
),
);
@@ -969,20 +993,32 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-1",
"2026-02-24T10:11:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-2",
"2026-02-24T10:11:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn before restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-3",
"2026-02-24T10:11:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -996,7 +1032,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
messageId: "msg-user-claude-recover-1",
text: "Before restart",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
@@ -1018,20 +1054,32 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-4",
"2026-02-24T10:11:01.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-5",
"2026-02-24T10:11:01.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn after restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-6",
"2026-02-24T10:11:01.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1063,7 +1111,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeAgent",
CLAUDE_AGENT_PROVIDER,
),
);
@@ -1077,13 +1125,21 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-approval-1",
"2026-02-24T10:12:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-approval-2",
"2026-02-24T10:12:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
@@ -1092,7 +1148,11 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
},
{
type: "turn.completed",
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-approval-3",
"2026-02-24T10:12:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1106,7 +1166,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
messageId: "msg-user-claude-approval",
text: "Need approval",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
@@ -1137,7 +1197,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
"claudeAgent",
CLAUDE_AGENT_PROVIDER,
),
);
@@ -1151,20 +1211,32 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-interrupt-1",
"2026-02-24T10:13:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-interrupt-2",
"2026-02-24T10:13:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Long running output.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-interrupt-3",
"2026-02-24T10:13:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1178,7 +1250,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
@@ -1206,7 +1278,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
);
assert.equal(interruptCalls.length, 1);
}),
"claudeAgent",
CLAUDE_AGENT_PROVIDER,
),
);
@@ -1220,20 +1292,32 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-1",
"2026-02-24T10:14:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-2",
"2026-02-24T10:14:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-3",
"2026-02-24T10:14:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1251,7 +1335,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
@@ -1266,20 +1350,32 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-4",
"2026-02-24T10:14:01.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-5",
"2026-02-24T10:14:01.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-6",
"2026-02-24T10:14:01.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1330,6 +1426,6 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeAgent",
CLAUDE_AGENT_PROVIDER,
),
);
@@ -1,13 +1,17 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import {
ProviderService,
@@ -29,6 +33,8 @@ import {
codexTurnTextFixture,
} from "./fixtures/providerRuntime.ts";
const codexInstanceId = ProviderInstanceId.make("codex");
const makeWorkspaceDirectory = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
@@ -47,13 +53,9 @@ const makeIntegrationFixture = Effect.gen(function* () {
const cwd = yield* makeWorkspaceDirectory;
const harness = yield* makeTestProviderAdapterHarness();
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(harness.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const registry = makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: harness.adapter,
});
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
@@ -64,6 +66,7 @@ const makeIntegrationFixture = Effect.gen(function* () {
Layer.succeed(ProviderAdapterRegistry, registry),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
AnalyticsService.layerTest,
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
@@ -124,7 +127,8 @@ it.live("replays typed runtime fixture events", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
threadId: ThreadId.make("thread-integration-typed"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -142,6 +146,10 @@ it.live("replays typed runtime fixture events", () =>
observedEvents.map((event) => event.type),
codexTurnTextFixture.map((event) => event.type),
);
assert.deepEqual(
observedEvents.map((event) => event.providerInstanceId),
codexTurnTextFixture.map(() => codexInstanceId),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
@@ -156,7 +164,8 @@ it.live("replays file-changing fixture turn events", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
threadId: ThreadId.make("thread-integration-tools"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -192,7 +201,8 @@ it.live("runs multi-turn tool/approval flow", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
threadId: ThreadId.make("thread-integration-multi"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -243,7 +253,8 @@ it.live("rolls back provider conversation state only", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
threadId: ThreadId.make("thread-integration-rollback"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.21",
"version": "0.0.22",
"license": "MIT",
"repository": {
"type": "git",
@@ -19,7 +19,6 @@
"build": "node scripts/cli.ts build",
"build:bundle": "tsdown",
"start": "node dist/bin.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
@@ -30,7 +29,7 @@
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@opencode-ai/sdk": "^1.3.15",
"@pierre/diffs": "^1.1.0-beta.16",
"@pierre/diffs": "catalog:",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0"
@@ -15,9 +15,8 @@ import * as CliError from "effect/unstable/cli/CliError";
import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/unstable/cli";
import { cli } from "./cli.ts";
import { cli } from "./bin.ts";
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
import {
@@ -149,7 +148,7 @@ const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Ef
);
});
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
it.layer(NodeServices.layer)("bin cli parsing", (it) => {
it.effect("accepts the built-in lowercase log-level flag values", () =>
runCliWithRuntime(["--log-level", "debug", "--version"]),
);
@@ -316,8 +315,8 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
"--base-dir",
baseDir,
]);
const orchestrationEngine = yield* OrchestrationEngineService;
const readModel = yield* orchestrationEngine.getReadModel();
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const readModel = yield* projectionSnapshotQuery.getSnapshot();
const addedProject = readModel.projects.find(
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
);
+16 -5
View File
@@ -5,13 +5,24 @@ import * as Layer from "effect/Layer";
import { Command } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
import { cli } from "./cli.ts";
import packageJson from "../package.json" with { type: "json" };
import { authCommand } from "./cli/auth.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
Command.run(cli, { version: packageJson.version }).pipe(
Effect.scoped,
Effect.provide(CliRuntimeLayer),
NodeRuntime.runMain,
export const cli = Command.make("t3", { ...sharedServerCommandFlags }).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((flags) => runServerCommand(flags)),
Command.withSubcommands([startCommand, serveCommand, authCommand, projectCommand]),
);
if (import.meta.main) {
Command.run(cli, { version: packageJson.version }).pipe(
Effect.scoped,
Effect.provide(CliRuntimeLayer),
NodeRuntime.runMain,
);
}
+2 -5
View File
@@ -1,6 +1,6 @@
import { Schema } from "effect";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import type { VcsError } from "@t3tools/contracts";
/**
* CheckpointUnavailableError - Expected checkpoint does not exist.
@@ -35,9 +35,6 @@ export class CheckpointInvariantError extends Schema.TaggedErrorClass<Checkpoint
}
}
export type CheckpointStoreError =
| GitCommandError
| CheckpointInvariantError
| CheckpointUnavailableError;
export type CheckpointStoreError = VcsError | CheckpointInvariantError | CheckpointUnavailableError;
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
@@ -48,6 +48,7 @@ describe("CheckpointDiffQueryLive", () => {
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly cwd: string;
readonly ignoreWhitespace: boolean;
}> = [];
const threadCheckpointContext = makeThreadCheckpointContext({
@@ -68,9 +69,14 @@ describe("CheckpointDiffQueryLive", () => {
return true;
}),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) =>
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd });
diffCheckpointsCalls.push({
fromCheckpointRef,
toCheckpointRef,
cwd,
ignoreWhitespace,
});
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
@@ -80,10 +86,13 @@ describe("CheckpointDiffQueryLive", () => {
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
@@ -102,6 +111,7 @@ describe("CheckpointDiffQueryLive", () => {
threadId,
fromTurnCount: 0,
toTurnCount: 1,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer)),
);
@@ -113,6 +123,7 @@ describe("CheckpointDiffQueryLive", () => {
cwd: "/tmp/workspace",
fromCheckpointRef: expectedFromRef,
toCheckpointRef,
ignoreWhitespace: true,
},
]);
expect(result).toEqual({
@@ -123,6 +134,70 @@ describe("CheckpointDiffQueryLive", () => {
});
});
it("defaults to hide whitespace changes", async () => {
const projectId = ProjectId.make("project-default-whitespace");
const threadId = ThreadId.make("thread-default-whitespace");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = [];
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ ignoreWhitespace }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({ ignoreWhitespace });
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
),
);
await Effect.runPromise(
Effect.gen(function* () {
const query = yield* CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
}).pipe(Effect.provide(layer)),
);
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
});
it("fails when the thread is missing from the snapshot", async () => {
const threadId = ThreadId.make("thread-missing");
@@ -139,10 +214,13 @@ describe("CheckpointDiffQueryLive", () => {
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
@@ -24,6 +24,7 @@ const make = Effect.gen(function* () {
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
function* (input) {
const operation = "CheckpointDiffQuery.getTurnDiff";
const ignoreWhitespace = input.ignoreWhitespace ?? true;
if (input.fromTurnCount === input.toTurnCount) {
const emptyDiff: OrchestrationGetTurnDiffResultType = {
@@ -131,6 +132,7 @@ const make = Effect.gen(function* () {
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
});
const turnDiff: OrchestrationGetTurnDiffResultType = {
@@ -157,6 +159,7 @@ const make = Effect.gen(function* () {
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
ignoreWhitespace: input.ignoreWhitespace ?? true,
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
return {
@@ -8,24 +8,27 @@ import { describe, expect } from "vitest";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStoreLive } from "./CheckpointStore.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitCommandError } from "@t3tools/contracts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import type { VcsError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { ThreadId } from "@t3tools/contracts";
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-store-test-",
});
const GitCoreTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfigLayer),
Layer.provide(NodeServices.layer),
);
const VcsProcessTestLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
const VcsDriverTestLayer = VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcessTestLayer));
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
Layer.provide(GitCoreTestLayer),
Layer.provide(NodeServices.layer),
Layer.provideMerge(VcsDriverTestLayer),
Layer.provideMerge(NodeServices.layer),
);
const TestLayer = CheckpointStoreTestLayer.pipe(
Layer.provideMerge(VcsProcessTestLayer),
Layer.provideMerge(VcsDriverTestLayer),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
function makeTmpDir(
prefix = "checkpoint-store-test-",
@@ -49,11 +52,12 @@ function writeTextFile(
function git(
cwd: string,
args: ReadonlyArray<string>,
): Effect.Effect<string, GitCommandError, GitCore> {
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
const result = yield* gitCore.execute({
const process = yield* VcsProcess.VcsProcess;
const result = yield* process.run({
operation: "CheckpointStore.test.git",
command: "git",
cwd,
args,
timeoutMs: 10_000,
@@ -66,12 +70,11 @@ function initRepoWithCommit(
cwd: string,
): Effect.Effect<
void,
GitCommandError | PlatformError.PlatformError,
GitCore | FileSystem.FileSystem
VcsError | PlatformError.PlatformError,
VcsProcess.VcsProcess | FileSystem.FileSystem
> {
return Effect.gen(function* () {
const core = yield* GitCore;
yield* core.initRepo({ cwd });
yield* git(cwd, ["init"]);
yield* git(cwd, ["config", "user.email", "[email protected]"]);
yield* git(cwd, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
@@ -111,6 +114,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
ignoreWhitespace: true,
});
expect(diff).toContain("diff --git");
@@ -118,5 +122,80 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
expect(diff).toContain("+line 04999");
}),
);
it.effect("can hide indentation churn when changes wrap existing lines", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore;
const threadId = ThreadId.make("thread-checkpoint-store-whitespace");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const componentPath = path.join(tmp, "Component.tsx");
yield* writeTextFile(
componentPath,
[
"export function View() {",
" return (",
" <section>",
" <h1>Title</h1>",
" <p>Body</p>",
" </section>",
" );",
"}",
"",
].join("\n"),
);
yield* checkpointStore.captureCheckpoint({
cwd: tmp,
checkpointRef: fromCheckpointRef,
});
yield* writeTextFile(
componentPath,
[
"export function View() {",
" return (",
" <section>",
" {isReady ? (",
" <div>",
" <h1>Title</h1>",
" <p>Body</p>",
" </div>",
" ) : null}",
" </section>",
" );",
"}",
"",
].join("\n"),
);
yield* checkpointStore.captureCheckpoint({
cwd: tmp,
checkpointRef: toCheckpointRef,
});
const normalDiff = yield* checkpointStore.diffCheckpoints({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
ignoreWhitespace: false,
});
const whitespaceIgnoredDiff = yield* checkpointStore.diffCheckpoints({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
ignoreWhitespace: true,
});
expect(normalDiff).toContain("diff --git");
expect(normalDiff).toContain("- <h1>Title</h1>");
expect(normalDiff).toContain("+ <h1>Title</h1>");
expect(whitespaceIgnoredDiff).toContain("diff --git");
expect(whitespaceIgnoredDiff).toContain("+ {isReady ? (");
expect(whitespaceIgnoredDiff).toContain("+ <div>");
expect(whitespaceIgnoredDiff).not.toContain("- <h1>Title</h1>");
expect(whitespaceIgnoredDiff).not.toContain("+ <h1>Title</h1>");
}),
);
});
});
@@ -14,8 +14,8 @@ import { randomUUID } from "node:crypto";
import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { VcsProcessExitError } from "@t3tools/contracts";
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
@@ -24,10 +24,26 @@ const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const git = yield* GitCore;
const vcsRegistry = yield* VcsDriverRegistry;
const vcs = {
execute: (input: {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
}) =>
vcsRegistry
.resolve({ cwd: input.cwd, requestedKind: "git" })
.pipe(Effect.flatMap((handle) => handle.driver.execute(input))),
};
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
git
const resolveHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.resolveHeadCommit",
cwd,
@@ -36,7 +52,7 @@ const makeCheckpointStore = Effect.gen(function* () {
})
.pipe(
Effect.map((result) => {
if (result.code !== 0) {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
@@ -44,21 +60,18 @@ const makeCheckpointStore = Effect.gen(function* () {
}),
);
const hasHeadCommit = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
git
const hasHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.hasHeadCommit",
cwd,
args: ["rev-parse", "--verify", "HEAD"],
allowNonZeroExit: true,
})
.pipe(Effect.map((result) => result.code === 0));
.pipe(Effect.map((result) => result.exitCode === 0));
const resolveCheckpointCommit = (
cwd: string,
checkpointRef: CheckpointRef,
): Effect.Effect<string | null, GitCommandError> =>
git
const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
vcs
.execute({
operation: "CheckpointStore.resolveCheckpointCommit",
cwd,
@@ -67,7 +80,7 @@ const makeCheckpointStore = Effect.gen(function* () {
})
.pipe(
Effect.map((result) => {
if (result.code !== 0) {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
@@ -76,7 +89,7 @@ const makeCheckpointStore = Effect.gen(function* () {
);
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
git
vcs
.execute({
operation: "CheckpointStore.isGitRepository",
cwd,
@@ -84,7 +97,7 @@ const makeCheckpointStore = Effect.gen(function* () {
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"),
Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
Effect.catch(() => Effect.succeed(false)),
);
@@ -108,7 +121,7 @@ const makeCheckpointStore = Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
@@ -116,14 +129,14 @@ const makeCheckpointStore = Effect.gen(function* () {
});
}
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* git.execute({
const writeTreeResult = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
@@ -131,16 +144,17 @@ const makeCheckpointStore = Effect.gen(function* () {
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
return yield* new VcsProcessExitError({
operation,
command: "git write-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git write-tree returned an empty tree oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.execute({
const commitTreeResult = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
@@ -148,15 +162,16 @@ const makeCheckpointStore = Effect.gen(function* () {
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new GitCommandError({
return yield* new VcsProcessExitError({
operation,
command: "git commit-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
@@ -197,12 +212,12 @@ const makeCheckpointStore = Effect.gen(function* () {
return false;
}
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
@@ -210,7 +225,7 @@ const makeCheckpointStore = Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
@@ -235,18 +250,29 @@ const makeCheckpointStore = Effect.gen(function* () {
}
if (!fromCommitOid || !toCommitOid) {
return yield* new GitCommandError({
return yield* new VcsProcessExitError({
operation,
command: "git diff",
cwd: input.cwd,
exitCode: 1,
detail: "Checkpoint ref is unavailable for diff operation.",
});
}
const result = yield* git.execute({
const diffArgs = [
"diff",
"--patch",
"--minimal",
"--no-color",
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
fromCommitOid,
toCommitOid,
];
const result = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
args: diffArgs,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
@@ -262,7 +288,7 @@ const makeCheckpointStore = Effect.gen(function* () {
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
@@ -32,6 +32,7 @@ export interface DiffCheckpointsInput {
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly fallbackFromToHead?: boolean;
readonly ignoreWhitespace: boolean;
}
export interface DeleteCheckpointRefsInput {
File diff suppressed because it is too large. Load diff
+243
View File
@@ -0,0 +1,243 @@
import { AuthSessionId } from "@t3tools/contracts";
import { Console, Effect, Layer, Option, References } from "effect";
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";
import { AuthControlPlane } from "../auth/Services/AuthControlPlane.ts";
import type { AuthControlPlaneShape } from "../auth/Services/AuthControlPlane.ts";
import {
formatIssuedPairingCredential,
formatIssuedSession,
formatPairingCredentialList,
formatSessionList,
} from "../cliAuthFormat.ts";
import { ServerConfig } from "../config.ts";
import {
authLocationFlags,
type CliAuthLocationFlags,
DurationFromString,
resolveCliAuthConfig,
} from "./config.ts";
const runWithAuthControlPlane = <A, E>(
flags: CliAuthLocationFlags,
run: (authControlPlane: AuthControlPlaneShape) => Effect.Effect<A, E>,
options?: {
readonly quietLogs?: boolean;
},
) =>
Effect.gen(function* () {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveCliAuthConfig(flags, logLevel);
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
return yield* Effect.gen(function* () {
const authControlPlane = yield* AuthControlPlane;
return yield* run(authControlPlane);
}).pipe(
Effect.provide(
Layer.mergeAll(AuthControlPlaneRuntimeLive).pipe(
Layer.provide(Layer.succeed(ServerConfig, config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
),
),
);
});
const ttlFlag = Flag.string("ttl").pipe(
Flag.withSchema(DurationFromString),
Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."),
Flag.optional,
);
const jsonFlag = Flag.boolean("json").pipe(
Flag.withDescription("Emit JSON instead of human-readable output."),
Flag.withDefault(false),
);
const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe(
Flag.withDescription("Role for the issued bearer session."),
Flag.withDefault("owner"),
);
const labelFlag = Flag.string("label").pipe(
Flag.withDescription("Optional human-readable label."),
Flag.optional,
);
const subjectFlag = Flag.string("subject").pipe(
Flag.withDescription("Optional session subject."),
Flag.optional,
);
const baseUrlFlag = Flag.string("base-url").pipe(
Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."),
Flag.optional,
);
const tokenOnlyFlag = Flag.boolean("token-only").pipe(
Flag.withDescription("Print only the issued bearer token."),
Flag.withDefault(false),
);
const pairingCreateCommand = Command.make("create", {
...authLocationFlags,
ttl: ttlFlag,
label: labelFlag,
baseUrl: baseUrlFlag,
json: jsonFlag,
}).pipe(
Command.withDescription("Issue a new client pairing token."),
Command.withHandler((flags) =>
runWithAuthControlPlane(
flags,
(authControlPlane) =>
Effect.gen(function* () {
const issued = yield* authControlPlane.createPairingLink({
role: "client",
subject: "one-time-token",
...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
});
const output = formatIssuedPairingCredential(issued, {
json: flags.json,
...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}),
});
yield* Console.log(output);
}),
{
quietLogs: flags.json,
},
),
),
);
const pairingListCommand = Command.make("list", {
...authLocationFlags,
json: jsonFlag,
}).pipe(
Command.withDescription("List active client pairing tokens without revealing their secrets."),
Command.withHandler((flags) =>
runWithAuthControlPlane(
flags,
(authControlPlane) =>
Effect.gen(function* () {
const pairingLinks = yield* authControlPlane.listPairingLinks({ role: "client" });
yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));
}),
{
quietLogs: flags.json,
},
),
),
);
const pairingRevokeCommand = Command.make("revoke", {
...authLocationFlags,
id: Argument.string("id").pipe(Argument.withDescription("Pairing credential id to revoke.")),
}).pipe(
Command.withDescription("Revoke an active client pairing token."),
Command.withHandler((flags) =>
runWithAuthControlPlane(flags, (authControlPlane) =>
Effect.gen(function* () {
const revoked = yield* authControlPlane.revokePairingLink(flags.id);
yield* Console.log(
revoked
? `Revoked pairing credential ${flags.id}.\n`
: `No active pairing credential found for ${flags.id}.\n`,
);
}),
),
),
);
const pairingCommand = Command.make("pairing").pipe(
Command.withDescription("Manage one-time client pairing tokens."),
Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
);
const sessionIssueCommand = Command.make("issue", {
...authLocationFlags,
ttl: ttlFlag,
role: sessionRoleFlag,
label: labelFlag,
subject: subjectFlag,
tokenOnly: tokenOnlyFlag,
json: jsonFlag,
}).pipe(
Command.withDescription("Issue a bearer session token for headless or remote clients."),
Command.withHandler((flags) =>
runWithAuthControlPlane(
flags,
(authControlPlane) =>
Effect.gen(function* () {
const issued = yield* authControlPlane.issueSession({
role: flags.role,
...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),
});
yield* Console.log(
formatIssuedSession(issued, {
json: flags.json,
tokenOnly: flags.tokenOnly,
}),
);
}),
{
quietLogs: flags.json || flags.tokenOnly,
},
),
),
);
const sessionListCommand = Command.make("list", {
...authLocationFlags,
json: jsonFlag,
}).pipe(
Command.withDescription("List active sessions without revealing bearer tokens."),
Command.withHandler((flags) =>
runWithAuthControlPlane(
flags,
(authControlPlane) =>
Effect.gen(function* () {
const sessions = yield* authControlPlane.listSessions();
yield* Console.log(formatSessionList(sessions, { json: flags.json }));
}),
{
quietLogs: flags.json,
},
),
),
);
const sessionRevokeCommand = Command.make("revoke", {
...authLocationFlags,
sessionId: Argument.string("session-id").pipe(
Argument.withDescription("Session id to revoke."),
Argument.withSchema(AuthSessionId),
),
}).pipe(
Command.withDescription("Revoke an active session."),
Command.withHandler((flags) =>
runWithAuthControlPlane(flags, (authControlPlane) =>
Effect.gen(function* () {
const revoked = yield* authControlPlane.revokeSession(flags.sessionId);
yield* Console.log(
revoked
? `Revoked session ${flags.sessionId}.\n`
: `No active session found for ${flags.sessionId}.\n`,
);
}),
),
),
);
const sessionCommand = Command.make("session").pipe(
Command.withDescription("Manage bearer sessions."),
Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),
);
export const authCommand = Command.make("auth").pipe(
Command.withDescription("Manage the local auth control plane for headless deployments."),
Command.withSubcommands([pairingCommand, sessionCommand]),
);
@@ -5,8 +5,8 @@ import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect"
import { NetService } from "@t3tools/shared/Net";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { deriveServerPaths } from "./config.ts";
import { resolveServerConfig } from "./cli.ts";
import { deriveServerPaths } from "../config.ts";
import { resolveServerConfig } from "./config.ts";
it.layer(NodeServices.layer)("cli config resolution", (it) => {
const defaultObservabilityConfig = {
+490
View File
@@ -0,0 +1,490 @@
import { NetService } from "@t3tools/shared/Net";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import {
Config,
Duration,
Effect,
FileSystem,
LogLevel,
Option,
Path,
Schema,
SchemaIssue,
SchemaTransformation,
} from "effect";
import { Argument, Flag } from "effect/unstable/cli";
import { readBootstrapEnvelope } from "../bootstrap.ts";
import {
DEFAULT_PORT,
deriveServerPaths,
ensureServerDirectories,
resolveStaticDir,
RuntimeMode,
type ServerConfigShape,
type StartupPresentation,
} from "../config.ts";
import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
const BootstrapEnvelopeSchema = Schema.Struct({
mode: Schema.optional(RuntimeMode),
port: Schema.optional(PortSchema),
host: Schema.optional(Schema.String),
t3Home: Schema.optional(Schema.String),
devUrl: Schema.optional(Schema.URLFromString),
noBrowser: Schema.optional(Schema.Boolean),
desktopBootstrapToken: Schema.optional(Schema.String),
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
logWebSocketEvents: Schema.optional(Schema.Boolean),
tailscaleServeEnabled: Schema.optional(Schema.Boolean),
tailscaleServePort: Schema.optional(PortSchema),
otlpTracesUrl: Schema.optional(Schema.String),
otlpMetricsUrl: Schema.optional(Schema.String),
});
export const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
Flag.optional,
);
export const portFlag = Flag.integer("port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription("Port for the HTTP/WebSocket server."),
Flag.optional,
);
export const hostFlag = Flag.string("host").pipe(
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
Flag.optional,
);
export const baseDirFlag = Flag.string("base-dir").pipe(
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
Flag.optional,
);
export const devUrlFlag = Flag.string("dev-url").pipe(
Flag.withSchema(Schema.URLFromString),
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
Flag.optional,
);
export const noBrowserFlag = Flag.boolean("no-browser").pipe(
Flag.withDescription("Disable automatic browser opening."),
Flag.optional,
);
export const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
Flag.withSchema(Schema.Int),
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
Flag.optional,
);
export const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
Flag.withDescription(
"Create a project for the current working directory on startup when missing.",
),
Flag.optional,
);
export const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
Flag.withDescription(
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
),
Flag.withAlias("log-ws-events"),
Flag.optional,
);
export const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(
Flag.withDescription(
"Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
),
Flag.optional,
);
export const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
Flag.optional,
);
const EnvServerConfig = Config.all({
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
Config.withDefault(10_000),
),
otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
tailscaleServeEnabled: Config.boolean("T3CODE_TAILSCALE_SERVE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
tailscaleServePort: Config.port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
});
export interface CliServerFlags {
readonly mode: Option.Option<RuntimeMode>;
readonly port: Option.Option<number>;
readonly host: Option.Option<string>;
readonly baseDir: Option.Option<string>;
readonly cwd: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly noBrowser: Option.Option<boolean>;
readonly bootstrapFd: Option.Option<number>;
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
readonly logWebSocketEvents: Option.Option<boolean>;
readonly tailscaleServeEnabled: Option.Option<boolean>;
readonly tailscaleServePort: Option.Option<number>;
}
export interface CliAuthLocationFlags {
readonly baseDir: Option.Option<string>;
readonly devUrl?: Option.Option<URL>;
}
export const sharedServerLocationFlags = {
baseDir: baseDirFlag,
devUrl: devUrlFlag,
} as const;
export const projectLocationFlags = {
baseDir: baseDirFlag,
} as const;
export const sharedServerCommandFlags = {
mode: modeFlag,
port: portFlag,
host: hostFlag,
baseDir: baseDirFlag,
cwd: Argument.string("cwd").pipe(
Argument.withDescription(
"Working directory for provider sessions (defaults to the current directory).",
),
Argument.optional,
),
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
bootstrapFd: bootstrapFdFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
tailscaleServeEnabled: tailscaleServeFlag,
tailscaleServePort: tailscaleServePortFlag,
} as const;
export const authLocationFlags = sharedServerLocationFlags;
const resolveOptionPrecedence = <Value>(
...values: ReadonlyArray<Option.Option<Value>>
): Option.Option<Value> => Option.firstSomeOf(values);
const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
const fs = yield* FileSystem.FileSystem;
const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
if (!exists) {
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}
const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
return parsePersistedServerObservabilitySettings(raw);
});
export const resolveServerConfig = (
flags: CliServerFlags,
cliLogLevel: Option.Option<LogLevel.LogLevel>,
options?: {
readonly startupPresentation?: StartupPresentation;
readonly forceAutoBootstrapProjectFromCwd?: boolean;
},
) =>
Effect.gen(function* () {
const { findAvailablePort } = yield* NetService;
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const env = yield* EnvServerConfig;
const normalizedFlags = {
mode: flags.mode ?? Option.none(),
port: flags.port ?? Option.none(),
host: flags.host ?? Option.none(),
baseDir: flags.baseDir ?? Option.none(),
cwd: flags.cwd ?? Option.none(),
devUrl: flags.devUrl ?? Option.none(),
noBrowser: flags.noBrowser ?? Option.none(),
bootstrapFd: flags.bootstrapFd ?? Option.none(),
autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
} satisfies CliServerFlags;
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
bootstrapFd !== undefined
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
: Option.none();
const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
const mode: RuntimeMode = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.mode,
Option.fromUndefinedOr(env.mode),
Option.fromUndefinedOr(bootstrap?.mode),
),
() => "web",
);
const port = yield* Option.match(
resolveOptionPrecedence(
normalizedFlags.port,
Option.fromUndefinedOr(env.port),
Option.fromUndefinedOr(bootstrap?.port),
),
{
onSome: (value) => Effect.succeed(value),
onNone: () => {
if (mode === "desktop") {
return Effect.succeed(DEFAULT_PORT);
}
return findAvailablePort(DEFAULT_PORT);
},
},
);
const devUrl = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.devUrl,
Option.fromUndefinedOr(env.devUrl),
Option.fromUndefinedOr(bootstrap?.devUrl),
),
() => undefined,
);
const baseDir = yield* resolveBaseDir(
Option.getOrUndefined(
resolveOptionPrecedence(
normalizedFlags.baseDir,
Option.fromUndefinedOr(env.t3Home),
Option.fromUndefinedOr(bootstrap?.t3Home),
),
),
);
const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
yield* fs.makeDirectory(cwd, { recursive: true });
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* ensureServerDirectories(derivedPaths);
const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
derivedPaths.settingsPath,
);
const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
const startupPresentation = options?.startupPresentation ?? "browser";
const isHeadlessStartup = startupPresentation === "headless";
const noBrowser = Option.getOrElse(
resolveOptionPrecedence(
isHeadlessStartup ? Option.some(true) : Option.none(),
normalizedFlags.noBrowser,
Option.fromUndefinedOr(env.noBrowser),
Option.fromUndefinedOr(bootstrap?.noBrowser),
),
() => mode === "desktop",
);
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
const autoBootstrapProjectFromCwd = Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
isHeadlessStartup ? Option.some(false) : Option.none(),
normalizedFlags.autoBootstrapProjectFromCwd,
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
Option.fromUndefinedOr(bootstrap?.autoBootstrapProjectFromCwd),
),
() => mode === "web",
);
const logWebSocketEvents = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.logWebSocketEvents,
Option.fromUndefinedOr(env.logWebSocketEvents),
Option.fromUndefinedOr(bootstrap?.logWebSocketEvents),
),
() => Boolean(devUrl),
);
const tailscaleServeEnabled = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.tailscaleServeEnabled,
Option.fromUndefinedOr(env.tailscaleServeEnabled),
Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
),
() => false,
);
const tailscaleServePort = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.tailscaleServePort,
Option.fromUndefinedOr(env.tailscaleServePort),
Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
),
() => 443,
);
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
const host = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.host,
Option.fromUndefinedOr(env.host),
Option.fromUndefinedOr(bootstrap?.host),
),
() => (mode === "desktop" ? "127.0.0.1" : undefined),
);
const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
const config: ServerConfigShape = {
logLevel,
traceMinLevel: env.traceMinLevel,
traceTimingEnabled: env.traceTimingEnabled,
traceBatchWindowMs: env.traceBatchWindowMs,
traceMaxBytes: env.traceMaxBytes,
traceMaxFiles: env.traceMaxFiles,
otlpTracesUrl:
env.otlpTracesUrl ??
bootstrap?.otlpTracesUrl ??
persistedObservabilitySettings.otlpTracesUrl,
otlpMetricsUrl:
env.otlpMetricsUrl ??
bootstrap?.otlpMetricsUrl ??
persistedObservabilitySettings.otlpMetricsUrl,
otlpExportIntervalMs: env.otlpExportIntervalMs,
otlpServiceName: env.otlpServiceName,
mode,
port,
cwd,
baseDir,
...derivedPaths,
serverTracePath,
host,
staticDir,
devUrl,
noBrowser,
startupPresentation,
desktopBootstrapToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
tailscaleServeEnabled,
tailscaleServePort,
};
return config;
});
export const resolveCliAuthConfig = (
flags: CliAuthLocationFlags,
cliLogLevel: Option.Option<LogLevel.LogLevel>,
) =>
resolveServerConfig(
{
mode: Option.none(),
port: Option.none(),
host: Option.none(),
baseDir: flags.baseDir,
cwd: Option.none(),
devUrl: flags.devUrl ?? Option.none(),
noBrowser: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
cliLogLevel,
);
const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
const parseDurationInput = (value: string): Duration.Duration | null => {
const trimmed = value.trim();
if (trimmed.length === 0) return null;
const shorthand = DurationShorthandPattern.exec(trimmed);
const normalizedInput = shorthand?.groups
? (() => {
const amountText = shorthand.groups.value;
const unitText = shorthand.groups.unit;
if (typeof amountText !== "string" || typeof unitText !== "string") {
return null;
}
const amount = Number.parseInt(amountText, 10);
if (!Number.isFinite(amount)) return null;
switch (unitText.toLowerCase()) {
case "ms":
return `${amount} millis`;
case "s":
return `${amount} seconds`;
case "m":
return `${amount} minutes`;
case "h":
return `${amount} hours`;
case "d":
return `${amount} days`;
case "w":
return `${amount} weeks`;
default:
return null;
}
})()
: (trimmed as Duration.Input);
if (normalizedInput === null) return null;
const decoded = Duration.fromInput(normalizedInput as Duration.Input);
return Option.isSome(decoded) ? decoded.value : null;
};
export const DurationFromString = Schema.String.pipe(
Schema.decodeTo(
Schema.Duration,
SchemaTransformation.transformOrFail({
decode: (value) => {
const duration = parseDurationInput(value);
if (duration !== null) {
return Effect.succeed(duration);
}
return Effect.fail(
new SchemaIssue.InvalidValue(Option.some(value), {
message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
}),
);
},
encode: (duration) => Effect.succeed(Duration.format(duration)),
}),
),
);
+434
View File
@@ -0,0 +1,434 @@
import {
CommandId,
OrchestrationReadModel,
ProjectId,
type ClientOrchestrationCommand,
} from "@t3tools/contracts";
import {
Console,
Duration,
Effect,
Exit,
FileSystem,
Layer,
Option,
Path,
References,
Schema,
} from "effect";
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
HttpClientResponse,
} from "effect/unstable/http";
import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";
import { AuthControlPlane } from "../auth/Services/AuthControlPlane.ts";
import type { AuthControlPlaneShape } from "../auth/Services/AuthControlPlane.ts";
import { ServerConfig, type ServerConfigShape } from "../config.ts";
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
import { RepositoryIdentityResolverLive } from "../project/Layers/RepositoryIdentityResolver.ts";
import { getAutoBootstrapDefaultModelSelection } from "../serverRuntimeStartup.ts";
import {
clearPersistedServerRuntimeState,
readPersistedServerRuntimeState,
} from "../serverRuntimeState.ts";
import { WorkspacePathsLive } from "../workspace/Layers/WorkspacePaths.ts";
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";
import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
type ProjectMutationTarget = {
readonly id: ProjectId;
readonly title: string;
readonly workspaceRoot: string;
};
type ProjectCommandExecutionMode = "live" | "offline";
type ProjectCliDispatchCommand = Extract<
ClientOrchestrationCommand,
{ type: "project.create" | "project.meta.update" | "project.delete" }
>;
const ProjectCliRuntimeLive = Layer.mergeAll(
WorkspacePathsLive,
OrchestrationLayerLive.pipe(
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(SqlitePersistenceLayerLive),
),
);
const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
const OrchestrationHttpErrorResponse = Schema.Struct({
error: Schema.String,
});
const withProjectCliSessionToken = <A, E, R>(
authControlPlane: AuthControlPlaneShape,
run: (token: string) => Effect.Effect<A, E, R>,
) =>
Effect.acquireUseRelease(
authControlPlane.issueSession({
role: "owner",
label: "t3 project cli",
}),
(issued) => run(issued.token),
(issued) => authControlPlane.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
);
const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
const runLiveServerRequest = <A, E extends Error, R>(
request: HttpClientRequest.HttpClientRequest,
handle: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E, R>,
) =>
Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
const response = yield* httpClient.execute(request);
return yield* handle(response);
}).pipe(withProjectCliLiveServerTimeout);
const decodeOrchestrationReadModelResponse = (response: HttpClientResponse.HttpClientResponse) =>
HttpClientResponse.schemaBodyJson(OrchestrationReadModel)(response);
const readErrorMessageFromResponse = (response: HttpClientResponse.HttpClientResponse) =>
HttpClientResponse.schemaBodyJson(OrchestrationHttpErrorResponse)(response).pipe(
Effect.map((body) => body.error),
Effect.catch(() => Effect.succeed(null)),
Effect.map((body) => {
if (typeof body === "string" && body.trim().length > 0) {
return body;
}
return `Server request failed with status ${response.status}.`;
}),
);
const normalizeWorkspaceRootForProjectCommand = Effect.fn(
"normalizeWorkspaceRootForProjectCommand",
)(function* (workspaceRoot: string) {
const workspacePaths = yield* WorkspacePaths;
return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
});
const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
workspaceRoot: string,
explicitTitle?: string,
) {
if (explicitTitle !== undefined) {
const trimmed = explicitTitle.trim();
if (trimmed.length > 0) {
return trimmed;
}
return yield* Effect.fail(new Error("Project title cannot be empty."));
}
const path = yield* Path.Path;
const basename = path.basename(workspaceRoot).trim();
return basename.length > 0 ? basename : "project";
});
const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
readonly snapshot: OrchestrationReadModel;
readonly identifier: string;
}) {
const trimmedIdentifier = input.identifier.trim();
if (trimmedIdentifier.length === 0) {
return yield* Effect.fail(new Error("Project identifier cannot be empty."));
}
const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
if (exactIdMatch) {
return {
id: exactIdMatch.id,
title: exactIdMatch.title,
workspaceRoot: exactIdMatch.workspaceRoot,
} satisfies ProjectMutationTarget;
}
const normalizedWorkspaceRootResult = yield* Effect.exit(
normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
);
const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult)
? normalizedWorkspaceRootResult.value
: null;
const exactWorkspaceMatch =
normalizedWorkspaceRoot === null
? undefined
: activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);
const resolved = exactWorkspaceMatch;
if (!resolved) {
return yield* Effect.fail(new Error(`No active project found for '${trimmedIdentifier}'.`));
}
return {
id: resolved.id,
title: resolved.title,
workspaceRoot: resolved.workspaceRoot,
} satisfies ProjectMutationTarget;
});
const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
runLiveServerRequest(
HttpClientRequest.get(`${origin}/api/orchestration/snapshot`).pipe(
HttpClientRequest.acceptJson,
HttpClientRequest.bearerToken(bearerToken),
),
HttpClientResponse.matchStatus({
"2xx": decodeOrchestrationReadModelResponse,
orElse: (response) =>
readErrorMessageFromResponse(response).pipe(
Effect.flatMap((message) => Effect.fail(new Error(message))),
),
}),
);
const dispatchLiveOrchestrationCommand = (
origin: string,
bearerToken: string,
command: ProjectCliDispatchCommand,
) =>
HttpClientRequest.post(`${origin}/api/orchestration/dispatch`).pipe(
HttpClientRequest.acceptJson,
HttpClientRequest.bearerToken(bearerToken),
HttpClientRequest.bodyJson(command),
Effect.flatMap((request) =>
runLiveServerRequest(
request,
HttpClientResponse.matchStatus({
"2xx": () => Effect.void,
orElse: (response) =>
readErrorMessageFromResponse(response).pipe(
Effect.flatMap((message) => Effect.fail(new Error(message))),
),
}),
),
),
);
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
return yield* projectionSnapshotQuery.getSnapshot();
});
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
function* (authControlPlane: AuthControlPlaneShape, config: ServerConfigShape) {
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
if (Option.isNone(runtimeState)) {
return Option.none<{ readonly origin: string }>();
}
const attempt = withProjectCliSessionToken(authControlPlane, (token) =>
fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
Effect.as({
origin: runtimeState.value.origin,
}),
),
);
const attempted = yield* Effect.exit(attempt);
if (Exit.isSuccess(attempted)) {
return Option.some(attempted.value);
}
yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
return Option.none<{ readonly origin: string }>();
},
);
const runProjectMutation = Effect.fn("runProjectMutation")(function* (
flags: CliAuthLocationFlags,
run: (input: {
readonly snapshot: OrchestrationReadModel;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
readonly mode: ProjectCommandExecutionMode;
}) => Effect.Effect<
string,
Error,
FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
>,
) {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveCliAuthConfig(flags, logLevel);
const minimumLogLevel = config.logLevel;
return yield* Effect.gen(function* () {
const authControlPlane = yield* AuthControlPlane;
const liveMode = yield* tryResolveLiveProjectExecutionMode(authControlPlane, config);
if (Option.isSome(liveMode)) {
return yield* withProjectCliSessionToken(authControlPlane, (token) =>
Effect.gen(function* () {
const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
const output = yield* run({
snapshot,
dispatch: (command) =>
dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
mode: "live",
});
yield* Console.log(output);
}),
);
}
const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(
Layer.provide(Layer.succeed(ServerConfig, config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
);
return yield* Effect.gen(function* () {
const snapshot = yield* getOfflineSnapshot();
const orchestrationEngine = yield* OrchestrationEngineService;
const output = yield* run({
snapshot,
dispatch: (command) => orchestrationEngine.dispatch(command),
mode: "offline",
});
yield* Console.log(output);
}).pipe(Effect.provide(offlineRuntimeLayer));
}).pipe(
Effect.provide(
Layer.mergeAll(AuthControlPlaneRuntimeLive, WorkspacePathsLive).pipe(
Layer.provideMerge(FetchHttpClient.layer),
Layer.provide(Layer.succeed(ServerConfig, config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
),
),
);
});
const projectAddCommand = Command.make("add", {
...projectLocationFlags,
workspaceRoot: Argument.string("path").pipe(
Argument.withDescription("Workspace root to add as a project."),
),
title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
}).pipe(
Command.withDescription("Add a project."),
Command.withHandler((flags) =>
runProjectMutation(
flags,
Effect.fn("projectAddMutation")(function* ({
snapshot,
dispatch,
}: {
readonly snapshot: OrchestrationReadModel;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
}) {
const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
const existingProject = snapshot.projects.find(
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
);
if (existingProject) {
return yield* Effect.fail(
new Error(`An active project already exists for '${workspaceRoot}'.`),
);
}
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
const projectId = ProjectId.make(crypto.randomUUID());
yield* dispatch({
type: "project.create",
commandId: CommandId.make(crypto.randomUUID()),
projectId,
title,
workspaceRoot,
defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
createdAt: new Date().toISOString(),
});
return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
}),
),
),
);
const projectRemoveCommand = Command.make("remove", {
...projectLocationFlags,
project: Argument.string("project").pipe(
Argument.withDescription("Project id or workspace root to remove."),
),
}).pipe(
Command.withDescription("Remove a project."),
Command.withHandler((flags) =>
runProjectMutation(
flags,
Effect.fn("projectRemoveMutation")(function* ({
snapshot,
dispatch,
}: {
readonly snapshot: OrchestrationReadModel;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
}) {
const project = yield* findActiveProjectTarget({
snapshot,
identifier: flags.project,
});
yield* dispatch({
type: "project.delete",
commandId: CommandId.make(crypto.randomUUID()),
projectId: project.id,
});
return `Removed project ${project.id} (${project.title}).`;
}),
),
),
);
const projectRenameCommand = Command.make("rename", {
...projectLocationFlags,
project: Argument.string("project").pipe(
Argument.withDescription("Project id or workspace root to rename."),
),
title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
}).pipe(
Command.withDescription("Rename a project."),
Command.withHandler((flags) =>
runProjectMutation(
flags,
Effect.fn("projectRenameMutation")(function* ({
snapshot,
dispatch,
}: {
readonly snapshot: OrchestrationReadModel;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
}) {
const project = yield* findActiveProjectTarget({
snapshot,
identifier: flags.project,
});
const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
if (nextTitle === project.title) {
return `Project ${project.id} is already named ${nextTitle}.`;
}
yield* dispatch({
type: "project.meta.update",
commandId: CommandId.make(crypto.randomUUID()),
projectId: project.id,
title: nextTitle,
});
return `Renamed project ${project.id} to ${nextTitle}.`;
}),
),
),
);
export const projectCommand = Command.make("project").pipe(
Command.withDescription("Manage projects."),
Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
);
+36
View File
@@ -0,0 +1,36 @@
import { Effect } from "effect";
import { Command, GlobalFlag } from "effect/unstable/cli";
import { ServerConfig, type StartupPresentation } from "../config.ts";
import { runServer } from "../server.ts";
import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } from "./config.ts";
export const runServerCommand = (
flags: CliServerFlags,
options?: {
readonly startupPresentation?: StartupPresentation;
readonly forceAutoBootstrapProjectFromCwd?: boolean;
},
) =>
Effect.gen(function* () {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveServerConfig(flags, logLevel, options);
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
});
export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((flags) => runServerCommand(flags)),
);
export const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(
Command.withDescription(
"Run the T3 Code server without opening a browser and print headless pairing details.",
),
Command.withHandler((flags) =>
runServerCommand(flags, {
startupPresentation: "headless",
forceAutoBootstrapProjectFromCwd: false,
}),
),
);
@@ -0,0 +1,252 @@
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
const encoder = new TextEncoder();
function mockHandle(result: {
readonly stdout?: string;
readonly stderr?: string;
readonly code?: number;
}) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
describe("ProcessDiagnostics", () => {
it.effect("parses POSIX ps rows with full commands", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parsePosixProcessRows(
[
" 10 1 10 Ss 0.0 1024 01:02.03 /usr/bin/node server.js",
" 11 10 10 S+ 12.5 20480 00:04 codex app-server --config /tmp/one two",
].join("\n"),
);
expect(rows).toEqual([
{
pid: 10,
ppid: 1,
pgid: 10,
status: "Ss",
cpuPercent: 0,
rssBytes: 1024 * 1024,
elapsed: "01:02.03",
command: "/usr/bin/node server.js",
},
{
pid: 11,
ppid: 10,
pgid: 10,
status: "S+",
cpuPercent: 12.5,
rssBytes: 20480 * 1024,
elapsed: "00:04",
command: "codex app-server --config /tmp/one two",
},
]);
}),
);
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
serverPid: 100,
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
{
pid: 101,
ppid: 100,
pgid: 100,
status: "S",
cpuPercent: 1.5,
rssBytes: 2_000,
elapsed: "00:20",
command: "codex app-server",
},
{
pid: 102,
ppid: 101,
pgid: 100,
status: "R",
cpuPercent: 3.25,
rssBytes: 4_000,
elapsed: "00:05",
command: "git status",
},
{
pid: 200,
ppid: 1,
pgid: 200,
status: "S",
cpuPercent: 99,
rssBytes: 8_000,
elapsed: "00:01",
command: "unrelated",
},
{
pid: 201,
ppid: 100,
pgid: 100,
status: "R",
cpuPercent: 9,
rssBytes: 9_000,
elapsed: "00:00",
command: "ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=",
},
],
});
expect(diagnostics.serverPid).toBe(100);
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
expect(diagnostics.processCount).toBe(2);
expect(diagnostics.totalRssBytes).toBe(6_000);
expect(diagnostics.totalCpuPercent).toBe(4.75);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
}),
);
it.effect("preserves ascending sibling order for nested descendants", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
serverPid: 100,
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
rows: [
{
pid: 101,
ppid: 100,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 100,
elapsed: "00:10",
command: "agent",
},
{
pid: 103,
ppid: 101,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 100,
elapsed: "00:10",
command: "child-b",
},
{
pid: 102,
ppid: 101,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 100,
elapsed: "00:10",
command: "child-a",
},
],
});
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
}),
);
it.effect("queries processes through the ChildProcessSpawner service", () =>
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
commands.push({ command: childProcess.command, args: childProcess.args });
return Effect.succeed(
mockHandle({
stdout: [
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
` 4242 ${process.pid} ${process.pid} S 1.5 2048 00:04 agent`,
].join("\n"),
}),
);
}),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
Effect.flatMap((pd) => pd.read),
Effect.provide(layer),
);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
expect(commands).toEqual([
{
command: "ps",
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
},
]);
}),
);
it.effect("does not allow signaling the diagnostics query process", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
stdout: [
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
` 4242 ${process.pid} ${process.pid} R 1.5 2048 00:00 ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=`,
].join("\n"),
}),
),
),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
Effect.flatMap((pd) => pd.signal({ pid: 4242, signal: "SIGINT" })),
Effect.provide(layer),
);
expect(result).toEqual({
pid: 4242,
signal: "SIGINT",
signaled: false,
message: Option.some("Process 4242 is not a live descendant of the T3 server."),
});
}),
);
});
@@ -0,0 +1,461 @@
import type {
ServerProcessDiagnosticsEntry,
ServerProcessDiagnosticsResult,
ServerProcessSignal,
ServerSignalProcessResult,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
interface ProcessRow {
readonly pid: number;
readonly ppid: number;
readonly pgid: number | null;
readonly status: string;
readonly cpuPercent: number;
readonly rssBytes: number;
readonly elapsed: string;
readonly command: string;
}
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
export interface ProcessDiagnosticsShape {
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
readonly signal: (input: {
readonly pid: number;
readonly signal: ServerProcessSignal;
}) => Effect.Effect<ServerSignalProcessResult>;
}
export class ProcessDiagnostics extends Context.Service<
ProcessDiagnostics,
ProcessDiagnosticsShape
>()("t3/diagnostics/ProcessDiagnostics") {}
class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
"ProcessDiagnosticsError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
return new ProcessDiagnosticsError({
message,
...(cause === undefined ? {} : { cause }),
});
}
function parsePositiveInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
}
function parseNonNegativeInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
}
function parseNumber(value: string): number | null {
const parsed = Number.parseFloat(value);
return Number.isFinite(parsed) ? parsed : null;
}
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
for (const line of output.split(/\r?\n/)) {
if (line.trim().length === 0) continue;
const match = rowPattern.exec(line);
if (!match) continue;
const pidText = match[1];
const ppidText = match[2];
const pgidText = match[3];
const status = match[4];
const cpuText = match[5];
const rssText = match[6];
const elapsed = match[7];
const command = match[8];
if (
pidText === undefined ||
ppidText === undefined ||
pgidText === undefined ||
status === undefined ||
cpuText === undefined ||
rssText === undefined ||
elapsed === undefined ||
command === undefined
) {
continue;
}
const pid = parsePositiveInt(pidText);
const ppid = parseNonNegativeInt(ppidText);
const pgid = Number.parseInt(pgidText, 10);
const cpuPercent = parseNumber(cpuText);
const rssKiB = parseNonNegativeInt(rssText);
if (
pid === null ||
ppid === null ||
!Number.isInteger(pgid) ||
cpuPercent === null ||
rssKiB === null ||
!status ||
!elapsed ||
!command
) {
continue;
}
rows.push({
pid,
ppid,
pgid,
status,
cpuPercent,
rssBytes: rssKiB * 1024,
elapsed,
command,
});
}
return rows;
}
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
? record.Name
: null;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
}
function buildDescendantEntries(
rows: ReadonlyArray<ProcessRow>,
serverPid: number,
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
const childrenByParent = new Map<number, ProcessRow[]>();
for (const row of rows) {
const children = childrenByParent.get(row.ppid) ?? [];
children.push(row);
childrenByParent.set(row.ppid, children);
}
const entries: ServerProcessDiagnosticsEntry[] = [];
const visited = new Set<number>();
const stack = [...(childrenByParent.get(serverPid) ?? [])]
.toSorted((left, right) => left.pid - right.pid)
.map((row) => ({ row, depth: 0 }));
while (stack.length > 0) {
const item = stack.shift();
if (!item || visited.has(item.row.pid)) continue;
visited.add(item.row.pid);
const children = [...(childrenByParent.get(item.row.pid) ?? [])].toSorted(
(left, right) => left.pid - right.pid,
);
entries.push({
pid: item.row.pid,
ppid: item.row.ppid,
pgid: Option.fromNullishOr(item.row.pgid),
status: item.row.status,
cpuPercent: item.row.cpuPercent,
rssBytes: item.row.rssBytes,
elapsed: item.row.elapsed || "n/a",
command: item.row.command,
depth: item.depth,
childPids: children.map((child) => child.pid),
});
stack.unshift(...children.map((row) => ({ row, depth: item.depth + 1 })));
}
return entries;
}
function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
if (row.ppid !== serverPid) return false;
const command = row.command.trim();
return (
/(?:^|[/\\])ps\s+-axo\s+pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=/.test(command) ||
(/\bpowershell(?:\.exe)?\b/i.test(command) &&
/\bGet-CimInstance\s+Win32_Process\b/i.test(command))
);
}
function makeResult(input: {
readonly serverPid: number;
readonly rows: ReadonlyArray<ProcessRow>;
readonly readAt: DateTime.Utc;
readonly error?: string;
}): ServerProcessDiagnosticsResult {
const readAt = input.readAt;
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
const processes = buildDescendantEntries(rows, input.serverPid);
const totalRssBytes = processes.reduce((total, process) => total + process.rssBytes, 0);
const totalCpuPercent = processes.reduce((total, process) => total + process.cpuPercent, 0);
return {
serverPid: input.serverPid,
readAt,
processCount: processes.length,
totalRssBytes,
totalCpuPercent,
processes,
error: input.error ? Option.some({ message: input.error }) : Option.none(),
};
}
interface ProcessOutput {
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
}
const runProcess = Effect.fn("runProcess")(
function* (input: {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly errorMessage: string;
}) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(
ChildProcess.make(input.command, input.args, {
cwd: process.cwd(),
shell: process.platform === "win32",
}),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectUint8StreamText({
stream: child.stdout,
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
truncatedMarker: "\n\n[truncated]",
}),
collectUint8StreamText({
stream: child.stderr,
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
truncatedMarker: "\n\n[truncated]",
}),
child.exitCode,
],
{ concurrency: "unbounded" },
);
return {
exitCode,
stdout: stdout.text,
stderr: stderr.text,
} satisfies ProcessOutput;
},
(effect, input) =>
effect.pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
onSome: Effect.succeed,
}),
),
Effect.mapError((cause) =>
Schema.is(ProcessDiagnosticsError)(cause)
? cause
: toProcessDiagnosticsError(input.errorMessage, cause),
),
),
);
function readPosixProcessRows(): Effect.Effect<
ReadonlyArray<ProcessRow>,
ProcessDiagnosticsError,
ChildProcessSpawner.ChildProcessSpawner
> {
return runProcess({
command: "ps",
args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
errorMessage: "Failed to query process diagnostics.",
}).pipe(
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
: Effect.succeed(parsePosixProcessRows(result.stdout)),
),
);
}
function readWindowsProcessRows(): Effect.Effect<
ReadonlyArray<ProcessRow>,
ProcessDiagnosticsError,
ChildProcessSpawner.ChildProcessSpawner
> {
const command = [
"$processes = Get-CimInstance Win32_Process | ForEach-Object {",
'$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
"[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
"};",
"$processes | ConvertTo-Json -Compress -Depth 3",
].join(" ");
return runProcess({
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
errorMessage: "Failed to query process diagnostics.",
}).pipe(
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
)
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
),
);
}
const readProcessRows = (platform = process.platform) =>
platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
export function aggregateProcessDiagnostics(input: {
readonly serverPid: number;
readonly rows: ReadonlyArray<ProcessRow>;
readonly readAt: DateTime.Utc;
}): ServerProcessDiagnosticsResult {
return makeResult(input);
}
function assertDescendantPid(
pid: number,
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
if (pid === process.pid) {
return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
}
return readProcessRows().pipe(
Effect.flatMap((rows) => {
const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
const descendant = buildDescendantEntries(filteredRows, process.pid).some(
(entry) => entry.pid === pid,
);
return descendant
? Effect.void
: Effect.fail(
toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
);
}),
);
}
export const make = Effect.fn("makeProcessDiagnostics")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const read: ProcessDiagnosticsShape["read"] = Effect.gen(function* () {
const readAt = yield* DateTime.now;
const rows = yield* readProcessRows().pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return makeResult({ serverPid: process.pid, rows, readAt });
}).pipe(
Effect.catch((error: ProcessDiagnosticsError) =>
DateTime.now.pipe(
Effect.map((readAt) =>
makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
),
),
),
);
const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
function* (input) {
return yield* assertDescendantPid(input.pid).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.flatMap(() =>
Effect.try({
try: () => {
process.kill(input.pid, input.signal);
return {
pid: input.pid,
signal: input.signal,
signaled: true,
message: Option.none(),
};
},
catch: (cause) =>
toProcessDiagnosticsError(
`Failed to signal process ${input.pid} with ${input.signal}.`,
cause,
),
}),
),
Effect.catch((error: ProcessDiagnosticsError) =>
Effect.succeed({
pid: input.pid,
signal: input.signal,
signaled: false,
message: Option.some(error.message),
}),
),
);
},
);
return ProcessDiagnostics.of({ read, signal });
});
export const layer = Layer.effect(ProcessDiagnostics, make());
@@ -0,0 +1,258 @@
import { assert, describe, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as TraceDiagnostics from "./TraceDiagnostics.ts";
function ns(ms: number): string {
return String(BigInt(ms) * 1_000_000n);
}
function record(input: {
readonly name: string;
readonly traceId: string;
readonly spanId: string;
readonly startMs: number;
readonly durationMs: number;
readonly exit?: { readonly _tag: "Success" | "Failure" | "Interrupted"; readonly cause?: string };
readonly events?: ReadonlyArray<unknown>;
}) {
return JSON.stringify({
type: "effect-span",
name: input.name,
traceId: input.traceId,
spanId: input.spanId,
sampled: true,
kind: "internal",
startTimeUnixNano: ns(input.startMs),
endTimeUnixNano: ns(input.startMs + input.durationMs),
durationMs: input.durationMs,
attributes: {},
events: input.events ?? [],
links: [],
exit: input.exit ?? { _tag: "Success" },
});
}
describe("TraceDiagnostics", () => {
it.effect("aggregates failures, slow spans, log levels, and parse errors", () =>
Effect.sync(() => {
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
traceFilePath: "/tmp/server.trace.ndjson",
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
slowSpanThresholdMs: 1_000,
files: [
{
path: "/tmp/server.trace.ndjson.1",
text: [
record({
name: "server.getConfig",
traceId: "trace-a",
spanId: "span-a",
startMs: 1_000,
durationMs: 50,
}),
"not-json",
].join("\n"),
},
{
path: "/tmp/server.trace.ndjson",
text: [
record({
name: "orchestration.dispatch",
traceId: "trace-b",
spanId: "span-b",
startMs: 2_000,
durationMs: 1_500,
exit: { _tag: "Failure", cause: "Provider crashed" },
events: [
{
name: "provider failed",
timeUnixNano: ns(3_400),
attributes: { "effect.logLevel": "Error" },
},
],
}),
record({
name: "orchestration.dispatch",
traceId: "trace-c",
spanId: "span-c",
startMs: 4_000,
durationMs: 250,
exit: { _tag: "Failure", cause: "Provider crashed" },
}),
record({
name: "git.status",
traceId: "trace-d",
spanId: "span-d",
startMs: 5_000,
durationMs: 25,
exit: { _tag: "Interrupted", cause: "Interrupted" },
events: [
{
name: "status delayed",
timeUnixNano: ns(5_010),
attributes: { "effect.logLevel": "Warning" },
},
],
}),
].join("\n"),
},
],
});
assert.equal(diagnostics.recordCount, 4);
assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
assert.equal(
Option.match(diagnostics.firstSpanAt, {
onNone: () => null,
onSome: DateTime.formatIso,
}),
"1970-01-01T00:00:01.000Z",
);
assert.equal(
Option.match(diagnostics.lastSpanAt, {
onNone: () => null,
onSome: DateTime.formatIso,
}),
"1970-01-01T00:00:05.025Z",
);
assert.equal(diagnostics.parseErrorCount, 1);
assert.equal(diagnostics.failureCount, 2);
assert.equal(diagnostics.interruptionCount, 1);
assert.equal(diagnostics.slowSpanCount, 1);
assert.equal(diagnostics.logLevelCounts.Error, 1);
assert.equal(diagnostics.logLevelCounts.Warning, 1);
assert.equal(diagnostics.commonFailures[0]?.name, "orchestration.dispatch");
assert.equal(diagnostics.commonFailures[0]?.count, 2);
assert.equal(diagnostics.latestFailures[0]?.traceId, "trace-c");
assert.equal(diagnostics.slowestSpans[0]?.traceId, "trace-b");
assert.equal(diagnostics.latestWarningAndErrorLogs[0]?.message, "status delayed");
assert.equal(diagnostics.topSpansByCount[0]?.name, "orchestration.dispatch");
}),
);
it.effect("returns a not-found diagnostic when no files are available", () =>
Effect.sync(() => {
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
traceFilePath: "/tmp/missing.trace.ndjson",
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
files: [],
});
assert.equal(diagnostics.recordCount, 0);
assert.equal(Option.getOrUndefined(diagnostics.error)?.kind, "trace-file-not-found");
}),
);
it.effect("preserves full failure causes and log messages", () =>
Effect.sync(() => {
const longCause = `VcsProcessSpawnError: ${"missing executable ".repeat(80)}`.trim();
const longMessage = `provider warning: ${"retrying command ".repeat(80)}`.trim();
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
traceFilePath: "/tmp/server.trace.ndjson",
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
files: [
{
path: "/tmp/server.trace.ndjson",
text: record({
name: "VcsProcess.run",
traceId: "trace-long",
spanId: "span-long",
startMs: 1_000,
durationMs: 25,
exit: { _tag: "Failure", cause: longCause },
events: [
{
name: longMessage,
timeUnixNano: ns(1_010),
attributes: { "effect.logLevel": "Warning" },
},
],
}),
},
],
});
assert.equal(diagnostics.latestFailures[0]?.cause, longCause);
assert.equal(diagnostics.commonFailures[0]?.cause, longCause);
assert.equal(diagnostics.latestWarningAndErrorLogs[0]?.message, longMessage);
}),
);
it.effect("keeps loaded trace data when one rotated trace file fails to read", () =>
Effect.gen(function* () {
const traceFilePath = "/tmp/server.trace.ndjson";
const fileSystemLayer = FileSystem.layerNoop({
readFileString: (path) =>
path === `${traceFilePath}.1`
? Effect.fail(
PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
description: "permission denied",
pathOrDescriptor: path,
}),
)
: Effect.succeed(
record({
name: "server.getConfig",
traceId: "trace-a",
spanId: "span-a",
startMs: 1_000,
durationMs: 50,
}),
),
});
const diagnostics = yield* TraceDiagnostics.readTraceDiagnostics({
traceFilePath,
maxFiles: 1,
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
}).pipe(Effect.provide(TraceDiagnostics.layer.pipe(Layer.provide(fileSystemLayer))));
assert.equal(diagnostics.recordCount, 1);
assert.equal(
Option.getOrElse(diagnostics.partialFailure, () => false),
true,
);
assert.equal(Option.getOrUndefined(diagnostics.error)?.kind, "trace-file-read-failed");
assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]);
}),
);
it.effect("keeps only the slowest span occurrences while aggregating large inputs", () =>
Effect.sync(() => {
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
traceFilePath: "/tmp/server.trace.ndjson",
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
files: [
{
path: "/tmp/server.trace.ndjson",
text: Array.from({ length: 25 }, (_, index) =>
record({
name: `span-${index}`,
traceId: `trace-${index}`,
spanId: `span-${index}`,
startMs: index * 1_000,
durationMs: index,
}),
).join("\n"),
},
],
});
assert.equal(diagnostics.recordCount, 25);
assert.equal(diagnostics.slowestSpans.length, 10);
assert.deepStrictEqual(
diagnostics.slowestSpans.map((span) => span.durationMs),
[24, 23, 22, 21, 20, 19, 18, 17, 16, 15],
);
}),
);
});
@@ -0,0 +1,470 @@
import type {
ServerTraceDiagnosticsErrorKind,
ServerTraceDiagnosticsFailureSummary,
ServerTraceDiagnosticsLogEvent,
ServerTraceDiagnosticsRecentFailure,
ServerTraceDiagnosticsResult,
ServerTraceDiagnosticsSpanOccurrence,
ServerTraceDiagnosticsSpanSummary,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
interface TraceRecordLike {
readonly name?: unknown;
readonly traceId?: unknown;
readonly spanId?: unknown;
readonly startTimeUnixNano?: unknown;
readonly endTimeUnixNano?: unknown;
readonly durationMs?: unknown;
readonly exit?: unknown;
readonly events?: unknown;
}
interface TraceEventLike {
readonly name?: unknown;
readonly timeUnixNano?: unknown;
readonly attributes?: unknown;
}
export interface TraceDiagnosticsOptions {
readonly traceFilePath: string;
readonly maxFiles: number;
readonly slowSpanThresholdMs?: number;
readonly readAt?: DateTime.Utc;
}
export interface TraceDiagnosticsShape {
readonly read: (options: TraceDiagnosticsOptions) => Effect.Effect<ServerTraceDiagnosticsResult>;
}
export class TraceDiagnostics extends Context.Service<TraceDiagnostics, TraceDiagnosticsShape>()(
"t3/diagnostics/TraceDiagnostics",
) {}
interface TraceDiagnosticsInput {
readonly traceFilePath: string;
readonly files: ReadonlyArray<{ readonly path: string; readonly text: string }>;
readonly scannedFilePaths?: ReadonlyArray<string>;
readonly slowSpanThresholdMs?: number;
readonly readAt: DateTime.Utc;
readonly error?: TraceDiagnosticsErrorSummary;
readonly partialFailure?: boolean;
}
interface TraceDiagnosticsErrorSummary {
readonly kind: ServerTraceDiagnosticsErrorKind;
readonly message: string;
}
const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
const TOP_LIMIT = 10;
const RECENT_LIMIT = 20;
function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {
const backupCount = Math.max(0, Math.floor(maxFiles));
const backups = Array.from(
{ length: backupCount },
(_, index) => `${traceFilePath}.${backupCount - index}`,
);
return [...backups, traceFilePath];
}
function isRecordObject(value: unknown): value is TraceRecordLike {
return typeof value === "object" && value !== null;
}
function toStringValue(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
function toNumberValue(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
const text = toStringValue(value);
if (!text) return null;
try {
const millis = Number(BigInt(text) / 1_000_000n);
if (!Number.isFinite(millis)) return null;
return DateTime.makeUnsafe(millis);
} catch {
return null;
}
}
function isAfter(left: DateTime.Utc, right: DateTime.Utc): boolean {
return DateTime.toEpochMillis(left) > DateTime.toEpochMillis(right);
}
function isBefore(left: DateTime.Utc, right: DateTime.Utc): boolean {
return DateTime.toEpochMillis(left) < DateTime.toEpochMillis(right);
}
function readExitTag(exit: unknown): string | null {
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
return toStringValue(exit._tag);
}
function readExitCause(exit: unknown): string {
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
return toStringValue(exit.cause)?.trim() ?? "Failure";
}
function isTraceEvent(value: unknown): value is TraceEventLike {
return typeof value === "object" && value !== null;
}
function readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {
return typeof event.attributes === "object" && event.attributes !== null
? (event.attributes as Readonly<Record<string, unknown>>)
: {};
}
function makeEmptyDiagnostics(input: {
readonly traceFilePath: string;
readonly scannedFilePaths: ReadonlyArray<string>;
readonly readAt: DateTime.Utc;
readonly slowSpanThresholdMs: number;
readonly error?: TraceDiagnosticsErrorSummary;
readonly partialFailure?: boolean;
}): ServerTraceDiagnosticsResult {
return {
traceFilePath: input.traceFilePath,
scannedFilePaths: [...input.scannedFilePaths],
readAt: input.readAt,
recordCount: 0,
parseErrorCount: 0,
firstSpanAt: Option.none(),
lastSpanAt: Option.none(),
failureCount: 0,
interruptionCount: 0,
slowSpanThresholdMs: input.slowSpanThresholdMs,
slowSpanCount: 0,
logLevelCounts: {},
topSpansByCount: [],
slowestSpans: [],
commonFailures: [],
latestFailures: [],
latestWarningAndErrorLogs: [],
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
error: Option.fromNullishOr(input.error),
};
}
function isNotFoundError(error: PlatformError.PlatformError): boolean {
return error.reason._tag === "NotFound";
}
function platformErrorMessage(error: PlatformError.PlatformError): string {
return error.message || String(error);
}
function insertBoundedSlowestSpan(
slowestSpans: ServerTraceDiagnosticsSpanOccurrence[],
span: ServerTraceDiagnosticsSpanOccurrence,
): void {
if (
slowestSpans.length >= TOP_LIMIT &&
span.durationMs <= slowestSpans[slowestSpans.length - 1]!.durationMs
) {
return;
}
slowestSpans.push(span);
slowestSpans.sort((left, right) => right.durationMs - left.durationMs);
if (slowestSpans.length > TOP_LIMIT) {
slowestSpans.length = TOP_LIMIT;
}
}
export function aggregateTraceDiagnostics(
input: TraceDiagnosticsInput,
): ServerTraceDiagnosticsResult {
const readAt = input.readAt;
const slowSpanThresholdMs = input.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
const scannedFilePaths = input.scannedFilePaths ?? input.files.map((file) => file.path);
if (input.files.length === 0) {
return makeEmptyDiagnostics({
traceFilePath: input.traceFilePath,
scannedFilePaths,
readAt,
slowSpanThresholdMs,
error: input.error ?? {
kind: "trace-file-not-found",
message: "No local trace files were found.",
},
...(input.partialFailure ? { partialFailure: true } : {}),
});
}
let parseErrorCount = 0;
let recordCount = 0;
let failureCount = 0;
let interruptionCount = 0;
let slowSpanCount = 0;
let firstSpanAt: DateTime.Utc | null = null;
let lastSpanAt: DateTime.Utc | null = null;
const spansByName = new Map<
string,
{ count: number; failureCount: number; totalDurationMs: number; maxDurationMs: number }
>();
const failuresByKey = new Map<string, ServerTraceDiagnosticsFailureSummary>();
const latestFailures: ServerTraceDiagnosticsRecentFailure[] = [];
const slowestSpans: ServerTraceDiagnosticsSpanOccurrence[] = [];
const latestWarningAndErrorLogs: ServerTraceDiagnosticsLogEvent[] = [];
const logLevelCounts: Record<string, number> = {};
for (const file of input.files) {
const lines = file.text.split(/\r?\n/);
for (const line of lines) {
if (line.trim().length === 0) continue;
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
parseErrorCount += 1;
continue;
}
if (!isRecordObject(parsed)) {
parseErrorCount += 1;
continue;
}
const name = toStringValue(parsed.name);
const traceId = toStringValue(parsed.traceId);
const spanId = toStringValue(parsed.spanId);
const durationMs = toNumberValue(parsed.durationMs);
const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
parseErrorCount += 1;
continue;
}
recordCount += 1;
firstSpanAt =
startedAt && (firstSpanAt === null || isBefore(startedAt, firstSpanAt))
? startedAt
: firstSpanAt;
lastSpanAt = lastSpanAt === null || isAfter(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
const exitTag = readExitTag(parsed.exit);
const isFailure = exitTag === "Failure";
const isInterrupted = exitTag === "Interrupted";
if (isFailure) failureCount += 1;
if (isInterrupted) interruptionCount += 1;
const spanSummary = spansByName.get(name) ?? {
count: 0,
failureCount: 0,
totalDurationMs: 0,
maxDurationMs: 0,
};
spanSummary.count += 1;
spanSummary.totalDurationMs += durationMs;
spanSummary.maxDurationMs = Math.max(spanSummary.maxDurationMs, durationMs);
if (isFailure) spanSummary.failureCount += 1;
spansByName.set(name, spanSummary);
const spanItem = { name, durationMs, endedAt, traceId, spanId };
if (durationMs >= slowSpanThresholdMs) {
slowSpanCount += 1;
}
insertBoundedSlowestSpan(slowestSpans, spanItem);
if (isFailure) {
const cause = readExitCause(parsed.exit);
latestFailures.push({ ...spanItem, cause });
const failureKey = `${name}\0${cause}`;
const existing = failuresByKey.get(failureKey);
const isLatestFailure = !existing || isAfter(endedAt, existing.lastSeenAt);
failuresByKey.set(failureKey, {
name,
cause,
count: (existing?.count ?? 0) + 1,
lastSeenAt: isLatestFailure ? endedAt : existing!.lastSeenAt,
traceId: isLatestFailure ? traceId : existing!.traceId,
spanId: isLatestFailure ? spanId : existing!.spanId,
});
}
if (Array.isArray(parsed.events)) {
for (const rawEvent of parsed.events) {
if (!isTraceEvent(rawEvent)) continue;
const attributes = readEventAttributes(rawEvent);
const level = toStringValue(attributes["effect.logLevel"]);
if (!level) continue;
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
const normalizedLevel = level.toLowerCase();
if (
normalizedLevel !== "warning" &&
normalizedLevel !== "warn" &&
normalizedLevel !== "error" &&
normalizedLevel !== "fatal"
) {
continue;
}
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
latestWarningAndErrorLogs.push({
spanName: name,
level,
message,
seenAt,
traceId,
spanId,
});
}
}
}
}
const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()]
.map(([name, span]) => ({
name,
count: span.count,
failureCount: span.failureCount,
totalDurationMs: span.totalDurationMs,
averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0,
maxDurationMs: span.maxDurationMs,
}))
.toSorted((left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs)
.slice(0, TOP_LIMIT);
return {
traceFilePath: input.traceFilePath,
scannedFilePaths,
readAt,
recordCount,
parseErrorCount,
firstSpanAt: Option.fromNullishOr(firstSpanAt),
lastSpanAt: Option.fromNullishOr(lastSpanAt),
failureCount,
interruptionCount,
slowSpanThresholdMs,
slowSpanCount,
logLevelCounts,
topSpansByCount,
slowestSpans,
commonFailures: [...failuresByKey.values()]
.toSorted(
(left, right) =>
right.count - left.count ||
DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt),
)
.slice(0, TOP_LIMIT),
latestFailures: latestFailures
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt),
)
.slice(0, RECENT_LIMIT),
latestWarningAndErrorLogs: latestWarningAndErrorLogs
.toSorted(
(left, right) => DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt),
)
.slice(0, RECENT_LIMIT),
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
error: Option.fromNullishOr(input.error),
};
}
type TraceFileReadResult =
| { readonly _tag: "Loaded"; readonly path: string; readonly text: string }
| { readonly _tag: "Missing"; readonly path: string }
| { readonly _tag: "Failed"; readonly path: string; readonly message: string };
function readTraceFile(
fileSystem: FileSystem.FileSystem,
path: string,
): Effect.Effect<TraceFileReadResult> {
return fileSystem.readFileString(path).pipe(
Effect.map((text) => ({ _tag: "Loaded" as const, path, text })),
Effect.catch((error: PlatformError.PlatformError) =>
Effect.succeed(
isNotFoundError(error)
? { _tag: "Missing" as const, path }
: { _tag: "Failed" as const, path, message: platformErrorMessage(error) },
),
),
);
}
export const make = Effect.fn("makeTraceDiagnostics")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const read: TraceDiagnosticsShape["read"] = Effect.fn("TraceDiagnostics.read")(
function* (options) {
const readAt = options.readAt ?? (yield* DateTime.now);
const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
const paths = toRotatedTracePaths(options.traceFilePath, options.maxFiles);
const results = yield* Effect.all(
paths.map((path) => readTraceFile(fileSystem, path)),
{
concurrency: 1,
},
);
const files = results.flatMap((result) =>
result._tag === "Loaded" ? [{ path: result.path, text: result.text }] : [],
);
const readFailure = results.find((result) => result._tag === "Failed");
const readFailureError = readFailure
? ({
kind: "trace-file-read-failed",
message: readFailure.message.trim() || `Failed to read ${readFailure.path}.`,
} satisfies TraceDiagnosticsErrorSummary)
: undefined;
if (files.length === 0) {
return makeEmptyDiagnostics({
traceFilePath: options.traceFilePath,
scannedFilePaths: paths,
readAt,
slowSpanThresholdMs,
error:
readFailureError ??
({
kind: "trace-file-not-found",
message: "No local trace files were found.",
} satisfies TraceDiagnosticsErrorSummary),
});
}
return aggregateTraceDiagnostics({
traceFilePath: options.traceFilePath,
files,
scannedFilePaths: paths,
readAt,
slowSpanThresholdMs,
...(readFailureError ? { partialFailure: true, error: readFailureError } : {}),
});
},
);
return TraceDiagnostics.of({ read });
});
export const layer = Layer.effect(TraceDiagnostics, make());
export function readTraceDiagnostics(
options: TraceDiagnosticsOptions,
): Effect.Effect<ServerTraceDiagnosticsResult, never, TraceDiagnostics> {
return Effect.gen(function* () {
const diagnostics = yield* TraceDiagnostics;
return yield* diagnostics.read(options);
});
}
@@ -5,6 +5,7 @@ import { spawnSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { expect } from "vitest";
import type {
GitActionProgressEvent,
@@ -13,24 +14,27 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
import { type GitManagerShape } from "../Services/GitManager.ts";
import { GitCommandError, TextGenerationError } from "@t3tools/contracts";
import { type GitManagerShape } from "./GitManager.ts";
import {
GitHubCliError,
type GitHubCliShape,
type GitHubPullRequestSummary,
GitHubCli,
} from "../Services/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import { GitCoreLive } from "./GitCore.ts";
import { GitCore } from "../Services/GitCore.ts";
} from "../sourceControl/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../textGeneration/TextGeneration.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import { makeGitManager } from "./GitManager.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ServerConfig } from "../config.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import {
ProjectSetupScriptRunner,
type ProjectSetupScriptRunnerInput,
type ProjectSetupScriptRunnerShape,
} from "../../project/Services/ProjectSetupScriptRunner.ts";
} from "../project/Services/ProjectSetupScriptRunner.ts";
interface FakeGhScenario {
prListSequence?: string[];
@@ -53,6 +57,16 @@ interface FakeGhScenario {
failWith?: GitHubCliError;
}
function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
}
interface FakeGitTextGeneration {
generateCommitMessage: (input: {
cwd: string;
@@ -209,18 +223,27 @@ function runGit(
args: readonly string[],
allowNonZeroExit = false,
): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string },
{
readonly exitCode: GitVcsDriver.ExecuteGitResult["exitCode"];
readonly stdout: string;
readonly stderr: string;
},
GitCommandError,
GitCore
GitVcsDriver.GitVcsDriver
> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
return yield* gitCore.execute({
const git = yield* GitVcsDriver.GitVcsDriver;
const result = yield* git.execute({
operation: "GitManager.test.runGit",
cwd,
args,
allowNonZeroExit,
});
return {
exitCode: result.exitCode,
stdout: result.stdout,
stderr: result.stderr,
};
});
}
@@ -229,7 +252,7 @@ function initRepo(
): Effect.Effect<
void,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -245,7 +268,7 @@ function initRepo(
function createBareRemote(): Effect.Effect<
string,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
> {
return Effect.gen(function* () {
const remoteDir = yield* makeTempDir("t3code-git-remote-");
@@ -259,7 +282,7 @@ function configureRemote(
remoteName: string,
remotePath: string,
fetchNamespace: string,
): Effect.Effect<void, GitCommandError, GitCore> {
): Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver> {
return Effect.gen(function* () {
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
yield* runGit(cwd, [
@@ -271,6 +294,18 @@ function configureRemote(
});
}
function configureVisibleRemoteUrlWithLocalRewrite(
cwd: string,
remoteName: string,
visibleUrl: string,
localRemotePath: string,
): Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver> {
return Effect.gen(function* () {
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, visibleUrl]);
yield* runGit(cwd, ["config", `url.${localRemotePath}.insteadOf`, visibleUrl]);
});
}
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
const implementation: FakeGitTextGeneration = {
generateCommitMessage: (input) =>
@@ -379,24 +414,15 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
? scenario.prListByHeadSelector?.[headSelector]
: undefined;
const stdout = (mappedQueue ?? mappedStdout ?? prListQueue.shift() ?? "[]") + "\n";
return Effect.succeed({
stdout,
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
return Effect.succeed(fakeGhOutput(stdout));
}
if (args[0] === "pr" && args[1] === "create") {
return Effect.succeed({
stdout:
return Effect.succeed(
fakeGhOutput(
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
),
);
}
if (args[0] === "pr" && args[1] === "view") {
@@ -408,8 +434,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
headRefName: "feature/pull-request",
state: "open",
};
return Effect.succeed({
stdout:
return Effect.succeed(
fakeGhOutput(
JSON.stringify({
...pullRequest,
...(pullRequest.headRepositoryNameWithOwner
@@ -427,11 +453,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}
: {}),
}) + "\n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
),
);
}
if (args[0] === "pr" && args[1] === "checkout") {
@@ -453,13 +476,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
runGitSyncForFakeGh(input.cwd, ["checkout", "-b", headBranch]);
}
}
return {
stdout: "",
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
return fakeGhOutput("");
},
catch: (error) =>
isGitHubCliError(error)
@@ -486,26 +503,17 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}),
);
}
return Effect.succeed({
stdout:
return Effect.succeed(
fakeGhOutput(
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: "",
code: 0,
signal: null,
timedOut: false,
});
return Effect.succeed(fakeGhOutput(`${scenario.defaultBranch ?? "main"}\n`));
}
return Effect.fail(
@@ -584,6 +592,13 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
cwd: input.cwd,
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
createRepository: (input) =>
Effect.fail(
new GitHubCliError({
operation: "createRepository",
detail: `Unexpected repository create: ${input.repository}`,
}),
),
checkoutPullRequest: (input) =>
execute({
cwd: input.cwd,
@@ -639,13 +654,27 @@ function makeManager(input?: {
const serverSettingsLayer = ServerSettingsService.layerTest();
const gitCoreLayer = GitCoreLive.pipe(
const vcsDriverLayer = GitVcsDriver.layer.pipe(
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerConfigLayer),
);
const sourceControlRegistryLayer = Layer.effect(
SourceControlProviderRegistry.SourceControlProviderRegistry,
GitHubSourceControlProvider.make().pipe(
Effect.map((provider) =>
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
get: () => Effect.succeed(provider),
resolveHandle: () => Effect.succeed({ provider, context: null }),
resolve: () => Effect.succeed(provider),
discover: Effect.succeed([]),
}),
),
Effect.provide(Layer.succeed(GitHubCli, gitHubCli)),
),
);
const managerLayer = Layer.mergeAll(
Layer.succeed(GitHubCli, gitHubCli),
Layer.succeed(TextGeneration, textGeneration),
Layer.succeed(
ProjectSetupScriptRunner,
@@ -653,9 +682,9 @@ function makeManager(input?: {
runForThread: () => Effect.succeed({ status: "no-script" as const }),
},
),
gitCoreLayer,
vcsDriverLayer,
serverSettingsLayer,
).pipe(Layer.provideMerge(NodeServices.layer));
).pipe(Layer.provideMerge(sourceControlRegistryLayer), Layer.provideMerge(NodeServices.layer));
return makeGitManager().pipe(
Effect.provide(managerLayer),
@@ -665,8 +694,9 @@ function makeManager(input?: {
const asThreadId = (threadId: string) => threadId as ThreadId;
const GitManagerTestLayer = GitCoreLive.pipe(
const GitManagerTestLayer = GitVcsDriver.layer.pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
);
@@ -698,15 +728,15 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const status = yield* manager.status({ cwd: repoDir });
expect(status.isRepo).toBe(true);
expect(status.hasOriginRemote).toBe(true);
expect(status.isDefaultBranch).toBe(false);
expect(status.branch).toBe("feature/status-open-pr");
expect(status.hasPrimaryRemote).toBe(true);
expect(status.isDefaultRef).toBe(false);
expect(status.refName).toBe("feature/status-open-pr");
expect(status.pr).toEqual({
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseBranch: "main",
headBranch: "feature/status-open-pr",
baseRef: "main",
headRef: "feature/status-open-pr",
state: "open",
});
}),
@@ -743,8 +773,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 14,
title: "Existing PR title",
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
baseBranch: "main",
headBranch: "feature/status-trimmed-pr",
baseRef: "main",
headRef: "feature/status-trimmed-pr",
state: "open",
});
}),
@@ -794,8 +824,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 15,
title: "Valid PR title",
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
baseBranch: "main",
headBranch: "feature/status-valid-pr-entry",
baseRef: "main",
headRef: "feature/status-valid-pr-entry",
state: "open",
});
}),
@@ -843,8 +873,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 17,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
baseBranch: "main",
headBranch: "feature/status-lowercase-state",
baseRef: "main",
headRef: "feature/status-lowercase-state",
state: "merged",
});
}),
@@ -859,9 +889,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(status).toEqual({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -871,6 +901,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
});
}),
@@ -888,9 +919,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(status).toEqual({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -900,6 +931,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
});
}),
@@ -972,7 +1004,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("main");
expect(status.refName).toBe("main");
expect(status.pr).toBeNull();
}),
);
@@ -992,11 +1024,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-488/statemachine"]);
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
yield* configureVisibleRemoteUrlWithLocalRewrite(
repoDir,
"fork-seed",
"[email protected]:jasonLaster/codething-mvp.git",
]);
forkDir,
);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
@@ -1026,13 +1059,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("t3code/pr-488/statemachine");
expect(status.refName).toBe("t3code/pr-488/statemachine");
expect(status.pr).toEqual({
number: 488,
title: "Rebase this PR on latest main",
url: "https://github.com/pingdotgg/codething-mvp/pull/488",
baseBranch: "main",
headBranch: "statemachine",
baseRef: "main",
headRef: "statemachine",
state: "open",
});
expect(ghCalls).toContain(
@@ -1056,17 +1089,19 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]);
yield* runGit(repoDir, [
"config",
"remote.origin.url",
yield* configureVisibleRemoteUrlWithLocalRewrite(
repoDir,
"origin",
"[email protected]:pingdotgg/codething-mvp.git",
]);
originDir,
);
yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]);
yield* runGit(repoDir, [
"config",
"remote.my-org/upstream.url",
"[email protected]:pingdotgg/codething-mvp.git",
]);
yield* configureVisibleRemoteUrlWithLocalRewrite(
repoDir,
"my-org/upstream",
"ssh://[email protected]/pingdotgg/codething-mvp.git",
upstreamDir,
);
yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
@@ -1126,13 +1161,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("upstream/effect-atom");
expect(status.refName).toBe("upstream/effect-atom");
expect(status.pr).toEqual({
number: 1618,
title: "Correct PR",
url: "https://github.com/pingdotgg/t3code/pull/1618",
baseBranch: "main",
headBranch: "effect-atom",
baseRef: "main",
headRef: "effect-atom",
state: "open",
});
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
@@ -1176,18 +1211,48 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-merged-pr");
expect(status.refName).toBe("feature/status-merged-pr");
expect(status.pr).toEqual({
number: 22,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
baseBranch: "main",
headBranch: "feature/status-merged-pr",
baseRef: "main",
headRef: "feature/status-merged-pr",
state: "merged",
});
}),
);
it.effect("status hides merged PRs on the default branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 23,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/23",
baseRefName: "feature/status-default-branch-target",
headRefName: "main",
state: "MERGED",
mergedAt: "2026-01-30T10:00:00Z",
updatedAt: "2026-01-30T10:00:00Z",
},
]),
],
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.refName).toBe("main");
expect(status.pr).toBeNull();
}),
);
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -1223,13 +1288,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-open-over-merged");
expect(status.refName).toBe("feature/status-open-over-merged");
expect(status.pr).toEqual({
number: 46,
title: "Open PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
baseBranch: "main",
headBranch: "feature/status-open-over-merged",
baseRef: "main",
headRef: "feature/status-open-over-merged",
state: "open",
});
}),
@@ -1254,7 +1319,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-no-gh");
expect(status.refName).toBe("feature/status-no-gh");
expect(status.pr).toBeNull();
}),
);
@@ -1632,6 +1697,41 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("pushes existing commits without committing dirty worktree changes", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/push-dirty"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "push-dirty.txt"), "push dirty\n");
yield* runGit(repoDir, ["add", "push-dirty.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Push dirty branch"]);
fs.mkdirSync(path.join(repoDir, ".vercel"));
fs.writeFileSync(path.join(repoDir, ".vercel", "project.json"), "{}\n");
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "push",
});
expect(result.commit.status).toBe("skipped_not_requested");
expect(result.push.status).toBe("pushed");
expect(result.pr.status).toBe("skipped_not_requested");
expect(
yield* runGit(repoDir, ["status", "--porcelain"]).pipe(
Effect.map((output) => output.stdout.trim()),
),
).toContain("?? .vercel/");
expect(
yield* runGit(remoteDir, ["log", "-1", "--pretty=%s", "feature/push-dirty"]).pipe(
Effect.map((output) => output.stdout.trim()),
),
).toBe("Push dirty branch");
}),
);
it.effect("create_pr pushes a clean branch before creating the PR when needed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -1678,6 +1778,49 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("create_pr falls back to main when source control provider detection fails", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/provider-fallback"]);
fs.writeFileSync(path.join(repoDir, "provider-fallback.txt"), "fallback\n");
yield* runGit(repoDir, ["add", "provider-fallback.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Provider fallback"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
"[]",
JSON.stringify([
{
number: 404,
title: "Provider fallback",
url: "https://github.com/pingdotgg/codething-mvp/pull/404",
baseRefName: "main",
headRefName: "feature/provider-fallback",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "create_pr",
});
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(404);
expect(
ghCalls.some((call) =>
call.includes("pr create --base main --head feature/provider-fallback"),
),
).toBe(true);
}),
);
it.effect("returns existing PR metadata for commit/push/pr action", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -1733,11 +1876,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
yield* configureVisibleRemoteUrlWithLocalRewrite(
repoDir,
"fork-seed",
"[email protected]:octocat/codething-mvp.git",
]);
forkDir,
);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
@@ -1795,17 +1939,19 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]);
yield* runGit(repoDir, [
"config",
"remote.origin.url",
yield* configureVisibleRemoteUrlWithLocalRewrite(
repoDir,
"origin",
"[email protected]:pingdotgg/codething-mvp.git",
]);
originDir,
);
yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]);
yield* runGit(repoDir, [
"config",
"remote.my-org/upstream.url",
"[email protected]:pingdotgg/codething-mvp.git",
]);
yield* configureVisibleRemoteUrlWithLocalRewrite(
repoDir,
"my-org/upstream",
"ssh://[email protected]/pingdotgg/codething-mvp.git",
upstreamDir,
);
yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
@@ -1885,11 +2031,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-142/statemachine"]);
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
yield* configureVisibleRemoteUrlWithLocalRewrite(
repoDir,
"fork-seed",
"[email protected]:octocat/codething-mvp.git",
]);
forkDir,
);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
@@ -1955,11 +2102,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-142/statemachine"]);
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
yield* configureVisibleRemoteUrlWithLocalRewrite(
repoDir,
"fork-seed",
"[email protected]:octocat/codething-mvp.git",
]);
forkDir,
);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
@@ -2135,11 +2283,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-91/statemachine"]);
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
yield* configureVisibleRemoteUrlWithLocalRewrite(
repoDir,
"fork-seed",
"[email protected]:octocat/codething-mvp.git",
]);
forkDir,
);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
@@ -2335,6 +2484,113 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"restores same-repository upstream tracking after local PR checkout without a remote ref",
() =>
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-local-upstream"]);
fs.writeFileSync(path.join(repoDir, "upstream.txt"), "upstream\n");
yield* runGit(repoDir, ["add", "upstream.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local upstream PR branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-upstream"]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-upstream"]);
yield* runGit(repoDir, [
"update-ref",
"-d",
"refs/remotes/origin/feature/pr-local-upstream",
]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 65,
title: "Local upstream PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/65",
baseRefName: "main",
headRefName: "feature/pr-local-upstream",
state: "open",
isCrossRepository: false,
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
headRepositoryOwnerLogin: "pingdotgg",
},
repositoryCloneUrls: {
"pingdotgg/codething-mvp": {
url: remoteDir,
sshUrl: remoteDir,
},
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "65",
mode: "local",
});
expect(result.worktreePath).toBeNull();
expect(result.branch).toBe("feature/pr-local-upstream");
expect(
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
).toBe("origin/feature/pr-local-upstream");
}),
);
it.effect(
"restores same-repository upstream tracking when provider omits head repository metadata",
() =>
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-local-no-head-repo"]);
fs.writeFileSync(path.join(repoDir, "no-head-repo.txt"), "upstream\n");
yield* runGit(repoDir, ["add", "no-head-repo.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local PR branch without repo metadata"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-no-head-repo"]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-no-head-repo"]);
yield* runGit(repoDir, [
"update-ref",
"-d",
"refs/remotes/origin/feature/pr-local-no-head-repo",
]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 66,
title: "Local upstream PR without repo metadata",
url: "https://github.com/pingdotgg/codething-mvp/pull/66",
baseRefName: "main",
headRefName: "feature/pr-local-no-head-repo",
state: "open",
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "66",
mode: "local",
});
expect(result.worktreePath).toBeNull();
expect(result.branch).toBe("feature/pr-local-no-head-repo");
expect(
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
).toBe("origin/feature/pr-local-no-head-repo");
}),
);
it.effect("prepares pull request threads in worktree mode on the PR head branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2912,7 +3168,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
fs.writeFileSync(path.join(repoDir, "hooked.txt"), "hooked\n");
fs.writeFileSync(
path.join(repoDir, ".git", "hooks", "pre-commit"),
'#!/bin/sh\necho "hook: start" >&2\nsleep 1\necho "hook: end" >&2\n',
'#!/bin/sh\necho "hook: start" >&2\nsleep 0.05\necho "hook: end" >&2\n',
{ mode: 0o755 },
);
@@ -3089,7 +3345,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect.objectContaining({
kind: "phase_started",
phase: "pr",
label: "Creating GitHub pull request...",
label: "Creating pull request...",
}),
]);
}),
@@ -1,55 +1,96 @@
import { randomUUID } from "node:crypto";
import { realpathSync } from "node:fs";
import {
Array as Arr,
Cache,
Context,
DateTime,
Duration,
Effect,
Exit,
FileSystem,
Layer,
Option,
Order,
Path,
Ref,
Result,
} from "effect";
import {
GitActionProgressEvent,
GitActionProgressPhase,
GitCommandError,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStackedAction,
type GitStatusLocalResult,
type GitStatusRemoteResult,
VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
VcsStatusResult,
ModelSelection,
} from "@t3tools/contracts";
import {
detectGitHostingProviderFromRemoteUrl,
detectSourceControlProviderFromGitRemoteUrl,
mergeGitStatusParts,
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
sanitizeFeatureBranchName,
} from "@t3tools/shared/git";
import {
getChangeRequestTerminologyForKind,
type ChangeRequestTerminology,
} from "@t3tools/shared/sourceControl";
import { GitManagerError } from "@t3tools/contracts";
import {
GitManager,
type GitActionProgressReporter,
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { GitCore } from "../Services/GitCore.ts";
import type { GitStatusDetails } from "../Services/GitCore.ts";
import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { TextGeneration } from "../textGeneration/TextGeneration.ts";
import { ProjectSetupScriptRunner } from "../project/Services/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
import {
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "../githubPullRequests.ts";
import { GitVcsDriver, type GitStatusDetails } from "../vcs/GitVcsDriver.ts";
import { SourceControlProviderRegistry } from "../sourceControl/SourceControlProviderRegistry.ts";
import type { ChangeRequest } from "@t3tools/contracts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}
export interface GitRunStackedActionOptions {
readonly actionId?: string;
readonly progressReporter?: GitActionProgressReporter;
}
export interface GitManagerShape {
readonly status: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
readonly localStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
readonly remoteStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
readonly resolvePullRequest: (
input: GitPullRequestRefInput,
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
readonly preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
}
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
"t3/git/GitManager",
) {}
const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
@@ -75,9 +116,14 @@ interface OpenPrInfo {
interface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo {
state: "open" | "closed" | "merged";
updatedAt: string | null;
updatedAt: Option.Option<DateTime.Utc>;
}
const pullRequestUpdatedAtDescOrder: Order.Order<PullRequestInfo> = Order.mapInput(
Order.flip(Option.makeOrder(DateTime.Order)),
(pullRequest) => pullRequest.updatedAt,
);
interface ResolvedPullRequest {
number: number;
title: string;
@@ -88,9 +134,9 @@ interface ResolvedPullRequest {
}
interface PullRequestHeadRemoteInfo {
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
isCrossRepository?: boolean | undefined;
headRepositoryNameWithOwner?: string | null | undefined;
headRepositoryOwnerLogin?: string | null | undefined;
}
interface BranchHeadContext {
@@ -256,7 +302,7 @@ function matchesBranchHeadContext(
return true;
}
function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
return {
number: summary.number,
title: summary.title,
@@ -264,7 +310,7 @@ function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
baseRefName: summary.baseRefName,
headRefName: summary.headRefName,
state: summary.state ?? "open",
updatedAt: null,
updatedAt: summary.updatedAt,
...(summary.isCrossRepository !== undefined
? { isCrossRepository: summary.isCrossRepository }
: {}),
@@ -311,13 +357,14 @@ function withDescription(title: string, description: string | undefined) {
function summarizeGitActionResult(
result: Pick<GitRunStackedActionResult, "commit" | "push" | "pr">,
terms: ChangeRequestTerminology,
): {
title: string;
description?: string;
} {
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
const title = `${result.pr.status === "created" ? "Created" : "Opened"} ${terms.shortLabel}${prNumber}`;
return withDescription(title, truncateText(result.pr.title));
}
@@ -422,16 +469,16 @@ function toStatusPr(pr: PullRequestInfo): {
number: number;
title: string;
url: string;
baseBranch: string;
headBranch: string;
baseRef: string;
headRef: string;
state: "open" | "closed" | "merged";
} {
return {
number: pr.number,
title: pr.title,
url: pr.url,
baseBranch: pr.baseRefName,
headBranch: pr.headRefName,
baseRef: pr.baseRefName,
headRef: pr.headRefName,
state: pr.state,
};
}
@@ -442,14 +489,6 @@ function normalizePullRequestReference(reference: string): string {
return hashNumber?.[1] ?? trimmed;
}
function canonicalizeExistingPath(value: string): string {
try {
return realpathSync.native(value);
} catch {
return value;
}
}
function toResolvedPullRequest(pr: {
number: number;
title: string;
@@ -475,9 +514,9 @@ function shouldPreferSshRemote(url: string | null): boolean {
}
function toPullRequestHeadRemoteInfo(pr: {
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
isCrossRepository?: boolean | undefined;
headRepositoryNameWithOwner?: string | null | undefined;
headRepositoryOwnerLogin?: string | null | undefined;
}): PullRequestHeadRemoteInfo {
return {
...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
@@ -491,10 +530,12 @@ function toPullRequestHeadRemoteInfo(pr: {
}
export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const gitCore = yield* GitCore;
const gitHubCli = yield* GitHubCli;
const gitCore = yield* GitVcsDriver;
const sourceControlProviders = yield* SourceControlProviderRegistry;
const textGeneration = yield* TextGeneration;
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
const serverSettingsService = yield* ServerSettingsService;
const createProgressEmitter = (
@@ -527,11 +568,27 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
localBranch = pullRequest.headBranch,
) {
const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
if (repositoryNameWithOwner.length === 0 && pullRequest.isCrossRepository !== true) {
const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
yield* gitCore.fetchRemoteTrackingBranch({
cwd,
remoteName,
remoteBranch: pullRequest.headBranch,
});
yield* gitCore.setBranchUpstream({
cwd,
branch: localBranch,
remoteName,
remoteBranch: pullRequest.headBranch,
});
return;
}
if (repositoryNameWithOwner.length === 0) {
return;
}
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
@@ -547,6 +604,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
url: remoteUrl,
});
yield* gitCore.fetchRemoteTrackingBranch({
cwd,
remoteName,
remoteBranch: pullRequest.headBranch,
});
yield* gitCore.setBranchUpstream({
cwd,
branch: localBranch,
@@ -586,7 +648,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return;
}
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
@@ -635,7 +697,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const path = yield* Path.Path;
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd);
const canonicalizeExistingPath = (value: string) =>
fileSystem.realPath(value).pipe(Effect.catch(() => Effect.succeed(value)));
const normalizeStatusCacheKey = canonicalizeExistingPath;
const nonRepositoryStatusDetails = {
isRepo: false,
hasOriginRemote: false,
@@ -647,6 +711,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
} satisfies GitStatusDetails;
const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
const details = yield* gitCore
@@ -660,20 +725,22 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return {
isRepo: details.isRepo,
...(hostingProvider ? { hostingProvider } : {}),
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),
hasPrimaryRemote: details.hasOriginRemote,
isDefaultRef: details.isDefaultBranch,
refName: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
} satisfies GitStatusLocalResult;
} satisfies VcsStatusLocalResult;
});
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
capacity: STATUS_RESULT_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
const invalidateLocalStatusResultCache = (cwd: string) =>
Cache.invalidate(localStatusResultCache, normalizeStatusCacheKey(cwd));
normalizeStatusCacheKey(cwd).pipe(
Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),
);
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
const details = yield* gitCore
.statusDetails(cwd)
@@ -688,7 +755,13 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
branch: details.branch,
upstreamRef: details.upstreamRef,
}).pipe(
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
Effect.map((latest) => {
if (!latest) return null;
// On the default branch, only surface open PRs.
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
if (details.isDefaultBranch && latest.state !== "open") return null;
return toStatusPr(latest);
}),
Effect.catch(() => Effect.succeed(null)),
)
: null;
@@ -697,15 +770,18 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
aheadOfDefaultCount: details.aheadOfDefaultCount,
pr,
} satisfies GitStatusRemoteResult;
} satisfies VcsStatusRemoteResult;
});
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
capacity: STATUS_RESULT_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
const invalidateRemoteStatusResultCache = (cwd: string) =>
Cache.invalidate(remoteStatusResultCache, normalizeStatusCacheKey(cwd));
normalizeStatusCacheKey(cwd).pipe(
Effect.flatMap((cacheKey) => Cache.invalidate(remoteStatusResultCache, cacheKey)),
);
const readConfigValueNullable = (cwd: string, key: string) =>
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
@@ -722,7 +798,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
return remoteUrl ? detectGitHostingProviderFromRemoteUrl(remoteUrl) : null;
return remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;
});
const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
@@ -827,9 +903,10 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
>,
) {
for (const headSelector of headContext.headSelectors) {
const pullRequests = yield* gitHubCli.listOpenPullRequests({
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
cwd,
headSelector,
state: "open",
limit: 1,
});
const normalizedPullRequests = pullRequests.map(toPullRequestInfo);
@@ -845,7 +922,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
baseRefName: firstPullRequest.baseRefName,
headRefName: firstPullRequest.headRefName,
state: "open",
updatedAt: null,
updatedAt: Option.none(),
} satisfies PullRequestInfo;
}
}
@@ -861,46 +938,14 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const parsedByNumber = new Map<number, PullRequestInfo>();
for (const headSelector of headContext.headSelectors) {
const stdout = yield* gitHubCli
.execute({
cwd,
args: [
"pr",
"list",
"--head",
headSelector,
"--state",
"all",
"--limit",
"20",
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
})
.pipe(Effect.map((result) => result.stdout));
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
cwd,
headSelector,
state: "all",
limit: 20,
});
const raw = stdout.trim();
if (raw.length === 0) {
continue;
}
const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
gitManagerError(
"findLatestPr",
`GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
decoded.failure,
),
);
}
return Effect.succeed(decoded.success);
}),
);
for (const pr of pullRequests) {
for (const pr of pullRequests.map(toPullRequestInfo)) {
if (!matchesBranchHeadContext(pr, headContext)) {
continue;
}
@@ -908,11 +953,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
}
}
const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => {
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
return right - left;
});
const parsed = Arr.sort(parsedByNumber.values(), pullRequestUpdatedAtDescOrder);
const latestOpenPr = parsed.find((pr) => pr.state === "open");
if (latestOpenPr) {
@@ -925,7 +966,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
cwd: string,
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
) {
const summary = summarizeGitActionResult(result);
const terms = yield* sourceControlProvider(cwd).pipe(
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
);
const summary = summarizeGitActionResult(result, terms);
let latestOpenPr: PullRequestInfo | null = null;
let currentBranchIsDefault = false;
let finalBranchContext: {
@@ -990,7 +1035,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
result.pr.status === "opened_existing")
? {
kind: "open_pr" as const,
label: "View PR",
label: `View ${terms.shortLabel}`,
url: openPr.url,
}
: (result.action === "push" || result.action === "commit_push") &&
@@ -998,7 +1043,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
!currentBranchIsDefault
? {
kind: "run_action" as const,
label: "Create PR",
label: `Create ${terms.shortLabel}`,
action: { kind: "create_pr" as const },
}
: {
@@ -1029,11 +1074,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
}
}
const defaultFromGh = yield* gitHubCli
.getDefaultBranch({ cwd })
.pipe(Effect.catch(() => Effect.succeed(null)));
if (defaultFromGh) {
return defaultFromGh;
const defaultFromProvider = yield* sourceControlProvider(cwd).pipe(
Effect.flatMap((provider) => provider.getDefaultBranch({ cwd })),
Effect.catch(() => Effect.succeed(null)),
);
if (defaultFromProvider) {
return defaultFromProvider;
}
return "main";
@@ -1205,6 +1251,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
fallbackBranch: string | null,
emit: GitActionProgressEmitter,
) {
const provider = yield* sourceControlProvider(cwd);
const terms = getChangeRequestTerminologyForKind(provider.kind);
const details = yield* gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
@@ -1241,7 +1289,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
yield* emit({
kind: "phase_started",
phase: "pr",
label: "Generating PR content...",
label: `Generating ${terms.shortLabel} content...`,
});
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
@@ -1266,12 +1314,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
yield* emit({
kind: "phase_started",
phase: "pr",
label: "Creating GitHub pull request...",
label: `Creating ${terms.singular}...`,
});
yield* gitHubCli
.createPullRequest({
yield* provider
.createChangeRequest({
cwd,
baseBranch,
baseRefName: baseBranch,
headSelector: headContext.preferredHeadSelector,
title: generated.title,
bodyFile,
@@ -1299,11 +1347,13 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
});
const localStatus: GitManagerShape["localStatus"] = Effect.fn("localStatus")(function* (input) {
return yield* Cache.get(localStatusResultCache, normalizeStatusCacheKey(input.cwd));
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
return yield* Cache.get(localStatusResultCache, cacheKey);
});
const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")(
function* (input) {
return yield* Cache.get(remoteStatusResultCache, normalizeStatusCacheKey(input.cwd));
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
return yield* Cache.get(remoteStatusResultCache, cacheKey);
},
);
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
@@ -1329,8 +1379,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
function* (input) {
const pullRequest = yield* gitHubCli
.getPullRequest({
const pullRequest = yield* (yield* sourceControlProvider(input.cwd))
.getChangeRequest({
cwd: input.cwd,
reference: normalizePullRequestReference(input.reference),
})
@@ -1363,15 +1413,15 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
};
return yield* Effect.gen(function* () {
const normalizedReference = normalizePullRequestReference(input.reference);
const rootWorktreePath = canonicalizeExistingPath(input.cwd);
const pullRequestSummary = yield* gitHubCli.getPullRequest({
const rootWorktreePath = yield* canonicalizeExistingPath(input.cwd);
const pullRequestSummary = yield* (yield* sourceControlProvider(input.cwd)).getChangeRequest({
cwd: input.cwd,
reference: normalizedReference,
});
const pullRequest = toResolvedPullRequest(pullRequestSummary);
if (input.mode === "local") {
yield* gitHubCli.checkoutPullRequest({
yield* (yield* sourceControlProvider(input.cwd)).checkoutChangeRequest({
cwd: input.cwd,
reference: normalizedReference,
force: true,
@@ -1413,33 +1463,35 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
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 findLocalHeadBranch = Effect.fn("findLocalHeadBranch")(function* (cwd: string) {
const result = yield* gitCore.listRefs({ cwd });
const localBranch = result.refs.find(
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
);
if (localBranch) {
return localBranch;
}
if (localPullRequestBranch === pullRequest.headBranch) {
return null;
}
for (const branch of result.refs) {
if (branch.isRemote || branch.name !== pullRequest.headBranch || !branch.worktreePath) {
continue;
}
const worktreePath = yield* canonicalizeExistingPath(branch.worktreePath);
if (worktreePath !== rootWorktreePath) {
return branch;
}
}
return null;
});
const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd);
const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath
? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
? yield* canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
: null;
if (
existingBranchBeforeFetch?.worktreePath &&
@@ -1467,7 +1519,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd);
const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath
? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
? yield* canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
: null;
if (
existingBranchAfterFetch?.worktreePath &&
@@ -1489,7 +1541,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const worktree = yield* gitCore.createWorktree({
cwd: input.cwd,
branch: localPullRequestBranch,
refName: localPullRequestBranch,
path: null,
});
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
@@ -1497,7 +1549,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return {
pullRequest,
branch: worktree.worktree.branch,
branch: worktree.worktree.refName,
worktreePath: worktree.worktree.path,
};
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
@@ -1529,8 +1581,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
yield* gitCore.createRef({ cwd, refName: resolvedBranch });
yield* Effect.scoped(gitCore.switchRef({ cwd, refName: resolvedBranch }));
return {
branchStep: { status: "created" as const, name: resolvedBranch },
@@ -1564,12 +1616,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
"Feature-branch checkout is only supported for commit actions.",
);
}
if (input.action === "push" && initialStatus.hasWorkingTreeChanges) {
return yield* gitManagerError(
"runStackedAction",
"Commit or stash local changes before pushing.",
);
}
if (input.action === "create_pr" && initialStatus.hasWorkingTreeChanges) {
return yield* gitManagerError(
"runStackedAction",
@@ -1633,6 +1679,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const currentBranch = branchStep.name ?? initialStatus.branch;
const commitAction = isCommitAction(input.action) ? input.action : null;
const changeRequestTerms = wantsPr
? yield* sourceControlProvider(input.cwd).pipe(
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
)
: null;
const commit = commitAction
? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
@@ -1670,7 +1722,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
.emit({
kind: "phase_started",
phase: "pr",
label: "Preparing PR...",
label: `Preparing ${changeRequestTerms?.shortLabel ?? "PR"}...`,
})
.pipe(
Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))),
@@ -1731,4 +1783,4 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
} satisfies GitManagerShape;
});
export const GitManagerLive = Layer.effect(GitManager, makeGitManager());
export const layer = Layer.effect(GitManager, makeGitManager());
@@ -0,0 +1,132 @@
import { assert, describe, it, vi } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as GitManager from "./GitManager.ts";
import * as GitWorkflowService from "./GitWorkflowService.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
function makeLayer(input: { readonly detect: VcsDriverRegistry.VcsDriverRegistryShape["detect"] }) {
return GitWorkflowService.layer.pipe(
Layer.provide(
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
detect: input.detect,
}),
),
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
Layer.provide(Layer.mock(GitManager.GitManager)({})),
);
}
describe("GitWorkflowService", () => {
it.effect("returns an empty local status when no VCS repository is detected", () =>
Effect.gen(function* () {
const workflow = yield* GitWorkflowService.GitWorkflowService;
const status = yield* workflow.localStatus({ cwd: "/not-a-repo" });
assert.deepStrictEqual(status, {
isRepo: false,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
});
}).pipe(
Effect.provide(
makeLayer({
detect: () => Effect.succeed(null),
}),
),
),
);
it.effect("returns an empty full status when no VCS repository is detected", () =>
Effect.gen(function* () {
const workflow = yield* GitWorkflowService.GitWorkflowService;
const status = yield* workflow.status({ cwd: "/not-a-repo" });
assert.deepStrictEqual(status, {
isRepo: false,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
});
}).pipe(
Effect.provide(
makeLayer({
detect: () => Effect.succeed(null),
}),
),
),
);
it.effect("does not call GitManager status methods when no VCS repository is detected", () => {
const localStatus = vi.fn();
const remoteStatus = vi.fn();
const status = vi.fn();
const testLayer = GitWorkflowService.layer.pipe(
Layer.provide(
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
detect: () => Effect.succeed(null),
}),
),
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
Layer.provide(
Layer.mock(GitManager.GitManager)({
localStatus,
remoteStatus,
status,
}),
),
);
return Effect.gen(function* () {
const workflow = yield* GitWorkflowService.GitWorkflowService;
yield* workflow.localStatus({ cwd: "/not-a-repo" });
yield* workflow.remoteStatus({ cwd: "/not-a-repo" });
yield* workflow.status({ cwd: "/not-a-repo" });
assert.equal(localStatus.mock.calls.length, 0);
assert.equal(remoteStatus.mock.calls.length, 0);
assert.equal(status.mock.calls.length, 0);
}).pipe(Effect.provide(testLayer));
});
it.effect("returns an empty ref list when no VCS repository is detected", () =>
Effect.gen(function* () {
const workflow = yield* GitWorkflowService.GitWorkflowService;
const refs = yield* workflow.listRefs({ cwd: "/not-a-repo" });
assert.deepStrictEqual(refs, {
refs: [],
isRepo: false,
hasPrimaryRemote: false,
nextCursor: null,
totalCount: 0,
});
}).pipe(
Effect.provide(
makeLayer({
detect: () => Effect.succeed(null),
}),
),
),
);
});
+314
View File
@@ -0,0 +1,314 @@
import { Context, Effect, Layer } from "effect";
import {
GitManagerError,
GitCommandError,
type VcsSwitchRefInput,
type VcsSwitchRefResult,
type VcsCreateRefInput,
type VcsCreateRefResult,
type VcsCreateWorktreeInput,
type VcsCreateWorktreeResult,
type VcsListRefsInput,
type VcsListRefsResult,
type GitManagerServiceError,
type GitPreparePullRequestThreadInput,
type GitPreparePullRequestThreadResult,
type GitPullRequestRefInput,
type VcsPullResult,
type VcsRemoveWorktreeInput,
type GitResolvePullRequestResult,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
type VcsStatusResult,
} from "@t3tools/contracts";
import { GitManager, type GitRunStackedActionOptions } from "./GitManager.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
export interface GitWorkflowServiceShape {
readonly status: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
readonly localStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
readonly remoteStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
readonly resolvePullRequest: (
input: GitPullRequestRefInput,
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
readonly preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
readonly createWorktree: (
input: VcsCreateWorktreeInput,
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
readonly createRef: (
input: VcsCreateRefInput,
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
readonly switchRef: (
input: VcsSwitchRefInput,
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
readonly renameBranch: (input: {
readonly cwd: string;
readonly oldBranch: string;
readonly newBranch: string;
}) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
}
export class GitWorkflowService extends Context.Service<
GitWorkflowService,
GitWorkflowServiceShape
>()("t3/git/GitWorkflowService") {}
const unsupportedGitWorkflow = (operation: string, cwd: string, detail: string) =>
new GitManagerError({
operation,
detail: `${detail} (${cwd})`,
});
const unsupportedGitCommand = (operation: string, cwd: string, detail: string) =>
new GitCommandError({
operation,
command: "vcs-route",
cwd,
detail,
});
function nonRepositoryLocalStatus(): VcsStatusLocalResult {
return {
isRepo: false,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
};
}
function nonRepositoryStatus(): VcsStatusResult {
return {
...nonRepositoryLocalStatus(),
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
};
}
function nonRepositoryListRefs(): VcsListRefsResult {
return {
refs: [],
isRepo: false,
hasPrimaryRemote: false,
nextCursor: null,
totalCount: 0,
};
}
export const make = Effect.fn("makeGitWorkflowService")(function* () {
const registry = yield* VcsDriverRegistry;
const git = yield* GitVcsDriver;
const gitManager = yield* GitManager;
const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
operation: string,
cwd: string,
) {
const handle = yield* registry
.resolve({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
operation,
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (handle.kind !== "git") {
return yield* unsupportedGitWorkflow(
operation,
cwd,
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
);
}
});
const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
operation: string,
cwd: string,
) {
const handle = yield* registry
.resolve({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitCommand(
operation,
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (handle.kind !== "git") {
return yield* unsupportedGitCommand(
operation,
cwd,
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
);
}
});
const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
function* (operation: string, cwd: string) {
const handle = yield* registry
.detect({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
operation,
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (!handle) {
return false;
}
if (handle.kind !== "git") {
return yield* unsupportedGitWorkflow(
operation,
cwd,
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
);
}
return true;
},
);
const detectGitRepositoryForCommand = Effect.fn(
"GitWorkflowService.detectGitRepositoryForCommand",
)(function* (operation: string, cwd: string) {
const handle = yield* registry
.detect({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitCommand(
operation,
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (!handle) {
return false;
}
if (handle.kind !== "git") {
return yield* unsupportedGitCommand(
operation,
cwd,
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
);
}
return true;
});
const routeGitManager =
<Input extends { readonly cwd: string }, Output>(
operation: string,
run: (input: Input) => Effect.Effect<Output, GitManagerServiceError>,
) =>
(input: Input) =>
ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
return GitWorkflowService.of({
status: (input) =>
detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),
),
),
localStatus: (input) =>
detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository
? gitManager.localStatus(input)
: Effect.succeed(nonRepositoryLocalStatus()),
),
),
remoteStatus: (input) =>
detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository ? gitManager.remoteStatus(input) : Effect.succeed(null),
),
),
invalidateLocalStatus: gitManager.invalidateLocalStatus,
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
invalidateStatus: gitManager.invalidateStatus,
pullCurrentBranch: (cwd) =>
ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
Effect.andThen(git.pullCurrentBranch(cwd)),
),
runStackedAction: (input, options) =>
ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
Effect.andThen(gitManager.runStackedAction(input, options)),
),
resolvePullRequest: routeGitManager(
"GitWorkflowService.resolvePullRequest",
gitManager.resolvePullRequest,
),
preparePullRequestThread: routeGitManager(
"GitWorkflowService.preparePullRequestThread",
gitManager.preparePullRequestThread,
),
listRefs: (input) =>
detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
),
),
createWorktree: (input) =>
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
Effect.andThen(git.createWorktree(input)),
),
removeWorktree: (input) =>
ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
Effect.andThen(git.removeWorktree(input)),
),
createRef: (input) =>
ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
Effect.andThen(git.createRef(input)),
),
switchRef: (input) =>
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
Effect.andThen(Effect.scoped(git.switchRef(input))),
),
renameBranch: (input) =>
ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
Effect.andThen(git.renameBranch(input)),
),
});
});
export const layer = Layer.effect(GitWorkflowService, make());
@@ -1,306 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { sanitizeThreadTitle } from "../Utils.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-claude-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeClaudeBinary(dir: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = path.join(dir, "bin");
const claudePath = path.join(binDir, "claude");
yield* fs.makeDirectory(binDir, { recursive: true });
yield* fs.writeFileString(
claudePath,
[
"#!/bin/sh",
'args="$*"',
'stdin_content="$(cat)"',
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then',
' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "args missing expected content" >&2',
" exit 2",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then',
' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then',
' printf "%s\\n" "args contained forbidden content" >&2',
" exit 3",
" fi",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then',
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "stdin missing expected content" >&2',
" exit 4",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
"fi",
'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"',
'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"',
"",
].join("\n"),
);
yield* fs.chmod(claudePath, 0o755);
return binDir;
});
}
function withFakeClaudeEnv<A, E, R>(
input: {
output: string;
exitCode?: number;
stderr?: string;
argsMustContain?: string;
argsMustNotContain?: string;
stdinMustContain?: string;
},
effect: Effect.Effect<A, E, R>,
) {
return Effect.acquireUseRelease(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
const binDir = yield* makeFakeClaudeBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
if (input.exitCode !== undefined) {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
} else {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
}
if (input.stderr !== undefined) {
process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
} else {
delete process.env.T3_FAKE_CLAUDE_STDERR;
}
if (input.argsMustContain !== undefined) {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
} else {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
}
if (input.argsMustNotContain !== undefined) {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
} else {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
}
if (input.stdinMustContain !== undefined) {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
} else {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
}
});
return {
previousPath,
previousOutput,
previousExitCode,
previousStderr,
previousArgsMustContain,
previousArgsMustNotContain,
previousStdinMustContain,
};
}),
() => effect,
(previous) =>
Effect.sync(() => {
process.env.PATH = previous.previousPath;
if (previous.previousOutput === undefined) {
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
} else {
process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;
}
if (previous.previousExitCode === undefined) {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
} else {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;
}
if (previous.previousStderr === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDERR;
} else {
process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;
}
if (previous.previousArgsMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;
}
if (previous.previousArgsMustNotContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;
}
if (previous.previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
}
}),
);
}
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
subject: "Add important change",
body: "",
},
}),
argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
argsMustNotContain: "--effort",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/claude-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
...createModelSelection("claudeAgent", "claude-haiku-4-5", [
{ id: "thinking", value: false },
{ id: "effort", value: "high" },
]),
},
});
expect(generated.subject).toBe("Add important change");
}),
),
);
it.effect("forwards Claude fast mode and supported effort", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title: "Improve orchestration flow",
body: "Body",
},
}),
argsMustContain: '--effort max --settings {"fastMode":true}',
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/claude-effect",
commitSummary: "Improve orchestration",
diffSummary: "1 file changed",
diffPatch: "diff --git a/README.md b/README.md",
modelSelection: {
...createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "effort", value: "max" },
{ id: "fastMode", value: true },
]),
},
});
expect(generated.title).toBe("Improve orchestration flow");
}),
),
);
it.effect("generates thread titles through the Claude provider", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title:
' "Reconnect failures after restart because the session state does not recover" ',
},
}),
stdinMustContain: "You write concise thread titles for coding conversations.",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate reconnect failures after restarting the session.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe(
sanitizeThreadTitle(
'"Reconnect failures after restart because the session state does not recover"',
),
);
}),
),
);
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title: ' """ """ ',
},
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe("New thread");
}),
),
);
});
@@ -1,297 +0,0 @@
import * as path from "node:path";
import * as os from "node:os";
import { fileURLToPath } from "node:url";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { ServerSettingsError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
const binDir = path.join(dir, "bin");
const agentPath = path.join(binDir, "agent");
mkdirSync(binDir, { recursive: true });
writeFileSync(
agentPath,
[
"#!/bin/sh",
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
'if [ "$1" != "acp" ]; then',
' printf "%s\\n" "unexpected args: $*" >&2',
" exit 11",
"fi",
`exec bun ${JSON.stringify(mockAgentPath)}`,
"",
].join("\n"),
"utf8",
);
chmodSync(agentPath, 0o755);
return agentPath;
}
function withFakeAcpAgent<A, E, R>(
env: Record<string, string>,
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {
return Effect.gen(function* () {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));
const agentPath = makeAcpAgentWrapper(tempDir, env);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
cursor: {
binaryPath: agentPath,
},
},
});
return yield* effect.pipe(
Effect.ensuring(
serverSettings
.updateSettings({
providers: {
cursor: {
binaryPath: previousSettings.providers.cursor.binaryPath,
},
},
})
.pipe(
Effect.catch(() => Effect.void),
Effect.ensuring(
Effect.sync(() => {
rmSync(tempDir, { recursive: true, force: true });
}),
),
Effect.asVoid,
),
),
);
});
}
function waitForFileContent(path: string): Effect.Effect<string> {
return Effect.promise(async () => {
const deadline = Date.now() + 5_000;
for (;;) {
try {
return readFileSync(path, "utf8");
} catch (error) {
if (Date.now() >= deadline) {
throw error instanceof Error ? error : new Error(String(error));
}
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
});
}
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
return withFakeAcpAgent(
{
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Add generated commit message",
body: "- verify cursor acp model config path",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-text-generation",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
...createModelSelection("cursor", "gpt-5.4", [
{ id: "reasoning", value: "xhigh" },
{ id: "fastMode", value: true },
{ id: "contextWindow", value: "1m" },
]),
},
});
expect(generated.subject).toBe("Add generated commit message");
expect(generated.body).toBe("- verify cursor acp model config path");
const requests = readFileSync(requestLogPath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
expect(
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
).toMatchObject({
_meta: {
parameterizedModelPicker: true,
},
});
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "model" &&
request.params?.value === "gpt-5.4",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "reasoning" &&
request.params?.value === "extra-high",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "context" &&
request.params?.value === "1m",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "fast" &&
request.params?.value === "true",
),
).toBe(true);
expect(
requests.find((request) => request.method === "session/prompt")?.params?.prompt,
).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: "text",
text: expect.stringContaining("Staged patch:"),
}),
]),
);
rmSync(requestLogDir, { recursive: true, force: true });
}),
);
});
it.effect("accepts json objects with extra assistant text around them", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT:
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-noisy-json",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
expect(generated.body).toBe("");
}),
),
);
it.effect("generates thread titles through Cursor ACP text generation", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
title: '"Trim reconnect spinner status after resume."',
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Fix the reconnect spinner after a resumed session.",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
}),
),
);
it.effect("closes the ACP child process after text generation completes", () => {
const exitLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-"));
const exitLogPath = path.join(exitLogDir, "exit.log");
return withFakeAcpAgent(
{
T3_ACP_EXIT_LOG_PATH: exitLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Close runtime after generation",
body: "",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-runtime-close",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Close runtime after generation");
const exitLog = yield* waitForFileContent(exitLogPath);
expect(exitLog).toContain("exit:0");
rmSync(exitLogDir, { recursive: true, force: true });
}),
);
});
});
File diff suppressed because it is too large. Load diff
@@ -1,227 +0,0 @@
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.ts";
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("trims pull request fields decoded from gh json", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: JSON.stringify({
number: 42,
title: " Add PR thread creation \n",
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
baseRefName: " main ",
headRefName: "\tfeature/pr-threads\t",
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",
});
}),
);
it.effect("skips invalid entries when parsing pr lists", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: JSON.stringify([
{
number: 0,
title: "invalid",
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
baseRefName: "main",
headRefName: "feature/invalid",
},
{
number: 43,
title: " Valid PR ",
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
baseRefName: " main ",
headRefName: " feature/pr-list ",
headRepository: {
nameWithOwner: " ",
},
headRepositoryOwner: {
login: " ",
},
},
]),
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.listOpenPullRequests({
cwd: "/repo",
headSelector: "feature/pr-list",
});
});
assert.deepStrictEqual(result, [
{
number: 43,
title: "Valid PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/43",
baseRefName: "main",
headRefName: "feature/pr-list",
state: "open",
},
]);
}),
);
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);
}),
);
});
-240
View File
@@ -1,240 +0,0 @@
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import { runProcess } from "../../processRunner.ts";
import { GitHubCliError } from "@t3tools/contracts";
import {
GitHubCli,
type GitHubRepositoryCloneUrls,
type GitHubCliShape,
} from "../Services/GitHubCli.ts";
import {
decodeGitHubPullRequestJson,
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "../githubPullRequests.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError {
if (error instanceof Error) {
if (error.message.includes("Command not found: gh")) {
return new GitHubCliError({
operation,
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: error,
});
}
const lower = error.message.toLowerCase();
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("gh auth login") ||
lower.includes("no oauth token")
) {
return new GitHubCliError({
operation,
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
cause: error,
});
}
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}`,
cause: error,
});
}
return new GitHubCliError({
operation,
detail: "GitHub CLI command failed.",
cause: error,
});
}
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
nameWithOwner: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
sshUrl: TrimmedNonEmptyString,
});
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: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
cause: error,
}),
),
);
}
const makeGitHubCli = Effect.sync(() => {
const execute: GitHubCliShape["execute"] = (input) =>
Effect.tryPromise({
try: () =>
runProcess("gh", input.args, {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
}),
catch: (error) => normalizeGitHubCliError("execute", error),
});
const service = {
execute,
listOpenPullRequests: (input) =>
execute({
cwd: input.cwd,
args: [
"pr",
"list",
"--head",
input.headSelector,
"--state",
"open",
"--limit",
String(input.limit ?? 1),
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubCliError({
operation: "listOpenPullRequests",
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
}
return Effect.succeed(
decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
);
}),
),
),
),
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) =>
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubCliError({
operation: "getPullRequest",
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
}
return Effect.succeed(
(({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
);
}),
),
),
),
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({
cwd: input.cwd,
args: [
"pr",
"create",
"--base",
input.baseBranch,
"--head",
input.headSelector,
"--title",
input.title,
"--body-file",
input.bodyFile,
],
}).pipe(Effect.asVoid),
getDefaultBranch: (input) =>
execute({
cwd: input.cwd,
args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
}).pipe(
Effect.map((value) => {
const trimmed = value.stdout.trim();
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;
});
export const GitHubCliLive = Layer.effect(GitHubCli, makeGitHubCli);
@@ -1,311 +0,0 @@
import { realpathSync } from "node:fs";
import {
Duration,
Effect,
Exit,
Fiber,
Layer,
PubSub,
Ref,
Scope,
Stream,
SynchronizedRef,
} from "effect";
import type {
GitStatusInput,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
import { mergeGitStatusParts } from "@t3tools/shared/git";
import {
GitStatusBroadcaster,
type GitStatusBroadcasterShape,
} from "../Services/GitStatusBroadcaster.ts";
import { GitManager } from "../Services/GitManager.ts";
const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
interface GitStatusChange {
readonly cwd: string;
readonly event: GitStatusStreamEvent;
}
interface CachedValue<T> {
readonly fingerprint: string;
readonly value: T;
}
interface CachedGitStatus {
readonly local: CachedValue<GitStatusLocalResult> | null;
readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
}
interface ActiveRemotePoller {
readonly fiber: Fiber.Fiber<void, never>;
readonly subscriberCount: number;
}
function normalizeCwd(cwd: string): string {
try {
return realpathSync.native(cwd);
} catch {
return cwd;
}
}
function fingerprintStatusPart(status: unknown): string {
return JSON.stringify(status);
}
export const GitStatusBroadcasterLive = Layer.effect(
GitStatusBroadcaster,
Effect.gen(function* () {
const gitManager = yield* GitManager;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<GitStatusChange>(),
(pubsub) => PubSub.shutdown(pubsub),
);
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
);
const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
const getCachedStatus = Effect.fn("getCachedStatus")(function* (cwd: string) {
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
});
const updateCachedLocalStatus = Effect.fn("updateCachedLocalStatus")(function* (
cwd: string,
local: GitStatusLocalResult,
options?: { publish?: boolean },
) {
const nextLocal = {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<GitStatusLocalResult>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
local: nextLocal,
});
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "localUpdated",
local,
},
});
}
return local;
});
const updateCachedRemoteStatus = Effect.fn("updateCachedRemoteStatus")(function* (
cwd: string,
remote: GitStatusRemoteResult | null,
options?: { publish?: boolean },
) {
const nextRemote = {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<GitStatusRemoteResult | null>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
remote: nextRemote,
});
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "remoteUpdated",
remote,
},
});
}
return remote;
});
const loadLocalStatus = Effect.fn("loadLocalStatus")(function* (cwd: string) {
const local = yield* gitManager.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local);
});
const loadRemoteStatus = Effect.fn("loadRemoteStatus")(function* (cwd: string) {
const remote = yield* gitManager.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote);
});
const getOrLoadLocalStatus = Effect.fn("getOrLoadLocalStatus")(function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.local) {
return cached.local.value;
}
return yield* loadLocalStatus(cwd);
});
const getOrLoadRemoteStatus = Effect.fn("getOrLoadRemoteStatus")(function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.remote) {
return cached.remote.value;
}
return yield* loadRemoteStatus(cwd);
});
const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* (
input: GitStatusInput,
) {
const normalizedCwd = normalizeCwd(input.cwd);
const [local, remote] = yield* Effect.all([
getOrLoadLocalStatus(normalizedCwd),
getOrLoadRemoteStatus(normalizedCwd),
]);
return mergeGitStatusParts(local, remote);
});
const refreshLocalStatus: GitStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
"refreshLocalStatus",
)(function* (cwd) {
const normalizedCwd = normalizeCwd(cwd);
yield* gitManager.invalidateLocalStatus(normalizedCwd);
const local = yield* gitManager.localStatus({ cwd: normalizedCwd });
return yield* updateCachedLocalStatus(normalizedCwd, local, { publish: true });
});
const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) {
yield* gitManager.invalidateRemoteStatus(cwd);
const remote = yield* gitManager.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
});
const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
function* (cwd) {
const normalizedCwd = normalizeCwd(cwd);
const [local, remote] = yield* Effect.all([
refreshLocalStatus(normalizedCwd),
refreshRemoteStatus(normalizedCwd),
]);
return mergeGitStatusParts(local, remote);
},
);
const makeRemoteRefreshLoop = (cwd: string) => {
const logRefreshFailure = (error: Error) =>
Effect.logWarning("git remote status refresh failed", {
cwd,
detail: error.message,
});
return refreshRemoteStatus(cwd).pipe(
Effect.catch(logRefreshFailure),
Effect.andThen(
Effect.forever(
Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
),
),
),
);
};
const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) {
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (existing) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount + 1,
});
return Effect.succeed([undefined, nextPollers] as const);
}
return makeRemoteRefreshLoop(cwd).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
fiber,
subscriberCount: 1,
});
return [undefined, nextPollers] as const;
}),
);
});
});
const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) {
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (!existing) {
return [null, activePollers] as const;
}
if (existing.subscriberCount > 1) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount - 1,
});
return [null, nextPollers] as const;
}
const nextPollers = new Map(activePollers);
nextPollers.delete(cwd);
return [existing.fiber, nextPollers] as const;
});
if (pollerToInterrupt) {
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
}
});
const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
Stream.unwrap(
Effect.gen(function* () {
const normalizedCwd = normalizeCwd(input.cwd);
const subscription = yield* PubSub.subscribe(changesPubSub);
const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd);
const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null;
yield* retainRemotePoller(normalizedCwd);
const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid);
return Stream.concat(
Stream.make({
_tag: "snapshot" as const,
local: initialLocal,
remote: initialRemote,
}),
Stream.fromSubscription(subscription).pipe(
Stream.filter((event) => event.cwd === normalizedCwd),
Stream.map((event) => event.event),
),
).pipe(Stream.ensuring(release));
}),
);
return {
getStatus,
refreshLocalStatus,
refreshStatus,
streamStatus,
} satisfies GitStatusBroadcasterShape;
}),
);
@@ -1,340 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Duration, Effect, Layer } from "effect";
import { TestClock } from "effect/testing";
import { NetService } from "@t3tools/shared/Net";
import { beforeEach, expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../../provider/opencodeRuntime.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
const runtimeMock = {
state: {
startCalls: [] as string[],
promptUrls: [] as string[],
authHeaders: [] as Array<string | null>,
closeCalls: [] as string[],
promptResult: undefined as
| { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
| undefined,
},
reset() {
this.state.startCalls.length = 0;
this.state.promptUrls.length = 0;
this.state.authHeaders.length = 0;
this.state.closeCalls.length = 0;
this.state.promptResult = undefined;
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
startOpenCodeServerProcess: ({ binaryPath }) =>
Effect.gen(function* () {
const index = runtimeMock.state.startCalls.length + 1;
const url = `http://127.0.0.1:${4_300 + index}`;
runtimeMock.state.startCalls.push(binaryPath);
// The production runtime binds server lifetime to the caller's scope.
// Mirror that here so the closeCalls probe observes scope close.
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
runtimeMock.state.closeCalls.push(url);
}),
);
return {
url,
exitCode: Effect.never,
};
}),
connectToOpenCodeServer: ({ serverUrl }) =>
Effect.succeed({
url: serverUrl ?? "http://127.0.0.1:4301",
exitCode: null,
external: Boolean(serverUrl),
}),
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
({
session: {
create: async () => ({ data: { id: `${baseUrl}/session` } }),
prompt: async () => {
runtimeMock.state.promptUrls.push(baseUrl);
runtimeMock.state.authHeaders.push(
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
);
return (
runtimeMock.state.promptResult ?? {
data: {
parts: [
{
type: "text",
text: JSON.stringify({
subject: "Improve OpenCode reuse",
body: "Reuse one server for the full action.",
}),
},
],
},
}
);
},
},
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
loadOpenCodeInventory: () =>
Effect.fail(
new OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
cause: null,
}),
),
};
const DEFAULT_TEST_MODEL_SELECTION = {
provider: "opencode" as const,
model: "openai/gpt-5",
};
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
},
},
}),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-test-",
}),
),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
);
const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
},
},
}),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-existing-server-test-",
}),
),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
);
beforeEach(() => {
runtimeMock.reset();
});
const advanceIdleClock = Effect.gen(function* () {
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
yield* Effect.yieldNow;
});
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:4301",
"http://127.0.0.1:4301",
]);
expect(runtimeMock.state.closeCalls).toEqual([]);
yield* advanceIdleClock;
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("starts a new server after the warm server idles out", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* advanceIdleClock;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:4301",
"http://127.0.0.1:4302",
]);
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = { data: {} };
const textGeneration = yield* TextGeneration;
const error = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("OpenCode returned empty output.");
}),
);
it.effect("parses JSON returned as plain text output", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
parts: [
{
type: "text",
text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
},
],
},
};
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(result).toEqual({
subject: "Tighten OpenCode parsing",
body: "Handle JSON text output locally.",
});
}),
);
it.effect("surfaces the upstream OpenCode structured-output error message", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
info: {
error: {
name: "StructuredOutputError",
data: {
message: "Model did not produce structured output",
retries: 2,
},
},
},
},
};
const textGeneration = yield* TextGeneration;
const error = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("Model did not produce structured output");
}),
);
});
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
"OpenCodeTextGenerationLive with configured server URL",
(it) => {
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual([]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:9999",
"http://127.0.0.1:9999",
]);
expect(runtimeMock.state.authHeaders).toEqual([
`Basic ${btoa("opencode:secret-password")}`,
`Basic ${btoa("opencode:secret-password")}`,
]);
yield* advanceIdleClock;
expect(runtimeMock.state.closeCalls).toEqual([]);
}).pipe(Effect.provide(TestClock.layer())),
);
},
);
@@ -1,104 +0,0 @@
/**
* RoutingTextGeneration – Dispatches text generation requests to either the
* Codex CLI or Claude CLI implementation based on the provider in each
* request input.
*
* When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to
* the Claude layer; for any other value (including the default `undefined`) it
* falls through to the Codex layer.
*
* @module RoutingTextGeneration
*/
import { Effect, Layer, Context } from "effect";
import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
// ---------------------------------------------------------------------------
// Internal service tags so both concrete layers can coexist.
// ---------------------------------------------------------------------------
class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
) {}
class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
) {}
class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CursorTextGen",
) {}
class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen",
) {}
// ---------------------------------------------------------------------------
// Routing implementation
// ---------------------------------------------------------------------------
const makeRoutingTextGeneration = Effect.gen(function* () {
const byProvider = {
codex: yield* CodexTextGen,
claudeAgent: yield* ClaudeTextGen,
cursor: yield* CursorTextGen,
opencode: yield* OpenCodeTextGen,
};
return {
generateCommitMessage: (input) =>
byProvider[input.modelSelection.provider].generateCommitMessage(input),
generatePrContent: (input) =>
byProvider[input.modelSelection.provider].generatePrContent(input),
generateBranchName: (input) =>
byProvider[input.modelSelection.provider].generateBranchName(input),
generateThreadTitle: (input) =>
byProvider[input.modelSelection.provider].generateThreadTitle(input),
} satisfies TextGenerationShape;
});
const InternalCodexLayer = Layer.effect(
CodexTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CodexTextGenerationLive));
const InternalClaudeLayer = Layer.effect(
ClaudeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(ClaudeTextGenerationLive));
const InternalCursorLayer = Layer.effect(
CursorTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CursorTextGenerationLive));
const InternalOpenCodeLayer = Layer.effect(
OpenCodeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(OpenCodeTextGenerationLive));
export const RoutingTextGenerationLive = Layer.effect(
TextGeneration,
makeRoutingTextGeneration,
).pipe(
Layer.provide(InternalCodexLayer),
Layer.provide(InternalClaudeLayer),
Layer.provide(InternalCursorLayer),
Layer.provide(InternalOpenCodeLayer),
);
-313
View File
@@ -1,313 +0,0 @@
/**
* GitCore - Effect service contract for low-level Git operations.
*
* Wraps core repository primitives used by higher-level orchestration
* services and WebSocket routes.
*
* @module GitCore
*/
import { Context } from "effect";
import type { Effect } from "effect";
import type {
GitCheckoutInput,
GitCheckoutResult,
GitCreateBranchInput,
GitCreateBranchResult,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
GitListBranchesInput,
GitListBranchesResult,
GitPullResult,
GitRemoveWorktreeInput,
GitStatusInput,
GitStatusResult,
} from "@t3tools/contracts";
import type { GitCommandError } from "@t3tools/contracts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
readonly progress?: ExecuteGitProgress;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
}
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
upstreamRef: string | null;
}
export interface GitPreparedCommitContext {
stagedSummary: string;
stagedPatch: string;
}
export interface ExecuteGitProgress {
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitProgress {
readonly onOutputLine?: (input: {
stream: "stdout" | "stderr";
text: string;
}) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitOptions {
readonly timeoutMs?: number;
readonly progress?: GitCommitProgress;
}
export interface GitPushResult {
status: "pushed" | "skipped_up_to_date";
branch: string;
upstreamBranch?: string | undefined;
setUpstream?: boolean | undefined;
}
export interface GitRangeContext {
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
export interface GitListWorkspaceFilesResult {
readonly paths: ReadonlyArray<string>;
readonly truncated: boolean;
}
export interface GitRenameBranchInput {
cwd: string;
oldBranch: string;
newBranch: string;
}
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.
*/
export interface GitCoreShape {
/**
* Execute a raw Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
/**
* Read Git status for a repository.
*/
readonly status: (input: GitStatusInput) => Effect.Effect<GitStatusResult, GitCommandError>;
/**
* Read detailed working tree / branch status for a repository.
*/
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
/**
* Read detailed working tree / branch status without refreshing remote tracking refs.
*/
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
/**
* Build staged change context for commit generation.
*/
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
/**
* Create a commit with provided subject/body.
*/
readonly commit: (
cwd: string,
subject: string,
body: string,
options?: GitCommitOptions,
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
/**
* Push current branch, setting upstream if needed.
*/
readonly pushCurrentBranch: (
cwd: string,
fallbackBranch: string | null,
) => Effect.Effect<GitPushResult, GitCommandError>;
/**
* Collect commit/diff context between base branch and current HEAD.
*/
readonly readRangeContext: (
cwd: string,
baseBranch: string,
) => Effect.Effect<GitRangeContext, GitCommandError>;
/**
* Read a Git config value from the local repository.
*/
readonly readConfigValue: (
cwd: string,
key: string,
) => Effect.Effect<string | null, GitCommandError>;
/**
* Determine whether the provided cwd is inside a git work tree.
*/
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, GitCommandError>;
/**
* List tracked and untracked workspace file paths relative to cwd.
*/
readonly listWorkspaceFiles: (
cwd: string,
) => Effect.Effect<GitListWorkspaceFilesResult, GitCommandError>;
/**
* Remove gitignored paths from a relative path list.
*/
readonly filterIgnoredPaths: (
cwd: string,
relativePaths: ReadonlyArray<string>,
) => Effect.Effect<ReadonlyArray<string>, GitCommandError>;
/**
* List local + remote branches and branch metadata.
*/
readonly listBranches: (
input: GitListBranchesInput,
) => Effect.Effect<GitListBranchesResult, GitCommandError>;
/**
* Pull current branch from upstream using fast-forward only.
*/
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<GitPullResult, GitCommandError>;
/**
* Create a worktree and branch from a base branch.
*/
readonly createWorktree: (
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.
*/
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
/**
* Rename an existing local branch.
*/
readonly renameBranch: (
input: GitRenameBranchInput,
) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
/**
* Create a local branch.
*/
readonly createBranch: (
input: GitCreateBranchInput,
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
/**
* Checkout an existing branch and refresh its upstream metadata in background.
*/
readonly checkoutBranch: (
input: GitCheckoutInput,
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
/**
* Initialize a repository in the provided directory.
*/
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
/**
* List local branch names (short format).
*/
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
}
/**
* GitCore - Service tag for low-level Git repository operations.
*/
export class GitCore extends Context.Service<GitCore, GitCoreShape>()("t3/git/Services/GitCore") {}
-103
View File
@@ -1,103 +0,0 @@
/**
* GitHubCli - Effect service contract for `gh` process interactions.
*
* Provides thin command execution helpers used by Git workflow orchestration.
*
* @module GitHubCli
*/
import { Context } from "effect";
import type { Effect } from "effect";
import type { ProcessRunResult } from "../../processRunner.ts";
import type { GitHubCliError } from "@t3tools/contracts";
export interface GitHubPullRequestSummary {
readonly number: number;
readonly title: string;
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;
}
/**
* GitHubCliShape - Service API for executing GitHub CLI commands.
*/
export interface GitHubCliShape {
/**
* Execute a GitHub CLI command and return full process output.
*/
readonly execute: (input: {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
/**
* List open pull requests for a head branch.
*/
readonly listOpenPullRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
/**
* Resolve a pull request by URL, number, or branch-ish identifier.
*/
readonly getPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
/**
* Resolve clone URLs for a GitHub repository.
*/
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
/**
* Create a pull request from branch context and body file.
*/
readonly createPullRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
readonly headSelector: string;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitHubCliError>;
/**
* Resolve repository default branch through GitHub metadata.
*/
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>;
}
/**
* GitHubCli - Service tag for GitHub CLI process execution.
*/
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
"t3/git/Services/GitHubCli",
) {}
-104
View File
@@ -1,104 +0,0 @@
/**
* GitManager - Effect service contract for stacked Git workflows.
*
* Orchestrates status inspection and commit/push/PR flows by composing
* lower-level Git and external tool services.
*
* @module GitManager
*/
import {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusInput,
GitStatusResult,
} from "@t3tools/contracts";
import { Context } from "effect";
import type { Effect } from "effect";
import type { GitManagerServiceError } from "@t3tools/contracts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}
export interface GitRunStackedActionOptions {
readonly actionId?: string;
readonly progressReporter?: GitActionProgressReporter;
}
/**
* GitManagerShape - Service API for high-level Git workflow actions.
*/
export interface GitManagerShape {
/**
* Read current repository Git status plus open PR metadata when available.
*/
readonly status: (
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
/**
* Read local repository status without remote hosting enrichment.
*/
readonly localStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
/**
* Read remote tracking / PR status for a repository.
*/
readonly remoteStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusRemoteResult | null, GitManagerServiceError>;
/**
* Clear any cached local status snapshot for a repository.
*/
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Clear any cached remote status snapshot for a repository.
*/
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Clear any cached status snapshot for a repository so the next read is fresh.
*/
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* 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 Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first.
*/
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
}
/**
* GitManager - Service tag for stacked Git workflow orchestration.
*/
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
"t3/git/Services/GitManager",
) {}
@@ -1,27 +0,0 @@
import { Context } from "effect";
import type { Effect, Stream } from "effect";
import type {
GitManagerServiceError,
GitStatusInput,
GitStatusLocalResult,
GitStatusResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
export interface GitStatusBroadcasterShape {
readonly getStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly refreshLocalStatus: (
cwd: string,
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
readonly refreshStatus: (cwd: string) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly streamStatus: (
input: GitStatusInput,
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
}
export class GitStatusBroadcaster extends Context.Service<
GitStatusBroadcaster,
GitStatusBroadcasterShape
>()("t3/git/Services/GitStatusBroadcaster") {}
-165
View File
@@ -1,171 +1,6 @@
/**
* Shared utilities for text generation layers (Codex, Claude, etc.).
*
* @module textGenerationUtils
*/
import { Schema } from "effect";
import { TextGenerationError } from "@t3tools/contracts";
import { existsSync } from "node:fs";
import { join } from "node:path";
export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
/** Normalise a raw PR title to a single line with a sensible fallback. */
export function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
export function sanitizeThreadTitle(raw: string): string {
const normalized = raw
.trim()
.split(/\r?\n/g)[0]
?.trim()
.replace(/^['"`]+|['"`]+$/g, "")
.trim()
.replace(/\s+/g, " ");
if (!normalized || normalized.trim().length === 0) {
return "New thread";
}
if (normalized.length <= 50) {
return normalized;
}
return `${normalized.slice(0, 47).trimEnd()}...`;
}
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
function cliLabel(cliName: string): string {
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
return `${capitalized} CLI (\`${cliName}\`)`;
}
/**
* Normalize an unknown error from a CLI text generation process into a
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
* and Claude (and future providers) can share the same logic.
*/
export function normalizeCliError(
cliName: string,
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes(`Command not found: ${cliName}`) ||
lower.includes(`spawn ${cliName}`) ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}
+50 -1
View File
@@ -354,7 +354,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("replaces existing custom keybinding for the same command", () =>
it.effect("appends additional custom keybindings for the same command", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
@@ -368,6 +368,55 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
});
});
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
assert.deepEqual(persistedView, [
{ key: "mod+r", command: "script.run-tests.run" },
{ key: "mod+shift+r", command: "script.run-tests.run" },
]);
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("replaces only the targeted custom keybinding", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
{ key: "mod+r", command: "script.run-tests.run" },
{ key: "mod+shift+r", command: "script.run-tests.run" },
]);
yield* Effect.gen(function* () {
const keybindings = yield* Keybindings;
return yield* keybindings.upsertKeybindingRule({
key: "mod+alt+r",
command: "script.run-tests.run",
replace: { key: "mod+r", command: "script.run-tests.run" },
});
});
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
assert.deepEqual(persistedView, [
{ key: "mod+shift+r", command: "script.run-tests.run" },
{ key: "mod+alt+r", command: "script.run-tests.run" },
]);
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("removes only the targeted custom keybinding", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
{ key: "mod+r", command: "script.run-tests.run" },
{ key: "mod+shift+r", command: "script.run-tests.run" },
]);
yield* Effect.gen(function* () {
const keybindings = yield* Keybindings;
return yield* keybindings.removeKeybindingRule({
key: "mod+r",
command: "script.run-tests.run",
});
});
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
+72 -280
View File
@@ -13,14 +13,12 @@ import {
KeybindingShortcut,
KeybindingWhenNode,
MAX_KEYBINDINGS_COUNT,
MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
MAX_WHEN_EXPRESSION_DEPTH,
ResolvedKeybindingRule,
ResolvedKeybindingsConfig,
THREAD_JUMP_KEYBINDING_COMMANDS,
type ServerRemoveKeybindingInput,
type ServerUpsertKeybindingInput,
type ServerConfigIssue,
} from "@t3tools/contracts";
import type { Mutable } from "effect/Types";
import {
Array,
Cache,
@@ -48,278 +46,20 @@ import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config.ts";
import { writeFileStringAtomically } from "./atomicWrite.ts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import {
DEFAULT_KEYBINDINGS,
DEFAULT_RESOLVED_KEYBINDINGS,
compileResolvedKeybindingRule,
compileResolvedKeybindingsConfig,
parseKeybindingShortcut,
} from "@t3tools/shared/keybindings";
type WhenToken =
| { type: "identifier"; value: string }
| { type: "not" }
| { type: "and" }
| { type: "or" }
| { type: "lparen" }
| { type: "rparen" };
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },
{ key: "mod+o", command: "editor.openFavorite" },
{ key: "mod+shift+[", command: "thread.previous" },
{ key: "mod+shift+]", command: "thread.next" },
...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
key: `mod+${index + 1}`,
command,
})),
...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
key: `mod+${index + 1}`,
command,
when: "modelPickerOpen",
})),
];
function normalizeKeyToken(token: string): string {
if (token === "space") return " ";
if (token === "esc") return "escape";
return token;
}
/** @internal - Exported for testing */
export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
const rawTokens = value
.toLowerCase()
.split("+")
.map((token) => token.trim());
const tokens = [...rawTokens];
let trailingEmptyCount = 0;
while (tokens[tokens.length - 1] === "") {
trailingEmptyCount += 1;
tokens.pop();
}
if (trailingEmptyCount > 0) {
tokens.push("+");
}
if (tokens.some((token) => token.length === 0)) {
return null;
}
if (tokens.length === 0) return null;
let key: string | null = null;
let metaKey = false;
let ctrlKey = false;
let shiftKey = false;
let altKey = false;
let modKey = false;
for (const token of tokens) {
switch (token) {
case "cmd":
case "meta":
metaKey = true;
break;
case "ctrl":
case "control":
ctrlKey = true;
break;
case "shift":
shiftKey = true;
break;
case "alt":
case "option":
altKey = true;
break;
case "mod":
modKey = true;
break;
default: {
if (key !== null) return null;
key = normalizeKeyToken(token);
}
}
}
if (key === null) return null;
return {
key,
metaKey,
ctrlKey,
shiftKey,
altKey,
modKey,
};
}
function tokenizeWhenExpression(expression: string): WhenToken[] | null {
const tokens: WhenToken[] = [];
let index = 0;
while (index < expression.length) {
const current = expression[index];
if (!current) break;
if (/\s/.test(current)) {
index += 1;
continue;
}
if (expression.startsWith("&&", index)) {
tokens.push({ type: "and" });
index += 2;
continue;
}
if (expression.startsWith("||", index)) {
tokens.push({ type: "or" });
index += 2;
continue;
}
if (current === "!") {
tokens.push({ type: "not" });
index += 1;
continue;
}
if (current === "(") {
tokens.push({ type: "lparen" });
index += 1;
continue;
}
if (current === ")") {
tokens.push({ type: "rparen" });
index += 1;
continue;
}
const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
if (!identifier) {
return null;
}
tokens.push({ type: "identifier", value: identifier[0] });
index += identifier[0].length;
}
return tokens;
}
function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
const tokens = tokenizeWhenExpression(expression);
if (!tokens || tokens.length === 0) return null;
let index = 0;
const parsePrimary = (depth: number): KeybindingWhenNode | null => {
if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
return null;
}
const token = tokens[index];
if (!token) return null;
if (token.type === "identifier") {
index += 1;
return { type: "identifier", name: token.value };
}
if (token.type === "lparen") {
index += 1;
const expressionNode = parseOr(depth + 1);
const closeToken = tokens[index];
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
return null;
}
index += 1;
return expressionNode;
}
return null;
};
const parseUnary = (depth: number): KeybindingWhenNode | null => {
let notCount = 0;
while (tokens[index]?.type === "not") {
index += 1;
notCount += 1;
if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
return null;
}
}
let node = parsePrimary(depth);
if (!node) return null;
while (notCount > 0) {
node = { type: "not", node };
notCount -= 1;
}
return node;
};
const parseAnd = (depth: number): KeybindingWhenNode | null => {
let left = parseUnary(depth);
if (!left) return null;
while (tokens[index]?.type === "and") {
index += 1;
const right = parseUnary(depth);
if (!right) return null;
left = { type: "and", left, right };
}
return left;
};
const parseOr = (depth: number): KeybindingWhenNode | null => {
let left = parseAnd(depth);
if (!left) return null;
while (tokens[index]?.type === "or") {
index += 1;
const right = parseAnd(depth);
if (!right) return null;
left = { type: "or", left, right };
}
return left;
};
const ast = parseOr(0);
if (!ast || index !== tokens.length) return null;
return ast;
}
/** @internal - Exported for testing */
export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
const shortcut = parseKeybindingShortcut(rule.key);
if (!shortcut) return null;
if (rule.when !== undefined) {
const whenAst = parseKeybindingWhenExpression(rule.when);
if (!whenAst) return null;
return {
command: rule.command,
shortcut,
whenAst,
};
}
return {
command: rule.command,
shortcut,
};
}
export function compileResolvedKeybindingsConfig(
config: KeybindingsConfig,
): ResolvedKeybindingsConfig {
const compiled: Mutable<ResolvedKeybindingsConfig> = [];
for (const rule of config) {
const result = Schema.decodeExit(ResolvedKeybindingFromConfig)(rule);
if (result._tag === "Success") {
compiled.push(result.value);
}
}
return compiled;
}
export {
DEFAULT_KEYBINDINGS,
compileResolvedKeybindingRule,
compileResolvedKeybindingsConfig,
parseKeybindingShortcut,
};
export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
Schema.decodeTo(
@@ -386,6 +126,25 @@ function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): bo
return leftContext === rightContext;
}
function keybindingRuleFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule {
return input.when === undefined
? { key: input.key, command: input.command }
: { key: input.key, command: input.command, when: input.when };
}
function replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null {
if (!input.replace) return null;
return input.replace.when === undefined
? { key: input.replace.key, command: input.replace.command }
: { key: input.replace.key, command: input.replace.command, when: input.replace.when };
}
function keybindingRuleFromRemoveInput(input: ServerRemoveKeybindingInput): KeybindingRule {
return input.when === undefined
? { key: input.key, command: input.command }
: { key: input.key, command: input.command, when: input.when };
}
function encodeShortcut(shortcut: KeybindingShortcut): string | null {
const modifiers: string[] = [];
if (shortcut.modKey) modifiers.push("mod");
@@ -412,8 +171,6 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
}
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
@@ -523,7 +280,14 @@ export interface KeybindingsShape {
* oldest entries when needed.
*/
readonly upsertKeybindingRule: (
rule: KeybindingRule,
input: ServerUpsertKeybindingInput,
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
/**
* Remove a single persisted keybinding rule by exact key/command/when match.
*/
readonly removeKeybindingRule: (
input: ServerRemoveKeybindingInput,
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
}
@@ -880,12 +644,19 @@ const makeKeybindings = Effect.gen(function* () {
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
upsertKeybindingRule: (rule) =>
upsertKeybindingRule: (input) =>
upsertSemaphore.withPermits(1)(
Effect.gen(function* () {
const customConfig = yield* loadWritableCustomKeybindingsConfig();
const rule = keybindingRuleFromUpsertInput(input);
const replaceTarget = replaceTargetFromUpsertInput(input);
const nextConfig = [
...customConfig.filter((entry) => entry.command !== rule.command),
...customConfig.filter((entry) => {
if (replaceTarget) {
return !isSameKeybindingRule(entry, replaceTarget);
}
return !isSameKeybindingRule(entry, rule);
}),
rule,
];
const cappedConfig =
@@ -913,6 +684,27 @@ const makeKeybindings = Effect.gen(function* () {
return nextResolved;
}),
),
removeKeybindingRule: (input) =>
upsertSemaphore.withPermits(1)(
Effect.gen(function* () {
const customConfig = yield* loadWritableCustomKeybindingsConfig();
const target = keybindingRuleFromRemoveInput(input);
const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
yield* writeConfigAtomically(nextConfig);
const nextResolved = mergeWithDefaultKeybindings(
compileResolvedKeybindingsConfig(nextConfig),
);
yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
keybindings: nextResolved,
issues: [],
});
yield* emitChange({
keybindings: nextResolved,
issues: [],
});
return nextResolved;
}),
),
} satisfies KeybindingsShape;
});
+51 -5
View File
@@ -1,5 +1,7 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect, Metric } from "effect";
import { ProviderDriverKind } from "@t3tools/contracts";
import { Duration, Effect, Fiber, Metric } from "effect";
import { TestClock } from "effect/testing";
import { withMetrics } from "./Metrics.ts";
@@ -14,6 +16,18 @@ const hasMetricSnapshot = (
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
const findHistogramSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.find(
(snapshot): snapshot is Extract<Metric.Metric.Snapshot, { readonly type: "Histogram" }> =>
snapshot.type === "Histogram" &&
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
describe("withMetrics", () => {
it.effect("supports pipe-style usage", () =>
Effect.gen(function* () {
@@ -75,10 +89,11 @@ describe("withMetrics", () => {
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_lazy_total");
const timer = Metric.timer("with_metrics_lazy_duration");
let provider = "unknown";
let provider = ProviderDriverKind.make("unknown");
const lazyInittedProvider = ProviderDriverKind.make("codex");
yield* Effect.sync(() => {
provider = "codex";
provider = lazyInittedProvider;
}).pipe(
withMetrics({
counter,
@@ -93,7 +108,7 @@ describe("withMetrics", () => {
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {
provider: "codex",
provider: lazyInittedProvider,
operation: "lazy",
outcome: "success",
}),
@@ -101,11 +116,42 @@ describe("withMetrics", () => {
);
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {
provider: "codex",
provider: lazyInittedProvider,
operation: "lazy",
}),
true,
);
}),
);
it.effect("records timer durations from nanosecond clock readings", () =>
Effect.gen(function* () {
const duration = Duration.nanos(1_500_000n);
const timer = Metric.timer("with_metrics_nanos_duration");
yield* Effect.gen(function* () {
const fiber = yield* Effect.sleep(duration).pipe(
withMetrics({
timer,
attributes: {
operation: "nanos",
},
}),
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* TestClock.adjust(duration);
yield* Fiber.join(fiber);
}).pipe(Effect.provide(TestClock.layer()));
const snapshots = yield* Metric.snapshot;
const snapshot = findHistogramSnapshot(snapshots, "with_metrics_nanos_duration", {
operation: "nanos",
});
assert.equal(snapshot?.state.count, 1);
assert.equal(snapshot?.state.sum, 1.5);
}),
);
});
+5 -3
View File
@@ -1,4 +1,4 @@
import { Duration, Effect, Exit, Metric } from "effect";
import { Clock, Duration, Effect, Exit, Metric } from "effect";
import { dual } from "effect/Function";
import {
@@ -96,9 +96,11 @@ const withMetricsImpl = <A, E, R>(
options: WithMetricsOptions,
): Effect.Effect<A, E, R> =>
Effect.gen(function* () {
const startedAt = Date.now();
const startedAt = yield* Clock.currentTimeNanos;
const exit = yield* Effect.exit(effect);
const duration = Duration.millis(Math.max(0, Date.now() - startedAt));
const endedAt = yield* Clock.currentTimeNanos;
const elapsedNanos = endedAt > startedAt ? endedAt - startedAt : 0n;
const duration = Duration.nanos(elapsedNanos);
const baseAttributes =
typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});
@@ -1,5 +1,7 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect, Exit, Metric, Stream } from "effect";
import { WS_METHODS } from "@t3tools/contracts";
import { Duration, Effect, Exit, Fiber, Metric, Stream, Tracer } from "effect";
import { TestClock } from "effect/testing";
import {
observeRpcEffect,
@@ -18,6 +20,44 @@ const hasMetricSnapshot = (
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
const findHistogramSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.find(
(snapshot): snapshot is Extract<Metric.Metric.Snapshot, { readonly type: "Histogram" }> =>
snapshot.type === "Histogram" &&
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
const collectSpanNames = <A, E, R>(
effect: Effect.Effect<A, E, R>,
): Effect.Effect<ReadonlyArray<string>, E, R> =>
Effect.gen(function* () {
const spanNames: Array<string> = [];
const tracer = Tracer.make({
span: (options) => {
const span = new Tracer.NativeSpan(options);
const end = span.end.bind(span);
span.end = (endTime, exit) => {
end(endTime, exit);
if (span.sampled) {
spanNames.push(span.name);
}
};
return span;
},
});
yield* effect.pipe(Effect.withTracer(tracer));
return spanNames;
});
describe("RpcInstrumentation", () => {
it.effect("records success metrics for unary RPC handlers", () =>
Effect.gen(function* () {
@@ -129,6 +169,37 @@ describe("RpcInstrumentation", () => {
}),
);
it.effect("records direct stream durations from nanosecond clock readings", () =>
Effect.gen(function* () {
const duration = Duration.nanos(1_500_000n);
const events = yield* Effect.gen(function* () {
const fiber = yield* Stream.runCollect(
observeRpcStream(
WS_METHODS.serverGetProcessDiagnostics,
Stream.fromEffect(Effect.sleep(duration).pipe(Effect.as("ok"))),
{
"rpc.aggregate": "test",
},
),
).pipe(Effect.forkChild);
yield* Effect.yieldNow;
yield* TestClock.adjust(duration);
return yield* Fiber.join(fiber);
}).pipe(Effect.provide(TestClock.layer()));
assert.deepStrictEqual(Array.from(events), ["ok"]);
const snapshots = yield* Metric.snapshot;
const snapshot = findHistogramSnapshot(snapshots, "t3_rpc_request_duration", {
method: WS_METHODS.serverGetProcessDiagnostics,
});
assert.equal(snapshot?.state.count, 1);
assert.equal(snapshot?.state.sum, 1.5);
}),
);
it.effect("records failure outcomes when a stream RPC effect produces a failing stream", () =>
Effect.gen(function* () {
const exit = yield* Stream.runCollect(
@@ -158,4 +229,79 @@ describe("RpcInstrumentation", () => {
);
}),
);
it.effect("records spans for traced stream RPC handlers", () =>
Effect.gen(function* () {
const spanNames = yield* collectSpanNames(
Stream.runCollect(
observeRpcStream(
"rpc.instrumentation.traced.stream",
Stream.fromEffect(
Effect.succeed("ok").pipe(Effect.withSpan("rpc.instrumentation.traced.stream.child")),
),
{ "rpc.aggregate": "test" },
),
),
);
assert.equal(spanNames.includes("ws.rpc.rpc.instrumentation.traced.stream"), true);
assert.equal(spanNames.includes("rpc.instrumentation.traced.stream.child"), true);
}),
);
it.effect("does not create spans for disabled unary RPC handlers", () =>
Effect.gen(function* () {
const spanNames = yield* collectSpanNames(
observeRpcEffect(
WS_METHODS.serverGetTraceDiagnostics,
Effect.succeed("ok").pipe(Effect.withSpan("rpc.instrumentation.disabled.unary.child")),
{ "rpc.aggregate": "test" },
),
);
assert.deepStrictEqual(spanNames, []);
}),
);
it.effect("does not create spans for disabled direct stream RPC handlers", () =>
Effect.gen(function* () {
const spanNames = yield* collectSpanNames(
Stream.runCollect(
observeRpcStream(
WS_METHODS.serverGetTraceDiagnostics,
Stream.fromEffect(
Effect.succeed("ok").pipe(
Effect.withSpan("rpc.instrumentation.disabled.stream.child"),
),
),
{ "rpc.aggregate": "test" },
),
),
);
assert.deepStrictEqual(spanNames, []);
}),
);
it.effect("does not create spans for disabled stream effect RPC handlers", () =>
Effect.gen(function* () {
const spanNames = yield* collectSpanNames(
Stream.runCollect(
observeRpcStreamEffect(
WS_METHODS.serverGetTraceDiagnostics,
Effect.succeed(
Stream.fromEffect(
Effect.succeed("ok").pipe(
Effect.withSpan("rpc.instrumentation.disabled.stream.effect.consume"),
),
),
).pipe(Effect.withSpan("rpc.instrumentation.disabled.stream.effect.create")),
{ "rpc.aggregate": "test" },
),
),
);
assert.deepStrictEqual(spanNames, []);
}),
);
});
@@ -1,26 +1,71 @@
import { Duration, Effect, Exit, Metric, Stream } from "effect";
import { WS_METHODS } from "@t3tools/contracts";
import { Clock, Duration, Effect, Exit, Metric, References, Stream } from "effect";
import { outcomeFromExit } from "./Attributes.ts";
import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
const annotateRpcSpan = (
const RPC_SPAN_PREFIX = "ws.rpc";
const DEFAULT_RPC_SPAN_ATTRIBUTES = {
"rpc.transport": "websocket",
"rpc.system": "effect-rpc",
} as const;
const RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet<string> = new Set([
WS_METHODS.serverGetTraceDiagnostics,
WS_METHODS.serverGetProcessDiagnostics,
WS_METHODS.serverSignalProcess,
]);
function shouldTraceRpc(method: string): boolean {
return !RPC_METHODS_WITH_TRACING_DISABLED.has(method);
}
const rpcSpanAttributes = (
method: string,
traceAttributes?: Readonly<Record<string, unknown>>,
): Effect.Effect<void, never, never> =>
Effect.annotateCurrentSpan({
"rpc.method": method,
...traceAttributes,
});
): Record<string, unknown> => ({
...DEFAULT_RPC_SPAN_ATTRIBUTES,
"rpc.method": method,
...traceAttributes,
});
const withRpcEffectTracing = <A, E, R>(
method: string,
effect: Effect.Effect<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Effect.Effect<A, E, R> =>
shouldTraceRpc(method)
? effect.pipe(
Effect.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {
attributes: rpcSpanAttributes(method, traceAttributes),
}),
)
: effect.pipe(Effect.provideService(References.TracerEnabled, false));
const withRpcStreamTracing = <A, E, R>(
method: string,
stream: Stream.Stream<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, E, R> =>
shouldTraceRpc(method)
? stream.pipe(
Stream.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {
attributes: rpcSpanAttributes(method, traceAttributes),
}),
)
: stream.pipe(Stream.provideService(References.TracerEnabled, false));
const recordRpcStreamMetrics = <E>(
method: string,
startedAt: number,
startedAt: bigint,
exit: Exit.Exit<unknown, E>,
): Effect.Effect<void, never, never> =>
Effect.gen(function* () {
const endedAt = yield* Clock.currentTimeNanos;
const elapsedNanos = endedAt > startedAt ? endedAt - startedAt : 0n;
yield* Metric.update(
Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),
Duration.millis(Math.max(0, Date.now() - startedAt)),
Duration.nanos(elapsedNanos),
);
yield* Metric.update(
Metric.withAttributes(
@@ -38,43 +83,43 @@ export const observeRpcEffect = <A, E, R>(
method: string,
effect: Effect.Effect<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Effect.Effect<A, E, R> =>
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
): Effect.Effect<A, E, R> => {
const instrumented = effect.pipe(
withMetrics({
counter: rpcRequestsTotal,
timer: rpcRequestDuration,
attributes: {
method,
},
}),
);
return yield* effect.pipe(
withMetrics({
counter: rpcRequestsTotal,
timer: rpcRequestDuration,
attributes: {
method,
},
}),
);
});
return withRpcEffectTracing(method, instrumented, traceAttributes);
};
export const observeRpcStream = <A, E, R>(
method: string,
stream: Stream.Stream<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, E, R> =>
Stream.unwrap(
): Stream.Stream<A, E, R> => {
const instrumented = Stream.unwrap(
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
const startedAt = Date.now();
const startedAt = yield* Clock.currentTimeNanos;
return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));
}),
);
return withRpcStreamTracing(method, instrumented, traceAttributes);
};
export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
method: string,
effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> =>
Stream.unwrap(
): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> => {
const instrumented = Stream.unwrap(
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
const startedAt = Date.now();
const startedAt = yield* Clock.currentTimeNanos;
const exit = yield* Effect.exit(effect);
if (Exit.isFailure(exit)) {
@@ -87,3 +132,6 @@ export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectErro
);
}),
);
return withRpcStreamTracing(method, instrumented, traceAttributes);
};
+227 -1
View File
@@ -98,6 +98,105 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
command: "idea",
args: ["/tmp/workspace"],
});
const aquaLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "aqua" },
"darwin",
);
assert.deepEqual(aquaLaunch, {
command: "aqua",
args: ["/tmp/workspace"],
});
const clionLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "clion" },
"darwin",
);
assert.deepEqual(clionLaunch, {
command: "clion",
args: ["/tmp/workspace"],
});
const datagripLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "datagrip" },
"darwin",
);
assert.deepEqual(datagripLaunch, {
command: "datagrip",
args: ["/tmp/workspace"],
});
const dataspellLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "dataspell" },
"darwin",
);
assert.deepEqual(dataspellLaunch, {
command: "dataspell",
args: ["/tmp/workspace"],
});
const golandLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "goland" },
"darwin",
);
assert.deepEqual(golandLaunch, {
command: "goland",
args: ["/tmp/workspace"],
});
const phpstormLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "phpstorm" },
"darwin",
);
assert.deepEqual(phpstormLaunch, {
command: "phpstorm",
args: ["/tmp/workspace"],
});
const pycharmLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "pycharm" },
"darwin",
);
assert.deepEqual(pycharmLaunch, {
command: "pycharm",
args: ["/tmp/workspace"],
});
const riderLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "rider" },
"darwin",
);
assert.deepEqual(riderLaunch, {
command: "rider",
args: ["/tmp/workspace"],
});
const rubymineLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "rubymine" },
"darwin",
);
assert.deepEqual(rubymineLaunch, {
command: "rubymine",
args: ["/tmp/workspace"],
});
const rustroverLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "rustrover" },
"darwin",
);
assert.deepEqual(rustroverLaunch, {
command: "rustrover",
args: ["/tmp/workspace"],
});
const webstormLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "webstorm" },
"darwin",
);
assert.deepEqual(webstormLaunch, {
command: "webstorm",
args: ["/tmp/workspace"],
});
}),
);
@@ -207,6 +306,105 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
command: "idea",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const aquaLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "aqua" },
"darwin",
);
assert.deepEqual(aquaLineAndColumn, {
command: "aqua",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const clionLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "clion" },
"darwin",
);
assert.deepEqual(clionLineAndColumn, {
command: "clion",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const datagripLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "datagrip" },
"darwin",
);
assert.deepEqual(datagripLineAndColumn, {
command: "datagrip",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const dataspellLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "dataspell" },
"darwin",
);
assert.deepEqual(dataspellLineAndColumn, {
command: "dataspell",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const golandLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "goland" },
"darwin",
);
assert.deepEqual(golandLineAndColumn, {
command: "goland",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const phpstormLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "phpstorm" },
"darwin",
);
assert.deepEqual(phpstormLineAndColumn, {
command: "phpstorm",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const pycharmLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "pycharm" },
"darwin",
);
assert.deepEqual(pycharmLineAndColumn, {
command: "pycharm",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const riderLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rider" },
"darwin",
);
assert.deepEqual(riderLineAndColumn, {
command: "rider",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const rubymineLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rubymine" },
"darwin",
);
assert.deepEqual(rubymineLineAndColumn, {
command: "rubymine",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const rustroverLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rustrover" },
"darwin",
);
assert.deepEqual(rustroverLineAndColumn, {
command: "rustrover",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const webstormLineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "webstorm" },
"darwin",
);
assert.deepEqual(webstormLineOnly, {
command: "webstorm",
args: ["--line", "48", "/tmp/workspace/AGENTS.md"],
});
}),
);
@@ -377,12 +575,40 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
yield* fs.writeFileString(path.join(dir, "kiro.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "aqua.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "clion.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "datagrip.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "dataspell.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "goland.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "phpstorm.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "pycharm.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "rider.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "rubymine.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "rustrover.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "webstorm.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
const editors = resolveAvailableEditors("win32", {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["trae", "kiro", "vscode-insiders", "vscodium", "file-manager"]);
assert.deepEqual(editors, [
"trae",
"kiro",
"vscode-insiders",
"vscodium",
"aqua",
"clion",
"datagrip",
"dataspell",
"goland",
"phpstorm",
"pycharm",
"rider",
"rubymine",
"rustrover",
"webstorm",
"file-manager",
]);
}),
);
@@ -3,7 +3,12 @@ import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
ProviderDriverKind,
ProviderRuntimeEvent,
ProviderSession,
ProviderInstanceId,
} from "@t3tools/contracts";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -19,8 +24,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
@@ -35,6 +41,7 @@ import {
type OrchestrationEngineShape,
} from "../Services/OrchestrationEngine.ts";
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
ProviderService,
type ProviderServiceShape,
@@ -50,7 +57,7 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: ProviderDriverKind;
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -64,7 +71,7 @@ function createProviderServiceHarness(
cwd: string,
hasSession = true,
sessionCwd = cwd,
providerName: ProviderSession["provider"] = "codex",
providerName: ProviderSession["provider"] = ProviderDriverKind.make("codex"),
) {
const now = new Date().toISOString();
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
@@ -97,6 +104,17 @@ function createProviderServiceHarness(
stopSession: () => unsupported(),
listSessions,
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
getInstanceInfo: (instanceId) =>
Effect.succeed({
instanceId,
driverKind: ProviderDriverKind.make(providerName),
displayName: undefined,
enabled: true,
continuationIdentity: {
driverKind: ProviderDriverKind.make(providerName),
continuationKey: `${providerName}:instance:${instanceId}`,
},
}),
rollbackConversation,
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
@@ -115,7 +133,14 @@ function createProviderServiceHarness(
}
async function waitForThread(
engine: OrchestrationEngineShape,
readModel: () => Promise<{
readonly threads: ReadonlyArray<{
readonly id: ThreadId;
readonly latestTurn: { readonly turnId: string } | null;
readonly checkpoints: ReadonlyArray<{ readonly checkpointTurnCount: number }>;
readonly activities: ReadonlyArray<{ readonly kind: string }>;
}>;
}>,
predicate: (thread: {
latestTurn: { turnId: string } | null;
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
@@ -129,8 +154,8 @@ async function waitForThread(
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
activities: ReadonlyArray<{ kind: string }>;
}> => {
const readModel = await Effect.runPromise(engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const snapshot = await readModel();
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
if (thread && predicate(thread)) {
return thread;
}
@@ -214,7 +239,7 @@ async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000)
describe("CheckpointReactor", () => {
let runtime: ManagedRuntime.ManagedRuntime<
OrchestrationEngineService | CheckpointReactor | CheckpointStore,
OrchestrationEngineService | CheckpointReactor | CheckpointStore | ProjectionSnapshotQuery,
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
@@ -243,7 +268,7 @@ describe("CheckpointReactor", () => {
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly providerSessionCwd?: string;
readonly providerName?: ProviderKind;
readonly providerName?: ProviderDriverKind;
readonly gitStatusRefreshCalls?: Array<string>;
}) {
const cwd = createGitRepository();
@@ -252,7 +277,7 @@ describe("CheckpointReactor", () => {
cwd,
options?.hasSession ?? true,
options?.providerSessionCwd ?? cwd,
options?.providerName ?? "codex",
options?.providerName ?? ProviderDriverKind.make("codex"),
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
@@ -262,11 +287,15 @@ describe("CheckpointReactor", () => {
Layer.provide(RepositoryIdentityResolverLive),
Layer.provide(SqlitePersistenceMemory),
);
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(RepositoryIdentityResolverLive),
Layer.provide(SqlitePersistenceMemory),
);
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-reactor-test-",
});
const gitStatusBroadcasterLayer = Layer.succeed(GitStatusBroadcaster, {
const vcsStatusBroadcasterLayer = Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: (cwd: string) =>
Effect.sync(() => {
@@ -274,9 +303,9 @@ describe("CheckpointReactor", () => {
}).pipe(
Effect.as({
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: true,
branch: "main",
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -287,19 +316,26 @@ describe("CheckpointReactor", () => {
const layer = CheckpointReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(gitStatusBroadcasterLayer),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(vcsStatusBroadcasterLayer),
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer))),
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(VcsDriverRegistry.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
const reactor = await runtime.runPromise(Effect.service(CheckpointReactor));
const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore));
scope = await Effect.runPromise(Scope.make("sequential"));
@@ -315,7 +351,7 @@ describe("CheckpointReactor", () => {
title: "Test Project",
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -329,7 +365,7 @@ describe("CheckpointReactor", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -365,6 +401,7 @@ describe("CheckpointReactor", () => {
return {
engine,
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
provider,
cwd,
drain,
@@ -396,7 +433,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-1"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -411,7 +448,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-1"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -421,7 +458,7 @@ describe("CheckpointReactor", () => {
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
const thread = await waitForThread(
harness.engine,
harness.readModel,
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
@@ -457,7 +494,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-refresh-local-status"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-refresh-local-status"),
@@ -494,7 +531,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-main"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -510,7 +547,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-aux"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -519,14 +556,14 @@ describe("CheckpointReactor", () => {
});
await harness.drain();
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midReadModel = await harness.readModel();
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(midThread?.checkpoints).toHaveLength(0);
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-main"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -535,7 +572,7 @@ describe("CheckpointReactor", () => {
});
const thread = await waitForThread(
harness.engine,
harness.readModel,
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
@@ -544,7 +581,7 @@ describe("CheckpointReactor", () => {
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: "claudeAgent",
providerName: ProviderDriverKind.make("claudeAgent"),
});
const createdAt = new Date().toISOString();
@@ -569,7 +606,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-claude-1"),
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-claude-1"),
@@ -583,7 +620,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-claude-1"),
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-claude-1"),
@@ -592,7 +629,7 @@ describe("CheckpointReactor", () => {
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
const thread = await waitForThread(
harness.engine,
harness.readModel,
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
);
@@ -627,7 +664,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-missing-baseline"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -637,7 +674,7 @@ describe("CheckpointReactor", () => {
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
const thread = await waitForThread(
harness.engine,
harness.readModel,
(entry) =>
entry.checkpoints.length === 1 &&
entry.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
@@ -716,7 +753,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -762,7 +799,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "checkpoint.captured",
eventId: EventId.make("evt-checkpoint-captured-3"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -772,7 +809,7 @@ describe("CheckpointReactor", () => {
});
await harness.drain();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
false,
@@ -812,7 +849,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-runtime-capture-failure"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -823,7 +860,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-after-runtime-failure"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -901,7 +938,10 @@ describe("CheckpointReactor", () => {
);
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
const thread = await waitForThread(
harness.readModel,
(entry) => entry.checkpoints.length === 1,
);
expect(thread.latestTurn?.turnId).toBe("turn-1");
expect(thread.checkpoints).toHaveLength(1);
@@ -918,7 +958,7 @@ describe("CheckpointReactor", () => {
});
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: "claudeAgent" });
const harness = await createHarness({ providerName: ProviderDriverKind.make("claudeAgent") });
const createdAt = new Date().toISOString();
await Effect.runPromise(
@@ -1083,7 +1123,7 @@ describe("CheckpointReactor", () => {
}),
);
const thread = await waitForThread(harness.engine, (entry) =>
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some((activity) => activity.kind === "checkpoint.revert.failed"),
);
@@ -20,11 +20,12 @@ import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import type { OrchestrationDispatchError } from "../Errors.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
type ReactorInput =
@@ -66,11 +67,12 @@ const serverCommandId = (tag: string): CommandId =>
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
const checkpointStore = yield* CheckpointStore;
const receiptBus = yield* RuntimeReceiptBus;
const workspaceEntries = yield* WorkspaceEntries;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const appendRevertFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -124,29 +126,26 @@ const make = Effect.gen(function* () {
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
threadId: ThreadId,
): 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);
const sessions = yield* providerService.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
return session?.cwd
? Option.some({ threadId: session.threadId, cwd: session.cwd })
: Option.none();
});
const findSessionWithCwd = (
session: (typeof sessions)[number] | undefined,
): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => {
if (!session?.cwd) {
return Option.none();
}
return Option.some({ threadId: session.threadId, cwd: session.cwd });
};
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
return yield* projectionSnapshotQuery
.getThreadDetailById(threadId)
.pipe(Effect.map(Option.getOrUndefined));
});
if (thread) {
const projectedSession = sessions.find((session) => session.threadId === thread.id);
const fromProjected = findSessionWithCwd(projectedSession);
if (Option.isSome(fromProjected)) {
return fromProjected;
}
}
return Option.none();
const resolveThreadProjects = Effect.fn("resolveThreadProjects")(function* (
projectId: ProjectId,
) {
const project = yield* projectionSnapshotQuery
.getProjectShellById(projectId)
.pipe(Effect.map(Option.getOrUndefined));
return project ? [project] : [];
});
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
@@ -237,6 +236,7 @@ const make = Effect.gen(function* () {
fromCheckpointRef,
toCheckpointRef: targetCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace: false,
})
.pipe(
Effect.map((diff) =>
@@ -330,8 +330,7 @@ const make = Effect.gen(function* () {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
const thread = yield* resolveThreadDetail(event.threadId);
if (!thread) {
return;
}
@@ -352,10 +351,11 @@ const make = Effect.gen(function* () {
return;
}
const projects = yield* resolveThreadProjects(thread.projectId);
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
projects,
preferSessionRuntime: true,
});
if (!checkpointCwd) {
@@ -406,8 +406,7 @@ const make = Effect.gen(function* () {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
const thread = yield* resolveThreadDetail(threadId);
if (!thread) {
yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
threadId,
@@ -428,10 +427,11 @@ const make = Effect.gen(function* () {
return;
}
const projects = yield* resolveThreadProjects(thread.projectId);
const checkpointCwd = yield* resolveCheckpointCwd({
threadId,
thread,
projects: readModel.projects,
projects,
preferSessionRuntime: true,
});
if (!checkpointCwd) {
@@ -457,16 +457,16 @@ const make = Effect.gen(function* () {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
const thread = yield* resolveThreadDetail(event.threadId);
if (!thread) {
return;
}
const projects = yield* resolveThreadProjects(thread.projectId);
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
projects,
preferSessionRuntime: false,
});
if (!checkpointCwd) {
@@ -508,7 +508,7 @@ const make = Effect.gen(function* () {
return;
}
yield* gitStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to refresh local git status after turn completion", {
threadId: event.threadId,
@@ -539,16 +539,16 @@ const make = Effect.gen(function* () {
}
const threadId = event.payload.threadId;
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
const thread = yield* resolveThreadDetail(threadId);
if (!thread) {
return;
}
const projects = yield* resolveThreadProjects(thread.projectId);
const checkpointCwd = yield* resolveCheckpointCwd({
threadId,
thread,
projects: readModel.projects,
projects,
preferSessionRuntime: false,
});
if (!checkpointCwd) {
@@ -586,8 +586,7 @@ const make = Effect.gen(function* () {
) {
const now = new Date().toISOString();
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.payload.threadId);
const thread = yield* resolveThreadDetail(event.payload.threadId);
if (!thread) {
yield* appendRevertFailureActivity({
threadId: event.payload.threadId,
@@ -7,6 +7,8 @@ import {
ThreadId,
TurnId,
type OrchestrationEvent,
ProviderInstanceId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
import { describe, expect, it } from "vitest";
@@ -41,9 +43,13 @@ async function createOrchestrationSystem() {
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-orchestration-engine-test-",
});
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
const orchestrationLayer = Layer.mergeAll(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
),
OrchestrationProjectionSnapshotQueryLive,
).pipe(
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(RepositoryIdentityResolverLive),
@@ -53,8 +59,10 @@ async function createOrchestrationSystem() {
);
const runtime = ManagedRuntime.make(orchestrationLayer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
return {
engine,
readModel: () => runtime.runPromise(snapshotQuery.getSnapshot()),
run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
dispose: () => runtime.dispose(),
};
@@ -76,15 +84,18 @@ const hasMetricSnapshot = (
);
describe("OrchestrationEngine", () => {
it("bootstraps the in-memory read model from persisted projections", async () => {
const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
append: () =>
Effect.fail(
new PersistenceSqlError({
operation: "test.append",
detail: "append should not be called during bootstrap",
}),
),
it("bootstraps command handling from persisted projections without reading the full snapshot", async () => {
let nextSequence = 8;
const eventStore: OrchestrationEventStoreShape = {
append: (event) =>
Effect.sync(() => {
const savedEvent = {
...event,
sequence: nextSequence,
} as OrchestrationEvent;
nextSequence += 1;
return savedEvent;
}),
readFromSequence: () => Stream.empty,
readAll: () =>
Stream.fail(
@@ -104,7 +115,7 @@ describe("OrchestrationEngine", () => {
title: "Bootstrap Project",
workspaceRoot: "/tmp/project-bootstrap",
defaultModelSelection: {
provider: "codex" as const,
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
scripts: [],
@@ -119,7 +130,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-bootstrap"),
title: "Bootstrap Thread",
modelSelection: {
provider: "codex" as const,
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -139,11 +150,27 @@ describe("OrchestrationEngine", () => {
},
],
};
const commandReadModel = {
...projectionSnapshot,
threads: projectionSnapshot.threads.map((thread) => ({
...thread,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
})),
};
let fullSnapshotReadCount = 0;
const layer = OrchestrationEngineLive.pipe(
Layer.provide(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.succeed(projectionSnapshot),
getCommandReadModel: () => Effect.succeed(commandReadModel),
getSnapshot: () =>
Effect.sync(() => {
fullSnapshotReadCount += 1;
return projectionSnapshot;
}),
getShellSnapshot: () =>
Effect.succeed({
snapshotSequence: projectionSnapshot.snapshotSequence,
@@ -151,6 +178,8 @@ describe("OrchestrationEngine", () => {
threads: [],
updatedAt: projectionSnapshot.updatedAt,
}),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
@@ -166,7 +195,7 @@ describe("OrchestrationEngine", () => {
projectEvent: () => Effect.void,
} satisfies OrchestrationProjectionPipelineShape),
),
Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)),
Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
);
@@ -174,18 +203,22 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const readModel = await runtime.runPromise(engine.getReadModel());
const result = await runtime.runPromise(
engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-bootstrap-thread-update"),
threadId: ThreadId.make("thread-bootstrap"),
title: "Updated Bootstrap Thread",
}),
);
expect(readModel.snapshotSequence).toBe(7);
expect(readModel.projects).toHaveLength(1);
expect(readModel.projects[0]?.title).toBe("Bootstrap Project");
expect(readModel.threads).toHaveLength(1);
expect(readModel.threads[0]?.title).toBe("Bootstrap Thread");
expect(result.sequence).toBe(8);
expect(fullSnapshotReadCount).toBe(0);
await runtime.dispose();
});
it("returns deterministic read models for repeated reads", async () => {
it("persists deterministic read models for repeated snapshot reads", async () => {
const createdAt = now();
const system = await createOrchestrationSystem();
const { engine } = system;
@@ -198,7 +231,7 @@ describe("OrchestrationEngine", () => {
title: "Project 1",
workspaceRoot: "/tmp/project-1",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -212,7 +245,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -239,8 +272,8 @@ describe("OrchestrationEngine", () => {
}),
);
const readModelA = await system.run(engine.getReadModel());
const readModelB = await system.run(engine.getReadModel());
const readModelA = await system.readModel();
const readModelB = await system.readModel();
expect(readModelB).toEqual(readModelA);
await system.dispose();
});
@@ -258,7 +291,7 @@ describe("OrchestrationEngine", () => {
title: "Project Archive",
workspaceRoot: "/tmp/project-archive",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -272,7 +305,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-archive"),
title: "Archive me",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -291,9 +324,8 @@ describe("OrchestrationEngine", () => {
}),
);
expect(
(await system.run(engine.getReadModel())).threads.find(
(thread) => thread.id === "thread-archive",
)?.archivedAt,
(await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
?.archivedAt,
).not.toBeNull();
await system.run(
@@ -304,9 +336,8 @@ describe("OrchestrationEngine", () => {
}),
);
expect(
(await system.run(engine.getReadModel())).threads.find(
(thread) => thread.id === "thread-archive",
)?.archivedAt,
(await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
?.archivedAt,
).toBeNull();
await system.dispose();
@@ -325,7 +356,7 @@ describe("OrchestrationEngine", () => {
title: "Replay Project",
workspaceRoot: "/tmp/project-replay",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -339,7 +370,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-replay"),
title: "replay",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -383,7 +414,7 @@ describe("OrchestrationEngine", () => {
title: "Stream Project",
workspaceRoot: "/tmp/project-stream",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -407,7 +438,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-stream"),
title: "domain-stream",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -444,7 +475,7 @@ describe("OrchestrationEngine", () => {
title: "Ack Project",
workspaceRoot: "/tmp/project-ack",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -459,7 +490,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-ack"),
title: "Ack Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -496,7 +527,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-missing"),
title: "Missing Project Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -533,7 +564,7 @@ describe("OrchestrationEngine", () => {
title: "Turn Diff Project",
workspaceRoot: "/tmp/project-turn-diff",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -547,7 +578,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-turn-diff"),
title: "Turn diff thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -572,7 +603,7 @@ describe("OrchestrationEngine", () => {
}),
);
const thread = (await system.run(engine.getReadModel())).threads.find(
const thread = (await system.readModel()).threads.find(
(entry) => entry.id === "thread-turn-diff",
);
expect(thread?.checkpoints).toEqual([
@@ -652,7 +683,7 @@ describe("OrchestrationEngine", () => {
title: "Flaky Project",
workspaceRoot: "/tmp/project-flaky",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -668,7 +699,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "flaky-fail",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -688,7 +719,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "flaky-ok",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -700,7 +731,15 @@ describe("OrchestrationEngine", () => {
);
expect(result.sequence).toBe(2);
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
const eventsAfterRetry = await runtime.runPromise(
Stream.runCollect(engine.readEvents(0)).pipe(
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
),
);
expect(eventsAfterRetry.map((event) => event.type)).toEqual([
"project.created",
"thread.created",
]);
await runtime.dispose();
});
@@ -747,7 +786,7 @@ describe("OrchestrationEngine", () => {
title: "Atomic Project",
workspaceRoot: "/tmp/project-atomic",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -761,7 +800,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-atomic"),
title: "atomic",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -800,7 +839,6 @@ describe("OrchestrationEngine", () => {
"project.created",
"thread.created",
]);
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
expect(retryResult.sequence).toBe(4);
@@ -823,7 +861,7 @@ describe("OrchestrationEngine", () => {
await runtime.dispose();
});
it("reconciles in-memory state when append persists but projection fails", async () => {
it("reconciles command state when append persists but projection fails", async () => {
type StoredEvent =
ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
? A
@@ -855,7 +893,7 @@ describe("OrchestrationEngine", () => {
projectEvent: (event) => {
if (
shouldFailProjection &&
event.commandId === CommandId.make("cmd-thread-meta-sync-fail")
event.commandId === CommandId.make("cmd-thread-archive-sync-fail")
) {
shouldFailProjection = false;
return Effect.fail(
@@ -890,7 +928,7 @@ describe("OrchestrationEngine", () => {
title: "Sync Project",
workspaceRoot: "/tmp/project-sync",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -904,7 +942,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-sync"),
title: "sync-before",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -918,20 +956,22 @@ describe("OrchestrationEngine", () => {
await expect(
runtime.runPromise(
engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-meta-sync-fail"),
type: "thread.archive",
commandId: CommandId.make("cmd-thread-archive-sync-fail"),
threadId: ThreadId.make("thread-sync"),
title: "sync-after-failed-projection",
}),
),
).rejects.toThrow("projection failed");
const readModelAfterFailure = await runtime.runPromise(engine.getReadModel());
const updatedThread = readModelAfterFailure.threads.find(
(thread) => thread.id === "thread-sync",
);
expect(readModelAfterFailure.snapshotSequence).toBe(3);
expect(updatedThread?.title).toBe("sync-after-failed-projection");
await expect(
runtime.runPromise(
engine.dispatch({
type: "thread.archive",
commandId: CommandId.make("cmd-thread-archive-sync-retry"),
threadId: ThreadId.make("thread-sync"),
}),
),
).rejects.toThrow("already archived");
await runtime.dispose();
});
@@ -975,7 +1015,7 @@ describe("OrchestrationEngine", () => {
title: "Duplicate Project",
workspaceRoot: "/tmp/project-duplicate",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -990,7 +1030,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -1010,7 +1050,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -34,6 +34,7 @@ import {
OrchestrationCommandInvariantError,
OrchestrationCommandPreviouslyRejectedError,
type OrchestrationDispatchError,
type OrchestrationProjectorDecodeError,
} from "../Errors.ts";
import { decideOrchestrationCommand } from "../decider.ts";
import { createEmptyReadModel, projectEvent } from "../projector.ts";
@@ -77,13 +78,25 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
let readModel = createEmptyReadModel(new Date().toISOString());
let commandReadModel = createEmptyReadModel(new Date().toISOString());
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
const projectEventsOntoReadModel = (
baseReadModel: OrchestrationReadModel,
events: ReadonlyArray<OrchestrationEvent>,
): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError, never> =>
Effect.gen(function* () {
let nextReadModel = baseReadModel;
for (const event of events) {
nextReadModel = yield* projectEvent(nextReadModel, event);
}
return nextReadModel;
});
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
const dispatchStartSequence = readModel.snapshotSequence;
const dispatchStartSequence = commandReadModel.snapshotSequence;
const processingStartedAtMs = Date.now();
const aggregateRef = commandToAggregateRef(envelope.command);
const baseMetricAttributes = {
@@ -98,11 +111,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
return;
}
let nextReadModel = readModel;
for (const persistedEvent of persistedEvents) {
nextReadModel = yield* projectEvent(nextReadModel, persistedEvent);
}
readModel = nextReadModel;
commandReadModel = yield* projectEventsOntoReadModel(commandReadModel, persistedEvents);
for (const persistedEvent of persistedEvents) {
yield* PubSub.publish(eventPubSub, persistedEvent);
@@ -135,18 +144,18 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel,
readModel: commandReadModel,
});
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
const committedCommand = yield* sql
.withTransaction(
Effect.gen(function* () {
const committedEvents: OrchestrationEvent[] = [];
let nextReadModel = readModel;
let nextCommandReadModel = commandReadModel;
for (const nextEvent of eventBases) {
const savedEvent = yield* eventStore.append(nextEvent);
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);
yield* projectionPipeline.projectEvent(savedEvent);
committedEvents.push(savedEvent);
}
@@ -172,7 +181,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
return {
committedEvents,
lastSequence: lastSavedEvent.sequence,
nextReadModel,
nextCommandReadModel,
} as const;
}),
)
@@ -184,7 +193,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
),
);
readModel = committedCommand.nextReadModel;
commandReadModel = committedCommand.nextCommandReadModel;
for (const [index, event] of committedCommand.committedEvents.entries()) {
yield* PubSub.publish(eventPubSub, event);
if (index === 0) {
@@ -242,7 +251,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
).pipe(
Effect.annotateLogs({
commandId: envelope.command.commandId,
snapshotSequence: readModel.snapshotSequence,
snapshotSequence: commandReadModel.snapshotSequence,
}),
),
),
@@ -255,7 +264,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
aggregateKind: aggregateRef.aggregateKind,
aggregateId: aggregateRef.aggregateId,
acceptedAt: new Date().toISOString(),
resultSequence: readModel.snapshotSequence,
resultSequence: commandReadModel.snapshotSequence,
status: "rejected",
error: error.message,
})
@@ -270,17 +279,14 @@ const makeOrchestrationEngine = Effect.gen(function* () {
};
yield* projectionPipeline.bootstrap;
readModel = yield* projectionSnapshotQuery.getSnapshot();
commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
yield* Effect.forkScoped(worker);
yield* Effect.logDebug("orchestration engine started").pipe(
Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
);
const getReadModel: OrchestrationEngineShape["getReadModel"] = () =>
Effect.sync((): OrchestrationReadModel => readModel);
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
eventStore.readFromSequence(fromSequenceExclusive);
@@ -292,7 +298,6 @@ const makeOrchestrationEngine = Effect.gen(function* () {
});
return {
getReadModel,
readEvents,
dispatch,
// Each access creates a fresh PubSub subscription so that multiple
@@ -7,6 +7,7 @@ import {
ProjectId,
ThreadId,
TurnId,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
@@ -92,7 +93,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-1"),
title: "Thread 1",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -364,7 +365,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-clear-attachments"),
title: "Thread Clear Attachments",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -492,7 +493,7 @@ it.layer(
projectId: ProjectId.make("project-overwrite"),
title: "Thread Overwrite",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -640,7 +641,7 @@ it.layer(
projectId: ProjectId.make("project-rollback"),
title: "Thread Rollback",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -769,7 +770,7 @@ it.layer(
projectId: ProjectId.make("project-revert-files"),
title: "Thread Revert Files",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -977,7 +978,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
projectId: ProjectId.make("project-delete-files"),
title: "Thread Delete Files",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1140,7 +1141,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-a"),
title: "Thread A",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1267,7 +1268,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-empty"),
title: "Thread Empty",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1407,7 +1408,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-conflict"),
title: "Thread Conflict",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1551,7 +1552,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-stale-approval"),
title: "Thread Stale Approval",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -1694,7 +1695,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-nonstale-approval"),
title: "Thread Non-Stale Approval",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -1874,7 +1875,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-revert"),
title: "Thread Revert",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -2195,7 +2196,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
title: "Live Project",
workspaceRoot: "/tmp/project-live",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -2233,7 +2234,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
title: "Scripts Project",
workspaceRoot: "/tmp/project-scripts",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -2253,7 +2254,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
},
],
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5",
},
});
@@ -2272,7 +2273,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
{
scriptsJson:
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
defaultModelSelection: '{"provider":"codex","model":"gpt-5"}',
defaultModelSelection: '{"instanceId":"codex","model":"gpt-5"}',
},
]);
}),
@@ -739,9 +739,31 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
if (Option.isNone(existingRow)) {
return;
}
const retainedTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
let latestTurnId: ProjectionTurn["turnId"] = null;
let latestCheckpointTurnCount = -1;
for (let index = 0; index < retainedTurns.length; index += 1) {
const turn = retainedTurns[index];
if (
!turn ||
turn.turnId === null ||
turn.checkpointTurnCount === null ||
turn.checkpointTurnCount > event.payload.turnCount
) {
continue;
}
if (turn.checkpointTurnCount > latestCheckpointTurnCount) {
latestCheckpointTurnCount = turn.checkpointTurnCount;
latestTurnId = turn.turnId;
}
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
latestTurnId: null,
latestTurnId,
updatedAt: event.occurredAt,
});
yield* refreshThreadShellSummary(event.payload.threadId);
@@ -945,6 +967,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
threadId: event.payload.threadId,
status: event.payload.session.status,
providerName: event.payload.session.providerName,
providerInstanceId: event.payload.session.providerInstanceId ?? null,
runtimeMode: event.payload.session.runtimeMode,
activeTurnId: event.payload.session.activeTurnId,
lastError: event.payload.session.lastError,
@@ -1,9 +1,18 @@
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import {
CheckpointRef,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
ProviderInstanceId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIdentityResolver.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
@@ -252,7 +261,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
workspaceRoot: "/tmp/project-1",
repositoryIdentity: null,
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
scripts: [
@@ -275,7 +284,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
projectId: asProjectId("project-1"),
title: "Thread 1",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "default",
@@ -363,7 +372,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
workspaceRoot: "/tmp/project-1",
repositoryIdentity: null,
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
scripts: [
@@ -385,7 +394,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
projectId: asProjectId("project-1"),
title: "Thread 1",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "default",
@@ -1021,4 +1030,378 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
}
}),
);
it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-1',
'Project 1',
'/tmp/project-1',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-04-03T00:00:00.000Z',
'2026-04-03T00:00:01.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES (
'thread-1',
'project-1',
'Thread 1',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
'turn-running',
'2026-04-03T00:00:04.000Z',
0,
0,
0,
'2026-04-03T00:00:02.000Z',
'2026-04-03T00:00:03.000Z',
NULL,
NULL
)
`;
yield* sql`
INSERT INTO projection_turns (
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
started_at,
completed_at,
checkpoint_turn_count,
checkpoint_ref,
checkpoint_status,
checkpoint_files_json
)
VALUES
(
'thread-1',
'turn-running',
'message-user-2',
NULL,
NULL,
NULL,
'running',
'2026-04-03T00:00:30.000Z',
'2026-04-03T00:00:30.000Z',
NULL,
NULL,
NULL,
NULL,
'[]'
),
(
'thread-1',
'turn-completed',
'message-user-1',
NULL,
NULL,
'message-assistant-1',
'completed',
'2026-04-03T00:00:05.000Z',
'2026-04-03T00:00:06.000Z',
'2026-04-03T00:00:20.000Z',
NULL,
NULL,
NULL,
'[]'
)
`;
yield* sql`
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES
(${ORCHESTRATION_PROJECTOR_NAMES.projects}, 3, '2026-04-03T00:00:40.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threads}, 3, '2026-04-03T00:00:40.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 3, '2026-04-03T00:00:40.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 3, '2026-04-03T00:00:40.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 3, '2026-04-03T00:00:40.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 3, '2026-04-03T00:00:40.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 3, '2026-04-03T00:00:40.000Z')
`;
const commandReadModel = yield* snapshotQuery.getCommandReadModel();
assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "running");
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
assert.equal(shellSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
assert.equal(shellSnapshot.threads[0]?.latestTurn?.state, "running");
const fullSnapshot = yield* snapshotQuery.getSnapshot();
assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "running");
}),
);
it.effect("keeps deleted project and thread tombstones in the command read model", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-deleted',
'Deleted Project',
'/tmp/deleted-project',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-04-05T00:00:00.000Z',
'2026-04-05T00:00:01.000Z',
'2026-04-05T00:00:02.000Z'
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES (
'thread-deleted',
'project-deleted',
'Deleted Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
'turn-deleted',
NULL,
0,
0,
0,
'2026-04-05T00:00:03.000Z',
'2026-04-05T00:00:04.000Z',
NULL,
'2026-04-05T00:00:05.000Z'
)
`;
yield* sql`
INSERT INTO projection_turns (
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
started_at,
completed_at,
checkpoint_turn_count,
checkpoint_ref,
checkpoint_status,
checkpoint_files_json
)
VALUES (
'thread-deleted',
'turn-deleted',
'message-deleted-user',
NULL,
NULL,
'message-deleted-assistant',
'completed',
'2026-04-05T00:00:04.100Z',
'2026-04-05T00:00:04.200Z',
'2026-04-05T00:00:04.300Z',
NULL,
NULL,
NULL,
'[]'
)
`;
const commandReadModel = yield* snapshotQuery.getCommandReadModel();
assert.equal(commandReadModel.projects[0]?.id, asProjectId("project-deleted"));
assert.equal(commandReadModel.projects[0]?.deletedAt, "2026-04-05T00:00:02.000Z");
assert.equal(commandReadModel.threads[0]?.id, ThreadId.make("thread-deleted"));
assert.equal(commandReadModel.threads[0]?.deletedAt, "2026-04-05T00:00:05.000Z");
assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted"));
assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "completed");
const fullSnapshot = yield* snapshotQuery.getSnapshot();
assert.equal(fullSnapshot.threads[0]?.id, ThreadId.make("thread-deleted"));
assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted"));
assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "completed");
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
assert.equal(shellSnapshot.projects.length, 0);
assert.equal(shellSnapshot.threads.length, 0);
}),
);
});
it.effect(
"ProjectionSnapshotQuery dedupes repository identity resolution by workspace root and skips deleted projects for shell snapshots",
() => {
const resolveCalls: string[] = [];
const layer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provideMerge(
Layer.succeed(RepositoryIdentityResolver, {
resolve: (cwd: string) =>
Effect.sync(() => {
resolveCalls.push(cwd);
return {
canonicalKey: `github.com/acme${cwd}`,
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: `https://github.com/acme${cwd}.git`,
},
rootPath: cwd,
};
}),
}),
),
Layer.provideMerge(SqlitePersistenceMemory),
);
return Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES
(
'project-1',
'Shared Project 1',
'/tmp/shared-root',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-04-04T00:00:00.000Z',
'2026-04-04T00:00:01.000Z',
NULL
),
(
'project-2',
'Shared Project 2',
'/tmp/shared-root',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-04-04T00:00:02.000Z',
'2026-04-04T00:00:03.000Z',
NULL
),
(
'project-3',
'Deleted Project',
'/tmp/deleted-root',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-04-04T00:00:04.000Z',
'2026-04-04T00:00:05.000Z',
'2026-04-04T00:00:06.000Z'
)
`;
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/shared-root"]);
assert.equal(shellSnapshot.projects.length, 2);
assert.equal(shellSnapshot.projects[0]?.repositoryIdentity?.rootPath, "/tmp/shared-root");
assert.equal(shellSnapshot.projects[1]?.repositoryIdentity?.rootPath, "/tmp/shared-root");
resolveCalls.length = 0;
const fullSnapshot = yield* snapshotQuery.getSnapshot();
assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/deleted-root", "/tmp/shared-root"]);
assert.equal(fullSnapshot.projects.length, 3);
assert.equal(fullSnapshot.projects[2]?.repositoryIdentity?.rootPath, "/tmp/deleted-root");
}).pipe(Effect.provide(layer));
},
);
@@ -195,6 +195,7 @@ function mapSessionRow(
threadId: row.threadId,
status: row.status,
providerName: row.providerName,
...(row.providerInstanceId !== null ? { providerInstanceId: row.providerInstanceId } : {}),
runtimeMode: row.runtimeMode,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
@@ -218,6 +219,20 @@ function mapProjectShellRow(
};
}
function mapProposedPlanRow(
row: Schema.Schema.Type<typeof ProjectionThreadProposedPlanDbRowSchema>,
): OrchestrationProposedPlan {
return {
id: row.planId,
turnId: row.turnId,
planMarkdown: row.planMarkdown,
implementedAt: row.implementedAt,
implementationThreadId: row.implementationThreadId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
};
}
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown): ProjectionRepositoryError =>
Schema.isSchemaError(cause)
@@ -229,6 +244,37 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
const repositoryIdentityResolutionConcurrency = 4;
const resolveRepositoryIdentitiesForProjects = Effect.fn(
"ProjectionSnapshotQuery.resolveRepositoryIdentitiesForProjects",
)(function* (
projectRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>>,
options?: {
readonly includeDeleted?: boolean;
},
) {
const filteredProjectRows =
options?.includeDeleted === true
? projectRows
: projectRows.filter((row) => row.deletedAt === null);
const uniqueWorkspaceRoots = [...new Set(filteredProjectRows.map((row) => row.workspaceRoot))];
const repositoryIdentityByWorkspaceRoot = new Map(
yield* Effect.forEach(
uniqueWorkspaceRoots,
(workspaceRoot) =>
repositoryIdentityResolver
.resolve(workspaceRoot)
.pipe(Effect.map((identity) => [workspaceRoot, identity] as const)),
{ concurrency: repositoryIdentityResolutionConcurrency },
),
);
return new Map(
filteredProjectRows.map((row) => [
row.projectId,
repositoryIdentityByWorkspaceRoot.get(row.workspaceRoot) ?? null,
]),
);
});
const listProjectRows = SqlSchema.findAll({
Request: Schema.Void,
@@ -334,7 +380,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
FROM projection_thread_activities
ORDER BY
thread_id ASC,
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
sequence ASC,
created_at ASC,
activity_id ASC
@@ -350,6 +395,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
status,
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
provider_session_id AS "providerSessionId",
provider_thread_id AS "providerThreadId",
runtime_mode AS "runtimeMode",
@@ -387,18 +433,46 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
execute: () =>
sql`
SELECT
thread_id AS "threadId",
turn_id AS "turnId",
state,
requested_at AS "requestedAt",
started_at AS "startedAt",
completed_at AS "completedAt",
assistant_message_id AS "assistantMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId"
FROM projection_turns
WHERE turn_id IS NOT NULL
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
turns.thread_id AS "threadId",
turns.turn_id AS "turnId",
turns.state,
turns.requested_at AS "requestedAt",
turns.started_at AS "startedAt",
turns.completed_at AS "completedAt",
turns.assistant_message_id AS "assistantMessageId",
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
turns.source_proposed_plan_id AS "sourceProposedPlanId"
FROM projection_threads threads
JOIN projection_turns turns
ON turns.thread_id = threads.thread_id
AND turns.turn_id = threads.latest_turn_id
WHERE threads.latest_turn_id IS NOT NULL
ORDER BY turns.thread_id ASC
`,
});
const listActiveLatestTurnRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionLatestTurnDbRowSchema,
execute: () =>
sql`
SELECT
turns.thread_id AS "threadId",
turns.turn_id AS "turnId",
turns.state,
turns.requested_at AS "requestedAt",
turns.started_at AS "startedAt",
turns.completed_at AS "completedAt",
turns.assistant_message_id AS "assistantMessageId",
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
turns.source_proposed_plan_id AS "sourceProposedPlanId"
FROM projection_threads threads
JOIN projection_turns turns
ON turns.thread_id = threads.thread_id
AND turns.turn_id = threads.latest_turn_id
WHERE threads.deleted_at IS NULL
AND threads.latest_turn_id IS NOT NULL
ORDER BY turns.thread_id ASC
`,
});
@@ -592,7 +666,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
FROM projection_thread_activities
WHERE thread_id = ${threadId}
ORDER BY
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
sequence ASC,
created_at ASC,
activity_id ASC
@@ -608,6 +681,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
status,
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
runtime_mode AS "runtimeMode",
active_turn_id AS "activeTurnId",
last_error AS "lastError",
@@ -879,6 +953,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
threadId: row.threadId,
status: row.status,
providerName: row.providerName,
...(row.providerInstanceId !== null
? { providerInstanceId: row.providerInstanceId }
: {}),
runtimeMode: row.runtimeMode,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
@@ -886,15 +963,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
}
const repositoryIdentities = new Map(
yield* Effect.forEach(
projectRows,
(row) =>
repositoryIdentityResolver
.resolve(row.workspaceRoot)
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
{ concurrency: repositoryIdentityResolutionConcurrency },
),
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
projectRows,
{ includeDeleted: true },
);
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
@@ -952,6 +1023,199 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
}),
);
const getCommandReadModel: ProjectionSnapshotQueryShape["getCommandReadModel"] = () =>
sql
.withTransaction(
Effect.all([
listProjectRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getCommandReadModel:listProjects:query",
"ProjectionSnapshotQuery.getCommandReadModel:listProjects:decodeRows",
),
),
),
listThreadRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getCommandReadModel:listThreads:query",
"ProjectionSnapshotQuery.getCommandReadModel:listThreads:decodeRows",
),
),
),
listThreadProposedPlanRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:query",
"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:decodeRows",
),
),
),
listThreadSessionRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:query",
"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:decodeRows",
),
),
),
listLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:query",
"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:decodeRows",
),
),
),
listProjectionStateRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:query",
"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:decodeRows",
),
),
),
]),
)
.pipe(
Effect.flatMap(
([projectRows, threadRows, proposedPlanRows, sessionRows, latestTurnRows, stateRows]) =>
Effect.sync(() => {
let updatedAt: string | null = null;
const projects: OrchestrationProject[] = [];
const threads: OrchestrationThread[] = [];
for (let index = 0; index < projectRows.length; index += 1) {
const row = projectRows[index];
if (!row) {
continue;
}
updatedAt = maxIso(updatedAt, row.updatedAt);
projects.push({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
});
}
for (let index = 0; index < threadRows.length; index += 1) {
const row = threadRows[index];
if (!row) {
continue;
}
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (let index = 0; index < proposedPlanRows.length; index += 1) {
const row = proposedPlanRows[index];
if (!row) {
continue;
}
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (let index = 0; index < sessionRows.length; index += 1) {
const row = sessionRows[index];
if (!row) {
continue;
}
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (let index = 0; index < latestTurnRows.length; index += 1) {
const row = latestTurnRows[index];
if (!row) {
continue;
}
updatedAt = maxIso(updatedAt, row.requestedAt);
if (row.startedAt !== null) {
updatedAt = maxIso(updatedAt, row.startedAt);
}
if (row.completedAt !== null) {
updatedAt = maxIso(updatedAt, row.completedAt);
}
}
for (let index = 0; index < stateRows.length; index += 1) {
const row = stateRows[index];
if (!row) {
continue;
}
updatedAt = maxIso(updatedAt, row.updatedAt);
}
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
for (let index = 0; index < latestTurnRows.length; index += 1) {
const row = latestTurnRows[index];
if (!row) {
continue;
}
latestTurnByThread.set(row.threadId, mapLatestTurn(row));
}
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
const sessionByThread = new Map<string, OrchestrationSession>();
for (let index = 0; index < sessionRows.length; index += 1) {
const row = sessionRows[index];
if (!row) {
continue;
}
sessionByThread.set(row.threadId, mapSessionRow(row));
}
for (let index = 0; index < proposedPlanRows.length; index += 1) {
const row = proposedPlanRows[index];
if (!row) {
continue;
}
const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];
threadProposedPlans.push(mapProposedPlanRow(row));
proposedPlansByThread.set(row.threadId, threadProposedPlans);
}
for (let index = 0; index < threadRows.length; index += 1) {
const row = threadRows[index];
if (!row) {
continue;
}
threads.push({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
deletedAt: row.deletedAt,
messages: [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: [],
checkpoints: [],
session: sessionByThread.get(row.threadId) ?? null,
});
}
return {
snapshotSequence: computeSnapshotSequence(stateRows),
projects,
threads,
updatedAt: updatedAt ?? new Date(0).toISOString(),
} satisfies OrchestrationReadModel;
}),
),
Effect.mapError((error) => {
if (isPersistenceError(error)) {
return error;
}
return toPersistenceSqlError("ProjectionSnapshotQuery.getCommandReadModel:query")(error);
}),
);
const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () =>
sql
.withTransaction(
@@ -980,7 +1244,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listLatestTurnRows(undefined).pipe(
listActiveLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
@@ -1024,16 +1288,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
const repositoryIdentities = new Map(
yield* Effect.forEach(
projectRows,
(row) =>
repositoryIdentityResolver
.resolve(row.workspaceRoot)
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
{ concurrency: repositoryIdentityResolutionConcurrency },
),
);
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(projectRows);
const latestTurnByThread = new Map(
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
);
@@ -1091,6 +1346,19 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
}),
);
const getSnapshotSequence: ProjectionSnapshotQueryShape["getSnapshotSequence"] = () =>
listProjectionStateRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getSnapshotSequence:query",
"ProjectionSnapshotQuery.getSnapshotSequence:decodeRows",
),
),
Effect.map((stateRows) => ({
snapshotSequence: computeSnapshotSequence(stateRows),
})),
);
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
readProjectionCounts(undefined).pipe(
Effect.mapError(
@@ -1370,15 +1638,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
}
return message;
}),
proposedPlans: proposedPlanRows.map((row) => ({
id: row.planId,
turnId: row.turnId,
planMarkdown: row.planMarkdown,
implementedAt: row.implementedAt,
implementationThreadId: row.implementationThreadId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
})),
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
activities: activityRows.map((row) => {
const activity = {
id: row.activityId,
@@ -1416,8 +1676,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
return {
getCommandReadModel,
getSnapshot,
getShellSnapshot,
getSnapshotSequence,
getCounts,
getActiveProjectByWorkspaceRoot,
getProjectShellById,
@@ -2,7 +2,13 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
ModelSelection,
ProviderRuntimeEvent,
ProviderSession,
ProviderDriverKind,
ProviderInstanceId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import {
ApprovalRequestId,
@@ -27,21 +33,23 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
import {
GitStatusBroadcaster,
type GitStatusBroadcasterShape,
} from "../../git/Services/GitStatusBroadcaster.ts";
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
import {
providerErrorLabel,
providerErrorLabelFromInstanceHint,
ProviderCommandReactorLive,
} from "./ProviderCommandReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService, type GitWorkflowServiceShape } from "../../git/GitWorkflowService.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
@@ -72,7 +80,7 @@ async function waitFor(
describe("ProviderCommandReactor", () => {
let runtime: ManagedRuntime.ManagedRuntime<
OrchestrationEngineService | ProviderCommandReactor,
OrchestrationEngineService | ProviderCommandReactor | ProjectionSnapshotQuery,
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
@@ -98,6 +106,30 @@ describe("ProviderCommandReactor", () => {
createdBaseDirs.clear();
});
describe("provider error attribution", () => {
it("uses the current provider instance slug when current instance lookup fails", () => {
expect(
providerErrorLabelFromInstanceHint({
instanceId: "codex_personal",
modelSelectionInstanceId: "codex",
sessionProvider: "codex",
}),
).toBe("codex_personal");
});
it("uses the desired provider instance slug when desired instance lookup fails", () => {
expect(
providerErrorLabelFromInstanceHint({
instanceId: "claude_openrouter",
}),
).toBe("claude_openrouter");
});
it("uses the unknown driver kind when the resolved driver is not registered locally", () => {
expect(providerErrorLabel("third_party_driver")).toBe("third_party_driver");
});
});
async function createHarness(input?: {
readonly baseDir?: string;
readonly threadModelSelection?: ModelSelection;
@@ -112,7 +144,7 @@ describe("ProviderCommandReactor", () => {
let nextSessionIndex = 1;
const runtimeSessions: Array<ProviderSession> = [];
const modelSelection = input?.threadModelSelection ?? {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
};
const startSession = vi.fn((_: unknown, input: unknown) => {
@@ -128,8 +160,24 @@ describe("ProviderCommandReactor", () => {
typeof input.threadId === "string"
? ThreadId.make(input.threadId)
: ThreadId.make(`thread-${sessionIndex}`);
const inputModelSelection =
typeof input === "object" && input !== null && "modelSelection" in input
? (input.modelSelection as ModelSelection | undefined)
: undefined;
const providerInstanceId =
typeof input === "object" && input !== null && "providerInstanceId" in input
? (input.providerInstanceId as ProviderInstanceId | undefined)
: inputModelSelection?.instanceId;
const provider =
typeof input === "object" &&
input !== null &&
"provider" in input &&
typeof input.provider === "string"
? (input.provider as ProviderSession["provider"])
: ProviderDriverKind.make(inputModelSelection?.instanceId ?? modelSelection.instanceId);
const session: ProviderSession = {
provider: modelSelection.provider,
provider,
...(providerInstanceId ? { providerInstanceId } : {}),
status: "ready" as const,
runtimeMode:
typeof input === "object" &&
@@ -144,7 +192,9 @@ describe("ProviderCommandReactor", () => {
typeof input.cwd === "string"
? { cwd: input.cwd }
: {}),
...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),
...((inputModelSelection?.model ?? modelSelection.model)
? { model: inputModelSelection?.model ?? modelSelection.model }
: {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
createdAt: now,
@@ -191,9 +241,9 @@ describe("ProviderCommandReactor", () => {
const refreshStatus = vi.fn((_: string) =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "renamed-branch",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "renamed-branch",
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -236,6 +286,25 @@ describe("ProviderCommandReactor", () => {
Effect.succeed({
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
}),
getInstanceInfo: (instanceId) => {
const raw = String(instanceId);
const driverKind = ProviderDriverKind.make(
raw.startsWith("claude") ? "claudeAgent" : raw.startsWith("codex") ? "codex" : raw,
);
return Effect.succeed({
instanceId,
driverKind,
displayName: undefined,
enabled: true,
continuationIdentity: {
driverKind,
continuationKey:
driverKind === ProviderDriverKind.make("codex")
? "codex:home:/shared-codex"
: `${driverKind}:instance:${instanceId}`,
},
});
},
rollbackConversation: () => unsupported(),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
@@ -250,18 +319,27 @@ describe("ProviderCommandReactor", () => {
Layer.provide(RepositoryIdentityResolverLive),
Layer.provide(SqlitePersistenceMemory),
);
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(RepositoryIdentityResolverLive),
Layer.provide(SqlitePersistenceMemory),
);
const layer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
Layer.provideMerge(Layer.succeed(ProviderService, service)),
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
Layer.provideMerge(
Layer.succeed(GitStatusBroadcaster, {
Layer.mock(GitWorkflowService)({
renameBranch,
} satisfies Partial<GitWorkflowServiceShape>),
),
Layer.provideMerge(
Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: () =>
Effect.die("refreshLocalStatus should not be called in this test"),
refreshStatus,
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
} satisfies GitStatusBroadcasterShape),
}),
),
Layer.provideMerge(
Layer.mock(TextGeneration, {
@@ -276,6 +354,7 @@ describe("ProviderCommandReactor", () => {
runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
@@ -310,6 +389,7 @@ describe("ProviderCommandReactor", () => {
return {
engine,
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
startSession,
sendTurn,
interruptTurn,
@@ -320,6 +400,7 @@ describe("ProviderCommandReactor", () => {
refreshStatus,
generateBranchName,
generateThreadTitle,
runtimeSessions,
stateDir,
drain,
};
@@ -352,13 +433,13 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("approval-required");
@@ -403,13 +484,13 @@ describe("ProviderCommandReactor", () => {
});
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
return (
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
"Generated title"
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.title).toBe("Generated title");
});
@@ -449,7 +530,7 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.title).toBe("Keep this custom title");
});
@@ -493,14 +574,14 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
return (
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
"Reconnect spinner resume bug"
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.title).toBe("Reconnect spinner resume bug");
});
@@ -574,7 +655,7 @@ describe("ProviderCommandReactor", () => {
text: "hello fast mode",
attachments: [],
},
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -587,14 +668,14 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -603,7 +684,10 @@ describe("ProviderCommandReactor", () => {
it("forwards claude effort options through session start and turn send", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
const now = new Date().toISOString();
@@ -618,9 +702,11 @@ describe("ProviderCommandReactor", () => {
text: "hello with effort",
attachments: [],
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -630,21 +716,28 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
});
});
it("forwards claude fast mode options through session start and turn send", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
});
const now = new Date().toISOString();
@@ -659,9 +752,11 @@ describe("ProviderCommandReactor", () => {
text: "hello with fast mode",
attachments: [],
},
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -671,15 +766,19 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
});
});
@@ -766,15 +865,15 @@ describe("ProviderCommandReactor", () => {
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
});
});
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
it("starts a first turn on the requested provider instance even when it differs from the thread model", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
threadModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
});
const now = new Date().toISOString();
@@ -790,7 +889,7 @@ describe("ProviderCommandReactor", () => {
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -799,29 +898,25 @@ describe("ProviderCommandReactor", () => {
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession).not.toHaveBeenCalled();
expect(harness.sendTurn).not.toHaveBeenCalled();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session).toBeNull();
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
summary: "Provider turn start failed",
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
expect(harness.startSession).toHaveBeenCalledTimes(1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: ProviderDriverKind.make("claudeAgent"),
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
});
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.providerName).toBe("claudeAgent");
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toBeUndefined();
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
@@ -870,9 +965,74 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts an existing Codex thread on a compatible requested instance", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-compatible-codex-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-compatible-codex-1"),
role: "user",
text: "first",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-compatible-codex-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-compatible-codex-2"),
role: "user",
text: "second",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("codex_work"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession).toHaveBeenCalledTimes(2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
provider: ProviderDriverKind.make("codex"),
providerInstanceId: ProviderInstanceId.make("codex_work"),
resumeCursor: { opaque: "resume-1" },
});
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
});
it("restarts the provider session when the thread workspace changes", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
const now = new Date().toISOString();
@@ -933,7 +1093,7 @@ describe("ProviderCommandReactor", () => {
cwd: "/tmp/provider-project-worktree",
resumeCursor: { opaque: "resume-1" },
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
runtimeMode: "approval-required",
@@ -942,7 +1102,10 @@ describe("ProviderCommandReactor", () => {
it("restarts claude sessions when claude effort changes", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
const now = new Date().toISOString();
@@ -957,9 +1120,11 @@ describe("ProviderCommandReactor", () => {
text: "first claude turn",
attachments: [],
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "medium" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "medium" }],
),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -980,9 +1145,11 @@ describe("ProviderCommandReactor", () => {
text: "second claude turn",
attachments: [],
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -993,9 +1160,11 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
resumeCursor: { opaque: "resume-1" },
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
});
});
@@ -1044,7 +1213,7 @@ describe("ProviderCommandReactor", () => {
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return thread?.runtimeMode === "approval-required";
});
@@ -1078,7 +1247,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.make("thread-1"),
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("approval-required");
@@ -1086,7 +1255,10 @@ describe("ProviderCommandReactor", () => {
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
});
const now = new Date().toISOString();
@@ -1122,7 +1294,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
runtimeMode: "approval-required",
@@ -1178,7 +1350,7 @@ describe("ProviderCommandReactor", () => {
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return thread?.runtimeMode === "approval-required";
});
@@ -1188,7 +1360,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(1);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("full-access");
@@ -1230,7 +1402,7 @@ describe("ProviderCommandReactor", () => {
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -1240,7 +1412,7 @@ describe("ProviderCommandReactor", () => {
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
@@ -1252,7 +1424,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.sendTurn.mock.calls.length).toBe(1);
expect(harness.stopSession.mock.calls.length).toBe(0);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerName).toBe("codex");
@@ -1266,6 +1438,72 @@ describe("ProviderCommandReactor", () => {
});
});
it("rejects cross-driver provider changes after the existing thread session has stopped", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-stopped-provider-switch"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "stopped",
providerName: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-stopped-provider-switch"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-stopped-provider-switch"),
role: "user",
text: "continue with claude",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(0);
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
});
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1349,7 +1587,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -1359,6 +1597,77 @@ describe("ProviderCommandReactor", () => {
});
});
it("rejects active runtime sessions that are missing provider instance ids", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-missing-instance"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
harness.runtimeSessions.push({
provider: ProviderDriverKind.make("codex"),
status: "ready",
runtimeMode: "approval-required",
threadId: ThreadId.make("thread-1"),
cwd: "/tmp/provider-project",
resumeCursor: { opaque: "resume-without-instance" },
createdAt: now,
updatedAt: now,
});
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-missing-instance"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-missing-instance"),
role: "user",
text: "resume codex",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(0);
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("without a provider instance id"),
},
});
});
it("reacts to thread.approval.respond by forwarding provider approval response", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1451,7 +1760,7 @@ describe("ProviderCommandReactor", () => {
harness.respondToRequest.mockImplementation(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
method: "session/request_permission",
detail: "Unknown pending permission request: approval-request-1",
}),
@@ -1509,7 +1818,7 @@ describe("ProviderCommandReactor", () => {
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
if (!thread) return false;
return thread.activities.some(
@@ -1517,7 +1826,7 @@ describe("ProviderCommandReactor", () => {
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread).toBeDefined();
@@ -1546,7 +1855,7 @@ describe("ProviderCommandReactor", () => {
harness.respondToUserInput.mockImplementation(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
method: "item/tool/respondToUserInput",
detail: "Unknown pending user-input request: user-input-request-1",
}),
@@ -1618,7 +1927,7 @@ describe("ProviderCommandReactor", () => {
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
if (!thread) return false;
return thread.activities.some(
@@ -1626,7 +1935,7 @@ describe("ProviderCommandReactor", () => {
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread).toBeDefined();
@@ -1662,6 +1971,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
providerInstanceId: ProviderInstanceId.make("codex_work"),
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
@@ -1681,11 +1991,12 @@ describe("ProviderCommandReactor", () => {
);
await waitFor(() => harness.stopSession.mock.calls.length === 1);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session).not.toBeNull();
expect(thread?.session?.status).toBe("stopped");
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
expect(thread?.session?.activeTurnId).toBeNull();
});
});
@@ -4,7 +4,8 @@ import {
EventId,
type ModelSelection,
type OrchestrationEvent,
ProviderKind,
ProviderDriverKind,
type ProjectId,
type OrchestrationSession,
ThreadId,
type ProviderSession,
@@ -16,19 +17,20 @@ import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream }
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
ProviderCommandReactor,
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -77,6 +79,21 @@ const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const DEFAULT_THREAD_TITLE = "New thread";
export function providerErrorLabel(value: string | undefined): string {
const normalized = value?.trim();
return normalized && normalized.length > 0 ? normalized : "unknown";
}
export function providerErrorLabelFromInstanceHint(input: {
readonly instanceId?: string | undefined;
readonly modelSelectionInstanceId?: string | undefined;
readonly sessionProvider?: string | undefined;
}): string {
return providerErrorLabel(
input.instanceId ?? input.modelSelectionInstanceId ?? input.sessionProvider,
);
}
function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
const trimmedCurrentTitle = currentTitle.trim();
if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) {
@@ -152,9 +169,10 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
const git = yield* GitCore;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const gitWorkflow = yield* GitWorkflowService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const handledTurnStartKeys = yield* Cache.make<string, true>({
@@ -252,9 +270,16 @@ const make = Effect.gen(function* () {
});
});
const resolveProject = Effect.fnUntraced(function* (projectId: ProjectId) {
return yield* projectionSnapshotQuery
.getProjectShellById(projectId)
.pipe(Effect.map(Option.getOrUndefined));
});
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
return readModel.threads.find((entry) => entry.id === threadId);
return yield* projectionSnapshotQuery
.getThreadDetailById(threadId)
.pipe(Effect.map(Option.getOrUndefined));
});
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
@@ -264,49 +289,115 @@ const make = Effect.gen(function* () {
readonly modelSelection?: ModelSelection;
},
) {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
const thread = yield* resolveThread(threadId);
if (!thread) {
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
}
const desiredRuntimeMode = thread.runtimeMode;
const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(
thread.session?.providerName,
)
? thread.session.providerName
: undefined;
const requestedModelSelection = options?.modelSelection;
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
if (
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== threadProvider
) {
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
});
}
const preferredProvider: ProviderKind = threadProvider;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
});
const resolveActiveSession = (threadId: ThreadId) =>
providerService
.listSessions()
.pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));
const activeSession = yield* resolveActiveSession(threadId);
const activeThreadSession =
thread.session !== null && thread.session.status !== "stopped" && activeSession
? thread.session
: null;
if (
activeThreadSession !== null &&
activeSession !== undefined &&
(activeThreadSession.providerInstanceId === undefined ||
activeSession.providerInstanceId === undefined)
) {
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(activeThreadSession.providerName ?? undefined),
method: "thread.turn.start",
detail: `Thread '${threadId}' has an active provider session without a provider instance id.`,
});
}
const currentInstanceId =
activeThreadSession !== null &&
activeSession !== undefined &&
activeSession.providerInstanceId !== undefined
? activeSession.providerInstanceId
: thread.modelSelection.instanceId;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const desiredInstanceId = desiredModelSelection.instanceId;
const currentInfo = yield* providerService.getInstanceInfo(currentInstanceId).pipe(
Effect.mapError(
() =>
new ProviderAdapterRequestError({
provider: providerErrorLabelFromInstanceHint({
instanceId: String(currentInstanceId),
modelSelectionInstanceId: String(thread.modelSelection.instanceId),
sessionProvider: thread.session?.providerName ?? undefined,
}),
method: "thread.turn.start",
detail: `Thread '${threadId}' references unknown provider instance '${currentInstanceId}'. The instance is not configured in this build.`,
}),
),
);
const desiredInfo = yield* providerService.getInstanceInfo(desiredInstanceId).pipe(
Effect.mapError(
() =>
new ProviderAdapterRequestError({
provider: providerErrorLabelFromInstanceHint({
instanceId: String(desiredModelSelection.instanceId),
}),
method: "thread.turn.start",
detail: `Requested provider instance '${desiredInstanceId}' is not configured in this build.`,
}),
),
);
const desiredDriverKind = desiredInfo.driverKind;
if (!Schema.is(ProviderDriverKind)(desiredDriverKind)) {
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(String(desiredDriverKind)),
method: "thread.turn.start",
detail: `Requested provider instance '${desiredInstanceId}' uses unknown provider driver '${desiredDriverKind}'. The driver is not installed in this build.`,
});
}
const preferredProvider: ProviderDriverKind = desiredDriverKind;
if (
thread.session !== null &&
requestedModelSelection !== undefined &&
requestedModelSelection.instanceId !== currentInstanceId
) {
if (currentInfo.driverKind !== desiredInfo.driverKind) {
return yield* new ProviderAdapterRequestError({
provider: preferredProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to driver '${currentInfo.driverKind}' and cannot switch to '${desiredInfo.driverKind}'.`,
});
}
if (
currentInfo.continuationIdentity.continuationKey !==
desiredInfo.continuationIdentity.continuationKey
) {
return yield* new ProviderAdapterRequestError({
provider: preferredProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' cannot switch from instance '${currentInstanceId}' to '${desiredInstanceId}' because their provider resume state is incompatible.`,
});
}
}
const project = yield* resolveProject(thread.projectId);
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
projects: project ? [project] : [],
});
const startProviderSession = (input?: {
readonly resumeCursor?: unknown;
readonly provider?: ProviderKind;
readonly provider?: ProviderDriverKind;
}) =>
providerService.startSession(threadId, {
threadId,
...(preferredProvider ? { provider: preferredProvider } : {}),
providerInstanceId: desiredInstanceId,
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
modelSelection: desiredModelSelection,
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
@@ -314,44 +405,55 @@ const make = Effect.gen(function* () {
});
const bindSessionToThread = (session: ProviderSession) =>
setThreadSession({
threadId,
session: {
Effect.gen(function* () {
if (session.providerInstanceId === undefined) {
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(session.provider),
method: "thread.turn.start",
detail: `Provider session '${session.threadId}' started without a provider instance id.`,
});
}
yield* setThreadSession({
threadId,
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
providerName: session.provider,
runtimeMode: desiredRuntimeMode,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: session.lastError ?? null,
updatedAt: session.updatedAt,
},
createdAt,
session: {
threadId,
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
providerName: session.provider,
providerInstanceId: session.providerInstanceId,
runtimeMode: desiredRuntimeMode,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: session.lastError ?? null,
updatedAt: session.updatedAt,
},
createdAt,
});
});
const activeSession = yield* resolveActiveSession(threadId);
const existingSessionThreadId =
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
if (existingSessionThreadId) {
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
const cwdChanged = effectiveCwd !== activeSession?.cwd;
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const sessionModelSwitch = (yield* providerService.getCapabilities(desiredInstanceId))
.sessionModelSwitch;
const modelChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.model !== activeSession?.model;
const instanceChanged =
requestedModelSelection !== undefined &&
activeSession?.providerInstanceId !== requestedModelSelection.instanceId;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
const previousModelSelection = threadModelSelections.get(threadId);
const shouldRestartForModelSelectionChange =
currentProvider === "claudeAgent" &&
preferredProvider === "claudeAgent" &&
requestedModelSelection !== undefined &&
!Equal.equals(previousModelSelection, requestedModelSelection);
if (
!runtimeModeChanged &&
!cwdChanged &&
!instanceChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelSelectionChange
) {
@@ -364,8 +466,10 @@ const make = Effect.gen(function* () {
yield* Effect.logInfo("provider command reactor restarting provider session", {
threadId,
existingSessionThreadId,
currentProvider,
desiredProvider: desiredModelSelection.provider,
currentProvider: activeSession?.provider,
currentInstanceId,
desiredInstanceId,
desiredProvider: desiredModelSelection.instanceId,
currentRuntimeMode: thread.session?.runtimeMode,
desiredRuntimeMode: thread.runtimeMode,
runtimeModeChanged,
@@ -373,6 +477,7 @@ const make = Effect.gen(function* () {
desiredCwd: effectiveCwd,
cwdChanged,
modelChanged,
instanceChanged,
shouldRestartForModelChange,
shouldRestartForModelSelectionChange,
hasResumeCursor: resumeCursor !== undefined,
@@ -429,7 +534,14 @@ const make = Effect.gen(function* () {
const sessionModelSwitch =
activeSession === undefined
? "in-session"
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
: activeSession.providerInstanceId === undefined
? yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(activeSession.provider),
method: "thread.turn.start",
detail: `Active provider session '${activeSession.threadId}' is missing a provider instance id.`,
})
: (yield* providerService.getCapabilities(activeSession.providerInstanceId))
.sessionModelSwitch;
const requestedModelSelection =
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
const modelForTurn =
@@ -485,7 +597,7 @@ const make = Effect.gen(function* () {
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
if (targetBranch === oldBranch) return;
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("worktree-branch-rename"),
@@ -493,7 +605,7 @@ const make = Effect.gen(function* () {
branch: renamed.branch,
worktreePath: cwd,
});
yield* gitStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
yield* vcsStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
@@ -580,10 +692,11 @@ const make = Effect.gen(function* () {
const isFirstUserMessageTurn =
thread.messages.filter((entry) => entry.role === "user").length === 1;
if (isFirstUserMessageTurn) {
const project = yield* resolveProject(thread.projectId);
const generationCwd =
resolveThreadWorkspaceCwd({
thread,
projects: (yield* orchestrationEngine.getReadModel()).projects,
projects: project ? [project] : [],
}) ?? process.cwd();
const generationInput = {
messageText: message.text,
@@ -717,20 +830,16 @@ const make = Effect.gen(function* () {
})
.pipe(
Effect.catchCause((cause) =>
Effect.gen(function* () {
yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.approval.respond.failed",
summary: "Provider approval response failed",
detail: isUnknownPendingApprovalRequestError(cause)
? stalePendingRequestDetail("approval", event.payload.requestId)
: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
if (!isUnknownPendingApprovalRequestError(cause)) return;
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.approval.respond.failed",
summary: "Provider approval response failed",
detail: isUnknownPendingApprovalRequestError(cause)
? stalePendingRequestDetail("approval", event.payload.requestId)
: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
}),
),
);
@@ -800,6 +909,9 @@ const make = Effect.gen(function* () {
threadId: thread.id,
status: "stopped",
providerName: thread.session?.providerName ?? null,
...(thread.session?.providerInstanceId !== undefined
? { providerInstanceId: thread.session.providerInstanceId }
: {}),
runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
activeTurnId: null,
lastError: thread.session?.lastError ?? null,
File diff suppressed because it is too large. Load diff
@@ -4,12 +4,16 @@ import {
CommandId,
MessageId,
type OrchestrationEvent,
type OrchestrationMessage,
type OrchestrationProposedPlanId,
CheckpointRef,
isToolLifecycleItemType,
ThreadId,
type ThreadTokenUsageSnapshot,
TurnId,
type OrchestrationCheckpointSummary,
type OrchestrationProposedPlan,
type OrchestrationThread,
type OrchestrationThreadActivity,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
@@ -19,9 +23,9 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
ProviderRuntimeIngestionService,
type ProviderRuntimeIngestionShape,
@@ -77,6 +81,82 @@ function sameId(left: string | null | undefined, right: string | null | undefine
return left === right;
}
function hasAssistantMessageForTurn(
messages: ReadonlyArray<OrchestrationMessage>,
turnId: TurnId,
options?: { readonly streamingOnly?: boolean },
): boolean {
for (let index = 0; index < messages.length; index += 1) {
const message = messages[index];
if (!message) {
continue;
}
if (message.role !== "assistant" || message.turnId !== turnId) {
continue;
}
if (options?.streamingOnly === true && !message.streaming) {
continue;
}
return true;
}
return false;
}
function findMessageById(
messages: ReadonlyArray<OrchestrationMessage>,
messageId: MessageId,
): OrchestrationMessage | undefined {
for (let index = 0; index < messages.length; index += 1) {
const message = messages[index];
if (message?.id === messageId) {
return message;
}
}
return undefined;
}
function findProposedPlanById(
proposedPlans: ReadonlyArray<
Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
>,
planId: string,
):
| Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
| undefined {
for (let index = 0; index < proposedPlans.length; index += 1) {
const proposedPlan = proposedPlans[index];
if (proposedPlan?.id === planId) {
return proposedPlan;
}
}
return undefined;
}
function hasCheckpointForTurn(
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
turnId: TurnId,
): boolean {
for (let index = 0; index < checkpoints.length; index += 1) {
if (checkpoints[index]?.turnId === turnId) {
return true;
}
}
return false;
}
function maxCheckpointTurnCount(
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
): number {
let maxTurnCount = 0;
for (let index = 0; index < checkpoints.length; index += 1) {
const checkpoint = checkpoints[index];
if (checkpoint && checkpoint.checkpointTurnCount > maxTurnCount) {
maxTurnCount = checkpoint.checkpointTurnCount;
}
}
return maxTurnCount;
}
function truncateDetail(value: string, limit = 180): string {
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
}
@@ -522,6 +602,7 @@ function runtimeEventToActivities(
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const serverSettingsService = yield* ServerSettingsService;
@@ -553,20 +634,16 @@ const make = Effect.gen(function* () {
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
});
const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
if (!thread) {
return false;
}
const workspaceCwd = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
});
if (!workspaceCwd) {
return false;
}
return isGitRepository(workspaceCwd);
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
return yield* projectionSnapshotQuery
.getThreadDetailById(threadId)
.pipe(Effect.map(Option.getOrUndefined));
});
const resolveThreadShell = Effect.fn("resolveThreadShell")(function* (threadId: ThreadId) {
return yield* projectionSnapshotQuery
.getThreadShellById(threadId)
.pipe(Effect.map(Option.getOrUndefined));
});
const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
@@ -917,7 +994,7 @@ const make = Effect.gen(function* () {
return;
}
const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId);
const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
@@ -1070,8 +1147,7 @@ const make = Effect.gen(function* () {
implementationThreadId: ThreadId,
implementedAt: string,
) {
const readModel = yield* orchestrationEngine.getReadModel();
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
const sourceThread = yield* resolveThreadDetail(sourceThreadId);
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
return;
@@ -1096,10 +1172,19 @@ const make = Effect.gen(function* () {
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
const thread = yield* resolveThreadShell(event.threadId);
if (!thread) return;
let loadedThreadDetail: OrchestrationThread | null | undefined;
const getLoadedThreadDetail = () =>
Effect.gen(function* () {
if (loadedThreadDetail !== undefined) {
return loadedThreadDetail;
}
loadedThreadDetail = (yield* resolveThreadDetail(thread.id)) ?? null;
return loadedThreadDetail;
});
const now = event.createdAt;
const eventTurnId = toTurnId(event.turnId);
const activeTurnId = thread.session?.activeTurnId ?? null;
@@ -1211,6 +1296,9 @@ const make = Effect.gen(function* () {
threadId: thread.id,
status,
providerName: event.provider,
...(event.providerInstanceId !== undefined
? { providerInstanceId: event.providerInstanceId }
: {}),
runtimeMode: thread.session?.runtimeMode ?? "full-access",
activeTurnId: nextActiveTurnId,
lastError,
@@ -1274,6 +1362,7 @@ const make = Effect.gen(function* () {
? toTurnId(event.turnId)
: undefined;
if (pauseForUserTurnId) {
const detailedThread = yield* getLoadedThreadDetail();
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
@@ -1304,10 +1393,11 @@ const make = Effect.gen(function* () {
event.type === "request.opened"
? "assistant-delta-finalize-on-request-opened"
: "assistant-delta-finalize-on-user-input-requested",
hasProjectedMessage: thread.messages.some(
(entry) =>
entry.role === "assistant" && entry.turnId === pauseForUserTurnId && entry.streaming,
),
hasProjectedMessage:
detailedThread !== null &&
hasAssistantMessageForTurn(detailedThread.messages, pauseForUserTurnId, {
streamingOnly: true,
}),
flushedMessageIds,
});
}
@@ -1336,21 +1426,19 @@ const make = Effect.gen(function* () {
: undefined;
if (assistantCompletion) {
const detailedThread = yield* getLoadedThreadDetail();
const messages = detailedThread?.messages ?? [];
const turnId = toTurnId(event.turnId);
const activeAssistantMessageId = turnId
? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId)
: Option.none<MessageId>();
const hasAssistantMessagesForTurn =
turnId !== undefined
? thread.messages.some((entry) => entry.role === "assistant" && entry.turnId === turnId)
: false;
turnId !== undefined ? hasAssistantMessageForTurn(messages, turnId) : false;
const assistantMessageId = Option.getOrElse(
activeAssistantMessageId,
() => assistantCompletion.messageId,
);
const existingAssistantMessage = thread.messages.find(
(entry) => entry.id === assistantMessageId,
);
const existingAssistantMessage = findMessageById(messages, assistantMessageId);
const shouldApplyFallbackCompletionText =
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
@@ -1390,10 +1478,11 @@ const make = Effect.gen(function* () {
}
if (proposedPlanCompletion) {
const detailedThread = yield* getLoadedThreadDetail();
yield* finalizeBufferedProposedPlan({
event,
threadId: thread.id,
threadProposedPlans: thread.proposedPlans,
threadProposedPlans: detailedThread?.proposedPlans ?? [],
planId: proposedPlanCompletion.planId,
...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
fallbackMarkdown: proposedPlanCompletion.planMarkdown,
@@ -1402,6 +1491,9 @@ const make = Effect.gen(function* () {
}
if (event.type === "turn.completed") {
const detailedThread = yield* getLoadedThreadDetail();
const messages = detailedThread?.messages ?? [];
const proposedPlans = detailedThread?.proposedPlans ?? [];
const turnId = toTurnId(event.turnId);
if (turnId) {
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
@@ -1416,9 +1508,7 @@ const make = Effect.gen(function* () {
createdAt: now,
commandTag: "assistant-complete-finalize",
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
hasProjectedMessage: thread.messages.some(
(entry) => entry.id === assistantMessageId,
),
hasProjectedMessage: findMessageById(messages, assistantMessageId) !== undefined,
}),
{ concurrency: 1 },
).pipe(Effect.asVoid);
@@ -1428,7 +1518,7 @@ const make = Effect.gen(function* () {
yield* finalizeBufferedProposedPlan({
event,
threadId: thread.id,
threadProposedPlans: thread.proposedPlans,
threadProposedPlans: proposedPlans,
planId: proposedPlanIdForTurn(thread.id, turnId),
turnId,
updatedAt: now,
@@ -1456,6 +1546,9 @@ const make = Effect.gen(function* () {
threadId: thread.id,
status: "error",
providerName: event.provider,
...(event.providerInstanceId !== undefined
? { providerInstanceId: event.providerInstanceId }
: {}),
runtimeMode: thread.session?.runtimeMode ?? "full-access",
activeTurnId: eventTurnId ?? null,
lastError: runtimeErrorMessage,
@@ -1477,21 +1570,24 @@ const make = Effect.gen(function* () {
if (event.type === "turn.diff.updated") {
const turnId = toTurnId(event.turnId);
if (turnId && (yield* isGitRepoForThread(thread.id))) {
const checkpointContext = turnId
? yield* projectionSnapshotQuery
.getThreadCheckpointContext(thread.id)
.pipe(Effect.map(Option.getOrUndefined))
: undefined;
const workspaceCwd =
checkpointContext?.worktreePath ?? checkpointContext?.workspaceRoot ?? undefined;
if (turnId && checkpointContext && workspaceCwd && isGitRepository(workspaceCwd)) {
// Skip if a checkpoint already exists for this turn. A real
// (non-placeholder) capture from CheckpointReactor should not
// be clobbered, and dispatching a duplicate placeholder for the
// same turnId would produce an unstable checkpointTurnCount.
if (thread.checkpoints.some((c) => c.turnId === turnId)) {
if (hasCheckpointForTurn(checkpointContext.checkpoints, turnId)) {
// Already tracked; no-op.
} else {
const assistantMessageId = MessageId.make(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
const maxTurnCount = thread.checkpoints.reduce(
(max, c) => Math.max(max, c.checkpointTurnCount),
0,
);
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: providerCommandId(event, "thread-turn-diff-complete"),
@@ -1502,7 +1598,7 @@ const make = Effect.gen(function* () {
status: "missing",
files: [],
assistantMessageId,
checkpointTurnCount: maxTurnCount + 1,
checkpointTurnCount: maxCheckpointTurnCount(checkpointContext.checkpoints) + 1,
createdAt: now,
});
}
@@ -10,11 +10,7 @@
*
* @module OrchestrationEngineService
*/
import type {
OrchestrationCommand,
OrchestrationEvent,
OrchestrationReadModel,
} from "@t3tools/contracts";
import type { OrchestrationCommand, OrchestrationEvent } from "@t3tools/contracts";
import { Context } from "effect";
import type { Effect, Stream } from "effect";
@@ -25,13 +21,6 @@ import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts";
* OrchestrationEngineShape - Service API for orchestration command and event flow.
*/
export interface OrchestrationEngineShape {
/**
* Read the current in-memory orchestration read model.
*
* @returns Effect containing the latest read model.
*/
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never, never>;
/**
* Replay persisted orchestration events from an exclusive sequence cursor.
*
@@ -70,7 +59,7 @@ export interface OrchestrationEngineShape {
* ```ts
* const program = Effect.gen(function* () {
* const engine = yield* OrchestrationEngineService
* return yield* engine.getReadModel()
* return yield* engine.dispatch(command)
* })
* ```
*/
@@ -28,6 +28,10 @@ export interface ProjectionSnapshotCounts {
readonly threadCount: number;
}
export interface ProjectionSnapshotSequence {
readonly snapshotSequence: number;
}
export interface ProjectionThreadCheckpointContext {
readonly threadId: ThreadId;
readonly projectId: ProjectId;
@@ -40,6 +44,15 @@ export interface ProjectionThreadCheckpointContext {
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
*/
export interface ProjectionSnapshotQueryShape {
/**
* Read the lightweight command snapshot used to bootstrap the in-memory
* orchestration engine without hydrating message/activity/checkpoint bodies.
*/
readonly getCommandReadModel: () => Effect.Effect<
OrchestrationReadModel,
ProjectionRepositoryError
>;
/**
* Read the latest orchestration projection snapshot.
*
@@ -59,6 +72,15 @@ export interface ProjectionSnapshotQueryShape {
ProjectionRepositoryError
>;
/**
* Read the latest projection snapshot sequence without hydrating read-model
* entities.
*/
readonly getSnapshotSequence: () => Effect.Effect<
ProjectionSnapshotSequence,
ProjectionRepositoryError
>;
/**
* Read aggregate projection counts without hydrating the full read model.
*/
@@ -7,6 +7,7 @@ import {
ThreadId,
type OrchestrationCommand,
type OrchestrationReadModel,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect } from "effect";
@@ -29,7 +30,7 @@ const readModel: OrchestrationReadModel = {
title: "Project A",
workspaceRoot: "/tmp/project-a",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
scripts: [],
@@ -42,7 +43,7 @@ const readModel: OrchestrationReadModel = {
title: "Project B",
workspaceRoot: "/tmp/project-b",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
scripts: [],
@@ -57,7 +58,7 @@ const readModel: OrchestrationReadModel = {
projectId: ProjectId.make("project-a"),
title: "Thread A",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -80,7 +81,7 @@ const readModel: OrchestrationReadModel = {
projectId: ProjectId.make("project-b"),
title: "Thread B",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -157,7 +158,7 @@ describe("commandInvariants", () => {
projectId: ProjectId.make("project-a"),
title: "new",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -181,7 +182,7 @@ describe("commandInvariants", () => {
projectId: ProjectId.make("project-a"),
title: "dup",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -7,6 +7,7 @@ import {
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
@@ -63,7 +64,7 @@ async function seedReadModel(): Promise<OrchestrationReadModel> {
projectId: asProjectId("project-delete"),
title: "Thread Delete 1",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -93,7 +94,7 @@ async function seedReadModel(): Promise<OrchestrationReadModel> {
projectId: asProjectId("project-delete"),
title: "Thread Delete 2",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -5,6 +5,7 @@ import {
MessageId,
ProjectId,
ThreadId,
ProviderInstanceId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { describe, expect, it } from "vitest";
@@ -138,7 +139,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -163,7 +164,7 @@ describe("decider project scripts", () => {
text: "hello",
attachments: [],
},
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -188,7 +189,7 @@ describe("decider project scripts", () => {
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.make("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -239,7 +240,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -321,7 +322,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+11 -10
View File
@@ -2,6 +2,7 @@ import {
CommandId,
EventId,
ProjectId,
ProviderDriverKind,
ThreadId,
type OrchestrationEvent,
} from "@t3tools/contracts";
@@ -57,7 +58,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -77,7 +78,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
instanceId: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -118,7 +119,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5-codex",
},
branch: null,
@@ -150,7 +151,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -253,7 +254,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -319,7 +320,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -376,7 +377,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -463,7 +464,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -678,7 +679,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -831,7 +832,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "capped",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1,4 +1,4 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { ProjectId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -28,7 +28,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
title: "Null options project",
workspaceRoot: "/tmp/project-null-options",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
scripts: [],
@@ -52,7 +52,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.strictEqual(
row.defaultModelSelection,
JSON.stringify({
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
}),
);
@@ -61,7 +61,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
projectId: ProjectId.make("project-null-options"),
});
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
});
}),
@@ -77,7 +77,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
projectId: ProjectId.make("project-null-options"),
title: "Null options thread",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
runtimeMode: "full-access",
@@ -110,7 +110,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.strictEqual(
row.modelSelection,
JSON.stringify({
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
}),
);
@@ -119,7 +119,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
threadId: ThreadId.make("thread-null-options"),
});
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
});
}),
@@ -23,6 +23,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
thread_id,
status,
provider_name,
provider_instance_id,
runtime_mode,
active_turn_id,
last_error,
@@ -32,6 +33,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
${row.threadId},
${row.status},
${row.providerName},
${row.providerInstanceId},
${row.runtimeMode},
${row.activeTurnId},
${row.lastError},
@@ -41,6 +43,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
DO UPDATE SET
status = excluded.status,
provider_name = excluded.provider_name,
provider_instance_id = excluded.provider_instance_id,
runtime_mode = excluded.runtime_mode,
active_turn_id = excluded.active_turn_id,
last_error = excluded.last_error,
@@ -57,6 +60,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
thread_id AS "threadId",
status,
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
runtime_mode AS "runtimeMode",
active_turn_id AS "activeTurnId",
last_error AS "lastError",
@@ -46,6 +46,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
INSERT INTO provider_session_runtime (
thread_id,
provider_name,
provider_instance_id,
adapter_key,
runtime_mode,
status,
@@ -56,6 +57,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
VALUES (
${runtime.threadId},
${runtime.providerName},
${runtime.providerInstanceId},
${runtime.adapterKey},
${runtime.runtimeMode},
${runtime.status},
@@ -66,6 +68,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
ON CONFLICT (thread_id)
DO UPDATE SET
provider_name = excluded.provider_name,
provider_instance_id = excluded.provider_instance_id,
adapter_key = excluded.adapter_key,
runtime_mode = excluded.runtime_mode,
status = excluded.status,
@@ -83,6 +86,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
adapter_key AS "adapterKey",
runtime_mode AS "runtimeMode",
status,
@@ -102,6 +106,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
adapter_key AS "adapterKey",
runtime_mode AS "runtimeMode",
status,
@@ -39,6 +39,9 @@ import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts";
import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";
/**
* Migration loader with all migrations defined inline.
@@ -77,6 +80,9 @@ export const migrationEntries = [
[24, "BackfillProjectionThreadShellSummary", Migration0024],
[25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
[26, "CanonicalizeModelSelectionOptions", Migration0026],
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
[28, "ProjectionThreadSessionInstanceId", Migration0028],
[29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,74 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("027_028_ProviderInstanceIdColumns", (it) => {
it.effect("continues when provider_session_runtime was partially migrated", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 26 });
yield* sql`
ALTER TABLE provider_session_runtime
ADD COLUMN provider_instance_id TEXT
`;
yield* runMigrations({ toMigrationInclusive: 28 });
const migrations = yield* sql<{
readonly migration_id: number;
readonly name: string;
}>`
SELECT migration_id, name
FROM effect_sql_migrations
WHERE migration_id IN (27, 28)
ORDER BY migration_id
`;
assert.deepStrictEqual(migrations, [
{
migration_id: 27,
name: "ProviderSessionRuntimeInstanceId",
},
{
migration_id: 28,
name: "ProjectionThreadSessionInstanceId",
},
]);
const providerSessionColumns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(provider_session_runtime)
`;
assert.ok(providerSessionColumns.some((column) => column.name === "provider_instance_id"));
const projectionThreadSessionColumns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_thread_sessions)
`;
assert.ok(
projectionThreadSessionColumns.some((column) => column.name === "provider_instance_id"),
);
const providerSessionIndexes = yield* sql<{ readonly name: string }>`
PRAGMA index_list(provider_session_runtime)
`;
assert.ok(
providerSessionIndexes.some(
(index) => index.name === "idx_provider_session_runtime_instance",
),
);
const projectionThreadSessionIndexes = yield* sql<{ readonly name: string }>`
PRAGMA index_list(projection_thread_sessions)
`;
assert.ok(
projectionThreadSessionIndexes.some(
(index) => index.name === "idx_projection_thread_sessions_instance",
),
);
}),
);
});
@@ -0,0 +1,38 @@
/**
* Adds the nullable `provider_instance_id` routing column to
* `provider_session_runtime`.
*
* Slice D of the provider-array refactor splits "driver kind" from
* "configured instance". Existing rows have only the driver name in
* `provider_name`; new rows additionally carry the user-defined instance
* routing key. The column remains nullable so legacy rows can still decode;
* the persistence boundary is responsible for materializing a concrete
* instance id before any hot routing path sees the binding.
*
* The column is nullable on purpose — backfilling it during the migration
* would require knowing which configured instance "owned" each historical
* session, and that mapping is ambiguous when the user later configures
* multiple instances of the same driver. Keeping that compatibility at the
* persistence boundary keeps the fallback out of active routing code.
*/
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(provider_session_runtime)
`;
if (!columns.some((column) => column.name === "provider_instance_id")) {
yield* sql`
ALTER TABLE provider_session_runtime
ADD COLUMN provider_instance_id TEXT
`;
}
yield* sql`
CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_instance
ON provider_session_runtime(provider_instance_id)
`;
});
@@ -0,0 +1,21 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_thread_sessions)
`;
if (!columns.some((column) => column.name === "provider_instance_id")) {
yield* sql`
ALTER TABLE projection_thread_sessions
ADD COLUMN provider_instance_id TEXT
`;
}
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_thread_sessions_instance
ON projection_thread_sessions(provider_instance_id)
`;
});
@@ -0,0 +1,73 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("029_ProjectionThreadDetailOrderingIndexes", (it) => {
it.effect("creates indexes matching thread detail ordering queries", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 28 });
yield* runMigrations({ toMigrationInclusive: 29 });
const activityIndexes = yield* sql<{
readonly seq: number;
readonly name: string;
readonly unique: number;
readonly origin: string;
readonly partial: number;
}>`
PRAGMA index_list(projection_thread_activities)
`;
assert.ok(
activityIndexes.some(
(index) => index.name === "idx_projection_thread_activities_thread_sequence_created_id",
),
);
const activityIndexColumns = yield* sql<{
readonly seqno: number;
readonly cid: number;
readonly name: string;
}>`
PRAGMA index_info('idx_projection_thread_activities_thread_sequence_created_id')
`;
assert.deepStrictEqual(
activityIndexColumns.map((column) => column.name),
["thread_id", "sequence", "created_at", "activity_id"],
);
const messageIndexes = yield* sql<{
readonly seq: number;
readonly name: string;
readonly unique: number;
readonly origin: string;
readonly partial: number;
}>`
PRAGMA index_list(projection_thread_messages)
`;
assert.ok(
messageIndexes.some(
(index) => index.name === "idx_projection_thread_messages_thread_created_id",
),
);
const messageIndexColumns = yield* sql<{
readonly seqno: number;
readonly cid: number;
readonly name: string;
}>`
PRAGMA index_info('idx_projection_thread_messages_thread_created_id')
`;
assert.deepStrictEqual(
messageIndexColumns.map((column) => column.name),
["thread_id", "created_at", "message_id"],
);
}),
);
});
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence_created_id
ON projection_thread_activities(thread_id, sequence, created_at, activity_id)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_thread_messages_thread_created_id
ON projection_thread_messages(thread_id, created_at, message_id)
`;
});
@@ -10,6 +10,7 @@ import {
RuntimeMode,
IsoDateTime,
OrchestrationSessionStatus,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
@@ -22,6 +23,7 @@ export const ProjectionThreadSession = Schema.Struct({
threadId: ThreadId,
status: OrchestrationSessionStatus,
providerName: Schema.NullOr(Schema.String),
providerInstanceId: Schema.NullOr(ProviderInstanceId),
runtimeMode: RuntimeMode,
activeTurnId: Schema.NullOr(TurnId),
lastError: Schema.NullOr(Schema.String),
Loaded 100 of 494 files, more files were not shown because too many files have changed in this diff. Show more