Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06b5fc27b5 | ||
|
|
20c056483b | ||
|
|
a542a3b168 | ||
|
|
56d13faa1a | ||
|
|
2a435aef66 | ||
|
|
28afb14004 | ||
|
|
8f3515572d | ||
|
|
529315b4c8 | ||
|
|
0a503d0cde | ||
|
|
d4a7e1ac0b | ||
|
|
be1abc88fd | ||
|
|
384f35084e | ||
|
|
1371ce2cce | ||
|
|
d6408a2949 | ||
|
|
e823f8f14e | ||
|
|
2b08d86696 | ||
|
|
e11fb6e778 | ||
|
|
d415558915 | ||
|
|
843d6d8678 | ||
|
|
754cded24a | ||
|
|
2b6640af1e | ||
|
|
9e29c9d728 | ||
|
|
ef2569196f | ||
|
|
34cef6202b | ||
|
|
25c7003226 | ||
|
|
46e63b3612 | ||
|
|
d373389703 | ||
|
|
bc12421736 | ||
|
|
8f11ea44a7 | ||
|
|
56660b04e9 | ||
|
|
2a237c2001 | ||
|
|
77716b4ccb | ||
|
|
fb18b2de16 | ||
|
|
0de5742b04 | ||
|
|
b500a36a94 | ||
|
|
1310045629 | ||
|
|
579a69eb77 | ||
|
|
9ee8c4f543 | ||
|
|
55560f5116 | ||
|
|
3710ddb611 | ||
|
|
3fce14bbcf | ||
|
|
d430a0624b | ||
|
|
765c1dc9e4 | ||
|
|
e6d9a271fc | ||
|
|
4b811dae61 | ||
|
|
6d76865e74 | ||
|
|
2bb71f41c3 | ||
|
|
cc2ab00074 | ||
|
|
8b8e8b38e5 | ||
|
|
46ea594f02 | ||
|
|
790fda1a97 | ||
|
|
89ffcf42eb | ||
|
|
876bbd715a | ||
|
|
ac0d1f52a0 | ||
|
|
d0ae0adc99 | ||
|
|
995a26660e | ||
|
|
dfd62cfb86 | ||
|
|
64dc07a8e5 | ||
|
|
ae4ae9973c | ||
|
|
36473f7de6 | ||
|
|
a14debc83e | ||
|
|
71a7473a81 | ||
|
|
5c03fb62c4 | ||
|
|
727c0cfcbf | ||
|
|
dcd2e5c34f | ||
|
|
1e276573c2 | ||
|
|
db17ff3323 | ||
|
|
b496ae8395 | ||
|
|
724f54c2c1 | ||
|
|
b6eba3347d | ||
|
|
74c22628b3 | ||
|
|
224acebb57 | ||
|
|
85c174a6ca | ||
|
|
581d242925 | ||
|
|
d9d0216e98 | ||
|
|
c52ad29b31 | ||
|
|
fcbf3f3c22 | ||
|
|
ab0002f99d | ||
|
|
f63cda22fa | ||
|
|
b60a34eba4 | ||
|
|
ed4be2c849 | ||
|
|
5e23e9c7c7 | ||
|
|
c3bfcc36b8 | ||
|
|
a33cc8c758 | ||
|
|
a01d712751 | ||
|
|
774cff9a74 | ||
|
|
e3d46b687c | ||
|
|
8636ea0ec4 | ||
|
|
ff6a66dcab | ||
|
|
2ac735657e | ||
|
|
bbab1fc891 |
No files matched your search
+1
-1
@@ -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 -- --state-dir ~/.t3/another-dev-state`
|
||||
`bun run dev -- --base-dir ~/.t3-2`
|
||||
- `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.
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
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.
|
||||
@@ -0,0 +1,101 @@
|
||||
name: Feature request
|
||||
description: Propose a scoped improvement or new capability.
|
||||
title: "[Feature]: "
|
||||
labels:
|
||||
- enhancement
|
||||
- needs-triage
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use this form for new capabilities or meaningful improvements to existing behavior.
|
||||
This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate.
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: Before submitting
|
||||
options:
|
||||
- label: I searched existing issues and did not find a duplicate.
|
||||
required: true
|
||||
- label: I am describing a concrete problem or use case, not just a vague idea.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area
|
||||
description: Which part of the project would this change affect?
|
||||
options:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
- Not sure
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem or use case
|
||||
description: What are you trying to do? What is hard, slow, or impossible today?
|
||||
placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed solution
|
||||
description: Describe the behavior, API, or UX you want.
|
||||
placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: value
|
||||
attributes:
|
||||
label: Why this matters
|
||||
description: Who benefits, and what outcome does this unlock?
|
||||
placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Smallest useful scope
|
||||
description: What is the narrowest version of this request that would still solve your problem?
|
||||
placeholder: A first pass only needs to support restoring the active session for the current thread.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives considered
|
||||
description: Workarounds, prior art, or other approaches you considered.
|
||||
placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context.
|
||||
|
||||
- type: textarea
|
||||
id: tradeoffs
|
||||
attributes:
|
||||
label: Risks or tradeoffs
|
||||
description: What costs, complexity, or edge cases should be considered?
|
||||
placeholder: This may require careful handling when the underlying provider session has already exited.
|
||||
|
||||
- type: textarea
|
||||
id: references
|
||||
attributes:
|
||||
label: Examples or references
|
||||
description: Links, screenshots, mockups, or comparable tools.
|
||||
|
||||
- type: checkboxes
|
||||
id: contribution
|
||||
attributes:
|
||||
label: Contribution
|
||||
options:
|
||||
- label: I would be open to helping implement this.
|
||||
@@ -19,6 +19,7 @@ github:hwanseoc
|
||||
github:jamesx0416
|
||||
github:jasonLaster
|
||||
github:JoeEverest
|
||||
github:maria-rcks
|
||||
github:nmggithub
|
||||
github:Noojuno
|
||||
github:notkainoa
|
||||
@@ -27,3 +28,4 @@ github:realAhmedRoach
|
||||
github:shiroyasha9
|
||||
github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- 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@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Cache Bun and Turbo
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@v5
|
||||
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@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- 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@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
name: Issue Labels
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- .github/ISSUE_TEMPLATE/**
|
||||
- .github/workflows/issue-labels.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
name: Sync issue labels
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Ensure managed issue labels exist
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const managedLabels = [
|
||||
{
|
||||
name: "bug",
|
||||
color: "d73a4a",
|
||||
description: "Something is broken or behaving incorrectly.",
|
||||
},
|
||||
{
|
||||
name: "enhancement",
|
||||
color: "a2eeef",
|
||||
description: "Requested improvement or new capability.",
|
||||
},
|
||||
{
|
||||
name: "needs-triage",
|
||||
color: "fbca04",
|
||||
description: "Issue needs maintainer review and initial categorization.",
|
||||
},
|
||||
];
|
||||
|
||||
for (const label of managedLabels) {
|
||||
try {
|
||||
const { data: existing } = await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
});
|
||||
|
||||
if (
|
||||
existing.color !== label.color ||
|
||||
(existing.description ?? "") !== label.description
|
||||
) {
|
||||
await github.rest.issues.updateLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
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})`,
|
||||
);
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
targets: ${{ steps.collect.outputs.targets }}
|
||||
steps:
|
||||
- id: collect
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
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@v7
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_NUMBER: ${{ matrix.target.number }}
|
||||
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
|
||||
@@ -111,7 +111,7 @@ jobs:
|
||||
},
|
||||
];
|
||||
|
||||
const managedLabelNames = managedLabels.map((label) => label.name);
|
||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||
|
||||
for (const label of managedLabels) {
|
||||
try {
|
||||
@@ -138,13 +138,19 @@ jobs:
|
||||
throw error;
|
||||
}
|
||||
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
description: label.description,
|
||||
});
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,17 +165,35 @@ jobs:
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
const preservedLabels = currentLabels
|
||||
.map((label) => label.name)
|
||||
.filter((name) => !managedLabelNames.includes(name));
|
||||
for (const label of currentLabels) {
|
||||
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await github.rest.issues.setLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: [...preservedLabels, nextLabelName],
|
||||
});
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
name: label.name,
|
||||
});
|
||||
} catch (removeError) {
|
||||
if (removeError.status !== 404) {
|
||||
throw removeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!currentLabels.some((label) => label.name === nextLabelName)) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: [nextLabelName],
|
||||
});
|
||||
}
|
||||
|
||||
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
@@ -61,7 +61,7 @@ jobs:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
@@ -107,7 +107,7 @@ jobs:
|
||||
arch: x64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
@@ -118,13 +118,16 @@ jobs:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
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:
|
||||
@@ -214,7 +217,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
|
||||
path: release-publish/*
|
||||
@@ -226,7 +229,7 @@ jobs:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
@@ -236,7 +239,7 @@ jobs:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
registry-url: https://registry.npmjs.org
|
||||
@@ -244,6 +247,9 @@ 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
|
||||
|
||||
@@ -256,17 +262,17 @@ jobs:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: desktop-*
|
||||
merge-multiple: true
|
||||
@@ -302,11 +308,31 @@ 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@v4
|
||||
uses: actions/checkout@v6
|
||||
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
|
||||
@@ -314,7 +340,7 @@ jobs:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
@@ -343,8 +369,8 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git config user.name "${{ steps.app_bot.outputs.name }}"
|
||||
git config user.email "${{ steps.app_bot.outputs.email }}"
|
||||
|
||||
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"
|
||||
|
||||
@@ -13,6 +13,10 @@ build/
|
||||
.logs/
|
||||
release/
|
||||
.t3
|
||||
.idea/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
@@ -0,0 +1,441 @@
|
||||
# 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`.
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
|
||||
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
|
||||
|
||||
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 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.
|
||||
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.
|
||||
|
||||
## Package Roles
|
||||
|
||||
|
||||
+1
-1
@@ -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.
|
||||
PRs are automatically labeled with a `vouch:*` trust status and a `size:*` diff size based on changed lines.
|
||||
|
||||
If you are an external contributor, expect `vouch:unvouched` until we explicitly add you to [.github/VOUCHED.td](.github/VOUCHED.td).
|
||||
|
||||
|
||||
+1
-1
@@ -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 local chat thread for the active project (no worktree context)
|
||||
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
|
||||
## How to use
|
||||
|
||||
|
||||
@@ -6,21 +6,24 @@ Use this when you want to open T3 Code from another device (phone, tablet, anoth
|
||||
|
||||
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
|
||||
|
||||
| CLI flag | Env var | Notes |
|
||||
| ----------------------- | --------------------- | ---------------------------------- |
|
||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||
| `--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. |
|
||||
| CLI flag | Env var | Notes |
|
||||
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
|
||||
| `--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. |
|
||||
| `--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. Use this for standard CLI and remote-server flows. |
|
||||
| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
|
||||
|
||||
> TIP: Use the `--help` flag to see all available options and their descriptions.
|
||||
|
||||
## Security First
|
||||
|
||||
- Always set `--auth-token` before exposing the server outside localhost.
|
||||
- When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <fd>`.
|
||||
With `--bootstrap-fd <fd>`, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments.
|
||||
- Treat the token like a password.
|
||||
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.9",
|
||||
"version": "0.0.14",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -80,12 +80,13 @@ function startApp() {
|
||||
}
|
||||
});
|
||||
|
||||
app.once("exit", () => {
|
||||
app.once("exit", (code, signal) => {
|
||||
if (currentApp === app) {
|
||||
currentApp = null;
|
||||
}
|
||||
|
||||
if (!shuttingDown && !expectedExits.has(app)) {
|
||||
const exitedAbnormally = signal !== null || code !== 0;
|
||||
if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
|
||||
scheduleRestart();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
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.
|
||||
}
|
||||
}
|
||||
+65
-22
@@ -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 { fixPath } from "./fixPath";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
@@ -44,7 +44,7 @@ import {
|
||||
} from "./updateMachine";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
|
||||
fixPath();
|
||||
syncShellEnvironment();
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
@@ -56,8 +56,9 @@ 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 STATE_DIR =
|
||||
process.env.T3CODE_STATE_DIR?.trim() || Path.join(OS.homedir(), ".t3", "userdata");
|
||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
|
||||
const STATE_DIR = Path.join(BASE_DIR, "userdata");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
@@ -535,7 +536,28 @@ function handleCheckForUpdatesMenuClick(): void {
|
||||
if (!BrowserWindow.getAllWindows().length) {
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
void checkForUpdates("menu");
|
||||
void checkForUpdatesFromMenu();
|
||||
}
|
||||
|
||||
async function checkForUpdatesFromMenu(): Promise<void> {
|
||||
await checkForUpdates("menu");
|
||||
|
||||
if (updateState.status === "up-to-date") {
|
||||
void dialog.showMessageBox({
|
||||
type: "info",
|
||||
title: "You're up to date!",
|
||||
message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
|
||||
buttons: ["OK"],
|
||||
});
|
||||
} else if (updateState.status === "error") {
|
||||
void dialog.showMessageBox({
|
||||
type: "warning",
|
||||
title: "Update check failed",
|
||||
message: "Could not check for updates.",
|
||||
detail: updateState.message ?? "An unknown error occurred. Please try again later.",
|
||||
buttons: ["OK"],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function configureApplicationMenu(): void {
|
||||
@@ -619,6 +641,7 @@ 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),
|
||||
];
|
||||
@@ -896,17 +919,6 @@ function configureAutoUpdater(): void {
|
||||
}, AUTO_UPDATE_POLL_INTERVAL_MS);
|
||||
updatePollTimer.unref();
|
||||
}
|
||||
function backendEnv(): NodeJS.ProcessEnv {
|
||||
return {
|
||||
...process.env,
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "1",
|
||||
T3CODE_PORT: String(backendPort),
|
||||
T3CODE_STATE_DIR: STATE_DIR,
|
||||
T3CODE_AUTH_TOKEN: backendAuthToken,
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleBackendRestart(reason: string): void {
|
||||
if (isQuitting || restartTimer) return;
|
||||
|
||||
@@ -930,16 +942,42 @@ function startBackend(): void {
|
||||
}
|
||||
|
||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry], {
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
|
||||
cwd: resolveBackendCwd(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
env: {
|
||||
...backendEnv(),
|
||||
...process.env,
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
// Clear env vars that the bootstrap pipe now delivers, so stray
|
||||
// values inherited from the user's shell cannot override them.
|
||||
T3CODE_MODE: undefined,
|
||||
T3CODE_PORT: undefined,
|
||||
T3CODE_HOME: undefined,
|
||||
T3CODE_NO_BROWSER: undefined,
|
||||
T3CODE_AUTH_TOKEN: undefined,
|
||||
},
|
||||
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
|
||||
stdio: captureBackendLogs
|
||||
? ["ignore", "pipe", "pipe", "pipe"]
|
||||
: ["ignore", "inherit", "inherit", "pipe"],
|
||||
});
|
||||
const bootstrapStream = child.stdio[3];
|
||||
if (bootstrapStream && "write" in bootstrapStream) {
|
||||
bootstrapStream.write(
|
||||
`${JSON.stringify({
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: backendPort,
|
||||
t3Home: BASE_DIR,
|
||||
authToken: backendAuthToken,
|
||||
})}\n`,
|
||||
);
|
||||
bootstrapStream.end();
|
||||
} else {
|
||||
child.kill("SIGTERM");
|
||||
scheduleBackendRestart("missing desktop bootstrap pipe");
|
||||
return;
|
||||
}
|
||||
backendProcess = child;
|
||||
let backendSessionClosed = false;
|
||||
const closeBackendSession = (details: string) => {
|
||||
@@ -1050,6 +1088,11 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
}
|
||||
|
||||
function registerIpcHandlers(): void {
|
||||
ipcMain.removeAllListeners(GET_WS_URL_CHANNEL);
|
||||
ipcMain.on(GET_WS_URL_CHANNEL, (event) => {
|
||||
event.returnValue = backendWsUrl;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
|
||||
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||
@@ -1298,9 +1341,9 @@ 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)}`;
|
||||
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
|
||||
writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
|
||||
const baseUrl = `ws://127.0.0.1:${backendPort}`;
|
||||
backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);
|
||||
|
||||
registerIpcHandlers();
|
||||
writeDesktopLogHeader("bootstrap ipc handlers registered");
|
||||
|
||||
@@ -11,10 +11,13 @@ 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 wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => wsUrl,
|
||||
getWsUrl: () => {
|
||||
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
|
||||
return typeof result === "string" ? result : null;
|
||||
},
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,10 @@
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"astro": "^5.7.13"
|
||||
"astro": "^6.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.4",
|
||||
"@astrojs/check": "^0.9.7",
|
||||
"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,6 +24,7 @@ import {
|
||||
|
||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
@@ -65,7 +66,7 @@ import {
|
||||
makeTestProviderAdapterHarness,
|
||||
type TestProviderAdapterHarness,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import { ServerConfig } from "../src/config.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -75,14 +76,16 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
});
|
||||
}
|
||||
|
||||
function initializeGitWorkspace(cwd: string) {
|
||||
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
|
||||
runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const { join } = yield* Path.Path;
|
||||
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
|
||||
runGit(cwd, ["add", "."]);
|
||||
runGit(cwd, ["commit", "-m", "Initial"]);
|
||||
}
|
||||
});
|
||||
|
||||
export function gitRefExists(cwd: string, ref: string): boolean {
|
||||
try {
|
||||
@@ -205,7 +208,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: "codex";
|
||||
readonly provider?: ProviderKind;
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
@@ -213,7 +216,9 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
options?: MakeOrchestrationIntegrationHarnessOptions,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const provider = options?.provider ?? "codex";
|
||||
const useRealCodex = options?.realCodex === true;
|
||||
const adapterHarness = useRealCodex
|
||||
@@ -230,13 +235,16 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||
} as typeof ProviderAdapterRegistry.Service)
|
||||
: null;
|
||||
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
||||
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-orchestration-integration-",
|
||||
});
|
||||
const workspaceDir = path.join(rootDir, "workspace");
|
||||
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 { 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 persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
@@ -261,7 +269,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(makeCodexAdapterLive()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
@@ -277,12 +285,13 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
CheckpointStoreLive,
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusLive,
|
||||
);
|
||||
@@ -311,7 +320,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -351,7 +360,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
|
||||
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkIn(scope));
|
||||
yield* sleep(10);
|
||||
yield* Effect.sleep(10);
|
||||
|
||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||
threadId,
|
||||
@@ -468,13 +477,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
}
|
||||
});
|
||||
|
||||
yield* shutdown.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* shutdown;
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
ProviderTurnStartResult,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
@@ -35,7 +36,7 @@ export interface TestTurnResponse {
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex";
|
||||
readonly provider: ProviderKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -177,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: "codex";
|
||||
readonly provider: ProviderKind;
|
||||
readonly queueTurnResponse: (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
@@ -197,7 +198,7 @@ export interface TestProviderAdapterHarness {
|
||||
}
|
||||
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: "codex";
|
||||
readonly provider?: ProviderKind;
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
@@ -205,7 +206,7 @@ function nowIso(): string {
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: "codex",
|
||||
provider: ProviderKind,
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
@@ -215,7 +216,7 @@ function sessionNotFound(
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: "codex",
|
||||
provider: ProviderKind,
|
||||
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: "Command run",
|
||||
title: "Ran command",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
@@ -85,7 +85,7 @@ export const codexTurnToolFixture = [
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Command run",
|
||||
title: "Ran command",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -5,10 +5,13 @@ import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderKind,
|
||||
ThreadId,
|
||||
ModelSelection,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Option, Schema } from "effect";
|
||||
@@ -25,6 +28,7 @@ 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);
|
||||
@@ -36,7 +40,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 = "codex";
|
||||
type IntegrationProvider = ProviderKind;
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
@@ -49,8 +53,6 @@ class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWai
|
||||
},
|
||||
) {}
|
||||
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
|
||||
function waitForSync<A>(
|
||||
read: () => A,
|
||||
predicate: (value: A) => boolean,
|
||||
@@ -68,7 +70,7 @@ function waitForSync<A>(
|
||||
if (Date.now() >= deadline) {
|
||||
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
|
||||
}
|
||||
yield* sleep(10);
|
||||
yield* Effect.sleep(10);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -89,7 +91,7 @@ function withHarness<A, E>(
|
||||
makeOrchestrationIntegrationHarness({ provider }),
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
);
|
||||
).pipe(Effect.provide(NodeServices.layer));
|
||||
}
|
||||
|
||||
function withRealCodexHarness<A, E>(
|
||||
@@ -99,12 +101,14 @@ 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",
|
||||
@@ -112,7 +116,10 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider,
|
||||
model: defaultModel,
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -122,7 +129,10 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider,
|
||||
model: defaultModel,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -136,7 +146,7 @@ const startTurn = (input: {
|
||||
readonly commandId: string;
|
||||
readonly messageId: string;
|
||||
readonly text: string;
|
||||
readonly provider?: IntegrationProvider;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
}) =>
|
||||
input.harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -148,7 +158,11 @@ const startTurn = (input: {
|
||||
text: input.text,
|
||||
attachments: [],
|
||||
},
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
...(input.modelSelection !== undefined
|
||||
? {
|
||||
modelSelection: input.modelSelection,
|
||||
}
|
||||
: {}),
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: nowIso(),
|
||||
@@ -251,7 +265,10 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel: "gpt-5.3-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -261,7 +278,10 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -882,3 +902,435 @@ 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",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
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",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
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",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
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",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
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",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
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",
|
||||
),
|
||||
);
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.9",
|
||||
"version": "0.0.14",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
@@ -22,6 +23,7 @@
|
||||
"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",
|
||||
@@ -44,6 +46,6 @@
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.13 || ^23.4 || >=24.10"
|
||||
"node": "^22.16 || ^23.11 || >=24.10"
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ export function normalizeAttachmentRelativePath(rawRelativePath: string): string
|
||||
}
|
||||
|
||||
export function resolveAttachmentRelativePath(input: {
|
||||
readonly stateDir: string;
|
||||
readonly attachmentsDir: 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(path.join(input.stateDir, "attachments"));
|
||||
const attachmentsRoot = path.resolve(input.attachmentsDir);
|
||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||
return null;
|
||||
|
||||
@@ -44,34 +44,32 @@ describe("attachmentStore", () => {
|
||||
});
|
||||
|
||||
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||
const attachmentsDir = 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({
|
||||
stateDir,
|
||||
attachmentsDir,
|
||||
attachmentId,
|
||||
});
|
||||
expect(resolved).toBe(pngPath);
|
||||
} finally {
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns null when no attachment file exists for the id", () => {
|
||||
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||
try {
|
||||
const resolved = resolveAttachmentPathById({
|
||||
stateDir,
|
||||
attachmentsDir,
|
||||
attachmentId: "thread-1-missing",
|
||||
});
|
||||
expect(resolved).toBeNull();
|
||||
} finally {
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -66,17 +66,17 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
|
||||
}
|
||||
|
||||
export function resolveAttachmentPath(input: {
|
||||
readonly stateDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly attachment: ChatAttachment;
|
||||
}): string | null {
|
||||
return resolveAttachmentRelativePath({
|
||||
stateDir: input.stateDir,
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
relativePath: attachmentRelativePath(input.attachment),
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveAttachmentPathById(input: {
|
||||
readonly stateDir: string;
|
||||
readonly attachmentsDir: 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({
|
||||
stateDir: input.stateDir,
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
relativePath: `${normalizedId}${extension}`,
|
||||
});
|
||||
if (maybePath && existsSync(maybePath)) {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import * as NFS from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { FileSystem, Schema } from "effect";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||
|
||||
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
|
||||
|
||||
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
it.effect("reads a bootstrap envelope from a provided fd", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
filePath,
|
||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||
mode: "desktop",
|
||||
})}\n`,
|
||||
);
|
||||
|
||||
const fd = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => NFS.openSync(filePath, "r")),
|
||||
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
||||
);
|
||||
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
assertSome(payload, {
|
||||
mode: "desktop",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when the fd is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = NFS.openSync("/dev/null", "r");
|
||||
NFS.closeSync(fd);
|
||||
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
assertNone(payload);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when the bootstrap read times out before any value arrives", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bootstrap-" });
|
||||
const fifoPath = path.join(tempDir, "bootstrap.pipe");
|
||||
|
||||
yield* Effect.sync(() => execFileSync("mkfifo", [fifoPath]));
|
||||
|
||||
const _writer = yield* Effect.acquireRelease(
|
||||
Effect.sync(() =>
|
||||
spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
|
||||
stdio: ["ignore", "ignore", "ignore"],
|
||||
}),
|
||||
),
|
||||
(writer) =>
|
||||
Effect.sync(() => {
|
||||
writer.kill("SIGKILL");
|
||||
}),
|
||||
);
|
||||
|
||||
const fd = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => NFS.openSync(fifoPath, "r")),
|
||||
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
||||
);
|
||||
|
||||
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
|
||||
timeoutMs: 100,
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.millis(100));
|
||||
|
||||
const payload = yield* Fiber.join(fiber);
|
||||
assertNone(payload);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import * as NFS from "node:fs";
|
||||
import * as readline from "node:readline";
|
||||
|
||||
import { Data, Effect, Option, Result, Schema } from "effect";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
|
||||
class BootstrapError extends Data.TaggedError("BootstrapError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <
|
||||
S extends Schema.Codec<unknown, unknown, never, never>,
|
||||
>(
|
||||
schema: S,
|
||||
fd: number,
|
||||
options?: {
|
||||
timeoutMs?: number;
|
||||
},
|
||||
): Effect.fn.Return<Option.Option<Schema.Schema.Type<S>>, BootstrapError> {
|
||||
const fdReady = yield* Effect.try({
|
||||
try: () => NFS.fstatSync(fd),
|
||||
catch: (error) =>
|
||||
new BootstrapError({
|
||||
message: "Failed to stat bootstrap fd.",
|
||||
cause: error,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchIf(
|
||||
(error) => isUnavailableBootstrapFdError(error.cause),
|
||||
() => Effect.succeed(false),
|
||||
),
|
||||
);
|
||||
if (!fdReady) return Option.none();
|
||||
|
||||
const streamFd = yield* Effect.try({
|
||||
try: () => {
|
||||
const fdPath = resolveFdPath(fd);
|
||||
if (fdPath === undefined) return fd;
|
||||
return NFS.openSync(fdPath, "r");
|
||||
},
|
||||
catch: (error) =>
|
||||
new BootstrapError({
|
||||
message: "Failed to duplicate bootstrap fd.",
|
||||
cause: error,
|
||||
}),
|
||||
});
|
||||
|
||||
const stream = NFS.createReadStream("", {
|
||||
fd: streamFd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
|
||||
const timeoutMs = options?.timeoutMs ?? 1000;
|
||||
|
||||
return yield* Effect.callback<Option.Option<Schema.Schema.Type<S>>, BootstrapError>((resume) => {
|
||||
const input = readline.createInterface({
|
||||
input: stream,
|
||||
crlfDelay: Infinity,
|
||||
});
|
||||
|
||||
const cleanup = () => {
|
||||
stream.removeListener("error", handleError);
|
||||
input.removeListener("line", handleLine);
|
||||
input.removeListener("close", handleClose);
|
||||
input.close();
|
||||
};
|
||||
|
||||
const handleError = (error: Error) => {
|
||||
if (isUnavailableBootstrapFdError(error)) {
|
||||
resume(Effect.succeed(Option.none<Schema.Schema.Type<S>>()));
|
||||
return;
|
||||
}
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BootstrapError({
|
||||
message: "Failed to read bootstrap envelope.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const handleLine = (line: string) => {
|
||||
const parsed = decodeJsonResult(schema)(line);
|
||||
if (Result.isSuccess(parsed)) {
|
||||
resume(Effect.succeed(Option.some(parsed.success as Schema.Schema.Type<S>)));
|
||||
return;
|
||||
}
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BootstrapError({
|
||||
message: "Failed to decode bootstrap envelope.",
|
||||
cause: parsed.failure,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
resume(Effect.succeed(Option.none<Schema.Schema.Type<S>>()));
|
||||
};
|
||||
|
||||
stream.once("error", handleError);
|
||||
input.once("line", handleLine);
|
||||
input.once("close", handleClose);
|
||||
|
||||
return Effect.sync(cleanup);
|
||||
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
|
||||
});
|
||||
|
||||
function isUnavailableBootstrapFdError(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof Error && "code" in error && (error.code === "EBADF" || error.code === "ENOENT")
|
||||
);
|
||||
}
|
||||
|
||||
function resolveFdPath(fd: number): string | undefined {
|
||||
if (process.platform === "linux") {
|
||||
return `/proc/self/fd/${fd}`;
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
return undefined;
|
||||
}
|
||||
return `/dev/fd/${fd}`;
|
||||
}
|
||||
@@ -31,7 +31,7 @@ function makeSnapshot(input: {
|
||||
id: input.projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
@@ -43,7 +43,10 @@ function makeSnapshot(input: {
|
||||
id: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
|
||||
@@ -15,15 +15,14 @@ import { Effect, Layer, FileSystem, Path } from "effect";
|
||||
|
||||
import { CheckpointInvariantError } from "../Errors.ts";
|
||||
import { GitCommandError } from "../../git/Errors.ts";
|
||||
import { GitServiceLive } from "../../git/Layers/GitService.ts";
|
||||
import { GitService } from "../../git/Services/GitService.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.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* GitService;
|
||||
const git = yield* GitCore;
|
||||
|
||||
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||
git
|
||||
@@ -277,6 +276,4 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
} satisfies CheckpointStoreShape;
|
||||
});
|
||||
|
||||
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
|
||||
Layer.provideMerge(GitServiceLive),
|
||||
);
|
||||
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);
|
||||
@@ -37,6 +37,7 @@ function createSendTurnHarness() {
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
},
|
||||
collabReceiverTurns: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -75,6 +76,7 @@ function createThreadControlHarness() {
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
collabReceiverTurns: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -117,6 +119,7 @@ function createPendingUserInputHarness() {
|
||||
},
|
||||
],
|
||||
]),
|
||||
collabReceiverTurns: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -135,6 +138,43 @@ 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();
|
||||
@@ -721,6 +761,7 @@ describe("respondToUserInput", () => {
|
||||
},
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
collabReceiverTurns: new Map(),
|
||||
};
|
||||
type ApprovalRequestContext = {
|
||||
session: typeof context.session;
|
||||
@@ -748,6 +789,152 @@ 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-"));
|
||||
|
||||
@@ -70,6 +70,7 @@ interface CodexSessionContext {
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
|
||||
collabReceiverTurns: Map<string, TurnId>;
|
||||
nextRequestId: number;
|
||||
stopping: boolean;
|
||||
}
|
||||
@@ -571,6 +572,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
collabReceiverTurns: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
@@ -732,6 +734,7 @@ 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 }
|
||||
@@ -1121,7 +1124,16 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
context: CodexSessionContext,
|
||||
notification: JsonRpcNotification,
|
||||
): void {
|
||||
const route = this.readRouteFields(notification.params);
|
||||
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 textDelta =
|
||||
notification.method === "item/agentMessage/delta"
|
||||
? this.readString(notification.params, "delta")
|
||||
@@ -1134,8 +1146,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
threadId: context.session.threadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: notification.method,
|
||||
turnId: route.turnId,
|
||||
itemId: route.itemId,
|
||||
...((childParentTurnId ?? rawRoute.turnId)
|
||||
? { turnId: childParentTurnId ?? rawRoute.turnId }
|
||||
: {}),
|
||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||
textDelta,
|
||||
payload: notification.params,
|
||||
});
|
||||
@@ -1151,6 +1165,9 @@ 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",
|
||||
@@ -1160,6 +1177,10 @@ 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");
|
||||
@@ -1172,6 +1193,9 @@ 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");
|
||||
|
||||
@@ -1183,7 +1207,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
|
||||
const route = this.readRouteFields(request.params);
|
||||
const rawRoute = this.readRouteFields(request.params);
|
||||
const childParentTurnId = this.readChildParentTurnId(context, request.params);
|
||||
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
|
||||
const requestKind = this.requestKindForMethod(request.method);
|
||||
let requestId: ApprovalRequestId | undefined;
|
||||
if (requestKind) {
|
||||
@@ -1199,8 +1225,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
: "item/fileChange/requestApproval",
|
||||
requestKind,
|
||||
threadId: context.session.threadId,
|
||||
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||
...(route.itemId ? { itemId: route.itemId } : {}),
|
||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||
};
|
||||
context.pendingApprovals.set(requestId, pendingRequest);
|
||||
}
|
||||
@@ -1211,8 +1237,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
threadId: context.session.threadId,
|
||||
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||
...(route.itemId ? { itemId: route.itemId } : {}),
|
||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1223,8 +1249,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
threadId: context.session.threadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: request.method,
|
||||
turnId: route.turnId,
|
||||
itemId: route.itemId,
|
||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||
requestId,
|
||||
requestKind,
|
||||
payload: request.params,
|
||||
@@ -1451,6 +1477,64 @@ 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
|
||||
|
||||
@@ -12,16 +12,32 @@ 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 {
|
||||
export interface ServerConfigShape extends ServerDerivedPaths {
|
||||
readonly mode: RuntimeMode;
|
||||
readonly port: number;
|
||||
readonly host: string | undefined;
|
||||
readonly cwd: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly stateDir: string;
|
||||
readonly baseDir: string;
|
||||
readonly staticDir: string | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly noBrowser: boolean;
|
||||
@@ -30,31 +46,68 @@ export interface ServerConfigShape {
|
||||
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, statedir: string) =>
|
||||
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
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 });
|
||||
|
||||
return {
|
||||
cwd,
|
||||
stateDir: statedir,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
mode: "web",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
authToken: undefined,
|
||||
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devUrl,
|
||||
noBrowser: false,
|
||||
};
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,11 +8,14 @@ import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
|
||||
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
|
||||
CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-codex-text-generation-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
function makeFakeCodexBinary(dir: string) {
|
||||
return Effect.gen(function* () {
|
||||
@@ -186,8 +189,6 @@ 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(
|
||||
@@ -325,9 +326,10 @@ 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(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
@@ -363,9 +365,10 @@ 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(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
@@ -410,8 +413,9 @@ 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(process.cwd(), "attachments", `${missingAttachmentId}.png`);
|
||||
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
|
||||
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
@@ -3,6 +3,7 @@ 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";
|
||||
@@ -17,7 +18,6 @@ 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({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||
@@ -187,6 +187,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
outputSchemaJson,
|
||||
imagePaths = [],
|
||||
cleanupPaths = [],
|
||||
model,
|
||||
}: {
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
cwd: string;
|
||||
@@ -194,6 +195,7 @@ 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(
|
||||
@@ -212,7 +214,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
model ?? DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
@@ -353,6 +355,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
@@ -398,6 +401,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
title: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
@@ -449,6 +453,7 @@ 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
+1494
-1089
File diff suppressed because it is too large.
Load diff
@@ -6,6 +6,7 @@ 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";
|
||||
@@ -15,10 +16,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[];
|
||||
@@ -106,11 +107,11 @@ function runGit(
|
||||
): Effect.Effect<
|
||||
{ readonly code: number; readonly stdout: string; readonly stderr: string },
|
||||
GitCommandError,
|
||||
GitService
|
||||
GitCore
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const gitService = yield* GitService;
|
||||
return yield* gitService.execute({
|
||||
const gitCore = yield* GitCore;
|
||||
return yield* gitCore.execute({
|
||||
operation: "GitManager.test.runGit",
|
||||
cwd,
|
||||
args,
|
||||
@@ -124,7 +125,7 @@ function initRepo(
|
||||
): Effect.Effect<
|
||||
void,
|
||||
PlatformError.PlatformError | GitCommandError,
|
||||
FileSystem.FileSystem | Scope.Scope | GitService
|
||||
FileSystem.FileSystem | Scope.Scope | GitCore
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
@@ -140,7 +141,7 @@ function initRepo(
|
||||
function createBareRemote(): Effect.Effect<
|
||||
string,
|
||||
PlatformError.PlatformError | GitCommandError,
|
||||
FileSystem.FileSystem | Scope.Scope | GitService
|
||||
FileSystem.FileSystem | Scope.Scope | GitCore
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const remoteDir = yield* makeTempDir("t3code-git-remote-");
|
||||
@@ -449,11 +450,20 @@ 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);
|
||||
return manager.runStackedAction(
|
||||
{
|
||||
...input,
|
||||
actionId: input.actionId ?? "test-action-id",
|
||||
},
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) {
|
||||
@@ -473,18 +483,20 @@ 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,
|
||||
NodeServices.layer,
|
||||
);
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
return makeGitManager.pipe(
|
||||
Effect.provide(managerLayer),
|
||||
@@ -492,7 +504,10 @@ function makeManager(input?: {
|
||||
);
|
||||
}
|
||||
|
||||
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
||||
const GitManagerTestLayer = GitCoreLive.pipe(
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
it.effect("status includes PR metadata when branch already has an open PR", () =>
|
||||
@@ -767,6 +782,31 @@ 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-");
|
||||
@@ -1910,4 +1950,117 @@ 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",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2,6 +2,7 @@ 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,
|
||||
@@ -9,11 +10,21 @@ import {
|
||||
} from "@t3tools/shared/git";
|
||||
|
||||
import { GitManagerError } from "../Errors.ts";
|
||||
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
|
||||
import {
|
||||
GitManager,
|
||||
type GitActionProgressReporter,
|
||||
type GitManagerShape,
|
||||
type GitRunStackedActionOptions,
|
||||
} 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;
|
||||
@@ -200,6 +211,17 @@ 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;
|
||||
@@ -337,6 +359,29 @@ 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,
|
||||
@@ -638,9 +683,11 @@ 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);
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
|
||||
if (!context) {
|
||||
return null;
|
||||
}
|
||||
@@ -664,6 +711,7 @@ 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)));
|
||||
|
||||
@@ -677,23 +725,111 @@ 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 suggestion =
|
||||
preResolvedSuggestion ??
|
||||
(yield* resolveCommitAndBranchSuggestion({
|
||||
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({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
}));
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(model ? { model } : {}),
|
||||
});
|
||||
}
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
}
|
||||
|
||||
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
|
||||
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;
|
||||
}
|
||||
return {
|
||||
status: "created" as const,
|
||||
commitSha,
|
||||
@@ -701,7 +837,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const runPrStep = (cwd: string, fallbackBranch: string | null) =>
|
||||
const runPrStep = (cwd: string, fallbackBranch: string | null, model?: string) =>
|
||||
Effect.gen(function* () {
|
||||
const details = yield* gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
@@ -745,6 +881,7 @@ 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`);
|
||||
@@ -964,13 +1101,21 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
||||
const runFeatureBranchStep = (
|
||||
cwd: string,
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
filePaths?: readonly string[],
|
||||
model?: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion = yield* resolveCommitAndBranchSuggestion({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
includeBranch: true,
|
||||
...(model ? { model } : {}),
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* gitManagerError(
|
||||
@@ -994,62 +1139,135 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
|
||||
function* (input) {
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
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;
|
||||
|
||||
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 runAction = Effect.gen(function* () {
|
||||
yield* progress.emit({
|
||||
kind: "action_started",
|
||||
phases,
|
||||
});
|
||||
|
||||
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
|
||||
if (input.featureBranch) {
|
||||
const result = yield* runFeatureBranchStep(
|
||||
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,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
input.action,
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
options?.progressReporter,
|
||||
progress.actionId,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
|
||||
} else {
|
||||
branchStep = { status: "skipped_not_requested" as const };
|
||||
}
|
||||
|
||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||
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 };
|
||||
|
||||
const commit = yield* runCommitStep(
|
||||
input.cwd,
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
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 };
|
||||
|
||||
const result = {
|
||||
action: input.action,
|
||||
branch: branchStep,
|
||||
commit,
|
||||
push,
|
||||
pr,
|
||||
};
|
||||
yield* progress.emit({
|
||||
kind: "action_finished",
|
||||
result,
|
||||
});
|
||||
return result;
|
||||
});
|
||||
|
||||
return yield* runAction.pipe(
|
||||
Effect.catch((error) =>
|
||||
progress
|
||||
.emit({
|
||||
kind: "action_failed",
|
||||
phase: currentPhase,
|
||||
message: error.message,
|
||||
})
|
||||
.pipe(Effect.flatMap(() => Effect.fail(error))),
|
||||
),
|
||||
);
|
||||
|
||||
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,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
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__");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,144 +0,0 @@
|
||||
/**
|
||||
* 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);
|
||||
@@ -24,6 +24,23 @@ 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;
|
||||
}
|
||||
@@ -33,6 +50,35 @@ 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;
|
||||
@@ -86,6 +132,11 @@ 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.
|
||||
*/
|
||||
@@ -101,6 +152,7 @@ export interface GitCoreShape {
|
||||
*/
|
||||
readonly prepareCommitContext: (
|
||||
cwd: string,
|
||||
filePaths?: readonly string[],
|
||||
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
@@ -110,6 +162,7 @@ export interface GitCoreShape {
|
||||
cwd: string,
|
||||
subject: string,
|
||||
body: string,
|
||||
options?: GitCommitOptions,
|
||||
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* @module GitManager
|
||||
*/
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitPreparePullRequestThreadResult,
|
||||
GitPullRequestRefInput,
|
||||
@@ -20,6 +21,15 @@ 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.
|
||||
*/
|
||||
@@ -51,6 +61,7 @@ export interface GitManagerShape {
|
||||
*/
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
/**
|
||||
* 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,6 +19,8 @@ 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 {
|
||||
@@ -35,6 +37,8 @@ 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 {
|
||||
@@ -46,6 +50,8 @@ 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 {
|
||||
|
||||
@@ -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, type ServerConfigShape } from "./config";
|
||||
import { ServerConfig } from "./config";
|
||||
|
||||
import {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
@@ -17,21 +17,17 @@ import {
|
||||
} from "./keybindings";
|
||||
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const makeKeybindingsLayer = () =>
|
||||
KeybindingsLive.pipe(
|
||||
const makeKeybindingsLayer = () => {
|
||||
return KeybindingsLive.pipe(
|
||||
Layer.provideMerge(
|
||||
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;
|
||||
Layer.fresh(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-keybindings-test-",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
|
||||
effect.pipe(
|
||||
@@ -42,7 +38,9 @@ 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);
|
||||
});
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { assert, it, vi } from "@effect/vitest";
|
||||
import type { OrchestrationReadModel } from "@t3tools/contracts";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Command from "effect/unstable/cli/Command";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
@@ -60,13 +61,11 @@ 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,
|
||||
},
|
||||
}),
|
||||
@@ -93,8 +92,8 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
"4010",
|
||||
"--host",
|
||||
"0.0.0.0",
|
||||
"--state-dir",
|
||||
"/tmp/t3-cli-state",
|
||||
"--home-dir",
|
||||
"/tmp/t3-cli-home",
|
||||
"--dev-url",
|
||||
"http://127.0.0.1:5173",
|
||||
"--no-browser",
|
||||
@@ -106,7 +105,8 @@ 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?.stateDir, "/tmp/t3-cli-state");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-cli-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "auth-secret");
|
||||
@@ -131,7 +131,7 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_PORT: "4999",
|
||||
T3CODE_HOST: "100.88.10.4",
|
||||
T3CODE_STATE_DIR: "/tmp/t3-env-state",
|
||||
T3CODE_HOME: "/tmp/t3-env-home",
|
||||
VITE_DEV_SERVER_URL: "http://localhost:5173",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTH_TOKEN: "env-token",
|
||||
@@ -141,7 +141,8 @@ 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?.stateDir, "/tmp/t3-env-state");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "env-token");
|
||||
@@ -151,6 +152,99 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`);
|
||||
const { fd } = yield* fs.open(filePath, { flag: "r" });
|
||||
return fd;
|
||||
});
|
||||
|
||||
it.effect("recognizes bootstrap fd from environment config", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({ authToken: "bootstrap-token" });
|
||||
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_AUTH_TOKEN: "env-token",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.authToken, "env-token");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses bootstrap envelope values as fallbacks when CLI and env are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: "/tmp/t3-bootstrap-home",
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: true,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
|
||||
yield* runCli([], {
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4888);
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.2");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-bootstrap-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-bootstrap-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "bootstrap-token");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("applies CLI then env precedence over bootstrap envelope values", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: "/tmp/t3-bootstrap-home",
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: false,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
|
||||
yield* runCli(["--port", "4999", "--host", "0.0.0.0", "--auth-token", "cli-token"], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_HOME: "/tmp/t3-env-home",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.port, 4999);
|
||||
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "cli-token");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers --mode over T3CODE_MODE", () =>
|
||||
Effect.gen(function* () {
|
||||
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(4666));
|
||||
|
||||
+147
-45
@@ -11,12 +11,13 @@ 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, resolveStateDir } from "./os-jank";
|
||||
import { fixPath, resolveBaseDir } from "./os-jank";
|
||||
import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
@@ -26,20 +27,36 @@ import { Server } from "./wsServer";
|
||||
import { ServerLoggerLive } from "./serverLogger";
|
||||
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
const BootstrapEnvelopeSchema = Schema.Struct({
|
||||
mode: Schema.optional(Schema.String),
|
||||
port: Schema.optional(PortSchema),
|
||||
host: Schema.optional(Schema.String),
|
||||
t3Home: Schema.optional(Schema.String),
|
||||
devUrl: Schema.optional(Schema.URLFromString),
|
||||
noBrowser: Schema.optional(Schema.Boolean),
|
||||
authToken: Schema.optional(Schema.String),
|
||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
interface CliInput {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly stateDir: Option.Option<string>;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly authToken: Option.Option<string>;
|
||||
readonly bootstrapFd: Option.Option<number>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
}
|
||||
@@ -90,19 +107,12 @@ export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
|
||||
const CliEnvConfig = Config.all({
|
||||
mode: Config.string("T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(
|
||||
Option.match<RuntimeMode, string>({
|
||||
onNone: () => "web",
|
||||
onSome: (value) => (value === "desktop" ? "desktop" : "web"),
|
||||
}),
|
||||
),
|
||||
Config.map(Option.map((value) => (value === "desktop" ? "desktop" : "web"))),
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
stateDir: Config.string("T3CODE_STATE_DIR").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
@@ -112,6 +122,10 @@ const CliEnvConfig = Config.all({
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
@@ -125,6 +139,14 @@ const CliEnvConfig = Config.all({
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
|
||||
const isValidPort = (value: number): boolean => value >= 1 && value <= 65_535;
|
||||
const isRuntimeMode = (value: string): value is RuntimeMode =>
|
||||
value === "web" || value === "desktop";
|
||||
|
||||
const ServerConfigLive = (input: CliInput) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
@@ -138,53 +160,127 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
),
|
||||
);
|
||||
|
||||
const mode = Option.getOrElse(input.mode, () => env.mode);
|
||||
const bootstrapFd = Option.getOrUndefined(input.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
|
||||
const port = yield* Option.match(input.port, {
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (env.port) {
|
||||
return Effect.succeed(env.port);
|
||||
}
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
});
|
||||
const stateDir = yield* resolveStateDir(
|
||||
Option.getOrUndefined(input.stateDir) ?? env.stateDir,
|
||||
const mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.mode), isRuntimeMode),
|
||||
),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
const port = yield* Option.match(
|
||||
resolveOptionPrecedence(
|
||||
input.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.port), isValidPort),
|
||||
),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const devUrl = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.devUrl),
|
||||
),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
const baseDir = yield* resolveBaseDir(
|
||||
Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
input.t3Home,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.t3Home),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
const noBrowser = resolveBooleanFlag(
|
||||
input.noBrowser,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.noBrowser),
|
||||
),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
),
|
||||
);
|
||||
const authToken = resolveOptionPrecedence(
|
||||
input.authToken,
|
||||
Option.fromUndefinedOr(env.authToken),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.authToken),
|
||||
),
|
||||
);
|
||||
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
|
||||
const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
|
||||
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
input.autoBootstrapProjectFromCwd,
|
||||
env.autoBootstrapProjectFromCwd ?? mode === "web",
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
),
|
||||
() => mode === "web",
|
||||
),
|
||||
);
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
input.logWebSocketEvents,
|
||||
env.logWebSocketEvents ?? Boolean(devUrl),
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.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 ??
|
||||
(mode === "desktop" ? "127.0.0.1" : undefined);
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
mode,
|
||||
port,
|
||||
cwd: cliConfig.cwd,
|
||||
keybindingsConfigPath,
|
||||
host,
|
||||
stateDir,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
authToken,
|
||||
authToken: Option.getOrUndefined(authToken),
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
} satisfies ServerConfigShape;
|
||||
@@ -291,7 +387,7 @@ const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
|
||||
Flag.optional,
|
||||
);
|
||||
const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
@@ -299,8 +395,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 stateDirFlag = Flag.string("state-dir").pipe(
|
||||
Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
|
||||
const t3HomeFlag = Flag.string("home-dir").pipe(
|
||||
Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
@@ -317,6 +413,11 @@ const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
|
||||
Flag.withSchema(Schema.Int),
|
||||
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
|
||||
Flag.optional,
|
||||
);
|
||||
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Create a project for the current working directory on startup when missing.",
|
||||
@@ -335,10 +436,11 @@ export const t3Cli = Command.make("t3", {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
host: hostFlag,
|
||||
stateDir: stateDirFlag,
|
||||
t3Home: t3HomeFlag,
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
authToken: authTokenFlag,
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
}).pipe(
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
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 {
|
||||
isCommandAvailable,
|
||||
@@ -10,12 +9,19 @@ import {
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
import { Effect } from "effect";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
|
||||
describe("resolveEditorLaunch", () => {
|
||||
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
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",
|
||||
@@ -117,7 +123,7 @@ describe("resolveEditorLaunch", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("launchDetached", () => {
|
||||
it.layer(NodeServices.layer)("launchDetached", (it) => {
|
||||
it.effect("resolves when command can be spawned", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
@@ -139,26 +145,20 @@ describe("launchDetached", () => {
|
||||
);
|
||||
});
|
||||
|
||||
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");
|
||||
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");
|
||||
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,55 +168,65 @@ describe("isCommandAvailable", () => {
|
||||
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
|
||||
});
|
||||
|
||||
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");
|
||||
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");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
|
||||
});
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
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");
|
||||
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");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("my.tool", { 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.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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
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");
|
||||
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");
|
||||
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 { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -19,6 +19,7 @@ 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";
|
||||
@@ -44,7 +45,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex";
|
||||
readonly provider: ProviderKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -235,6 +236,7 @@ describe("CheckpointReactor", () => {
|
||||
readonly projectWorkspaceRoot?: string;
|
||||
readonly threadWorktreePath?: string | null;
|
||||
readonly providerSessionCwd?: string;
|
||||
readonly providerName?: ProviderKind;
|
||||
}) {
|
||||
const cwd = createGitRepository();
|
||||
tempDirs.push(cwd);
|
||||
@@ -242,7 +244,7 @@ describe("CheckpointReactor", () => {
|
||||
cwd,
|
||||
options?.hasSession ?? true,
|
||||
options?.providerSessionCwd ?? cwd,
|
||||
"codex",
|
||||
options?.providerName ?? "codex",
|
||||
);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -251,12 +253,16 @@ 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),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -276,7 +282,10 @@ describe("CheckpointReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Test Project",
|
||||
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -287,7 +296,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -477,6 +489,67 @@ 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();
|
||||
@@ -792,6 +865,75 @@ 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,12 +35,15 @@ 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(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||
@@ -69,7 +72,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -80,7 +86,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -123,7 +132,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "Replay Project",
|
||||
workspaceRoot: "/tmp/project-replay",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -134,7 +146,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-replay"),
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "replay",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -175,7 +190,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "Stream Project",
|
||||
workspaceRoot: "/tmp/project-stream",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -196,7 +214,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-stream"),
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "domain-stream",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -230,7 +251,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn Diff Project",
|
||||
workspaceRoot: "/tmp/project-turn-diff",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -241,7 +265,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn diff thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -317,13 +344,17 @@ 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(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
@@ -337,7 +368,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "Flaky Project",
|
||||
workspaceRoot: "/tmp/project-flaky",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -350,7 +384,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-fail",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -367,7 +404,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-ok",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -421,7 +461,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "Atomic Project",
|
||||
workspaceRoot: "/tmp/project-atomic",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -432,7 +475,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "atomic",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -556,7 +602,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "Sync Project",
|
||||
workspaceRoot: "/tmp/project-sync",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -567,7 +616,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-sync"),
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "sync-before",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -635,7 +687,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "Duplicate Project",
|
||||
workspaceRoot: "/tmp/project-duplicate",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -647,7 +702,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -664,7 +722,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
|
||||
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 = path.join(serverConfig.stateDir, "attachments");
|
||||
const attachmentsRootDir = serverConfig.attachmentsDir;
|
||||
|
||||
yield* Effect.forEach(
|
||||
sideEffects.deletedThreadIds,
|
||||
@@ -362,7 +362,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
workspaceRoot: event.payload.workspaceRoot,
|
||||
defaultModel: event.payload.defaultModel,
|
||||
defaultModelSelection: event.payload.defaultModelSelection,
|
||||
scripts: event.payload.scripts,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -383,8 +383,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
...(event.payload.workspaceRoot !== undefined
|
||||
? { workspaceRoot: event.payload.workspaceRoot }
|
||||
: {}),
|
||||
...(event.payload.defaultModel !== undefined
|
||||
? { defaultModel: event.payload.defaultModel }
|
||||
...(event.payload.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: event.payload.defaultModelSelection }
|
||||
: {}),
|
||||
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -420,7 +420,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
model: event.payload.model,
|
||||
modelSelection: event.payload.modelSelection,
|
||||
runtimeMode: event.payload.runtimeMode,
|
||||
interactionMode: event.payload.interactionMode,
|
||||
branch: event.payload.branch,
|
||||
@@ -442,7 +442,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.modelSelection !== undefined
|
||||
? { modelSelection: event.payload.modelSelection }
|
||||
: {}),
|
||||
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
|
||||
...(event.payload.worktreePath !== undefined
|
||||
? { worktreePath: event.payload.worktreePath }
|
||||
@@ -653,6 +655,8 @@ 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,
|
||||
});
|
||||
@@ -775,6 +779,8 @@ 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;
|
||||
@@ -804,6 +810,16 @@ 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)
|
||||
@@ -822,6 +838,12 @@ 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)
|
||||
@@ -875,6 +897,8 @@ 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,
|
||||
@@ -910,6 +934,8 @@ 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,
|
||||
@@ -954,6 +980,8 @@ 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,6 +26,7 @@ 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`
|
||||
@@ -33,7 +34,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
@@ -43,7 +44,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'gpt-5-codex',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
'2026-02-24T00:00:01.000Z',
|
||||
@@ -56,7 +57,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model,
|
||||
model_selection_json,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
@@ -68,7 +69,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'gpt-5-codex',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
@@ -101,6 +102,29 @@ 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,
|
||||
@@ -154,6 +178,8 @@ 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,
|
||||
@@ -168,6 +194,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'thread-1',
|
||||
'plan-1',
|
||||
'message-1',
|
||||
'completed',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
@@ -206,7 +234,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
id: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
@@ -226,7 +257,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -238,6 +272,10 @@ 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",
|
||||
@@ -253,7 +291,17 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
updatedAt: "2026-02-24T00:00:05.000Z",
|
||||
},
|
||||
],
|
||||
proposedPlans: [],
|
||||
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",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
{
|
||||
id: asEventId("activity-1"),
|
||||
|
||||
@@ -4,8 +4,10 @@ import {
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationReadModel,
|
||||
ProjectScript,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationLatestTurn,
|
||||
@@ -15,6 +17,7 @@ import {
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
ModelSelection,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -43,6 +46,7 @@ import {
|
||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
@@ -53,7 +57,11 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
@@ -74,6 +82,8 @@ 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;
|
||||
|
||||
@@ -137,7 +147,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model AS "defaultModel",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -156,7 +166,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -200,6 +210,8 @@ 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
|
||||
@@ -284,7 +296,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
requested_at AS "requestedAt",
|
||||
started_at AS "startedAt",
|
||||
completed_at AS "completedAt",
|
||||
assistant_message_id AS "assistantMessageId"
|
||||
assistant_message_id AS "assistantMessageId",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NOT NULL
|
||||
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
||||
@@ -435,6 +449,8 @@ 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,
|
||||
});
|
||||
@@ -497,6 +513,14 @@ 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,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -513,22 +537,22 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const projects: Array<OrchestrationProject> = projectRows.map((row) => ({
|
||||
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModel: row.defaultModel,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
}));
|
||||
|
||||
const threads: Array<OrchestrationThread> = threadRows.map((row) => ({
|
||||
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
model: row.model,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
|
||||
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../../git/Errors.ts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
@@ -41,6 +41,9 @@ 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,
|
||||
@@ -67,6 +70,7 @@ describe("ProviderCommandReactor", () => {
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
const createdStateDirs = new Set<string>();
|
||||
const createdBaseDirs = new Set<string>();
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
@@ -81,35 +85,35 @@ 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 stateDir?: string }) {
|
||||
async function createHarness(input?: {
|
||||
readonly baseDir?: string;
|
||||
readonly threadModelSelection?: ModelSelection;
|
||||
readonly sessionModelSwitch?: "unsupported" | "in-session";
|
||||
}) {
|
||||
const now = new Date().toISOString();
|
||||
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||
createdBaseDirs.add(baseDir);
|
||||
const { stateDir } = deriveServerPathsSync(baseDir, undefined);
|
||||
createdStateDirs.add(stateDir);
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
let nextSessionIndex = 1;
|
||||
const runtimeSessions: Array<ProviderSession> = [];
|
||||
const modelSelection = input?.threadModelSelection ?? {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
const startSession = vi.fn((_: unknown, input: unknown) => {
|
||||
const sessionIndex = nextSessionIndex++;
|
||||
const provider =
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"provider" in input &&
|
||||
input.provider === "codex"
|
||||
? input.provider
|
||||
: "codex";
|
||||
const resumeCursor =
|
||||
typeof input === "object" && input !== null && "resumeCursor" in input
|
||||
? input.resumeCursor
|
||||
: undefined;
|
||||
const model =
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"model" in input &&
|
||||
typeof input.model === "string"
|
||||
? input.model
|
||||
: undefined;
|
||||
const threadId =
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
@@ -118,7 +122,7 @@ describe("ProviderCommandReactor", () => {
|
||||
? ThreadId.makeUnsafe(input.threadId)
|
||||
: ThreadId.makeUnsafe(`thread-${sessionIndex}`);
|
||||
const session: ProviderSession = {
|
||||
provider,
|
||||
provider: modelSelection.provider,
|
||||
status: "ready" as const,
|
||||
runtimeMode:
|
||||
typeof input === "object" &&
|
||||
@@ -127,9 +131,9 @@ describe("ProviderCommandReactor", () => {
|
||||
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
|
||||
? input.runtimeMode
|
||||
: "full-access",
|
||||
...(model !== undefined ? { model } : {}),
|
||||
...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),
|
||||
threadId,
|
||||
resumeCursor: resumeCursor ?? { opaque: `cursor-${sessionIndex}` },
|
||||
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
@@ -189,9 +193,9 @@ describe("ProviderCommandReactor", () => {
|
||||
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
|
||||
stopSession: stopSession as ProviderServiceShape["stopSession"],
|
||||
listSessions: () => Effect.succeed(runtimeSessions),
|
||||
getCapabilities: (provider) =>
|
||||
getCapabilities: (_provider) =>
|
||||
Effect.succeed({
|
||||
sessionModelSwitch: provider === "codex" ? "in-session" : "in-session",
|
||||
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
|
||||
}),
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
@@ -210,7 +214,7 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
|
||||
),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
@@ -228,7 +232,7 @@ describe("ProviderCommandReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: modelSelection,
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -239,7 +243,7 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: modelSelection,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -289,7 +293,10 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1"));
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
cwd: "/tmp/provider-project",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
@@ -314,10 +321,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -331,9 +338,10 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -341,9 +349,10 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -351,6 +360,112 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards claude effort options through session start and turn send", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||
});
|
||||
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: [],
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
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({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards claude fast mode options through session start and turn send", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
||||
});
|
||||
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: [],
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
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({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards plan interaction mode to the provider turn request", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -389,6 +504,111 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
|
||||
});
|
||||
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: [],
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-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?.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("preserves the active session model when in-session model switching is unsupported", async () => {
|
||||
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -435,6 +655,77 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
});
|
||||
|
||||
it("restarts claude sessions when claude effort changes", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "claudeAgent", model: "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: [],
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
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: [],
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
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({
|
||||
resumeCursor: { opaque: "resume-1" },
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
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();
|
||||
@@ -509,7 +800,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: "cursor-1" },
|
||||
resumeCursor: { opaque: "resume-1" },
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
@@ -522,6 +813,125 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-runtime-mode-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-claude-no-options"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
runtimeMode: "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: [],
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-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.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();
|
||||
@@ -797,6 +1207,7 @@ 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(
|
||||
@@ -809,6 +1220,117 @@ 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,10 +1,11 @@
|
||||
import {
|
||||
type ChatAttachment,
|
||||
CommandId,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
EventId,
|
||||
type ModelSelection,
|
||||
type OrchestrationEvent,
|
||||
type ProviderModelOptions,
|
||||
type ProviderKind,
|
||||
ProviderKind,
|
||||
type ProviderStartOptions,
|
||||
type OrchestrationSession,
|
||||
ThreadId,
|
||||
@@ -12,7 +13,7 @@ import {
|
||||
type RuntimeMode,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
@@ -90,6 +91,21 @@ 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());
|
||||
}
|
||||
@@ -136,6 +152,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const threadProviderOptions = new Map<string, ProviderStartOptions>();
|
||||
const threadModelSelections = new Map<string, ModelSelection>();
|
||||
|
||||
const appendProviderFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -192,9 +209,7 @@ const make = Effect.gen(function* () {
|
||||
threadId: ThreadId,
|
||||
createdAt: string,
|
||||
options?: {
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
},
|
||||
) {
|
||||
@@ -205,10 +220,25 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const desiredRuntimeMode = thread.runtimeMode;
|
||||
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 currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(
|
||||
thread.session?.providerName,
|
||||
)
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
const requestedModelSelection = options?.modelSelection;
|
||||
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
|
||||
if (
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== threadProvider
|
||||
) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: threadProvider,
|
||||
method: "thread.turn.start",
|
||||
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
|
||||
});
|
||||
}
|
||||
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
|
||||
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
@@ -225,12 +255,9 @@ const make = Effect.gen(function* () {
|
||||
}) =>
|
||||
providerService.startSession(threadId, {
|
||||
threadId,
|
||||
...((input?.provider ?? preferredProvider)
|
||||
? { provider: input?.provider ?? preferredProvider }
|
||||
: {}),
|
||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
...(desiredModel ? { model: desiredModel } : {}),
|
||||
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
|
||||
modelSelection: desiredModelSelection,
|
||||
...(options?.providerOptions !== undefined
|
||||
? { providerOptions: options.providerOptions }
|
||||
: {}),
|
||||
@@ -259,16 +286,29 @@ const make = Effect.gen(function* () {
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged =
|
||||
options?.provider !== undefined && options.provider !== currentProvider;
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== currentProvider;
|
||||
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
|
||||
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
|
||||
const modelChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.model !== activeSession?.model;
|
||||
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
|
||||
const previousModelSelection = threadModelSelections.get(threadId);
|
||||
const shouldRestartForModelSelectionChange =
|
||||
currentProvider === "claudeAgent" &&
|
||||
requestedModelSelection !== undefined &&
|
||||
!Equal.equals(previousModelSelection, requestedModelSelection);
|
||||
|
||||
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
|
||||
if (
|
||||
!runtimeModeChanged &&
|
||||
!providerChanged &&
|
||||
!shouldRestartForModelChange &&
|
||||
!shouldRestartForModelSelectionChange
|
||||
) {
|
||||
return existingSessionThreadId;
|
||||
}
|
||||
|
||||
@@ -280,19 +320,19 @@ const make = Effect.gen(function* () {
|
||||
threadId,
|
||||
existingSessionThreadId,
|
||||
currentProvider,
|
||||
desiredProvider: options?.provider ?? currentProvider,
|
||||
desiredProvider: desiredModelSelection.provider,
|
||||
currentRuntimeMode: thread.session?.runtimeMode,
|
||||
desiredRuntimeMode: thread.runtimeMode,
|
||||
runtimeModeChanged,
|
||||
providerChanged,
|
||||
modelChanged,
|
||||
shouldRestartForModelChange,
|
||||
shouldRestartForModelSelectionChange,
|
||||
hasResumeCursor: resumeCursor !== undefined,
|
||||
});
|
||||
const restartedSession = yield* startProviderSession({
|
||||
...(resumeCursor !== undefined ? { resumeCursor } : {}),
|
||||
...(options?.provider !== undefined ? { provider: options.provider } : {}),
|
||||
});
|
||||
const restartedSession = yield* startProviderSession(
|
||||
resumeCursor !== undefined ? { resumeCursor } : undefined,
|
||||
);
|
||||
yield* Effect.logInfo("provider command reactor restarted provider session", {
|
||||
threadId,
|
||||
previousSessionId: existingSessionThreadId,
|
||||
@@ -304,9 +344,7 @@ const make = Effect.gen(function* () {
|
||||
return restartedSession.threadId;
|
||||
}
|
||||
|
||||
const startedSession = yield* startProviderSession(
|
||||
options?.provider !== undefined ? { provider: options.provider } : undefined,
|
||||
);
|
||||
const startedSession = yield* startProviderSession(undefined);
|
||||
yield* bindSessionToThread(startedSession);
|
||||
return startedSession.threadId;
|
||||
});
|
||||
@@ -315,9 +353,7 @@ const make = Effect.gen(function* () {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
readonly interactionMode?: "default" | "plan";
|
||||
readonly createdAt: string;
|
||||
@@ -326,15 +362,16 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||
});
|
||||
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.modelSelection !== undefined) {
|
||||
threadModelSelections.set(input.threadId, input.modelSelection);
|
||||
}
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
const activeSession = yield* providerService
|
||||
@@ -346,14 +383,23 @@ const make = Effect.gen(function* () {
|
||||
activeSession === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
|
||||
const modelForTurn = sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
|
||||
const requestedModelSelection =
|
||||
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
|
||||
const modelForTurn =
|
||||
sessionModelSwitch === "unsupported"
|
||||
? activeSession?.model !== undefined
|
||||
? {
|
||||
...requestedModelSelection,
|
||||
model: activeSession.model,
|
||||
}
|
||||
: requestedModelSelection
|
||||
: input.modelSelection;
|
||||
|
||||
yield* providerService.sendTurn({
|
||||
threadId: input.threadId,
|
||||
...(normalizedInput ? { input: normalizedInput } : {}),
|
||||
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
|
||||
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
|
||||
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
|
||||
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
|
||||
});
|
||||
});
|
||||
@@ -391,6 +437,7 @@ const make = Effect.gen(function* () {
|
||||
cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
@@ -465,17 +512,26 @@ const make = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
messageText: message.text,
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.modelOptions !== undefined
|
||||
? { modelOptions: event.payload.modelOptions }
|
||||
...(event.payload.modelSelection !== undefined
|
||||
? { modelSelection: event.payload.modelSelection }
|
||||
: {}),
|
||||
...(event.payload.providerOptions !== undefined
|
||||
? { providerOptions: event.payload.providerOptions }
|
||||
: {}),
|
||||
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* (
|
||||
@@ -534,7 +590,9 @@ const make = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
detail: Cause.pretty(cause),
|
||||
detail: isUnknownPendingApprovalRequestError(cause)
|
||||
? stalePendingRequestDetail("approval", event.payload.requestId)
|
||||
: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
@@ -578,7 +636,9 @@ const make = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.user-input.respond.failed",
|
||||
summary: "Provider user input response failed",
|
||||
detail: Cause.pretty(cause),
|
||||
detail: isUnknownPendingUserInputRequestError(cause)
|
||||
? stalePendingRequestDetail("user-input", event.payload.requestId)
|
||||
: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
@@ -624,13 +684,13 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(
|
||||
event.payload.threadId,
|
||||
event.occurredAt,
|
||||
cachedProviderOptions !== undefined
|
||||
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
|
||||
...(cachedProviderOptions !== undefined
|
||||
? { providerOptions: cachedProviderOptions }
|
||||
: undefined,
|
||||
);
|
||||
: {}),
|
||||
...(cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "thread.turn-start-requested":
|
||||
|
||||
@@ -2,7 +2,12 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { OrchestrationReadModel, ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import type {
|
||||
OrchestrationReadModel,
|
||||
ProviderKind,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSession,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
@@ -45,7 +50,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex";
|
||||
readonly provider: ProviderKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -57,6 +62,7 @@ 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 = {
|
||||
@@ -66,12 +72,21 @@ function createProviderServiceHarness() {
|
||||
respondToRequest: () => unsupported(),
|
||||
respondToUserInput: () => unsupported(),
|
||||
stopSession: () => unsupported(),
|
||||
listSessions: () => Effect.succeed([]),
|
||||
listSessions: () => Effect.succeed([...runtimeSessions]),
|
||||
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));
|
||||
};
|
||||
@@ -79,6 +94,7 @@ function createProviderServiceHarness() {
|
||||
return {
|
||||
service,
|
||||
emit,
|
||||
setSession,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -86,11 +102,12 @@ 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.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
@@ -150,6 +167,7 @@ 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),
|
||||
@@ -169,7 +187,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -180,7 +201,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -205,10 +229,19 @@ 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,
|
||||
};
|
||||
}
|
||||
@@ -402,6 +435,60 @@ 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();
|
||||
@@ -628,6 +715,511 @@ 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",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
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",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
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",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
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",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
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",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
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();
|
||||
@@ -1327,6 +1919,185 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(checkpoint?.checkpointRef).toBe("provider-diff:evt-turn-diff-updated");
|
||||
});
|
||||
|
||||
it("projects context window updates into normalized thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: asEventId("evt-thread-token-usage-updated"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 1075,
|
||||
totalProcessedTokens: 10_200,
|
||||
maxTokens: 128_000,
|
||||
inputTokens: 1000,
|
||||
cachedInputTokens: 500,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 25,
|
||||
lastUsedTokens: 1075,
|
||||
lastInputTokens: 1000,
|
||||
lastCachedInputTokens: 500,
|
||||
lastOutputTokens: 50,
|
||||
lastReasoningOutputTokens: 25,
|
||||
compactsAutomatically: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
);
|
||||
|
||||
const usageActivity = thread.activities.find(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
);
|
||||
expect(usageActivity).toBeDefined();
|
||||
expect(usageActivity?.payload).toMatchObject({
|
||||
usedTokens: 1075,
|
||||
totalProcessedTokens: 10_200,
|
||||
maxTokens: 128_000,
|
||||
inputTokens: 1000,
|
||||
cachedInputTokens: 500,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 25,
|
||||
lastUsedTokens: 1075,
|
||||
compactsAutomatically: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("projects Codex camelCase token usage payloads into normalized thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: asEventId("evt-thread-token-usage-updated-camel"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 126,
|
||||
totalProcessedTokens: 11_839,
|
||||
maxTokens: 258_400,
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
lastUsedTokens: 126,
|
||||
lastInputTokens: 120,
|
||||
lastCachedInputTokens: 0,
|
||||
lastOutputTokens: 6,
|
||||
lastReasoningOutputTokens: 0,
|
||||
compactsAutomatically: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
);
|
||||
|
||||
const usageActivity = thread.activities.find(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
);
|
||||
expect(usageActivity?.payload).toMatchObject({
|
||||
usedTokens: 126,
|
||||
totalProcessedTokens: 11_839,
|
||||
maxTokens: 258_400,
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
lastUsedTokens: 126,
|
||||
lastInputTokens: 120,
|
||||
lastOutputTokens: 6,
|
||||
compactsAutomatically: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("projects Claude usage snapshots with context window into normalized thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: asEventId("evt-thread-token-usage-updated-claude-window"),
|
||||
provider: "claudeAgent",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 31_251,
|
||||
lastUsedTokens: 31_251,
|
||||
maxTokens: 200_000,
|
||||
toolUses: 25,
|
||||
durationMs: 43_567,
|
||||
},
|
||||
},
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/result/success",
|
||||
payload: {},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
);
|
||||
|
||||
const usageActivity = thread.activities.find(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
);
|
||||
expect(usageActivity?.payload).toMatchObject({
|
||||
usedTokens: 31_251,
|
||||
lastUsedTokens: 31_251,
|
||||
maxTokens: 200_000,
|
||||
toolUses: 25,
|
||||
durationMs: 43_567,
|
||||
});
|
||||
});
|
||||
|
||||
it("projects compacted thread state into context compaction activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.state.changed",
|
||||
eventId: asEventId("evt-thread-compacted"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
payload: {
|
||||
state: "compacted",
|
||||
detail: { source: "provider" },
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-compaction",
|
||||
),
|
||||
);
|
||||
|
||||
const activity = thread.activities.find(
|
||||
(candidate: ProviderRuntimeTestActivity) => candidate.kind === "context-compaction",
|
||||
);
|
||||
expect(activity?.summary).toBe("Context compacted");
|
||||
expect(activity?.tone).toBe("info");
|
||||
});
|
||||
|
||||
it("projects Codex task lifecycle chunks into thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -1354,6 +2125,7 @@ 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.",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1416,8 +2188,9 @@ 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(
|
||||
"Comparing the desktop rollout chunks to the app-server stream.",
|
||||
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(completed?.kind).toBe("task.completed");
|
||||
expect(completedPayload?.detail).toBe("<proposed_plan>\n# Plan title\n</proposed_plan>");
|
||||
|
||||
@@ -4,8 +4,11 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationProposedPlanId,
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
ThreadId,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
TurnId,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
@@ -14,6 +17,8 @@ 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";
|
||||
@@ -97,6 +102,15 @@ function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function buildContextWindowActivityPayload(
|
||||
event: ProviderRuntimeEvent,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
if (event.type !== "thread.token-usage.updated" || event.payload.usage.usedTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
return event.payload.usage;
|
||||
}
|
||||
|
||||
function runtimePayloadRecord(event: ProviderRuntimeEvent): Record<string, unknown> | undefined {
|
||||
const payload = (event as { payload?: unknown }).payload;
|
||||
if (!payload || typeof payload !== "object") {
|
||||
@@ -173,18 +187,6 @@ 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> {
|
||||
@@ -381,7 +383,8 @@ function runtimeEventToActivities(
|
||||
summary: "Reasoning update",
|
||||
payload: {
|
||||
taskId: event.payload.taskId,
|
||||
detail: truncateDetail(event.payload.description),
|
||||
detail: truncateDetail(event.payload.summary ?? event.payload.description),
|
||||
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
|
||||
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
|
||||
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
|
||||
},
|
||||
@@ -416,6 +419,48 @@ function runtimeEventToActivities(
|
||||
];
|
||||
}
|
||||
|
||||
case "thread.state.changed": {
|
||||
if (event.payload.state !== "compacted") {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
createdAt: event.createdAt,
|
||||
tone: "info",
|
||||
kind: "context-compaction",
|
||||
summary: "Context compacted",
|
||||
payload: {
|
||||
state: event.payload.state,
|
||||
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "thread.token-usage.updated": {
|
||||
const payload = buildContextWindowActivityPayload(event);
|
||||
if (!payload) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
createdAt: event.createdAt,
|
||||
tone: "info",
|
||||
kind: "context-window.updated",
|
||||
summary: "Context window updated",
|
||||
payload,
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "item.updated": {
|
||||
if (!isToolLifecycleItemType(event.payload.itemType)) {
|
||||
return [];
|
||||
@@ -449,7 +494,7 @@ function runtimeEventToActivities(
|
||||
createdAt: event.createdAt,
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: `${event.payload.title ?? "Tool"} complete`,
|
||||
summary: event.payload.title ?? "Tool",
|
||||
payload: {
|
||||
itemType: event.payload.itemType,
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
@@ -491,6 +536,7 @@ 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,
|
||||
@@ -682,6 +728,8 @@ const make = Effect.gen(function* () {
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
@@ -704,6 +752,8 @@ 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,
|
||||
},
|
||||
@@ -717,6 +767,8 @@ const make = Effect.gen(function* () {
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
@@ -783,6 +835,79 @@ 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();
|
||||
@@ -823,6 +948,10 @@ 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" ||
|
||||
@@ -865,6 +994,26 @@ 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"),
|
||||
@@ -1155,4 +1304,7 @@ const make = Effect.gen(function* () {
|
||||
} satisfies ProviderRuntimeIngestionShape;
|
||||
});
|
||||
|
||||
export const ProviderRuntimeIngestionLive = Layer.effect(ProviderRuntimeIngestionService, make);
|
||||
export const ProviderRuntimeIngestionLive = Layer.effect(
|
||||
ProviderRuntimeIngestionService,
|
||||
make,
|
||||
).pipe(Layer.provide(ProjectionTurnRepositoryLive));
|
||||
@@ -28,7 +28,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Project A",
|
||||
workspaceRoot: "/tmp/project-a",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -38,7 +41,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ProjectId.makeUnsafe("project-b"),
|
||||
title: "Project B",
|
||||
workspaceRoot: "/tmp/project-b",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -50,7 +56,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -69,7 +78,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ThreadId.makeUnsafe("thread-2"),
|
||||
projectId: ProjectId.makeUnsafe("project-b"),
|
||||
title: "Thread B",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -144,7 +156,10 @@ describe("commandInvariants", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-3"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "new",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -165,7 +180,10 @@ describe("commandInvariants", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "dup",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
|
||||
@@ -59,7 +59,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-scripts"),
|
||||
title: "Scripts",
|
||||
workspaceRoot: "/tmp/scripts",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -113,7 +113,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -136,7 +136,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -159,10 +162,10 @@ describe("decider project scripts", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -189,10 +192,10 @@ describe("decider project scripts", () => {
|
||||
expect(turnStartEvent.payload).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
messageId: asMessageId("message-user-1"),
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -220,7 +223,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -243,7 +246,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -299,7 +305,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -322,7 +328,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
|
||||
@@ -77,7 +77,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
workspaceRoot: command.workspaceRoot,
|
||||
defaultModel: command.defaultModel ?? null,
|
||||
defaultModelSelection: command.defaultModelSelection ?? null,
|
||||
scripts: [],
|
||||
createdAt: command.createdAt,
|
||||
updatedAt: command.createdAt,
|
||||
@@ -104,7 +104,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
projectId: command.projectId,
|
||||
...(command.title !== undefined ? { title: command.title } : {}),
|
||||
...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
|
||||
...(command.defaultModel !== undefined ? { defaultModel: command.defaultModel } : {}),
|
||||
...(command.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: command.defaultModelSelection }
|
||||
: {}),
|
||||
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
@@ -156,7 +158,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
model: command.model,
|
||||
modelSelection: command.modelSelection,
|
||||
runtimeMode: command.runtimeMode,
|
||||
interactionMode: command.interactionMode,
|
||||
branch: command.branch,
|
||||
@@ -207,7 +209,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
...(command.title !== undefined ? { title: command.title } : {}),
|
||||
...(command.model !== undefined ? { model: command.model } : {}),
|
||||
...(command.modelSelection !== undefined
|
||||
? { modelSelection: command.modelSelection }
|
||||
: {}),
|
||||
...(command.branch !== undefined ? { branch: command.branch } : {}),
|
||||
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
|
||||
updatedAt: occurredAt,
|
||||
@@ -262,11 +266,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.turn.start": {
|
||||
yield* requireThread({
|
||||
const targetThread = 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",
|
||||
@@ -299,19 +327,16 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.message.messageId,
|
||||
...(command.provider !== undefined ? { provider: command.provider } : {}),
|
||||
...(command.model !== undefined ? { model: command.model } : {}),
|
||||
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
|
||||
...(command.modelSelection !== undefined
|
||||
? { modelSelection: command.modelSelection }
|
||||
: {}),
|
||||
...(command.providerOptions !== undefined
|
||||
? { providerOptions: command.providerOptions }
|
||||
: {}),
|
||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
runtimeMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
|
||||
command.runtimeMode,
|
||||
interactionMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
|
||||
command.interactionMode,
|
||||
runtimeMode: targetThread.runtimeMode,
|
||||
interactionMode: targetThread.interactionMode,
|
||||
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -56,7 +56,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -73,7 +76,10 @@ describe("orchestration projector", () => {
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
@@ -110,7 +116,10 @@ describe("orchestration projector", () => {
|
||||
// missing required threadId
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -170,7 +179,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -233,7 +245,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -287,7 +302,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -371,7 +389,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -583,7 +604,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-revert",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -733,7 +757,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-capped",
|
||||
projectId: "project-1",
|
||||
title: "capped",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
|
||||
@@ -181,7 +181,7 @@ export function projectEvent(
|
||||
id: payload.projectId,
|
||||
title: payload.title,
|
||||
workspaceRoot: payload.workspaceRoot,
|
||||
defaultModel: payload.defaultModel,
|
||||
defaultModelSelection: payload.defaultModelSelection,
|
||||
scripts: payload.scripts,
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
@@ -211,8 +211,8 @@ export function projectEvent(
|
||||
...(payload.workspaceRoot !== undefined
|
||||
? { workspaceRoot: payload.workspaceRoot }
|
||||
: {}),
|
||||
...(payload.defaultModel !== undefined
|
||||
? { defaultModel: payload.defaultModel }
|
||||
...(payload.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: payload.defaultModelSelection }
|
||||
: {}),
|
||||
...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
@@ -252,7 +252,7 @@ export function projectEvent(
|
||||
id: payload.threadId,
|
||||
projectId: payload.projectId,
|
||||
title: payload.title,
|
||||
model: payload.model,
|
||||
modelSelection: payload.modelSelection,
|
||||
runtimeMode: payload.runtimeMode,
|
||||
interactionMode: payload.interactionMode,
|
||||
branch: payload.branch,
|
||||
@@ -295,7 +295,9 @@ export function projectEvent(
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
...(payload.title !== undefined ? { title: payload.title } : {}),
|
||||
...(payload.model !== undefined ? { model: payload.model } : {}),
|
||||
...(payload.modelSelection !== undefined
|
||||
? { modelSelection: payload.modelSelection }
|
||||
: {}),
|
||||
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
|
||||
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
|
||||
@@ -27,10 +27,10 @@ export const expandHomePath = Effect.fn(function* (input: string) {
|
||||
return input;
|
||||
});
|
||||
|
||||
export const resolveStateDir = Effect.fn(function* (raw: string | undefined) {
|
||||
export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {
|
||||
const { join, resolve } = yield* Path.Path;
|
||||
if (!raw || raw.trim().length === 0) {
|
||||
return join(OS.homedir(), ".t3", "userdata");
|
||||
return join(OS.homedir(), ".t3");
|
||||
}
|
||||
return resolve(yield* expandHomePath(raw.trim()));
|
||||
});
|
||||
@@ -35,7 +35,7 @@ layer("OrchestrationEventStore", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-roundtrip"),
|
||||
title: "Roundtrip Project",
|
||||
workspaceRoot: "/tmp/project-roundtrip",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Option, Schema, Struct } from "effect";
|
||||
|
||||
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
|
||||
import { ModelSelection, ProjectScript } from "@t3tools/contracts";
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionProjectInput,
|
||||
GetProjectionProjectInput,
|
||||
@@ -11,69 +11,64 @@ import {
|
||||
ProjectionProjectRepository,
|
||||
type ProjectionProjectRepositoryShape,
|
||||
} from "../Services/ProjectionProjects.ts";
|
||||
import { ProjectScript } from "@t3tools/contracts";
|
||||
|
||||
// Makes sure that the scripts are parsed from the JSON string the DB returns
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({ scripts: Schema.fromJsonString(Schema.Array(ProjectScript)) }),
|
||||
const ProjectionProjectDbRow = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown) =>
|
||||
Schema.isSchemaError(cause)
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
type ProjectionProjectDbRow = typeof ProjectionProjectDbRow.Type;
|
||||
|
||||
const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertProjectionProjectRow = SqlSchema.void({
|
||||
Request: ProjectionProjectDbRowSchema,
|
||||
Request: ProjectionProject,
|
||||
execute: (row) =>
|
||||
sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.workspaceRoot},
|
||||
${row.defaultModel},
|
||||
${row.scripts},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (project_id)
|
||||
DO UPDATE SET
|
||||
title = excluded.title,
|
||||
workspace_root = excluded.workspace_root,
|
||||
default_model = excluded.default_model,
|
||||
scripts_json = excluded.scripts_json,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
deleted_at = excluded.deleted_at
|
||||
`,
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.workspaceRoot},
|
||||
${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},
|
||||
${JSON.stringify(row.scripts)},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (project_id)
|
||||
DO UPDATE SET
|
||||
title = excluded.title,
|
||||
workspace_root = excluded.workspace_root,
|
||||
default_model_selection_json = excluded.default_model_selection_json,
|
||||
scripts_json = excluded.scripts_json,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
deleted_at = excluded.deleted_at
|
||||
`,
|
||||
});
|
||||
|
||||
const getProjectionProjectRow = SqlSchema.findOneOption({
|
||||
Request: GetProjectionProjectInput,
|
||||
Result: ProjectionProjectDbRowSchema,
|
||||
Result: ProjectionProjectDbRow,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model AS "defaultModel",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -85,14 +80,14 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
|
||||
const listProjectionProjectRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionProjectDbRowSchema,
|
||||
Result: ProjectionProjectDbRow,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model AS "defaultModel",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -113,40 +108,17 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
|
||||
const upsert: ProjectionProjectRepositoryShape["upsert"] = (row) =>
|
||||
upsertProjectionProjectRow(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionProjectRepository.upsert:query",
|
||||
"ProjectionProjectRepository.upsert:encodeRequest",
|
||||
),
|
||||
),
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.upsert:query")),
|
||||
);
|
||||
|
||||
const getById: ProjectionProjectRepositoryShape["getById"] = (input) =>
|
||||
getProjectionProjectRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionProjectRepository.getById:query",
|
||||
"ProjectionProjectRepository.getById:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((rowOption) =>
|
||||
Option.match(rowOption, {
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (row) =>
|
||||
Effect.succeed(Option.some(row as Schema.Schema.Type<typeof ProjectionProject>)),
|
||||
}),
|
||||
),
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.getById:query")),
|
||||
);
|
||||
|
||||
const listAll: ProjectionProjectRepositoryShape["listAll"] = () =>
|
||||
listProjectionProjectRows().pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionProjectRepository.listAll:query",
|
||||
"ProjectionProjectRepository.listAll:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionProject>>),
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.listAll:query")),
|
||||
);
|
||||
|
||||
const deleteById: ProjectionProjectRepositoryShape["deleteById"] = (input) =>
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { SqlitePersistenceMemory } from "./Sqlite.ts";
|
||||
import { ProjectionProjectRepositoryLive } from "./ProjectionProjects.ts";
|
||||
import { ProjectionThreadRepositoryLive } from "./ProjectionThreads.ts";
|
||||
import { ProjectionProjectRepository } from "../Services/ProjectionProjects.ts";
|
||||
import { ProjectionThreadRepository } from "../Services/ProjectionThreads.ts";
|
||||
|
||||
const projectionRepositoriesLayer = it.layer(
|
||||
Layer.mergeAll(
|
||||
ProjectionProjectRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
ProjectionThreadRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
SqlitePersistenceMemory,
|
||||
),
|
||||
);
|
||||
|
||||
projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
it.effect("stores SQL NULL for missing project model options", () =>
|
||||
Effect.gen(function* () {
|
||||
const projects = yield* ProjectionProjectRepository;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* projects.upsert({
|
||||
projectId: ProjectId.makeUnsafe("project-null-options"),
|
||||
title: "Null options project",
|
||||
workspaceRoot: "/tmp/project-null-options",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
const rows = yield* sql<{
|
||||
readonly defaultModelSelection: string | null;
|
||||
}>`
|
||||
SELECT default_model_selection_json AS "defaultModelSelection"
|
||||
FROM projection_projects
|
||||
WHERE project_id = 'project-null-options'
|
||||
`;
|
||||
const row = rows[0];
|
||||
if (!row) {
|
||||
return yield* Effect.fail(new Error("Expected projection_projects row to exist."));
|
||||
}
|
||||
|
||||
assert.strictEqual(
|
||||
row.defaultModelSelection,
|
||||
JSON.stringify({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
}),
|
||||
);
|
||||
|
||||
const persisted = yield* projects.getById({
|
||||
projectId: ProjectId.makeUnsafe("project-null-options"),
|
||||
});
|
||||
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stores JSON for thread model options", () =>
|
||||
Effect.gen(function* () {
|
||||
const threads = yield* ProjectionThreadRepository;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* threads.upsert({
|
||||
threadId: ThreadId.makeUnsafe("thread-null-options"),
|
||||
projectId: ProjectId.makeUnsafe("project-null-options"),
|
||||
title: "Null options thread",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurnId: null,
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
const rows = yield* sql<{
|
||||
readonly modelSelection: string | null;
|
||||
}>`
|
||||
SELECT model_selection_json AS "modelSelection"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-null-options'
|
||||
`;
|
||||
const row = rows[0];
|
||||
if (!row) {
|
||||
return yield* Effect.fail(new Error("Expected projection_threads row to exist."));
|
||||
}
|
||||
|
||||
assert.strictEqual(
|
||||
row.modelSelection,
|
||||
JSON.stringify({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
}),
|
||||
);
|
||||
|
||||
const persisted = yield* threads.getById({
|
||||
threadId: ThreadId.makeUnsafe("thread-null-options"),
|
||||
});
|
||||
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -22,6 +22,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
turn_id,
|
||||
plan_markdown,
|
||||
implemented_at,
|
||||
implementation_thread_id,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
@@ -30,6 +32,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.planMarkdown},
|
||||
${row.implementedAt},
|
||||
${row.implementationThreadId},
|
||||
${row.createdAt},
|
||||
${row.updatedAt}
|
||||
)
|
||||
@@ -38,6 +42,8 @@ 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
|
||||
`,
|
||||
@@ -52,6 +58,8 @@ 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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
@@ -11,6 +11,14 @@ import {
|
||||
ProjectionThreadRepository,
|
||||
type ProjectionThreadRepositoryShape,
|
||||
} from "../Services/ProjectionThreads.ts";
|
||||
import { ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
const ProjectionThreadDbRow = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
}),
|
||||
);
|
||||
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
|
||||
|
||||
const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
@@ -23,7 +31,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
@@ -37,7 +45,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.model},
|
||||
${JSON.stringify(row.modelSelection)},
|
||||
${row.runtimeMode},
|
||||
${row.interactionMode},
|
||||
${row.branch},
|
||||
@@ -51,7 +59,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
DO UPDATE SET
|
||||
project_id = excluded.project_id,
|
||||
title = excluded.title,
|
||||
model = excluded.model,
|
||||
model_selection_json = excluded.model_selection_json,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
interaction_mode = excluded.interaction_mode,
|
||||
branch = excluded.branch,
|
||||
@@ -65,14 +73,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
|
||||
const getProjectionThreadRow = SqlSchema.findOneOption({
|
||||
Request: GetProjectionThreadInput,
|
||||
Result: ProjectionThread,
|
||||
Result: ProjectionThreadDbRow,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -88,14 +96,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
|
||||
const listProjectionThreadRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadsByProjectInput,
|
||||
Result: ProjectionThread,
|
||||
Result: ProjectionThreadDbRow,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
|
||||
@@ -47,6 +47,8 @@ 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,
|
||||
@@ -61,6 +63,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.pendingMessageId},
|
||||
${row.sourceProposedPlanThreadId},
|
||||
${row.sourceProposedPlanId},
|
||||
${row.assistantMessageId},
|
||||
${row.state},
|
||||
${row.requestedAt},
|
||||
@@ -74,6 +78,8 @@ 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,
|
||||
@@ -106,6 +112,8 @@ 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,
|
||||
@@ -120,6 +128,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
NULL,
|
||||
${row.messageId},
|
||||
${row.sourceProposedPlanThreadId},
|
||||
${row.sourceProposedPlanId},
|
||||
NULL,
|
||||
'pending',
|
||||
${row.requestedAt},
|
||||
@@ -141,6 +151,8 @@ 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}
|
||||
@@ -162,6 +174,8 @@ 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",
|
||||
@@ -193,6 +207,8 @@ 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",
|
||||
|
||||
@@ -31,7 +31,7 @@ const setup = Layer.effectDiscard(
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`PRAGMA journal_mode = WAL;`;
|
||||
yield* sql`PRAGMA foreign_keys = ON;`;
|
||||
yield* runMigrations;
|
||||
yield* runMigrations();
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -49,9 +49,6 @@ export const SqlitePersistenceMemory = Layer.provideMerge(
|
||||
makeRuntimeSqliteLayer({ filename: ":memory:" }),
|
||||
);
|
||||
|
||||
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);
|
||||
export const layerConfig = Layer.unwrap(
|
||||
Effect.map(Effect.service(ServerConfig), ({ dbPath }) => makeSqlitePersistenceLive(dbPath)),
|
||||
);
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
import * as Migrator from "effect/unstable/sql/Migrator";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
// Import all migrations statically
|
||||
import Migration0001 from "./Migrations/001_OrchestrationEvents.ts";
|
||||
@@ -25,7 +26,9 @@ 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 { Effect } from "effect";
|
||||
import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
|
||||
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
|
||||
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -37,21 +40,33 @@ import { Effect } from "effect";
|
||||
* Uses Migrator.fromRecord which parses the key format and
|
||||
* returns migrations sorted by ID.
|
||||
*/
|
||||
const loader = Migrator.fromRecord({
|
||||
"1_OrchestrationEvents": Migration0001,
|
||||
"2_OrchestrationCommandReceipts": Migration0002,
|
||||
"3_CheckpointDiffBlobs": Migration0003,
|
||||
"4_ProviderSessionRuntime": Migration0004,
|
||||
"5_Projections": Migration0005,
|
||||
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
|
||||
"7_ProjectionThreadMessageAttachments": Migration0007,
|
||||
"8_ProjectionThreadActivitySequence": Migration0008,
|
||||
"9_ProviderSessionRuntimeMode": Migration0009,
|
||||
"10_ProjectionThreadsRuntimeMode": Migration0010,
|
||||
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
|
||||
"12_ProjectionThreadsInteractionMode": Migration0012,
|
||||
"13_ProjectionThreadProposedPlans": Migration0013,
|
||||
});
|
||||
export const migrationEntries = [
|
||||
[1, "OrchestrationEvents", Migration0001],
|
||||
[2, "OrchestrationCommandReceipts", Migration0002],
|
||||
[3, "CheckpointDiffBlobs", Migration0003],
|
||||
[4, "ProviderSessionRuntime", Migration0004],
|
||||
[5, "Projections", Migration0005],
|
||||
[6, "ProjectionThreadSessionRuntimeModeColumns", Migration0006],
|
||||
[7, "ProjectionThreadMessageAttachments", Migration0007],
|
||||
[8, "ProjectionThreadActivitySequence", Migration0008],
|
||||
[9, "ProviderSessionRuntimeMode", Migration0009],
|
||||
[10, "ProjectionThreadsRuntimeMode", Migration0010],
|
||||
[11, "OrchestrationThreadCreatedRuntimeMode", Migration0011],
|
||||
[12, "ProjectionThreadsInteractionMode", Migration0012],
|
||||
[13, "ProjectionThreadProposedPlans", Migration0013],
|
||||
[14, "ProjectionThreadProposedPlanImplementation", Migration0014],
|
||||
[15, "ProjectionTurnsSourceProposedPlan", Migration0015],
|
||||
[16, "CanonicalizeModelSelections", Migration0016],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
Migrator.fromRecord(
|
||||
Object.fromEntries(
|
||||
migrationEntries
|
||||
.filter(([id]) => throughId === undefined || id <= throughId)
|
||||
.map(([id, name, migration]) => [`${id}_${name}`, migration]),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Migrator run function - no schema dumping needed
|
||||
@@ -59,6 +74,10 @@ const loader = Migrator.fromRecord({
|
||||
*/
|
||||
const run = Migrator.make({});
|
||||
|
||||
export interface RunMigrationsOptions {
|
||||
readonly toMigrationInclusive?: number | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run all pending migrations.
|
||||
*
|
||||
@@ -69,11 +88,19 @@ const run = Migrator.make({});
|
||||
*
|
||||
* @returns Effect containing array of executed migrations
|
||||
*/
|
||||
export const runMigrations = Effect.gen(function* () {
|
||||
yield* Effect.log("Running migrations...");
|
||||
yield* run({ loader });
|
||||
yield* Effect.log("Migrations ran successfully");
|
||||
});
|
||||
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.log(
|
||||
toMigrationInclusive === undefined
|
||||
? "Running all migrations..."
|
||||
: `Running migrations 1 through ${toMigrationInclusive}...`,
|
||||
);
|
||||
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
|
||||
yield* Effect.log("Migrations ran successfully").pipe(
|
||||
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
|
||||
);
|
||||
return executedMigrations;
|
||||
});
|
||||
|
||||
/**
|
||||
* Layer that runs migrations when the layer is built.
|
||||
@@ -92,4 +119,4 @@ export const runMigrations = Effect.gen(function* () {
|
||||
* )
|
||||
* ```
|
||||
*/
|
||||
export const MigrationsLive = Layer.effectDiscard(runMigrations);
|
||||
export const MigrationsLive = Layer.effectDiscard(runMigrations());
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
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
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
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
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,357 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("016_CanonicalizeModelSelections", (it) => {
|
||||
it.effect(
|
||||
"migrates legacy projection rows and event payloads to the canonical model-selection shape",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
// Setup base state
|
||||
{
|
||||
yield* runMigrations({ toMigrationInclusive: 15 });
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES
|
||||
('project-codex', 'Codex project', '/tmp/project-codex', 'gpt-5.4', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL),
|
||||
('project-claude', 'Claude project', '/tmp/project-claude', 'claude-sonnet-4-6', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL),
|
||||
('project-null', 'Null project', '/tmp/project-null', NULL, '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL)
|
||||
`;
|
||||
yield* sql`
|
||||
UPDATE projection_projects
|
||||
SET default_model = 'claude-opus-4-6'
|
||||
WHERE project_id = 'project-claude'
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at,
|
||||
runtime_mode,
|
||||
interaction_mode
|
||||
)
|
||||
VALUES
|
||||
('thread-session', 'project-codex', 'Session thread', 'gpt-5.4', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
|
||||
('thread-claude', 'project-claude', 'Claude thread', 'claude-opus-4-6', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
|
||||
('thread-codex', 'project-codex', 'Codex thread', 'gpt-5.4', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
|
||||
('thread-legacy-options', 'project-claude', 'Legacy options thread', 'claude-opus-4-6', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default')
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_sessions (
|
||||
thread_id,
|
||||
status,
|
||||
provider_name,
|
||||
provider_session_id,
|
||||
provider_thread_id,
|
||||
active_turn_id,
|
||||
last_error,
|
||||
updated_at,
|
||||
runtime_mode
|
||||
)
|
||||
VALUES (
|
||||
'thread-session',
|
||||
'running',
|
||||
'claudeAgent',
|
||||
'provider-session-1',
|
||||
'provider-thread-1',
|
||||
NULL,
|
||||
NULL,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'full-access'
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_events (
|
||||
event_id,
|
||||
aggregate_kind,
|
||||
stream_id,
|
||||
stream_version,
|
||||
event_type,
|
||||
occurred_at,
|
||||
command_id,
|
||||
causation_event_id,
|
||||
correlation_id,
|
||||
actor_kind,
|
||||
payload_json,
|
||||
metadata_json
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'event-project-created',
|
||||
'project',
|
||||
'project-1',
|
||||
1,
|
||||
'project.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-project-created',
|
||||
NULL,
|
||||
'correlation-project-created',
|
||||
'user',
|
||||
'{"projectId":"project-1","title":"Project","workspaceRoot":"/tmp/project","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"high"},"claudeAgent":{"effort":"max"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-project-created-fallback',
|
||||
'project',
|
||||
'project-2',
|
||||
1,
|
||||
'project.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-project-created-fallback',
|
||||
NULL,
|
||||
'correlation-project-created-fallback',
|
||||
'user',
|
||||
'{"projectId":"project-2","title":"Fallback Project","workspaceRoot":"/tmp/project-2","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"low"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-created',
|
||||
'thread',
|
||||
'thread-1',
|
||||
1,
|
||||
'thread.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-thread-created',
|
||||
NULL,
|
||||
'correlation-thread-created',
|
||||
'user',
|
||||
'{"threadId":"thread-1","projectId":"project-1","title":"Thread","model":"claude-opus-4-6","modelOptions":{"codex":{"reasoningEffort":"high"},"claudeAgent":{"effort":"max","thinking":false}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-created-fallback',
|
||||
'thread',
|
||||
'thread-2',
|
||||
1,
|
||||
'thread.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-thread-created-fallback',
|
||||
NULL,
|
||||
'correlation-thread-created-fallback',
|
||||
'user',
|
||||
'{"threadId":"thread-2","projectId":"project-1","title":"Fallback Thread","model":"gpt-5.4","modelOptions":{"claudeAgent":{"effort":"max"}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-turn-start-requested',
|
||||
'thread',
|
||||
'thread-1',
|
||||
2,
|
||||
'thread.turn-start-requested',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-turn-start-requested',
|
||||
NULL,
|
||||
'correlation-turn-start-requested',
|
||||
'user',
|
||||
'{"threadId":"thread-1","turnId":"turn-1","input":"hi","model":"gpt-5.4","modelOptions":{"codex":{"fastMode":true},"claudeAgent":{"effort":"max"}},"deliveryMode":"buffered"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-created-no-model',
|
||||
'thread',
|
||||
'thread-3',
|
||||
1,
|
||||
'thread.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-thread-created-no-model',
|
||||
NULL,
|
||||
'correlation-thread-created-no-model',
|
||||
'user',
|
||||
'{"threadId":"thread-3","projectId":"project-1","title":"Ancient Thread","runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
)
|
||||
`;
|
||||
}
|
||||
|
||||
// Execute migration under test
|
||||
yield* runMigrations({ toMigrationInclusive: 16 });
|
||||
|
||||
// Assert expected state
|
||||
{
|
||||
const projectRows = yield* sql<{
|
||||
readonly projectId: string;
|
||||
readonly defaultModelSelection: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
default_model_selection_json AS "defaultModelSelection"
|
||||
FROM projection_projects
|
||||
ORDER BY project_id
|
||||
`;
|
||||
assert.deepStrictEqual(projectRows, [
|
||||
{
|
||||
projectId: "project-claude",
|
||||
defaultModelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}',
|
||||
},
|
||||
{
|
||||
projectId: "project-codex",
|
||||
defaultModelSelection: '{"provider":"codex","model":"gpt-5.4"}',
|
||||
},
|
||||
{ projectId: "project-null", defaultModelSelection: null },
|
||||
]);
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly threadId: string;
|
||||
readonly modelSelection: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
model_selection_json AS "modelSelection"
|
||||
FROM projection_threads
|
||||
ORDER BY thread_id
|
||||
`;
|
||||
assert.deepStrictEqual(threadRows, [
|
||||
{
|
||||
threadId: "thread-claude",
|
||||
modelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}',
|
||||
},
|
||||
{
|
||||
threadId: "thread-codex",
|
||||
modelSelection: '{"provider":"codex","model":"gpt-5.4"}',
|
||||
},
|
||||
{
|
||||
threadId: "thread-legacy-options",
|
||||
modelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}',
|
||||
},
|
||||
{
|
||||
threadId: "thread-session",
|
||||
modelSelection: '{"provider":"claudeAgent","model":"gpt-5.4"}',
|
||||
},
|
||||
]);
|
||||
|
||||
const eventRows = yield* sql<{
|
||||
readonly payloadJson: string;
|
||||
}>`
|
||||
SELECT payload_json AS "payloadJson"
|
||||
FROM orchestration_events
|
||||
ORDER BY rowid ASC
|
||||
`;
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[0]!.payloadJson), {
|
||||
projectId: "project-1",
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[1]!.payloadJson), {
|
||||
projectId: "project-2",
|
||||
title: "Fallback Project",
|
||||
workspaceRoot: "/tmp/project-2",
|
||||
defaultModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
},
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), {
|
||||
threadId: "thread-2",
|
||||
projectId: "project-1",
|
||||
title: "Fallback Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
input: "hi",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
deliveryMode: "buffered",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
|
||||
threadId: "thread-3",
|
||||
projectId: "project-1",
|
||||
title: "Ancient Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
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_projects
|
||||
ADD COLUMN default_model_selection_json TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_projects
|
||||
SET default_model_selection_json = CASE
|
||||
WHEN default_model IS NULL THEN NULL
|
||||
ELSE json_object(
|
||||
'provider',
|
||||
CASE
|
||||
WHEN lower(default_model) LIKE '%claude%' THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END,
|
||||
'model',
|
||||
default_model
|
||||
)
|
||||
END
|
||||
WHERE default_model_selection_json IS NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN model_selection_json TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET model_selection_json = json_object(
|
||||
'provider',
|
||||
COALESCE(
|
||||
(
|
||||
SELECT provider_name
|
||||
FROM projection_thread_sessions
|
||||
WHERE projection_thread_sessions.thread_id = projection_threads.thread_id
|
||||
),
|
||||
CASE
|
||||
WHEN lower(model) LIKE '%claude%' THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END,
|
||||
'codex'
|
||||
),
|
||||
'model',
|
||||
model
|
||||
)
|
||||
WHERE model_selection_json IS NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_projects
|
||||
DROP COLUMN default_model
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
DROP COLUMN model
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE orchestration_events
|
||||
SET payload_json = CASE
|
||||
WHEN json_type(payload_json, '$.defaultModel') = 'null' THEN json_remove(
|
||||
json_set(payload_json, '$.defaultModelSelection', json('null')),
|
||||
'$.defaultProvider',
|
||||
'$.defaultModel',
|
||||
'$.defaultModelOptions'
|
||||
)
|
||||
ELSE json_remove(
|
||||
json_set(
|
||||
payload_json,
|
||||
'$.defaultModelSelection',
|
||||
json_patch(
|
||||
json_object(
|
||||
'provider',
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL
|
||||
THEN json_extract(payload_json, '$.defaultProvider')
|
||||
WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%'
|
||||
THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END,
|
||||
'model',
|
||||
json_extract(payload_json, '$.defaultModel')
|
||||
),
|
||||
CASE
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions') IS NULL THEN '{}'
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
|
||||
OR json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
|
||||
THEN CASE
|
||||
WHEN (
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL
|
||||
THEN json_extract(payload_json, '$.defaultProvider')
|
||||
WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%'
|
||||
THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END
|
||||
) = 'claudeAgent'
|
||||
THEN CASE
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.codex'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
ELSE CASE
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.codex'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
END
|
||||
ELSE json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions'))
|
||||
)
|
||||
END
|
||||
)
|
||||
),
|
||||
'$.defaultProvider',
|
||||
'$.defaultModel',
|
||||
'$.defaultModelOptions'
|
||||
)
|
||||
END
|
||||
WHERE event_type IN ('project.created', 'project.meta-updated')
|
||||
AND json_type(payload_json, '$.defaultModelSelection') IS NULL
|
||||
AND json_type(payload_json, '$.defaultModel') IS NOT NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE orchestration_events
|
||||
SET payload_json = json_remove(
|
||||
json_set(
|
||||
payload_json,
|
||||
'$.modelSelection',
|
||||
json_patch(
|
||||
json_object(
|
||||
'provider',
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.provider') IS NOT NULL
|
||||
THEN json_extract(payload_json, '$.provider')
|
||||
WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'
|
||||
THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END,
|
||||
'model',
|
||||
json_extract(payload_json, '$.model')
|
||||
),
|
||||
CASE
|
||||
WHEN json_type(payload_json, '$.modelOptions') IS NULL THEN '{}'
|
||||
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
|
||||
OR json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
|
||||
THEN CASE
|
||||
WHEN (
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.provider') IS NOT NULL
|
||||
THEN json_extract(payload_json, '$.provider')
|
||||
WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'
|
||||
THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END
|
||||
) = 'claudeAgent'
|
||||
THEN CASE
|
||||
WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.claudeAgent'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.codex'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
ELSE CASE
|
||||
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.codex'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.claudeAgent'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
END
|
||||
ELSE json_object('options', json(json_extract(payload_json, '$.modelOptions')))
|
||||
END
|
||||
)
|
||||
),
|
||||
'$.provider',
|
||||
'$.model',
|
||||
'$.modelOptions'
|
||||
)
|
||||
WHERE event_type IN ('thread.created', 'thread.meta-updated', 'thread.turn-start-requested')
|
||||
AND json_type(payload_json, '$.modelSelection') IS NULL
|
||||
AND json_type(payload_json, '$.model') IS NOT NULL
|
||||
`;
|
||||
|
||||
// Backfill thread.created events that predate the model field entirely
|
||||
yield* sql`
|
||||
UPDATE orchestration_events
|
||||
SET payload_json = json_set(
|
||||
payload_json,
|
||||
'$.modelSelection',
|
||||
json(json_object('provider', 'codex', 'model', 'gpt-5.4'))
|
||||
)
|
||||
WHERE event_type = 'thread.created'
|
||||
AND json_type(payload_json, '$.modelSelection') IS NULL
|
||||
AND json_type(payload_json, '$.model') IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -50,11 +50,35 @@ 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
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module ProjectionProjectRepository
|
||||
*/
|
||||
import { IsoDateTime, ProjectId, ProjectScript } from "@t3tools/contracts";
|
||||
import { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from "@t3tools/contracts";
|
||||
import { Option, Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
@@ -16,7 +16,7 @@ export const ProjectionProject = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.String,
|
||||
workspaceRoot: Schema.String,
|
||||
defaultModel: Schema.NullOr(Schema.String),
|
||||
defaultModelSelection: Schema.NullOr(ModelSelection),
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
|
||||
@@ -15,6 +15,8 @@ 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,
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
import {
|
||||
IsoDateTime,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
@@ -23,7 +24,7 @@ export const ProjectionThread = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
modelSelection: ModelSelection,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationCheckpointStatus,
|
||||
ThreadId,
|
||||
@@ -34,6 +35,8 @@ 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,
|
||||
@@ -50,6 +53,8 @@ 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,
|
||||
@@ -65,6 +70,8 @@ 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;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -22,6 +22,7 @@ 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";
|
||||
@@ -156,6 +157,29 @@ 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();
|
||||
@@ -164,9 +188,10 @@ validationLayer("CodexAdapterLive validation", (it) => {
|
||||
yield* adapter.startSession({
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
@@ -232,9 +257,10 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
adapter.sendTurn({
|
||||
threadId: asThreadId("sess-missing"),
|
||||
input: "hello",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -776,6 +802,109 @@ 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");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unwraps Codex token usage payloads for context window 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-thread-token-usage-updated"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "thread/tokenUsage/updated",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
tokenUsage: {
|
||||
total: {
|
||||
inputTokens: 11_833,
|
||||
cachedInputTokens: 3456,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
totalTokens: 11_839,
|
||||
},
|
||||
last: {
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
totalTokens: 126,
|
||||
},
|
||||
modelContextWindow: 258_400,
|
||||
},
|
||||
},
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
assert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.type, "thread.token-usage.updated");
|
||||
if (firstEvent.value.type !== "thread.token-usage.updated") {
|
||||
return;
|
||||
}
|
||||
|
||||
assert.deepEqual(firstEvent.value.payload.usage, {
|
||||
usedTokens: 126,
|
||||
totalProcessedTokens: 11_839,
|
||||
maxTokens: 258_400,
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
lastUsedTokens: 126,
|
||||
lastInputTokens: 120,
|
||||
lastCachedInputTokens: 0,
|
||||
lastOutputTokens: 6,
|
||||
lastReasoningOutputTokens: 0,
|
||||
compactsAutomatically: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type CanonicalRequestType,
|
||||
type ProviderEvent,
|
||||
type ProviderRuntimeEvent,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
type ProviderUserInputAnswers,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
@@ -109,6 +110,56 @@ function asNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined {
|
||||
const usage = asObject(value);
|
||||
const totalUsage = asObject(usage?.total_token_usage ?? usage?.total);
|
||||
const lastUsage = asObject(usage?.last_token_usage ?? usage?.last);
|
||||
|
||||
const totalProcessedTokens =
|
||||
asNumber(totalUsage?.total_tokens) ?? asNumber(totalUsage?.totalTokens);
|
||||
const usedTokens =
|
||||
asNumber(lastUsage?.total_tokens) ?? asNumber(lastUsage?.totalTokens) ?? totalProcessedTokens;
|
||||
if (usedTokens === undefined || usedTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const maxTokens = asNumber(usage?.model_context_window) ?? asNumber(usage?.modelContextWindow);
|
||||
const inputTokens = asNumber(lastUsage?.input_tokens) ?? asNumber(lastUsage?.inputTokens);
|
||||
const cachedInputTokens =
|
||||
asNumber(lastUsage?.cached_input_tokens) ?? asNumber(lastUsage?.cachedInputTokens);
|
||||
const outputTokens = asNumber(lastUsage?.output_tokens) ?? asNumber(lastUsage?.outputTokens);
|
||||
const reasoningOutputTokens =
|
||||
asNumber(lastUsage?.reasoning_output_tokens) ?? asNumber(lastUsage?.reasoningOutputTokens);
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens
|
||||
? { totalProcessedTokens }
|
||||
: {}),
|
||||
...(maxTokens !== undefined ? { maxTokens } : {}),
|
||||
...(inputTokens !== undefined ? { inputTokens } : {}),
|
||||
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
|
||||
...(outputTokens !== undefined ? { outputTokens } : {}),
|
||||
...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
|
||||
...(usedTokens !== undefined ? { lastUsedTokens: usedTokens } : {}),
|
||||
...(inputTokens !== undefined ? { lastInputTokens: inputTokens } : {}),
|
||||
...(cachedInputTokens !== undefined ? { lastCachedInputTokens: cachedInputTokens } : {}),
|
||||
...(outputTokens !== undefined ? { lastOutputTokens: outputTokens } : {}),
|
||||
...(reasoningOutputTokens !== undefined
|
||||
? { lastReasoningOutputTokens: reasoningOutputTokens }
|
||||
: {}),
|
||||
compactsAutomatically: true,
|
||||
};
|
||||
}
|
||||
|
||||
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":
|
||||
@@ -164,7 +215,7 @@ function itemTitle(itemType: CanonicalItemType): string | undefined {
|
||||
case "plan":
|
||||
return "Plan";
|
||||
case "command_execution":
|
||||
return "Command run";
|
||||
return "Ran command";
|
||||
case "file_change":
|
||||
return "File change";
|
||||
case "mcp_tool_call":
|
||||
@@ -415,27 +466,27 @@ function codexEventBase(
|
||||
): Omit<ProviderRuntimeEvent, "type" | "payload"> {
|
||||
const payload = asObject(event.payload);
|
||||
const msg = codexEventMessage(payload);
|
||||
const turnId = asString(msg?.turn_id) ?? asString(msg?.turnId);
|
||||
const itemId = asString(msg?.item_id) ?? asString(msg?.itemId);
|
||||
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 requestId = asString(msg?.request_id) ?? asString(msg?.requestId);
|
||||
const base = runtimeEventBase(event, canonicalThreadId);
|
||||
const providerRefs = base.providerRefs
|
||||
? {
|
||||
...base.providerRefs,
|
||||
...(turnId ? { providerTurnId: turnId } : {}),
|
||||
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
|
||||
...(itemId ? { providerItemId: itemId } : {}),
|
||||
...(requestId ? { providerRequestId: requestId } : {}),
|
||||
}
|
||||
: {
|
||||
...(turnId ? { providerTurnId: turnId } : {}),
|
||||
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
|
||||
...(itemId ? { providerItemId: itemId } : {}),
|
||||
...(requestId ? { providerRequestId: requestId } : {}),
|
||||
};
|
||||
|
||||
return {
|
||||
...base,
|
||||
...(turnId ? { turnId: TurnId.makeUnsafe(turnId) } : {}),
|
||||
...(itemId ? { itemId: asRuntimeItemId(ProviderItemId.makeUnsafe(itemId)) } : {}),
|
||||
...(turnId ? { turnId } : {}),
|
||||
...(itemId ? { itemId: asRuntimeItemId(itemId) } : {}),
|
||||
...(requestId ? { requestId: asRuntimeRequestId(requestId) } : {}),
|
||||
...(Object.keys(providerRefs).length > 0 ? { providerRefs } : {}),
|
||||
};
|
||||
@@ -700,12 +751,17 @@ function mapToRuntimeEvents(
|
||||
}
|
||||
|
||||
if (event.method === "thread/tokenUsage/updated") {
|
||||
const tokenUsage = asObject(payload?.tokenUsage);
|
||||
const normalizedUsage = normalizeCodexTokenUsage(tokenUsage ?? event.payload);
|
||||
if (!normalizedUsage) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
type: "thread.token-usage.updated",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
usage: event.payload ?? {},
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -1305,8 +1361,12 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
...(input.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||
runtimeMode: input.runtimeMode,
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.modelOptions?.codex?.fastMode ? { serviceTier: "fast" } : {}),
|
||||
...(input.modelSelection?.provider === "codex"
|
||||
? { model: input.modelSelection.model }
|
||||
: {}),
|
||||
...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
|
||||
? { serviceTier: "fast" }
|
||||
: {}),
|
||||
};
|
||||
|
||||
return Effect.tryPromise({
|
||||
@@ -1328,7 +1388,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
@@ -1362,11 +1422,17 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
const managerInput = {
|
||||
threadId: input.threadId,
|
||||
...(input.input !== undefined ? { input: input.input } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.modelOptions?.codex?.reasoningEffort !== undefined
|
||||
? { effort: input.modelOptions.codex.reasoningEffort }
|
||||
...(input.modelSelection?.provider === "codex"
|
||||
? { model: input.modelSelection.model }
|
||||
: {}),
|
||||
...(input.modelSelection?.provider === "codex" &&
|
||||
input.modelSelection.options?.reasoningEffort !== undefined
|
||||
? { effort: input.modelSelection.options.reasoningEffort }
|
||||
: {}),
|
||||
...(input.modelSelection?.provider === "codex" &&
|
||||
input.modelSelection.options?.fastMode
|
||||
? { serviceTier: "fast" }
|
||||
: {}),
|
||||
...(input.modelOptions?.codex?.fastMode ? { serviceTier: "fast" } : {}),
|
||||
...(input.interactionMode !== undefined
|
||||
? { interactionMode: input.interactionMode }
|
||||
: {}),
|
||||
|
||||
@@ -4,6 +4,7 @@ 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";
|
||||
@@ -27,9 +28,32 @@ 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.succeed(CodexAdapter, fakeCodexAdapter)),
|
||||
Layer.provide(
|
||||
ProviderAdapterRegistryLive,
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(CodexAdapter, fakeCodexAdapter),
|
||||
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
|
||||
),
|
||||
),
|
||||
NodeServices.layer,
|
||||
),
|
||||
);
|
||||
@@ -39,10 +63,12 @@ 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"]);
|
||||
assert.deepEqual(providers, ["codex", "claudeAgent"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* ProviderAdapterRegistryLive - In-memory provider adapter lookup layer.
|
||||
*
|
||||
* Binds provider kinds (codex/cursor/...) to concrete adapter services.
|
||||
* Binds provider kinds (codex/claudeAgent/...) to concrete adapter services.
|
||||
* This layer only performs adapter lookup; it does not route session-scoped
|
||||
* calls or own provider lifecycle workflows.
|
||||
*
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
ProviderAdapterRegistry,
|
||||
type ProviderAdapterRegistryShape,
|
||||
} from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
|
||||
export interface ProviderAdapterRegistryLiveOptions {
|
||||
@@ -23,7 +24,10 @@ export interface ProviderAdapterRegistryLiveOptions {
|
||||
|
||||
const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const adapters = options?.adapters !== undefined ? options.adapters : [yield* CodexAdapter];
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: [yield* CodexAdapter, yield* ClaudeAdapter];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
|
||||
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
|
||||
|
||||
@@ -5,9 +5,11 @@ import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
checkClaudeProviderStatus,
|
||||
checkCodexProviderStatus,
|
||||
hasCustomModelProvider,
|
||||
parseAuthStatusFromOutput,
|
||||
parseClaudeAuthStatusFromOutput,
|
||||
readCodexConfigModelProvider,
|
||||
} from "./ProviderHealth";
|
||||
|
||||
@@ -464,4 +466,175 @@ 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");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,7 @@ 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 ────────────────────────────────────────────────────
|
||||
|
||||
@@ -44,12 +45,7 @@ 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("command not found: codex") ||
|
||||
lower.includes("spawn codex enoent") ||
|
||||
lower.includes("enoent") ||
|
||||
lower.includes("notfound")
|
||||
);
|
||||
return lower.includes("enoent") || lower.includes("notfound");
|
||||
}
|
||||
|
||||
function detailFromResult(
|
||||
@@ -264,6 +260,27 @@ 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<
|
||||
@@ -390,18 +407,197 @@ 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 codexStatusFiber = yield* checkCodexProviderStatus.pipe(
|
||||
Effect.map(Array.of),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
const statusesFiber = yield* Effect.all([checkCodexProviderStatus, checkClaudeProviderStatus], {
|
||||
concurrency: "unbounded",
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
return {
|
||||
getStatuses: Fiber.join(codexStatusFiber),
|
||||
getStatuses: Fiber.join(statusesFiber),
|
||||
} satisfies ProviderHealthShape;
|
||||
}),
|
||||
);
|
||||
@@ -52,7 +52,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex";
|
||||
readonly provider: ProviderKind;
|
||||
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: `cursor-${String(input.threadId)}` },
|
||||
resumeCursor: input.resumeCursor ?? { opaque: `resume-${String(input.threadId)}` },
|
||||
cwd: input.cwd ?? process.cwd(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -195,9 +195,21 @@ 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,
|
||||
@@ -217,12 +229,15 @@ 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)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
: provider === "claudeAgent"
|
||||
? Effect.succeed(claude.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex", "claudeAgent"]),
|
||||
};
|
||||
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
@@ -247,6 +262,7 @@ function makeProviderServiceLayer() {
|
||||
|
||||
return {
|
||||
codex,
|
||||
claude,
|
||||
layer,
|
||||
};
|
||||
}
|
||||
@@ -344,16 +360,29 @@ 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");
|
||||
return yield* provider.startSession(threadId, {
|
||||
const session = 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* () {
|
||||
@@ -363,7 +392,7 @@ it.effect(
|
||||
assert.equal(Option.isSome(persistedAfterStopAll), true);
|
||||
if (Option.isSome(persistedAfterStopAll)) {
|
||||
assert.equal(persistedAfterStopAll.value.status, "stopped");
|
||||
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, startedSession.resumeCursor);
|
||||
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, updatedResumeCursor);
|
||||
}
|
||||
|
||||
const secondCodex = makeFakeCodexAdapter();
|
||||
@@ -406,7 +435,7 @@ it.effect(
|
||||
};
|
||||
assert.equal(startPayload.provider, "codex");
|
||||
assert.equal(startPayload.cwd, "/tmp/project");
|
||||
assert.deepEqual(startPayload.resumeCursor, startedSession.resumeCursor);
|
||||
assert.deepEqual(startPayload.resumeCursor, updatedResumeCursor);
|
||||
assert.equal(startPayload.threadId, startedSession.threadId);
|
||||
}
|
||||
assert.equal(secondCodex.rollbackThread.mock.calls.length, 1);
|
||||
@@ -533,6 +562,29 @@ 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;
|
||||
@@ -573,6 +625,61 @@ 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",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
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;
|
||||
modelSelection?: unknown;
|
||||
resumeCursor?: unknown;
|
||||
threadId?: string;
|
||||
};
|
||||
assert.equal(startPayload.provider, "claudeAgent");
|
||||
assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn");
|
||||
assert.deepEqual(startPayload.modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
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;
|
||||
@@ -589,6 +696,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
});
|
||||
|
||||
yield* routing.codex.stopAll();
|
||||
yield* routing.claude.stopAll();
|
||||
|
||||
const remaining = yield* provider.listSessions();
|
||||
assert.equal(remaining.length, 0);
|
||||
@@ -637,6 +745,96 @@ 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();
|
||||
@@ -654,7 +852,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(20);
|
||||
yield* sleep(50);
|
||||
|
||||
const completedEvent: LegacyProviderRuntimeEvent = {
|
||||
type: "turn.completed",
|
||||
@@ -667,7 +865,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
};
|
||||
|
||||
fanout.codex.emit(completedEvent);
|
||||
yield* sleep(20);
|
||||
yield* sleep(50);
|
||||
|
||||
const events = yield* Ref.get(eventsRef);
|
||||
yield* Fiber.interrupt(consumer);
|
||||
@@ -693,7 +891,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
Stream.runForEach((event) => Ref.update(receivedRef, (current) => [...current, event])),
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* sleep(20);
|
||||
yield* sleep(50);
|
||||
|
||||
fanout.codex.emit({
|
||||
type: "tool.started",
|
||||
@@ -703,7 +901,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
threadId: session.threadId,
|
||||
turnId: asTurnId("turn-1"),
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
title: "Ran command",
|
||||
});
|
||||
fanout.codex.emit({
|
||||
type: "tool.completed",
|
||||
@@ -713,7 +911,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
threadId: session.threadId,
|
||||
turnId: asTurnId("turn-1"),
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
title: "Ran command",
|
||||
});
|
||||
fanout.codex.emit({
|
||||
type: "turn.completed",
|
||||
@@ -757,7 +955,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
Stream.runForEach(() => Effect.fail("listener crash")),
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* sleep(20);
|
||||
yield* sleep(50);
|
||||
|
||||
const events: ReadonlyArray<LegacyProviderRuntimeEvent> = [
|
||||
{
|
||||
@@ -768,7 +966,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
threadId: session.threadId,
|
||||
turnId: asTurnId("turn-1"),
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
title: "Ran command",
|
||||
detail: "echo one",
|
||||
},
|
||||
{
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
* @module ProviderServiceLive
|
||||
*/
|
||||
import {
|
||||
ModelSelection,
|
||||
NonNegativeInt,
|
||||
ThreadId,
|
||||
ProviderInterruptTurnInput,
|
||||
@@ -88,17 +89,37 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
|
||||
|
||||
function toRuntimePayloadFromSession(
|
||||
session: ProviderSession,
|
||||
extra?: { readonly providerOptions?: unknown },
|
||||
extra?: {
|
||||
readonly modelSelection?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
cwd: session.cwd ?? null,
|
||||
model: session.model ?? null,
|
||||
activeTurnId: session.activeTurnId ?? null,
|
||||
lastError: session.lastError ?? null,
|
||||
...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}),
|
||||
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
|
||||
...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
|
||||
...(extra?.lastRuntimeEventAt !== undefined
|
||||
? { lastRuntimeEventAt: extra.lastRuntimeEventAt }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function readPersistedModelSelection(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
): ModelSelection | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
}
|
||||
const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined;
|
||||
return Schema.is(ModelSelection)(raw) ? raw : undefined;
|
||||
}
|
||||
|
||||
function readPersistedProviderOptions(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
): Record<string, unknown> | undefined {
|
||||
@@ -150,7 +171,12 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const upsertSessionBinding = (
|
||||
session: ProviderSession,
|
||||
threadId: ThreadId,
|
||||
extra?: { readonly providerOptions?: unknown },
|
||||
extra?: {
|
||||
readonly modelSelection?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
@@ -165,7 +191,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const adapters = yield* Effect.forEach(providers, (provider) =>
|
||||
registry.getByProvider(provider),
|
||||
);
|
||||
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
publishRuntimeEvent(event);
|
||||
|
||||
@@ -213,12 +238,14 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
const persistedModelSelection = readPersistedModelSelection(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 } : {}),
|
||||
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
|
||||
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
runtimeMode: input.binding.runtimeMode ?? "full-access",
|
||||
@@ -281,8 +308,17 @@ 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);
|
||||
const session = yield* adapter.startSession({
|
||||
...input,
|
||||
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
|
||||
});
|
||||
|
||||
if (session.provider !== adapter.provider) {
|
||||
return yield* toValidationError(
|
||||
@@ -292,6 +328,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
modelSelection: input.modelSelection,
|
||||
providerOptions: input.providerOptions,
|
||||
});
|
||||
yield* analytics.record("provider.session.started", {
|
||||
@@ -299,7 +336,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
runtimeMode: input.runtimeMode,
|
||||
hasResumeCursor: session.resumeCursor !== undefined,
|
||||
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
|
||||
hasModel: typeof input.model === "string" && input.model.trim().length > 0,
|
||||
hasModel:
|
||||
typeof input.modelSelection?.model === "string" &&
|
||||
input.modelSelection.model.trim().length > 0,
|
||||
});
|
||||
|
||||
return session;
|
||||
@@ -335,6 +374,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
status: "running",
|
||||
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
|
||||
runtimePayload: {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
activeTurnId: turn.turnId,
|
||||
lastRuntimeEvent: "provider.sendTurn",
|
||||
lastRuntimeEventAt: new Date().toISOString(),
|
||||
@@ -342,7 +382,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
});
|
||||
yield* analytics.record("provider.turn.sent", {
|
||||
provider: routed.adapter.provider,
|
||||
model: input.model,
|
||||
model: input.modelSelection?.model,
|
||||
interactionMode: input.interactionMode,
|
||||
attachmentCount: input.attachments.length,
|
||||
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
|
||||
@@ -498,6 +538,17 @@ 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: "cursor",
|
||||
adapterKey: "cursor",
|
||||
providerName: "claudeAgent",
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
|
||||
@@ -22,7 +22,7 @@ function decodeProviderKind(
|
||||
providerName: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
|
||||
if (providerName === "codex") {
|
||||
if (providerName === "codex" || providerName === "claudeAgent") {
|
||||
return Effect.succeed(providerName);
|
||||
}
|
||||
return Effect.fail(
|
||||
|
||||
Loaded 100 of 250 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user