Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 2fedbbc83c move ws package to server dev dependencies
Co-authored-by: Julius Marminge <[email protected]>
2026-03-11 02:34:34 +00:00
Cursor AgentandJulius Marminge 37f063f537 migrate server routing to effect httprouter websocket
Co-authored-by: Julius Marminge <[email protected]>
2026-03-11 02:31:33 +00:00
Cursor AgentandJulius Marminge 082876c397 refactor ws push bus client abstraction
Co-authored-by: Julius Marminge <[email protected]>
2026-03-11 02:13:49 +00:00
Julius Marminge 7b11cdd56f add reference 2026-03-10 18:52:47 -07:00
250 changed files with 10294 additions and 30335 deletions

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --base-dir ~/.t3-2`
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
-117
View File
@@ -1,117 +0,0 @@
name: Bug report
description: Report broken behavior, regressions, crashes, or reliability issues.
title: "[Bug]: "
labels:
- bug
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for broken behavior, regressions, crashes, or reliability problems.
Search existing issues first and keep the report focused on one problem.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I included enough detail to reproduce or investigate the problem.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project is affected?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: Provide a minimal, deterministic repro.
placeholder: |
1. Start the app with ...
2. Open ...
3. Disconnect the network
4. Reconnect and send another prompt
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
placeholder: The thread should resume normally and accept the new message.
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual behavior
placeholder: The composer clears, no new turn starts, and the session stays in a pending state.
validations:
required: true
- type: dropdown
id: impact
attributes:
label: Impact
description: How bad is this in practice?
options:
- Blocks work completely
- Major degradation or frequent failure
- Minor bug or occasional failure
- Cosmetic issue
validations:
required: true
- type: input
id: version
attributes:
label: Version or commit
description: Release version, commit SHA, or branch name if known.
placeholder: main @ abc1234
- type: input
id: environment
attributes:
label: Environment
description: OS, browser or desktop app version, Node/Bun version, provider/model if relevant.
placeholder: macOS 15.3, Chrome 135, Bun 1.3.9, Codex app-server ...
- type: textarea
id: logs
attributes:
label: Logs or stack traces
description: Paste the most relevant output only. Redact secrets.
render: shell
- type: upload
id: attachments
attributes:
label: Screenshots, recordings, or supporting files
description: Upload screenshots, short recordings, repro archives, or log files. Redact secrets before uploading.
validations:
required: false
accept: ".png,.jpg,.jpeg,.gif,.webp,.svg,.mp4,.mov,.webm,.log,.txt,.json,.zip"
- type: textarea
id: workaround
attributes:
label: Workaround
description: If you found a temporary workaround, include it.
placeholder: Restarting the provider session clears the stuck state.
-101
View File
@@ -1,101 +0,0 @@
name: Feature request
description: Propose a scoped improvement or new capability.
title: "[Feature]: "
labels:
- enhancement
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for new capabilities or meaningful improvements to existing behavior.
This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I am describing a concrete problem or use case, not just a vague idea.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project would this change affect?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: problem
attributes:
label: Problem or use case
description: What are you trying to do? What is hard, slow, or impossible today?
placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state.
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: Describe the behavior, API, or UX you want.
placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load.
validations:
required: true
- type: textarea
id: value
attributes:
label: Why this matters
description: Who benefits, and what outcome does this unlock?
placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions.
validations:
required: true
- type: textarea
id: scope
attributes:
label: Smallest useful scope
description: What is the narrowest version of this request that would still solve your problem?
placeholder: A first pass only needs to support restoring the active session for the current thread.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: Workarounds, prior art, or other approaches you considered.
placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context.
- type: textarea
id: tradeoffs
attributes:
label: Risks or tradeoffs
description: What costs, complexity, or edge cases should be considered?
placeholder: This may require careful handling when the underlying provider session has already exited.
- type: textarea
id: references
attributes:
label: Examples or references
description: Links, screenshots, mockups, or comparable tools.
- type: checkboxes
id: contribution
attributes:
label: Contribution
options:
- label: I would be open to helping implement this.
-2
View File
@@ -19,7 +19,6 @@ github:hwanseoc
github:jamesx0416
github:jasonLaster
github:JoeEverest
github:maria-rcks
github:nmggithub
github:Noojuno
github:notkainoa
@@ -28,4 +27,3 @@ github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
+6 -6
View File
@@ -12,7 +12,7 @@ jobs:
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -20,12 +20,12 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Cache Bun and Turbo
uses: actions/cache@v5
uses: actions/cache@v4
with:
path: |
~/.bun/install/cache
@@ -35,7 +35,7 @@ jobs:
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v5
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
@@ -78,7 +78,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -86,7 +86,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
-75
View File
@@ -1,75 +0,0 @@
name: Issue Labels
on:
push:
branches:
- main
paths:
- .github/ISSUE_TEMPLATE/**
- .github/workflows/issue-labels.yml
workflow_dispatch:
permissions:
issues: write
jobs:
sync:
name: Sync issue labels
runs-on: ubuntu-24.04
steps:
- name: Ensure managed issue labels exist
uses: actions/github-script@v7
with:
script: |
const managedLabels = [
{
name: "bug",
color: "d73a4a",
description: "Something is broken or behaving incorrectly.",
},
{
name: "enhancement",
color: "a2eeef",
description: "Requested improvement or new capability.",
},
{
name: "needs-triage",
color: "fbca04",
description: "Issue needs maintainer review and initial categorization.",
},
];
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
-255
View File
@@ -1,255 +0,0 @@
name: PR Size
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
permissions:
contents: read
jobs:
prepare-config:
name: Prepare PR size config
runs-on: ubuntu-24.04
outputs:
labels_json: ${{ steps.config.outputs.labels_json }}
steps:
- id: config
name: Build PR size label config
uses: actions/github-script@v8
with:
result-encoding: string
script: |
const managedLabels = [
{
name: "size:XS",
color: "0e8a16",
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:S",
color: "5ebd3e",
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:M",
color: "fbca04",
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:L",
color: "fe7d37",
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:XL",
color: "d93f0b",
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:XXL",
color: "b60205",
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
},
];
core.setOutput("labels_json", JSON.stringify(managedLabels));
sync-label-definitions:
name: Sync PR size label definitions
needs: prepare-config
if: github.event_name != 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: write
steps:
- name: Ensure PR size labels exist
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
}
}
label:
name: Label PR size
needs: prepare-config
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: read
pull-requests: write
concurrency:
group: pr-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
steps:
- name: Sync PR size label
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const issueNumber = context.payload.pull_request.number;
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
// Keep this aligned with the repo's test entrypoints and test-only support files.
const testFilePatterns = [
/(^|\/)__tests__(\/|$)/,
/(^|\/)tests?(\/|$)/,
/^apps\/server\/integration\//,
/\.(test|spec|browser|integration)\.[^.\/]+$/,
];
const isTestFile = (filename) =>
testFilePatterns.some((pattern) => pattern.test(filename));
const resolveSizeLabel = (totalChangedLines) => {
if (totalChangedLines < 10) {
return "size:XS";
}
if (totalChangedLines < 30) {
return "size:S";
}
if (totalChangedLines < 100) {
return "size:M";
}
if (totalChangedLines < 500) {
return "size:L";
}
if (totalChangedLines < 1000) {
return "size:XL";
}
return "size:XXL";
};
const files = await github.paginate(
github.rest.pulls.listFiles,
{
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: issueNumber,
per_page: 100,
},
(response) => response.data,
);
if (files.length >= 3000) {
core.warning(
"The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.",
);
}
let testChangedLines = 0;
let nonTestChangedLines = 0;
for (const file of files) {
const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0);
if (changedLinesForFile === 0) {
continue;
}
if (isTestFile(file.filename)) {
testChangedLines += changedLinesForFile;
continue;
}
nonTestChangedLines += changedLinesForFile;
}
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
const nextLabelName = resolveSizeLabel(changedLines);
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
const classification =
nonTestChangedLines === 0
? testChangedLines > 0
? "test-only PR"
: "no line changes"
: testChangedLines > 0
? "test lines excluded"
: "all non-test changes";
core.info(
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
);
+19 -43
View File
@@ -25,7 +25,7 @@ jobs:
targets: ${{ steps.collect.outputs.targets }}
steps:
- id: collect
uses: actions/github-script@v8
uses: actions/github-script@v7
with:
script: |
if (context.eventName === "pull_request_target") {
@@ -85,7 +85,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Sync PR labels
uses: actions/github-script@v8
uses: actions/github-script@v7
env:
PR_NUMBER: ${{ matrix.target.number }}
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
@@ -111,7 +111,7 @@ jobs:
},
];
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
const managedLabelNames = managedLabels.map((label) => label.name);
for (const label of managedLabels) {
try {
@@ -138,19 +138,13 @@ jobs:
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
@@ -165,35 +159,17 @@ jobs:
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
const preservedLabels = currentLabels
.map((label) => label.name)
.filter((name) => !managedLabelNames.includes(name));
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
await github.rest.issues.setLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [...preservedLabels, nextLabelName],
});
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
+14 -40
View File
@@ -27,7 +27,7 @@ jobs:
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- id: release_meta
name: Resolve release version
@@ -61,7 +61,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
@@ -107,7 +107,7 @@ jobs:
arch: x64
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
@@ -118,16 +118,13 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build desktop artifact
shell: bash
env:
@@ -217,7 +214,7 @@ jobs:
fi
- name: Upload build artifacts
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release-publish/*
@@ -229,7 +226,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
@@ -239,7 +236,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
@@ -247,9 +244,6 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
@@ -262,17 +256,17 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
pattern: desktop-*
merge-multiple: true
@@ -308,31 +302,11 @@ jobs:
needs: [preflight, release]
runs-on: ubuntu-24.04
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
token: ${{ steps.app_token.outputs.token }}
persist-credentials: true
- id: app_bot
name: Resolve GitHub App bot identity
env:
GH_TOKEN: ${{ steps.app_token.outputs.token }}
APP_SLUG: ${{ steps.app_token.outputs.app-slug }}
run: |
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -340,7 +314,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
@@ -369,8 +343,8 @@ jobs:
exit 0
fi
git config user.name "${{ steps.app_bot.outputs.name }}"
git config user.email "${{ steps.app_bot.outputs.email }}"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
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"
-4
View File
@@ -13,10 +13,6 @@ build/
.logs/
release/
.t3
.idea/
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
-441
View File
@@ -1,441 +0,0 @@
# Plan: Claude Code Integration (Orchestration Architecture)
## Why this plan was rewritten
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
1. `orchestration.dispatchCommand` (client intent)
2. `OrchestrationEngine` (decide + persist + publish domain events)
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
4. `ProviderService` (adapter routing + canonical runtime stream)
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
6. `orchestration.domainEvent` (single push channel consumed by web)
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
---
## Current constraints to design around (post-Stage 1)
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
---
## Architecture target
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
Key decisions:
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
---
## Phase 1: Contracts and command shape updates
### 1.1 Provider-aware model contract
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
Expected outcomes:
1. Introduce provider-scoped model lists (Codex + Claude).
2. Add helpers that resolve model by provider.
3. Preserve backwards compatibility for existing Codex defaults.
### 1.2 Turn-start provider intent
Update `packages/contracts/src/orchestration.ts`:
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
2. Carry provider through `ThreadTurnStartRequestedPayload`.
3. Keep existing command valid when provider is omitted.
This removes the implicit “Codex unless session already exists” behavior as the only path.
### 1.3 Provider session start input for Claude runtime knobs (completed)
Update `packages/contracts/src/provider.ts`:
1. Move provider-specific start fields into typed `providerOptions`:
- `providerOptions.codex`
- `providerOptions.claudeCode`
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
3. Deprecate/remove `resumeThreadId` from the generic start contract.
4. Treat `resumeCursor` as adapter-owned opaque state.
### 1.4 Contract tests (completed)
Update/add tests in `packages/contracts/src/*.test.ts` for:
1. New command payload shape.
2. Provider-aware model resolution behavior.
3. Breaking-change expectations for removed top-level provider fields.
---
## Phase 2: Claude adapter implementation
### 2.1 Add adapter service + layer
Create:
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
### 2.1.a SDK dependency and baseline config
Add server dependency:
1. `@anthropic-ai/claude-agent-sdk`
Baseline adapter options to support from day one:
1. `cwd`
2. `model`
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
6. `resume`
7. `resumeSessionAt`
8. `includePartialMessages`
9. `canUseTool`
10. `hooks`
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
### 2.2 Claude runtime bridge
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
Required capabilities:
1. Long-lived session context per adapter session.
2. Multi-turn input queue.
3. Interrupt support.
4. Approval request/response bridge.
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
#### 2.2.a Agent SDK details to preserve
The adapter should explicitly rely on these SDK capabilities:
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
2. Multi-turn input is supported via async-iterable prompt input.
3. Tool approval decisions are provided via `canUseTool`.
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
#### 2.2.b Effect-native session lifecycle skeleton
```ts
import { query } from "@anthropic-ai/claude-agent-sdk";
import { Effect } from "effect";
const acquireSession = (input: ProviderSessionStartInput) =>
Effect.acquireRelease(
Effect.tryPromise({
try: async () => {
const claudeOptions = input.providerOptions?.claudeCode;
const resumeState = readClaudeResumeState(input.resumeCursor);
const abortController = new AbortController();
const result = query({
prompt: makePromptAsyncIterable(),
options: {
cwd: input.cwd,
model: input.model,
permissionMode: claudeOptions?.permissionMode,
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
resume: resumeState?.threadId,
resumeSessionAt: resumeState?.sessionAt,
signal: abortController.signal,
includePartialMessages: true,
canUseTool: makeCanUseTool(),
hooks: makeClaudeHooks(),
},
});
return { abortController, result };
},
catch: (cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId: "pending",
detail: "Failed to start Claude runtime session.",
cause,
}),
}),
({ abortController }) => Effect.sync(() => abortController.abort()),
);
```
#### 2.2.c AsyncIterable -> Effect Stream integration
Preferred when available in the pinned Effect version:
```ts
const sdkMessageStream = Stream.fromAsyncIterable(
session.result,
(cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
```
Portable fallback (already aligned with current server patterns):
```ts
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
let cancelled = false;
void (async () => {
try {
for await (const message of session.result) {
if (cancelled) break;
emit.single(message);
}
emit.end();
} catch (cause) {
emit.fail(
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
}
})();
return Effect.sync(() => {
cancelled = true;
});
});
```
### 2.3 Canonical event mapping
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
Initial mapping target:
1. assistant text deltas -> `content.delta`
2. final assistant text -> `item.completed` and/or `turn.completed`
3. approval requests -> `request.opened`
4. approval results -> `request.resolved`
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
6. errors -> `runtime.error`
7. plan/proposed-plan content when derivable
Implementation note:
1. Keep raw Claude message on `raw` for debugging.
2. Prefer canonical item/request kinds over provider-native enums.
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
### 2.4 Resume cursor strategy
Define Claude-owned opaque resume state, e.g.:
```ts
interface ClaudeResumeCursor {
readonly version: 1;
readonly threadId?: string;
readonly sessionAt?: string;
}
```
Rules:
1. Serialize only adapter-owned state into `resumeCursor`.
2. Parse/validate only inside Claude adapter.
3. Store updated cursor when Claude runtime yields enough data to resume safely.
4. Never overload orchestration thread id as Claude thread id.
### 2.5 Interrupt and stop semantics
Map orchestration stop/interrupt expectations onto SDK controls:
1. `interruptTurn()` -> active query interrupt.
2. `stopSession()` -> close session resources and prevent future sends.
3. `rollbackThread()` -> see Phase 4.
---
## Phase 3: Provider service and composition
### 3.1 Register Claude adapter
Update provider registry layer to include Claude:
1. add `claudeCode` -> `ClaudeAdapter`
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
### 3.2 Persist provider binding
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
Required validation:
1. Claude bindings survive restart.
2. resume cursor remains opaque and round-trips untouched.
3. stopAll + restart can recover Claude sessions when possible.
### 3.3 Provider start routing
Update `ProviderCommandReactor` / orchestration flow:
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
2. If a thread already has Claude session binding, reuse it.
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
---
## Phase 4: Checkpoint and revert strategy
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
Pick one explicit strategy:
### Option A: provider-native rewind
If SDK/runtime supports safe rewind:
1. implement in Claude adapter
2. keep `CheckpointReactor` unchanged
### Option B: session restart + state truncation shim
If no native rewind exists:
1. Claude adapter returns successful rollback by:
- stopping current Claude session
- clearing/rewriting stored Claude resume cursor to last safe resumable point
- forcing next turn to recreate session from persisted orchestration state
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
Whichever option is chosen:
1. behavior must be deterministic
2. checkpoint revert tests must pass under orchestration expectations
3. user-visible activity log should explain failures clearly when provider rollback is impossible
---
## Phase 5: Web integration
### 5.1 Provider picker and model picker
Update web state/UI:
1. allow choosing Claude as thread provider before first turn
2. show Claude model list from provider-aware model helpers
3. preserve existing Codex default behavior when provider omitted
Likely touch points:
1. `apps/web/src/store.ts`
2. `apps/web/src/components/ChatView.tsx`
3. `apps/web/src/types.ts`
4. `packages/shared/src/model.ts`
### 5.2 Settings for Claude executable/options
Add app settings if needed for:
1. Claude binary path
2. default permission mode
3. default max thinking tokens
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
### 5.3 Session rendering
No new WS channel should be needed. Claude should appear through existing:
1. thread messages
2. activities/worklog
3. approvals
4. session state
5. checkpoints/diffs
---
## Phase 6: Testing strategy
### 6.1 Contract tests
Cover:
1. provider-aware model schemas
2. provider field on turn-start command
3. provider-specific start options schema
### 6.2 Adapter layer tests
Add `ClaudeAdapter.test.ts` covering:
1. session start
2. event mapping
3. approval bridge
4. resume cursor parse/serialize
5. interrupt behavior
6. rollback behavior or explicit unsupported error path
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
### 6.3 Provider service integration tests
Extend provider integration coverage so Claude is exercised through `ProviderService`:
1. start Claude session
2. send turn
3. receive canonical runtime events
4. restart/recover using persisted binding
### 6.4 Orchestration integration tests
Add/extend integration tests around:
1. first-turn provider selection
2. Claude approval requests routed through orchestration
3. Claude runtime ingestion -> messages/activities/session updates
4. checkpoint revert behavior under Claude
5. stopAll/restart recovery
These should validate real orchestration flows, not just adapter behavior.
---
## Phase 7: Rollout order
Recommended implementation order:
1. contracts/provider-aware models
2. provider field on turn-start
3. Claude adapter skeleton + start/send/stream
4. canonical event mapping
5. provider registry/service wiring
6. orchestration recovery + checkpoint strategy
7. web provider/model picker
8. full integration tests
---
## Non-goals
1. Reintroducing provider-specific WS methods/channels.
2. Storing provider-native thread ids as orchestration ids.
3. Bypassing orchestration engine for Claude-specific UI flows.
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@effect-http-ws-cli/server",
"version": "0.1.0",
"private": true,
"type": "module",
"exports": {
"./client": "./src/client.ts",
"./contracts": "./src/contracts.ts"
},
"scripts": {
"dev": "node src/bin.ts",
"start": "node src/bin.ts",
"test": "vitest run",
"lint": "tsc --noEmit"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-node": "catalog:",
"effect": "catalog:"
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/node": "^24.10.0",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
@@ -0,0 +1,32 @@
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 TABLE IF NOT EXISTS todos (
id TEXT PRIMARY KEY NOT NULL,
title TEXT NOT NULL,
completed INTEGER NOT NULL,
archived INTEGER NOT NULL,
revision INTEGER NOT NULL,
updated_at TEXT NOT NULL
)
`
yield* sql`
CREATE TABLE IF NOT EXISTS todo_events (
event_offset INTEGER PRIMARY KEY AUTOINCREMENT,
at TEXT NOT NULL,
todo_json TEXT NOT NULL,
change_json TEXT NOT NULL,
archived INTEGER NOT NULL
)
`
yield* sql`
CREATE INDEX IF NOT EXISTS idx_todo_events_archived_offset
ON todo_events (archived, event_offset)
`
})
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime"
import * as NodeServices from "@effect/platform-node/NodeServices"
import * as Effect from "effect/Effect"
import { cli } from "./cli.ts"
import { Command } from "effect/unstable/cli"
Command.run(cli, { version: "0.1.0" }).pipe(
Effect.provide(NodeServices.layer),
NodeRuntime.runMain
)
+125
View File
@@ -0,0 +1,125 @@
import * as SqliteNode from "@effect/sql-sqlite-node"
import { Command, Flag } from "effect/unstable/cli"
import * as Config from "effect/Config"
import * as Effect from "effect/Effect"
import * as FileSystem from "effect/FileSystem"
import * as Option from "effect/Option"
import * as Path from "effect/Path"
import { fileURLToPath } from "node:url"
import { ServerConfig } from "./config.ts"
import { runMigrations } from "./migrations.ts"
import { runServer } from "./server.ts"
import type { ServerConfigData } from "./config.ts"
const defaultAssetsDir = fileURLToPath(new URL("../../public", import.meta.url))
const defaultDbFilename = fileURLToPath(new URL("../../todo.sqlite", import.meta.url))
const hostFlag = Flag.string("host").pipe(
Flag.withDescription("Host interface to bind"),
Flag.optional
)
const portFlag = Flag.integer("port").pipe(
Flag.withDescription("Port to listen on"),
Flag.optional
)
const assetsFlag = Flag.directory("assets").pipe(
Flag.withDescription("Directory of static assets"),
Flag.optional
)
const dbFlag = Flag.string("db").pipe(
Flag.withDescription("SQLite database filename"),
Flag.optional
)
const requestLoggingFlag = Flag.boolean("request-logging").pipe(
Flag.withDescription("Enable request logging"),
Flag.optional
)
const frontendDevOriginFlag = Flag.string("frontend-dev-origin").pipe(
Flag.withDescription("Redirect frontend GET requests to a Vite dev server origin"),
Flag.optional
)
const EnvServerConfig = Config.unwrap({
host: Config.string("HOST").pipe(Config.withDefault("127.0.0.1")),
port: Config.port("PORT").pipe(Config.withDefault(8787)),
assetsDir: Config.string("ASSETS_DIR").pipe(Config.withDefault(defaultAssetsDir)),
dbFilename: Config.string("DB_FILENAME").pipe(Config.withDefault(defaultDbFilename)),
requestLogging: Config.boolean("REQUEST_LOGGING").pipe(Config.withDefault(true)),
frontendDevOrigin: Config.string("FRONTEND_DEV_ORIGIN").pipe(
Config.option,
Config.map(Option.getOrUndefined)
)
})
export interface CliServerFlags {
readonly host: Option.Option<string>
readonly port: Option.Option<number>
readonly assets: Option.Option<string>
readonly db: Option.Option<string>
readonly requestLogging: Option.Option<boolean>
readonly frontendDevOrigin: Option.Option<string>
}
export const resolveServerConfig = (
flags: CliServerFlags
): Effect.Effect<ServerConfigData, Config.ConfigError> =>
Effect.gen(function*() {
const env = yield* EnvServerConfig
return {
host: Option.getOrElse(flags.host, () => env.host),
port: Option.getOrElse(flags.port, () => env.port),
assetsDir: Option.getOrElse(flags.assets, () => env.assetsDir),
dbFilename: Option.getOrElse(flags.db, () => env.dbFilename),
requestLogging: Option.getOrElse(flags.requestLogging, () => env.requestLogging),
frontendDevOrigin: Option.getOrElse(flags.frontendDevOrigin, () => env.frontendDevOrigin)
}
})
export const resetDatabase = (dbFilename: string) =>
Effect.gen(function*() {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
if (dbFilename !== ":memory:") {
yield* fs.remove(path.resolve(dbFilename), { force: true })
}
const sqliteLayer = SqliteNode.SqliteClient.layer({
filename: dbFilename
})
yield* runMigrations.pipe(Effect.provide(sqliteLayer))
})
const commandFlags = {
host: hostFlag,
port: portFlag,
assets: assetsFlag,
db: dbFlag,
requestLogging: requestLoggingFlag,
frontendDevOrigin: frontendDevOriginFlag
} as const
const rootCommand = Command.make("effect-http-ws-cli", commandFlags).pipe(
Command.withDescription("Run a unified Effect HTTP + WebSocket server"),
Command.withHandler((flags) =>
Effect.flatMap(resolveServerConfig(flags), (config) =>
runServer.pipe(Effect.provideService(ServerConfig, config)))),
)
const resetCommand = Command.make("reset", commandFlags).pipe(
Command.withDescription("Delete the SQLite database file and rerun migrations"),
Command.withHandler((flags) =>
Effect.flatMap(resolveServerConfig(flags), (config) => resetDatabase(config.dbFilename))
)
)
export const cli = rootCommand.pipe(
Command.withSubcommands([resetCommand])
)
+58
View File
@@ -0,0 +1,58 @@
import { NodeSocket } from "@effect/platform-node"
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as RpcClient from "effect/unstable/rpc/RpcClient"
import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization"
import * as Stream from "effect/Stream"
import { WsRpcGroup } from "./contracts.ts"
export const wsRpcProtocolLayer = (wsUrl: string) =>
RpcClient.layerProtocolSocket().pipe(
Layer.provide(NodeSocket.layerWebSocket(wsUrl)),
Layer.provide(RpcSerialization.layerJson)
)
export const makeWsRpcClient = RpcClient.make(WsRpcGroup)
type WsRpcClient = typeof makeWsRpcClient extends Effect.Effect<infer Client, any, any> ? Client : never
export const withWsRpcClient = <A, E, R>(
wsUrl: string,
f: (client: WsRpcClient) => Effect.Effect<A, E, R>
) =>
makeWsRpcClient.pipe(
Effect.flatMap(f),
Effect.provide(wsRpcProtocolLayer(wsUrl))
)
export const runClientExample = (wsUrl: string) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const echoed = yield* client.echo({ text: "hello from client" })
const summed = yield* client.sum({ left: 20, right: 22 })
const time = yield* client.time(undefined)
return { echoed, summed, time }
})
)
)
export const runSubscriptionExample = (wsUrl: string, modelId: string) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const todo = snapshot.todos[0]
if (!todo) {
return []
}
yield* client.renameTodo({ id: todo.id, title: `${modelId}: first` })
yield* client.completeTodo({ id: todo.id, completed: true })
return yield* client.subscribeTodos({ fromOffset: snapshot.offset, includeArchived: true }).pipe(
Stream.take(2),
Stream.runCollect
)
})
)
)
+14
View File
@@ -0,0 +1,14 @@
import * as ServiceMap from "effect/ServiceMap"
export interface ServerConfigData {
readonly host: string
readonly port: number
readonly assetsDir: string
readonly dbFilename: string
readonly requestLogging: boolean
readonly frontendDevOrigin: string | undefined
}
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigData>()(
"effect-http-ws-cli/ServerConfig"
) {}
+132
View File
@@ -0,0 +1,132 @@
import * as Schema from "effect/Schema"
import * as Rpc from "effect/unstable/rpc/Rpc"
import * as RpcGroup from "effect/unstable/rpc/RpcGroup"
export const EchoPayload = Schema.Struct({
text: Schema.String
})
export const EchoResult = Schema.Struct({
text: Schema.String
})
export const SumPayload = Schema.Struct({
left: Schema.Number,
right: Schema.Number
})
export const SumResult = Schema.Struct({
total: Schema.Number
})
export const TimeResult = Schema.Struct({
iso: Schema.String
})
export const Todo = Schema.Struct({
id: Schema.String,
title: Schema.String,
completed: Schema.Boolean,
archived: Schema.Boolean,
revision: Schema.Number,
updatedAt: Schema.String
})
export type Todo = Schema.Schema.Type<typeof Todo>
export const TodoChange = Schema.Union([
Schema.Struct({
_tag: Schema.Literal("TodoCreated")
}),
Schema.Struct({
_tag: Schema.Literal("TodoRenamed"),
title: Schema.String
}),
Schema.Struct({
_tag: Schema.Literal("TodoCompleted"),
completed: Schema.Boolean
}),
Schema.Struct({
_tag: Schema.Literal("TodoArchived"),
archived: Schema.Boolean
})
])
export type TodoChange = Schema.Schema.Type<typeof TodoChange>
export const TodoEvent = Schema.Struct({
offset: Schema.Number,
at: Schema.String,
todo: Todo,
change: TodoChange
})
export type TodoEvent = Schema.Schema.Type<typeof TodoEvent>
export const TodoSnapshot = Schema.Struct({
offset: Schema.Number,
todos: Schema.Array(Todo)
})
export type TodoSnapshot = Schema.Schema.Type<typeof TodoSnapshot>
export const EchoRpc = Rpc.make("echo", {
payload: EchoPayload,
success: EchoResult
})
export const SumRpc = Rpc.make("sum", {
payload: SumPayload,
success: SumResult
})
export const TimeRpc = Rpc.make("time", {
success: TimeResult
})
export const ListTodosRpc = Rpc.make("listTodos", {
payload: Schema.Struct({
includeArchived: Schema.Boolean
}),
success: TodoSnapshot
})
export const RenameTodoRpc = Rpc.make("renameTodo", {
payload: Schema.Struct({
id: Schema.String,
title: Schema.String
}),
success: TodoEvent
})
export const CompleteTodoRpc = Rpc.make("completeTodo", {
payload: Schema.Struct({
id: Schema.String,
completed: Schema.Boolean
}),
success: TodoEvent
})
export const ArchiveTodoRpc = Rpc.make("archiveTodo", {
payload: Schema.Struct({
id: Schema.String,
archived: Schema.Boolean
}),
success: TodoEvent
})
export const SubscribeTodosRpc = Rpc.make("subscribeTodos", {
payload: Schema.Struct({
fromOffset: Schema.Number,
includeArchived: Schema.Boolean
}),
success: TodoEvent,
stream: true
})
export const WsRpcGroup = RpcGroup.make(
EchoRpc,
SumRpc,
TimeRpc,
ListTodosRpc,
RenameTodoRpc,
CompleteTodoRpc,
ArchiveTodoRpc,
SubscribeTodosRpc
)
+73
View File
@@ -0,0 +1,73 @@
import * as Schema from "effect/Schema"
import * as SchemaTransformation from "effect/SchemaTransformation"
export const ClientMessage = Schema.Union([
Schema.Struct({
kind: Schema.Literal("echo"),
text: Schema.String
}),
Schema.Struct({
kind: Schema.Literal("sum"),
left: Schema.Number,
right: Schema.Number
}),
Schema.Struct({
kind: Schema.Literal("time")
})
])
export type ClientMessage = Schema.Schema.Type<typeof ClientMessage>
export const ServerMessage = Schema.Union([
Schema.Struct({
kind: Schema.Literal("echo"),
text: Schema.String
}),
Schema.Struct({
kind: Schema.Literal("sumResult"),
total: Schema.Number
}),
Schema.Struct({
kind: Schema.Literal("time"),
iso: Schema.String
}),
Schema.Struct({
kind: Schema.Literal("error"),
error: Schema.String
})
])
export type ServerMessage = Schema.Schema.Type<typeof ServerMessage>
export const decodeClientMessage = Schema.decodeUnknownEffect(ClientMessage)
const Utf8StringFromUint8Array = Schema.Uint8Array.pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.transform({
decode: (bytes) => new TextDecoder().decode(bytes),
encode: (text) => new TextEncoder().encode(text)
})
)
)
const ClientMessageFromWire = Schema.Union([
Schema.String,
Utf8StringFromUint8Array
]).pipe(
Schema.decodeTo(Schema.fromJsonString(ClientMessage))
)
export const decodeWireClientMessage = Schema.decodeUnknownEffect(ClientMessageFromWire)
export const routeClientMessage = (message: ClientMessage): ServerMessage => {
switch (message.kind) {
case "echo":
return { kind: "echo", text: message.text }
case "sum":
return { kind: "sumResult", total: message.left + message.right }
case "time":
return { kind: "time", iso: new Date().toISOString() }
}
}
+41
View File
@@ -0,0 +1,41 @@
/**
* MigrationsLive - Migration runner with inline loader
*
* Uses Migrator.make with fromRecord to define migrations inline.
* All migrations are statically imported - no dynamic file system loading.
*
* Migrations run automatically when the MigrationsLive layer is provided,
* ensuring the database schema is up-to-date before the application starts.
*/
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as ServiceMap from "effect/ServiceMap"
import * as Migrator from "effect/unstable/sql/Migrator"
import Migration0001 from "./Migrations/001_TodoSchema.ts"
const loader = Migrator.fromRecord({
"1_TodoSchema": Migration0001
})
const run = Migrator.make({})
export const runMigrations = Effect.gen(function*() {
yield* Effect.log("Running migrations...")
yield* run({ loader })
yield* Effect.log("Migrations ran successfully")
})
export interface MigrationsReadyApi {
readonly ready: true
}
export class MigrationsReady extends ServiceMap.Service<MigrationsReady, MigrationsReadyApi>()(
"effect-http-ws-cli/MigrationsReady"
) {}
export const MigrationsLive = Layer.effect(
MigrationsReady,
runMigrations.pipe(
Effect.as(MigrationsReady.of({ ready: true }))
)
)
+268
View File
@@ -0,0 +1,268 @@
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as Option from "effect/Option"
import * as PubSub from "effect/PubSub"
import * as Schema from "effect/Schema"
import * as ServiceMap from "effect/ServiceMap"
import * as Stream from "effect/Stream"
import * as SqlClient from "effect/unstable/sql/SqlClient"
import * as SqlSchema from "effect/unstable/sql/SqlSchema"
import type { Todo, TodoChange, TodoEvent, TodoSnapshot } from "./contracts.ts"
import { Todo as TodoSchema, TodoChange as TodoChangeSchema } from "./contracts.ts"
import { MigrationsReady } from "./migrations.ts"
export interface TodoStoreApi {
readonly list: (input: {
readonly includeArchived: boolean
}) => Effect.Effect<TodoSnapshot, never, SqlClient.SqlClient>
readonly rename: (input: {
readonly id: string
readonly title: string
}) => Effect.Effect<TodoEvent, never, SqlClient.SqlClient>
readonly complete: (input: {
readonly id: string
readonly completed: boolean
}) => Effect.Effect<TodoEvent, never, SqlClient.SqlClient>
readonly archive: (input: {
readonly id: string
readonly archived: boolean
}) => Effect.Effect<TodoEvent, never, SqlClient.SqlClient>
readonly subscribe: (input: {
readonly fromOffset: number
readonly includeArchived: boolean
}) => Stream.Stream<TodoEvent, never, SqlClient.SqlClient>
}
export class TodoStore extends ServiceMap.Service<TodoStore, TodoStoreApi>()(
"effect-http-ws-cli/TodoStore"
) {}
const TodoRow = Schema.Struct({
id: Schema.String,
title: Schema.String,
completed: Schema.BooleanFromBit,
archived: Schema.BooleanFromBit,
revision: Schema.Number,
updatedAt: Schema.String
})
const TodoEventRow = Schema.Struct({
offset: Schema.Number,
at: Schema.String,
todo: Schema.fromJsonString(TodoSchema),
change: Schema.fromJsonString(TodoChangeSchema)
})
const EventInsertRequest = Schema.Struct({
at: Schema.String,
todo: Schema.fromJsonString(TodoSchema),
change: Schema.fromJsonString(TodoChangeSchema),
archived: Schema.BooleanFromBit
})
const ListRequest = Schema.Struct({
includeArchived: Schema.Boolean
})
const CatchupRequest = Schema.Struct({
fromOffset: Schema.Number,
includeArchived: Schema.Boolean
})
const OffsetRow = Schema.Struct({
offset: Schema.Number
})
const makeQueries = (sql: SqlClient.SqlClient) => {
const listTodoRows = SqlSchema.findAll({
Request: ListRequest,
Result: TodoRow,
execute: (request) =>
request.includeArchived
? sql<Todo>`
SELECT id, title, completed, archived, revision, updated_at AS updatedAt
FROM todos
ORDER BY id
`
: sql<Todo>`
SELECT id, title, completed, archived, revision, updated_at AS updatedAt
FROM todos
WHERE archived = 0
ORDER BY id
`
})
const findTodoById = SqlSchema.findOneOption({
Request: Schema.String,
Result: TodoRow,
execute: (id) => sql<Todo>`
SELECT id, title, completed, archived, revision, updated_at AS updatedAt
FROM todos
WHERE id = ${id}
`
})
const upsertTodo = SqlSchema.void({
Request: TodoRow,
execute: (todo) => sql`
INSERT INTO todos (id, title, completed, archived, revision, updated_at)
VALUES (${todo.id}, ${todo.title}, ${todo.completed}, ${todo.archived}, ${todo.revision}, ${todo.updatedAt})
ON CONFLICT(id) DO UPDATE SET
title = excluded.title,
completed = excluded.completed,
archived = excluded.archived,
revision = excluded.revision,
updated_at = excluded.updated_at
`
})
const loadEventsSince = SqlSchema.findAll({
Request: CatchupRequest,
Result: TodoEventRow,
execute: (request) =>
request.includeArchived
? sql<TodoEvent>`
SELECT event_offset AS "offset", at, todo_json AS todo, change_json AS change
FROM todo_events
WHERE event_offset > ${request.fromOffset}
ORDER BY event_offset
`
: sql<TodoEvent>`
SELECT event_offset AS "offset", at, todo_json AS todo, change_json AS change
FROM todo_events
WHERE event_offset > ${request.fromOffset} AND archived = 0
ORDER BY event_offset
`
})
const insertTodoEvent = SqlSchema.findOne({
Request: EventInsertRequest,
Result: TodoEventRow,
execute: (request) => sql<TodoEvent>`
INSERT INTO todo_events (at, todo_json, change_json, archived)
VALUES (${request.at}, ${request.todo}, ${request.change}, ${request.archived})
RETURNING event_offset AS "offset", at, todo_json AS todo, change_json AS change
`
})
const currentOffset = SqlSchema.findOne({
Request: Schema.Undefined,
Result: OffsetRow,
execute: () => sql<{ readonly offset: number }>`
SELECT COALESCE(MAX(event_offset), 0) AS "offset"
FROM todo_events
`
})
return {
listTodoRows,
findTodoById,
upsertTodo,
loadEventsSince,
insertTodoEvent,
currentOffset
} as const
}
export const layerTodoStore = Layer.effect(
TodoStore,
Effect.gen(function*() {
yield* MigrationsReady
const eventsPubSub = yield* PubSub.unbounded<TodoEvent>()
const append = (
todoId: string,
change: TodoChange,
update: (todo: Todo) => Todo
): Effect.Effect<TodoEvent, never, SqlClient.SqlClient> =>
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const queries = makeQueries(sql)
return sql.withTransaction(
queries.findTodoById(todoId).pipe(
Effect.flatMap(
Option.match({
onNone: () => Effect.die(`Todo not found: ${todoId}`),
onSome: (todo) => {
const updated = update(todo)
return queries.upsertTodo(updated).pipe(
Effect.flatMap(() =>
queries.insertTodoEvent({
at: updated.updatedAt,
todo: updated,
change,
archived: updated.archived
})
)
)
}
})
)
)
)
}).pipe(Effect.tap((event) => PubSub.publish(eventsPubSub, event)), Effect.orDie)
const visible = (todo: Todo, includeArchived: boolean) => includeArchived || !todo.archived
const subscribe = (input: {
readonly fromOffset: number
readonly includeArchived: boolean
}): Stream.Stream<TodoEvent, never, SqlClient.SqlClient> => {
const catchup = Stream.fromIterableEffect(
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => makeQueries(sql).loadEventsSince(input))
).pipe(Stream.orDie)
const live = Stream.fromPubSub(eventsPubSub).pipe(
Stream.filter((event) => visible(event.todo, input.includeArchived))
)
return Stream.concat(catchup, live)
}
return TodoStore.of({
list: ({ includeArchived }) =>
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const queries = makeQueries(sql)
return Effect.all({
todos: queries.listTodoRows({ includeArchived }),
offset: queries.currentOffset(undefined).pipe(Effect.map(({ offset }) => offset))
}).pipe(
Effect.map(({ offset, todos }) => ({ offset, todos }))
)
}).pipe(Effect.orDie),
rename: ({ id, title }) =>
append(
id,
{ _tag: "TodoRenamed", title },
(todo) => ({
...todo,
title,
revision: todo.revision + 1,
updatedAt: new Date().toISOString()
})
),
complete: ({ id, completed }) =>
append(
id,
{ _tag: "TodoCompleted", completed },
(todo) => ({
...todo,
completed,
revision: todo.revision + 1,
updatedAt: new Date().toISOString()
})
),
archive: ({ id, archived }) =>
append(
id,
{ _tag: "TodoArchived", archived },
(todo) => ({
...todo,
archived,
revision: todo.revision + 1,
updatedAt: new Date().toISOString()
})
),
subscribe
})
})
)
+155
View File
@@ -0,0 +1,155 @@
import { NodeHttpServer } from "@effect/platform-node"
import * as SqliteNode from "@effect/sql-sqlite-node"
import * as Effect from "effect/Effect"
import * as FileSystem from "effect/FileSystem"
import * as Layer from "effect/Layer"
import * as Path from "effect/Path"
import * as Http from "node:http"
import {
HttpRouter,
HttpServerRequest,
HttpServerResponse
} from "effect/unstable/http"
import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization"
import * as RpcServer from "effect/unstable/rpc/RpcServer"
import * as Stream from "effect/Stream"
import {
ClientMessage,
routeClientMessage,
ServerMessage
} from "./messages.ts"
import { ServerConfig } from "./config.ts"
import { WsRpcGroup } from "./contracts.ts"
import { TodoStore, layerTodoStore } from "./model-store.ts"
import { MigrationsLive } from "./migrations.ts"
const respondMessage = HttpServerResponse.schemaJson(ServerMessage)
const messageDispatchRoute = HttpRouter.add(
"POST",
"/api/dispatch",
HttpServerRequest.schemaBodyJson(ClientMessage).pipe(
Effect.flatMap((message) => respondMessage(routeClientMessage(message))),
Effect.catchTag(
"SchemaError",
() => Effect.succeed(HttpServerResponse.jsonUnsafe({ kind: "error", error: "Invalid message schema" }, { status: 400 }))
),
Effect.catchTag(
"HttpServerError",
() => Effect.succeed(HttpServerResponse.jsonUnsafe({ kind: "error", error: "Invalid request body" }, { status: 400 }))
)
)
)
const websocketRpcRoute = RpcServer.layerHttp({
group: WsRpcGroup,
path: "/ws",
protocol: "websocket"
}).pipe(
Layer.provide(WsRpcGroup.toLayer({
echo: ({ text }) => Effect.succeed({ text }),
sum: ({ left, right }) => Effect.succeed({ total: left + right }),
time: () => Effect.sync(() => ({ iso: new Date().toISOString() })),
listTodos: ({ includeArchived }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.list({ includeArchived })),
renameTodo: ({ id, title }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.rename({ id, title })),
completeTodo: ({ id, completed }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.complete({ id, completed })),
archiveTodo: ({ id, archived }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.archive({ id, archived })),
subscribeTodos: ({ fromOffset, includeArchived }) =>
Stream.unwrap(
Effect.map(
Effect.service(TodoStore),
(store) => store.subscribe({ fromOffset, includeArchived })
)
)
})),
Layer.provide(layerTodoStore),
Layer.provide(RpcSerialization.layerJson)
)
const staticRoute = HttpRouter.add(
"GET",
"*",
(request) =>
Effect.gen(function*() {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
const config = yield* ServerConfig
const url = HttpServerRequest.toURL(request)
if (!url) {
return HttpServerResponse.text("Bad Request", { status: 400 })
}
if (config.frontendDevOrigin) {
return HttpServerResponse.redirect(
new URL(`${url.pathname}${url.search}`, config.frontendDevOrigin),
{
status: 307,
headers: { "cache-control": "no-store" }
}
)
}
const root = path.resolve(config.assetsDir)
const decodedPath = decodeURIComponent(url.pathname)
const target = decodedPath === "/"
? "index.html"
: decodedPath.endsWith("/")
? `${decodedPath.slice(1)}index.html`
: decodedPath.slice(1)
const normalizedTarget = path.normalize(target)
const absoluteTarget = path.resolve(root, normalizedTarget)
const relativeToRoot = path.relative(root, absoluteTarget)
if (relativeToRoot.startsWith("..") || path.isAbsolute(relativeToRoot)) {
return HttpServerResponse.text("Forbidden", { status: 403 })
}
const exists = yield* fs.exists(absoluteTarget)
if (!exists) {
return HttpServerResponse.text("Not Found", { status: 404 })
}
return yield* HttpServerResponse.file(absoluteTarget)
}).pipe(Effect.catchCause(() => Effect.succeed(HttpServerResponse.text("Bad Request", { status: 400 }))))
)
export const makeRoutesLayer =
Layer.mergeAll(
HttpRouter.add(
"GET",
"/health",
HttpServerResponse.json({ ok: true })
),
messageDispatchRoute,
websocketRpcRoute,
staticRoute
)
export const makeServerLayer = Layer.unwrap(
Effect.gen(function*() {
const config = yield* ServerConfig
const sqliteLayer = SqliteNode.SqliteClient.layer({
filename: config.dbFilename
})
const persistenceLayer = MigrationsLive.pipe(
Layer.provideMerge(sqliteLayer)
)
return HttpRouter.serve(makeRoutesLayer, {
disableLogger: !config.requestLogging
}).pipe(
Layer.provideMerge(persistenceLayer),
Layer.provide(NodeHttpServer.layer(Http.createServer, {
host: config.host,
port: config.port
}))
)
})
)
export const runServer = Layer.launch(makeServerLayer)
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it } from "@effect/vitest"
import * as ConfigProvider from "effect/ConfigProvider"
import * as Effect from "effect/Effect"
import * as Option from "effect/Option"
import { resolveServerConfig } from "../src/cli.ts"
describe("cli config resolution", () => {
it.effect("falls back to effect/config values when flags are omitted", () =>
Effect.gen(function*() {
const resolved = yield* resolveServerConfig({
host: Option.none(),
port: Option.none(),
assets: Option.none(),
db: Option.none(),
requestLogging: Option.none(),
frontendDevOrigin: Option.none()
}).pipe(
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.fromEnv({
env: {
HOST: "0.0.0.0",
PORT: "4001",
ASSETS_DIR: "public",
DB_FILENAME: "dev.sqlite",
REQUEST_LOGGING: "false",
FRONTEND_DEV_ORIGIN: "http://127.0.0.1:5173"
}
})
)
)
expect(resolved).toEqual({
host: "0.0.0.0",
port: 4001,
assetsDir: "public",
dbFilename: "dev.sqlite",
requestLogging: false,
frontendDevOrigin: "http://127.0.0.1:5173"
})
})
)
it.effect("uses CLI flags when provided", () =>
Effect.gen(function*() {
const resolved = yield* resolveServerConfig({
host: Option.some("127.0.0.1"),
port: Option.some(8788),
assets: Option.some("public"),
db: Option.some("override.sqlite"),
requestLogging: Option.some(true),
frontendDevOrigin: Option.some("http://127.0.0.1:4173")
}).pipe(
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.fromEnv({
env: {
HOST: "0.0.0.0",
PORT: "4001",
ASSETS_DIR: "other",
DB_FILENAME: "ignored.sqlite",
REQUEST_LOGGING: "false",
FRONTEND_DEV_ORIGIN: "http://127.0.0.1:5173"
}
})
)
)
expect(resolved).toEqual({
host: "127.0.0.1",
port: 8788,
assetsDir: "public",
dbFilename: "override.sqlite",
requestLogging: true,
frontendDevOrigin: "http://127.0.0.1:4173"
})
})
)
})
+90
View File
@@ -0,0 +1,90 @@
import * as NodeServices from "@effect/platform-node/NodeServices"
import * as SqliteNode from "@effect/sql-sqlite-node"
import { describe, expect, it } from "@effect/vitest"
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as SqlClient from "effect/unstable/sql/SqlClient"
import * as FileSystem from "node:fs"
import * as OS from "node:os"
import * as NodePath from "node:path"
import { resetDatabase } from "../src/cli.ts"
import { MigrationsLive } from "../src/migrations.ts"
const countRows = (dbFilename: string, tableName: string) =>
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) =>
sql<{ readonly count: number }>`SELECT COUNT(*) AS count FROM ${sql(tableName)}`.pipe(
Effect.map((rows) => rows[0]?.count ?? 0)
)
).pipe(
Effect.provide(SqliteNode.SqliteClient.layer({ filename: dbFilename }))
)
const insertTodo = (dbFilename: string) =>
Effect.scoped(
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const now = new Date().toISOString()
const id = "todo-reset-test"
const title = "before-reset"
return sql.withTransaction(
sql`
INSERT INTO todos (id, title, completed, archived, revision, updated_at)
VALUES (${id}, ${title}, 0, 0, 1, ${now})
`.pipe(
Effect.flatMap(() =>
sql`
INSERT INTO todo_events (at, todo_json, change_json, archived)
VALUES (
${now},
${JSON.stringify({
id,
title,
completed: false,
archived: false,
revision: 1,
updatedAt: now
})},
${JSON.stringify({ _tag: "TodoCreated" })},
0
)
`
)
)
)
}).pipe(
Effect.provide(MigrationsLive.pipe(Layer.provideMerge(SqliteNode.SqliteClient.layer({ filename: dbFilename }))))
)
)
describe("reset command", () => {
it.effect("deletes the database and reruns migrations without reseeding todos", () =>
Effect.gen(function*() {
const dbFilename = NodePath.join(
OS.tmpdir(),
`effect-http-ws-cli-reset-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite`
)
yield* insertTodo(dbFilename)
const beforeCount = yield* countRows(dbFilename, "todos")
expect(beforeCount).toBe(1)
yield* resetDatabase(dbFilename).pipe(
Effect.provide(NodeServices.layer)
)
const todoCount = yield* countRows(dbFilename, "todos")
const migrationCount = yield* countRows(dbFilename, "effect_sql_migrations")
expect(todoCount).toBe(0)
expect(migrationCount).toBe(1)
yield* Effect.sync(() => {
try {
FileSystem.rmSync(dbFilename, { force: true })
} catch {
// ignore cleanup failures in tests
}
})
})
)
})
+310
View File
@@ -0,0 +1,310 @@
import { NodeHttpServer } from "@effect/platform-node"
import * as SqliteNode from "@effect/sql-sqlite-node"
import { describe, expect, it } from "@effect/vitest"
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as Stream from "effect/Stream"
import * as FileSystem from "node:fs"
import * as OS from "node:os"
import * as NodePath from "node:path"
import {
HttpBody,
HttpClient,
HttpClientResponse,
HttpServer,
HttpRouter
} from "effect/unstable/http"
import * as SqlClient from "effect/unstable/sql/SqlClient"
import { ServerConfig } from "../src/config.ts"
import { MigrationsLive } from "../src/migrations.ts"
import { ServerMessage } from "../src/messages.ts"
import { withWsRpcClient } from "../src/client.ts"
import { makeRoutesLayer } from "../src/server.ts"
const testServerConfig = {
host: "127.0.0.1",
port: 0,
assetsDir: new URL("../../public", import.meta.url).pathname,
dbFilename: ":memory:",
requestLogging: false,
frontendDevOrigin: undefined
}
const AppUnderTest = HttpRouter.serve(
makeRoutesLayer,
{
disableListenLog: true,
disableLogger: true
}
)
const persistenceLayer = (dbFilename: string) => {
const sqliteLayer = SqliteNode.SqliteClient.layer({ filename: dbFilename })
return MigrationsLive.pipe(Layer.provideMerge(sqliteLayer))
}
const appLayer = (dbFilename: string) =>
AppUnderTest.pipe(Layer.provideMerge(persistenceLayer(dbFilename)))
const insertTodo = (dbFilename: string, id: string, title: string) =>
Effect.scoped(
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const now = new Date().toISOString()
return sql.withTransaction(
sql`
INSERT INTO todos (id, title, completed, archived, revision, updated_at)
VALUES (${id}, ${title}, 0, 0, 1, ${now})
`.pipe(
Effect.flatMap(() =>
sql`
INSERT INTO todo_events (at, todo_json, change_json, archived)
VALUES (
${now},
${JSON.stringify({
id,
title,
completed: false,
archived: false,
revision: 1,
updatedAt: now
})},
${JSON.stringify({ _tag: "TodoCreated" })},
0
)
`
)
)
)
}).pipe(
Effect.provide(persistenceLayer(dbFilename))
)
)
describe("server", () => {
it.effect("routes HTTP messages validated by Schema", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const client = yield* HttpClient.HttpClient
const response = yield* client.post("/api/dispatch", {
body: HttpBody.jsonUnsafe({ kind: "sum", left: 20, right: 22 })
})
const parsed = yield* HttpClientResponse.schemaBodyJson(ServerMessage)(response)
expect(parsed).toEqual({ kind: "sumResult", total: 42 })
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("serves static files from local filesystem", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const text = yield* HttpClient.get("/").pipe(
Effect.flatMap((response) => response.text)
)
expect(text).toContain("effect-http-ws-cli")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("redirects frontend requests to the Vite dev server when enabled", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, {
...testServerConfig,
frontendDevOrigin: "http://127.0.0.1:5173"
})
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const response = yield* Effect.promise(() =>
fetch(`http://127.0.0.1:${address.port}/todos?filter=active`, {
redirect: "manual"
})
)
expect(response.status).toBe(307)
expect(response.headers.get("location")).toBe("http://127.0.0.1:5173/todos?filter=active")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("routes WebSocket RPC messages with shared contracts", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
const response = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client.echo({ text: "hello from ws" }))
)
expect(response).toEqual({ text: "hello from ws" })
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("routes WebSocket RPC calls for multiple procedures", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.all({
sum: client.sum({ left: 1, right: 2 }),
time: client.time(undefined)
})
)
)
expect(result.sum).toEqual({ total: 3 })
expect(typeof result.time.iso).toBe("string")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("lists todos and streams todo updates from offset", () =>
Effect.gen(function*() {
const dbFilename = NodePath.join(
OS.tmpdir(),
`effect-http-ws-cli-stream-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite`
)
yield* insertTodo(dbFilename, "todo-stream-test", "stream-seed")
const events = yield* Effect.scoped(
Effect.gen(function*() {
yield* Layer.build(appLayer(dbFilename)).pipe(
Effect.provideService(ServerConfig, {
...testServerConfig,
dbFilename
})
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
return yield* withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const firstTodo = snapshot.todos[0]
if (!firstTodo) {
return yield* Effect.die("Expected a todo fixture")
}
yield* client.renameTodo({ id: firstTodo.id, title: "alpha" })
yield* client.completeTodo({ id: firstTodo.id, completed: true })
yield* client.archiveTodo({ id: firstTodo.id, archived: true })
return yield* client.subscribeTodos({
fromOffset: snapshot.offset,
includeArchived: true
}).pipe(
Stream.take(3),
Stream.runCollect
)
})
)
})
).pipe(
Effect.ensuring(
Effect.sync(() => {
try {
FileSystem.rmSync(dbFilename, { force: true })
} catch {
// ignore cleanup failures in tests
}
})
)
)
expect(events).toHaveLength(3)
expect(events[0]?.change).toEqual({ _tag: "TodoRenamed", title: "alpha" })
expect(events[1]?.change).toEqual({ _tag: "TodoCompleted", completed: true })
expect(events[2]?.change).toEqual({ _tag: "TodoArchived", archived: true })
expect(events[0]?.todo.title).toBe("alpha")
expect(events[1]?.todo.completed).toBe(true)
expect(events[2]?.todo.archived).toBe(true)
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("persists todos across server restarts when using a file database", () =>
Effect.gen(function*() {
const dbFilename = NodePath.join(
OS.tmpdir(),
`effect-http-ws-cli-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite`
)
yield* insertTodo(dbFilename, "todo-persist-test", "persist-seed")
const withServer = <A, E, R>(f: (wsUrl: string) => Effect.Effect<A, E, R>) =>
Effect.scoped(
Effect.gen(function*() {
yield* Layer.build(appLayer(dbFilename)).pipe(
Effect.provideService(ServerConfig, {
...testServerConfig,
dbFilename
})
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
return yield* f(wsUrl)
})
)
const renamedTodoId = yield* withServer((wsUrl) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const firstTodo = snapshot.todos[0]
if (!firstTodo) {
return yield* Effect.die("Expected a todo fixture")
}
yield* client.renameTodo({ id: firstTodo.id, title: "persisted-title" })
return firstTodo.id
})
)
)
)
const persistedTitle = yield* withServer((wsUrl) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const persisted = snapshot.todos.find((todo) => todo.id === renamedTodoId)
if (!persisted) {
return yield* Effect.die("Expected persisted todo")
}
return persisted.title
})
)
)
).pipe(
Effect.ensuring(
Effect.sync(() => {
try {
FileSystem.rmSync(dbFilename, { force: true })
} catch {
// ignore cleanup failures in tests
}
})
)
)
expect(persistedTitle).toBe("persisted-title")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
})
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../tsconfig.json",
"include": ["src", "test", "vitest.config.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
include: ["test/**/*.test.ts"],
environment: "node"
}
})
+2 -2
View File
@@ -7,7 +7,7 @@
## Project Snapshot
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
@@ -21,7 +21,7 @@ If a tradeoff is required, choose correctness and robustness over short-term con
## Maintainability
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
## Package Roles
+1 -1
View File
@@ -8,7 +8,7 @@ You can still open an issue or PR, but please do so knowing there is a high chan
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
PRs are automatically labeled with a `vouch:*` trust status and a `size:*` diff size based on changed lines.
PRs are automatically labeled with a `vouch:*` trust status.
If you are an external contributor, expect `vouch:unvouched` until we explicitly add you to [.github/VOUCHED.td](.github/VOUCHED.td).
+1 -1
View File
@@ -51,7 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `editor.openFavorite`: open current project/worktree in the last-used editor
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
+1 -1
View File
@@ -1,6 +1,6 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
## How to use
+1 -1
View File
@@ -11,7 +11,7 @@ The T3 Code CLI accepts the following configuration options, available either as
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State directory. |
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.13",
"version": "0.0.9",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+2 -3
View File
@@ -80,13 +80,12 @@ function startApp() {
}
});
app.once("exit", (code, signal) => {
app.once("exit", () => {
if (currentApp === app) {
currentApp = null;
}
const exitedAbnormally = signal !== null || code !== 0;
if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
if (!shuttingDown && !expectedExits.has(app)) {
scheduleRestart();
}
});
+15
View File
@@ -0,0 +1,15 @@
import { readPathFromLoginShell } from "@t3tools/shared/shell";
export function fixPath(): void {
if (process.platform !== "darwin") return;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = readPathFromLoginShell(shell);
if (result) {
process.env.PATH = result;
}
} catch {
// Keep inherited PATH if shell lookup fails.
}
}
+7 -29
View File
@@ -28,7 +28,7 @@ import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { fixPath } from "./fixPath";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
import {
createInitialDesktopUpdateState,
@@ -44,7 +44,7 @@ import {
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
syncShellEnvironment();
fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
@@ -56,8 +56,8 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
const STATE_DIR =
process.env.T3CODE_STATE_DIR?.trim() || Path.join(OS.homedir(), ".t3", "userdata");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
@@ -535,28 +535,7 @@ function handleCheckForUpdatesMenuClick(): void {
if (!BrowserWindow.getAllWindows().length) {
mainWindow = createWindow();
}
void checkForUpdatesFromMenu();
}
async function checkForUpdatesFromMenu(): Promise<void> {
await checkForUpdates("menu");
if (updateState.status === "up-to-date") {
void dialog.showMessageBox({
type: "info",
title: "You're up to date!",
message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
buttons: ["OK"],
});
} else if (updateState.status === "error") {
void dialog.showMessageBox({
type: "warning",
title: "Update check failed",
message: "Could not check for updates.",
detail: updateState.message ?? "An unknown error occurred. Please try again later.",
buttons: ["OK"],
});
}
void checkForUpdates("menu");
}
function configureApplicationMenu(): void {
@@ -640,7 +619,6 @@ function configureApplicationMenu(): void {
function resolveResourcePath(fileName: string): string | null {
const candidates = [
Path.join(__dirname, "../resources", fileName),
Path.join(__dirname, "../prod-resources", fileName),
Path.join(process.resourcesPath, "resources", fileName),
Path.join(process.resourcesPath, fileName),
];
@@ -924,7 +902,7 @@ function backendEnv(): NodeJS.ProcessEnv {
T3CODE_MODE: "desktop",
T3CODE_NO_BROWSER: "1",
T3CODE_PORT: String(backendPort),
T3CODE_HOME: BASE_DIR,
T3CODE_STATE_DIR: STATE_DIR,
T3CODE_AUTH_TOKEN: backendAuthToken,
};
}
@@ -1320,7 +1298,7 @@ async function bootstrap(): Promise<void> {
);
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
backendAuthToken = Crypto.randomBytes(24).toString("hex");
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
backendWsUrl = `ws://127.0.0.1:${backendPort}/ws?token=${encodeURIComponent(backendAuthToken)}`;
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
@@ -1,85 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment";
describe("syncShellEnvironment", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("preserves an inherited SSH_AUTH_SOCK value", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/login-shell.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("preserves inherited values when the login shell omits them", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("does nothing outside macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "linux",
readEnvironment,
});
expect(readEnvironment).not.toHaveBeenCalled();
expect(env.PATH).toBe("/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
});
-29
View File
@@ -1,29 +0,0 @@
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
export function syncShellEnvironment(
env: NodeJS.ProcessEnv = process.env,
options: {
platform?: NodeJS.Platform;
readEnvironment?: ShellEnvironmentReader;
} = {},
): void {
if ((options.platform ?? process.platform) !== "darwin") return;
try {
const shell = env.SHELL ?? "/bin/zsh";
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
"PATH",
"SSH_AUTH_SOCK",
]);
if (shellEnvironment.PATH) {
env.PATH = shellEnvironment.PATH;
}
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
} catch {
// Keep inherited environment if shell lookup fails.
}
}
+2 -2
View File
@@ -10,10 +10,10 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^6.0.4"
"astro": "^5.7.13"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
"@astrojs/check": "^0.9.4",
"typescript": "catalog:"
}
}
@@ -1,20 +1,20 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
ProviderKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import {
Effect,
Exit,
FileSystem,
Layer,
ManagedRuntime,
Option,
Path,
Ref,
Schedule,
Schema,
@@ -24,7 +24,6 @@ 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 { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -66,7 +65,7 @@ import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
} from "./TestProviderAdapter.integration.ts";
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { ServerConfig } from "../src/config.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -76,16 +75,14 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
});
}
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
function initializeGitWorkspace(cwd: string) {
runGit(cwd, ["init", "--initial-branch=main"]);
runGit(cwd, ["config", "user.email", "[email protected]"]);
runGit(cwd, ["config", "user.name", "Test User"]);
const fileSystem = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
runGit(cwd, ["add", "."]);
runGit(cwd, ["commit", "-m", "Initial"]);
});
}
export function gitRefExists(cwd: string, ref: string): boolean {
try {
@@ -208,7 +205,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: "codex";
readonly realCodex?: boolean;
}
@@ -216,9 +213,7 @@ export const makeOrchestrationIntegrationHarness = (
options?: MakeOrchestrationIntegrationHarnessOptions,
) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const sleep = (ms: number) => Effect.sleep(ms);
const provider = options?.provider ?? "codex";
const useRealCodex = options?.realCodex === true;
const adapterHarness = useRealCodex
@@ -235,16 +230,13 @@ export const makeOrchestrationIntegrationHarness = (
listProviders: () => Effect.succeed([adapterHarness.provider]),
} as typeof ProviderAdapterRegistry.Service)
: null;
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-orchestration-integration-",
});
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
const workspaceDir = path.join(rootDir, "workspace");
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
Effect.provideService(Path.Path, path),
);
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
yield* initializeGitWorkspace(workspaceDir);
const stateDir = path.join(rootDir, "state");
const dbPath = path.join(stateDir, "state.sqlite");
fs.mkdirSync(workspaceDir, { recursive: true });
fs.mkdirSync(stateDir, { recursive: true });
initializeGitWorkspace(workspaceDir);
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -269,7 +261,7 @@ export const makeOrchestrationIntegrationHarness = (
}),
).pipe(
Layer.provide(makeCodexAdapterLive()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
@@ -285,13 +277,12 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(AnalyticsService.layerTest),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
CheckpointStoreLive,
providerLayer,
RuntimeReceiptBusLive,
);
@@ -320,7 +311,7 @@ export const makeOrchestrationIntegrationHarness = (
);
const layer = orchestrationReactorLayer.pipe(
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(NodeServices.layer),
);
@@ -360,7 +351,7 @@ export const makeOrchestrationIntegrationHarness = (
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* Effect.sleep(10);
yield* sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
threadId,
@@ -477,7 +468,13 @@ export const makeOrchestrationIntegrationHarness = (
}
});
yield* shutdown;
yield* shutdown.pipe(
Effect.ensuring(
Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
}),
),
);
});
return {
@@ -10,7 +10,6 @@ import {
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderKind,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
@@ -36,7 +35,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -178,7 +177,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -198,7 +197,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: "codex";
}
function nowIso(): string {
@@ -206,7 +205,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: ProviderKind,
provider: "codex",
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +215,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: ProviderKind,
provider: "codex",
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -73,7 +73,7 @@ export const codexTurnToolFixture = [
turnId: TURN_ID,
payload: {
itemType: "command_execution",
title: "Ran command",
title: "Command run",
detail: "echo integration",
},
},
@@ -85,7 +85,7 @@ export const codexTurnToolFixture = [
payload: {
itemType: "command_execution",
status: "completed",
title: "Ran command",
title: "Command run",
detail: "echo integration",
},
},
@@ -5,11 +5,9 @@ import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ProviderKind,
ThreadId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
@@ -27,7 +25,6 @@ import type {
CheckpointDiffFinalizedReceipt,
TurnProcessingQuiescedReceipt,
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
@@ -39,7 +36,7 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = ProviderKind;
type IntegrationProvider = "codex";
function nowIso() {
return new Date().toISOString();
@@ -52,6 +49,8 @@ class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWai
},
) {}
const sleep = (ms: number) => Effect.sleep(ms);
function waitForSync<A>(
read: () => A,
predicate: (value: A) => boolean,
@@ -69,7 +68,7 @@ function waitForSync<A>(
if (Date.now() >= deadline) {
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
}
yield* Effect.sleep(10);
yield* sleep(10);
}
});
}
@@ -90,7 +89,7 @@ function withHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
);
}
function withRealCodexHarness<A, E>(
@@ -100,14 +99,12 @@ function withRealCodexHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
);
}
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
const provider = harness.adapterHarness?.provider ?? "codex";
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
yield* harness.engine.dispatch({
type: "project.create",
@@ -115,7 +112,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModel,
defaultModel: "gpt-5-codex",
createdAt,
});
@@ -125,7 +122,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
model: defaultModel,
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -885,420 +882,3 @@ it.live(
}),
),
);
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Claude first turn.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-initial",
messageId: "msg-user-claude-initial",
text: "Use Claude",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.session.status === "ready" &&
entry.messages.some(
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
),
);
assert.equal(thread.session?.providerName, "claudeAgent");
}),
"claudeAgent",
),
);
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn before restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-1",
messageId: "msg-user-claude-recover-1",
text: "Before restart",
provider: "claudeAgent",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.adapter.stopAll();
yield* waitForSync(
() => harness.adapterHarness!.listActiveSessionIds(),
(sessionIds) => sessionIds.length === 0,
"provider stopAll",
);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn after restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-2",
messageId: "msg-user-claude-recover-2",
text: "After restart",
});
yield* waitForSync(
() => harness.adapterHarness!.getStartCount(),
(count) => count === 2,
"claude provider recovery start",
);
const recoveredThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.messages.some(
(message) => message.role === "user" && message.text === "After restart",
) &&
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
);
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeAgent",
),
);
it.live("forwards claudeAgent approval responses to the provider session", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
requestKind: "command",
detail: "Approve Claude tool call",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-approval",
messageId: "msg-user-claude-approval",
text: "Need approval",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some((activity) => activity.kind === "approval.requested"),
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
createdAt: nowIso(),
});
yield* harness.waitForPendingApproval(
"req-approval-1",
(row) => row.status === "resolved" && row.decision === "accept",
);
const approvalResponses = yield* waitForSync(
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
(responses) => responses.length === 1,
"claude provider approval response",
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
"claudeAgent",
),
);
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Long running output.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-interrupt",
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1",
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
threadId: THREAD_ID,
createdAt: nowIso(),
});
yield* harness.waitForDomainEvent(
(event) => event.type === "thread.turn-interrupt-requested",
);
const interruptCalls = yield* waitForSync(
() => harness.adapterHarness!.getInterruptCalls(THREAD_ID),
(calls) => calls.length === 1,
"claude provider interrupt call",
);
assert.equal(interruptCalls.length, 1);
}),
"claudeAgent",
),
);
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
provider: "claudeAgent",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeAgent",
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeAgent",
),
);
+5 -7
View File
@@ -1,7 +1,6 @@
{
"name": "t3",
"version": "0.0.13",
"license": "MIT",
"version": "0.0.9",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
@@ -23,14 +22,12 @@
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
"open": "^10.1.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -43,9 +40,10 @@
"@types/ws": "^8.5.13",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
"vitest": "catalog:",
"ws": "^8.18.0"
},
"engines": {
"node": "^22.16 || ^23.11 || >=24.10"
"node": "^22.13 || ^23.4 || >=24.10"
}
}
+2 -2
View File
@@ -11,7 +11,7 @@ export function normalizeAttachmentRelativePath(rawRelativePath: string): string
}
export function resolveAttachmentRelativePath(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly relativePath: string;
}): string | null {
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
@@ -19,7 +19,7 @@ export function resolveAttachmentRelativePath(input: {
return null;
}
const attachmentsRoot = path.resolve(input.attachmentsDir);
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
return null;
+8 -6
View File
@@ -44,32 +44,34 @@ describe("attachmentStore", () => {
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const attachmentId = "thread-1-attachment";
const attachmentsDir = path.join(stateDir, "attachments");
fs.mkdirSync(attachmentsDir, { recursive: true });
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
fs.writeFileSync(pngPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
attachmentsDir,
stateDir,
attachmentId,
});
expect(resolved).toBe(pngPath);
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
it("returns null when no attachment file exists for the id", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const resolved = resolveAttachmentPathById({
attachmentsDir,
stateDir,
attachmentId: "thread-1-missing",
});
expect(resolved).toBeNull();
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
});
+4 -4
View File
@@ -66,17 +66,17 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
}
export function resolveAttachmentPath(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly attachment: ChatAttachment;
}): string | null {
return resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
stateDir: input.stateDir,
relativePath: attachmentRelativePath(input.attachment),
});
}
export function resolveAttachmentPathById(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly attachmentId: string;
}): string | null {
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
@@ -85,7 +85,7 @@ export function resolveAttachmentPathById(input: {
}
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
const maybePath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
stateDir: input.stateDir,
relativePath: `${normalizedId}${extension}`,
});
if (maybePath && existsSync(maybePath)) {
@@ -15,14 +15,15 @@ import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { GitCommandError } from "../../git/Errors.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitServiceLive } from "../../git/Layers/GitService.ts";
import { GitService } from "../../git/Services/GitService.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const git = yield* GitCore;
const git = yield* GitService;
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
git
@@ -276,4 +277,6 @@ const makeCheckpointStore = Effect.gen(function* () {
} satisfies CheckpointStoreShape;
});
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
Layer.provideMerge(GitServiceLive),
);
@@ -37,7 +37,6 @@ function createSendTurnHarness() {
planType: null,
sparkEnabled: true,
},
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -76,7 +75,6 @@ function createThreadControlHarness() {
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -119,7 +117,6 @@ function createPendingUserInputHarness() {
},
],
]),
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -138,43 +135,6 @@ function createPendingUserInputHarness() {
return { manager, context, requireSession, writeMessage, emitEvent };
}
function createCollabNotificationHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
provider: "codex",
status: "running",
threadId: asThreadId("thread_1"),
runtimeMode: "full-access",
model: "gpt-5.3-codex",
activeTurnId: "turn_parent",
resumeCursor: { threadId: "provider_parent" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map<string, string>(),
nextRequestId: 1,
stopping: false,
};
const emitEvent = vi
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
.mockImplementation(() => {});
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, emitEvent, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -761,7 +721,6 @@ describe("respondToUserInput", () => {
},
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
};
type ApprovalRequestContext = {
session: typeof context.session;
@@ -789,152 +748,6 @@ describe("respondToUserInput", () => {
});
});
describe("collab child conversation routing", () => {
it("rewrites child notification turn ids onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/agentMessage/delta",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "msg_child_1",
delta: "working",
},
});
expect(emitEvent).toHaveBeenLastCalledWith(
expect.objectContaining({
method: "item/agentMessage/delta",
turnId: "turn_parent",
itemId: "msg_child_1",
}),
);
});
it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
updateSession.mockClear();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/started",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1" },
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/completed",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1", status: "completed" },
},
});
expect(emitEvent).not.toHaveBeenCalled();
expect(updateSession).not.toHaveBeenCalled();
});
it("rewrites child approval requests onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
(
manager as unknown as {
handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
}
).handleServerRequest(context, {
id: 42,
method: "item/commandExecution/requestApproval",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "call_child_1",
command: "bun install",
},
});
expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
expect.objectContaining({
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "item/commandExecution/requestApproval",
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
});
});
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
+10 -94
View File
@@ -70,7 +70,6 @@ interface CodexSessionContext {
pending: Map<PendingRequestKey, PendingRequest>;
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
collabReceiverTurns: Map<string, TurnId>;
nextRequestId: number;
stopping: boolean;
}
@@ -572,7 +571,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
nextRequestId: 1,
stopping: false,
};
@@ -734,7 +732,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
const context = this.requireSession(input.threadId);
context.collabReceiverTurns.clear();
const turnInput: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
@@ -1124,16 +1121,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context: CodexSessionContext,
notification: JsonRpcNotification,
): void {
const rawRoute = this.readRouteFields(notification.params);
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
const isChildConversation = childParentTurnId !== undefined;
if (
isChildConversation &&
this.shouldSuppressChildConversationNotification(notification.method)
) {
return;
}
const route = this.readRouteFields(notification.params);
const textDelta =
notification.method === "item/agentMessage/delta"
? this.readString(notification.params, "delta")
@@ -1146,10 +1134,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: notification.method,
...((childParentTurnId ?? rawRoute.turnId)
? { turnId: childParentTurnId ?? rawRoute.turnId }
: {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
turnId: route.turnId,
itemId: route.itemId,
textDelta,
payload: notification.params,
});
@@ -1165,9 +1151,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/started") {
if (isChildConversation) {
return;
}
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
this.updateSession(context, {
status: "running",
@@ -1177,10 +1160,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/completed") {
if (isChildConversation) {
return;
}
context.collabReceiverTurns.clear();
const turn = this.readObject(notification.params, "turn");
const status = this.readString(turn, "status");
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
@@ -1193,9 +1172,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "error") {
if (isChildConversation) {
return;
}
const message = this.readString(this.readObject(notification.params)?.error, "message");
const willRetry = this.readBoolean(notification.params, "willRetry");
@@ -1207,9 +1183,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
const rawRoute = this.readRouteFields(request.params);
const childParentTurnId = this.readChildParentTurnId(context, request.params);
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
const route = this.readRouteFields(request.params);
const requestKind = this.requestKindForMethod(request.method);
let requestId: ApprovalRequestId | undefined;
if (requestKind) {
@@ -1225,8 +1199,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
: "item/fileChange/requestApproval",
requestKind,
threadId: context.session.threadId,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
};
context.pendingApprovals.set(requestId, pendingRequest);
}
@@ -1237,8 +1211,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
requestId,
jsonRpcId: request.id,
threadId: context.session.threadId,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
});
}
@@ -1249,8 +1223,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: request.method,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
turnId: route.turnId,
itemId: route.itemId,
requestId,
requestKind,
payload: request.params,
@@ -1477,64 +1451,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return route;
}
private readProviderConversationId(params: unknown): string | undefined {
return (
this.readString(params, "threadId") ??
this.readString(this.readObject(params, "thread"), "id") ??
this.readString(params, "conversationId")
);
}
private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined {
const providerConversationId = this.readProviderConversationId(params);
if (!providerConversationId) {
return undefined;
}
return context.collabReceiverTurns.get(providerConversationId);
}
private rememberCollabReceiverTurns(
context: CodexSessionContext,
params: unknown,
parentTurnId: TurnId | undefined,
): void {
if (!parentTurnId) {
return;
}
const payload = this.readObject(params);
const item = this.readObject(payload, "item") ?? payload;
const itemType = this.readString(item, "type") ?? this.readString(item, "kind");
if (itemType !== "collabAgentToolCall") {
return;
}
const receiverThreadIds =
this.readArray(item, "receiverThreadIds")
?.map((value) => (typeof value === "string" ? value : null))
.filter((value): value is string => value !== null) ?? [];
for (const receiverThreadId of receiverThreadIds) {
context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
}
}
private shouldSuppressChildConversationNotification(method: string): boolean {
return (
method === "thread/started" ||
method === "thread/status/changed" ||
method === "thread/archived" ||
method === "thread/unarchived" ||
method === "thread/closed" ||
method === "thread/compacted" ||
method === "thread/name/updated" ||
method === "thread/tokenUsage/updated" ||
method === "turn/started" ||
method === "turn/completed" ||
method === "turn/aborted" ||
method === "turn/plan/updated" ||
method === "item/plan/delta"
);
}
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
const target =
key === undefined
+9 -62
View File
@@ -12,32 +12,16 @@ export const DEFAULT_PORT = 3773;
export type RuntimeMode = "web" | "desktop";
/**
* ServerDerivedPaths - Derived paths from the base directory.
*/
export interface ServerDerivedPaths {
readonly stateDir: string;
readonly dbPath: string;
readonly keybindingsConfigPath: string;
readonly worktreesDir: string;
readonly attachmentsDir: string;
readonly logsDir: string;
readonly serverLogPath: string;
readonly providerLogsDir: string;
readonly providerEventLogPath: string;
readonly terminalLogsDir: string;
readonly anonymousIdPath: string;
}
/**
* ServerConfigShape - Process/runtime configuration required by the server.
*/
export interface ServerConfigShape extends ServerDerivedPaths {
export interface ServerConfigShape {
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
readonly cwd: string;
readonly baseDir: string;
readonly keybindingsConfigPath: string;
readonly stateDir: string;
readonly staticDir: string | undefined;
readonly devUrl: URL | undefined;
readonly noBrowser: boolean;
@@ -46,68 +30,31 @@ export interface ServerConfigShape extends ServerDerivedPaths {
readonly logWebSocketEvents: boolean;
}
export const deriveServerPaths = Effect.fn(function* (
baseDir: ServerConfigShape["baseDir"],
devUrl: ServerConfigShape["devUrl"],
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
const { join } = yield* Path.Path;
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata");
const dbPath = join(stateDir, "state.sqlite");
const attachmentsDir = join(stateDir, "attachments");
const logsDir = join(stateDir, "logs");
const providerLogsDir = join(logsDir, "provider");
return {
stateDir,
dbPath,
keybindingsConfigPath: join(stateDir, "keybindings.json"),
worktreesDir: join(baseDir, "worktrees"),
attachmentsDir,
logsDir,
serverLogPath: join(logsDir, "server.log"),
providerLogsDir,
providerEventLogPath: join(providerLogsDir, "events.log"),
terminalLogsDir: join(logsDir, "terminals"),
anonymousIdPath: join(stateDir, "anonymous-id"),
};
});
/**
* ServerConfig - Service tag for server runtime configuration.
*/
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
"t3/config/ServerConfig",
) {
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
static readonly layerTest = (cwd: string, statedir: string) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const devUrl = undefined;
const fs = yield* FileSystem.FileSystem;
const baseDir =
typeof baseDirOrPrefix === "string"
? baseDirOrPrefix
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* fs.makeDirectory(derivedPaths.stateDir, { recursive: true });
yield* fs.makeDirectory(derivedPaths.logsDir, { recursive: true });
yield* fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true });
const path = yield* Path.Path;
return {
cwd,
baseDir,
...derivedPaths,
stateDir: statedir,
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
port: 0,
host: undefined,
authToken: undefined,
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
staticDir: undefined,
devUrl,
devUrl: undefined,
noBrowser: false,
} satisfies ServerConfigShape;
};
}),
);
}
@@ -8,14 +8,11 @@ import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { TextGenerationError } from "../Errors.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-codex-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
CodexTextGenerationLive.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeCodexBinary(dir: string) {
return Effect.gen(function* () {
@@ -189,6 +186,8 @@ function withFakeCodexEnv<A, E, R>(
);
}
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
it.effect("generates and sanitizes commit messages without branch by default", () =>
withFakeCodexEnv(
@@ -326,10 +325,9 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
@@ -365,10 +363,9 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
@@ -413,9 +410,8 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
const textGeneration = yield* TextGeneration;
@@ -3,7 +3,6 @@ import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
@@ -18,6 +17,7 @@ import {
TextGeneration,
} from "../Services/TextGeneration.ts";
const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
@@ -163,7 +163,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
}
const resolvedPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
attachment,
});
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
@@ -187,7 +187,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
outputSchemaJson,
imagePaths = [],
cleanupPaths = [],
model,
}: {
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
cwd: string;
@@ -195,7 +194,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
outputSchemaJson: S;
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
model?: string;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
@@ -214,7 +212,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
"-s",
"read-only",
"--model",
model ?? DEFAULT_GIT_TEXT_GENERATION_MODEL,
CODEX_MODEL,
"--config",
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
@@ -355,7 +353,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
cwd: input.cwd,
prompt,
outputSchemaJson,
...(input.model ? { model: input.model } : {}),
}).pipe(
Effect.map(
(generated) =>
@@ -401,7 +398,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
title: Schema.String,
body: Schema.String,
}),
...(input.model ? { model: input.model } : {}),
}).pipe(
Effect.map(
(generated) =>
@@ -453,7 +449,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
branch: Schema.String,
}),
imagePaths,
...(input.model ? { model: input.model } : {}),
});
return {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+12 -165
View File
@@ -6,7 +6,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { expect } from "vitest";
import type { GitActionProgressEvent } from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
import { type GitManagerShape } from "../Services/GitManager.ts";
@@ -16,10 +15,10 @@ import {
GitHubCli,
} from "../Services/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
import { GitCoreLive } from "./GitCore.ts";
import { GitCore } from "../Services/GitCore.ts";
import { makeGitManager } from "./GitManager.ts";
import { ServerConfig } from "../../config.ts";
interface FakeGhScenario {
prListSequence?: string[];
@@ -107,11 +106,11 @@ function runGit(
): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string },
GitCommandError,
GitCore
GitService
> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
return yield* gitCore.execute({
const gitService = yield* GitService;
return yield* gitService.execute({
operation: "GitManager.test.runGit",
cwd,
args,
@@ -125,7 +124,7 @@ function initRepo(
): Effect.Effect<
void,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitService
> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -141,7 +140,7 @@ function initRepo(
function createBareRemote(): Effect.Effect<
string,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitService
> {
return Effect.gen(function* () {
const remoteDir = yield* makeTempDir("t3code-git-remote-");
@@ -450,20 +449,11 @@ function runStackedAction(
input: {
cwd: string;
action: "commit" | "commit_push" | "commit_push_pr";
actionId?: string;
commitMessage?: string;
featureBranch?: boolean;
filePaths?: readonly string[];
},
options?: Parameters<GitManagerShape["runStackedAction"]>[1],
) {
return manager.runStackedAction(
{
...input,
actionId: input.actionId ?? "test-action-id",
},
options,
);
return manager.runStackedAction(input);
}
function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) {
@@ -483,20 +473,18 @@ function makeManager(input?: {
}) {
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
const textGeneration = createTextGeneration(input?.textGeneration);
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-git-manager-test-",
});
const gitCoreLayer = GitCoreLive.pipe(
Layer.provideMerge(GitServiceLive),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerConfigLayer),
);
const managerLayer = Layer.mergeAll(
Layer.succeed(GitHubCli, gitHubCli),
Layer.succeed(TextGeneration, textGeneration),
gitCoreLayer,
).pipe(Layer.provideMerge(NodeServices.layer));
NodeServices.layer,
);
return makeGitManager.pipe(
Effect.provide(managerLayer),
@@ -504,10 +492,7 @@ function makeManager(input?: {
);
}
const GitManagerTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
Layer.provideMerge(NodeServices.layer),
);
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
it.layer(GitManagerTestLayer)("GitManager", (it) => {
it.effect("status includes PR metadata when branch already has an open PR", () =>
@@ -782,31 +767,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("commits only selected files when filePaths is provided", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "a.txt"), "file a\n");
fs.writeFileSync(path.join(repoDir, "b.txt"), "file b\n");
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit",
filePaths: ["a.txt"],
});
expect(result.commit.status).toBe("created");
// b.txt should remain in the working tree
const statusStdout = yield* runGit(repoDir, ["status", "--porcelain"]).pipe(
Effect.map((r) => r.stdout),
);
expect(statusStdout).toContain("b.txt");
expect(statusStdout).not.toContain("a.txt");
}),
);
it.effect("creates feature branch, commits, and pushes with featureBranch option", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -1950,117 +1910,4 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(errorMessage).toContain("already checked out in the main repo");
}),
);
it.effect("emits ordered progress events for commit hooks", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
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',
{ mode: 0o755 },
);
const { manager } = yield* makeManager();
const events: GitActionProgressEvent[] = [];
const result = yield* runStackedAction(
manager,
{
cwd: repoDir,
action: "commit",
},
{
actionId: "action-1",
progressReporter: {
publish: (event) =>
Effect.sync(() => {
events.push(event);
}),
},
},
);
expect(result.commit.status).toBe("created");
expect(events.map((event) => event.kind)).toContain("action_started");
expect(events).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "phase_started",
phase: "commit",
}),
expect.objectContaining({
kind: "hook_started",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "hook_output",
text: "hook: start",
}),
expect.objectContaining({
kind: "hook_output",
text: "hook: end",
}),
expect.objectContaining({
kind: "hook_finished",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "action_finished",
}),
]),
);
}),
);
it.effect("emits action_failed when a commit hook rejects", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "hook-failure.txt"), "broken\n");
fs.writeFileSync(
path.join(repoDir, ".git", "hooks", "pre-commit"),
'#!/bin/sh\necho "hook: fail" >&2\nexit 1\n',
{ mode: 0o755 },
);
const { manager } = yield* makeManager();
const events: GitActionProgressEvent[] = [];
const errorMessage = yield* runStackedAction(
manager,
{
cwd: repoDir,
action: "commit",
},
{
actionId: "action-2",
progressReporter: {
publish: (event) =>
Effect.sync(() => {
events.push(event);
}),
},
},
).pipe(
Effect.flip,
Effect.map((error) => error.message),
);
expect(errorMessage).toContain("hook: fail");
expect(events).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "hook_started",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "action_failed",
phase: "commit",
}),
]),
);
}),
);
});
+58 -276
View File
@@ -2,7 +2,6 @@ import { randomUUID } from "node:crypto";
import { realpathSync } from "node:fs";
import { Effect, FileSystem, Layer, Path } from "effect";
import type { GitActionProgressEvent, GitActionProgressPhase } from "@t3tools/contracts";
import {
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
@@ -10,21 +9,11 @@ import {
} from "@t3tools/shared/git";
import { GitManagerError } from "../Errors.ts";
import {
GitManager,
type GitActionProgressReporter,
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
import { GitCore } from "../Services/GitCore.ts";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
interface OpenPrInfo {
number: number;
title: string;
@@ -211,17 +200,6 @@ function sanitizeCommitMessage(generated: {
};
}
function sanitizeProgressText(value: string): string | null {
const trimmed = value.trim();
if (trimmed.length === 0) {
return null;
}
if (trimmed.length <= MAX_PROGRESS_TEXT_LENGTH) {
return trimmed;
}
return trimmed.slice(0, MAX_PROGRESS_TEXT_LENGTH).trimEnd();
}
interface CommitAndBranchSuggestion {
subject: string;
body: string;
@@ -359,29 +337,6 @@ export const makeGitManager = Effect.gen(function* () {
const gitHubCli = yield* GitHubCli;
const textGeneration = yield* TextGeneration;
const createProgressEmitter = (
input: { cwd: string; action: "commit" | "commit_push" | "commit_push_pr" },
options?: GitRunStackedActionOptions,
) => {
const actionId = options?.actionId ?? randomUUID();
const reporter = options?.progressReporter;
const emit = (event: GitActionProgressPayload) =>
reporter
? reporter.publish({
actionId,
cwd: input.cwd,
action: input.action,
...event,
} as GitActionProgressEvent)
: Effect.void;
return {
actionId,
emit,
};
};
const configurePullRequestHeadUpstream = (
cwd: string,
pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
@@ -683,11 +638,9 @@ export const makeGitManager = Effect.gen(function* () {
commitMessage?: string;
/** When true, also produce a semantic feature branch name. */
includeBranch?: boolean;
filePaths?: readonly string[];
model?: string;
}) =>
Effect.gen(function* () {
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
const context = yield* gitCore.prepareCommitContext(input.cwd);
if (!context) {
return null;
}
@@ -711,7 +664,6 @@ export const makeGitManager = Effect.gen(function* () {
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
...(input.includeBranch ? { includeBranch: true } : {}),
...(input.model ? { model: input.model } : {}),
})
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
@@ -725,111 +677,23 @@ export const makeGitManager = Effect.gen(function* () {
const runCommitStep = (
cwd: string,
action: "commit" | "commit_push" | "commit_push_pr",
branch: string | null,
commitMessage?: string,
preResolvedSuggestion?: CommitAndBranchSuggestion,
filePaths?: readonly string[],
model?: string,
progressReporter?: GitActionProgressReporter,
actionId?: string,
) =>
Effect.gen(function* () {
const emit = (event: GitActionProgressPayload) =>
progressReporter && actionId
? progressReporter.publish({
actionId,
cwd,
action,
...event,
} as GitActionProgressEvent)
: Effect.void;
let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion;
if (!suggestion) {
const needsGeneration = !commitMessage?.trim();
if (needsGeneration) {
yield* emit({
kind: "phase_started",
phase: "commit",
label: "Generating commit message...",
});
}
suggestion = yield* resolveCommitAndBranchSuggestion({
const suggestion =
preResolvedSuggestion ??
(yield* resolveCommitAndBranchSuggestion({
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
...(model ? { model } : {}),
});
}
}));
if (!suggestion) {
return { status: "skipped_no_changes" as const };
}
yield* emit({
kind: "phase_started",
phase: "commit",
label: "Committing...",
});
let currentHookName: string | null = null;
const commitProgress =
progressReporter && actionId
? {
onOutputLine: ({ stream, text }: { stream: "stdout" | "stderr"; text: string }) => {
const sanitized = sanitizeProgressText(text);
if (!sanitized) {
return Effect.void;
}
return emit({
kind: "hook_output",
hookName: currentHookName,
stream,
text: sanitized,
});
},
onHookStarted: (hookName: string) => {
currentHookName = hookName;
return emit({
kind: "hook_started",
hookName,
});
},
onHookFinished: ({
hookName,
exitCode,
durationMs,
}: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => {
if (currentHookName === hookName) {
currentHookName = null;
}
return emit({
kind: "hook_finished",
hookName,
exitCode,
durationMs,
});
},
}
: null;
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, {
timeoutMs: COMMIT_TIMEOUT_MS,
...(commitProgress ? { progress: commitProgress } : {}),
});
if (currentHookName !== null) {
yield* emit({
kind: "hook_finished",
hookName: currentHookName,
exitCode: 0,
durationMs: null,
});
currentHookName = null;
}
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
return {
status: "created" as const,
commitSha,
@@ -837,7 +701,7 @@ export const makeGitManager = Effect.gen(function* () {
};
});
const runPrStep = (cwd: string, fallbackBranch: string | null, model?: string) =>
const runPrStep = (cwd: string, fallbackBranch: string | null) =>
Effect.gen(function* () {
const details = yield* gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
@@ -881,7 +745,6 @@ export const makeGitManager = Effect.gen(function* () {
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
...(model ? { model } : {}),
});
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
@@ -1101,21 +964,13 @@ export const makeGitManager = Effect.gen(function* () {
},
);
const runFeatureBranchStep = (
cwd: string,
branch: string | null,
commitMessage?: string,
filePaths?: readonly string[],
model?: string,
) =>
const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
Effect.gen(function* () {
const suggestion = yield* resolveCommitAndBranchSuggestion({
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
includeBranch: true,
...(model ? { model } : {}),
});
if (!suggestion) {
return yield* gitManagerError(
@@ -1139,135 +994,62 @@ export const makeGitManager = Effect.gen(function* () {
});
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
function* (input, options) {
const progress = createProgressEmitter(input, options);
const phases: GitActionProgressPhase[] = [
...(input.featureBranch ? (["branch"] as const) : []),
"commit",
...(input.action !== "commit" ? (["push"] as const) : []),
...(input.action === "commit_push_pr" ? (["pr"] as const) : []),
];
let currentPhase: GitActionProgressPhase | null = null;
function* (input) {
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const runAction = Effect.gen(function* () {
yield* progress.emit({
kind: "action_started",
phases,
});
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
let commitMessageForStep = input.commitMessage;
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
if (input.featureBranch) {
currentPhase = "branch";
yield* progress.emit({
kind: "phase_started",
phase: "branch",
label: "Preparing feature branch...",
});
const result = yield* runFeatureBranchStep(
input.cwd,
initialStatus.branch,
input.commitMessage,
input.filePaths,
input.textGenerationModel,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
} else {
branchStep = { status: "skipped_not_requested" as const };
}
const currentBranch = branchStep.name ?? initialStatus.branch;
currentPhase = "commit";
const commit = yield* runCommitStep(
input.cwd,
input.action,
currentBranch,
commitMessageForStep,
preResolvedCommitSuggestion,
input.filePaths,
input.textGenerationModel,
options?.progressReporter,
progress.actionId,
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
const push = wantsPush
? yield* progress
.emit({
kind: "phase_started",
phase: "push",
label: "Pushing...",
})
.pipe(
Effect.flatMap(() =>
Effect.gen(function* () {
currentPhase = "push";
return yield* gitCore.pushCurrentBranch(input.cwd, currentBranch);
}),
),
)
: { status: "skipped_not_requested" as const };
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
let commitMessageForStep = input.commitMessage;
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
const pr = wantsPr
? yield* progress
.emit({
kind: "phase_started",
phase: "pr",
label: "Creating PR...",
})
.pipe(
Effect.flatMap(() =>
Effect.gen(function* () {
currentPhase = "pr";
return yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel);
}),
),
)
: { status: "skipped_not_requested" as const };
if (input.featureBranch) {
const result = yield* runFeatureBranchStep(
input.cwd,
initialStatus.branch,
input.commitMessage,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
} else {
branchStep = { status: "skipped_not_requested" as const };
}
const result = {
action: input.action,
branch: branchStep,
commit,
push,
pr,
};
yield* progress.emit({
kind: "action_finished",
result,
});
return result;
});
const currentBranch = branchStep.name ?? initialStatus.branch;
return yield* runAction.pipe(
Effect.catch((error) =>
progress
.emit({
kind: "action_failed",
phase: currentPhase,
message: error.message,
})
.pipe(Effect.flatMap(() => Effect.fail(error))),
),
const commit = yield* runCommitStep(
input.cwd,
currentBranch,
commitMessageForStep,
preResolvedCommitSuggestion,
);
const push = wantsPush
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? yield* runPrStep(input.cwd, currentBranch)
: { status: "skipped_not_requested" as const };
return {
action: input.action,
branch: branchStep,
commit,
push,
pr,
};
},
);
@@ -0,0 +1,59 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect";
import { GitCommandError } from "../Errors.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
layer("GitServiceLive", (it) => {
it.effect("runGit executes successful git commands", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.version",
cwd: process.cwd(),
args: ["--version"],
});
assert.equal(result.code, 0);
assert.ok(result.stdout.toLowerCase().includes("git version"));
}),
);
it.effect("runGit can return non-zero exit codes when allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.allowNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
allowNonZeroExit: true,
});
assert.notEqual(result.code, 0);
}),
);
it.effect("runGit fails with GitCommandError when non-zero exits are not allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* Effect.result(
gitService.execute({
operation: "GitProcess.test.failOnNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
}),
);
assert.equal(result._tag, "Failure");
if (result._tag === "Failure") {
assert.ok(Schema.is(GitCommandError)(result.failure));
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
}
}),
);
});
+144
View File
@@ -0,0 +1,144 @@
/**
* Git process helpers - Effect-native git execution with typed errors.
*
* Centralizes child-process git invocation for server modules. This module
* only executes git commands and reports structured failures.
*
* @module GitServiceLive
*/
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "../Errors.ts";
import {
ExecuteGitInput,
ExecuteGitResult,
GitService,
GitServiceShape,
} from "../Services/GitService.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
function quoteGitCommand(args: ReadonlyArray<string>): string {
return `git ${args.join(" ")}`;
}
function toGitCommandError(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
detail: string,
) {
return (cause: unknown) =>
Schema.is(GitCommandError)(cause)
? cause
: new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`,
...(cause !== undefined ? { cause } : {}),
});
}
const collectOutput = Effect.fn(function* <E>(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number,
): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder();
let bytes = 0;
let text = "";
yield* Stream.runForEach(stream, (chunk) =>
Effect.gen(function* () {
bytes += chunk.byteLength;
if (bytes > maxOutputBytes) {
return yield* new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
});
}
text += decoder.decode(chunk, { stream: true });
}),
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
text += decoder.decode();
return text;
});
const makeGitService = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
args: [...input.args],
} as const;
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const commandEffect = Effect.gen(function* () {
const child = yield* commandSpawner
.spawn(
ChildProcess.make("git", commandInput.args, {
cwd: commandInput.cwd,
...(input.env ? { env: input.env } : {}),
}),
)
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectOutput(commandInput, child.stdout, maxOutputBytes),
collectOutput(commandInput, child.stderr, maxOutputBytes),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
),
],
{ concurrency: "unbounded" },
);
if (!input.allowNonZeroExit && exitCode !== 0) {
const trimmedStderr = stderr.trim();
return yield* new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail:
trimmedStderr.length > 0
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
});
}
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
});
return yield* commandEffect.pipe(
Effect.scoped,
Effect.timeoutOption(timeoutMs),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
}),
),
onSome: Effect.succeed,
}),
),
);
});
return {
execute,
} satisfies GitServiceShape;
});
export const GitServiceLive = Layer.effect(GitService, makeGitService);
-53
View File
@@ -24,23 +24,6 @@ import type {
import type { GitCommandError } from "../Errors.ts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly progress?: ExecuteGitProgress;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
}
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
upstreamRef: string | null;
}
@@ -50,35 +33,6 @@ export interface GitPreparedCommitContext {
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;
@@ -132,11 +86,6 @@ export interface GitSetBranchUpstreamInput {
* 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.
*/
@@ -152,7 +101,6 @@ export interface GitCoreShape {
*/
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
/**
@@ -162,7 +110,6 @@ export interface GitCoreShape {
cwd: string,
subject: string,
body: string,
options?: GitCommitOptions,
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
/**
@@ -7,7 +7,6 @@
* @module GitManager
*/
import {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
@@ -21,15 +20,6 @@ import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitManagerServiceError } from "../Errors.ts";
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.
*/
@@ -61,7 +51,6 @@ export interface GitManagerShape {
*/
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
}
@@ -0,0 +1,45 @@
/**
* GitService - Service for Git command execution.
*
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
* domain errors for Git command execution.
*
* @module GitService
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitCommandError } from "../Errors.ts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
}
/**
* GitServiceShape - Service API for Git command execution.
*/
export interface GitServiceShape {
/**
* Execute a Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
}
/**
* GitService - Service for Git command execution.
*/
export class GitService extends ServiceMap.Service<GitService, GitServiceShape>()(
"t3/git/Services/GitService",
) {}
@@ -19,8 +19,6 @@ export interface CommitMessageGenerationInput {
stagedPatch: string;
/** When true, the model also returns a semantic branch name for the change. */
includeBranch?: boolean;
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
model?: string;
}
export interface CommitMessageGenerationResult {
@@ -37,8 +35,6 @@ export interface PrContentGenerationInput {
commitSummary: string;
diffSummary: string;
diffPatch: string;
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
model?: string;
}
export interface PrContentGenerationResult {
@@ -50,8 +46,6 @@ export interface BranchNameGenerationInput {
cwd: string;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
model?: string;
}
export interface BranchNameGenerationResult {
+11 -9
View File
@@ -3,7 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
import { ServerConfig } from "./config";
import { ServerConfig, type ServerConfigShape } from "./config";
import {
DEFAULT_KEYBINDINGS,
@@ -17,17 +17,21 @@ import {
} from "./keybindings";
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const makeKeybindingsLayer = () => {
return KeybindingsLive.pipe(
const makeKeybindingsLayer = () =>
KeybindingsLive.pipe(
Layer.provideMerge(
Layer.fresh(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-keybindings-test-",
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-server-config-test-" });
const configPath = join(dir, "keybindings.json");
return { keybindingsConfigPath: configPath } as ServerConfigShape;
}),
),
),
);
};
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
effect.pipe(
@@ -38,9 +42,7 @@ const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R
const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(rules);
yield* fileSystem.makeDirectory(path.dirname(configPath), { recursive: true });
yield* fileSystem.writeFileString(configPath, encoded);
});
+7 -7
View File
@@ -60,11 +60,13 @@ const runCli = (
args: ReadonlyArray<string>,
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
) => {
const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_STATE_DIR: uniqueStateDir,
...env,
},
}),
@@ -91,8 +93,8 @@ it.layer(testLayer)("server CLI command", (it) => {
"4010",
"--host",
"0.0.0.0",
"--home-dir",
"/tmp/t3-cli-home",
"--state-dir",
"/tmp/t3-cli-state",
"--dev-url",
"http://127.0.0.1:5173",
"--no-browser",
@@ -104,8 +106,7 @@ it.layer(testLayer)("server CLI command", (it) => {
assert.equal(resolvedConfig?.mode, "desktop");
assert.equal(resolvedConfig?.port, 4010);
assert.equal(resolvedConfig?.host, "0.0.0.0");
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-cli-home");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-home/dev");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-state");
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "auth-secret");
@@ -130,7 +131,7 @@ it.layer(testLayer)("server CLI command", (it) => {
T3CODE_MODE: "desktop",
T3CODE_PORT: "4999",
T3CODE_HOST: "100.88.10.4",
T3CODE_HOME: "/tmp/t3-env-home",
T3CODE_STATE_DIR: "/tmp/t3-env-state",
VITE_DEV_SERVER_URL: "http://localhost:5173",
T3CODE_NO_BROWSER: "true",
T3CODE_AUTH_TOKEN: "env-token",
@@ -140,8 +141,7 @@ it.layer(testLayer)("server CLI command", (it) => {
assert.equal(resolvedConfig?.mode, "desktop");
assert.equal(resolvedConfig?.port, 4999);
assert.equal(resolvedConfig?.host, "100.88.10.4");
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-home/dev");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-state");
assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "env-token");
+16 -12
View File
@@ -11,13 +11,12 @@ import { Command, Flag } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
import {
DEFAULT_PORT,
deriveServerPaths,
resolveStaticDir,
ServerConfig,
type RuntimeMode,
type ServerConfigShape,
} from "./config";
import { fixPath, resolveBaseDir } from "./os-jank";
import { fixPath, resolveStateDir } from "./os-jank";
import { Open } from "./open";
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
@@ -37,7 +36,7 @@ interface CliInput {
readonly mode: Option.Option<RuntimeMode>;
readonly port: Option.Option<number>;
readonly host: Option.Option<string>;
readonly t3Home: Option.Option<string>;
readonly stateDir: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly noBrowser: Option.Option<boolean>;
readonly authToken: Option.Option<string>;
@@ -100,7 +99,10 @@ const CliEnvConfig = Config.all({
),
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)),
stateDir: Config.string("T3CODE_STATE_DIR").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,
@@ -150,10 +152,10 @@ const ServerConfigLive = (input: CliInput) =>
return findAvailablePort(DEFAULT_PORT);
},
});
const stateDir = yield* resolveStateDir(
Option.getOrUndefined(input.stateDir) ?? env.stateDir,
);
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
const baseDir = yield* resolveBaseDir(Option.getOrUndefined(input.t3Home) ?? env.t3Home);
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
@@ -165,6 +167,8 @@ const ServerConfigLive = (input: CliInput) =>
env.logWebSocketEvents ?? Boolean(devUrl),
);
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
const { join } = yield* Path.Path;
const keybindingsConfigPath = join(stateDir, "keybindings.json");
const host =
Option.getOrUndefined(input.host) ??
env.host ??
@@ -174,9 +178,9 @@ const ServerConfigLive = (input: CliInput) =>
mode,
port,
cwd: cliConfig.cwd,
keybindingsConfigPath,
host,
baseDir,
...derivedPaths,
stateDir,
staticDir,
devUrl,
noBrowser,
@@ -295,8 +299,8 @@ 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,
);
const t3HomeFlag = Flag.string("home-dir").pipe(
Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
const stateDirFlag = Flag.string("state-dir").pipe(
Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
Flag.optional,
);
const devUrlFlag = Flag.string("dev-url").pipe(
@@ -331,7 +335,7 @@ export const t3Cli = Command.make("t3", {
mode: modeFlag,
port: portFlag,
host: hostFlag,
t3Home: t3HomeFlag,
stateDir: stateDirFlag,
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
authToken: authTokenFlag,
+56 -66
View File
@@ -1,7 +1,8 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import { FileSystem, Path, Effect } from "effect";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import {
isCommandAvailable,
@@ -9,19 +10,12 @@ import {
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open";
import { Effect } from "effect";
import { assertSuccess } from "@effect/vitest/utils";
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
describe("resolveEditorLaunch", () => {
it.effect("returns commands for command-based editors", () =>
Effect.gen(function* () {
const antigravityLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "antigravity" },
"darwin",
);
assert.deepEqual(antigravityLaunch, {
command: "agy",
args: ["/tmp/workspace"],
});
const cursorLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "cursor" },
"darwin",
@@ -123,7 +117,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
);
});
it.layer(NodeServices.layer)("launchDetached", (it) => {
describe("launchDetached", () => {
it.effect("resolves when command can be spawned", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
@@ -145,20 +139,26 @@ it.layer(NodeServices.layer)("launchDetached", (it) => {
);
});
it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
it.effect("resolves win32 commands with PATHEXT", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
describe("isCommandAvailable", () => {
function withTempDir(run: (dir: string) => void): void {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-"));
try {
run(dir);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
it("resolves win32 commands with PATHEXT", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "code.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
});
});
it("returns false when a command is not on PATH", () => {
const env = {
@@ -168,65 +168,55 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
});
it.effect("does not treat bare files without executable extension as available on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
it("does not treat bare files without executable extension as available on win32", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "npm"), "echo nope\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
}),
);
});
});
it.effect("appends PATHEXT for commands with non-executable extensions on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
it("appends PATHEXT for commands with non-executable extensions on win32", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "my.tool.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
}),
);
});
});
it.effect("uses platform-specific PATH delimiter for platform overrides", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
const env = {
PATH: `${firstDir};${secondDir}`,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
it("uses platform-specific PATH delimiter for platform overrides", () => {
withTempDir((firstDir) => {
withTempDir((secondDir) => {
fs.writeFileSync(path.join(secondDir, "code.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: `${firstDir};${secondDir}`,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
});
});
});
});
it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
it.effect("returns installed editors for command launches", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fs.writeFileString(path.join(dir, "cursor.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
describe("resolveAvailableEditors", () => {
it("returns only editors whose launch commands are available", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-"));
try {
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
const editors = resolveAvailableEditors("win32", {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["cursor", "file-manager"]);
}),
);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
@@ -3,7 +3,7 @@ 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 type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -19,7 +19,6 @@ 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 { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
@@ -45,7 +44,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -236,7 +235,6 @@ describe("CheckpointReactor", () => {
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly providerSessionCwd?: string;
readonly providerName?: ProviderKind;
}) {
const cwd = createGitRepository();
tempDirs.push(cwd);
@@ -244,7 +242,7 @@ describe("CheckpointReactor", () => {
cwd,
options?.hasSession ?? true,
options?.providerSessionCwd ?? cwd,
options?.providerName ?? "codex",
"codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
@@ -253,16 +251,12 @@ describe("CheckpointReactor", () => {
Layer.provide(SqlitePersistenceMemory),
);
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-reactor-test-",
});
const layer = CheckpointReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
@@ -483,67 +477,6 @@ describe("CheckpointReactor", () => {
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
});
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: "claudeAgent",
});
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
harness.provider.emit({
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
});
await waitForGitRefExists(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
);
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
harness.provider.emit({
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
payload: { state: "completed" },
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
const thread = await waitForThread(
harness.engine,
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
).toBe(true);
});
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
@@ -859,75 +792,6 @@ describe("CheckpointReactor", () => {
).toBe(false);
});
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: "claudeAgent" });
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
status: "ready",
files: [],
checkpointTurnCount: 1,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-2"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
status: "ready",
files: [],
checkpointTurnCount: 2,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
createdAt,
}),
);
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
});
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
const harness = await createHarness();
const createdAt = new Date().toISOString();
@@ -35,15 +35,12 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
async function createOrchestrationSystem() {
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-orchestration-engine-test-",
});
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(orchestrationLayer);
@@ -320,17 +317,13 @@ describe("OrchestrationEngine", () => {
},
};
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-orchestration-engine-test-",
});
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
),
);
File diff suppressed because it is too large. Load diff
@@ -243,7 +243,7 @@ const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSid
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
const path = yield* Effect.service(Path.Path);
const attachmentsRootDir = serverConfig.attachmentsDir;
const attachmentsRootDir = path.join(serverConfig.stateDir, "attachments");
yield* Effect.forEach(
sideEffects.deletedThreadIds,
@@ -653,8 +653,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
threadId: event.payload.threadId,
turnId: event.payload.proposedPlan.turnId,
planMarkdown: event.payload.proposedPlan.planMarkdown,
implementedAt: event.payload.proposedPlan.implementedAt,
implementationThreadId: event.payload.proposedPlan.implementationThreadId,
createdAt: event.payload.proposedPlan.createdAt,
updatedAt: event.payload.proposedPlan.updatedAt,
});
@@ -777,8 +775,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
yield* projectionTurnRepository.replacePendingTurnStart({
threadId: event.payload.threadId,
messageId: event.payload.messageId,
sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null,
sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null,
requestedAt: event.payload.createdAt,
});
return;
@@ -808,16 +804,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
pendingMessageId:
existingTurn.value.pendingMessageId ??
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),
sourceProposedPlanThreadId:
existingTurn.value.sourceProposedPlanThreadId ??
(Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanThreadId
: null),
sourceProposedPlanId:
existingTurn.value.sourceProposedPlanId ??
(Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanId
: null),
startedAt:
existingTurn.value.startedAt ??
(Option.isSome(pendingTurnStart)
@@ -836,12 +822,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
pendingMessageId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.messageId
: null,
sourceProposedPlanThreadId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanThreadId
: null,
sourceProposedPlanId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanId
: null,
assistantMessageId: null,
state: "running",
requestedAt: Option.isSome(pendingTurnStart)
@@ -895,8 +875,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.messageId,
state: event.payload.streaming ? "running" : "completed",
requestedAt: event.payload.createdAt,
@@ -932,8 +910,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: null,
state: "interrupted",
requestedAt: event.payload.createdAt,
@@ -978,8 +954,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.assistantMessageId,
state: nextState,
requestedAt: event.payload.completedAt,
@@ -26,7 +26,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_state`;
yield* sql`DELETE FROM projection_thread_proposed_plans`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
@@ -102,29 +101,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
)
`;
yield* sql`
INSERT INTO projection_thread_proposed_plans (
plan_id,
thread_id,
turn_id,
plan_markdown,
implemented_at,
implementation_thread_id,
created_at,
updated_at
)
VALUES (
'plan-1',
'thread-1',
'turn-1',
'# Ship it',
'2026-02-24T00:00:05.500Z',
'thread-2',
'2026-02-24T00:00:05.000Z',
'2026-02-24T00:00:05.500Z'
)
`;
yield* sql`
INSERT INTO projection_thread_activities (
activity_id,
@@ -178,8 +154,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
@@ -194,8 +168,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'thread-1',
'turn-1',
NULL,
'thread-1',
'plan-1',
'message-1',
'completed',
'2026-02-24T00:00:08.000Z',
@@ -266,10 +238,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
startedAt: "2026-02-24T00:00:08.000Z",
completedAt: "2026-02-24T00:00:08.000Z",
assistantMessageId: asMessageId("message-1"),
sourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-1"),
planId: "plan-1",
},
},
createdAt: "2026-02-24T00:00:02.000Z",
updatedAt: "2026-02-24T00:00:03.000Z",
@@ -285,17 +253,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
updatedAt: "2026-02-24T00:00:05.000Z",
},
],
proposedPlans: [
{
id: "plan-1",
turnId: asTurnId("turn-1"),
planMarkdown: "# Ship it",
implementedAt: "2026-02-24T00:00:05.500Z",
implementationThreadId: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-02-24T00:00:05.000Z",
updatedAt: "2026-02-24T00:00:05.500Z",
},
],
proposedPlans: [],
activities: [
{
id: asEventId("activity-1"),
@@ -4,10 +4,8 @@ import {
MessageId,
NonNegativeInt,
OrchestrationCheckpointFile,
OrchestrationProposedPlanId,
OrchestrationReadModel,
ProjectScript,
ThreadId,
TurnId,
type OrchestrationCheckpointSummary,
type OrchestrationLatestTurn,
@@ -76,8 +74,6 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
startedAt: Schema.NullOr(IsoDateTime),
completedAt: Schema.NullOr(IsoDateTime),
assistantMessageId: Schema.NullOr(MessageId),
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
});
const ProjectionStateDbRowSchema = ProjectionState;
@@ -204,8 +200,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
plan_markdown AS "planMarkdown",
implemented_at AS "implementedAt",
implementation_thread_id AS "implementationThreadId",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_proposed_plans
@@ -290,9 +284,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
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"
assistant_message_id AS "assistantMessageId"
FROM projection_turns
WHERE turn_id IS NOT NULL
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
@@ -443,8 +435,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
id: row.planId,
turnId: row.turnId,
planMarkdown: row.planMarkdown,
implementedAt: row.implementedAt,
implementationThreadId: row.implementationThreadId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
});
@@ -507,14 +497,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
startedAt: row.startedAt,
completedAt: row.completedAt,
assistantMessageId: row.assistantMessageId,
...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
? {
sourceProposedPlan: {
threadId: row.sourceProposedPlanThreadId,
planId: row.sourceProposedPlanId,
},
}
: {}),
});
}
@@ -16,7 +16,7 @@ import {
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../../git/Errors.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
@@ -41,9 +41,6 @@ const asApprovalRequestId = (value: string): ApprovalRequestId =>
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2000,
@@ -70,7 +67,6 @@ describe("ProviderCommandReactor", () => {
> | null = null;
let scope: Scope.Closeable | null = null;
const createdStateDirs = new Set<string>();
const createdBaseDirs = new Set<string>();
afterEach(async () => {
if (scope) {
@@ -85,22 +81,12 @@ describe("ProviderCommandReactor", () => {
fs.rmSync(stateDir, { recursive: true, force: true });
}
createdStateDirs.clear();
for (const baseDir of createdBaseDirs) {
fs.rmSync(baseDir, { recursive: true, force: true });
}
createdBaseDirs.clear();
});
async function createHarness(input?: {
readonly baseDir?: string;
readonly threadModel?: string;
}) {
async function createHarness(input?: { readonly stateDir?: string }) {
const now = new Date().toISOString();
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
createdBaseDirs.add(baseDir);
const { stateDir } = deriveServerPathsSync(baseDir, undefined);
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
createdStateDirs.add(stateDir);
const threadModel = input?.threadModel ?? "gpt-5-codex";
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
let nextSessionIndex = 1;
const runtimeSessions: Array<ProviderSession> = [];
@@ -110,7 +96,7 @@ describe("ProviderCommandReactor", () => {
typeof input === "object" &&
input !== null &&
"provider" in input &&
(input.provider === "codex" || input.provider === "claudeAgent")
input.provider === "codex"
? input.provider
: "codex";
const resumeCursor =
@@ -143,7 +129,7 @@ describe("ProviderCommandReactor", () => {
: "full-access",
...(model !== undefined ? { model } : {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
resumeCursor: resumeCursor ?? { opaque: `cursor-${sessionIndex}` },
createdAt: now,
updatedAt: now,
};
@@ -224,7 +210,7 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(layer);
@@ -242,7 +228,7 @@ describe("ProviderCommandReactor", () => {
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot: "/tmp/provider-project",
defaultModel: threadModel,
defaultModel: "gpt-5-codex",
createdAt: now,
}),
);
@@ -253,7 +239,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
model: threadModel,
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -365,106 +351,6 @@ describe("ProviderCommandReactor", () => {
});
});
it("forwards claude effort options through session start and turn send", async () => {
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort"),
role: "user",
text: "hello with effort",
attachments: [],
},
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
});
it("forwards claude fast mode options through session start and turn send", async () => {
const harness = await createHarness({ threadModel: "claude-opus-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-fast-mode"),
role: "user",
text: "hello with fast mode",
attachments: [],
},
provider: "claudeAgent",
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeAgent",
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
});
});
it("forwards plan interaction mode to the provider turn request", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -503,102 +389,6 @@ describe("ProviderCommandReactor", () => {
});
});
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-first"),
role: "user",
text: "hello claude",
attachments: [],
},
provider: "claudeAgent",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession).not.toHaveBeenCalled();
expect(harness.sendTurn).not.toHaveBeenCalled();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session).toBeNull();
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
summary: "Provider turn start failed",
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
});
it("rejects a turn when the requested model belongs to a different provider", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-model-provider-mismatch"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-model-provider-mismatch"),
role: "user",
text: "hello",
attachments: [],
},
model: "claude-sonnet-4-6",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession).not.toHaveBeenCalled();
expect(harness.sendTurn).not.toHaveBeenCalled();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("does not belong to provider 'codex'"),
},
});
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -645,74 +435,6 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts claude sessions when claude effort changes", async () => {
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort-1"),
role: "user",
text: "first claude turn",
attachments: [],
},
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "medium",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort-2"),
role: "user",
text: "second claude turn",
attachments: [],
},
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
provider: "claudeAgent",
resumeCursor: { opaque: "resume-1" },
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
});
it("restarts the provider session when runtime mode is updated on the thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -787,7 +509,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
resumeCursor: { opaque: "resume-1" },
resumeCursor: { opaque: "cursor-1" },
runtimeMode: "approval-required",
});
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
@@ -800,77 +522,6 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("rejects provider changes after a thread is already bound to a session provider", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-2"),
role: "user",
text: "second",
attachments: [],
},
provider: "claudeAgent",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession.mock.calls.length).toBe(1);
expect(harness.sendTurn.mock.calls.length).toBe(1);
expect(harness.stopSession.mock.calls.length).toBe(0);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerName).toBe("codex");
expect(thread?.session?.runtimeMode).toBe("approval-required");
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
});
it("does not stop the active session when restart fails before rebind", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1146,7 +797,6 @@ describe("ProviderCommandReactor", () => {
expect(failureActivity).toBeDefined();
expect(failureActivity?.payload).toMatchObject({
requestId: "approval-request-1",
detail: expect.stringContaining("Stale pending approval request: approval-request-1"),
});
const resolvedActivity = thread?.activities.find(
@@ -1159,117 +809,6 @@ describe("ProviderCommandReactor", () => {
expect(resolvedActivity).toBeUndefined();
});
it("surfaces stale provider user-input failures without faking user-input resolution", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.respondToUserInput.mockImplementation(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "claudeAgent",
method: "item/tool/respondToUserInput",
detail: "Unknown pending user-input request: user-input-request-1",
}),
),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input-error"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.activity.append",
commandId: CommandId.makeUnsafe("cmd-user-input-requested"),
threadId: ThreadId.makeUnsafe("thread-1"),
activity: {
id: EventId.makeUnsafe("activity-user-input-requested"),
tone: "info",
kind: "user-input.requested",
summary: "User input requested",
payload: {
requestId: "user-input-request-1",
questions: [
{
id: "sandbox_mode",
header: "Sandbox",
question: "Which mode should be used?",
options: [
{
label: "workspace-write",
description: "Allow workspace writes only",
},
],
},
],
},
turnId: null,
createdAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.user-input.respond",
commandId: CommandId.makeUnsafe("cmd-user-input-respond-stale"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("user-input-request-1"),
answers: {
sandbox_mode: "workspace-write",
},
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
if (!thread) return false;
return thread.activities.some(
(activity) => activity.kind === "provider.user-input.respond.failed",
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread).toBeDefined();
const failureActivity = thread?.activities.find(
(activity) => activity.kind === "provider.user-input.respond.failed",
);
expect(failureActivity).toBeDefined();
expect(failureActivity?.payload).toMatchObject({
requestId: "user-input-request-1",
detail: expect.stringContaining("Stale pending user-input request: user-input-request-1"),
});
const resolvedActivity = thread?.activities.find(
(activity) =>
activity.kind === "user-input.resolved" &&
typeof activity.payload === "object" &&
activity.payload !== null &&
(activity.payload as Record<string, unknown>).requestId === "user-input-request-1",
);
expect(resolvedActivity).toBeUndefined();
});
it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1,11 +1,10 @@
import {
type ChatAttachment,
CommandId,
DEFAULT_GIT_TEXT_GENERATION_MODEL,
EventId,
type OrchestrationEvent,
type ProviderModelOptions,
ProviderKind,
type ProviderKind,
type ProviderStartOptions,
type OrchestrationSession,
ThreadId,
@@ -26,7 +25,6 @@ import {
ProviderCommandReactor,
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { inferProviderForModel } from "@t3tools/shared/model";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -76,11 +74,6 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const WORKTREE_BRANCH_PREFIX = "t3code";
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
const sameModelOptions = (
left: ProviderModelOptions | undefined,
right: ProviderModelOptions | undefined,
): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
@@ -97,21 +90,6 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
);
}
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
}
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
}
function stalePendingRequestDetail(
requestKind: "approval" | "user-input",
requestId: string,
): string {
return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;
}
function isTemporaryWorktreeBranch(branch: string): boolean {
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
}
@@ -158,7 +136,6 @@ const make = Effect.gen(function* () {
);
const threadProviderOptions = new Map<string, ProviderStartOptions>();
const threadModelOptions = new Map<string, ProviderModelOptions>();
const appendProviderFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -228,30 +205,9 @@ const make = Effect.gen(function* () {
}
const desiredRuntimeMode = thread.runtimeMode;
const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(
thread.session?.providerName,
)
? thread.session.providerName
: undefined;
const threadProvider: ProviderKind = currentProvider ?? inferProviderForModel(thread.model);
if (options?.provider !== undefined && options.provider !== threadProvider) {
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${options.provider}'.`,
});
}
if (
options?.model !== undefined &&
inferProviderForModel(options.model, threadProvider) !== threadProvider
) {
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Model '${options.model}' does not belong to provider '${threadProvider}' for thread '${threadId}'.`,
});
}
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
const currentProvider: ProviderKind | undefined =
thread.session?.providerName === "codex" ? thread.session.providerName : undefined;
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
const desiredModel = options?.model ?? thread.model;
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
@@ -311,18 +267,8 @@ const make = Effect.gen(function* () {
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
const previousModelOptions = threadModelOptions.get(threadId);
const shouldRestartForModelOptionsChange =
currentProvider === "claudeAgent" &&
options?.modelOptions !== undefined &&
!sameModelOptions(previousModelOptions, options.modelOptions);
if (
!runtimeModeChanged &&
!providerChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelOptionsChange
) {
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
return existingSessionThreadId;
}
@@ -341,7 +287,6 @@ const make = Effect.gen(function* () {
providerChanged,
modelChanged,
shouldRestartForModelChange,
shouldRestartForModelOptionsChange,
hasResumeCursor: resumeCursor !== undefined,
});
const restartedSession = yield* startProviderSession({
@@ -381,18 +326,15 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
if (input.providerOptions !== undefined) {
threadProviderOptions.set(input.threadId, input.providerOptions);
}
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
if (input.providerOptions !== undefined) {
threadProviderOptions.set(input.threadId, input.providerOptions);
}
if (input.modelOptions !== undefined) {
threadModelOptions.set(input.threadId, input.modelOptions);
}
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
const activeSession = yield* providerService
@@ -449,7 +391,6 @@ const make = Effect.gen(function* () {
cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
})
.pipe(
Effect.catch((error) =>
@@ -534,18 +475,7 @@ const make = Effect.gen(function* () {
: {}),
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
}).pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
}),
),
);
});
});
const processTurnInterruptRequested = Effect.fnUntraced(function* (
@@ -604,9 +534,7 @@ const make = Effect.gen(function* () {
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),
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
@@ -650,9 +578,7 @@ const make = Effect.gen(function* () {
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: isUnknownPendingUserInputRequestError(cause)
? stalePendingRequestDetail("user-input", event.payload.requestId)
: Cause.pretty(cause),
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
@@ -698,13 +624,13 @@ const make = Effect.gen(function* () {
return;
}
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
const cachedModelOptions = threadModelOptions.get(event.payload.threadId);
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
...(cachedProviderOptions !== undefined
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedProviderOptions !== undefined
? { providerOptions: cachedProviderOptions }
: {}),
...(cachedModelOptions !== undefined ? { modelOptions: cachedModelOptions } : {}),
});
: undefined,
);
return;
}
case "thread.turn-start-requested":
@@ -2,12 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type {
OrchestrationReadModel,
ProviderKind,
ProviderRuntimeEvent,
ProviderSession,
} from "@t3tools/contracts";
import type { OrchestrationReadModel, ProviderRuntimeEvent } from "@t3tools/contracts";
import {
ApprovalRequestId,
CommandId,
@@ -50,7 +45,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -62,7 +57,6 @@ type LegacyProviderRuntimeEvent = {
function createProviderServiceHarness() {
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
const runtimeSessions: ProviderSession[] = [];
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: ProviderServiceShape = {
@@ -72,21 +66,12 @@ function createProviderServiceHarness() {
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession: () => unsupported(),
listSessions: () => Effect.succeed([...runtimeSessions]),
listSessions: () => Effect.succeed([]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
const setSession = (session: ProviderSession): void => {
const existingIndex = runtimeSessions.findIndex((entry) => entry.threadId === session.threadId);
if (existingIndex >= 0) {
runtimeSessions[existingIndex] = session;
return;
}
runtimeSessions.push(session);
};
const emit = (event: LegacyProviderRuntimeEvent): void => {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
};
@@ -94,7 +79,6 @@ function createProviderServiceHarness() {
return {
service,
emit,
setSession,
};
}
@@ -102,12 +86,11 @@ async function waitForThread(
engine: OrchestrationEngineShape,
predicate: (thread: ProviderRuntimeTestThread) => boolean,
timeoutMs = 2000,
threadId: ThreadId = asThreadId("thread-1"),
) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<ProviderRuntimeTestThread> => {
const readModel = await Effect.runPromise(engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === threadId);
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
if (thread && predicate(thread)) {
return thread;
}
@@ -167,7 +150,6 @@ describe("ProviderRuntimeIngestion", () => {
);
const layer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
@@ -223,19 +205,10 @@ describe("ProviderRuntimeIngestion", () => {
createdAt,
}),
);
provider.setSession({
provider: "codex",
status: "ready",
runtimeMode: "approval-required",
threadId: ThreadId.makeUnsafe("thread-1"),
createdAt,
updatedAt: createdAt,
});
return {
engine,
emit: provider.emit,
setProviderSession: provider.setSession,
drain,
};
}
@@ -429,60 +402,6 @@ describe("ProviderRuntimeIngestion", () => {
);
});
it("accepts claude turn lifecycle when seeded thread id is a synthetic placeholder", async () => {
const harness = await createHarness();
const seededAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-seed-claude-placeholder"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: seededAt,
lastError: null,
},
createdAt: seededAt,
}),
);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-claude-placeholder"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-claude-placeholder",
);
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-claude-placeholder"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
status: "completed",
});
await waitForThread(
harness.engine,
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
);
});
it("ignores auxiliary turn completions from a different provider thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -709,496 +628,6 @@ describe("ProviderRuntimeIngestion", () => {
);
});
it("marks the source proposed plan implemented only after the target turn starts", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
const targetThreadId = asThreadId("thread-implement");
const sourceTurnId = asTurnId("turn-plan-source");
const targetTurnId = asTurnId("turn-plan-implement");
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target"),
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target"),
threadId: targetThreadId,
session: {
threadId: targetThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
harness.setProviderSession({
provider: "codex",
status: "ready",
runtimeMode: "approval-required",
threadId: targetThreadId,
createdAt,
updatedAt: createdAt,
activeTurnId: targetTurnId,
});
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
payload: {
planMarkdown: "# Source plan",
},
});
const sourceThreadWithPlan = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) =>
entry.id === "plan:thread-plan:turn:turn-plan-source",
);
expect(sourcePlan).toBeDefined();
if (!sourcePlan) {
throw new Error("Expected source plan to exist.");
}
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target"),
role: "user",
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
attachments: [],
},
sourceProposedPlan: {
threadId: sourceThreadId,
planId: sourcePlan.id,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
const sourceThreadBeforeStart = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === sourcePlan.id && proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
expect(
sourceThreadBeforeStart.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementedAt: null,
implementationThreadId: null,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-plan-target-started"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: targetTurnId,
});
const sourceThreadAfterStart = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === sourcePlan.id &&
proposedPlan.implementedAt !== null &&
proposedPlan.implementationThreadId === targetThreadId,
),
2_000,
sourceThreadId,
);
expect(
sourceThreadAfterStart.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementationThreadId: "thread-implement",
});
});
it("does not mark the source proposed plan implemented for a rejected turn.started event", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
const targetThreadId = asThreadId("thread-1");
const sourceTurnId = asTurnId("turn-plan-source");
const activeTurnId = asTurnId("turn-already-running");
const staleTurnId = asTurnId("turn-stale-start");
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-guarded"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
harness.setProviderSession({
provider: "codex",
status: "running",
runtimeMode: "approval-required",
threadId: targetThreadId,
createdAt,
updatedAt: createdAt,
activeTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-already-running"),
provider: "codex",
createdAt,
threadId: targetThreadId,
turnId: activeTurnId,
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === activeTurnId,
2_000,
targetThreadId,
);
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed-guarded"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
payload: {
planMarkdown: "# Source plan",
},
});
const sourceThreadWithPlan = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) =>
entry.id === "plan:thread-plan:turn:turn-plan-source",
);
expect(sourcePlan).toBeDefined();
if (!sourcePlan) {
throw new Error("Expected source plan to exist.");
}
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-guarded"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target-guarded"),
role: "user",
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
attachments: [],
},
sourceProposedPlan: {
threadId: sourceThreadId,
planId: sourcePlan.id,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-stale-plan-implementation"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: staleTurnId,
});
await harness.drain();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const sourceThreadAfterRejectedStart = readModel.threads.find(
(entry) => entry.id === sourceThreadId,
);
expect(
sourceThreadAfterRejectedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementedAt: null,
implementationThreadId: null,
});
const targetThreadAfterRejectedStart = readModel.threads.find(
(entry) => entry.id === targetThreadId,
);
expect(targetThreadAfterRejectedStart?.session?.status).toBe("running");
expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId);
});
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
const targetThreadId = asThreadId("thread-implement");
const sourceTurnId = asTurnId("turn-plan-source");
const expectedTurnId = asTurnId("turn-plan-implement");
const replayedTurnId = asTurnId("turn-replayed");
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-unrelated"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-unrelated"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target-unrelated"),
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target-unrelated"),
threadId: targetThreadId,
session: {
threadId: targetThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed-unrelated"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
payload: {
planMarkdown: "# Source plan",
},
});
const sourceThreadWithPlan = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) =>
entry.id === "plan:thread-plan:turn:turn-plan-source",
);
expect(sourcePlan).toBeDefined();
if (!sourcePlan) {
throw new Error("Expected source plan to exist.");
}
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-unrelated"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target-unrelated"),
role: "user",
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
attachments: [],
},
sourceProposedPlan: {
threadId: sourceThreadId,
planId: sourcePlan.id,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
harness.setProviderSession({
provider: "codex",
status: "running",
runtimeMode: "approval-required",
threadId: targetThreadId,
createdAt,
updatedAt: createdAt,
activeTurnId: expectedTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-unrelated-plan-implementation"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: replayedTurnId,
});
await harness.drain();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const sourceThreadAfterUnrelatedStart = readModel.threads.find(
(entry) => entry.id === sourceThreadId,
);
expect(
sourceThreadAfterUnrelatedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementedAt: null,
implementationThreadId: null,
});
});
it("finalizes buffered proposed-plan deltas into a first-class proposed plan on turn completion", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1925,7 +1354,6 @@ describe("ProviderRuntimeIngestion", () => {
payload: {
taskId: "turn-task-1",
description: "Comparing the desktop rollout chunks to the app-server stream.",
summary: "Code reviewer is validating the desktop rollout chunks.",
},
});
@@ -1988,9 +1416,8 @@ describe("ProviderRuntimeIngestion", () => {
expect(started?.kind).toBe("task.started");
expect(started?.summary).toBe("Plan task started");
expect(progress?.kind).toBe("task.progress");
expect(progressPayload?.detail).toBe("Code reviewer is validating the desktop rollout chunks.");
expect(progressPayload?.summary).toBe(
"Code reviewer is validating the desktop rollout chunks.",
expect(progressPayload?.detail).toBe(
"Comparing the desktop rollout chunks to the app-server stream.",
);
expect(completed?.kind).toBe("task.completed");
expect(completedPayload?.detail).toBe("<proposed_plan>\n# Plan title\n</proposed_plan>");
@@ -4,9 +4,7 @@ import {
CommandId,
MessageId,
type OrchestrationEvent,
type OrchestrationProposedPlanId,
CheckpointRef,
isToolLifecycleItemType,
ThreadId,
TurnId,
type OrchestrationThreadActivity,
@@ -16,8 +14,6 @@ import { Cache, Cause, Duration, Effect, Layer, Option, Ref, Stream } from "effe
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { isGitRepository } from "../../git/isRepo.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -177,6 +173,18 @@ function requestKindFromCanonicalRequestType(
}
}
function isToolLifecycleItemType(itemType: string): boolean {
return (
itemType === "command_execution" ||
itemType === "file_change" ||
itemType === "mcp_tool_call" ||
itemType === "dynamic_tool_call" ||
itemType === "collab_agent_tool_call" ||
itemType === "web_search" ||
itemType === "image_view"
);
}
function runtimeEventToActivities(
event: ProviderRuntimeEvent,
): ReadonlyArray<OrchestrationThreadActivity> {
@@ -373,8 +381,7 @@ function runtimeEventToActivities(
summary: "Reasoning update",
payload: {
taskId: event.payload.taskId,
detail: truncateDetail(event.payload.summary ?? event.payload.description),
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
detail: truncateDetail(event.payload.description),
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
@@ -442,7 +449,7 @@ function runtimeEventToActivities(
createdAt: event.createdAt,
tone: "tool",
kind: "tool.completed",
summary: event.payload.title ?? "Tool",
summary: `${event.payload.title ?? "Tool"} complete`,
payload: {
itemType: event.payload.itemType,
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
@@ -484,7 +491,6 @@ function runtimeEventToActivities(
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
DEFAULT_ASSISTANT_DELIVERY_MODE,
@@ -676,8 +682,6 @@ const make = Effect.gen(function* () {
threadProposedPlans: ReadonlyArray<{
id: string;
createdAt: string;
implementedAt: string | null;
implementationThreadId: ThreadId | null;
}>;
planId: string;
turnId?: TurnId;
@@ -700,8 +704,6 @@ const make = Effect.gen(function* () {
id: input.planId,
turnId: input.turnId ?? null,
planMarkdown,
implementedAt: existingPlan?.implementedAt ?? null,
implementationThreadId: existingPlan?.implementationThreadId ?? null,
createdAt: existingPlan?.createdAt ?? input.createdAt,
updatedAt: input.updatedAt,
},
@@ -715,8 +717,6 @@ const make = Effect.gen(function* () {
threadProposedPlans: ReadonlyArray<{
id: string;
createdAt: string;
implementedAt: string | null;
implementationThreadId: ThreadId | null;
}>;
planId: string;
turnId?: TurnId;
@@ -783,79 +783,6 @@ const make = Effect.gen(function* () {
).pipe(Effect.asVoid);
});
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
) {
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId,
});
if (Option.isNone(pendingTurnStart)) {
return null;
}
const sourceThreadId = pendingTurnStart.value.sourceProposedPlanThreadId;
const sourcePlanId = pendingTurnStart.value.sourceProposedPlanId;
if (sourceThreadId === null || sourcePlanId === null) {
return null;
}
return {
sourceThreadId,
sourcePlanId,
} as const;
});
const getExpectedProviderTurnIdForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const sessions = yield* providerService.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
return session?.activeTurnId;
});
const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
eventTurnId: TurnId | undefined,
) {
if (eventTurnId === undefined) {
return null;
}
const expectedTurnId = yield* getExpectedProviderTurnIdForThread(threadId);
if (!sameId(expectedTurnId, eventTurnId)) {
return null;
}
return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId);
});
const markSourceProposedPlanImplemented = Effect.fnUntraced(function* (
sourceThreadId: ThreadId,
sourcePlanId: OrchestrationProposedPlanId,
implementationThreadId: ThreadId,
implementedAt: string,
) {
const readModel = yield* orchestrationEngine.getReadModel();
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.makeUnsafe(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
),
threadId: sourceThread.id,
proposedPlan: {
...sourcePlan,
implementedAt,
implementationThreadId,
updatedAt: implementedAt,
},
createdAt: implementedAt,
});
});
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -896,10 +823,6 @@ const make = Effect.gen(function* () {
return true;
}
})();
const acceptedTurnStartedSourcePlan =
event.type === "turn.started" && shouldApplyThreadLifecycle
? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)
: null;
if (
event.type === "session.started" ||
@@ -942,26 +865,6 @@ const make = Effect.gen(function* () {
: (thread.session?.lastError ?? null);
if (shouldApplyThreadLifecycle) {
if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) {
yield* markSourceProposedPlanImplemented(
acceptedTurnStartedSourcePlan.sourceThreadId,
acceptedTurnStartedSourcePlan.sourcePlanId,
thread.id,
now,
).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(
"provider runtime ingestion failed to mark source proposed plan",
{
eventId: event.eventId,
eventType: event.type,
cause: Cause.pretty(cause),
},
),
),
);
}
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "thread-session-set"),
@@ -1252,7 +1155,4 @@ const make = Effect.gen(function* () {
} satisfies ProviderRuntimeIngestionShape;
});
export const ProviderRuntimeIngestionLive = Layer.effect(
ProviderRuntimeIngestionService,
make,
).pipe(Layer.provide(ProjectionTurnRepositoryLive));
export const ProviderRuntimeIngestionLive = Layer.effect(ProviderRuntimeIngestionService, make);
+7 -28
View File
@@ -262,35 +262,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}
case "thread.turn.start": {
const targetThread = yield* requireThread({
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const sourceProposedPlan = command.sourceProposedPlan;
const sourceThread = sourceProposedPlan
? yield* requireThread({
readModel,
command,
threadId: sourceProposedPlan.threadId,
})
: null;
const sourcePlan =
sourceProposedPlan && sourceThread
? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
: null;
if (sourceProposedPlan && !sourcePlan) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
});
}
if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
});
}
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
...withEventBase({
aggregateKind: "thread",
@@ -330,9 +306,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
? { providerOptions: command.providerOptions }
: {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
runtimeMode: targetThread.runtimeMode,
interactionMode: targetThread.interactionMode,
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
runtimeMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
command.runtimeMode,
interactionMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
command.interactionMode,
createdAt: command.createdAt,
},
};
+2 -2
View File
@@ -27,10 +27,10 @@ export const expandHomePath = Effect.fn(function* (input: string) {
return input;
});
export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {
export const resolveStateDir = Effect.fn(function* (raw: string | undefined) {
const { join, resolve } = yield* Path.Path;
if (!raw || raw.trim().length === 0) {
return join(OS.homedir(), ".t3");
return join(OS.homedir(), ".t3", "userdata");
}
return resolve(yield* expandHomePath(raw.trim()));
});
@@ -22,8 +22,6 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
thread_id,
turn_id,
plan_markdown,
implemented_at,
implementation_thread_id,
created_at,
updated_at
)
@@ -32,8 +30,6 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
${row.threadId},
${row.turnId},
${row.planMarkdown},
${row.implementedAt},
${row.implementationThreadId},
${row.createdAt},
${row.updatedAt}
)
@@ -42,8 +38,6 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
plan_markdown = excluded.plan_markdown,
implemented_at = excluded.implemented_at,
implementation_thread_id = excluded.implementation_thread_id,
created_at = excluded.created_at,
updated_at = excluded.updated_at
`,
@@ -58,8 +52,6 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
plan_markdown AS "planMarkdown",
implemented_at AS "implementedAt",
implementation_thread_id AS "implementationThreadId",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_proposed_plans
@@ -47,8 +47,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
@@ -63,8 +61,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
${row.threadId},
${row.turnId},
${row.pendingMessageId},
${row.sourceProposedPlanThreadId},
${row.sourceProposedPlanId},
${row.assistantMessageId},
${row.state},
${row.requestedAt},
@@ -78,8 +74,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
ON CONFLICT (thread_id, turn_id)
DO UPDATE SET
pending_message_id = excluded.pending_message_id,
source_proposed_plan_thread_id = excluded.source_proposed_plan_thread_id,
source_proposed_plan_id = excluded.source_proposed_plan_id,
assistant_message_id = excluded.assistant_message_id,
state = excluded.state,
requested_at = excluded.requested_at,
@@ -112,8 +106,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
@@ -128,8 +120,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
${row.threadId},
NULL,
${row.messageId},
${row.sourceProposedPlanThreadId},
${row.sourceProposedPlanId},
NULL,
'pending',
${row.requestedAt},
@@ -151,8 +141,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
pending_message_id AS "messageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
requested_at AS "requestedAt"
FROM projection_turns
WHERE thread_id = ${threadId}
@@ -174,8 +162,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
pending_message_id AS "pendingMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
assistant_message_id AS "assistantMessageId",
state,
requested_at AS "requestedAt",
@@ -207,8 +193,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
pending_message_id AS "pendingMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
assistant_message_id AS "assistantMessageId",
state,
requested_at AS "requestedAt",
+6 -3
View File
@@ -49,6 +49,9 @@ export const SqlitePersistenceMemory = Layer.provideMerge(
makeRuntimeSqliteLayer({ filename: ":memory:" }),
);
export const layerConfig = Layer.unwrap(
Effect.map(Effect.service(ServerConfig), ({ dbPath }) => makeSqlitePersistenceLive(dbPath)),
);
export const layerConfig = Effect.gen(function* () {
const { stateDir } = yield* ServerConfig;
const { join } = yield* Path.Path;
const dbPath = join(stateDir, "state.sqlite");
return makeSqlitePersistenceLive(dbPath);
}).pipe(Layer.unwrap);
@@ -25,8 +25,6 @@ import Migration0010 from "./Migrations/010_ProjectionThreadsRuntimeMode.ts";
import Migration0011 from "./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts";
import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts";
import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
import { Effect } from "effect";
/**
@@ -53,8 +51,6 @@ const loader = Migrator.fromRecord({
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
"12_ProjectionThreadsInteractionMode": Migration0012,
"13_ProjectionThreadProposedPlans": Migration0013,
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
});
/**
@@ -1,16 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_thread_proposed_plans
ADD COLUMN implemented_at TEXT
`;
yield* sql`
ALTER TABLE projection_thread_proposed_plans
ADD COLUMN implementation_thread_id TEXT
`;
});
@@ -1,16 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_turns
ADD COLUMN source_proposed_plan_thread_id TEXT
`;
yield* sql`
ALTER TABLE projection_turns
ADD COLUMN source_proposed_plan_id TEXT
`;
});
@@ -50,35 +50,11 @@ export interface SqliteMemoryClientConfig extends Omit<
"filename" | "readonly"
> {}
/**
* Verify that the current Node.js version includes the `node:sqlite` APIs
* used by `NodeSqliteClient` — specifically `StatementSync.columns()` (added
* in Node 22.16.0 / 23.11.0).
*
* @see https://github.com/nodejs/node/pull/57490
*/
const checkNodeSqliteCompat = () => {
const parts = process.versions.node.split(".").map(Number);
const major = parts[0] ?? 0;
const minor = parts[1] ?? 0;
const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24;
if (!supported) {
return Effect.die(
`Node.js ${process.versions.node} is missing required node:sqlite APIs ` +
`(StatementSync.columns). Upgrade to Node.js >=22.16, >=23.11, or >=24.`,
);
}
return Effect.void;
};
const makeWithDatabase = (
options: SqliteClientConfig,
openDatabase: () => DatabaseSync,
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
Effect.gen(function* () {
yield* checkNodeSqliteCompat();
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
const transformRows = options.transformResultNames
? Statement.defaultTransforms(options.transformResultNames).array
@@ -15,8 +15,6 @@ export const ProjectionThreadProposedPlan = Schema.Struct({
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
planMarkdown: TrimmedNonEmptyString,
implementedAt: Schema.NullOr(IsoDateTime),
implementationThreadId: Schema.NullOr(ThreadId),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
});
@@ -11,7 +11,6 @@ import {
IsoDateTime,
MessageId,
NonNegativeInt,
OrchestrationProposedPlanId,
OrchestrationCheckpointFile,
OrchestrationCheckpointStatus,
ThreadId,
@@ -35,8 +34,6 @@ export const ProjectionTurn = Schema.Struct({
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
pendingMessageId: Schema.NullOr(MessageId),
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
assistantMessageId: Schema.NullOr(MessageId),
state: ProjectionTurnState,
requestedAt: IsoDateTime,
@@ -53,8 +50,6 @@ export const ProjectionTurnById = Schema.Struct({
threadId: ThreadId,
turnId: TurnId,
pendingMessageId: Schema.NullOr(MessageId),
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
assistantMessageId: Schema.NullOr(MessageId),
state: ProjectionTurnState,
requestedAt: IsoDateTime,
@@ -70,8 +65,6 @@ export type ProjectionTurnById = typeof ProjectionTurnById.Type;
export const ProjectionPendingTurnStart = Schema.Struct({
threadId: ThreadId,
messageId: MessageId,
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
requestedAt: IsoDateTime,
});
export type ProjectionPendingTurnStart = typeof ProjectionPendingTurnStart.Type;
+96 -86
View File
@@ -1,6 +1,8 @@
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { Effect, Option } from "effect";
import { HttpServerResponse } from "effect/unstable/http";
const FAVICON_MIME_TYPES: Record<string, string> = {
".png": "image/png",
@@ -70,102 +72,110 @@ function isPathWithinProject(projectCwd: string, candidatePath: string): boolean
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
}
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
const ext = path.extname(filePath).toLowerCase();
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
fs.readFile(filePath, (readErr, data) => {
if (readErr) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Read error");
return;
}
res.writeHead(200, {
"Content-Type": contentType,
"Cache-Control": "public, max-age=3600",
});
res.end(data);
});
async function isFile(candidatePath: string): Promise<boolean> {
try {
const stats = await fs.promises.stat(candidatePath);
return stats.isFile();
} catch {
return false;
}
}
function serveFallbackFavicon(res: http.ServerResponse): void {
res.writeHead(200, {
"Content-Type": "image/svg+xml",
"Cache-Control": "public, max-age=3600",
});
res.end(FALLBACK_FAVICON_SVG);
async function resolveFaviconPath(projectCwd: string): Promise<string | null> {
for (const candidate of FAVICON_CANDIDATES) {
const candidatePath = path.join(projectCwd, candidate);
if (!isPathWithinProject(projectCwd, candidatePath)) {
continue;
}
if (await isFile(candidatePath)) {
return candidatePath;
}
}
for (const sourceFile of ICON_SOURCE_FILES) {
const sourceFilePath = path.join(projectCwd, sourceFile);
let content: string;
try {
content = await fs.promises.readFile(sourceFilePath, "utf8");
} catch {
continue;
}
const href = extractIconHref(content);
if (!href) {
continue;
}
const candidates = resolveIconHref(projectCwd, href);
for (const candidatePath of candidates) {
if (!isPathWithinProject(projectCwd, candidatePath)) {
continue;
}
if (await isFile(candidatePath)) {
return candidatePath;
}
}
}
return null;
}
export const handleProjectFaviconRequest = (projectCwd: string | null) =>
Effect.gen(function* () {
if (!projectCwd) {
return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
}
const faviconPath = yield* Effect.promise(() => resolveFaviconPath(projectCwd));
if (!faviconPath) {
return HttpServerResponse.text(FALLBACK_FAVICON_SVG, {
contentType: "image/svg+xml",
headers: { "Cache-Control": "public, max-age=3600" },
});
}
const data = yield* Effect.promise(() => fs.promises.readFile(faviconPath)).pipe(Effect.option);
if (Option.isNone(data)) {
return HttpServerResponse.text("Read error", { status: 500 });
}
const ext = path.extname(faviconPath).toLowerCase();
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
return HttpServerResponse.uint8Array(new Uint8Array(data.value), {
contentType,
headers: { "Cache-Control": "public, max-age=3600" },
});
});
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
if (url.pathname !== "/api/project-favicon") {
return false;
}
const projectCwd = url.searchParams.get("cwd");
if (!projectCwd) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Missing cwd parameter");
return true;
}
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
if (index >= paths.length) {
onExhausted();
return;
}
const candidate = paths[index]!;
if (!isPathWithinProject(projectCwd, candidate)) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
void Effect.runPromise(handleProjectFaviconRequest(url.searchParams.get("cwd")))
.then((response) => {
const webResponse = HttpServerResponse.toWeb(response);
res.statusCode = webResponse.status;
for (const [header, value] of webResponse.headers.entries()) {
res.setHeader(header, value);
}
serveFaviconFile(candidate, res);
return webResponse
.arrayBuffer()
.then((buffer) => {
res.end(Buffer.from(buffer));
})
.catch(() => {
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "text/plain" });
}
res.end("Read error");
});
})
.catch(() => {
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "text/plain" });
}
res.end("Read error");
});
};
const trySourceFiles = (index: number): void => {
if (index >= ICON_SOURCE_FILES.length) {
serveFallbackFavicon(res);
return;
}
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
fs.readFile(sourceFile, "utf8", (err, content) => {
if (err) {
trySourceFiles(index + 1);
return;
}
const href = extractIconHref(content);
if (!href) {
trySourceFiles(index + 1);
return;
}
const candidates = resolveIconHref(projectCwd, href);
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
});
};
const tryCandidates = (index: number): void => {
if (index >= FAVICON_CANDIDATES.length) {
trySourceFiles(0);
return;
}
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
if (!isPathWithinProject(projectCwd, candidate)) {
tryCandidates(index + 1);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryCandidates(index + 1);
return;
}
serveFaviconFile(candidate, res);
});
};
tryCandidates(0);
return true;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -22,7 +22,6 @@ import {
type CodexAppServerSendTurnInput,
} from "../../codexAppServerManager.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
@@ -157,29 +156,6 @@ const validationLayer = it.layer(
);
validationLayer("CodexAdapterLive validation", (it) => {
it.effect("returns validation error for non-codex provider on startSession", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const result = yield* adapter
.startSession({
provider: "claudeAgent",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
})
.pipe(Effect.result);
assert.equal(result._tag, "Failure");
assert.deepStrictEqual(
result.failure,
new ProviderAdapterValidationError({
provider: "codex",
operation: "startSession",
issue: "Expected provider 'codex' but received 'claudeAgent'.",
}),
);
assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
}),
);
it.effect("maps codex model options before starting a session", () =>
Effect.gen(function* () {
validationManager.startSessionImpl.mockClear();
@@ -800,45 +776,6 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}
}),
);
it.effect("prefers manager-assigned turn ids for Codex task events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-started-parent-turn"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-parent"),
createdAt: new Date().toISOString(),
method: "codex/event/task_started",
payload: {
id: "turn-child",
msg: {
type: "task_started",
turn_id: "turn-child",
collaboration_mode_kind: "default",
},
conversationId: "child-provider-thread",
},
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "task.started");
if (firstEvent.value.type !== "task.started") {
return;
}
assert.equal(firstEvent.value.turnId, "turn-parent");
assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent");
assert.equal(firstEvent.value.payload.taskId, "turn-child");
}),
);
});
afterAll(() => {
@@ -109,14 +109,6 @@ function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function toTurnId(value: string | undefined): TurnId | undefined {
return value?.trim() ? TurnId.makeUnsafe(value) : undefined;
}
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
return value?.trim() ? ProviderItemId.makeUnsafe(value) : undefined;
}
function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" {
switch (value) {
case "completed":
@@ -172,7 +164,7 @@ function itemTitle(itemType: CanonicalItemType): string | undefined {
case "plan":
return "Plan";
case "command_execution":
return "Ran command";
return "Command run";
case "file_change":
return "File change";
case "mcp_tool_call":
@@ -423,27 +415,27 @@ function codexEventBase(
): Omit<ProviderRuntimeEvent, "type" | "payload"> {
const payload = asObject(event.payload);
const msg = codexEventMessage(payload);
const turnId = event.turnId ?? toTurnId(asString(msg?.turn_id) ?? asString(msg?.turnId));
const itemId = event.itemId ?? toProviderItemId(asString(msg?.item_id) ?? asString(msg?.itemId));
const turnId = asString(msg?.turn_id) ?? asString(msg?.turnId);
const itemId = asString(msg?.item_id) ?? asString(msg?.itemId);
const requestId = asString(msg?.request_id) ?? asString(msg?.requestId);
const base = runtimeEventBase(event, canonicalThreadId);
const providerRefs = base.providerRefs
? {
...base.providerRefs,
...(turnId ? { providerTurnId: turnId } : {}),
...(itemId ? { providerItemId: itemId } : {}),
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
...(requestId ? { providerRequestId: requestId } : {}),
}
: {
...(turnId ? { providerTurnId: turnId } : {}),
...(itemId ? { providerItemId: itemId } : {}),
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
...(requestId ? { providerRequestId: requestId } : {}),
};
return {
...base,
...(turnId ? { turnId } : {}),
...(itemId ? { itemId: asRuntimeItemId(itemId) } : {}),
...(turnId ? { turnId: TurnId.makeUnsafe(turnId) } : {}),
...(itemId ? { itemId: asRuntimeItemId(ProviderItemId.makeUnsafe(itemId)) } : {}),
...(requestId ? { requestId: asRuntimeRequestId(requestId) } : {}),
...(Object.keys(providerRefs).length > 0 ? { providerRefs } : {}),
};
@@ -1336,7 +1328,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
(attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
attachment,
});
if (!attachmentPath) {
@@ -4,7 +4,6 @@ import { assertFailure } from "@effect/vitest/utils";
import { Effect, Layer, Stream } from "effect";
import { ClaudeAdapter, ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
@@ -28,32 +27,9 @@ const fakeCodexAdapter: CodexAdapterShape = {
streamEvents: Stream.empty,
};
const fakeClaudeAdapter: ClaudeAdapterShape = {
provider: "claudeAgent",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
readThread: vi.fn(),
rollbackThread: vi.fn(),
stopAll: vi.fn(),
streamEvents: Stream.empty,
};
const layer = it.layer(
Layer.mergeAll(
Layer.provide(
ProviderAdapterRegistryLive,
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
),
),
Layer.provide(ProviderAdapterRegistryLive, Layer.succeed(CodexAdapter, fakeCodexAdapter)),
NodeServices.layer,
),
);
@@ -63,12 +39,10 @@ layer("ProviderAdapterRegistryLive", (it) => {
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry;
const codex = yield* registry.getByProvider("codex");
const claude = yield* registry.getByProvider("claudeAgent");
assert.equal(codex, fakeCodexAdapter);
assert.equal(claude, fakeClaudeAdapter);
const providers = yield* registry.listProviders();
assert.deepEqual(providers, ["codex", "claudeAgent"]);
assert.deepEqual(providers, ["codex"]);
}),
);
@@ -1,7 +1,7 @@
/**
* ProviderAdapterRegistryLive - In-memory provider adapter lookup layer.
*
* Binds provider kinds (codex/claudeAgent/...) to concrete adapter services.
* Binds provider kinds (codex/cursor/...) to concrete adapter services.
* This layer only performs adapter lookup; it does not route session-scoped
* calls or own provider lifecycle workflows.
*
@@ -15,7 +15,6 @@ import {
ProviderAdapterRegistry,
type ProviderAdapterRegistryShape,
} from "../Services/ProviderAdapterRegistry.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
export interface ProviderAdapterRegistryLiveOptions {
@@ -24,10 +23,7 @@ export interface ProviderAdapterRegistryLiveOptions {
const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
Effect.gen(function* () {
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeAdapter];
const adapters = options?.adapters !== undefined ? options.adapters : [yield* CodexAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
@@ -5,11 +5,9 @@ import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
checkClaudeProviderStatus,
checkCodexProviderStatus,
hasCustomModelProvider,
parseAuthStatusFromOutput,
parseClaudeAuthStatusFromOutput,
readCodexConfigModelProvider,
} from "./ProviderHealth";
@@ -466,175 +464,4 @@ it.layer(NodeServices.layer)("ProviderHealth", (it) => {
}),
);
});
// ── checkClaudeProviderStatus tests ──────────────────────────
describe("checkClaudeProviderStatus", () => {
it.effect("returns ready when claude is installed and authenticated", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unavailable when claude is missing", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
);
}).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
);
it.effect("returns error when version check fails with non-zero exit code", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version")
return { stdout: "", stderr: "Something went wrong", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when auth status reports not logged in", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Claude is not authenticated. Run `claude auth login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":false}\n',
stderr: "",
code: 1,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when output includes 'not logged in'", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status") return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when auth status command is unsupported", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent authentication status command is unavailable in this version of Claude.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
describe("parseClaudeAuthStatusFromOutput", () => {
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=true is authenticated", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=false is unauthenticated", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"loggedIn":false}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"ok":true}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
});
+11 -207
View File
@@ -26,7 +26,6 @@ import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHe
const DEFAULT_TIMEOUT_MS = 4_000;
const CODEX_PROVIDER = "codex" as const;
const CLAUDE_AGENT_PROVIDER = "claudeAgent" as const;
// ── Pure helpers ────────────────────────────────────────────────────
@@ -45,7 +44,12 @@ function nonEmptyTrimmed(value: string | undefined): string | undefined {
function isCommandMissingCause(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const lower = error.message.toLowerCase();
return lower.includes("enoent") || lower.includes("notfound");
return (
lower.includes("command not found: codex") ||
lower.includes("spawn codex enoent") ||
lower.includes("enoent") ||
lower.includes("notfound")
);
}
function detailFromResult(
@@ -260,27 +264,6 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
const runClaudeCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make("claude", [...args], {
shell: process.platform === "win32",
});
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
// ── Health check ────────────────────────────────────────────────────
export const checkCodexProviderStatus: Effect.Effect<
@@ -407,197 +390,18 @@ export const checkCodexProviderStatus: Effect.Effect<
} satisfies ServerProviderStatus;
});
// ── Claude Agent health check ───────────────────────────────────────
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: ServerProviderStatusState;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
authStatus: "unknown",
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `claude login`") ||
lowerOutput.includes("run claude login")
) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
// `claude auth status` returns JSON with a `loggedIn` boolean.
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
message: detail
? `Could not verify Claude authentication status. ${detail}`
: "Could not verify Claude authentication status.",
};
}
export const checkClaudeProviderStatus: Effect.Effect<
ServerProviderStatus,
never,
ChildProcessSpawner.ChildProcessSpawner
> = Effect.gen(function* () {
const checkedAt = new Date().toISOString();
// Probe 1: `claude --version` — is the CLI reachable?
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
};
}
if (Option.isNone(versionProbe.success)) {
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: "Claude Agent CLI is installed but failed to run. Timed out while running command.",
};
}
const version = versionProbe.success.value;
if (version.code !== 0) {
const detail = detailFromResult(version);
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
};
}
// Probe 2: `claude auth status` — is the user authenticated?
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
};
}
if (Option.isNone(authProbe.success)) {
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message: "Could not verify Claude authentication status. Timed out while running command.",
};
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
return {
provider: CLAUDE_AGENT_PROVIDER,
status: parsed.status,
available: true,
authStatus: parsed.authStatus,
checkedAt,
...(parsed.message ? { message: parsed.message } : {}),
} satisfies ServerProviderStatus;
});
// ── Layer ───────────────────────────────────────────────────────────
export const ProviderHealthLive = Layer.effect(
ProviderHealth,
Effect.gen(function* () {
const statusesFiber = yield* Effect.all([checkCodexProviderStatus, checkClaudeProviderStatus], {
concurrency: "unbounded",
}).pipe(Effect.forkScoped);
const codexStatusFiber = yield* checkCodexProviderStatus.pipe(
Effect.map(Array.of),
Effect.forkScoped,
);
return {
getStatuses: Fiber.join(statusesFiber),
getStatuses: Fiber.join(codexStatusFiber),
} satisfies ProviderHealthShape;
}),
);
@@ -52,7 +52,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -74,7 +74,7 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
status: "ready",
runtimeMode: input.runtimeMode,
threadId: input.threadId,
resumeCursor: input.resumeCursor ?? { opaque: `resume-${String(input.threadId)}` },
resumeCursor: input.resumeCursor ?? { opaque: `cursor-${String(input.threadId)}` },
cwd: input.cwd ?? process.cwd(),
createdAt: now,
updatedAt: now,
@@ -195,21 +195,9 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
};
const updateSession = (
threadId: ThreadId,
update: (session: ProviderSession) => ProviderSession,
): void => {
const existing = sessions.get(threadId);
if (!existing) {
return;
}
sessions.set(threadId, update(existing));
};
return {
adapter,
emit,
updateSession,
startSession,
sendTurn,
interruptTurn,
@@ -229,15 +217,12 @@ const sleep = (ms: number) =>
function makeProviderServiceLayer() {
const codex = makeFakeCodexAdapter();
const claude = makeFakeCodexAdapter("claudeAgent");
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(codex.adapter)
: provider === "claudeAgent"
? Effect.succeed(claude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex", "claudeAgent"]),
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
@@ -262,7 +247,6 @@ function makeProviderServiceLayer() {
return {
codex,
claude,
layer,
};
}
@@ -360,29 +344,16 @@ it.effect(
Layer.provide(firstDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
const updatedResumeCursor = {
threadId: asThreadId("thread-1"),
resume: "resume-session-1",
resumeSessionAt: "assistant-message-1",
turnCount: 1,
};
const startedSession = yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const threadId = asThreadId("thread-1");
const session = yield* provider.startSession(threadId, {
return yield* provider.startSession(threadId, {
provider: "codex",
cwd: "/tmp/project",
runtimeMode: "full-access",
threadId,
});
firstCodex.updateSession(threadId, (existing) => ({
...existing,
status: "ready",
resumeCursor: updatedResumeCursor,
updatedAt: new Date(Date.now() + 1_000).toISOString(),
}));
return session;
}).pipe(Effect.provide(firstProviderLayer));
const persistedAfterStopAll = yield* Effect.gen(function* () {
@@ -392,7 +363,7 @@ it.effect(
assert.equal(Option.isSome(persistedAfterStopAll), true);
if (Option.isSome(persistedAfterStopAll)) {
assert.equal(persistedAfterStopAll.value.status, "stopped");
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, updatedResumeCursor);
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, startedSession.resumeCursor);
}
const secondCodex = makeFakeCodexAdapter();
@@ -435,7 +406,7 @@ it.effect(
};
assert.equal(startPayload.provider, "codex");
assert.equal(startPayload.cwd, "/tmp/project");
assert.deepEqual(startPayload.resumeCursor, updatedResumeCursor);
assert.deepEqual(startPayload.resumeCursor, startedSession.resumeCursor);
assert.equal(startPayload.threadId, startedSession.threadId);
}
assert.equal(secondCodex.rollbackThread.mock.calls.length, 1);
@@ -562,29 +533,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("routes explicit claudeAgent provider session starts to the claude adapter", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(asThreadId("thread-claude"), {
provider: "claudeAgent",
threadId: asThreadId("thread-claude"),
cwd: "/tmp/project-claude",
runtimeMode: "full-access",
});
assert.equal(session.provider, "claudeAgent");
assert.equal(routing.claude.startSession.mock.calls.length, 1);
const startInput = routing.claude.startSession.mock.calls[0]?.[0];
assert.equal(typeof startInput === "object" && startInput !== null, true);
if (startInput && typeof startInput === "object") {
const startPayload = startInput as { provider?: string; cwd?: string };
assert.equal(startPayload.provider, "claudeAgent");
assert.equal(startPayload.cwd, "/tmp/project-claude");
}
}),
);
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -625,57 +573,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("recovers stale claudeAgent sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const initial = yield* provider.startSession(asThreadId("thread-claude-send-turn"), {
provider: "claudeAgent",
threadId: asThreadId("thread-claude-send-turn"),
cwd: "/tmp/project-claude-send-turn",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
runtimeMode: "full-access",
});
yield* routing.claude.stopAll();
routing.claude.startSession.mockClear();
routing.claude.sendTurn.mockClear();
yield* provider.sendTurn({
threadId: initial.threadId,
input: "resume with claude",
attachments: [],
});
assert.equal(routing.claude.startSession.mock.calls.length, 1);
const resumedStartInput = routing.claude.startSession.mock.calls[0]?.[0];
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
if (resumedStartInput && typeof resumedStartInput === "object") {
const startPayload = resumedStartInput as {
provider?: string;
cwd?: string;
modelOptions?: unknown;
resumeCursor?: unknown;
threadId?: string;
};
assert.equal(startPayload.provider, "claudeAgent");
assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn");
assert.deepEqual(startPayload.modelOptions, {
claudeAgent: {
effort: "max",
},
});
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
assert.equal(startPayload.threadId, initial.threadId);
}
assert.equal(routing.claude.sendTurn.mock.calls.length, 1);
}),
);
it.effect("lists no sessions after adapter runtime clears", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -692,7 +589,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
});
yield* routing.codex.stopAll();
yield* routing.claude.stopAll();
const remaining = yield* provider.listSessions();
assert.equal(remaining.length, 0);
@@ -741,96 +637,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}
}),
);
it.effect("reuses persisted resume cursor when startSession is called after a restart", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-start-"));
const dbPath = path.join(tempDir, "orchestration.sqlite");
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
Layer.provide(persistenceLayer),
);
const firstClaude = makeFakeCodexAdapter("claudeAgent");
const firstRegistry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "claudeAgent"
? Effect.succeed(firstClaude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["claudeAgent"]),
};
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
Layer.provide(firstDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
const initial = yield* Effect.gen(function* () {
const provider = yield* ProviderService;
return yield* provider.startSession(asThreadId("thread-claude-start"), {
provider: "claudeAgent",
threadId: asThreadId("thread-claude-start"),
cwd: "/tmp/project-claude-start",
runtimeMode: "full-access",
});
}).pipe(Effect.provide(firstProviderLayer));
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.listSessions();
}).pipe(Effect.provide(firstProviderLayer));
const secondClaude = makeFakeCodexAdapter("claudeAgent");
const secondRegistry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "claudeAgent"
? Effect.succeed(secondClaude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["claudeAgent"]),
};
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
Layer.provide(secondDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
secondClaude.startSession.mockClear();
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.startSession(initial.threadId, {
provider: "claudeAgent",
threadId: initial.threadId,
cwd: "/tmp/project-claude-start",
runtimeMode: "full-access",
});
}).pipe(Effect.provide(secondProviderLayer));
assert.equal(secondClaude.startSession.mock.calls.length, 1);
const resumedStartInput = secondClaude.startSession.mock.calls[0]?.[0];
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
if (resumedStartInput && typeof resumedStartInput === "object") {
const startPayload = resumedStartInput as {
provider?: string;
cwd?: string;
resumeCursor?: unknown;
threadId?: string;
};
assert.equal(startPayload.provider, "claudeAgent");
assert.equal(startPayload.cwd, "/tmp/project-claude-start");
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
assert.equal(startPayload.threadId, initial.threadId);
}
fs.rmSync(tempDir, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)),
);
});
const fanout = makeProviderServiceLayer();
@@ -848,7 +654,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
const consumer = yield* Stream.runForEach(provider.streamEvents, (event) =>
Ref.update(eventsRef, (current) => [...current, event]),
).pipe(Effect.forkChild);
yield* sleep(50);
yield* sleep(20);
const completedEvent: LegacyProviderRuntimeEvent = {
type: "turn.completed",
@@ -861,7 +667,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
};
fanout.codex.emit(completedEvent);
yield* sleep(50);
yield* sleep(20);
const events = yield* Ref.get(eventsRef);
yield* Fiber.interrupt(consumer);
@@ -887,7 +693,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
Stream.runForEach((event) => Ref.update(receivedRef, (current) => [...current, event])),
Effect.forkChild,
);
yield* sleep(50);
yield* sleep(20);
fanout.codex.emit({
type: "tool.started",
@@ -897,7 +703,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
threadId: session.threadId,
turnId: asTurnId("turn-1"),
toolKind: "command",
title: "Ran command",
title: "Command run",
});
fanout.codex.emit({
type: "tool.completed",
@@ -907,7 +713,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
threadId: session.threadId,
turnId: asTurnId("turn-1"),
toolKind: "command",
title: "Ran command",
title: "Command run",
});
fanout.codex.emit({
type: "turn.completed",
@@ -951,7 +757,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
Stream.runForEach(() => Effect.fail("listener crash")),
Effect.forkChild,
);
yield* sleep(50);
yield* sleep(20);
const events: ReadonlyArray<LegacyProviderRuntimeEvent> = [
{
@@ -962,7 +768,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
threadId: session.threadId,
turnId: asTurnId("turn-1"),
toolKind: "command",
title: "Ran command",
title: "Command run",
detail: "echo one",
},
{
@@ -88,38 +88,17 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
function toRuntimePayloadFromSession(
session: ProviderSession,
extra?: {
readonly modelOptions?: unknown;
readonly providerOptions?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
extra?: { readonly providerOptions?: unknown },
): Record<string, unknown> {
return {
cwd: session.cwd ?? null,
model: session.model ?? null,
activeTurnId: session.activeTurnId ?? null,
lastError: session.lastError ?? null,
...(extra?.modelOptions !== undefined ? { modelOptions: extra.modelOptions } : {}),
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
...(extra?.lastRuntimeEventAt !== undefined
? { lastRuntimeEventAt: extra.lastRuntimeEventAt }
: {}),
};
}
function readPersistedModelOptions(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): Record<string, unknown> | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const raw = "modelOptions" in runtimePayload ? runtimePayload.modelOptions : undefined;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
return raw as Record<string, unknown>;
}
function readPersistedProviderOptions(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): Record<string, unknown> | undefined {
@@ -171,12 +150,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const upsertSessionBinding = (
session: ProviderSession,
threadId: ThreadId,
extra?: {
readonly modelOptions?: unknown;
readonly providerOptions?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
extra?: { readonly providerOptions?: unknown },
) =>
directory.upsert({
threadId,
@@ -191,6 +165,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const adapters = yield* Effect.forEach(providers, (provider) =>
registry.getByProvider(provider),
);
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
publishRuntimeEvent(event);
@@ -238,14 +213,12 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelOptions = readPersistedModelOptions(input.binding.runtimePayload);
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelOptions ? { modelOptions: persistedModelOptions } : {}),
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
@@ -308,17 +281,8 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
threadId,
provider: parsed.provider ?? "codex",
};
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
const effectiveResumeCursor =
input.resumeCursor ??
(persistedBinding?.provider === input.provider
? persistedBinding.resumeCursor
: undefined);
const adapter = yield* registry.getByProvider(input.provider);
const session = yield* adapter.startSession({
...input,
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
});
const session = yield* adapter.startSession(input);
if (session.provider !== adapter.provider) {
return yield* toValidationError(
@@ -328,7 +292,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
yield* upsertSessionBinding(session, threadId, {
modelOptions: input.modelOptions,
providerOptions: input.providerOptions,
});
yield* analytics.record("provider.session.started", {
@@ -535,17 +498,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const runStopAll = () =>
Effect.gen(function* () {
const threadIds = yield* directory.listThreadIds();
const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
).pipe(
Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)),
);
yield* Effect.forEach(activeSessions, (session) =>
upsertSessionBinding(session, session.threadId, {
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
}),
).pipe(Effect.asVoid);
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
yield* Effect.forEach(threadIds, (threadId) =>
directory.getProvider(threadId).pipe(
@@ -141,8 +141,8 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
yield* runtimeRepository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
providerName: "cursor",
adapterKey: "cursor",
runtimeMode: "full-access",
status: "running",
lastSeenAt: new Date().toISOString(),
Loaded 100 of 250 files, more files were not shown because too many files have changed in this diff. Show more